repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
nicksnyder/go-i18n
i18n/bundle/bundle.go
Translations
func (b *Bundle) Translations() map[string]map[string]translation.Translation { t := make(map[string]map[string]translation.Translation) b.RLock() for tag, translations := range b.translations { t[tag] = make(map[string]translation.Translation) for id, translation := range translations { t[tag][id] = translation } } b.RUnlock() return t }
go
func (b *Bundle) Translations() map[string]map[string]translation.Translation { t := make(map[string]map[string]translation.Translation) b.RLock() for tag, translations := range b.translations { t[tag] = make(map[string]translation.Translation) for id, translation := range translations { t[tag][id] = translation } } b.RUnlock() return t }
[ "func", "(", "b", "*", "Bundle", ")", "Translations", "(", ")", "map", "[", "string", "]", "map", "[", "string", "]", "translation", ".", "Translation", "{", "t", ":=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "translation", ".", "Translation", ")", "\n", "b", ".", "RLock", "(", ")", "\n", "for", "tag", ",", "translations", ":=", "range", "b", ".", "translations", "{", "t", "[", "tag", "]", "=", "make", "(", "map", "[", "string", "]", "translation", ".", "Translation", ")", "\n", "for", "id", ",", "translation", ":=", "range", "translations", "{", "t", "[", "tag", "]", "[", "id", "]", "=", "translation", "\n", "}", "\n", "}", "\n", "b", ".", "RUnlock", "(", ")", "\n", "return", "t", "\n", "}" ]
// Translations returns all translations in the bundle.
[ "Translations", "returns", "all", "translations", "in", "the", "bundle", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/bundle/bundle.go#L233-L244
train
nicksnyder/go-i18n
i18n/bundle/bundle.go
LanguageTags
func (b *Bundle) LanguageTags() []string { var tags []string b.RLock() for k := range b.translations { tags = append(tags, k) } b.RUnlock() return tags }
go
func (b *Bundle) LanguageTags() []string { var tags []string b.RLock() for k := range b.translations { tags = append(tags, k) } b.RUnlock() return tags }
[ "func", "(", "b", "*", "Bundle", ")", "LanguageTags", "(", ")", "[", "]", "string", "{", "var", "tags", "[", "]", "string", "\n", "b", ".", "RLock", "(", ")", "\n", "for", "k", ":=", "range", "b", ".", "translations", "{", "tags", "=", "append", "(", "tags", ",", "k", ")", "\n", "}", "\n", "b", ".", "RUnlock", "(", ")", "\n", "return", "tags", "\n", "}" ]
// LanguageTags returns the tags of all languages that that have been added.
[ "LanguageTags", "returns", "the", "tags", "of", "all", "languages", "that", "that", "have", "been", "added", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/bundle/bundle.go#L247-L255
train
nicksnyder/go-i18n
i18n/bundle/bundle.go
LanguageTranslationIDs
func (b *Bundle) LanguageTranslationIDs(languageTag string) []string { var ids []string b.RLock() for id := range b.translations[languageTag] { ids = append(ids, id) } b.RUnlock() return ids }
go
func (b *Bundle) LanguageTranslationIDs(languageTag string) []string { var ids []string b.RLock() for id := range b.translations[languageTag] { ids = append(ids, id) } b.RUnlock() return ids }
[ "func", "(", "b", "*", "Bundle", ")", "LanguageTranslationIDs", "(", "languageTag", "string", ")", "[", "]", "string", "{", "var", "ids", "[", "]", "string", "\n", "b", ".", "RLock", "(", ")", "\n", "for", "id", ":=", "range", "b", ".", "translations", "[", "languageTag", "]", "{", "ids", "=", "append", "(", "ids", ",", "id", ")", "\n", "}", "\n", "b", ".", "RUnlock", "(", ")", "\n", "return", "ids", "\n", "}" ]
// LanguageTranslationIDs returns the ids of all translations that have been added for a given language.
[ "LanguageTranslationIDs", "returns", "the", "ids", "of", "all", "translations", "that", "have", "been", "added", "for", "a", "given", "language", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/bundle/bundle.go#L258-L266
train
nicksnyder/go-i18n
i18n/bundle/bundle.go
Tfunc
func (b *Bundle) Tfunc(pref string, prefs ...string) (TranslateFunc, error) { tfunc, _, err := b.TfuncAndLanguage(pref, prefs...) return tfunc, err }
go
func (b *Bundle) Tfunc(pref string, prefs ...string) (TranslateFunc, error) { tfunc, _, err := b.TfuncAndLanguage(pref, prefs...) return tfunc, err }
[ "func", "(", "b", "*", "Bundle", ")", "Tfunc", "(", "pref", "string", ",", "prefs", "...", "string", ")", "(", "TranslateFunc", ",", "error", ")", "{", "tfunc", ",", "_", ",", "err", ":=", "b", ".", "TfuncAndLanguage", "(", "pref", ",", "prefs", "...", ")", "\n", "return", "tfunc", ",", "err", "\n", "}" ]
// Tfunc is similar to TfuncAndLanguage except is doesn't return the Language.
[ "Tfunc", "is", "similar", "to", "TfuncAndLanguage", "except", "is", "doesn", "t", "return", "the", "Language", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/bundle/bundle.go#L287-L290
train
nicksnyder/go-i18n
i18n/bundle/bundle.go
supportedLanguage
func (b *Bundle) supportedLanguage(pref string, prefs ...string) *language.Language { lang := b.translatedLanguage(pref) if lang == nil { for _, pref := range prefs { lang = b.translatedLanguage(pref) if lang != nil { break } } } return lang }
go
func (b *Bundle) supportedLanguage(pref string, prefs ...string) *language.Language { lang := b.translatedLanguage(pref) if lang == nil { for _, pref := range prefs { lang = b.translatedLanguage(pref) if lang != nil { break } } } return lang }
[ "func", "(", "b", "*", "Bundle", ")", "supportedLanguage", "(", "pref", "string", ",", "prefs", "...", "string", ")", "*", "language", ".", "Language", "{", "lang", ":=", "b", ".", "translatedLanguage", "(", "pref", ")", "\n", "if", "lang", "==", "nil", "{", "for", "_", ",", "pref", ":=", "range", "prefs", "{", "lang", "=", "b", ".", "translatedLanguage", "(", "pref", ")", "\n", "if", "lang", "!=", "nil", "{", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "lang", "\n", "}" ]
// supportedLanguage returns the first language which // has a non-zero number of translations in the bundle.
[ "supportedLanguage", "returns", "the", "first", "language", "which", "has", "a", "non", "-", "zero", "number", "of", "translations", "in", "the", "bundle", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/i18n/bundle/bundle.go#L316-L327
train
nicksnyder/go-i18n
v2/internal/plural/rules.go
Rule
func (r Rules) Rule(tag language.Tag) *Rule { t := tag for { if rule := r[t]; rule != nil { return rule } t = t.Parent() if t.IsRoot() { break } } base, _ := tag.Base() baseTag, _ := language.Parse(base.String()) return r[baseTag] }
go
func (r Rules) Rule(tag language.Tag) *Rule { t := tag for { if rule := r[t]; rule != nil { return rule } t = t.Parent() if t.IsRoot() { break } } base, _ := tag.Base() baseTag, _ := language.Parse(base.String()) return r[baseTag] }
[ "func", "(", "r", "Rules", ")", "Rule", "(", "tag", "language", ".", "Tag", ")", "*", "Rule", "{", "t", ":=", "tag", "\n", "for", "{", "if", "rule", ":=", "r", "[", "t", "]", ";", "rule", "!=", "nil", "{", "return", "rule", "\n", "}", "\n", "t", "=", "t", ".", "Parent", "(", ")", "\n", "if", "t", ".", "IsRoot", "(", ")", "{", "break", "\n", "}", "\n", "}", "\n", "base", ",", "_", ":=", "tag", ".", "Base", "(", ")", "\n", "baseTag", ",", "_", ":=", "language", ".", "Parse", "(", "base", ".", "String", "(", ")", ")", "\n", "return", "r", "[", "baseTag", "]", "\n", "}" ]
// Rule returns the closest matching plural rule for the language tag // or nil if no rule could be found.
[ "Rule", "returns", "the", "closest", "matching", "plural", "rule", "for", "the", "language", "tag", "or", "nil", "if", "no", "rule", "could", "be", "found", "." ]
b2843f1401bcdec49ebbd5b729689ee36ea1e65a
https://github.com/nicksnyder/go-i18n/blob/b2843f1401bcdec49ebbd5b729689ee36ea1e65a/v2/internal/plural/rules.go#L10-L24
train
jdkato/prose
tag/tag.go
ReadTagged
func ReadTagged(text, sep string) TupleSlice { t := TupleSlice{} for _, sent := range strings.Split(text, "\n") { tokens := []string{} tags := []string{} for _, token := range strings.Split(sent, " ") { parts := strings.Split(token, sep) tokens = append(tokens, parts[0]) tags = append(tags, parts[1]) } t = append(t, [][]string{tokens, tags}) } return t }
go
func ReadTagged(text, sep string) TupleSlice { t := TupleSlice{} for _, sent := range strings.Split(text, "\n") { tokens := []string{} tags := []string{} for _, token := range strings.Split(sent, " ") { parts := strings.Split(token, sep) tokens = append(tokens, parts[0]) tags = append(tags, parts[1]) } t = append(t, [][]string{tokens, tags}) } return t }
[ "func", "ReadTagged", "(", "text", ",", "sep", "string", ")", "TupleSlice", "{", "t", ":=", "TupleSlice", "{", "}", "\n", "for", "_", ",", "sent", ":=", "range", "strings", ".", "Split", "(", "text", ",", "\"", "\\n", "\"", ")", "{", "tokens", ":=", "[", "]", "string", "{", "}", "\n", "tags", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "token", ":=", "range", "strings", ".", "Split", "(", "sent", ",", "\"", "\"", ")", "{", "parts", ":=", "strings", ".", "Split", "(", "token", ",", "sep", ")", "\n", "tokens", "=", "append", "(", "tokens", ",", "parts", "[", "0", "]", ")", "\n", "tags", "=", "append", "(", "tags", ",", "parts", "[", "1", "]", ")", "\n", "}", "\n", "t", "=", "append", "(", "t", ",", "[", "]", "[", "]", "string", "{", "tokens", ",", "tags", "}", ")", "\n", "}", "\n", "return", "t", "\n", "}" ]
// ReadTagged converts pre-tagged input into a TupleSlice suitable for training.
[ "ReadTagged", "converts", "pre", "-", "tagged", "input", "into", "a", "TupleSlice", "suitable", "for", "training", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tag/tag.go#L24-L37
train
jdkato/prose
tokenize/regexp.go
Tokenize
func (r RegexpTokenizer) Tokenize(text string) []string { var tokens []string if r.gaps { temp := r.regex.Split(text, -1) if r.discard { for _, s := range temp { if s != "" { tokens = append(tokens, s) } } } else { tokens = temp } } else { tokens = r.regex.FindAllString(text, -1) } return tokens }
go
func (r RegexpTokenizer) Tokenize(text string) []string { var tokens []string if r.gaps { temp := r.regex.Split(text, -1) if r.discard { for _, s := range temp { if s != "" { tokens = append(tokens, s) } } } else { tokens = temp } } else { tokens = r.regex.FindAllString(text, -1) } return tokens }
[ "func", "(", "r", "RegexpTokenizer", ")", "Tokenize", "(", "text", "string", ")", "[", "]", "string", "{", "var", "tokens", "[", "]", "string", "\n", "if", "r", ".", "gaps", "{", "temp", ":=", "r", ".", "regex", ".", "Split", "(", "text", ",", "-", "1", ")", "\n", "if", "r", ".", "discard", "{", "for", "_", ",", "s", ":=", "range", "temp", "{", "if", "s", "!=", "\"", "\"", "{", "tokens", "=", "append", "(", "tokens", ",", "s", ")", "\n", "}", "\n", "}", "\n", "}", "else", "{", "tokens", "=", "temp", "\n", "}", "\n", "}", "else", "{", "tokens", "=", "r", ".", "regex", ".", "FindAllString", "(", "text", ",", "-", "1", ")", "\n", "}", "\n", "return", "tokens", "\n", "}" ]
// Tokenize splits text into a slice of tokens according to its regexp pattern.
[ "Tokenize", "splits", "text", "into", "a", "slice", "of", "tokens", "according", "to", "its", "regexp", "pattern", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/regexp.go#L23-L40
train
jdkato/prose
tokenize/regexp.go
NewBlanklineTokenizer
func NewBlanklineTokenizer() *RegexpTokenizer { return &RegexpTokenizer{ regex: regexp.MustCompile(`\s*\n\s*\n\s*`), gaps: true, discard: true} }
go
func NewBlanklineTokenizer() *RegexpTokenizer { return &RegexpTokenizer{ regex: regexp.MustCompile(`\s*\n\s*\n\s*`), gaps: true, discard: true} }
[ "func", "NewBlanklineTokenizer", "(", ")", "*", "RegexpTokenizer", "{", "return", "&", "RegexpTokenizer", "{", "regex", ":", "regexp", ".", "MustCompile", "(", "`\\s*\\n\\s*\\n\\s*`", ")", ",", "gaps", ":", "true", ",", "discard", ":", "true", "}", "\n", "}" ]
// NewBlanklineTokenizer is a RegexpTokenizer constructor. // // This tokenizer splits on any sequence of blank lines.
[ "NewBlanklineTokenizer", "is", "a", "RegexpTokenizer", "constructor", ".", "This", "tokenizer", "splits", "on", "any", "sequence", "of", "blank", "lines", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/regexp.go#L45-L48
train
jdkato/prose
chunk/chunk.go
quadsString
func quadsString(tagged []tag.Token) string { tagQuads := "" for _, tok := range tagged { padding := "" pos := tok.Tag switch len(pos) { case 0: padding = "____" // should not exist case 1: padding = "___" case 2: padding = "__" case 3: padding = "_" case 4: // no padding required default: pos = pos[:4] // longer than 4 ... truncate! } tagQuads += pos + padding } return tagQuads }
go
func quadsString(tagged []tag.Token) string { tagQuads := "" for _, tok := range tagged { padding := "" pos := tok.Tag switch len(pos) { case 0: padding = "____" // should not exist case 1: padding = "___" case 2: padding = "__" case 3: padding = "_" case 4: // no padding required default: pos = pos[:4] // longer than 4 ... truncate! } tagQuads += pos + padding } return tagQuads }
[ "func", "quadsString", "(", "tagged", "[", "]", "tag", ".", "Token", ")", "string", "{", "tagQuads", ":=", "\"", "\"", "\n", "for", "_", ",", "tok", ":=", "range", "tagged", "{", "padding", ":=", "\"", "\"", "\n", "pos", ":=", "tok", ".", "Tag", "\n", "switch", "len", "(", "pos", ")", "{", "case", "0", ":", "padding", "=", "\"", "\"", "// should not exist", "\n", "case", "1", ":", "padding", "=", "\"", "\"", "\n", "case", "2", ":", "padding", "=", "\"", "\"", "\n", "case", "3", ":", "padding", "=", "\"", "\"", "\n", "case", "4", ":", "// no padding required", "default", ":", "pos", "=", "pos", "[", ":", "4", "]", "// longer than 4 ... truncate!", "\n", "}", "\n", "tagQuads", "+=", "pos", "+", "padding", "\n", "}", "\n", "return", "tagQuads", "\n", "}" ]
// quadString creates a string containing all of the tags, each padded to 4 // characters wide.
[ "quadString", "creates", "a", "string", "containing", "all", "of", "the", "tags", "each", "padded", "to", "4", "characters", "wide", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/chunk/chunk.go#L13-L34
train
jdkato/prose
chunk/chunk.go
Chunk
func Chunk(tagged []tag.Token, rx *regexp.Regexp) []string { chunks := []string{} for _, loc := range Locate(tagged, rx) { res := "" for t, tt := range tagged[loc[0]:loc[1]] { if t != 0 { res += " " } res += tt.Text } chunks = append(chunks, res) } return chunks }
go
func Chunk(tagged []tag.Token, rx *regexp.Regexp) []string { chunks := []string{} for _, loc := range Locate(tagged, rx) { res := "" for t, tt := range tagged[loc[0]:loc[1]] { if t != 0 { res += " " } res += tt.Text } chunks = append(chunks, res) } return chunks }
[ "func", "Chunk", "(", "tagged", "[", "]", "tag", ".", "Token", ",", "rx", "*", "regexp", ".", "Regexp", ")", "[", "]", "string", "{", "chunks", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "loc", ":=", "range", "Locate", "(", "tagged", ",", "rx", ")", "{", "res", ":=", "\"", "\"", "\n", "for", "t", ",", "tt", ":=", "range", "tagged", "[", "loc", "[", "0", "]", ":", "loc", "[", "1", "]", "]", "{", "if", "t", "!=", "0", "{", "res", "+=", "\"", "\"", "\n", "}", "\n", "res", "+=", "tt", ".", "Text", "\n", "}", "\n", "chunks", "=", "append", "(", "chunks", ",", "res", ")", "\n", "}", "\n", "return", "chunks", "\n", "}" ]
// Chunk returns a slice containing the chunks of interest according to the // regexp. // // This is a convenience wrapper around Locate, which should be used if you // need access the to the in-text locations of each chunk.
[ "Chunk", "returns", "a", "slice", "containing", "the", "chunks", "of", "interest", "according", "to", "the", "regexp", ".", "This", "is", "a", "convenience", "wrapper", "around", "Locate", "which", "should", "be", "used", "if", "you", "need", "access", "the", "to", "the", "in", "-", "text", "locations", "of", "each", "chunk", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/chunk/chunk.go#L48-L61
train
jdkato/prose
chunk/chunk.go
Locate
func Locate(tagged []tag.Token, rx *regexp.Regexp) [][]int { rx.Longest() // make sure we find the longest possible sequences rs := rx.FindAllStringIndex(quadsString(tagged), -1) for i, ii := range rs { for j := range ii { // quadsString makes every offset 4x what it should be rs[i][j] /= 4 } } return rs }
go
func Locate(tagged []tag.Token, rx *regexp.Regexp) [][]int { rx.Longest() // make sure we find the longest possible sequences rs := rx.FindAllStringIndex(quadsString(tagged), -1) for i, ii := range rs { for j := range ii { // quadsString makes every offset 4x what it should be rs[i][j] /= 4 } } return rs }
[ "func", "Locate", "(", "tagged", "[", "]", "tag", ".", "Token", ",", "rx", "*", "regexp", ".", "Regexp", ")", "[", "]", "[", "]", "int", "{", "rx", ".", "Longest", "(", ")", "// make sure we find the longest possible sequences", "\n", "rs", ":=", "rx", ".", "FindAllStringIndex", "(", "quadsString", "(", "tagged", ")", ",", "-", "1", ")", "\n", "for", "i", ",", "ii", ":=", "range", "rs", "{", "for", "j", ":=", "range", "ii", "{", "// quadsString makes every offset 4x what it should be", "rs", "[", "i", "]", "[", "j", "]", "/=", "4", "\n", "}", "\n", "}", "\n", "return", "rs", "\n", "}" ]
// Locate finds the chunks of interest according to the regexp.
[ "Locate", "finds", "the", "chunks", "of", "interest", "according", "to", "the", "regexp", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/chunk/chunk.go#L64-L74
train
jdkato/prose
transform/title.go
Title
func (tc *TitleConverter) Title(s string) string { idx, pos := 0, 0 t := sanitizer.Replace(s) end := len(t) return splitRE.ReplaceAllStringFunc(s, func(m string) string { sm := strings.ToLower(m) pos = strings.Index(t[idx:], m) + idx prev := charAt(t, pos-1) ext := utf8.RuneCountInString(m) idx = pos + ext if tc.ignore(sm, pos == 0 || idx == end) && (prev == ' ' || prev == '-' || prev == '/') && charAt(t, pos-2) != ':' && charAt(t, pos-2) != '-' && (charAt(t, pos+ext) != '-' || charAt(t, pos-1) == '-') { return sm } return toTitle(m, prev) }) }
go
func (tc *TitleConverter) Title(s string) string { idx, pos := 0, 0 t := sanitizer.Replace(s) end := len(t) return splitRE.ReplaceAllStringFunc(s, func(m string) string { sm := strings.ToLower(m) pos = strings.Index(t[idx:], m) + idx prev := charAt(t, pos-1) ext := utf8.RuneCountInString(m) idx = pos + ext if tc.ignore(sm, pos == 0 || idx == end) && (prev == ' ' || prev == '-' || prev == '/') && charAt(t, pos-2) != ':' && charAt(t, pos-2) != '-' && (charAt(t, pos+ext) != '-' || charAt(t, pos-1) == '-') { return sm } return toTitle(m, prev) }) }
[ "func", "(", "tc", "*", "TitleConverter", ")", "Title", "(", "s", "string", ")", "string", "{", "idx", ",", "pos", ":=", "0", ",", "0", "\n", "t", ":=", "sanitizer", ".", "Replace", "(", "s", ")", "\n", "end", ":=", "len", "(", "t", ")", "\n", "return", "splitRE", ".", "ReplaceAllStringFunc", "(", "s", ",", "func", "(", "m", "string", ")", "string", "{", "sm", ":=", "strings", ".", "ToLower", "(", "m", ")", "\n", "pos", "=", "strings", ".", "Index", "(", "t", "[", "idx", ":", "]", ",", "m", ")", "+", "idx", "\n", "prev", ":=", "charAt", "(", "t", ",", "pos", "-", "1", ")", "\n", "ext", ":=", "utf8", ".", "RuneCountInString", "(", "m", ")", "\n", "idx", "=", "pos", "+", "ext", "\n", "if", "tc", ".", "ignore", "(", "sm", ",", "pos", "==", "0", "||", "idx", "==", "end", ")", "&&", "(", "prev", "==", "' '", "||", "prev", "==", "'-'", "||", "prev", "==", "'/'", ")", "&&", "charAt", "(", "t", ",", "pos", "-", "2", ")", "!=", "':'", "&&", "charAt", "(", "t", ",", "pos", "-", "2", ")", "!=", "'-'", "&&", "(", "charAt", "(", "t", ",", "pos", "+", "ext", ")", "!=", "'-'", "||", "charAt", "(", "t", ",", "pos", "-", "1", ")", "==", "'-'", ")", "{", "return", "sm", "\n", "}", "\n", "return", "toTitle", "(", "m", ",", "prev", ")", "\n", "}", ")", "\n", "}" ]
// Title returns a copy of the string s in title case format.
[ "Title", "returns", "a", "copy", "of", "the", "string", "s", "in", "title", "case", "format", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/transform/title.go#L43-L61
train
jdkato/prose
transform/title.go
charAt
func charAt(s string, i int) byte { if i >= 0 && i < len(s) { return s[i] } return s[0] }
go
func charAt(s string, i int) byte { if i >= 0 && i < len(s) { return s[i] } return s[0] }
[ "func", "charAt", "(", "s", "string", ",", "i", "int", ")", "byte", "{", "if", "i", ">=", "0", "&&", "i", "<", "len", "(", "s", ")", "{", "return", "s", "[", "i", "]", "\n", "}", "\n", "return", "s", "[", "0", "]", "\n", "}" ]
// charAt returns the ith character of s, if it exists. Otherwise, it returns // the first character.
[ "charAt", "returns", "the", "ith", "character", "of", "s", "if", "it", "exists", ".", "Otherwise", "it", "returns", "the", "first", "character", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/transform/title.go#L96-L101
train
jdkato/prose
transform/title.go
toTitle
func toTitle(m string, prev byte) string { r, size := utf8.DecodeRuneInString(m) return string(unicode.ToTitle(r)) + m[size:] }
go
func toTitle(m string, prev byte) string { r, size := utf8.DecodeRuneInString(m) return string(unicode.ToTitle(r)) + m[size:] }
[ "func", "toTitle", "(", "m", "string", ",", "prev", "byte", ")", "string", "{", "r", ",", "size", ":=", "utf8", ".", "DecodeRuneInString", "(", "m", ")", "\n", "return", "string", "(", "unicode", ".", "ToTitle", "(", "r", ")", ")", "+", "m", "[", "size", ":", "]", "\n", "}" ]
// toTitle returns a copy of the string m with its first Unicode letter mapped // to its title case.
[ "toTitle", "returns", "a", "copy", "of", "the", "string", "m", "with", "its", "first", "Unicode", "letter", "mapped", "to", "its", "title", "case", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/transform/title.go#L105-L108
train
jdkato/prose
tag/aptag.go
NewAveragedPerceptron
func NewAveragedPerceptron(weights map[string]map[string]float64, tags map[string]string, classes []string) *AveragedPerceptron { return &AveragedPerceptron{ totals: make(map[string]float64), stamps: make(map[string]float64), classes: classes, tagMap: tags, weights: weights} }
go
func NewAveragedPerceptron(weights map[string]map[string]float64, tags map[string]string, classes []string) *AveragedPerceptron { return &AveragedPerceptron{ totals: make(map[string]float64), stamps: make(map[string]float64), classes: classes, tagMap: tags, weights: weights} }
[ "func", "NewAveragedPerceptron", "(", "weights", "map", "[", "string", "]", "map", "[", "string", "]", "float64", ",", "tags", "map", "[", "string", "]", "string", ",", "classes", "[", "]", "string", ")", "*", "AveragedPerceptron", "{", "return", "&", "AveragedPerceptron", "{", "totals", ":", "make", "(", "map", "[", "string", "]", "float64", ")", ",", "stamps", ":", "make", "(", "map", "[", "string", "]", "float64", ")", ",", "classes", ":", "classes", ",", "tagMap", ":", "tags", ",", "weights", ":", "weights", "}", "\n", "}" ]
// NewAveragedPerceptron creates a new AveragedPerceptron model.
[ "NewAveragedPerceptron", "creates", "a", "new", "AveragedPerceptron", "model", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tag/aptag.go#L48-L53
train
jdkato/prose
tag/aptag.go
NewPerceptronTagger
func NewPerceptronTagger() *PerceptronTagger { var wts map[string]map[string]float64 var tags map[string]string var classes []string dec := model.GetAsset("classes.gob") util.CheckError(dec.Decode(&classes)) dec = model.GetAsset("tags.gob") util.CheckError(dec.Decode(&tags)) dec = model.GetAsset("weights.gob") util.CheckError(dec.Decode(&wts)) return &PerceptronTagger{model: NewAveragedPerceptron(wts, tags, classes)} }
go
func NewPerceptronTagger() *PerceptronTagger { var wts map[string]map[string]float64 var tags map[string]string var classes []string dec := model.GetAsset("classes.gob") util.CheckError(dec.Decode(&classes)) dec = model.GetAsset("tags.gob") util.CheckError(dec.Decode(&tags)) dec = model.GetAsset("weights.gob") util.CheckError(dec.Decode(&wts)) return &PerceptronTagger{model: NewAveragedPerceptron(wts, tags, classes)} }
[ "func", "NewPerceptronTagger", "(", ")", "*", "PerceptronTagger", "{", "var", "wts", "map", "[", "string", "]", "map", "[", "string", "]", "float64", "\n", "var", "tags", "map", "[", "string", "]", "string", "\n", "var", "classes", "[", "]", "string", "\n\n", "dec", ":=", "model", ".", "GetAsset", "(", "\"", "\"", ")", "\n", "util", ".", "CheckError", "(", "dec", ".", "Decode", "(", "&", "classes", ")", ")", "\n\n", "dec", "=", "model", ".", "GetAsset", "(", "\"", "\"", ")", "\n", "util", ".", "CheckError", "(", "dec", ".", "Decode", "(", "&", "tags", ")", ")", "\n\n", "dec", "=", "model", ".", "GetAsset", "(", "\"", "\"", ")", "\n", "util", ".", "CheckError", "(", "dec", ".", "Decode", "(", "&", "wts", ")", ")", "\n\n", "return", "&", "PerceptronTagger", "{", "model", ":", "NewAveragedPerceptron", "(", "wts", ",", "tags", ",", "classes", ")", "}", "\n", "}" ]
// NewPerceptronTagger creates a new PerceptronTagger and loads the built-in // AveragedPerceptron model.
[ "NewPerceptronTagger", "creates", "a", "new", "PerceptronTagger", "and", "loads", "the", "built", "-", "in", "AveragedPerceptron", "model", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tag/aptag.go#L64-L79
train
jdkato/prose
tag/aptag.go
Tag
func (pt *PerceptronTagger) Tag(words []string) []Token { var tokens []Token var clean []string var tag string var found bool p1, p2 := "-START-", "-START2-" context := []string{p1, p2} for _, w := range words { if w == "" { continue } context = append(context, normalize(w)) clean = append(clean, w) } context = append(context, []string{"-END-", "-END2-"}...) for i, word := range clean { if none.MatchString(word) { tag = "-NONE-" } else if keep.MatchString(word) { tag = word } else if tag, found = pt.model.tagMap[word]; !found { tag = pt.model.predict(featurize(i, context, word, p1, p2)) } tokens = append(tokens, Token{Tag: tag, Text: word}) p2 = p1 p1 = tag } return tokens }
go
func (pt *PerceptronTagger) Tag(words []string) []Token { var tokens []Token var clean []string var tag string var found bool p1, p2 := "-START-", "-START2-" context := []string{p1, p2} for _, w := range words { if w == "" { continue } context = append(context, normalize(w)) clean = append(clean, w) } context = append(context, []string{"-END-", "-END2-"}...) for i, word := range clean { if none.MatchString(word) { tag = "-NONE-" } else if keep.MatchString(word) { tag = word } else if tag, found = pt.model.tagMap[word]; !found { tag = pt.model.predict(featurize(i, context, word, p1, p2)) } tokens = append(tokens, Token{Tag: tag, Text: word}) p2 = p1 p1 = tag } return tokens }
[ "func", "(", "pt", "*", "PerceptronTagger", ")", "Tag", "(", "words", "[", "]", "string", ")", "[", "]", "Token", "{", "var", "tokens", "[", "]", "Token", "\n", "var", "clean", "[", "]", "string", "\n", "var", "tag", "string", "\n", "var", "found", "bool", "\n\n", "p1", ",", "p2", ":=", "\"", "\"", ",", "\"", "\"", "\n", "context", ":=", "[", "]", "string", "{", "p1", ",", "p2", "}", "\n", "for", "_", ",", "w", ":=", "range", "words", "{", "if", "w", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "context", "=", "append", "(", "context", ",", "normalize", "(", "w", ")", ")", "\n", "clean", "=", "append", "(", "clean", ",", "w", ")", "\n", "}", "\n", "context", "=", "append", "(", "context", ",", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", "...", ")", "\n", "for", "i", ",", "word", ":=", "range", "clean", "{", "if", "none", ".", "MatchString", "(", "word", ")", "{", "tag", "=", "\"", "\"", "\n", "}", "else", "if", "keep", ".", "MatchString", "(", "word", ")", "{", "tag", "=", "word", "\n", "}", "else", "if", "tag", ",", "found", "=", "pt", ".", "model", ".", "tagMap", "[", "word", "]", ";", "!", "found", "{", "tag", "=", "pt", ".", "model", ".", "predict", "(", "featurize", "(", "i", ",", "context", ",", "word", ",", "p1", ",", "p2", ")", ")", "\n", "}", "\n", "tokens", "=", "append", "(", "tokens", ",", "Token", "{", "Tag", ":", "tag", ",", "Text", ":", "word", "}", ")", "\n", "p2", "=", "p1", "\n", "p1", "=", "tag", "\n", "}", "\n\n", "return", "tokens", "\n", "}" ]
// Tag takes a slice of words and returns a slice of tagged tokens.
[ "Tag", "takes", "a", "slice", "of", "words", "and", "returns", "a", "slice", "of", "tagged", "tokens", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tag/aptag.go#L120-L150
train
jdkato/prose
tag/aptag.go
Train
func (pt *PerceptronTagger) Train(sentences TupleSlice, iterations int) { var guess string var found bool pt.makeTagMap(sentences) for i := 0; i < iterations; i++ { for _, tuple := range sentences { words, tags := tuple[0], tuple[1] p1, p2 := "-START-", "-START2-" context := []string{p1, p2} for _, w := range words { if w == "" { continue } context = append(context, normalize(w)) } context = append(context, []string{"-END-", "-END2-"}...) for i, word := range words { if guess, found = pt.tagMap[word]; !found { feats := featurize(i, context, word, p1, p2) guess = pt.model.predict(feats) pt.model.update(tags[i], guess, feats) } p2 = p1 p1 = guess } } shuffle.Shuffle(sentences) } pt.model.averageWeights() }
go
func (pt *PerceptronTagger) Train(sentences TupleSlice, iterations int) { var guess string var found bool pt.makeTagMap(sentences) for i := 0; i < iterations; i++ { for _, tuple := range sentences { words, tags := tuple[0], tuple[1] p1, p2 := "-START-", "-START2-" context := []string{p1, p2} for _, w := range words { if w == "" { continue } context = append(context, normalize(w)) } context = append(context, []string{"-END-", "-END2-"}...) for i, word := range words { if guess, found = pt.tagMap[word]; !found { feats := featurize(i, context, word, p1, p2) guess = pt.model.predict(feats) pt.model.update(tags[i], guess, feats) } p2 = p1 p1 = guess } } shuffle.Shuffle(sentences) } pt.model.averageWeights() }
[ "func", "(", "pt", "*", "PerceptronTagger", ")", "Train", "(", "sentences", "TupleSlice", ",", "iterations", "int", ")", "{", "var", "guess", "string", "\n", "var", "found", "bool", "\n\n", "pt", ".", "makeTagMap", "(", "sentences", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "iterations", ";", "i", "++", "{", "for", "_", ",", "tuple", ":=", "range", "sentences", "{", "words", ",", "tags", ":=", "tuple", "[", "0", "]", ",", "tuple", "[", "1", "]", "\n", "p1", ",", "p2", ":=", "\"", "\"", ",", "\"", "\"", "\n", "context", ":=", "[", "]", "string", "{", "p1", ",", "p2", "}", "\n", "for", "_", ",", "w", ":=", "range", "words", "{", "if", "w", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "context", "=", "append", "(", "context", ",", "normalize", "(", "w", ")", ")", "\n", "}", "\n", "context", "=", "append", "(", "context", ",", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", "...", ")", "\n", "for", "i", ",", "word", ":=", "range", "words", "{", "if", "guess", ",", "found", "=", "pt", ".", "tagMap", "[", "word", "]", ";", "!", "found", "{", "feats", ":=", "featurize", "(", "i", ",", "context", ",", "word", ",", "p1", ",", "p2", ")", "\n", "guess", "=", "pt", ".", "model", ".", "predict", "(", "feats", ")", "\n", "pt", ".", "model", ".", "update", "(", "tags", "[", "i", "]", ",", "guess", ",", "feats", ")", "\n", "}", "\n", "p2", "=", "p1", "\n", "p1", "=", "guess", "\n", "}", "\n", "}", "\n", "shuffle", ".", "Shuffle", "(", "sentences", ")", "\n", "}", "\n", "pt", ".", "model", ".", "averageWeights", "(", ")", "\n", "}" ]
// Train an Averaged Perceptron model based on sentences.
[ "Train", "an", "Averaged", "Perceptron", "model", "based", "on", "sentences", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tag/aptag.go#L153-L183
train
jdkato/prose
transform/transform.go
Pascal
func Pascal(s string) string { out := "" wasSpace := false for i, c := range removeCase(s, " ", unicode.ToLower) { if i == 0 || wasSpace { c = unicode.ToUpper(c) } wasSpace = c == ' ' if !wasSpace { out += string(c) } } return out }
go
func Pascal(s string) string { out := "" wasSpace := false for i, c := range removeCase(s, " ", unicode.ToLower) { if i == 0 || wasSpace { c = unicode.ToUpper(c) } wasSpace = c == ' ' if !wasSpace { out += string(c) } } return out }
[ "func", "Pascal", "(", "s", "string", ")", "string", "{", "out", ":=", "\"", "\"", "\n", "wasSpace", ":=", "false", "\n", "for", "i", ",", "c", ":=", "range", "removeCase", "(", "s", ",", "\"", "\"", ",", "unicode", ".", "ToLower", ")", "{", "if", "i", "==", "0", "||", "wasSpace", "{", "c", "=", "unicode", ".", "ToUpper", "(", "c", ")", "\n", "}", "\n", "wasSpace", "=", "c", "==", "' '", "\n", "if", "!", "wasSpace", "{", "out", "+=", "string", "(", "c", ")", "\n", "}", "\n", "}", "\n", "return", "out", "\n", "}" ]
// Pascal returns a Pascal-cased copy of the string s.
[ "Pascal", "returns", "a", "Pascal", "-", "cased", "copy", "of", "the", "string", "s", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/transform/transform.go#L57-L70
train
jdkato/prose
transform/transform.go
Camel
func Camel(s string) string { first := ' ' for _, c := range s { if unicode.IsLetter(c) || unicode.IsNumber(c) { first = c break } } return strings.TrimSpace(string(unicode.ToLower(first)) + Pascal(s)[1:]) }
go
func Camel(s string) string { first := ' ' for _, c := range s { if unicode.IsLetter(c) || unicode.IsNumber(c) { first = c break } } return strings.TrimSpace(string(unicode.ToLower(first)) + Pascal(s)[1:]) }
[ "func", "Camel", "(", "s", "string", ")", "string", "{", "first", ":=", "' '", "\n", "for", "_", ",", "c", ":=", "range", "s", "{", "if", "unicode", ".", "IsLetter", "(", "c", ")", "||", "unicode", ".", "IsNumber", "(", "c", ")", "{", "first", "=", "c", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "strings", ".", "TrimSpace", "(", "string", "(", "unicode", ".", "ToLower", "(", "first", ")", ")", "+", "Pascal", "(", "s", ")", "[", "1", ":", "]", ")", "\n", "}" ]
// Camel returns a Camel-cased copy of the string s.
[ "Camel", "returns", "a", "Camel", "-", "cased", "copy", "of", "the", "string", "s", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/transform/transform.go#L73-L82
train
jdkato/prose
internal/util/util.go
ReadDataFile
func ReadDataFile(path string) []byte { p, err := filepath.Abs(path) CheckError(err) data, ferr := ioutil.ReadFile(p) CheckError(ferr) return data }
go
func ReadDataFile(path string) []byte { p, err := filepath.Abs(path) CheckError(err) data, ferr := ioutil.ReadFile(p) CheckError(ferr) return data }
[ "func", "ReadDataFile", "(", "path", "string", ")", "[", "]", "byte", "{", "p", ",", "err", ":=", "filepath", ".", "Abs", "(", "path", ")", "\n", "CheckError", "(", "err", ")", "\n\n", "data", ",", "ferr", ":=", "ioutil", ".", "ReadFile", "(", "p", ")", "\n", "CheckError", "(", "ferr", ")", "\n\n", "return", "data", "\n", "}" ]
// ReadDataFile reads data from a file, panicking on any errors.
[ "ReadDataFile", "reads", "data", "from", "a", "file", "panicking", "on", "any", "errors", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/internal/util/util.go#L13-L21
train
jdkato/prose
internal/util/util.go
IsPunct
func IsPunct(c byte) bool { for _, r := range []byte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") { if c == r { return true } } return false }
go
func IsPunct(c byte) bool { for _, r := range []byte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") { if c == r { return true } } return false }
[ "func", "IsPunct", "(", "c", "byte", ")", "bool", "{", "for", "_", ",", "r", ":=", "range", "[", "]", "byte", "(", "\"", "\\\"", "\\\\", "\"", ")", "{", "if", "c", "==", "r", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsPunct determines if a character is a punctuation symbol.
[ "IsPunct", "determines", "if", "a", "character", "is", "a", "punctuation", "symbol", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/internal/util/util.go#L39-L46
train
jdkato/prose
internal/util/util.go
IsSpace
func IsSpace(c byte) bool { for _, r := range []byte("\t\n\r\f\v") { if c == r { return true } } return false }
go
func IsSpace(c byte) bool { for _, r := range []byte("\t\n\r\f\v") { if c == r { return true } } return false }
[ "func", "IsSpace", "(", "c", "byte", ")", "bool", "{", "for", "_", ",", "r", ":=", "range", "[", "]", "byte", "(", "\"", "\\t", "\\n", "\\r", "\\f", "\\v", "\"", ")", "{", "if", "c", "==", "r", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsSpace determines if a character is a whitespace character.
[ "IsSpace", "determines", "if", "a", "character", "is", "a", "whitespace", "character", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/internal/util/util.go#L49-L56
train
jdkato/prose
internal/util/util.go
HasAnySuffix
func HasAnySuffix(a string, slice []string) bool { for _, b := range slice { if strings.HasSuffix(a, b) { return true } } return false }
go
func HasAnySuffix(a string, slice []string) bool { for _, b := range slice { if strings.HasSuffix(a, b) { return true } } return false }
[ "func", "HasAnySuffix", "(", "a", "string", ",", "slice", "[", "]", "string", ")", "bool", "{", "for", "_", ",", "b", ":=", "range", "slice", "{", "if", "strings", ".", "HasSuffix", "(", "a", ",", "b", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasAnySuffix determines if the string a has any suffixes contained in the // slice b.
[ "HasAnySuffix", "determines", "if", "the", "string", "a", "has", "any", "suffixes", "contained", "in", "the", "slice", "b", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/internal/util/util.go#L80-L87
train
jdkato/prose
internal/util/util.go
ContainsAny
func ContainsAny(a string, b []string) bool { for _, s := range b { if strings.Contains(a, s) { return true } } return false }
go
func ContainsAny(a string, b []string) bool { for _, s := range b { if strings.Contains(a, s) { return true } } return false }
[ "func", "ContainsAny", "(", "a", "string", ",", "b", "[", "]", "string", ")", "bool", "{", "for", "_", ",", "s", ":=", "range", "b", "{", "if", "strings", ".", "Contains", "(", "a", ",", "s", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// ContainsAny determines if the string a contains any fo the strings contained // in the slice b.
[ "ContainsAny", "determines", "if", "the", "string", "a", "contains", "any", "fo", "the", "strings", "contained", "in", "the", "slice", "b", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/internal/util/util.go#L91-L98
train
jdkato/prose
summarize/usage.go
WordDensity
func (d *Document) WordDensity() map[string]float64 { density := make(map[string]float64) for word, freq := range d.WordFrequency { val, _ := stats.Round(float64(freq)/d.NumWords, 3) density[word] = val } return density }
go
func (d *Document) WordDensity() map[string]float64 { density := make(map[string]float64) for word, freq := range d.WordFrequency { val, _ := stats.Round(float64(freq)/d.NumWords, 3) density[word] = val } return density }
[ "func", "(", "d", "*", "Document", ")", "WordDensity", "(", ")", "map", "[", "string", "]", "float64", "{", "density", ":=", "make", "(", "map", "[", "string", "]", "float64", ")", "\n", "for", "word", ",", "freq", ":=", "range", "d", ".", "WordFrequency", "{", "val", ",", "_", ":=", "stats", ".", "Round", "(", "float64", "(", "freq", ")", "/", "d", ".", "NumWords", ",", "3", ")", "\n", "density", "[", "word", "]", "=", "val", "\n", "}", "\n", "return", "density", "\n", "}" ]
// WordDensity returns a map of each word and its density.
[ "WordDensity", "returns", "a", "map", "of", "each", "word", "and", "its", "density", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/summarize/usage.go#L11-L18
train
jdkato/prose
summarize/usage.go
MeanWordLength
func (d *Document) MeanWordLength() float64 { val, _ := stats.Round(d.NumCharacters/d.NumWords, 3) return val }
go
func (d *Document) MeanWordLength() float64 { val, _ := stats.Round(d.NumCharacters/d.NumWords, 3) return val }
[ "func", "(", "d", "*", "Document", ")", "MeanWordLength", "(", ")", "float64", "{", "val", ",", "_", ":=", "stats", ".", "Round", "(", "d", ".", "NumCharacters", "/", "d", ".", "NumWords", ",", "3", ")", "\n", "return", "val", "\n", "}" ]
// MeanWordLength returns the mean number of characters per word.
[ "MeanWordLength", "returns", "the", "mean", "number", "of", "characters", "per", "word", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/summarize/usage.go#L42-L45
train
jdkato/prose
internal/model/load.go
GetAsset
func GetAsset(name string) *gob.Decoder { b, err := Asset("internal/model/" + name) util.CheckError(err) return gob.NewDecoder(bytes.NewReader(b)) }
go
func GetAsset(name string) *gob.Decoder { b, err := Asset("internal/model/" + name) util.CheckError(err) return gob.NewDecoder(bytes.NewReader(b)) }
[ "func", "GetAsset", "(", "name", "string", ")", "*", "gob", ".", "Decoder", "{", "b", ",", "err", ":=", "Asset", "(", "\"", "\"", "+", "name", ")", "\n", "util", ".", "CheckError", "(", "err", ")", "\n", "return", "gob", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "b", ")", ")", "\n", "}" ]
// GetAsset returns the named Asset.
[ "GetAsset", "returns", "the", "named", "Asset", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/internal/model/load.go#L14-L18
train
jdkato/prose
summarize/summarize.go
NewDocument
func NewDocument(text string) *Document { wTok := tokenize.NewWordBoundaryTokenizer() sTok := tokenize.NewPunktSentenceTokenizer() doc := Document{Content: text, WordTokenizer: wTok, SentenceTokenizer: sTok} doc.Initialize() return &doc }
go
func NewDocument(text string) *Document { wTok := tokenize.NewWordBoundaryTokenizer() sTok := tokenize.NewPunktSentenceTokenizer() doc := Document{Content: text, WordTokenizer: wTok, SentenceTokenizer: sTok} doc.Initialize() return &doc }
[ "func", "NewDocument", "(", "text", "string", ")", "*", "Document", "{", "wTok", ":=", "tokenize", ".", "NewWordBoundaryTokenizer", "(", ")", "\n", "sTok", ":=", "tokenize", ".", "NewPunktSentenceTokenizer", "(", ")", "\n", "doc", ":=", "Document", "{", "Content", ":", "text", ",", "WordTokenizer", ":", "wTok", ",", "SentenceTokenizer", ":", "sTok", "}", "\n", "doc", ".", "Initialize", "(", ")", "\n", "return", "&", "doc", "\n", "}" ]
// NewDocument is a Document constructor that takes a string as an argument. It // then calculates the data necessary for computing readability and usage // statistics. // // This is a convenience wrapper around the Document initialization process // that defaults to using a WordBoundaryTokenizer and a PunktSentenceTokenizer // as its word and sentence tokenizers, respectively.
[ "NewDocument", "is", "a", "Document", "constructor", "that", "takes", "a", "string", "as", "an", "argument", ".", "It", "then", "calculates", "the", "data", "necessary", "for", "computing", "readability", "and", "usage", "statistics", ".", "This", "is", "a", "convenience", "wrapper", "around", "the", "Document", "initialization", "process", "that", "defaults", "to", "using", "a", "WordBoundaryTokenizer", "and", "a", "PunktSentenceTokenizer", "as", "its", "word", "and", "sentence", "tokenizers", "respectively", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/summarize/summarize.go#L88-L94
train
jdkato/prose
summarize/summarize.go
Initialize
func (d *Document) Initialize() { d.WordFrequency = make(map[string]int) for i, paragraph := range strings.Split(d.Content, "\n\n") { for _, s := range d.SentenceTokenizer.Tokenize(paragraph) { wordCount := d.NumWords d.NumSentences++ words := []Word{} for _, word := range d.WordTokenizer.Tokenize(s) { word = strings.TrimSpace(word) if len(word) == 0 { continue } d.NumCharacters += countChars(word) if _, found := d.WordFrequency[word]; found { d.WordFrequency[word]++ } else { d.WordFrequency[word] = 1 } syllables := Syllables(word) words = append(words, Word{Text: word, Syllables: syllables}) d.NumSyllables += float64(syllables) if syllables > 2 { d.NumPolysylWords++ } if isComplex(word, syllables) { d.NumComplexWords++ } d.NumWords++ } d.Sentences = append(d.Sentences, Sentence{ Text: strings.TrimSpace(s), Length: int(d.NumWords - wordCount), Words: words, Paragraph: i}) } d.NumParagraphs++ } }
go
func (d *Document) Initialize() { d.WordFrequency = make(map[string]int) for i, paragraph := range strings.Split(d.Content, "\n\n") { for _, s := range d.SentenceTokenizer.Tokenize(paragraph) { wordCount := d.NumWords d.NumSentences++ words := []Word{} for _, word := range d.WordTokenizer.Tokenize(s) { word = strings.TrimSpace(word) if len(word) == 0 { continue } d.NumCharacters += countChars(word) if _, found := d.WordFrequency[word]; found { d.WordFrequency[word]++ } else { d.WordFrequency[word] = 1 } syllables := Syllables(word) words = append(words, Word{Text: word, Syllables: syllables}) d.NumSyllables += float64(syllables) if syllables > 2 { d.NumPolysylWords++ } if isComplex(word, syllables) { d.NumComplexWords++ } d.NumWords++ } d.Sentences = append(d.Sentences, Sentence{ Text: strings.TrimSpace(s), Length: int(d.NumWords - wordCount), Words: words, Paragraph: i}) } d.NumParagraphs++ } }
[ "func", "(", "d", "*", "Document", ")", "Initialize", "(", ")", "{", "d", ".", "WordFrequency", "=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "for", "i", ",", "paragraph", ":=", "range", "strings", ".", "Split", "(", "d", ".", "Content", ",", "\"", "\\n", "\\n", "\"", ")", "{", "for", "_", ",", "s", ":=", "range", "d", ".", "SentenceTokenizer", ".", "Tokenize", "(", "paragraph", ")", "{", "wordCount", ":=", "d", ".", "NumWords", "\n", "d", ".", "NumSentences", "++", "\n", "words", ":=", "[", "]", "Word", "{", "}", "\n", "for", "_", ",", "word", ":=", "range", "d", ".", "WordTokenizer", ".", "Tokenize", "(", "s", ")", "{", "word", "=", "strings", ".", "TrimSpace", "(", "word", ")", "\n", "if", "len", "(", "word", ")", "==", "0", "{", "continue", "\n", "}", "\n", "d", ".", "NumCharacters", "+=", "countChars", "(", "word", ")", "\n", "if", "_", ",", "found", ":=", "d", ".", "WordFrequency", "[", "word", "]", ";", "found", "{", "d", ".", "WordFrequency", "[", "word", "]", "++", "\n", "}", "else", "{", "d", ".", "WordFrequency", "[", "word", "]", "=", "1", "\n", "}", "\n", "syllables", ":=", "Syllables", "(", "word", ")", "\n", "words", "=", "append", "(", "words", ",", "Word", "{", "Text", ":", "word", ",", "Syllables", ":", "syllables", "}", ")", "\n", "d", ".", "NumSyllables", "+=", "float64", "(", "syllables", ")", "\n", "if", "syllables", ">", "2", "{", "d", ".", "NumPolysylWords", "++", "\n", "}", "\n", "if", "isComplex", "(", "word", ",", "syllables", ")", "{", "d", ".", "NumComplexWords", "++", "\n", "}", "\n", "d", ".", "NumWords", "++", "\n", "}", "\n", "d", ".", "Sentences", "=", "append", "(", "d", ".", "Sentences", ",", "Sentence", "{", "Text", ":", "strings", ".", "TrimSpace", "(", "s", ")", ",", "Length", ":", "int", "(", "d", ".", "NumWords", "-", "wordCount", ")", ",", "Words", ":", "words", ",", "Paragraph", ":", "i", "}", ")", "\n", "}", "\n", "d", ".", "NumParagraphs", "++", "\n", "}", "\n", "}" ]
// Initialize calculates the data necessary for computing readability and usage // statistics.
[ "Initialize", "calculates", "the", "data", "necessary", "for", "computing", "readability", "and", "usage", "statistics", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/summarize/summarize.go#L98-L135
train
jdkato/prose
summarize/summarize.go
Assess
func (d *Document) Assess() *Assessment { a := Assessment{ FleschKincaid: d.FleschKincaid(), ReadingEase: d.FleschReadingEase(), GunningFog: d.GunningFog(), SMOG: d.SMOG(), DaleChall: d.DaleChall(), AutomatedReadability: d.AutomatedReadability(), ColemanLiau: d.ColemanLiau()} gradeScores := []float64{ a.FleschKincaid, a.AutomatedReadability, a.GunningFog, a.SMOG, a.ColemanLiau} mean, merr := stats.Mean(gradeScores) stdDev, serr := stats.StandardDeviation(gradeScores) if merr != nil || serr != nil { a.MeanGradeLevel = 0.0 a.StdDevGradeLevel = 0.0 } else { a.MeanGradeLevel = mean a.StdDevGradeLevel = stdDev } return &a }
go
func (d *Document) Assess() *Assessment { a := Assessment{ FleschKincaid: d.FleschKincaid(), ReadingEase: d.FleschReadingEase(), GunningFog: d.GunningFog(), SMOG: d.SMOG(), DaleChall: d.DaleChall(), AutomatedReadability: d.AutomatedReadability(), ColemanLiau: d.ColemanLiau()} gradeScores := []float64{ a.FleschKincaid, a.AutomatedReadability, a.GunningFog, a.SMOG, a.ColemanLiau} mean, merr := stats.Mean(gradeScores) stdDev, serr := stats.StandardDeviation(gradeScores) if merr != nil || serr != nil { a.MeanGradeLevel = 0.0 a.StdDevGradeLevel = 0.0 } else { a.MeanGradeLevel = mean a.StdDevGradeLevel = stdDev } return &a }
[ "func", "(", "d", "*", "Document", ")", "Assess", "(", ")", "*", "Assessment", "{", "a", ":=", "Assessment", "{", "FleschKincaid", ":", "d", ".", "FleschKincaid", "(", ")", ",", "ReadingEase", ":", "d", ".", "FleschReadingEase", "(", ")", ",", "GunningFog", ":", "d", ".", "GunningFog", "(", ")", ",", "SMOG", ":", "d", ".", "SMOG", "(", ")", ",", "DaleChall", ":", "d", ".", "DaleChall", "(", ")", ",", "AutomatedReadability", ":", "d", ".", "AutomatedReadability", "(", ")", ",", "ColemanLiau", ":", "d", ".", "ColemanLiau", "(", ")", "}", "\n\n", "gradeScores", ":=", "[", "]", "float64", "{", "a", ".", "FleschKincaid", ",", "a", ".", "AutomatedReadability", ",", "a", ".", "GunningFog", ",", "a", ".", "SMOG", ",", "a", ".", "ColemanLiau", "}", "\n\n", "mean", ",", "merr", ":=", "stats", ".", "Mean", "(", "gradeScores", ")", "\n", "stdDev", ",", "serr", ":=", "stats", ".", "StandardDeviation", "(", "gradeScores", ")", "\n", "if", "merr", "!=", "nil", "||", "serr", "!=", "nil", "{", "a", ".", "MeanGradeLevel", "=", "0.0", "\n", "a", ".", "StdDevGradeLevel", "=", "0.0", "\n", "}", "else", "{", "a", ".", "MeanGradeLevel", "=", "mean", "\n", "a", ".", "StdDevGradeLevel", "=", "stdDev", "\n", "}", "\n\n", "return", "&", "a", "\n", "}" ]
// Assess returns an Assessment for the Document d.
[ "Assess", "returns", "an", "Assessment", "for", "the", "Document", "d", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/summarize/summarize.go#L138-L159
train
jdkato/prose
summarize/summarize.go
Summary
func (d *Document) Summary(n int) []RankedParagraph { rankings := []RankedParagraph{} scores := d.Keywords() for i := 0; i < int(d.NumParagraphs); i++ { p := RankedParagraph{Position: i} rank := 0 size := 0 for _, s := range d.Sentences { if s.Paragraph == i { size += s.Length for _, w := range s.Words { if score, found := scores[w.Text]; found { rank += score } } p.Sentences = append(p.Sentences, s) } } // Favor longer paragraphs, as they tend to be more informational. p.Rank = (rank * size) rankings = append(rankings, p) } // Sort by raking: sort.Sort(byRank(rankings)) // Take the top-n paragraphs: size := len(rankings) if size > n { rankings = rankings[size-n:] } // Sort by chronological position: sort.Sort(byIndex(rankings)) return rankings }
go
func (d *Document) Summary(n int) []RankedParagraph { rankings := []RankedParagraph{} scores := d.Keywords() for i := 0; i < int(d.NumParagraphs); i++ { p := RankedParagraph{Position: i} rank := 0 size := 0 for _, s := range d.Sentences { if s.Paragraph == i { size += s.Length for _, w := range s.Words { if score, found := scores[w.Text]; found { rank += score } } p.Sentences = append(p.Sentences, s) } } // Favor longer paragraphs, as they tend to be more informational. p.Rank = (rank * size) rankings = append(rankings, p) } // Sort by raking: sort.Sort(byRank(rankings)) // Take the top-n paragraphs: size := len(rankings) if size > n { rankings = rankings[size-n:] } // Sort by chronological position: sort.Sort(byIndex(rankings)) return rankings }
[ "func", "(", "d", "*", "Document", ")", "Summary", "(", "n", "int", ")", "[", "]", "RankedParagraph", "{", "rankings", ":=", "[", "]", "RankedParagraph", "{", "}", "\n", "scores", ":=", "d", ".", "Keywords", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "d", ".", "NumParagraphs", ")", ";", "i", "++", "{", "p", ":=", "RankedParagraph", "{", "Position", ":", "i", "}", "\n", "rank", ":=", "0", "\n", "size", ":=", "0", "\n", "for", "_", ",", "s", ":=", "range", "d", ".", "Sentences", "{", "if", "s", ".", "Paragraph", "==", "i", "{", "size", "+=", "s", ".", "Length", "\n", "for", "_", ",", "w", ":=", "range", "s", ".", "Words", "{", "if", "score", ",", "found", ":=", "scores", "[", "w", ".", "Text", "]", ";", "found", "{", "rank", "+=", "score", "\n", "}", "\n", "}", "\n", "p", ".", "Sentences", "=", "append", "(", "p", ".", "Sentences", ",", "s", ")", "\n", "}", "\n", "}", "\n", "// Favor longer paragraphs, as they tend to be more informational.", "p", ".", "Rank", "=", "(", "rank", "*", "size", ")", "\n", "rankings", "=", "append", "(", "rankings", ",", "p", ")", "\n", "}", "\n\n", "// Sort by raking:", "sort", ".", "Sort", "(", "byRank", "(", "rankings", ")", ")", "\n\n", "// Take the top-n paragraphs:", "size", ":=", "len", "(", "rankings", ")", "\n", "if", "size", ">", "n", "{", "rankings", "=", "rankings", "[", "size", "-", "n", ":", "]", "\n", "}", "\n\n", "// Sort by chronological position:", "sort", ".", "Sort", "(", "byIndex", "(", "rankings", ")", ")", "\n", "return", "rankings", "\n", "}" ]
// Summary returns a Document's n highest ranked paragraphs according to // keyword frequency.
[ "Summary", "returns", "a", "Document", "s", "n", "highest", "ranked", "paragraphs", "according", "to", "keyword", "frequency", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/summarize/summarize.go#L163-L198
train
jdkato/prose
tokenize/punkt.go
NewPunktSentenceTokenizer
func NewPunktSentenceTokenizer() *PunktSentenceTokenizer { var pt PunktSentenceTokenizer var err error pt.tokenizer, err = newSentenceTokenizer(nil) util.CheckError(err) return &pt }
go
func NewPunktSentenceTokenizer() *PunktSentenceTokenizer { var pt PunktSentenceTokenizer var err error pt.tokenizer, err = newSentenceTokenizer(nil) util.CheckError(err) return &pt }
[ "func", "NewPunktSentenceTokenizer", "(", ")", "*", "PunktSentenceTokenizer", "{", "var", "pt", "PunktSentenceTokenizer", "\n", "var", "err", "error", "\n\n", "pt", ".", "tokenizer", ",", "err", "=", "newSentenceTokenizer", "(", "nil", ")", "\n", "util", ".", "CheckError", "(", "err", ")", "\n\n", "return", "&", "pt", "\n", "}" ]
// NewPunktSentenceTokenizer creates a new PunktSentenceTokenizer and loads // its English model.
[ "NewPunktSentenceTokenizer", "creates", "a", "new", "PunktSentenceTokenizer", "and", "loads", "its", "English", "model", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/punkt.go#L41-L49
train
jdkato/prose
tokenize/punkt.go
newSentenceTokenizer
func newSentenceTokenizer(s *sentences.Storage) (*sentences.DefaultSentenceTokenizer, error) { training := s if training == nil { b, err := data.Asset("data/english.json") if err != nil { return nil, err } training, err = sentences.LoadTraining(b) if err != nil { return nil, err } } // supervisor abbreviations abbrevs := []string{"sgt", "gov", "no", "mt"} for _, abbr := range abbrevs { training.AbbrevTypes.Add(abbr) } lang := sentences.NewPunctStrings() word := newWordTokenizer(lang) annotations := sentences.NewAnnotations(training, lang, word) ortho := &sentences.OrthoContext{ Storage: training, PunctStrings: lang, TokenType: word, TokenFirst: word, } multiPunct := &multiPunctWordAnnotation{ Storage: training, TokenParser: word, TokenGrouper: &sentences.DefaultTokenGrouper{}, Ortho: ortho, } annotations = append(annotations, multiPunct) tokenizer := &sentences.DefaultSentenceTokenizer{ Storage: training, PunctStrings: lang, WordTokenizer: word, Annotations: annotations, } return tokenizer, nil }
go
func newSentenceTokenizer(s *sentences.Storage) (*sentences.DefaultSentenceTokenizer, error) { training := s if training == nil { b, err := data.Asset("data/english.json") if err != nil { return nil, err } training, err = sentences.LoadTraining(b) if err != nil { return nil, err } } // supervisor abbreviations abbrevs := []string{"sgt", "gov", "no", "mt"} for _, abbr := range abbrevs { training.AbbrevTypes.Add(abbr) } lang := sentences.NewPunctStrings() word := newWordTokenizer(lang) annotations := sentences.NewAnnotations(training, lang, word) ortho := &sentences.OrthoContext{ Storage: training, PunctStrings: lang, TokenType: word, TokenFirst: word, } multiPunct := &multiPunctWordAnnotation{ Storage: training, TokenParser: word, TokenGrouper: &sentences.DefaultTokenGrouper{}, Ortho: ortho, } annotations = append(annotations, multiPunct) tokenizer := &sentences.DefaultSentenceTokenizer{ Storage: training, PunctStrings: lang, WordTokenizer: word, Annotations: annotations, } return tokenizer, nil }
[ "func", "newSentenceTokenizer", "(", "s", "*", "sentences", ".", "Storage", ")", "(", "*", "sentences", ".", "DefaultSentenceTokenizer", ",", "error", ")", "{", "training", ":=", "s", "\n\n", "if", "training", "==", "nil", "{", "b", ",", "err", ":=", "data", ".", "Asset", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "training", ",", "err", "=", "sentences", ".", "LoadTraining", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "// supervisor abbreviations", "abbrevs", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "\n", "for", "_", ",", "abbr", ":=", "range", "abbrevs", "{", "training", ".", "AbbrevTypes", ".", "Add", "(", "abbr", ")", "\n", "}", "\n\n", "lang", ":=", "sentences", ".", "NewPunctStrings", "(", ")", "\n", "word", ":=", "newWordTokenizer", "(", "lang", ")", "\n", "annotations", ":=", "sentences", ".", "NewAnnotations", "(", "training", ",", "lang", ",", "word", ")", "\n\n", "ortho", ":=", "&", "sentences", ".", "OrthoContext", "{", "Storage", ":", "training", ",", "PunctStrings", ":", "lang", ",", "TokenType", ":", "word", ",", "TokenFirst", ":", "word", ",", "}", "\n\n", "multiPunct", ":=", "&", "multiPunctWordAnnotation", "{", "Storage", ":", "training", ",", "TokenParser", ":", "word", ",", "TokenGrouper", ":", "&", "sentences", ".", "DefaultTokenGrouper", "{", "}", ",", "Ortho", ":", "ortho", ",", "}", "\n\n", "annotations", "=", "append", "(", "annotations", ",", "multiPunct", ")", "\n\n", "tokenizer", ":=", "&", "sentences", ".", "DefaultSentenceTokenizer", "{", "Storage", ":", "training", ",", "PunctStrings", ":", "lang", ",", "WordTokenizer", ":", "word", ",", "Annotations", ":", "annotations", ",", "}", "\n\n", "return", "tokenizer", ",", "nil", "\n", "}" ]
// English customized sentence tokenizer.
[ "English", "customized", "sentence", "tokenizer", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/punkt.go#L69-L118
train
jdkato/prose
tokenize/pragmatic.go
sub
func (r *rule) sub(text string) string { if !r.pattern.MatchString(text) { return text } orig := len(text) diff := 0 for _, submat := range r.pattern.FindAllStringSubmatchIndex(text, -1) { for idx, mat := range submat { if mat != -1 && idx > 0 && idx%2 == 0 { loc := []int{mat - diff, submat[idx+1] - diff} text = text[:loc[0]] + r.replacement + text[loc[1]:] diff = orig - len(text) } } } return text }
go
func (r *rule) sub(text string) string { if !r.pattern.MatchString(text) { return text } orig := len(text) diff := 0 for _, submat := range r.pattern.FindAllStringSubmatchIndex(text, -1) { for idx, mat := range submat { if mat != -1 && idx > 0 && idx%2 == 0 { loc := []int{mat - diff, submat[idx+1] - diff} text = text[:loc[0]] + r.replacement + text[loc[1]:] diff = orig - len(text) } } } return text }
[ "func", "(", "r", "*", "rule", ")", "sub", "(", "text", "string", ")", "string", "{", "if", "!", "r", ".", "pattern", ".", "MatchString", "(", "text", ")", "{", "return", "text", "\n", "}", "\n\n", "orig", ":=", "len", "(", "text", ")", "\n", "diff", ":=", "0", "\n", "for", "_", ",", "submat", ":=", "range", "r", ".", "pattern", ".", "FindAllStringSubmatchIndex", "(", "text", ",", "-", "1", ")", "{", "for", "idx", ",", "mat", ":=", "range", "submat", "{", "if", "mat", "!=", "-", "1", "&&", "idx", ">", "0", "&&", "idx", "%", "2", "==", "0", "{", "loc", ":=", "[", "]", "int", "{", "mat", "-", "diff", ",", "submat", "[", "idx", "+", "1", "]", "-", "diff", "}", "\n", "text", "=", "text", "[", ":", "loc", "[", "0", "]", "]", "+", "r", ".", "replacement", "+", "text", "[", "loc", "[", "1", "]", ":", "]", "\n", "diff", "=", "orig", "-", "len", "(", "text", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "text", "\n", "}" ]
// sub replaces all occurrences of Pattern with Replacement.
[ "sub", "replaces", "all", "occurrences", "of", "Pattern", "with", "Replacement", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/pragmatic.go#L72-L90
train
jdkato/prose
tokenize/pragmatic.go
subPat
func subPat(text, mtype string, pat *regexp.Regexp) string { canidates := []string{} for _, s := range pat.FindAllString(text, -1) { canidates = append(canidates, strings.TrimSpace(s)) } r := punctuationReplacer{ matches: canidates, text: text, matchType: mtype} return r.replace() }
go
func subPat(text, mtype string, pat *regexp.Regexp) string { canidates := []string{} for _, s := range pat.FindAllString(text, -1) { canidates = append(canidates, strings.TrimSpace(s)) } r := punctuationReplacer{ matches: canidates, text: text, matchType: mtype} return r.replace() }
[ "func", "subPat", "(", "text", ",", "mtype", "string", ",", "pat", "*", "regexp", ".", "Regexp", ")", "string", "{", "canidates", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "s", ":=", "range", "pat", ".", "FindAllString", "(", "text", ",", "-", "1", ")", "{", "canidates", "=", "append", "(", "canidates", ",", "strings", ".", "TrimSpace", "(", "s", ")", ")", "\n", "}", "\n", "r", ":=", "punctuationReplacer", "{", "matches", ":", "canidates", ",", "text", ":", "text", ",", "matchType", ":", "mtype", "}", "\n", "return", "r", ".", "replace", "(", ")", "\n", "}" ]
// subPat replaces all punctuation in the strings that match the regexp pat.
[ "subPat", "replaces", "all", "punctuation", "in", "the", "strings", "that", "match", "the", "regexp", "pat", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/pragmatic.go#L185-L193
train
jdkato/prose
tokenize/pragmatic.go
replaceBetweenQuotes
func replaceBetweenQuotes(text string) string { text = subPat(text, "single", betweenSingleQuotesRE) text = subPat(text, "double", betweenDoubleQuotesRE) text = subPat(text, "double", betweenSquareBracketsRE) text = subPat(text, "double", betweenParensRE) text = subPat(text, "double", betweenArrowQuotesRE) text = subPat(text, "double", betweenSmartQuotesRE) return text }
go
func replaceBetweenQuotes(text string) string { text = subPat(text, "single", betweenSingleQuotesRE) text = subPat(text, "double", betweenDoubleQuotesRE) text = subPat(text, "double", betweenSquareBracketsRE) text = subPat(text, "double", betweenParensRE) text = subPat(text, "double", betweenArrowQuotesRE) text = subPat(text, "double", betweenSmartQuotesRE) return text }
[ "func", "replaceBetweenQuotes", "(", "text", "string", ")", "string", "{", "text", "=", "subPat", "(", "text", ",", "\"", "\"", ",", "betweenSingleQuotesRE", ")", "\n", "text", "=", "subPat", "(", "text", ",", "\"", "\"", ",", "betweenDoubleQuotesRE", ")", "\n", "text", "=", "subPat", "(", "text", ",", "\"", "\"", ",", "betweenSquareBracketsRE", ")", "\n", "text", "=", "subPat", "(", "text", ",", "\"", "\"", ",", "betweenParensRE", ")", "\n", "text", "=", "subPat", "(", "text", ",", "\"", "\"", ",", "betweenArrowQuotesRE", ")", "\n", "text", "=", "subPat", "(", "text", ",", "\"", "\"", ",", "betweenSmartQuotesRE", ")", "\n", "return", "text", "\n", "}" ]
// replaceBetweenQuotes replaces punctuation inside quotes.
[ "replaceBetweenQuotes", "replaces", "punctuation", "inside", "quotes", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/pragmatic.go#L196-L204
train
jdkato/prose
tokenize/pragmatic.go
substitute
func substitute(src, sub, repl string) string { idx := strings.Index(src, sub) for idx >= 0 { src = src[:idx] + repl + src[idx+len(sub):] idx = strings.Index(src, sub) } return src }
go
func substitute(src, sub, repl string) string { idx := strings.Index(src, sub) for idx >= 0 { src = src[:idx] + repl + src[idx+len(sub):] idx = strings.Index(src, sub) } return src }
[ "func", "substitute", "(", "src", ",", "sub", ",", "repl", "string", ")", "string", "{", "idx", ":=", "strings", ".", "Index", "(", "src", ",", "sub", ")", "\n", "for", "idx", ">=", "0", "{", "src", "=", "src", "[", ":", "idx", "]", "+", "repl", "+", "src", "[", "idx", "+", "len", "(", "sub", ")", ":", "]", "\n", "idx", "=", "strings", ".", "Index", "(", "src", ",", "sub", ")", "\n", "}", "\n", "return", "src", "\n", "}" ]
// substitute replaces the substring sub with the string repl.
[ "substitute", "replaces", "the", "substring", "sub", "with", "the", "string", "repl", "." ]
a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f
https://github.com/jdkato/prose/blob/a179b97cfa6fc3949fe1bcd21e01011bc17f4c2f/tokenize/pragmatic.go#L215-L222
train
looplab/fsm
utils.go
Visualize
func Visualize(fsm *FSM) string { var buf bytes.Buffer states := make(map[string]int) buf.WriteString(fmt.Sprintf(`digraph fsm {`)) buf.WriteString("\n") // make sure the initial state is at top for k, v := range fsm.transitions { if k.src == fsm.current { states[k.src]++ states[v]++ buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event)) buf.WriteString("\n") } } for k, v := range fsm.transitions { if k.src != fsm.current { states[k.src]++ states[v]++ buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event)) buf.WriteString("\n") } } buf.WriteString("\n") for k := range states { buf.WriteString(fmt.Sprintf(` "%s";`, k)) buf.WriteString("\n") } buf.WriteString(fmt.Sprintln("}")) return buf.String() }
go
func Visualize(fsm *FSM) string { var buf bytes.Buffer states := make(map[string]int) buf.WriteString(fmt.Sprintf(`digraph fsm {`)) buf.WriteString("\n") // make sure the initial state is at top for k, v := range fsm.transitions { if k.src == fsm.current { states[k.src]++ states[v]++ buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event)) buf.WriteString("\n") } } for k, v := range fsm.transitions { if k.src != fsm.current { states[k.src]++ states[v]++ buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event)) buf.WriteString("\n") } } buf.WriteString("\n") for k := range states { buf.WriteString(fmt.Sprintf(` "%s";`, k)) buf.WriteString("\n") } buf.WriteString(fmt.Sprintln("}")) return buf.String() }
[ "func", "Visualize", "(", "fsm", "*", "FSM", ")", "string", "{", "var", "buf", "bytes", ".", "Buffer", "\n\n", "states", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "\n\n", "buf", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "`digraph fsm {`", ")", ")", "\n", "buf", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n\n", "// make sure the initial state is at top", "for", "k", ",", "v", ":=", "range", "fsm", ".", "transitions", "{", "if", "k", ".", "src", "==", "fsm", ".", "current", "{", "states", "[", "k", ".", "src", "]", "++", "\n", "states", "[", "v", "]", "++", "\n", "buf", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "` \"%s\" -> \"%s\" [ label = \"%s\" ];`", ",", "k", ".", "src", ",", "v", ",", "k", ".", "event", ")", ")", "\n", "buf", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "}", "\n\n", "for", "k", ",", "v", ":=", "range", "fsm", ".", "transitions", "{", "if", "k", ".", "src", "!=", "fsm", ".", "current", "{", "states", "[", "k", ".", "src", "]", "++", "\n", "states", "[", "v", "]", "++", "\n", "buf", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "` \"%s\" -> \"%s\" [ label = \"%s\" ];`", ",", "k", ".", "src", ",", "v", ",", "k", ".", "event", ")", ")", "\n", "buf", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "}", "\n\n", "buf", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n\n", "for", "k", ":=", "range", "states", "{", "buf", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "` \"%s\";`", ",", "k", ")", ")", "\n", "buf", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "buf", ".", "WriteString", "(", "fmt", ".", "Sprintln", "(", "\"", "\"", ")", ")", "\n\n", "return", "buf", ".", "String", "(", ")", "\n", "}" ]
// Visualize outputs a visualization of a FSM in Graphviz format.
[ "Visualize", "outputs", "a", "visualization", "of", "a", "FSM", "in", "Graphviz", "format", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/utils.go#L9-L45
train
looplab/fsm
fsm.go
Current
func (f *FSM) Current() string { f.stateMu.RLock() defer f.stateMu.RUnlock() return f.current }
go
func (f *FSM) Current() string { f.stateMu.RLock() defer f.stateMu.RUnlock() return f.current }
[ "func", "(", "f", "*", "FSM", ")", "Current", "(", ")", "string", "{", "f", ".", "stateMu", ".", "RLock", "(", ")", "\n", "defer", "f", ".", "stateMu", ".", "RUnlock", "(", ")", "\n", "return", "f", ".", "current", "\n", "}" ]
// Current returns the current state of the FSM.
[ "Current", "returns", "the", "current", "state", "of", "the", "FSM", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L202-L206
train
looplab/fsm
fsm.go
Is
func (f *FSM) Is(state string) bool { f.stateMu.RLock() defer f.stateMu.RUnlock() return state == f.current }
go
func (f *FSM) Is(state string) bool { f.stateMu.RLock() defer f.stateMu.RUnlock() return state == f.current }
[ "func", "(", "f", "*", "FSM", ")", "Is", "(", "state", "string", ")", "bool", "{", "f", ".", "stateMu", ".", "RLock", "(", ")", "\n", "defer", "f", ".", "stateMu", ".", "RUnlock", "(", ")", "\n", "return", "state", "==", "f", ".", "current", "\n", "}" ]
// Is returns true if state is the current state.
[ "Is", "returns", "true", "if", "state", "is", "the", "current", "state", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L209-L213
train
looplab/fsm
fsm.go
SetState
func (f *FSM) SetState(state string) { f.stateMu.Lock() defer f.stateMu.Unlock() f.current = state return }
go
func (f *FSM) SetState(state string) { f.stateMu.Lock() defer f.stateMu.Unlock() f.current = state return }
[ "func", "(", "f", "*", "FSM", ")", "SetState", "(", "state", "string", ")", "{", "f", ".", "stateMu", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "stateMu", ".", "Unlock", "(", ")", "\n", "f", ".", "current", "=", "state", "\n", "return", "\n", "}" ]
// SetState allows the user to move to the given state from current state. // The call does not trigger any callbacks, if defined.
[ "SetState", "allows", "the", "user", "to", "move", "to", "the", "given", "state", "from", "current", "state", ".", "The", "call", "does", "not", "trigger", "any", "callbacks", "if", "defined", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L217-L222
train
looplab/fsm
fsm.go
Can
func (f *FSM) Can(event string) bool { f.stateMu.RLock() defer f.stateMu.RUnlock() _, ok := f.transitions[eKey{event, f.current}] return ok && (f.transition == nil) }
go
func (f *FSM) Can(event string) bool { f.stateMu.RLock() defer f.stateMu.RUnlock() _, ok := f.transitions[eKey{event, f.current}] return ok && (f.transition == nil) }
[ "func", "(", "f", "*", "FSM", ")", "Can", "(", "event", "string", ")", "bool", "{", "f", ".", "stateMu", ".", "RLock", "(", ")", "\n", "defer", "f", ".", "stateMu", ".", "RUnlock", "(", ")", "\n", "_", ",", "ok", ":=", "f", ".", "transitions", "[", "eKey", "{", "event", ",", "f", ".", "current", "}", "]", "\n", "return", "ok", "&&", "(", "f", ".", "transition", "==", "nil", ")", "\n", "}" ]
// Can returns true if event can occur in the current state.
[ "Can", "returns", "true", "if", "event", "can", "occur", "in", "the", "current", "state", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L225-L230
train
looplab/fsm
fsm.go
AvailableTransitions
func (f *FSM) AvailableTransitions() []string { f.stateMu.RLock() defer f.stateMu.RUnlock() var transitions []string for key := range f.transitions { if key.src == f.current { transitions = append(transitions, key.event) } } return transitions }
go
func (f *FSM) AvailableTransitions() []string { f.stateMu.RLock() defer f.stateMu.RUnlock() var transitions []string for key := range f.transitions { if key.src == f.current { transitions = append(transitions, key.event) } } return transitions }
[ "func", "(", "f", "*", "FSM", ")", "AvailableTransitions", "(", ")", "[", "]", "string", "{", "f", ".", "stateMu", ".", "RLock", "(", ")", "\n", "defer", "f", ".", "stateMu", ".", "RUnlock", "(", ")", "\n", "var", "transitions", "[", "]", "string", "\n", "for", "key", ":=", "range", "f", ".", "transitions", "{", "if", "key", ".", "src", "==", "f", ".", "current", "{", "transitions", "=", "append", "(", "transitions", ",", "key", ".", "event", ")", "\n", "}", "\n", "}", "\n", "return", "transitions", "\n", "}" ]
// AvailableTransitions returns a list of transitions avilable in the // current state.
[ "AvailableTransitions", "returns", "a", "list", "of", "transitions", "avilable", "in", "the", "current", "state", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L234-L244
train
looplab/fsm
fsm.go
Transition
func (f *FSM) Transition() error { f.eventMu.Lock() defer f.eventMu.Unlock() return f.doTransition() }
go
func (f *FSM) Transition() error { f.eventMu.Lock() defer f.eventMu.Unlock() return f.doTransition() }
[ "func", "(", "f", "*", "FSM", ")", "Transition", "(", ")", "error", "{", "f", ".", "eventMu", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "eventMu", ".", "Unlock", "(", ")", "\n", "return", "f", ".", "doTransition", "(", ")", "\n", "}" ]
// Transition wraps transitioner.transition.
[ "Transition", "wraps", "transitioner", ".", "transition", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L331-L335
train
looplab/fsm
fsm.go
beforeEventCallbacks
func (f *FSM) beforeEventCallbacks(e *Event) error { if fn, ok := f.callbacks[cKey{e.Event, callbackBeforeEvent}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } } if fn, ok := f.callbacks[cKey{"", callbackBeforeEvent}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } } return nil }
go
func (f *FSM) beforeEventCallbacks(e *Event) error { if fn, ok := f.callbacks[cKey{e.Event, callbackBeforeEvent}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } } if fn, ok := f.callbacks[cKey{"", callbackBeforeEvent}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } } return nil }
[ "func", "(", "f", "*", "FSM", ")", "beforeEventCallbacks", "(", "e", "*", "Event", ")", "error", "{", "if", "fn", ",", "ok", ":=", "f", ".", "callbacks", "[", "cKey", "{", "e", ".", "Event", ",", "callbackBeforeEvent", "}", "]", ";", "ok", "{", "fn", "(", "e", ")", "\n", "if", "e", ".", "canceled", "{", "return", "CanceledError", "{", "e", ".", "Err", "}", "\n", "}", "\n", "}", "\n", "if", "fn", ",", "ok", ":=", "f", ".", "callbacks", "[", "cKey", "{", "\"", "\"", ",", "callbackBeforeEvent", "}", "]", ";", "ok", "{", "fn", "(", "e", ")", "\n", "if", "e", ".", "canceled", "{", "return", "CanceledError", "{", "e", ".", "Err", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// beforeEventCallbacks calls the before_ callbacks, first the named then the // general version.
[ "beforeEventCallbacks", "calls", "the", "before_", "callbacks", "first", "the", "named", "then", "the", "general", "version", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L361-L375
train
looplab/fsm
fsm.go
leaveStateCallbacks
func (f *FSM) leaveStateCallbacks(e *Event) error { if fn, ok := f.callbacks[cKey{f.current, callbackLeaveState}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } else if e.async { return AsyncError{e.Err} } } if fn, ok := f.callbacks[cKey{"", callbackLeaveState}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } else if e.async { return AsyncError{e.Err} } } return nil }
go
func (f *FSM) leaveStateCallbacks(e *Event) error { if fn, ok := f.callbacks[cKey{f.current, callbackLeaveState}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } else if e.async { return AsyncError{e.Err} } } if fn, ok := f.callbacks[cKey{"", callbackLeaveState}]; ok { fn(e) if e.canceled { return CanceledError{e.Err} } else if e.async { return AsyncError{e.Err} } } return nil }
[ "func", "(", "f", "*", "FSM", ")", "leaveStateCallbacks", "(", "e", "*", "Event", ")", "error", "{", "if", "fn", ",", "ok", ":=", "f", ".", "callbacks", "[", "cKey", "{", "f", ".", "current", ",", "callbackLeaveState", "}", "]", ";", "ok", "{", "fn", "(", "e", ")", "\n", "if", "e", ".", "canceled", "{", "return", "CanceledError", "{", "e", ".", "Err", "}", "\n", "}", "else", "if", "e", ".", "async", "{", "return", "AsyncError", "{", "e", ".", "Err", "}", "\n", "}", "\n", "}", "\n", "if", "fn", ",", "ok", ":=", "f", ".", "callbacks", "[", "cKey", "{", "\"", "\"", ",", "callbackLeaveState", "}", "]", ";", "ok", "{", "fn", "(", "e", ")", "\n", "if", "e", ".", "canceled", "{", "return", "CanceledError", "{", "e", ".", "Err", "}", "\n", "}", "else", "if", "e", ".", "async", "{", "return", "AsyncError", "{", "e", ".", "Err", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// leaveStateCallbacks calls the leave_ callbacks, first the named then the // general version.
[ "leaveStateCallbacks", "calls", "the", "leave_", "callbacks", "first", "the", "named", "then", "the", "general", "version", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L379-L397
train
looplab/fsm
fsm.go
enterStateCallbacks
func (f *FSM) enterStateCallbacks(e *Event) { if fn, ok := f.callbacks[cKey{f.current, callbackEnterState}]; ok { fn(e) } if fn, ok := f.callbacks[cKey{"", callbackEnterState}]; ok { fn(e) } }
go
func (f *FSM) enterStateCallbacks(e *Event) { if fn, ok := f.callbacks[cKey{f.current, callbackEnterState}]; ok { fn(e) } if fn, ok := f.callbacks[cKey{"", callbackEnterState}]; ok { fn(e) } }
[ "func", "(", "f", "*", "FSM", ")", "enterStateCallbacks", "(", "e", "*", "Event", ")", "{", "if", "fn", ",", "ok", ":=", "f", ".", "callbacks", "[", "cKey", "{", "f", ".", "current", ",", "callbackEnterState", "}", "]", ";", "ok", "{", "fn", "(", "e", ")", "\n", "}", "\n", "if", "fn", ",", "ok", ":=", "f", ".", "callbacks", "[", "cKey", "{", "\"", "\"", ",", "callbackEnterState", "}", "]", ";", "ok", "{", "fn", "(", "e", ")", "\n", "}", "\n", "}" ]
// enterStateCallbacks calls the enter_ callbacks, first the named then the // general version.
[ "enterStateCallbacks", "calls", "the", "enter_", "callbacks", "first", "the", "named", "then", "the", "general", "version", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L401-L408
train
looplab/fsm
fsm.go
afterEventCallbacks
func (f *FSM) afterEventCallbacks(e *Event) { if fn, ok := f.callbacks[cKey{e.Event, callbackAfterEvent}]; ok { fn(e) } if fn, ok := f.callbacks[cKey{"", callbackAfterEvent}]; ok { fn(e) } }
go
func (f *FSM) afterEventCallbacks(e *Event) { if fn, ok := f.callbacks[cKey{e.Event, callbackAfterEvent}]; ok { fn(e) } if fn, ok := f.callbacks[cKey{"", callbackAfterEvent}]; ok { fn(e) } }
[ "func", "(", "f", "*", "FSM", ")", "afterEventCallbacks", "(", "e", "*", "Event", ")", "{", "if", "fn", ",", "ok", ":=", "f", ".", "callbacks", "[", "cKey", "{", "e", ".", "Event", ",", "callbackAfterEvent", "}", "]", ";", "ok", "{", "fn", "(", "e", ")", "\n", "}", "\n", "if", "fn", ",", "ok", ":=", "f", ".", "callbacks", "[", "cKey", "{", "\"", "\"", ",", "callbackAfterEvent", "}", "]", ";", "ok", "{", "fn", "(", "e", ")", "\n", "}", "\n", "}" ]
// afterEventCallbacks calls the after_ callbacks, first the named then the // general version.
[ "afterEventCallbacks", "calls", "the", "after_", "callbacks", "first", "the", "named", "then", "the", "general", "version", "." ]
84b5307469f859464403f80919467950a79de1b1
https://github.com/looplab/fsm/blob/84b5307469f859464403f80919467950a79de1b1/fsm.go#L412-L419
train
armon/go-socks5
request.go
Address
func (a AddrSpec) Address() string { if 0 != len(a.IP) { return net.JoinHostPort(a.IP.String(), strconv.Itoa(a.Port)) } return net.JoinHostPort(a.FQDN, strconv.Itoa(a.Port)) }
go
func (a AddrSpec) Address() string { if 0 != len(a.IP) { return net.JoinHostPort(a.IP.String(), strconv.Itoa(a.Port)) } return net.JoinHostPort(a.FQDN, strconv.Itoa(a.Port)) }
[ "func", "(", "a", "AddrSpec", ")", "Address", "(", ")", "string", "{", "if", "0", "!=", "len", "(", "a", ".", "IP", ")", "{", "return", "net", ".", "JoinHostPort", "(", "a", ".", "IP", ".", "String", "(", ")", ",", "strconv", ".", "Itoa", "(", "a", ".", "Port", ")", ")", "\n", "}", "\n", "return", "net", ".", "JoinHostPort", "(", "a", ".", "FQDN", ",", "strconv", ".", "Itoa", "(", "a", ".", "Port", ")", ")", "\n", "}" ]
// Address returns a string suitable to dial; prefer returning IP-based // address, fallback to FQDN
[ "Address", "returns", "a", "string", "suitable", "to", "dial", ";", "prefer", "returning", "IP", "-", "based", "address", "fallback", "to", "FQDN" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L60-L65
train
armon/go-socks5
request.go
NewRequest
func NewRequest(bufConn io.Reader) (*Request, error) { // Read the version byte header := []byte{0, 0, 0} if _, err := io.ReadAtLeast(bufConn, header, 3); err != nil { return nil, fmt.Errorf("Failed to get command version: %v", err) } // Ensure we are compatible if header[0] != socks5Version { return nil, fmt.Errorf("Unsupported command version: %v", header[0]) } // Read in the destination address dest, err := readAddrSpec(bufConn) if err != nil { return nil, err } request := &Request{ Version: socks5Version, Command: header[1], DestAddr: dest, bufConn: bufConn, } return request, nil }
go
func NewRequest(bufConn io.Reader) (*Request, error) { // Read the version byte header := []byte{0, 0, 0} if _, err := io.ReadAtLeast(bufConn, header, 3); err != nil { return nil, fmt.Errorf("Failed to get command version: %v", err) } // Ensure we are compatible if header[0] != socks5Version { return nil, fmt.Errorf("Unsupported command version: %v", header[0]) } // Read in the destination address dest, err := readAddrSpec(bufConn) if err != nil { return nil, err } request := &Request{ Version: socks5Version, Command: header[1], DestAddr: dest, bufConn: bufConn, } return request, nil }
[ "func", "NewRequest", "(", "bufConn", "io", ".", "Reader", ")", "(", "*", "Request", ",", "error", ")", "{", "// Read the version byte", "header", ":=", "[", "]", "byte", "{", "0", ",", "0", ",", "0", "}", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadAtLeast", "(", "bufConn", ",", "header", ",", "3", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Ensure we are compatible", "if", "header", "[", "0", "]", "!=", "socks5Version", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "header", "[", "0", "]", ")", "\n", "}", "\n\n", "// Read in the destination address", "dest", ",", "err", ":=", "readAddrSpec", "(", "bufConn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "request", ":=", "&", "Request", "{", "Version", ":", "socks5Version", ",", "Command", ":", "header", "[", "1", "]", ",", "DestAddr", ":", "dest", ",", "bufConn", ":", "bufConn", ",", "}", "\n\n", "return", "request", ",", "nil", "\n", "}" ]
// NewRequest creates a new Request from the tcp connection
[ "NewRequest", "creates", "a", "new", "Request", "from", "the", "tcp", "connection" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L90-L116
train
armon/go-socks5
request.go
handleRequest
func (s *Server) handleRequest(req *Request, conn conn) error { ctx := context.Background() // Resolve the address if we have a FQDN dest := req.DestAddr if dest.FQDN != "" { ctx_, addr, err := s.config.Resolver.Resolve(ctx, dest.FQDN) if err != nil { if err := sendReply(conn, hostUnreachable, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Failed to resolve destination '%v': %v", dest.FQDN, err) } ctx = ctx_ dest.IP = addr } // Apply any address rewrites req.realDestAddr = req.DestAddr if s.config.Rewriter != nil { ctx, req.realDestAddr = s.config.Rewriter.Rewrite(ctx, req) } // Switch on the command switch req.Command { case ConnectCommand: return s.handleConnect(ctx, conn, req) case BindCommand: return s.handleBind(ctx, conn, req) case AssociateCommand: return s.handleAssociate(ctx, conn, req) default: if err := sendReply(conn, commandNotSupported, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Unsupported command: %v", req.Command) } }
go
func (s *Server) handleRequest(req *Request, conn conn) error { ctx := context.Background() // Resolve the address if we have a FQDN dest := req.DestAddr if dest.FQDN != "" { ctx_, addr, err := s.config.Resolver.Resolve(ctx, dest.FQDN) if err != nil { if err := sendReply(conn, hostUnreachable, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Failed to resolve destination '%v': %v", dest.FQDN, err) } ctx = ctx_ dest.IP = addr } // Apply any address rewrites req.realDestAddr = req.DestAddr if s.config.Rewriter != nil { ctx, req.realDestAddr = s.config.Rewriter.Rewrite(ctx, req) } // Switch on the command switch req.Command { case ConnectCommand: return s.handleConnect(ctx, conn, req) case BindCommand: return s.handleBind(ctx, conn, req) case AssociateCommand: return s.handleAssociate(ctx, conn, req) default: if err := sendReply(conn, commandNotSupported, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Unsupported command: %v", req.Command) } }
[ "func", "(", "s", "*", "Server", ")", "handleRequest", "(", "req", "*", "Request", ",", "conn", "conn", ")", "error", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n\n", "// Resolve the address if we have a FQDN", "dest", ":=", "req", ".", "DestAddr", "\n", "if", "dest", ".", "FQDN", "!=", "\"", "\"", "{", "ctx_", ",", "addr", ",", "err", ":=", "s", ".", "config", ".", "Resolver", ".", "Resolve", "(", "ctx", ",", "dest", ".", "FQDN", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", ":=", "sendReply", "(", "conn", ",", "hostUnreachable", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dest", ".", "FQDN", ",", "err", ")", "\n", "}", "\n", "ctx", "=", "ctx_", "\n", "dest", ".", "IP", "=", "addr", "\n", "}", "\n\n", "// Apply any address rewrites", "req", ".", "realDestAddr", "=", "req", ".", "DestAddr", "\n", "if", "s", ".", "config", ".", "Rewriter", "!=", "nil", "{", "ctx", ",", "req", ".", "realDestAddr", "=", "s", ".", "config", ".", "Rewriter", ".", "Rewrite", "(", "ctx", ",", "req", ")", "\n", "}", "\n\n", "// Switch on the command", "switch", "req", ".", "Command", "{", "case", "ConnectCommand", ":", "return", "s", ".", "handleConnect", "(", "ctx", ",", "conn", ",", "req", ")", "\n", "case", "BindCommand", ":", "return", "s", ".", "handleBind", "(", "ctx", ",", "conn", ",", "req", ")", "\n", "case", "AssociateCommand", ":", "return", "s", ".", "handleAssociate", "(", "ctx", ",", "conn", ",", "req", ")", "\n", "default", ":", "if", "err", ":=", "sendReply", "(", "conn", ",", "commandNotSupported", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "req", ".", "Command", ")", "\n", "}", "\n", "}" ]
// handleRequest is used for request processing after authentication
[ "handleRequest", "is", "used", "for", "request", "processing", "after", "authentication" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L119-L156
train
armon/go-socks5
request.go
handleConnect
func (s *Server) handleConnect(ctx context.Context, conn conn, req *Request) error { // Check if this is allowed if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok { if err := sendReply(conn, ruleFailure, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Connect to %v blocked by rules", req.DestAddr) } else { ctx = ctx_ } // Attempt to connect dial := s.config.Dial if dial == nil { dial = func(ctx context.Context, net_, addr string) (net.Conn, error) { return net.Dial(net_, addr) } } target, err := dial(ctx, "tcp", req.realDestAddr.Address()) if err != nil { msg := err.Error() resp := hostUnreachable if strings.Contains(msg, "refused") { resp = connectionRefused } else if strings.Contains(msg, "network is unreachable") { resp = networkUnreachable } if err := sendReply(conn, resp, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Connect to %v failed: %v", req.DestAddr, err) } defer target.Close() // Send success local := target.LocalAddr().(*net.TCPAddr) bind := AddrSpec{IP: local.IP, Port: local.Port} if err := sendReply(conn, successReply, &bind); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } // Start proxying errCh := make(chan error, 2) go proxy(target, req.bufConn, errCh) go proxy(conn, target, errCh) // Wait for i := 0; i < 2; i++ { e := <-errCh if e != nil { // return from this function closes target (and conn). return e } } return nil }
go
func (s *Server) handleConnect(ctx context.Context, conn conn, req *Request) error { // Check if this is allowed if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok { if err := sendReply(conn, ruleFailure, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Connect to %v blocked by rules", req.DestAddr) } else { ctx = ctx_ } // Attempt to connect dial := s.config.Dial if dial == nil { dial = func(ctx context.Context, net_, addr string) (net.Conn, error) { return net.Dial(net_, addr) } } target, err := dial(ctx, "tcp", req.realDestAddr.Address()) if err != nil { msg := err.Error() resp := hostUnreachable if strings.Contains(msg, "refused") { resp = connectionRefused } else if strings.Contains(msg, "network is unreachable") { resp = networkUnreachable } if err := sendReply(conn, resp, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Connect to %v failed: %v", req.DestAddr, err) } defer target.Close() // Send success local := target.LocalAddr().(*net.TCPAddr) bind := AddrSpec{IP: local.IP, Port: local.Port} if err := sendReply(conn, successReply, &bind); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } // Start proxying errCh := make(chan error, 2) go proxy(target, req.bufConn, errCh) go proxy(conn, target, errCh) // Wait for i := 0; i < 2; i++ { e := <-errCh if e != nil { // return from this function closes target (and conn). return e } } return nil }
[ "func", "(", "s", "*", "Server", ")", "handleConnect", "(", "ctx", "context", ".", "Context", ",", "conn", "conn", ",", "req", "*", "Request", ")", "error", "{", "// Check if this is allowed", "if", "ctx_", ",", "ok", ":=", "s", ".", "config", ".", "Rules", ".", "Allow", "(", "ctx", ",", "req", ")", ";", "!", "ok", "{", "if", "err", ":=", "sendReply", "(", "conn", ",", "ruleFailure", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "req", ".", "DestAddr", ")", "\n", "}", "else", "{", "ctx", "=", "ctx_", "\n", "}", "\n\n", "// Attempt to connect", "dial", ":=", "s", ".", "config", ".", "Dial", "\n", "if", "dial", "==", "nil", "{", "dial", "=", "func", "(", "ctx", "context", ".", "Context", ",", "net_", ",", "addr", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "net", ".", "Dial", "(", "net_", ",", "addr", ")", "\n", "}", "\n", "}", "\n", "target", ",", "err", ":=", "dial", "(", "ctx", ",", "\"", "\"", ",", "req", ".", "realDestAddr", ".", "Address", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "msg", ":=", "err", ".", "Error", "(", ")", "\n", "resp", ":=", "hostUnreachable", "\n", "if", "strings", ".", "Contains", "(", "msg", ",", "\"", "\"", ")", "{", "resp", "=", "connectionRefused", "\n", "}", "else", "if", "strings", ".", "Contains", "(", "msg", ",", "\"", "\"", ")", "{", "resp", "=", "networkUnreachable", "\n", "}", "\n", "if", "err", ":=", "sendReply", "(", "conn", ",", "resp", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "req", ".", "DestAddr", ",", "err", ")", "\n", "}", "\n", "defer", "target", ".", "Close", "(", ")", "\n\n", "// Send success", "local", ":=", "target", ".", "LocalAddr", "(", ")", ".", "(", "*", "net", ".", "TCPAddr", ")", "\n", "bind", ":=", "AddrSpec", "{", "IP", ":", "local", ".", "IP", ",", "Port", ":", "local", ".", "Port", "}", "\n", "if", "err", ":=", "sendReply", "(", "conn", ",", "successReply", ",", "&", "bind", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Start proxying", "errCh", ":=", "make", "(", "chan", "error", ",", "2", ")", "\n", "go", "proxy", "(", "target", ",", "req", ".", "bufConn", ",", "errCh", ")", "\n", "go", "proxy", "(", "conn", ",", "target", ",", "errCh", ")", "\n\n", "// Wait", "for", "i", ":=", "0", ";", "i", "<", "2", ";", "i", "++", "{", "e", ":=", "<-", "errCh", "\n", "if", "e", "!=", "nil", "{", "// return from this function closes target (and conn).", "return", "e", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// handleConnect is used to handle a connect command
[ "handleConnect", "is", "used", "to", "handle", "a", "connect", "command" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L159-L214
train
armon/go-socks5
request.go
handleBind
func (s *Server) handleBind(ctx context.Context, conn conn, req *Request) error { // Check if this is allowed if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok { if err := sendReply(conn, ruleFailure, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Bind to %v blocked by rules", req.DestAddr) } else { ctx = ctx_ } // TODO: Support bind if err := sendReply(conn, commandNotSupported, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return nil }
go
func (s *Server) handleBind(ctx context.Context, conn conn, req *Request) error { // Check if this is allowed if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok { if err := sendReply(conn, ruleFailure, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return fmt.Errorf("Bind to %v blocked by rules", req.DestAddr) } else { ctx = ctx_ } // TODO: Support bind if err := sendReply(conn, commandNotSupported, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } return nil }
[ "func", "(", "s", "*", "Server", ")", "handleBind", "(", "ctx", "context", ".", "Context", ",", "conn", "conn", ",", "req", "*", "Request", ")", "error", "{", "// Check if this is allowed", "if", "ctx_", ",", "ok", ":=", "s", ".", "config", ".", "Rules", ".", "Allow", "(", "ctx", ",", "req", ")", ";", "!", "ok", "{", "if", "err", ":=", "sendReply", "(", "conn", ",", "ruleFailure", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "req", ".", "DestAddr", ")", "\n", "}", "else", "{", "ctx", "=", "ctx_", "\n", "}", "\n\n", "// TODO: Support bind", "if", "err", ":=", "sendReply", "(", "conn", ",", "commandNotSupported", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// handleBind is used to handle a connect command
[ "handleBind", "is", "used", "to", "handle", "a", "connect", "command" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L217-L233
train
armon/go-socks5
request.go
readAddrSpec
func readAddrSpec(r io.Reader) (*AddrSpec, error) { d := &AddrSpec{} // Get the address type addrType := []byte{0} if _, err := r.Read(addrType); err != nil { return nil, err } // Handle on a per type basis switch addrType[0] { case ipv4Address: addr := make([]byte, 4) if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil { return nil, err } d.IP = net.IP(addr) case ipv6Address: addr := make([]byte, 16) if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil { return nil, err } d.IP = net.IP(addr) case fqdnAddress: if _, err := r.Read(addrType); err != nil { return nil, err } addrLen := int(addrType[0]) fqdn := make([]byte, addrLen) if _, err := io.ReadAtLeast(r, fqdn, addrLen); err != nil { return nil, err } d.FQDN = string(fqdn) default: return nil, unrecognizedAddrType } // Read the port port := []byte{0, 0} if _, err := io.ReadAtLeast(r, port, 2); err != nil { return nil, err } d.Port = (int(port[0]) << 8) | int(port[1]) return d, nil }
go
func readAddrSpec(r io.Reader) (*AddrSpec, error) { d := &AddrSpec{} // Get the address type addrType := []byte{0} if _, err := r.Read(addrType); err != nil { return nil, err } // Handle on a per type basis switch addrType[0] { case ipv4Address: addr := make([]byte, 4) if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil { return nil, err } d.IP = net.IP(addr) case ipv6Address: addr := make([]byte, 16) if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil { return nil, err } d.IP = net.IP(addr) case fqdnAddress: if _, err := r.Read(addrType); err != nil { return nil, err } addrLen := int(addrType[0]) fqdn := make([]byte, addrLen) if _, err := io.ReadAtLeast(r, fqdn, addrLen); err != nil { return nil, err } d.FQDN = string(fqdn) default: return nil, unrecognizedAddrType } // Read the port port := []byte{0, 0} if _, err := io.ReadAtLeast(r, port, 2); err != nil { return nil, err } d.Port = (int(port[0]) << 8) | int(port[1]) return d, nil }
[ "func", "readAddrSpec", "(", "r", "io", ".", "Reader", ")", "(", "*", "AddrSpec", ",", "error", ")", "{", "d", ":=", "&", "AddrSpec", "{", "}", "\n\n", "// Get the address type", "addrType", ":=", "[", "]", "byte", "{", "0", "}", "\n", "if", "_", ",", "err", ":=", "r", ".", "Read", "(", "addrType", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Handle on a per type basis", "switch", "addrType", "[", "0", "]", "{", "case", "ipv4Address", ":", "addr", ":=", "make", "(", "[", "]", "byte", ",", "4", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadAtLeast", "(", "r", ",", "addr", ",", "len", "(", "addr", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "d", ".", "IP", "=", "net", ".", "IP", "(", "addr", ")", "\n\n", "case", "ipv6Address", ":", "addr", ":=", "make", "(", "[", "]", "byte", ",", "16", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadAtLeast", "(", "r", ",", "addr", ",", "len", "(", "addr", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "d", ".", "IP", "=", "net", ".", "IP", "(", "addr", ")", "\n\n", "case", "fqdnAddress", ":", "if", "_", ",", "err", ":=", "r", ".", "Read", "(", "addrType", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "addrLen", ":=", "int", "(", "addrType", "[", "0", "]", ")", "\n", "fqdn", ":=", "make", "(", "[", "]", "byte", ",", "addrLen", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadAtLeast", "(", "r", ",", "fqdn", ",", "addrLen", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "d", ".", "FQDN", "=", "string", "(", "fqdn", ")", "\n\n", "default", ":", "return", "nil", ",", "unrecognizedAddrType", "\n", "}", "\n\n", "// Read the port", "port", ":=", "[", "]", "byte", "{", "0", ",", "0", "}", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadAtLeast", "(", "r", ",", "port", ",", "2", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "d", ".", "Port", "=", "(", "int", "(", "port", "[", "0", "]", ")", "<<", "8", ")", "|", "int", "(", "port", "[", "1", "]", ")", "\n\n", "return", "d", ",", "nil", "\n", "}" ]
// readAddrSpec is used to read AddrSpec. // Expects an address type byte, follwed by the address and port
[ "readAddrSpec", "is", "used", "to", "read", "AddrSpec", ".", "Expects", "an", "address", "type", "byte", "follwed", "by", "the", "address", "and", "port" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L256-L304
train
armon/go-socks5
request.go
sendReply
func sendReply(w io.Writer, resp uint8, addr *AddrSpec) error { // Format the address var addrType uint8 var addrBody []byte var addrPort uint16 switch { case addr == nil: addrType = ipv4Address addrBody = []byte{0, 0, 0, 0} addrPort = 0 case addr.FQDN != "": addrType = fqdnAddress addrBody = append([]byte{byte(len(addr.FQDN))}, addr.FQDN...) addrPort = uint16(addr.Port) case addr.IP.To4() != nil: addrType = ipv4Address addrBody = []byte(addr.IP.To4()) addrPort = uint16(addr.Port) case addr.IP.To16() != nil: addrType = ipv6Address addrBody = []byte(addr.IP.To16()) addrPort = uint16(addr.Port) default: return fmt.Errorf("Failed to format address: %v", addr) } // Format the message msg := make([]byte, 6+len(addrBody)) msg[0] = socks5Version msg[1] = resp msg[2] = 0 // Reserved msg[3] = addrType copy(msg[4:], addrBody) msg[4+len(addrBody)] = byte(addrPort >> 8) msg[4+len(addrBody)+1] = byte(addrPort & 0xff) // Send the message _, err := w.Write(msg) return err }
go
func sendReply(w io.Writer, resp uint8, addr *AddrSpec) error { // Format the address var addrType uint8 var addrBody []byte var addrPort uint16 switch { case addr == nil: addrType = ipv4Address addrBody = []byte{0, 0, 0, 0} addrPort = 0 case addr.FQDN != "": addrType = fqdnAddress addrBody = append([]byte{byte(len(addr.FQDN))}, addr.FQDN...) addrPort = uint16(addr.Port) case addr.IP.To4() != nil: addrType = ipv4Address addrBody = []byte(addr.IP.To4()) addrPort = uint16(addr.Port) case addr.IP.To16() != nil: addrType = ipv6Address addrBody = []byte(addr.IP.To16()) addrPort = uint16(addr.Port) default: return fmt.Errorf("Failed to format address: %v", addr) } // Format the message msg := make([]byte, 6+len(addrBody)) msg[0] = socks5Version msg[1] = resp msg[2] = 0 // Reserved msg[3] = addrType copy(msg[4:], addrBody) msg[4+len(addrBody)] = byte(addrPort >> 8) msg[4+len(addrBody)+1] = byte(addrPort & 0xff) // Send the message _, err := w.Write(msg) return err }
[ "func", "sendReply", "(", "w", "io", ".", "Writer", ",", "resp", "uint8", ",", "addr", "*", "AddrSpec", ")", "error", "{", "// Format the address", "var", "addrType", "uint8", "\n", "var", "addrBody", "[", "]", "byte", "\n", "var", "addrPort", "uint16", "\n", "switch", "{", "case", "addr", "==", "nil", ":", "addrType", "=", "ipv4Address", "\n", "addrBody", "=", "[", "]", "byte", "{", "0", ",", "0", ",", "0", ",", "0", "}", "\n", "addrPort", "=", "0", "\n\n", "case", "addr", ".", "FQDN", "!=", "\"", "\"", ":", "addrType", "=", "fqdnAddress", "\n", "addrBody", "=", "append", "(", "[", "]", "byte", "{", "byte", "(", "len", "(", "addr", ".", "FQDN", ")", ")", "}", ",", "addr", ".", "FQDN", "...", ")", "\n", "addrPort", "=", "uint16", "(", "addr", ".", "Port", ")", "\n\n", "case", "addr", ".", "IP", ".", "To4", "(", ")", "!=", "nil", ":", "addrType", "=", "ipv4Address", "\n", "addrBody", "=", "[", "]", "byte", "(", "addr", ".", "IP", ".", "To4", "(", ")", ")", "\n", "addrPort", "=", "uint16", "(", "addr", ".", "Port", ")", "\n\n", "case", "addr", ".", "IP", ".", "To16", "(", ")", "!=", "nil", ":", "addrType", "=", "ipv6Address", "\n", "addrBody", "=", "[", "]", "byte", "(", "addr", ".", "IP", ".", "To16", "(", ")", ")", "\n", "addrPort", "=", "uint16", "(", "addr", ".", "Port", ")", "\n\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "addr", ")", "\n", "}", "\n\n", "// Format the message", "msg", ":=", "make", "(", "[", "]", "byte", ",", "6", "+", "len", "(", "addrBody", ")", ")", "\n", "msg", "[", "0", "]", "=", "socks5Version", "\n", "msg", "[", "1", "]", "=", "resp", "\n", "msg", "[", "2", "]", "=", "0", "// Reserved", "\n", "msg", "[", "3", "]", "=", "addrType", "\n", "copy", "(", "msg", "[", "4", ":", "]", ",", "addrBody", ")", "\n", "msg", "[", "4", "+", "len", "(", "addrBody", ")", "]", "=", "byte", "(", "addrPort", ">>", "8", ")", "\n", "msg", "[", "4", "+", "len", "(", "addrBody", ")", "+", "1", "]", "=", "byte", "(", "addrPort", "&", "0xff", ")", "\n\n", "// Send the message", "_", ",", "err", ":=", "w", ".", "Write", "(", "msg", ")", "\n", "return", "err", "\n", "}" ]
// sendReply is used to send a reply message
[ "sendReply", "is", "used", "to", "send", "a", "reply", "message" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L307-L350
train
armon/go-socks5
request.go
proxy
func proxy(dst io.Writer, src io.Reader, errCh chan error) { _, err := io.Copy(dst, src) if tcpConn, ok := dst.(closeWriter); ok { tcpConn.CloseWrite() } errCh <- err }
go
func proxy(dst io.Writer, src io.Reader, errCh chan error) { _, err := io.Copy(dst, src) if tcpConn, ok := dst.(closeWriter); ok { tcpConn.CloseWrite() } errCh <- err }
[ "func", "proxy", "(", "dst", "io", ".", "Writer", ",", "src", "io", ".", "Reader", ",", "errCh", "chan", "error", ")", "{", "_", ",", "err", ":=", "io", ".", "Copy", "(", "dst", ",", "src", ")", "\n", "if", "tcpConn", ",", "ok", ":=", "dst", ".", "(", "closeWriter", ")", ";", "ok", "{", "tcpConn", ".", "CloseWrite", "(", ")", "\n", "}", "\n", "errCh", "<-", "err", "\n", "}" ]
// proxy is used to suffle data from src to destination, and sends errors // down a dedicated channel
[ "proxy", "is", "used", "to", "suffle", "data", "from", "src", "to", "destination", "and", "sends", "errors", "down", "a", "dedicated", "channel" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/request.go#L358-L364
train
armon/go-socks5
socks5.go
New
func New(conf *Config) (*Server, error) { // Ensure we have at least one authentication method enabled if len(conf.AuthMethods) == 0 { if conf.Credentials != nil { conf.AuthMethods = []Authenticator{&UserPassAuthenticator{conf.Credentials}} } else { conf.AuthMethods = []Authenticator{&NoAuthAuthenticator{}} } } // Ensure we have a DNS resolver if conf.Resolver == nil { conf.Resolver = DNSResolver{} } // Ensure we have a rule set if conf.Rules == nil { conf.Rules = PermitAll() } // Ensure we have a log target if conf.Logger == nil { conf.Logger = log.New(os.Stdout, "", log.LstdFlags) } server := &Server{ config: conf, } server.authMethods = make(map[uint8]Authenticator) for _, a := range conf.AuthMethods { server.authMethods[a.GetCode()] = a } return server, nil }
go
func New(conf *Config) (*Server, error) { // Ensure we have at least one authentication method enabled if len(conf.AuthMethods) == 0 { if conf.Credentials != nil { conf.AuthMethods = []Authenticator{&UserPassAuthenticator{conf.Credentials}} } else { conf.AuthMethods = []Authenticator{&NoAuthAuthenticator{}} } } // Ensure we have a DNS resolver if conf.Resolver == nil { conf.Resolver = DNSResolver{} } // Ensure we have a rule set if conf.Rules == nil { conf.Rules = PermitAll() } // Ensure we have a log target if conf.Logger == nil { conf.Logger = log.New(os.Stdout, "", log.LstdFlags) } server := &Server{ config: conf, } server.authMethods = make(map[uint8]Authenticator) for _, a := range conf.AuthMethods { server.authMethods[a.GetCode()] = a } return server, nil }
[ "func", "New", "(", "conf", "*", "Config", ")", "(", "*", "Server", ",", "error", ")", "{", "// Ensure we have at least one authentication method enabled", "if", "len", "(", "conf", ".", "AuthMethods", ")", "==", "0", "{", "if", "conf", ".", "Credentials", "!=", "nil", "{", "conf", ".", "AuthMethods", "=", "[", "]", "Authenticator", "{", "&", "UserPassAuthenticator", "{", "conf", ".", "Credentials", "}", "}", "\n", "}", "else", "{", "conf", ".", "AuthMethods", "=", "[", "]", "Authenticator", "{", "&", "NoAuthAuthenticator", "{", "}", "}", "\n", "}", "\n", "}", "\n\n", "// Ensure we have a DNS resolver", "if", "conf", ".", "Resolver", "==", "nil", "{", "conf", ".", "Resolver", "=", "DNSResolver", "{", "}", "\n", "}", "\n\n", "// Ensure we have a rule set", "if", "conf", ".", "Rules", "==", "nil", "{", "conf", ".", "Rules", "=", "PermitAll", "(", ")", "\n", "}", "\n\n", "// Ensure we have a log target", "if", "conf", ".", "Logger", "==", "nil", "{", "conf", ".", "Logger", "=", "log", ".", "New", "(", "os", ".", "Stdout", ",", "\"", "\"", ",", "log", ".", "LstdFlags", ")", "\n", "}", "\n\n", "server", ":=", "&", "Server", "{", "config", ":", "conf", ",", "}", "\n\n", "server", ".", "authMethods", "=", "make", "(", "map", "[", "uint8", "]", "Authenticator", ")", "\n\n", "for", "_", ",", "a", ":=", "range", "conf", ".", "AuthMethods", "{", "server", ".", "authMethods", "[", "a", ".", "GetCode", "(", ")", "]", "=", "a", "\n", "}", "\n\n", "return", "server", ",", "nil", "\n", "}" ]
// New creates a new Server and potentially returns an error
[ "New", "creates", "a", "new", "Server", "and", "potentially", "returns", "an", "error" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/socks5.go#L61-L97
train
armon/go-socks5
socks5.go
ListenAndServe
func (s *Server) ListenAndServe(network, addr string) error { l, err := net.Listen(network, addr) if err != nil { return err } return s.Serve(l) }
go
func (s *Server) ListenAndServe(network, addr string) error { l, err := net.Listen(network, addr) if err != nil { return err } return s.Serve(l) }
[ "func", "(", "s", "*", "Server", ")", "ListenAndServe", "(", "network", ",", "addr", "string", ")", "error", "{", "l", ",", "err", ":=", "net", ".", "Listen", "(", "network", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "s", ".", "Serve", "(", "l", ")", "\n", "}" ]
// ListenAndServe is used to create a listener and serve on it
[ "ListenAndServe", "is", "used", "to", "create", "a", "listener", "and", "serve", "on", "it" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/socks5.go#L100-L106
train
armon/go-socks5
socks5.go
Serve
func (s *Server) Serve(l net.Listener) error { for { conn, err := l.Accept() if err != nil { return err } go s.ServeConn(conn) } return nil }
go
func (s *Server) Serve(l net.Listener) error { for { conn, err := l.Accept() if err != nil { return err } go s.ServeConn(conn) } return nil }
[ "func", "(", "s", "*", "Server", ")", "Serve", "(", "l", "net", ".", "Listener", ")", "error", "{", "for", "{", "conn", ",", "err", ":=", "l", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "go", "s", ".", "ServeConn", "(", "conn", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Serve is used to serve connections from a listener
[ "Serve", "is", "used", "to", "serve", "connections", "from", "a", "listener" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/socks5.go#L109-L118
train
armon/go-socks5
socks5.go
ServeConn
func (s *Server) ServeConn(conn net.Conn) error { defer conn.Close() bufConn := bufio.NewReader(conn) // Read the version byte version := []byte{0} if _, err := bufConn.Read(version); err != nil { s.config.Logger.Printf("[ERR] socks: Failed to get version byte: %v", err) return err } // Ensure we are compatible if version[0] != socks5Version { err := fmt.Errorf("Unsupported SOCKS version: %v", version) s.config.Logger.Printf("[ERR] socks: %v", err) return err } // Authenticate the connection authContext, err := s.authenticate(conn, bufConn) if err != nil { err = fmt.Errorf("Failed to authenticate: %v", err) s.config.Logger.Printf("[ERR] socks: %v", err) return err } request, err := NewRequest(bufConn) if err != nil { if err == unrecognizedAddrType { if err := sendReply(conn, addrTypeNotSupported, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } } return fmt.Errorf("Failed to read destination address: %v", err) } request.AuthContext = authContext if client, ok := conn.RemoteAddr().(*net.TCPAddr); ok { request.RemoteAddr = &AddrSpec{IP: client.IP, Port: client.Port} } // Process the client request if err := s.handleRequest(request, conn); err != nil { err = fmt.Errorf("Failed to handle request: %v", err) s.config.Logger.Printf("[ERR] socks: %v", err) return err } return nil }
go
func (s *Server) ServeConn(conn net.Conn) error { defer conn.Close() bufConn := bufio.NewReader(conn) // Read the version byte version := []byte{0} if _, err := bufConn.Read(version); err != nil { s.config.Logger.Printf("[ERR] socks: Failed to get version byte: %v", err) return err } // Ensure we are compatible if version[0] != socks5Version { err := fmt.Errorf("Unsupported SOCKS version: %v", version) s.config.Logger.Printf("[ERR] socks: %v", err) return err } // Authenticate the connection authContext, err := s.authenticate(conn, bufConn) if err != nil { err = fmt.Errorf("Failed to authenticate: %v", err) s.config.Logger.Printf("[ERR] socks: %v", err) return err } request, err := NewRequest(bufConn) if err != nil { if err == unrecognizedAddrType { if err := sendReply(conn, addrTypeNotSupported, nil); err != nil { return fmt.Errorf("Failed to send reply: %v", err) } } return fmt.Errorf("Failed to read destination address: %v", err) } request.AuthContext = authContext if client, ok := conn.RemoteAddr().(*net.TCPAddr); ok { request.RemoteAddr = &AddrSpec{IP: client.IP, Port: client.Port} } // Process the client request if err := s.handleRequest(request, conn); err != nil { err = fmt.Errorf("Failed to handle request: %v", err) s.config.Logger.Printf("[ERR] socks: %v", err) return err } return nil }
[ "func", "(", "s", "*", "Server", ")", "ServeConn", "(", "conn", "net", ".", "Conn", ")", "error", "{", "defer", "conn", ".", "Close", "(", ")", "\n", "bufConn", ":=", "bufio", ".", "NewReader", "(", "conn", ")", "\n\n", "// Read the version byte", "version", ":=", "[", "]", "byte", "{", "0", "}", "\n", "if", "_", ",", "err", ":=", "bufConn", ".", "Read", "(", "version", ")", ";", "err", "!=", "nil", "{", "s", ".", "config", ".", "Logger", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "// Ensure we are compatible", "if", "version", "[", "0", "]", "!=", "socks5Version", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "version", ")", "\n", "s", ".", "config", ".", "Logger", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "// Authenticate the connection", "authContext", ",", "err", ":=", "s", ".", "authenticate", "(", "conn", ",", "bufConn", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "s", ".", "config", ".", "Logger", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "request", ",", "err", ":=", "NewRequest", "(", "bufConn", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "unrecognizedAddrType", "{", "if", "err", ":=", "sendReply", "(", "conn", ",", "addrTypeNotSupported", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "request", ".", "AuthContext", "=", "authContext", "\n", "if", "client", ",", "ok", ":=", "conn", ".", "RemoteAddr", "(", ")", ".", "(", "*", "net", ".", "TCPAddr", ")", ";", "ok", "{", "request", ".", "RemoteAddr", "=", "&", "AddrSpec", "{", "IP", ":", "client", ".", "IP", ",", "Port", ":", "client", ".", "Port", "}", "\n", "}", "\n\n", "// Process the client request", "if", "err", ":=", "s", ".", "handleRequest", "(", "request", ",", "conn", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "s", ".", "config", ".", "Logger", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ServeConn is used to serve a single connection.
[ "ServeConn", "is", "used", "to", "serve", "a", "single", "connection", "." ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/socks5.go#L121-L169
train
armon/go-socks5
auth.go
authenticate
func (s *Server) authenticate(conn io.Writer, bufConn io.Reader) (*AuthContext, error) { // Get the methods methods, err := readMethods(bufConn) if err != nil { return nil, fmt.Errorf("Failed to get auth methods: %v", err) } // Select a usable method for _, method := range methods { cator, found := s.authMethods[method] if found { return cator.Authenticate(bufConn, conn) } } // No usable method found return nil, noAcceptableAuth(conn) }
go
func (s *Server) authenticate(conn io.Writer, bufConn io.Reader) (*AuthContext, error) { // Get the methods methods, err := readMethods(bufConn) if err != nil { return nil, fmt.Errorf("Failed to get auth methods: %v", err) } // Select a usable method for _, method := range methods { cator, found := s.authMethods[method] if found { return cator.Authenticate(bufConn, conn) } } // No usable method found return nil, noAcceptableAuth(conn) }
[ "func", "(", "s", "*", "Server", ")", "authenticate", "(", "conn", "io", ".", "Writer", ",", "bufConn", "io", ".", "Reader", ")", "(", "*", "AuthContext", ",", "error", ")", "{", "// Get the methods", "methods", ",", "err", ":=", "readMethods", "(", "bufConn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Select a usable method", "for", "_", ",", "method", ":=", "range", "methods", "{", "cator", ",", "found", ":=", "s", ".", "authMethods", "[", "method", "]", "\n", "if", "found", "{", "return", "cator", ".", "Authenticate", "(", "bufConn", ",", "conn", ")", "\n", "}", "\n", "}", "\n\n", "// No usable method found", "return", "nil", ",", "noAcceptableAuth", "(", "conn", ")", "\n", "}" ]
// authenticate is used to handle connection authentication
[ "authenticate", "is", "used", "to", "handle", "connection", "authentication" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/auth.go#L113-L130
train
armon/go-socks5
auth.go
noAcceptableAuth
func noAcceptableAuth(conn io.Writer) error { conn.Write([]byte{socks5Version, noAcceptable}) return NoSupportedAuth }
go
func noAcceptableAuth(conn io.Writer) error { conn.Write([]byte{socks5Version, noAcceptable}) return NoSupportedAuth }
[ "func", "noAcceptableAuth", "(", "conn", "io", ".", "Writer", ")", "error", "{", "conn", ".", "Write", "(", "[", "]", "byte", "{", "socks5Version", ",", "noAcceptable", "}", ")", "\n", "return", "NoSupportedAuth", "\n", "}" ]
// noAcceptableAuth is used to handle when we have no eligible // authentication mechanism
[ "noAcceptableAuth", "is", "used", "to", "handle", "when", "we", "have", "no", "eligible", "authentication", "mechanism" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/auth.go#L134-L137
train
armon/go-socks5
auth.go
readMethods
func readMethods(r io.Reader) ([]byte, error) { header := []byte{0} if _, err := r.Read(header); err != nil { return nil, err } numMethods := int(header[0]) methods := make([]byte, numMethods) _, err := io.ReadAtLeast(r, methods, numMethods) return methods, err }
go
func readMethods(r io.Reader) ([]byte, error) { header := []byte{0} if _, err := r.Read(header); err != nil { return nil, err } numMethods := int(header[0]) methods := make([]byte, numMethods) _, err := io.ReadAtLeast(r, methods, numMethods) return methods, err }
[ "func", "readMethods", "(", "r", "io", ".", "Reader", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "header", ":=", "[", "]", "byte", "{", "0", "}", "\n", "if", "_", ",", "err", ":=", "r", ".", "Read", "(", "header", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "numMethods", ":=", "int", "(", "header", "[", "0", "]", ")", "\n", "methods", ":=", "make", "(", "[", "]", "byte", ",", "numMethods", ")", "\n", "_", ",", "err", ":=", "io", ".", "ReadAtLeast", "(", "r", ",", "methods", ",", "numMethods", ")", "\n", "return", "methods", ",", "err", "\n", "}" ]
// readMethods is used to read the number of methods // and proceeding auth methods
[ "readMethods", "is", "used", "to", "read", "the", "number", "of", "methods", "and", "proceeding", "auth", "methods" ]
e75332964ef517daa070d7c38a9466a0d687e0a5
https://github.com/armon/go-socks5/blob/e75332964ef517daa070d7c38a9466a0d687e0a5/auth.go#L141-L151
train
qor/qor-example
models/orders/order_item.go
ProductImageURL
func (item *OrderItem) ProductImageURL() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.MainImageURL() }
go
func (item *OrderItem) ProductImageURL() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.MainImageURL() }
[ "func", "(", "item", "*", "OrderItem", ")", "ProductImageURL", "(", ")", "string", "{", "item", ".", "loadSizeVariation", "(", ")", "\n", "return", "item", ".", "SizeVariation", ".", "ColorVariation", ".", "MainImageURL", "(", ")", "\n", "}" ]
// ProductImageURL get product image
[ "ProductImageURL", "get", "product", "image" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L34-L37
train
qor/qor-example
models/orders/order_item.go
SellingPrice
func (item *OrderItem) SellingPrice() float32 { if item.IsCart() { item.loadSizeVariation() return item.SizeVariation.ColorVariation.Product.Price } return item.Price }
go
func (item *OrderItem) SellingPrice() float32 { if item.IsCart() { item.loadSizeVariation() return item.SizeVariation.ColorVariation.Product.Price } return item.Price }
[ "func", "(", "item", "*", "OrderItem", ")", "SellingPrice", "(", ")", "float32", "{", "if", "item", ".", "IsCart", "(", ")", "{", "item", ".", "loadSizeVariation", "(", ")", "\n", "return", "item", ".", "SizeVariation", ".", "ColorVariation", ".", "Product", ".", "Price", "\n", "}", "\n", "return", "item", ".", "Price", "\n", "}" ]
// SellingPrice order item's selling price
[ "SellingPrice", "order", "item", "s", "selling", "price" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L40-L46
train
qor/qor-example
models/orders/order_item.go
ProductName
func (item *OrderItem) ProductName() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.Product.Name }
go
func (item *OrderItem) ProductName() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.Product.Name }
[ "func", "(", "item", "*", "OrderItem", ")", "ProductName", "(", ")", "string", "{", "item", ".", "loadSizeVariation", "(", ")", "\n", "return", "item", ".", "SizeVariation", ".", "ColorVariation", ".", "Product", ".", "Name", "\n", "}" ]
// ProductName order item's color name
[ "ProductName", "order", "item", "s", "color", "name" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L49-L52
train
qor/qor-example
models/orders/order_item.go
ColorName
func (item *OrderItem) ColorName() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.Color.Name }
go
func (item *OrderItem) ColorName() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.Color.Name }
[ "func", "(", "item", "*", "OrderItem", ")", "ColorName", "(", ")", "string", "{", "item", ".", "loadSizeVariation", "(", ")", "\n", "return", "item", ".", "SizeVariation", ".", "ColorVariation", ".", "Color", ".", "Name", "\n", "}" ]
// ColorName order item's color name
[ "ColorName", "order", "item", "s", "color", "name" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L55-L58
train
qor/qor-example
models/orders/order_item.go
SizeName
func (item *OrderItem) SizeName() string { item.loadSizeVariation() return item.SizeVariation.Size.Name }
go
func (item *OrderItem) SizeName() string { item.loadSizeVariation() return item.SizeVariation.Size.Name }
[ "func", "(", "item", "*", "OrderItem", ")", "SizeName", "(", ")", "string", "{", "item", ".", "loadSizeVariation", "(", ")", "\n", "return", "item", ".", "SizeVariation", ".", "Size", ".", "Name", "\n", "}" ]
// SizeName order item's size name
[ "SizeName", "order", "item", "s", "size", "name" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L61-L64
train
qor/qor-example
models/orders/order_item.go
ProductPath
func (item *OrderItem) ProductPath() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.ViewPath() }
go
func (item *OrderItem) ProductPath() string { item.loadSizeVariation() return item.SizeVariation.ColorVariation.ViewPath() }
[ "func", "(", "item", "*", "OrderItem", ")", "ProductPath", "(", ")", "string", "{", "item", ".", "loadSizeVariation", "(", ")", "\n", "return", "item", ".", "SizeVariation", ".", "ColorVariation", ".", "ViewPath", "(", ")", "\n", "}" ]
// ProductPath order item's product name
[ "ProductPath", "order", "item", "s", "product", "name" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L67-L70
train
qor/qor-example
models/orders/order_item.go
Amount
func (item OrderItem) Amount() float32 { amount := item.SellingPrice() * float32(item.Quantity) if item.DiscountRate > 0 && item.DiscountRate <= 100 { amount = amount * float32(100-item.DiscountRate) / 100 } return amount }
go
func (item OrderItem) Amount() float32 { amount := item.SellingPrice() * float32(item.Quantity) if item.DiscountRate > 0 && item.DiscountRate <= 100 { amount = amount * float32(100-item.DiscountRate) / 100 } return amount }
[ "func", "(", "item", "OrderItem", ")", "Amount", "(", ")", "float32", "{", "amount", ":=", "item", ".", "SellingPrice", "(", ")", "*", "float32", "(", "item", ".", "Quantity", ")", "\n", "if", "item", ".", "DiscountRate", ">", "0", "&&", "item", ".", "DiscountRate", "<=", "100", "{", "amount", "=", "amount", "*", "float32", "(", "100", "-", "item", ".", "DiscountRate", ")", "/", "100", "\n", "}", "\n", "return", "amount", "\n", "}" ]
// Amount order item's amount
[ "Amount", "order", "item", "s", "amount" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/orders/order_item.go#L73-L79
train
qor/qor-example
app/admin/dashboard.go
SetupDashboard
func SetupDashboard(Admin *admin.Admin) { // Add Dashboard Admin.AddMenu(&admin.Menu{Name: "Dashboard", Link: "/admin", Priority: 1}) Admin.GetRouter().Get("/reports", ReportsDataHandler) initFuncMap(Admin) }
go
func SetupDashboard(Admin *admin.Admin) { // Add Dashboard Admin.AddMenu(&admin.Menu{Name: "Dashboard", Link: "/admin", Priority: 1}) Admin.GetRouter().Get("/reports", ReportsDataHandler) initFuncMap(Admin) }
[ "func", "SetupDashboard", "(", "Admin", "*", "admin", ".", "Admin", ")", "{", "// Add Dashboard", "Admin", ".", "AddMenu", "(", "&", "admin", ".", "Menu", "{", "Name", ":", "\"", "\"", ",", "Link", ":", "\"", "\"", ",", "Priority", ":", "1", "}", ")", "\n\n", "Admin", ".", "GetRouter", "(", ")", ".", "Get", "(", "\"", "\"", ",", "ReportsDataHandler", ")", "\n", "initFuncMap", "(", "Admin", ")", "\n", "}" ]
// SetupDashboard setup dashboard
[ "SetupDashboard", "setup", "dashboard" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/admin/dashboard.go#L61-L67
train
qor/qor-example
app/api/api.go
New
func New(config *Config) *App { if config.Prefix == "" { config.Prefix = "/api" } return &App{Config: config} }
go
func New(config *Config) *App { if config.Prefix == "" { config.Prefix = "/api" } return &App{Config: config} }
[ "func", "New", "(", "config", "*", "Config", ")", "*", "App", "{", "if", "config", ".", "Prefix", "==", "\"", "\"", "{", "config", ".", "Prefix", "=", "\"", "\"", "\n", "}", "\n", "return", "&", "App", "{", "Config", ":", "config", "}", "\n", "}" ]
// New new home app
[ "New", "new", "home", "app" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/api/api.go#L14-L19
train
qor/qor-example
app/admin/seo.go
SetupSEO
func SetupSEO(Admin *admin.Admin) { seo.SEOCollection = qor_seo.New("Common SEO") seo.SEOCollection.RegisterGlobalVaribles(&seo.SEOGlobalSetting{SiteName: "Qor Shop"}) seo.SEOCollection.SettingResource = Admin.AddResource(&seo.MySEOSetting{}, &admin.Config{Invisible: true}) seo.SEOCollection.RegisterSEO(&qor_seo.SEO{ Name: "Default Page", }) seo.SEOCollection.RegisterSEO(&qor_seo.SEO{ Name: "Product Page", Varibles: []string{"Name", "Code", "CategoryName"}, Context: func(objects ...interface{}) map[string]string { product := objects[0].(products.Product) context := make(map[string]string) context["Name"] = product.Name context["Code"] = product.Code context["CategoryName"] = product.Category.Name return context }, }) seo.SEOCollection.RegisterSEO(&qor_seo.SEO{ Name: "Category Page", Varibles: []string{"Name", "Code"}, Context: func(objects ...interface{}) map[string]string { category := objects[0].(products.Category) context := make(map[string]string) context["Name"] = category.Name context["Code"] = category.Code return context }, }) Admin.AddResource(seo.SEOCollection, &admin.Config{Name: "SEO Setting", Menu: []string{"Site Management"}, Singleton: true, Priority: 2}) }
go
func SetupSEO(Admin *admin.Admin) { seo.SEOCollection = qor_seo.New("Common SEO") seo.SEOCollection.RegisterGlobalVaribles(&seo.SEOGlobalSetting{SiteName: "Qor Shop"}) seo.SEOCollection.SettingResource = Admin.AddResource(&seo.MySEOSetting{}, &admin.Config{Invisible: true}) seo.SEOCollection.RegisterSEO(&qor_seo.SEO{ Name: "Default Page", }) seo.SEOCollection.RegisterSEO(&qor_seo.SEO{ Name: "Product Page", Varibles: []string{"Name", "Code", "CategoryName"}, Context: func(objects ...interface{}) map[string]string { product := objects[0].(products.Product) context := make(map[string]string) context["Name"] = product.Name context["Code"] = product.Code context["CategoryName"] = product.Category.Name return context }, }) seo.SEOCollection.RegisterSEO(&qor_seo.SEO{ Name: "Category Page", Varibles: []string{"Name", "Code"}, Context: func(objects ...interface{}) map[string]string { category := objects[0].(products.Category) context := make(map[string]string) context["Name"] = category.Name context["Code"] = category.Code return context }, }) Admin.AddResource(seo.SEOCollection, &admin.Config{Name: "SEO Setting", Menu: []string{"Site Management"}, Singleton: true, Priority: 2}) }
[ "func", "SetupSEO", "(", "Admin", "*", "admin", ".", "Admin", ")", "{", "seo", ".", "SEOCollection", "=", "qor_seo", ".", "New", "(", "\"", "\"", ")", "\n", "seo", ".", "SEOCollection", ".", "RegisterGlobalVaribles", "(", "&", "seo", ".", "SEOGlobalSetting", "{", "SiteName", ":", "\"", "\"", "}", ")", "\n", "seo", ".", "SEOCollection", ".", "SettingResource", "=", "Admin", ".", "AddResource", "(", "&", "seo", ".", "MySEOSetting", "{", "}", ",", "&", "admin", ".", "Config", "{", "Invisible", ":", "true", "}", ")", "\n", "seo", ".", "SEOCollection", ".", "RegisterSEO", "(", "&", "qor_seo", ".", "SEO", "{", "Name", ":", "\"", "\"", ",", "}", ")", "\n", "seo", ".", "SEOCollection", ".", "RegisterSEO", "(", "&", "qor_seo", ".", "SEO", "{", "Name", ":", "\"", "\"", ",", "Varibles", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", "Context", ":", "func", "(", "objects", "...", "interface", "{", "}", ")", "map", "[", "string", "]", "string", "{", "product", ":=", "objects", "[", "0", "]", ".", "(", "products", ".", "Product", ")", "\n", "context", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "context", "[", "\"", "\"", "]", "=", "product", ".", "Name", "\n", "context", "[", "\"", "\"", "]", "=", "product", ".", "Code", "\n", "context", "[", "\"", "\"", "]", "=", "product", ".", "Category", ".", "Name", "\n", "return", "context", "\n", "}", ",", "}", ")", "\n", "seo", ".", "SEOCollection", ".", "RegisterSEO", "(", "&", "qor_seo", ".", "SEO", "{", "Name", ":", "\"", "\"", ",", "Varibles", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "Context", ":", "func", "(", "objects", "...", "interface", "{", "}", ")", "map", "[", "string", "]", "string", "{", "category", ":=", "objects", "[", "0", "]", ".", "(", "products", ".", "Category", ")", "\n", "context", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "context", "[", "\"", "\"", "]", "=", "category", ".", "Name", "\n", "context", "[", "\"", "\"", "]", "=", "category", ".", "Code", "\n", "return", "context", "\n", "}", ",", "}", ")", "\n", "Admin", ".", "AddResource", "(", "seo", ".", "SEOCollection", ",", "&", "admin", ".", "Config", "{", "Name", ":", "\"", "\"", ",", "Menu", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "Singleton", ":", "true", ",", "Priority", ":", "2", "}", ")", "\n", "}" ]
// SetupSEO add seo
[ "SetupSEO", "add", "seo" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/admin/seo.go#L11-L42
train
qor/qor-example
app/home/handlers.go
Index
func (ctrl Controller) Index(w http.ResponseWriter, req *http.Request) { ctrl.View.Execute("index", map[string]interface{}{}, req, w) }
go
func (ctrl Controller) Index(w http.ResponseWriter, req *http.Request) { ctrl.View.Execute("index", map[string]interface{}{}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Index", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "ctrl", ".", "View", ".", "Execute", "(", "\"", "\"", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "}", ",", "req", ",", "w", ")", "\n", "}" ]
// Index home index page
[ "Index", "home", "index", "page" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/home/handlers.go#L17-L19
train
qor/qor-example
app/home/handlers.go
SwitchLocale
func (ctrl Controller) SwitchLocale(w http.ResponseWriter, req *http.Request) { utils.SetCookie(http.Cookie{Name: "locale", Value: req.URL.Query().Get("locale")}, &qor.Context{Request: req, Writer: w}) http.Redirect(w, req, req.Referer(), http.StatusSeeOther) }
go
func (ctrl Controller) SwitchLocale(w http.ResponseWriter, req *http.Request) { utils.SetCookie(http.Cookie{Name: "locale", Value: req.URL.Query().Get("locale")}, &qor.Context{Request: req, Writer: w}) http.Redirect(w, req, req.Referer(), http.StatusSeeOther) }
[ "func", "(", "ctrl", "Controller", ")", "SwitchLocale", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "utils", ".", "SetCookie", "(", "http", ".", "Cookie", "{", "Name", ":", "\"", "\"", ",", "Value", ":", "req", ".", "URL", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "}", ",", "&", "qor", ".", "Context", "{", "Request", ":", "req", ",", "Writer", ":", "w", "}", ")", "\n", "http", ".", "Redirect", "(", "w", ",", "req", ",", "req", ".", "Referer", "(", ")", ",", "http", ".", "StatusSeeOther", ")", "\n", "}" ]
// SwitchLocale switch locale
[ "SwitchLocale", "switch", "locale" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/home/handlers.go#L22-L25
train
qor/qor-example
config/application/application.go
New
func New(cfg *Config) *Application { if cfg == nil { cfg = &Config{} } if cfg.Router == nil { cfg.Router = chi.NewRouter() } if cfg.AssetFS == nil { cfg.AssetFS = assetfs.AssetFS() } return &Application{ Config: cfg, } }
go
func New(cfg *Config) *Application { if cfg == nil { cfg = &Config{} } if cfg.Router == nil { cfg.Router = chi.NewRouter() } if cfg.AssetFS == nil { cfg.AssetFS = assetfs.AssetFS() } return &Application{ Config: cfg, } }
[ "func", "New", "(", "cfg", "*", "Config", ")", "*", "Application", "{", "if", "cfg", "==", "nil", "{", "cfg", "=", "&", "Config", "{", "}", "\n", "}", "\n\n", "if", "cfg", ".", "Router", "==", "nil", "{", "cfg", ".", "Router", "=", "chi", ".", "NewRouter", "(", ")", "\n", "}", "\n\n", "if", "cfg", ".", "AssetFS", "==", "nil", "{", "cfg", ".", "AssetFS", "=", "assetfs", ".", "AssetFS", "(", ")", "\n", "}", "\n\n", "return", "&", "Application", "{", "Config", ":", "cfg", ",", "}", "\n", "}" ]
// New new application
[ "New", "new", "application" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/config/application/application.go#L34-L50
train
qor/qor-example
app/products/handlers.go
Index
func (ctrl Controller) Index(w http.ResponseWriter, req *http.Request) { var ( Products []products.Product tx = utils.GetDB(req) ) tx.Preload("Category").Find(&Products) ctrl.View.Execute("index", map[string]interface{}{}, req, w) }
go
func (ctrl Controller) Index(w http.ResponseWriter, req *http.Request) { var ( Products []products.Product tx = utils.GetDB(req) ) tx.Preload("Category").Find(&Products) ctrl.View.Execute("index", map[string]interface{}{}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Index", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "var", "(", "Products", "[", "]", "products", ".", "Product", "\n", "tx", "=", "utils", ".", "GetDB", "(", "req", ")", "\n", ")", "\n\n", "tx", ".", "Preload", "(", "\"", "\"", ")", ".", "Find", "(", "&", "Products", ")", "\n\n", "ctrl", ".", "View", ".", "Execute", "(", "\"", "\"", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "}", ",", "req", ",", "w", ")", "\n", "}" ]
// Index products index page
[ "Index", "products", "index", "page" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/products/handlers.go#L18-L27
train
qor/qor-example
app/products/handlers.go
Show
func (ctrl Controller) Show(w http.ResponseWriter, req *http.Request) { var ( product products.Product colorVariation products.ColorVariation codes = strings.Split(utils.URLParam("code", req), "_") productCode = codes[0] colorCode string tx = utils.GetDB(req) ) if len(codes) > 1 { colorCode = codes[1] } if tx.Preload("Category").Where(&products.Product{Code: productCode}).First(&product).RecordNotFound() { http.Redirect(w, req, "/", http.StatusFound) } tx.Preload("Product").Preload("Color").Preload("SizeVariations.Size").Where(&products.ColorVariation{ProductID: product.ID, ColorCode: colorCode}).First(&colorVariation) ctrl.View.Execute("show", map[string]interface{}{"CurrentColorVariation": colorVariation}, req, w) }
go
func (ctrl Controller) Show(w http.ResponseWriter, req *http.Request) { var ( product products.Product colorVariation products.ColorVariation codes = strings.Split(utils.URLParam("code", req), "_") productCode = codes[0] colorCode string tx = utils.GetDB(req) ) if len(codes) > 1 { colorCode = codes[1] } if tx.Preload("Category").Where(&products.Product{Code: productCode}).First(&product).RecordNotFound() { http.Redirect(w, req, "/", http.StatusFound) } tx.Preload("Product").Preload("Color").Preload("SizeVariations.Size").Where(&products.ColorVariation{ProductID: product.ID, ColorCode: colorCode}).First(&colorVariation) ctrl.View.Execute("show", map[string]interface{}{"CurrentColorVariation": colorVariation}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Show", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "var", "(", "product", "products", ".", "Product", "\n", "colorVariation", "products", ".", "ColorVariation", "\n", "codes", "=", "strings", ".", "Split", "(", "utils", ".", "URLParam", "(", "\"", "\"", ",", "req", ")", ",", "\"", "\"", ")", "\n", "productCode", "=", "codes", "[", "0", "]", "\n", "colorCode", "string", "\n", "tx", "=", "utils", ".", "GetDB", "(", "req", ")", "\n", ")", "\n\n", "if", "len", "(", "codes", ")", ">", "1", "{", "colorCode", "=", "codes", "[", "1", "]", "\n", "}", "\n\n", "if", "tx", ".", "Preload", "(", "\"", "\"", ")", ".", "Where", "(", "&", "products", ".", "Product", "{", "Code", ":", "productCode", "}", ")", ".", "First", "(", "&", "product", ")", ".", "RecordNotFound", "(", ")", "{", "http", ".", "Redirect", "(", "w", ",", "req", ",", "\"", "\"", ",", "http", ".", "StatusFound", ")", "\n", "}", "\n\n", "tx", ".", "Preload", "(", "\"", "\"", ")", ".", "Preload", "(", "\"", "\"", ")", ".", "Preload", "(", "\"", "\"", ")", ".", "Where", "(", "&", "products", ".", "ColorVariation", "{", "ProductID", ":", "product", ".", "ID", ",", "ColorCode", ":", "colorCode", "}", ")", ".", "First", "(", "&", "colorVariation", ")", "\n\n", "ctrl", ".", "View", ".", "Execute", "(", "\"", "\"", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "colorVariation", "}", ",", "req", ",", "w", ")", "\n", "}" ]
// Show product show page
[ "Show", "product", "show", "page" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/products/handlers.go#L42-L63
train
qor/qor-example
app/products/handlers.go
Category
func (ctrl Controller) Category(w http.ResponseWriter, req *http.Request) { var ( category products.Category Products []products.Product tx = utils.GetDB(req) ) if tx.Where("code = ?", utils.URLParam("code", req)).First(&category).RecordNotFound() { http.Redirect(w, req, "/", http.StatusFound) } tx.Where(&products.Product{CategoryID: category.ID}).Preload("ColorVariations").Find(&Products) ctrl.View.Execute("category", map[string]interface{}{"CategoryName": category.Name, "Products": Products}, req, w) }
go
func (ctrl Controller) Category(w http.ResponseWriter, req *http.Request) { var ( category products.Category Products []products.Product tx = utils.GetDB(req) ) if tx.Where("code = ?", utils.URLParam("code", req)).First(&category).RecordNotFound() { http.Redirect(w, req, "/", http.StatusFound) } tx.Where(&products.Product{CategoryID: category.ID}).Preload("ColorVariations").Find(&Products) ctrl.View.Execute("category", map[string]interface{}{"CategoryName": category.Name, "Products": Products}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Category", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "var", "(", "category", "products", ".", "Category", "\n", "Products", "[", "]", "products", ".", "Product", "\n", "tx", "=", "utils", ".", "GetDB", "(", "req", ")", "\n", ")", "\n\n", "if", "tx", ".", "Where", "(", "\"", "\"", ",", "utils", ".", "URLParam", "(", "\"", "\"", ",", "req", ")", ")", ".", "First", "(", "&", "category", ")", ".", "RecordNotFound", "(", ")", "{", "http", ".", "Redirect", "(", "w", ",", "req", ",", "\"", "\"", ",", "http", ".", "StatusFound", ")", "\n", "}", "\n\n", "tx", ".", "Where", "(", "&", "products", ".", "Product", "{", "CategoryID", ":", "category", ".", "ID", "}", ")", ".", "Preload", "(", "\"", "\"", ")", ".", "Find", "(", "&", "Products", ")", "\n\n", "ctrl", ".", "View", ".", "Execute", "(", "\"", "\"", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "category", ".", "Name", ",", "\"", "\"", ":", "Products", "}", ",", "req", ",", "w", ")", "\n", "}" ]
// Category category show page
[ "Category", "category", "show", "page" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/products/handlers.go#L66-L80
train
qor/qor-example
app/orders/handlers.go
Cart
func (ctrl Controller) Cart(w http.ResponseWriter, req *http.Request) { order := getCurrentOrderWithItems(w, req) ctrl.View.Execute("cart", map[string]interface{}{"Order": order}, req, w) }
go
func (ctrl Controller) Cart(w http.ResponseWriter, req *http.Request) { order := getCurrentOrderWithItems(w, req) ctrl.View.Execute("cart", map[string]interface{}{"Order": order}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Cart", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "order", ":=", "getCurrentOrderWithItems", "(", "w", ",", "req", ")", "\n", "ctrl", ".", "View", ".", "Execute", "(", "\"", "\"", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "order", "}", ",", "req", ",", "w", ")", "\n", "}" ]
// Cart shopping cart
[ "Cart", "shopping", "cart" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/orders/handlers.go#L27-L30
train
qor/qor-example
app/orders/handlers.go
Checkout
func (ctrl Controller) Checkout(w http.ResponseWriter, req *http.Request) { hasAmazon := req.URL.Query().Get("access_token") order := getCurrentOrderWithItems(w, req) ctrl.View.Execute("checkout", map[string]interface{}{"Order": order, "HasAmazon": hasAmazon}, req, w) }
go
func (ctrl Controller) Checkout(w http.ResponseWriter, req *http.Request) { hasAmazon := req.URL.Query().Get("access_token") order := getCurrentOrderWithItems(w, req) ctrl.View.Execute("checkout", map[string]interface{}{"Order": order, "HasAmazon": hasAmazon}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Checkout", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "hasAmazon", ":=", "req", ".", "URL", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", "\n", "order", ":=", "getCurrentOrderWithItems", "(", "w", ",", "req", ")", "\n", "ctrl", ".", "View", ".", "Execute", "(", "\"", "\"", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "order", ",", "\"", "\"", ":", "hasAmazon", "}", ",", "req", ",", "w", ")", "\n", "}" ]
// Checkout checkout shopping cart
[ "Checkout", "checkout", "shopping", "cart" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/orders/handlers.go#L33-L37
train
qor/qor-example
app/orders/handlers.go
Complete
func (ctrl Controller) Complete(w http.ResponseWriter, req *http.Request) { req.ParseForm() order := getCurrentOrder(w, req) if order.AmazonOrderReferenceID = req.Form.Get("amazon_order_reference_id"); order.AmazonOrderReferenceID != "" { order.AmazonAddressAccessToken = req.Form.Get("amazon_address_access_token") tx := utils.GetDB(req) err := orders.OrderState.Trigger("checkout", order, tx, "") if err == nil { tx.Save(order) http.Redirect(w, req, "/cart/success", http.StatusFound) return } utils.AddFlashMessage(w, req, err.Error(), "error") } else { utils.AddFlashMessage(w, req, "Order Reference ID not Found", "error") } http.Redirect(w, req, "/cart", http.StatusFound) }
go
func (ctrl Controller) Complete(w http.ResponseWriter, req *http.Request) { req.ParseForm() order := getCurrentOrder(w, req) if order.AmazonOrderReferenceID = req.Form.Get("amazon_order_reference_id"); order.AmazonOrderReferenceID != "" { order.AmazonAddressAccessToken = req.Form.Get("amazon_address_access_token") tx := utils.GetDB(req) err := orders.OrderState.Trigger("checkout", order, tx, "") if err == nil { tx.Save(order) http.Redirect(w, req, "/cart/success", http.StatusFound) return } utils.AddFlashMessage(w, req, err.Error(), "error") } else { utils.AddFlashMessage(w, req, "Order Reference ID not Found", "error") } http.Redirect(w, req, "/cart", http.StatusFound) }
[ "func", "(", "ctrl", "Controller", ")", "Complete", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "req", ".", "ParseForm", "(", ")", "\n\n", "order", ":=", "getCurrentOrder", "(", "w", ",", "req", ")", "\n", "if", "order", ".", "AmazonOrderReferenceID", "=", "req", ".", "Form", ".", "Get", "(", "\"", "\"", ")", ";", "order", ".", "AmazonOrderReferenceID", "!=", "\"", "\"", "{", "order", ".", "AmazonAddressAccessToken", "=", "req", ".", "Form", ".", "Get", "(", "\"", "\"", ")", "\n", "tx", ":=", "utils", ".", "GetDB", "(", "req", ")", "\n", "err", ":=", "orders", ".", "OrderState", ".", "Trigger", "(", "\"", "\"", ",", "order", ",", "tx", ",", "\"", "\"", ")", "\n\n", "if", "err", "==", "nil", "{", "tx", ".", "Save", "(", "order", ")", "\n", "http", ".", "Redirect", "(", "w", ",", "req", ",", "\"", "\"", ",", "http", ".", "StatusFound", ")", "\n", "return", "\n", "}", "\n", "utils", ".", "AddFlashMessage", "(", "w", ",", "req", ",", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "\n", "}", "else", "{", "utils", ".", "AddFlashMessage", "(", "w", ",", "req", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "http", ".", "Redirect", "(", "w", ",", "req", ",", "\"", "\"", ",", "http", ".", "StatusFound", ")", "\n", "}" ]
// Complete complete shopping cart
[ "Complete", "complete", "shopping", "cart" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/orders/handlers.go#L40-L60
train
qor/qor-example
app/orders/handlers.go
CompleteCreditCard
func (ctrl Controller) CompleteCreditCard(w http.ResponseWriter, req *http.Request) { req.ParseForm() order := getCurrentOrder(w, req) expMonth, _ := strconv.Atoi(req.Form.Get("exp_month")) expYear, _ := strconv.Atoi(req.Form.Get("exp_year")) creditCard := gomerchant.CreditCard{ Name: req.Form.Get("name"), Number: req.Form.Get("creditcard"), CVC: req.Form.Get("cvv"), ExpYear: uint(expYear), ExpMonth: uint(expMonth), } if creditCard.ValidNumber() { // TODO integrate with https://github.com/qor/gomerchant to handle those information tx := utils.GetDB(req) err := orders.OrderState.Trigger("checkout", order, tx, "") if err == nil { tx.Save(order) http.Redirect(w, req, "/cart/success", http.StatusFound) return } } utils.AddFlashMessage(w, req, "Invalid Credit Card", "error") http.Redirect(w, req, "/cart", http.StatusFound) }
go
func (ctrl Controller) CompleteCreditCard(w http.ResponseWriter, req *http.Request) { req.ParseForm() order := getCurrentOrder(w, req) expMonth, _ := strconv.Atoi(req.Form.Get("exp_month")) expYear, _ := strconv.Atoi(req.Form.Get("exp_year")) creditCard := gomerchant.CreditCard{ Name: req.Form.Get("name"), Number: req.Form.Get("creditcard"), CVC: req.Form.Get("cvv"), ExpYear: uint(expYear), ExpMonth: uint(expMonth), } if creditCard.ValidNumber() { // TODO integrate with https://github.com/qor/gomerchant to handle those information tx := utils.GetDB(req) err := orders.OrderState.Trigger("checkout", order, tx, "") if err == nil { tx.Save(order) http.Redirect(w, req, "/cart/success", http.StatusFound) return } } utils.AddFlashMessage(w, req, "Invalid Credit Card", "error") http.Redirect(w, req, "/cart", http.StatusFound) }
[ "func", "(", "ctrl", "Controller", ")", "CompleteCreditCard", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "req", ".", "ParseForm", "(", ")", "\n\n", "order", ":=", "getCurrentOrder", "(", "w", ",", "req", ")", "\n\n", "expMonth", ",", "_", ":=", "strconv", ".", "Atoi", "(", "req", ".", "Form", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "expYear", ",", "_", ":=", "strconv", ".", "Atoi", "(", "req", ".", "Form", ".", "Get", "(", "\"", "\"", ")", ")", "\n\n", "creditCard", ":=", "gomerchant", ".", "CreditCard", "{", "Name", ":", "req", ".", "Form", ".", "Get", "(", "\"", "\"", ")", ",", "Number", ":", "req", ".", "Form", ".", "Get", "(", "\"", "\"", ")", ",", "CVC", ":", "req", ".", "Form", ".", "Get", "(", "\"", "\"", ")", ",", "ExpYear", ":", "uint", "(", "expYear", ")", ",", "ExpMonth", ":", "uint", "(", "expMonth", ")", ",", "}", "\n\n", "if", "creditCard", ".", "ValidNumber", "(", ")", "{", "// TODO integrate with https://github.com/qor/gomerchant to handle those information", "tx", ":=", "utils", ".", "GetDB", "(", "req", ")", "\n", "err", ":=", "orders", ".", "OrderState", ".", "Trigger", "(", "\"", "\"", ",", "order", ",", "tx", ",", "\"", "\"", ")", "\n\n", "if", "err", "==", "nil", "{", "tx", ".", "Save", "(", "order", ")", "\n", "http", ".", "Redirect", "(", "w", ",", "req", ",", "\"", "\"", ",", "http", ".", "StatusFound", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "utils", ".", "AddFlashMessage", "(", "w", ",", "req", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "http", ".", "Redirect", "(", "w", ",", "req", ",", "\"", "\"", ",", "http", ".", "StatusFound", ")", "\n", "}" ]
// CompleteCreditCard complete shopping cart with credit card
[ "CompleteCreditCard", "complete", "shopping", "cart", "with", "credit", "card" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/orders/handlers.go#L63-L93
train
qor/qor-example
app/orders/handlers.go
UpdateCart
func (ctrl Controller) UpdateCart(w http.ResponseWriter, req *http.Request) { var ( input updateCartInput tx = utils.GetDB(req) ) req.ParseForm() decoder.Decode(&input, req.PostForm) order := getCurrentOrder(w, req) if input.Quantity > 0 { tx.Where(&orders.OrderItem{OrderID: order.ID, SizeVariationID: input.SizeVariationID}). Assign(&orders.OrderItem{Quantity: input.Quantity}). FirstOrCreate(&orders.OrderItem{}) } else { tx.Where(&orders.OrderItem{OrderID: order.ID, SizeVariationID: input.SizeVariationID}). Delete(&orders.OrderItem{}) } responder.With("html", func() { http.Redirect(w, req, "/cart", http.StatusFound) }).With([]string{"json", "xml"}, func() { config.Render.JSON(w, http.StatusOK, map[string]string{"status": "ok"}) }).Respond(req) }
go
func (ctrl Controller) UpdateCart(w http.ResponseWriter, req *http.Request) { var ( input updateCartInput tx = utils.GetDB(req) ) req.ParseForm() decoder.Decode(&input, req.PostForm) order := getCurrentOrder(w, req) if input.Quantity > 0 { tx.Where(&orders.OrderItem{OrderID: order.ID, SizeVariationID: input.SizeVariationID}). Assign(&orders.OrderItem{Quantity: input.Quantity}). FirstOrCreate(&orders.OrderItem{}) } else { tx.Where(&orders.OrderItem{OrderID: order.ID, SizeVariationID: input.SizeVariationID}). Delete(&orders.OrderItem{}) } responder.With("html", func() { http.Redirect(w, req, "/cart", http.StatusFound) }).With([]string{"json", "xml"}, func() { config.Render.JSON(w, http.StatusOK, map[string]string{"status": "ok"}) }).Respond(req) }
[ "func", "(", "ctrl", "Controller", ")", "UpdateCart", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "var", "(", "input", "updateCartInput", "\n", "tx", "=", "utils", ".", "GetDB", "(", "req", ")", "\n", ")", "\n\n", "req", ".", "ParseForm", "(", ")", "\n", "decoder", ".", "Decode", "(", "&", "input", ",", "req", ".", "PostForm", ")", "\n\n", "order", ":=", "getCurrentOrder", "(", "w", ",", "req", ")", "\n\n", "if", "input", ".", "Quantity", ">", "0", "{", "tx", ".", "Where", "(", "&", "orders", ".", "OrderItem", "{", "OrderID", ":", "order", ".", "ID", ",", "SizeVariationID", ":", "input", ".", "SizeVariationID", "}", ")", ".", "Assign", "(", "&", "orders", ".", "OrderItem", "{", "Quantity", ":", "input", ".", "Quantity", "}", ")", ".", "FirstOrCreate", "(", "&", "orders", ".", "OrderItem", "{", "}", ")", "\n", "}", "else", "{", "tx", ".", "Where", "(", "&", "orders", ".", "OrderItem", "{", "OrderID", ":", "order", ".", "ID", ",", "SizeVariationID", ":", "input", ".", "SizeVariationID", "}", ")", ".", "Delete", "(", "&", "orders", ".", "OrderItem", "{", "}", ")", "\n", "}", "\n\n", "responder", ".", "With", "(", "\"", "\"", ",", "func", "(", ")", "{", "http", ".", "Redirect", "(", "w", ",", "req", ",", "\"", "\"", ",", "http", ".", "StatusFound", ")", "\n", "}", ")", ".", "With", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "func", "(", ")", "{", "config", ".", "Render", ".", "JSON", "(", "w", ",", "http", ".", "StatusOK", ",", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", "}", ")", "\n", "}", ")", ".", "Respond", "(", "req", ")", "\n", "}" ]
// UpdateCart update shopping cart
[ "UpdateCart", "update", "shopping", "cart" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/orders/handlers.go#L108-L133
train
qor/qor-example
app/orders/handlers.go
AmazonCallback
func (ctrl Controller) AmazonCallback(w http.ResponseWriter, req *http.Request) { ipn, ok := amazonpay.VerifyIPNRequest(req) fmt.Printf("%#v\n", ipn) fmt.Printf("%#v\n", ok) }
go
func (ctrl Controller) AmazonCallback(w http.ResponseWriter, req *http.Request) { ipn, ok := amazonpay.VerifyIPNRequest(req) fmt.Printf("%#v\n", ipn) fmt.Printf("%#v\n", ok) }
[ "func", "(", "ctrl", "Controller", ")", "AmazonCallback", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "ipn", ",", "ok", ":=", "amazonpay", ".", "VerifyIPNRequest", "(", "req", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "ipn", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "ok", ")", "\n", "}" ]
// AmazonCallback amazon callback
[ "AmazonCallback", "amazon", "callback" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/orders/handlers.go#L136-L140
train
qor/qor-example
models/products/product.go
ViewPath
func (colorVariation ColorVariation) ViewPath() string { defaultPath := "" var product Product if !db.DB.First(&product, "id = ?", colorVariation.ProductID).RecordNotFound() { defaultPath = fmt.Sprintf("/products/%s_%s", product.Code, colorVariation.ColorCode) } return defaultPath }
go
func (colorVariation ColorVariation) ViewPath() string { defaultPath := "" var product Product if !db.DB.First(&product, "id = ?", colorVariation.ProductID).RecordNotFound() { defaultPath = fmt.Sprintf("/products/%s_%s", product.Code, colorVariation.ColorCode) } return defaultPath }
[ "func", "(", "colorVariation", "ColorVariation", ")", "ViewPath", "(", ")", "string", "{", "defaultPath", ":=", "\"", "\"", "\n", "var", "product", "Product", "\n", "if", "!", "db", ".", "DB", ".", "First", "(", "&", "product", ",", "\"", "\"", ",", "colorVariation", ".", "ProductID", ")", ".", "RecordNotFound", "(", ")", "{", "defaultPath", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "product", ".", "Code", ",", "colorVariation", ".", "ColorCode", ")", "\n", "}", "\n", "return", "defaultPath", "\n", "}" ]
// ViewPath view path of color variation
[ "ViewPath", "view", "path", "of", "color", "variation" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/models/products/product.go#L200-L207
train
qor/qor-example
utils/funcmapmaker/funcmapmaker.go
GetEditMode
func GetEditMode(w http.ResponseWriter, req *http.Request) bool { return admin.ActionBar.EditMode(w, req) }
go
func GetEditMode(w http.ResponseWriter, req *http.Request) bool { return admin.ActionBar.EditMode(w, req) }
[ "func", "GetEditMode", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "bool", "{", "return", "admin", ".", "ActionBar", ".", "EditMode", "(", "w", ",", "req", ")", "\n", "}" ]
// GetEditMode get edit mode
[ "GetEditMode", "get", "edit", "mode" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/utils/funcmapmaker/funcmapmaker.go#L24-L26
train
qor/qor-example
app/account/handlers.go
Profile
func (ctrl Controller) Profile(w http.ResponseWriter, req *http.Request) { var ( currentUser = utils.GetCurrentUser(req) tx = utils.GetDB(req) billingAddress, shippingAddress users.Address ) // TODO refactor tx.Model(currentUser).Related(&currentUser.Addresses, "Addresses") tx.Model(currentUser).Related(&billingAddress, "DefaultBillingAddress") tx.Model(currentUser).Related(&shippingAddress, "DefaultShippingAddress") ctrl.View.Execute("profile", map[string]interface{}{ "CurrentUser": currentUser, "DefaultBillingAddress": billingAddress, "DefaultShippingAddress": shippingAddress, }, req, w) }
go
func (ctrl Controller) Profile(w http.ResponseWriter, req *http.Request) { var ( currentUser = utils.GetCurrentUser(req) tx = utils.GetDB(req) billingAddress, shippingAddress users.Address ) // TODO refactor tx.Model(currentUser).Related(&currentUser.Addresses, "Addresses") tx.Model(currentUser).Related(&billingAddress, "DefaultBillingAddress") tx.Model(currentUser).Related(&shippingAddress, "DefaultShippingAddress") ctrl.View.Execute("profile", map[string]interface{}{ "CurrentUser": currentUser, "DefaultBillingAddress": billingAddress, "DefaultShippingAddress": shippingAddress, }, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Profile", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "var", "(", "currentUser", "=", "utils", ".", "GetCurrentUser", "(", "req", ")", "\n", "tx", "=", "utils", ".", "GetDB", "(", "req", ")", "\n", "billingAddress", ",", "shippingAddress", "users", ".", "Address", "\n", ")", "\n\n", "// TODO refactor", "tx", ".", "Model", "(", "currentUser", ")", ".", "Related", "(", "&", "currentUser", ".", "Addresses", ",", "\"", "\"", ")", "\n", "tx", ".", "Model", "(", "currentUser", ")", ".", "Related", "(", "&", "billingAddress", ",", "\"", "\"", ")", "\n", "tx", ".", "Model", "(", "currentUser", ")", ".", "Related", "(", "&", "shippingAddress", ",", "\"", "\"", ")", "\n\n", "ctrl", ".", "View", ".", "Execute", "(", "\"", "\"", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "currentUser", ",", "\"", "\"", ":", "billingAddress", ",", "\"", "\"", ":", "shippingAddress", ",", "}", ",", "req", ",", "w", ")", "\n", "}" ]
// Profile profile show page
[ "Profile", "profile", "show", "page" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/account/handlers.go#L18-L33
train
qor/qor-example
app/account/handlers.go
Orders
func (ctrl Controller) Orders(w http.ResponseWriter, req *http.Request) { var ( Orders []orders.Order currentUser = utils.GetCurrentUser(req) tx = utils.GetDB(req) ) tx.Preload("OrderItems").Where("state <> ? AND state != ?", orders.DraftState, "").Where(&orders.Order{UserID: &currentUser.ID}).Find(&Orders) ctrl.View.Execute("orders", map[string]interface{}{"Orders": Orders}, req, w) }
go
func (ctrl Controller) Orders(w http.ResponseWriter, req *http.Request) { var ( Orders []orders.Order currentUser = utils.GetCurrentUser(req) tx = utils.GetDB(req) ) tx.Preload("OrderItems").Where("state <> ? AND state != ?", orders.DraftState, "").Where(&orders.Order{UserID: &currentUser.ID}).Find(&Orders) ctrl.View.Execute("orders", map[string]interface{}{"Orders": Orders}, req, w) }
[ "func", "(", "ctrl", "Controller", ")", "Orders", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "var", "(", "Orders", "[", "]", "orders", ".", "Order", "\n", "currentUser", "=", "utils", ".", "GetCurrentUser", "(", "req", ")", "\n", "tx", "=", "utils", ".", "GetDB", "(", "req", ")", "\n", ")", "\n\n", "tx", ".", "Preload", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ",", "orders", ".", "DraftState", ",", "\"", "\"", ")", ".", "Where", "(", "&", "orders", ".", "Order", "{", "UserID", ":", "&", "currentUser", ".", "ID", "}", ")", ".", "Find", "(", "&", "Orders", ")", "\n\n", "ctrl", ".", "View", ".", "Execute", "(", "\"", "\"", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "Orders", "}", ",", "req", ",", "w", ")", "\n", "}" ]
// Orders orders page
[ "Orders", "orders", "page" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/app/account/handlers.go#L36-L46
train
qor/qor-example
utils/utils.go
GetCurrentUser
func GetCurrentUser(req *http.Request) *users.User { if currentUser, ok := auth.Auth.GetCurrentUser(req).(*users.User); ok { return currentUser } return nil }
go
func GetCurrentUser(req *http.Request) *users.User { if currentUser, ok := auth.Auth.GetCurrentUser(req).(*users.User); ok { return currentUser } return nil }
[ "func", "GetCurrentUser", "(", "req", "*", "http", ".", "Request", ")", "*", "users", ".", "User", "{", "if", "currentUser", ",", "ok", ":=", "auth", ".", "Auth", ".", "GetCurrentUser", "(", "req", ")", ".", "(", "*", "users", ".", "User", ")", ";", "ok", "{", "return", "currentUser", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetCurrentUser get current user from request
[ "GetCurrentUser", "get", "current", "user", "from", "request" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/utils/utils.go#L21-L26
train
qor/qor-example
utils/utils.go
GetCurrentLocale
func GetCurrentLocale(req *http.Request) string { locale := l10n.Global if cookie, err := req.Cookie("locale"); err == nil { locale = cookie.Value } return locale }
go
func GetCurrentLocale(req *http.Request) string { locale := l10n.Global if cookie, err := req.Cookie("locale"); err == nil { locale = cookie.Value } return locale }
[ "func", "GetCurrentLocale", "(", "req", "*", "http", ".", "Request", ")", "string", "{", "locale", ":=", "l10n", ".", "Global", "\n", "if", "cookie", ",", "err", ":=", "req", ".", "Cookie", "(", "\"", "\"", ")", ";", "err", "==", "nil", "{", "locale", "=", "cookie", ".", "Value", "\n", "}", "\n", "return", "locale", "\n", "}" ]
// GetCurrentLocale get current locale from request
[ "GetCurrentLocale", "get", "current", "locale", "from", "request" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/utils/utils.go#L29-L35
train
qor/qor-example
utils/utils.go
GetDB
func GetDB(req *http.Request) *gorm.DB { if db := utils.GetDBFromRequest(req); db != nil { return db } return db.DB }
go
func GetDB(req *http.Request) *gorm.DB { if db := utils.GetDBFromRequest(req); db != nil { return db } return db.DB }
[ "func", "GetDB", "(", "req", "*", "http", ".", "Request", ")", "*", "gorm", ".", "DB", "{", "if", "db", ":=", "utils", ".", "GetDBFromRequest", "(", "req", ")", ";", "db", "!=", "nil", "{", "return", "db", "\n", "}", "\n", "return", "db", ".", "DB", "\n", "}" ]
// GetDB get DB from request
[ "GetDB", "get", "DB", "from", "request" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/utils/utils.go#L38-L43
train
qor/qor-example
utils/utils.go
URLParam
func URLParam(name string, req *http.Request) string { return chi.URLParam(req, name) }
go
func URLParam(name string, req *http.Request) string { return chi.URLParam(req, name) }
[ "func", "URLParam", "(", "name", "string", ",", "req", "*", "http", ".", "Request", ")", "string", "{", "return", "chi", ".", "URLParam", "(", "req", ",", "name", ")", "\n", "}" ]
// URLParam get url params from request
[ "URLParam", "get", "url", "params", "from", "request" ]
75e1973e60a7aa67af70b31717666a5d51262ae7
https://github.com/qor/qor-example/blob/75e1973e60a7aa67af70b31717666a5d51262ae7/utils/utils.go#L46-L48
train
DataDog/datadog-go
statsd/uds_blocking.go
newBlockingUdsWriter
func newBlockingUdsWriter(addr string) (*blockingUdsWriter, error) { udsAddr, err := net.ResolveUnixAddr("unixgram", addr) if err != nil { return nil, err } // Defer connection to first Write writer := &blockingUdsWriter{addr: udsAddr, conn: nil, writeTimeout: defaultUDSTimeout} return writer, nil }
go
func newBlockingUdsWriter(addr string) (*blockingUdsWriter, error) { udsAddr, err := net.ResolveUnixAddr("unixgram", addr) if err != nil { return nil, err } // Defer connection to first Write writer := &blockingUdsWriter{addr: udsAddr, conn: nil, writeTimeout: defaultUDSTimeout} return writer, nil }
[ "func", "newBlockingUdsWriter", "(", "addr", "string", ")", "(", "*", "blockingUdsWriter", ",", "error", ")", "{", "udsAddr", ",", "err", ":=", "net", ".", "ResolveUnixAddr", "(", "\"", "\"", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Defer connection to first Write", "writer", ":=", "&", "blockingUdsWriter", "{", "addr", ":", "udsAddr", ",", "conn", ":", "nil", ",", "writeTimeout", ":", "defaultUDSTimeout", "}", "\n", "return", "writer", ",", "nil", "\n", "}" ]
// New returns a pointer to a new blockingUdsWriter given a socket file path as addr.
[ "New", "returns", "a", "pointer", "to", "a", "new", "blockingUdsWriter", "given", "a", "socket", "file", "path", "as", "addr", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/uds_blocking.go#L21-L29
train
DataDog/datadog-go
statsd/statsd.go
format
func (c *Client) format(name string, value interface{}, suffix []byte, tags []string, rate float64) []byte { // preallocated buffer, stack allocated as long as it doesn't escape buf := make([]byte, 0, 200) if c.Namespace != "" { buf = append(buf, c.Namespace...) } buf = append(buf, name...) buf = append(buf, ':') switch val := value.(type) { case float64: buf = strconv.AppendFloat(buf, val, 'f', 6, 64) case int64: buf = strconv.AppendInt(buf, val, 10) case string: buf = append(buf, val...) default: // do nothing } buf = append(buf, suffix...) if rate < 1 { buf = append(buf, "|@"...) buf = strconv.AppendFloat(buf, rate, 'f', -1, 64) } buf = appendTagString(buf, c.Tags, tags) // non-zeroing copy to avoid referencing a larger than necessary underlying array return append([]byte(nil), buf...) }
go
func (c *Client) format(name string, value interface{}, suffix []byte, tags []string, rate float64) []byte { // preallocated buffer, stack allocated as long as it doesn't escape buf := make([]byte, 0, 200) if c.Namespace != "" { buf = append(buf, c.Namespace...) } buf = append(buf, name...) buf = append(buf, ':') switch val := value.(type) { case float64: buf = strconv.AppendFloat(buf, val, 'f', 6, 64) case int64: buf = strconv.AppendInt(buf, val, 10) case string: buf = append(buf, val...) default: // do nothing } buf = append(buf, suffix...) if rate < 1 { buf = append(buf, "|@"...) buf = strconv.AppendFloat(buf, rate, 'f', -1, 64) } buf = appendTagString(buf, c.Tags, tags) // non-zeroing copy to avoid referencing a larger than necessary underlying array return append([]byte(nil), buf...) }
[ "func", "(", "c", "*", "Client", ")", "format", "(", "name", "string", ",", "value", "interface", "{", "}", ",", "suffix", "[", "]", "byte", ",", "tags", "[", "]", "string", ",", "rate", "float64", ")", "[", "]", "byte", "{", "// preallocated buffer, stack allocated as long as it doesn't escape", "buf", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "200", ")", "\n\n", "if", "c", ".", "Namespace", "!=", "\"", "\"", "{", "buf", "=", "append", "(", "buf", ",", "c", ".", "Namespace", "...", ")", "\n", "}", "\n", "buf", "=", "append", "(", "buf", ",", "name", "...", ")", "\n", "buf", "=", "append", "(", "buf", ",", "':'", ")", "\n\n", "switch", "val", ":=", "value", ".", "(", "type", ")", "{", "case", "float64", ":", "buf", "=", "strconv", ".", "AppendFloat", "(", "buf", ",", "val", ",", "'f'", ",", "6", ",", "64", ")", "\n\n", "case", "int64", ":", "buf", "=", "strconv", ".", "AppendInt", "(", "buf", ",", "val", ",", "10", ")", "\n\n", "case", "string", ":", "buf", "=", "append", "(", "buf", ",", "val", "...", ")", "\n\n", "default", ":", "// do nothing", "}", "\n", "buf", "=", "append", "(", "buf", ",", "suffix", "...", ")", "\n\n", "if", "rate", "<", "1", "{", "buf", "=", "append", "(", "buf", ",", "\"", "\"", "...", ")", "\n", "buf", "=", "strconv", ".", "AppendFloat", "(", "buf", ",", "rate", ",", "'f'", ",", "-", "1", ",", "64", ")", "\n", "}", "\n\n", "buf", "=", "appendTagString", "(", "buf", ",", "c", ".", "Tags", ",", "tags", ")", "\n\n", "// non-zeroing copy to avoid referencing a larger than necessary underlying array", "return", "append", "(", "[", "]", "byte", "(", "nil", ")", ",", "buf", "...", ")", "\n", "}" ]
// format a message from its name, value, tags and rate. Also adds global // namespace and tags.
[ "format", "a", "message", "from", "its", "name", "value", "tags", "and", "rate", ".", "Also", "adds", "global", "namespace", "and", "tags", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L184-L218
train
DataDog/datadog-go
statsd/statsd.go
SetWriteTimeout
func (c *Client) SetWriteTimeout(d time.Duration) error { if c == nil { return fmt.Errorf("Client is nil") } return c.writer.SetWriteTimeout(d) }
go
func (c *Client) SetWriteTimeout(d time.Duration) error { if c == nil { return fmt.Errorf("Client is nil") } return c.writer.SetWriteTimeout(d) }
[ "func", "(", "c", "*", "Client", ")", "SetWriteTimeout", "(", "d", "time", ".", "Duration", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "c", ".", "writer", ".", "SetWriteTimeout", "(", "d", ")", "\n", "}" ]
// SetWriteTimeout allows the user to set a custom UDS write timeout. Not supported for UDP.
[ "SetWriteTimeout", "allows", "the", "user", "to", "set", "a", "custom", "UDS", "write", "timeout", ".", "Not", "supported", "for", "UDP", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L221-L226
train
DataDog/datadog-go
statsd/statsd.go
Flush
func (c *Client) Flush() error { if c == nil { return fmt.Errorf("Client is nil") } c.Lock() defer c.Unlock() return c.flushLocked() }
go
func (c *Client) Flush() error { if c == nil { return fmt.Errorf("Client is nil") } c.Lock() defer c.Unlock() return c.flushLocked() }
[ "func", "(", "c", "*", "Client", ")", "Flush", "(", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "c", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "flushLocked", "(", ")", "\n", "}" ]
// Flush forces a flush of the pending commands in the buffer
[ "Flush", "forces", "a", "flush", "of", "the", "pending", "commands", "in", "the", "buffer" ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L308-L315
train
DataDog/datadog-go
statsd/statsd.go
flushLocked
func (c *Client) flushLocked() error { frames, flushable := c.joinMaxSize(c.commands, "\n", OptimalPayloadSize) var err error cmdsFlushed := 0 for i, data := range frames { _, e := c.writer.Write(data) if e != nil { err = e break } cmdsFlushed += flushable[i] } // clear the slice with a slice op, doesn't realloc if cmdsFlushed == len(c.commands) { c.commands = c.commands[:0] } else { //this case will cause a future realloc... // drop problematic command though (sorry). c.commands = c.commands[cmdsFlushed+1:] } return err }
go
func (c *Client) flushLocked() error { frames, flushable := c.joinMaxSize(c.commands, "\n", OptimalPayloadSize) var err error cmdsFlushed := 0 for i, data := range frames { _, e := c.writer.Write(data) if e != nil { err = e break } cmdsFlushed += flushable[i] } // clear the slice with a slice op, doesn't realloc if cmdsFlushed == len(c.commands) { c.commands = c.commands[:0] } else { //this case will cause a future realloc... // drop problematic command though (sorry). c.commands = c.commands[cmdsFlushed+1:] } return err }
[ "func", "(", "c", "*", "Client", ")", "flushLocked", "(", ")", "error", "{", "frames", ",", "flushable", ":=", "c", ".", "joinMaxSize", "(", "c", ".", "commands", ",", "\"", "\\n", "\"", ",", "OptimalPayloadSize", ")", "\n", "var", "err", "error", "\n", "cmdsFlushed", ":=", "0", "\n", "for", "i", ",", "data", ":=", "range", "frames", "{", "_", ",", "e", ":=", "c", ".", "writer", ".", "Write", "(", "data", ")", "\n", "if", "e", "!=", "nil", "{", "err", "=", "e", "\n", "break", "\n", "}", "\n", "cmdsFlushed", "+=", "flushable", "[", "i", "]", "\n", "}", "\n\n", "// clear the slice with a slice op, doesn't realloc", "if", "cmdsFlushed", "==", "len", "(", "c", ".", "commands", ")", "{", "c", ".", "commands", "=", "c", ".", "commands", "[", ":", "0", "]", "\n", "}", "else", "{", "//this case will cause a future realloc...", "// drop problematic command though (sorry).", "c", ".", "commands", "=", "c", ".", "commands", "[", "cmdsFlushed", "+", "1", ":", "]", "\n", "}", "\n", "return", "err", "\n", "}" ]
// flush the commands in the buffer. Lock must be held by caller.
[ "flush", "the", "commands", "in", "the", "buffer", ".", "Lock", "must", "be", "held", "by", "caller", "." ]
40bafcb5f6c1d49df36deaf4ab019e44961d5e36
https://github.com/DataDog/datadog-go/blob/40bafcb5f6c1d49df36deaf4ab019e44961d5e36/statsd/statsd.go#L318-L340
train