id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
11,900 | bobesa/go-domain-util | domainutil/util.go | stripURLParts | func stripURLParts(url string) string {
// Lower case the url
url = strings.ToLower(url)
// Strip protocol
if index := strings.Index(url, "://"); index > -1 {
url = url[index+3:]
}
// Now, if the url looks like this: username:[email protected]/path?query=?
// we remove the content before the '@' symbol
if index := strings.Index(url, "@"); index > -1 {
url = url[index+1:]
}
// Strip path (and query with it)
if index := strings.Index(url, "/"); index > -1 {
url = url[:index]
} else if index := strings.Index(url, "?"); index > -1 { // Strip query if path is not found
url = url[:index]
}
// Convert domain to unicode
if strings.Index(url, "xn--") != -1 {
var err error
url, err = idna.ToUnicode(url)
if err != nil {
return ""
}
}
// Return domain
return url
} | go | func stripURLParts(url string) string {
// Lower case the url
url = strings.ToLower(url)
// Strip protocol
if index := strings.Index(url, "://"); index > -1 {
url = url[index+3:]
}
// Now, if the url looks like this: username:[email protected]/path?query=?
// we remove the content before the '@' symbol
if index := strings.Index(url, "@"); index > -1 {
url = url[index+1:]
}
// Strip path (and query with it)
if index := strings.Index(url, "/"); index > -1 {
url = url[:index]
} else if index := strings.Index(url, "?"); index > -1 { // Strip query if path is not found
url = url[:index]
}
// Convert domain to unicode
if strings.Index(url, "xn--") != -1 {
var err error
url, err = idna.ToUnicode(url)
if err != nil {
return ""
}
}
// Return domain
return url
} | [
"func",
"stripURLParts",
"(",
"url",
"string",
")",
"string",
"{",
"// Lower case the url",
"url",
"=",
"strings",
".",
"ToLower",
"(",
"url",
")",
"\n\n",
"// Strip protocol",
"if",
"index",
":=",
"strings",
".",
"Index",
"(",
"url",
",",
"\"",
"\"",
")",
";",
"index",
">",
"-",
"1",
"{",
"url",
"=",
"url",
"[",
"index",
"+",
"3",
":",
"]",
"\n",
"}",
"\n\n",
"// Now, if the url looks like this: username:[email protected]/path?query=?",
"// we remove the content before the '@' symbol",
"if",
"index",
":=",
"strings",
".",
"Index",
"(",
"url",
",",
"\"",
"\"",
")",
";",
"index",
">",
"-",
"1",
"{",
"url",
"=",
"url",
"[",
"index",
"+",
"1",
":",
"]",
"\n",
"}",
"\n\n",
"// Strip path (and query with it)",
"if",
"index",
":=",
"strings",
".",
"Index",
"(",
"url",
",",
"\"",
"\"",
")",
";",
"index",
">",
"-",
"1",
"{",
"url",
"=",
"url",
"[",
":",
"index",
"]",
"\n",
"}",
"else",
"if",
"index",
":=",
"strings",
".",
"Index",
"(",
"url",
",",
"\"",
"\"",
")",
";",
"index",
">",
"-",
"1",
"{",
"// Strip query if path is not found",
"url",
"=",
"url",
"[",
":",
"index",
"]",
"\n",
"}",
"\n\n",
"// Convert domain to unicode",
"if",
"strings",
".",
"Index",
"(",
"url",
",",
"\"",
"\"",
")",
"!=",
"-",
"1",
"{",
"var",
"err",
"error",
"\n",
"url",
",",
"err",
"=",
"idna",
".",
"ToUnicode",
"(",
"url",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Return domain",
"return",
"url",
"\n",
"}"
] | // stripURLParts removes path, protocol & query from url and returns it. | [
"stripURLParts",
"removes",
"path",
"protocol",
"&",
"query",
"from",
"url",
"and",
"returns",
"it",
"."
] | 1d708c097a6a59a3e6432affc53cf41808b35c8b | https://github.com/bobesa/go-domain-util/blob/1d708c097a6a59a3e6432affc53cf41808b35c8b/domainutil/util.go#L88-L121 |
11,901 | bobesa/go-domain-util | domainutil/util.go | Protocol | func Protocol(url string) string {
if index := strings.Index(url, "://"); index > -1 {
return url[:index]
}
return ""
} | go | func Protocol(url string) string {
if index := strings.Index(url, "://"); index > -1 {
return url[:index]
}
return ""
} | [
"func",
"Protocol",
"(",
"url",
"string",
")",
"string",
"{",
"if",
"index",
":=",
"strings",
".",
"Index",
"(",
"url",
",",
"\"",
"\"",
")",
";",
"index",
">",
"-",
"1",
"{",
"return",
"url",
"[",
":",
"index",
"]",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Protocol returns protocol from given url
//
// If protocol is not present - return empty string | [
"Protocol",
"returns",
"protocol",
"from",
"given",
"url",
"If",
"protocol",
"is",
"not",
"present",
"-",
"return",
"empty",
"string"
] | 1d708c097a6a59a3e6432affc53cf41808b35c8b | https://github.com/bobesa/go-domain-util/blob/1d708c097a6a59a3e6432affc53cf41808b35c8b/domainutil/util.go#L126-L131 |
11,902 | bobesa/go-domain-util | domainutil/util.go | Username | func Username(url string) string {
auth := strings.SplitN(credentials(url), ":", 2)
if len(auth) == 0 {
return ""
}
return auth[0]
} | go | func Username(url string) string {
auth := strings.SplitN(credentials(url), ":", 2)
if len(auth) == 0 {
return ""
}
return auth[0]
} | [
"func",
"Username",
"(",
"url",
"string",
")",
"string",
"{",
"auth",
":=",
"strings",
".",
"SplitN",
"(",
"credentials",
"(",
"url",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"auth",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"auth",
"[",
"0",
"]",
"\n",
"}"
] | // Username returns username from given url
//
// If username is not present - return empty string | [
"Username",
"returns",
"username",
"from",
"given",
"url",
"If",
"username",
"is",
"not",
"present",
"-",
"return",
"empty",
"string"
] | 1d708c097a6a59a3e6432affc53cf41808b35c8b | https://github.com/bobesa/go-domain-util/blob/1d708c097a6a59a3e6432affc53cf41808b35c8b/domainutil/util.go#L148-L154 |
11,903 | bobesa/go-domain-util | domainutil/util.go | Password | func Password(url string) string {
auth := strings.SplitN(credentials(url), ":", 2)
if len(auth) < 2 {
return ""
}
return auth[1]
} | go | func Password(url string) string {
auth := strings.SplitN(credentials(url), ":", 2)
if len(auth) < 2 {
return ""
}
return auth[1]
} | [
"func",
"Password",
"(",
"url",
"string",
")",
"string",
"{",
"auth",
":=",
"strings",
".",
"SplitN",
"(",
"credentials",
"(",
"url",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"auth",
")",
"<",
"2",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"auth",
"[",
"1",
"]",
"\n",
"}"
] | // Password returns password from given url
//
// If password is not present - return empty string | [
"Password",
"returns",
"password",
"from",
"given",
"url",
"If",
"password",
"is",
"not",
"present",
"-",
"return",
"empty",
"string"
] | 1d708c097a6a59a3e6432affc53cf41808b35c8b | https://github.com/bobesa/go-domain-util/blob/1d708c097a6a59a3e6432affc53cf41808b35c8b/domainutil/util.go#L159-L165 |
11,904 | Shaked/gomobiledetect | rules.go | NewRules | func NewRules() *rules {
rules := &rules{namesKeys: nameToKey, phoneDevices: phoneDevices, tabletDevices: tabletDevices, operatingSystems: operatingSystems, browsers: browsers}
rules.setMobileDetectionRules(nameToKey)
return rules
} | go | func NewRules() *rules {
rules := &rules{namesKeys: nameToKey, phoneDevices: phoneDevices, tabletDevices: tabletDevices, operatingSystems: operatingSystems, browsers: browsers}
rules.setMobileDetectionRules(nameToKey)
return rules
} | [
"func",
"NewRules",
"(",
")",
"*",
"rules",
"{",
"rules",
":=",
"&",
"rules",
"{",
"namesKeys",
":",
"nameToKey",
",",
"phoneDevices",
":",
"phoneDevices",
",",
"tabletDevices",
":",
"tabletDevices",
",",
"operatingSystems",
":",
"operatingSystems",
",",
"browsers",
":",
"browsers",
"}",
"\n",
"rules",
".",
"setMobileDetectionRules",
"(",
"nameToKey",
")",
"\n",
"return",
"rules",
"\n",
"}"
] | // NewRules creates a object with all rules necessary to figure out a browser from a User Agent string | [
"NewRules",
"creates",
"a",
"object",
"with",
"all",
"rules",
"necessary",
"to",
"figure",
"out",
"a",
"browser",
"from",
"a",
"User",
"Agent",
"string"
] | 25f014f665680d424817c814f3d2982a13f0985a | https://github.com/Shaked/gomobiledetect/blob/25f014f665680d424817c814f3d2982a13f0985a/rules.go#L886-L890 |
11,905 | Shaked/gomobiledetect | gomobiledetect.go | NewMobileDetect | func NewMobileDetect(r *http.Request, rules *rules) *MobileDetect {
if nil == rules {
rules = NewRules()
}
md := &MobileDetect{
rules: rules,
userAgent: r.UserAgent(),
httpHeaders: getHttpHeaders(r),
compiledRegexRules: make(map[string]*regexp.Regexp, len(rules.mobileDetectionRules())),
properties: newProperties(),
}
return md
} | go | func NewMobileDetect(r *http.Request, rules *rules) *MobileDetect {
if nil == rules {
rules = NewRules()
}
md := &MobileDetect{
rules: rules,
userAgent: r.UserAgent(),
httpHeaders: getHttpHeaders(r),
compiledRegexRules: make(map[string]*regexp.Regexp, len(rules.mobileDetectionRules())),
properties: newProperties(),
}
return md
} | [
"func",
"NewMobileDetect",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"rules",
"*",
"rules",
")",
"*",
"MobileDetect",
"{",
"if",
"nil",
"==",
"rules",
"{",
"rules",
"=",
"NewRules",
"(",
")",
"\n",
"}",
"\n",
"md",
":=",
"&",
"MobileDetect",
"{",
"rules",
":",
"rules",
",",
"userAgent",
":",
"r",
".",
"UserAgent",
"(",
")",
",",
"httpHeaders",
":",
"getHttpHeaders",
"(",
"r",
")",
",",
"compiledRegexRules",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"regexp",
".",
"Regexp",
",",
"len",
"(",
"rules",
".",
"mobileDetectionRules",
"(",
")",
")",
")",
",",
"properties",
":",
"newProperties",
"(",
")",
",",
"}",
"\n",
"return",
"md",
"\n",
"}"
] | // NewMobileDetect creates the MobileDetect object | [
"NewMobileDetect",
"creates",
"the",
"MobileDetect",
"object"
] | 25f014f665680d424817c814f3d2982a13f0985a | https://github.com/Shaked/gomobiledetect/blob/25f014f665680d424817c814f3d2982a13f0985a/gomobiledetect.go#L73-L85 |
11,906 | Shaked/gomobiledetect | gomobiledetect.go | IsTablet | func (md *MobileDetect) IsTablet() bool {
for _, ruleValue := range md.rules.tabletDevices {
if md.match(ruleValue) {
return true
}
}
return false
} | go | func (md *MobileDetect) IsTablet() bool {
for _, ruleValue := range md.rules.tabletDevices {
if md.match(ruleValue) {
return true
}
}
return false
} | [
"func",
"(",
"md",
"*",
"MobileDetect",
")",
"IsTablet",
"(",
")",
"bool",
"{",
"for",
"_",
",",
"ruleValue",
":=",
"range",
"md",
".",
"rules",
".",
"tabletDevices",
"{",
"if",
"md",
".",
"match",
"(",
"ruleValue",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsMobile is a specific case to detect only mobile browsers on tablets. Do not overlap with IsMobile | [
"IsMobile",
"is",
"a",
"specific",
"case",
"to",
"detect",
"only",
"mobile",
"browsers",
"on",
"tablets",
".",
"Do",
"not",
"overlap",
"with",
"IsMobile"
] | 25f014f665680d424817c814f3d2982a13f0985a | https://github.com/Shaked/gomobiledetect/blob/25f014f665680d424817c814f3d2982a13f0985a/gomobiledetect.go#L136-L143 |
11,907 | Shaked/gomobiledetect | gomobiledetect.go | Is | func (md *MobileDetect) Is(key interface{}) bool {
switch key.(type) {
case string:
name := strings.ToLower(key.(string))
ruleKey, ok := md.rules.nameToKey(name)
if !ok {
return false
}
return md.matchUAAgainstKey(ruleKey)
case int:
ruleKey := key.(int)
return md.IsKey(ruleKey)
}
return false
} | go | func (md *MobileDetect) Is(key interface{}) bool {
switch key.(type) {
case string:
name := strings.ToLower(key.(string))
ruleKey, ok := md.rules.nameToKey(name)
if !ok {
return false
}
return md.matchUAAgainstKey(ruleKey)
case int:
ruleKey := key.(int)
return md.IsKey(ruleKey)
}
return false
} | [
"func",
"(",
"md",
"*",
"MobileDetect",
")",
"Is",
"(",
"key",
"interface",
"{",
"}",
")",
"bool",
"{",
"switch",
"key",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"name",
":=",
"strings",
".",
"ToLower",
"(",
"key",
".",
"(",
"string",
")",
")",
"\n",
"ruleKey",
",",
"ok",
":=",
"md",
".",
"rules",
".",
"nameToKey",
"(",
"name",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"md",
".",
"matchUAAgainstKey",
"(",
"ruleKey",
")",
"\n",
"case",
"int",
":",
"ruleKey",
":=",
"key",
".",
"(",
"int",
")",
"\n",
"return",
"md",
".",
"IsKey",
"(",
"ruleKey",
")",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // It is recommended to use IsKey instead | [
"It",
"is",
"recommended",
"to",
"use",
"IsKey",
"instead"
] | 25f014f665680d424817c814f3d2982a13f0985a | https://github.com/Shaked/gomobiledetect/blob/25f014f665680d424817c814f3d2982a13f0985a/gomobiledetect.go#L151-L165 |
11,908 | Shaked/gomobiledetect | gomobiledetect.go | VersionFloatKey | func (md *MobileDetect) VersionFloatKey(propertyVal int) float64 {
return md.properties.versionFloat(propertyVal, md.userAgent)
} | go | func (md *MobileDetect) VersionFloatKey(propertyVal int) float64 {
return md.properties.versionFloat(propertyVal, md.userAgent)
} | [
"func",
"(",
"md",
"*",
"MobileDetect",
")",
"VersionFloatKey",
"(",
"propertyVal",
"int",
")",
"float64",
"{",
"return",
"md",
".",
"properties",
".",
"versionFloat",
"(",
"propertyVal",
",",
"md",
".",
"userAgent",
")",
"\n",
"}"
] | // VersionFloat does the same as Version, but returns a float number good for version comparison | [
"VersionFloat",
"does",
"the",
"same",
"as",
"Version",
"but",
"returns",
"a",
"float",
"number",
"good",
"for",
"version",
"comparison"
] | 25f014f665680d424817c814f3d2982a13f0985a | https://github.com/Shaked/gomobiledetect/blob/25f014f665680d424817c814f3d2982a13f0985a/gomobiledetect.go#L168-L170 |
11,909 | Shaked/gomobiledetect | gomobiledetect.go | VersionKey | func (md *MobileDetect) VersionKey(propertyVal int) string {
return md.properties.version(propertyVal, md.userAgent)
} | go | func (md *MobileDetect) VersionKey(propertyVal int) string {
return md.properties.version(propertyVal, md.userAgent)
} | [
"func",
"(",
"md",
"*",
"MobileDetect",
")",
"VersionKey",
"(",
"propertyVal",
"int",
")",
"string",
"{",
"return",
"md",
".",
"properties",
".",
"version",
"(",
"propertyVal",
",",
"md",
".",
"userAgent",
")",
"\n",
"}"
] | // Version detects the browser version returning as string | [
"Version",
"detects",
"the",
"browser",
"version",
"returning",
"as",
"string"
] | 25f014f665680d424817c814f3d2982a13f0985a | https://github.com/Shaked/gomobiledetect/blob/25f014f665680d424817c814f3d2982a13f0985a/gomobiledetect.go#L173-L175 |
11,910 | Shaked/gomobiledetect | gomobiledetect.go | VersionFloat | func (md *MobileDetect) VersionFloat(propertyName interface{}) float64 {
switch propertyName.(type) {
case string:
return md.properties.versionFloatName(propertyName.(string), md.userAgent)
case int:
return md.VersionFloatKey(propertyName.(int))
}
return 0.0
} | go | func (md *MobileDetect) VersionFloat(propertyName interface{}) float64 {
switch propertyName.(type) {
case string:
return md.properties.versionFloatName(propertyName.(string), md.userAgent)
case int:
return md.VersionFloatKey(propertyName.(int))
}
return 0.0
} | [
"func",
"(",
"md",
"*",
"MobileDetect",
")",
"VersionFloat",
"(",
"propertyName",
"interface",
"{",
"}",
")",
"float64",
"{",
"switch",
"propertyName",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"return",
"md",
".",
"properties",
".",
"versionFloatName",
"(",
"propertyName",
".",
"(",
"string",
")",
",",
"md",
".",
"userAgent",
")",
"\n",
"case",
"int",
":",
"return",
"md",
".",
"VersionFloatKey",
"(",
"propertyName",
".",
"(",
"int",
")",
")",
"\n",
"}",
"\n",
"return",
"0.0",
"\n",
"}"
] | // It is recommended to use VersionFloatKey instead | [
"It",
"is",
"recommended",
"to",
"use",
"VersionFloatKey",
"instead"
] | 25f014f665680d424817c814f3d2982a13f0985a | https://github.com/Shaked/gomobiledetect/blob/25f014f665680d424817c814f3d2982a13f0985a/gomobiledetect.go#L178-L186 |
11,911 | Shaked/gomobiledetect | gomobiledetect.go | Version | func (md *MobileDetect) Version(propertyName interface{}) string {
switch propertyName.(type) {
case string:
return md.properties.versionByName(propertyName.(string), md.userAgent)
case int:
return md.VersionKey(propertyName.(int))
}
return ""
} | go | func (md *MobileDetect) Version(propertyName interface{}) string {
switch propertyName.(type) {
case string:
return md.properties.versionByName(propertyName.(string), md.userAgent)
case int:
return md.VersionKey(propertyName.(int))
}
return ""
} | [
"func",
"(",
"md",
"*",
"MobileDetect",
")",
"Version",
"(",
"propertyName",
"interface",
"{",
"}",
")",
"string",
"{",
"switch",
"propertyName",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"return",
"md",
".",
"properties",
".",
"versionByName",
"(",
"propertyName",
".",
"(",
"string",
")",
",",
"md",
".",
"userAgent",
")",
"\n",
"case",
"int",
":",
"return",
"md",
".",
"VersionKey",
"(",
"propertyName",
".",
"(",
"int",
")",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // It is recommended to use VersionKey instead | [
"It",
"is",
"recommended",
"to",
"use",
"VersionKey",
"instead"
] | 25f014f665680d424817c814f3d2982a13f0985a | https://github.com/Shaked/gomobiledetect/blob/25f014f665680d424817c814f3d2982a13f0985a/gomobiledetect.go#L189-L197 |
11,912 | Shaked/gomobiledetect | gomobiledetect.go | matchUAAgainstKey | func (md *MobileDetect) matchUAAgainstKey(key int) bool {
ret := false
rules := md.rules.mobileDetectionRules()
for ruleKey, ruleValue := range rules {
if key == ruleKey {
ret = md.match(ruleValue)
break
}
}
return ret
} | go | func (md *MobileDetect) matchUAAgainstKey(key int) bool {
ret := false
rules := md.rules.mobileDetectionRules()
for ruleKey, ruleValue := range rules {
if key == ruleKey {
ret = md.match(ruleValue)
break
}
}
return ret
} | [
"func",
"(",
"md",
"*",
"MobileDetect",
")",
"matchUAAgainstKey",
"(",
"key",
"int",
")",
"bool",
"{",
"ret",
":=",
"false",
"\n",
"rules",
":=",
"md",
".",
"rules",
".",
"mobileDetectionRules",
"(",
")",
"\n",
"for",
"ruleKey",
",",
"ruleValue",
":=",
"range",
"rules",
"{",
"if",
"key",
"==",
"ruleKey",
"{",
"ret",
"=",
"md",
".",
"match",
"(",
"ruleValue",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"ret",
"\n",
"}"
] | //Search for a certain key in the rules array.
//If the key is found the try to match the corresponding regex agains the User-Agent. | [
"Search",
"for",
"a",
"certain",
"key",
"in",
"the",
"rules",
"array",
".",
"If",
"the",
"key",
"is",
"found",
"the",
"try",
"to",
"match",
"the",
"corresponding",
"regex",
"agains",
"the",
"User",
"-",
"Agent",
"."
] | 25f014f665680d424817c814f3d2982a13f0985a | https://github.com/Shaked/gomobiledetect/blob/25f014f665680d424817c814f3d2982a13f0985a/gomobiledetect.go#L201-L212 |
11,913 | Shaked/gomobiledetect | gomobiledetect.go | matchDetectionRulesAgainstUA | func (md *MobileDetect) matchDetectionRulesAgainstUA() bool {
for _, ruleValue := range md.rules.mobileDetectionRules() {
if "" != ruleValue {
if md.match(ruleValue) {
return true
}
}
}
return false
} | go | func (md *MobileDetect) matchDetectionRulesAgainstUA() bool {
for _, ruleValue := range md.rules.mobileDetectionRules() {
if "" != ruleValue {
if md.match(ruleValue) {
return true
}
}
}
return false
} | [
"func",
"(",
"md",
"*",
"MobileDetect",
")",
"matchDetectionRulesAgainstUA",
"(",
")",
"bool",
"{",
"for",
"_",
",",
"ruleValue",
":=",
"range",
"md",
".",
"rules",
".",
"mobileDetectionRules",
"(",
")",
"{",
"if",
"\"",
"\"",
"!=",
"ruleValue",
"{",
"if",
"md",
".",
"match",
"(",
"ruleValue",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] | //Find a detection rule that matches the current User-agent. | [
"Find",
"a",
"detection",
"rule",
"that",
"matches",
"the",
"current",
"User",
"-",
"agent",
"."
] | 25f014f665680d424817c814f3d2982a13f0985a | https://github.com/Shaked/gomobiledetect/blob/25f014f665680d424817c814f3d2982a13f0985a/gomobiledetect.go#L215-L225 |
11,914 | Shaked/gomobiledetect | gomobiledetect.go | CheckHttpHeadersForMobile | func (md *MobileDetect) CheckHttpHeadersForMobile() bool {
for _, mobileHeader := range md.mobileHeaders() {
if headerString, ok := md.httpHeaders[mobileHeader]; ok {
mobileHeaderMatches := md.mobileHeaderMatches()
if matches, ok := mobileHeaderMatches[mobileHeader]; ok {
for _, match := range matches {
if -1 != strings.Index(headerString, match) {
return true
}
}
return false
} else {
return true
}
}
}
return false
} | go | func (md *MobileDetect) CheckHttpHeadersForMobile() bool {
for _, mobileHeader := range md.mobileHeaders() {
if headerString, ok := md.httpHeaders[mobileHeader]; ok {
mobileHeaderMatches := md.mobileHeaderMatches()
if matches, ok := mobileHeaderMatches[mobileHeader]; ok {
for _, match := range matches {
if -1 != strings.Index(headerString, match) {
return true
}
}
return false
} else {
return true
}
}
}
return false
} | [
"func",
"(",
"md",
"*",
"MobileDetect",
")",
"CheckHttpHeadersForMobile",
"(",
")",
"bool",
"{",
"for",
"_",
",",
"mobileHeader",
":=",
"range",
"md",
".",
"mobileHeaders",
"(",
")",
"{",
"if",
"headerString",
",",
"ok",
":=",
"md",
".",
"httpHeaders",
"[",
"mobileHeader",
"]",
";",
"ok",
"{",
"mobileHeaderMatches",
":=",
"md",
".",
"mobileHeaderMatches",
"(",
")",
"\n",
"if",
"matches",
",",
"ok",
":=",
"mobileHeaderMatches",
"[",
"mobileHeader",
"]",
";",
"ok",
"{",
"for",
"_",
",",
"match",
":=",
"range",
"matches",
"{",
"if",
"-",
"1",
"!=",
"strings",
".",
"Index",
"(",
"headerString",
",",
"match",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"else",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // CheckHttpHeadersForMobile looks for mobile rules to confirm if the browser is a mobile browser | [
"CheckHttpHeadersForMobile",
"looks",
"for",
"mobile",
"rules",
"to",
"confirm",
"if",
"the",
"browser",
"is",
"a",
"mobile",
"browser"
] | 25f014f665680d424817c814f3d2982a13f0985a | https://github.com/Shaked/gomobiledetect/blob/25f014f665680d424817c814f3d2982a13f0985a/gomobiledetect.go#L246-L263 |
11,915 | Shaked/gomobiledetect | gomobiledetect.go | MobileGrade | func (md *MobileDetect) MobileGrade() string {
isMobile := md.IsMobile()
if md.isMobileGradeA(isMobile) {
return MOBILE_GRADE_A
}
if md.isMobileGradeB() {
return MOBILE_GRADE_B
}
return MOBILE_GRADE_C
} | go | func (md *MobileDetect) MobileGrade() string {
isMobile := md.IsMobile()
if md.isMobileGradeA(isMobile) {
return MOBILE_GRADE_A
}
if md.isMobileGradeB() {
return MOBILE_GRADE_B
}
return MOBILE_GRADE_C
} | [
"func",
"(",
"md",
"*",
"MobileDetect",
")",
"MobileGrade",
"(",
")",
"string",
"{",
"isMobile",
":=",
"md",
".",
"IsMobile",
"(",
")",
"\n\n",
"if",
"md",
".",
"isMobileGradeA",
"(",
"isMobile",
")",
"{",
"return",
"MOBILE_GRADE_A",
"\n",
"}",
"\n",
"if",
"md",
".",
"isMobileGradeB",
"(",
")",
"{",
"return",
"MOBILE_GRADE_B",
"\n",
"}",
"\n",
"return",
"MOBILE_GRADE_C",
"\n",
"}"
] | // MobileGrade returns a graduation similar to jQuery's Graded Browse Support | [
"MobileGrade",
"returns",
"a",
"graduation",
"similar",
"to",
"jQuery",
"s",
"Graded",
"Browse",
"Support"
] | 25f014f665680d424817c814f3d2982a13f0985a | https://github.com/Shaked/gomobiledetect/blob/25f014f665680d424817c814f3d2982a13f0985a/gomobiledetect.go#L304-L314 |
11,916 | bndr/gotabulate | utils.go | createFromString | func createFromString(data [][]string) []*TabulateRow {
rows := make([]*TabulateRow, len(data))
for index, el := range data {
rows[index] = &TabulateRow{Elements: el}
}
return rows
} | go | func createFromString(data [][]string) []*TabulateRow {
rows := make([]*TabulateRow, len(data))
for index, el := range data {
rows[index] = &TabulateRow{Elements: el}
}
return rows
} | [
"func",
"createFromString",
"(",
"data",
"[",
"]",
"[",
"]",
"string",
")",
"[",
"]",
"*",
"TabulateRow",
"{",
"rows",
":=",
"make",
"(",
"[",
"]",
"*",
"TabulateRow",
",",
"len",
"(",
"data",
")",
")",
"\n\n",
"for",
"index",
",",
"el",
":=",
"range",
"data",
"{",
"rows",
"[",
"index",
"]",
"=",
"&",
"TabulateRow",
"{",
"Elements",
":",
"el",
"}",
"\n",
"}",
"\n",
"return",
"rows",
"\n",
"}"
] | // Create normalized Array from strings | [
"Create",
"normalized",
"Array",
"from",
"strings"
] | bc555436bfd5d4e93a2dd35b462ce37e067afdda | https://github.com/bndr/gotabulate/blob/bc555436bfd5d4e93a2dd35b462ce37e067afdda/utils.go#L7-L14 |
11,917 | bndr/gotabulate | utils.go | createFromInt | func createFromInt(data [][]int) []*TabulateRow {
rows := make([]*TabulateRow, len(data))
for index_1, arr := range data {
row := make([]string, len(arr))
for index, el := range arr {
row[index] = strconv.Itoa(el)
}
rows[index_1] = &TabulateRow{Elements: row}
}
return rows
} | go | func createFromInt(data [][]int) []*TabulateRow {
rows := make([]*TabulateRow, len(data))
for index_1, arr := range data {
row := make([]string, len(arr))
for index, el := range arr {
row[index] = strconv.Itoa(el)
}
rows[index_1] = &TabulateRow{Elements: row}
}
return rows
} | [
"func",
"createFromInt",
"(",
"data",
"[",
"]",
"[",
"]",
"int",
")",
"[",
"]",
"*",
"TabulateRow",
"{",
"rows",
":=",
"make",
"(",
"[",
"]",
"*",
"TabulateRow",
",",
"len",
"(",
"data",
")",
")",
"\n",
"for",
"index_1",
",",
"arr",
":=",
"range",
"data",
"{",
"row",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"arr",
")",
")",
"\n",
"for",
"index",
",",
"el",
":=",
"range",
"arr",
"{",
"row",
"[",
"index",
"]",
"=",
"strconv",
".",
"Itoa",
"(",
"el",
")",
"\n",
"}",
"\n",
"rows",
"[",
"index_1",
"]",
"=",
"&",
"TabulateRow",
"{",
"Elements",
":",
"row",
"}",
"\n",
"}",
"\n",
"return",
"rows",
"\n",
"}"
] | // Create normalized array from ints | [
"Create",
"normalized",
"array",
"from",
"ints"
] | bc555436bfd5d4e93a2dd35b462ce37e067afdda | https://github.com/bndr/gotabulate/blob/bc555436bfd5d4e93a2dd35b462ce37e067afdda/utils.go#L48-L58 |
11,918 | bndr/gotabulate | utils.go | createFromFloat64 | func createFromFloat64(data [][]float64, format byte) []*TabulateRow {
rows := make([]*TabulateRow, len(data))
for index_1, arr := range data {
row := make([]string, len(arr))
for index, el := range arr {
row[index] = strconv.FormatFloat(el, format, -1, 64)
}
rows[index_1] = &TabulateRow{Elements: row}
}
return rows
} | go | func createFromFloat64(data [][]float64, format byte) []*TabulateRow {
rows := make([]*TabulateRow, len(data))
for index_1, arr := range data {
row := make([]string, len(arr))
for index, el := range arr {
row[index] = strconv.FormatFloat(el, format, -1, 64)
}
rows[index_1] = &TabulateRow{Elements: row}
}
return rows
} | [
"func",
"createFromFloat64",
"(",
"data",
"[",
"]",
"[",
"]",
"float64",
",",
"format",
"byte",
")",
"[",
"]",
"*",
"TabulateRow",
"{",
"rows",
":=",
"make",
"(",
"[",
"]",
"*",
"TabulateRow",
",",
"len",
"(",
"data",
")",
")",
"\n",
"for",
"index_1",
",",
"arr",
":=",
"range",
"data",
"{",
"row",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"arr",
")",
")",
"\n",
"for",
"index",
",",
"el",
":=",
"range",
"arr",
"{",
"row",
"[",
"index",
"]",
"=",
"strconv",
".",
"FormatFloat",
"(",
"el",
",",
"format",
",",
"-",
"1",
",",
"64",
")",
"\n",
"}",
"\n",
"rows",
"[",
"index_1",
"]",
"=",
"&",
"TabulateRow",
"{",
"Elements",
":",
"row",
"}",
"\n",
"}",
"\n",
"return",
"rows",
"\n",
"}"
] | // Create normalized array from float64 | [
"Create",
"normalized",
"array",
"from",
"float64"
] | bc555436bfd5d4e93a2dd35b462ce37e067afdda | https://github.com/bndr/gotabulate/blob/bc555436bfd5d4e93a2dd35b462ce37e067afdda/utils.go#L61-L71 |
11,919 | bndr/gotabulate | utils.go | createFromInt32 | func createFromInt32(data [][]int32) []*TabulateRow {
rows := make([]*TabulateRow, len(data))
for index_1, arr := range data {
row := make([]string, len(arr))
for index, el := range arr {
quoted := strconv.QuoteRuneToASCII(el)
row[index] = quoted[1 : len(quoted)-1]
}
rows[index_1] = &TabulateRow{Elements: row}
}
return rows
} | go | func createFromInt32(data [][]int32) []*TabulateRow {
rows := make([]*TabulateRow, len(data))
for index_1, arr := range data {
row := make([]string, len(arr))
for index, el := range arr {
quoted := strconv.QuoteRuneToASCII(el)
row[index] = quoted[1 : len(quoted)-1]
}
rows[index_1] = &TabulateRow{Elements: row}
}
return rows
} | [
"func",
"createFromInt32",
"(",
"data",
"[",
"]",
"[",
"]",
"int32",
")",
"[",
"]",
"*",
"TabulateRow",
"{",
"rows",
":=",
"make",
"(",
"[",
"]",
"*",
"TabulateRow",
",",
"len",
"(",
"data",
")",
")",
"\n",
"for",
"index_1",
",",
"arr",
":=",
"range",
"data",
"{",
"row",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"arr",
")",
")",
"\n",
"for",
"index",
",",
"el",
":=",
"range",
"arr",
"{",
"quoted",
":=",
"strconv",
".",
"QuoteRuneToASCII",
"(",
"el",
")",
"\n",
"row",
"[",
"index",
"]",
"=",
"quoted",
"[",
"1",
":",
"len",
"(",
"quoted",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"rows",
"[",
"index_1",
"]",
"=",
"&",
"TabulateRow",
"{",
"Elements",
":",
"row",
"}",
"\n",
"}",
"\n",
"return",
"rows",
"\n",
"}"
] | // Create normalized array from ints32 | [
"Create",
"normalized",
"array",
"from",
"ints32"
] | bc555436bfd5d4e93a2dd35b462ce37e067afdda | https://github.com/bndr/gotabulate/blob/bc555436bfd5d4e93a2dd35b462ce37e067afdda/utils.go#L74-L85 |
11,920 | bndr/gotabulate | utils.go | createFromInt64 | func createFromInt64(data [][]int64) []*TabulateRow {
rows := make([]*TabulateRow, len(data))
for index_1, arr := range data {
row := make([]string, len(arr))
for index, el := range arr {
row[index] = strconv.FormatInt(el, 10)
}
rows[index_1] = &TabulateRow{Elements: row}
}
return rows
} | go | func createFromInt64(data [][]int64) []*TabulateRow {
rows := make([]*TabulateRow, len(data))
for index_1, arr := range data {
row := make([]string, len(arr))
for index, el := range arr {
row[index] = strconv.FormatInt(el, 10)
}
rows[index_1] = &TabulateRow{Elements: row}
}
return rows
} | [
"func",
"createFromInt64",
"(",
"data",
"[",
"]",
"[",
"]",
"int64",
")",
"[",
"]",
"*",
"TabulateRow",
"{",
"rows",
":=",
"make",
"(",
"[",
"]",
"*",
"TabulateRow",
",",
"len",
"(",
"data",
")",
")",
"\n",
"for",
"index_1",
",",
"arr",
":=",
"range",
"data",
"{",
"row",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"arr",
")",
")",
"\n",
"for",
"index",
",",
"el",
":=",
"range",
"arr",
"{",
"row",
"[",
"index",
"]",
"=",
"strconv",
".",
"FormatInt",
"(",
"el",
",",
"10",
")",
"\n",
"}",
"\n",
"rows",
"[",
"index_1",
"]",
"=",
"&",
"TabulateRow",
"{",
"Elements",
":",
"row",
"}",
"\n",
"}",
"\n",
"return",
"rows",
"\n",
"}"
] | // Create normalized array from ints64 | [
"Create",
"normalized",
"array",
"from",
"ints64"
] | bc555436bfd5d4e93a2dd35b462ce37e067afdda | https://github.com/bndr/gotabulate/blob/bc555436bfd5d4e93a2dd35b462ce37e067afdda/utils.go#L88-L98 |
11,921 | bndr/gotabulate | utils.go | createFromBool | func createFromBool(data [][]bool) []*TabulateRow {
rows := make([]*TabulateRow, len(data))
for index_1, arr := range data {
row := make([]string, len(arr))
for index, el := range arr {
row[index] = strconv.FormatBool(el)
}
rows[index_1] = &TabulateRow{Elements: row}
}
return rows
} | go | func createFromBool(data [][]bool) []*TabulateRow {
rows := make([]*TabulateRow, len(data))
for index_1, arr := range data {
row := make([]string, len(arr))
for index, el := range arr {
row[index] = strconv.FormatBool(el)
}
rows[index_1] = &TabulateRow{Elements: row}
}
return rows
} | [
"func",
"createFromBool",
"(",
"data",
"[",
"]",
"[",
"]",
"bool",
")",
"[",
"]",
"*",
"TabulateRow",
"{",
"rows",
":=",
"make",
"(",
"[",
"]",
"*",
"TabulateRow",
",",
"len",
"(",
"data",
")",
")",
"\n",
"for",
"index_1",
",",
"arr",
":=",
"range",
"data",
"{",
"row",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"arr",
")",
")",
"\n",
"for",
"index",
",",
"el",
":=",
"range",
"arr",
"{",
"row",
"[",
"index",
"]",
"=",
"strconv",
".",
"FormatBool",
"(",
"el",
")",
"\n",
"}",
"\n",
"rows",
"[",
"index_1",
"]",
"=",
"&",
"TabulateRow",
"{",
"Elements",
":",
"row",
"}",
"\n",
"}",
"\n",
"return",
"rows",
"\n",
"}"
] | // Create normalized array from bools | [
"Create",
"normalized",
"array",
"from",
"bools"
] | bc555436bfd5d4e93a2dd35b462ce37e067afdda | https://github.com/bndr/gotabulate/blob/bc555436bfd5d4e93a2dd35b462ce37e067afdda/utils.go#L101-L111 |
11,922 | bndr/gotabulate | utils.go | createFromMapString | func createFromMapString(data map[string][]string) (headers []string, tData []*TabulateRow) {
var dataslice [][]string
for key, value := range data {
headers = append(headers, key)
dataslice = append(dataslice, value)
}
return headers, createFromString(dataslice)
} | go | func createFromMapString(data map[string][]string) (headers []string, tData []*TabulateRow) {
var dataslice [][]string
for key, value := range data {
headers = append(headers, key)
dataslice = append(dataslice, value)
}
return headers, createFromString(dataslice)
} | [
"func",
"createFromMapString",
"(",
"data",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"(",
"headers",
"[",
"]",
"string",
",",
"tData",
"[",
"]",
"*",
"TabulateRow",
")",
"{",
"var",
"dataslice",
"[",
"]",
"[",
"]",
"string",
"\n",
"for",
"key",
",",
"value",
":=",
"range",
"data",
"{",
"headers",
"=",
"append",
"(",
"headers",
",",
"key",
")",
"\n",
"dataslice",
"=",
"append",
"(",
"dataslice",
",",
"value",
")",
"\n",
"}",
"\n",
"return",
"headers",
",",
"createFromString",
"(",
"dataslice",
")",
"\n",
"}"
] | // Create normalized array from Map of strings
// Keys will be used as header | [
"Create",
"normalized",
"array",
"from",
"Map",
"of",
"strings",
"Keys",
"will",
"be",
"used",
"as",
"header"
] | bc555436bfd5d4e93a2dd35b462ce37e067afdda | https://github.com/bndr/gotabulate/blob/bc555436bfd5d4e93a2dd35b462ce37e067afdda/utils.go#L127-L134 |
11,923 | bndr/gotabulate | tabulate.go | padRow | func (t *Tabulate) padRow(arr []string, padding int) []string {
if len(arr) < 1 {
return arr
}
padded := make([]string, len(arr))
for index, el := range arr {
b := createBuffer()
b.Write(" ", padding)
b.Write(el, 1)
b.Write(" ", padding)
padded[index] = b.String()
}
return padded
} | go | func (t *Tabulate) padRow(arr []string, padding int) []string {
if len(arr) < 1 {
return arr
}
padded := make([]string, len(arr))
for index, el := range arr {
b := createBuffer()
b.Write(" ", padding)
b.Write(el, 1)
b.Write(" ", padding)
padded[index] = b.String()
}
return padded
} | [
"func",
"(",
"t",
"*",
"Tabulate",
")",
"padRow",
"(",
"arr",
"[",
"]",
"string",
",",
"padding",
"int",
")",
"[",
"]",
"string",
"{",
"if",
"len",
"(",
"arr",
")",
"<",
"1",
"{",
"return",
"arr",
"\n",
"}",
"\n",
"padded",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"arr",
")",
")",
"\n",
"for",
"index",
",",
"el",
":=",
"range",
"arr",
"{",
"b",
":=",
"createBuffer",
"(",
")",
"\n",
"b",
".",
"Write",
"(",
"\"",
"\"",
",",
"padding",
")",
"\n",
"b",
".",
"Write",
"(",
"el",
",",
"1",
")",
"\n",
"b",
".",
"Write",
"(",
"\"",
"\"",
",",
"padding",
")",
"\n",
"padded",
"[",
"index",
"]",
"=",
"b",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"return",
"padded",
"\n",
"}"
] | // Add padding to each cell | [
"Add",
"padding",
"to",
"each",
"cell"
] | bc555436bfd5d4e93a2dd35b462ce37e067afdda | https://github.com/bndr/gotabulate/blob/bc555436bfd5d4e93a2dd35b462ce37e067afdda/tabulate.go#L114-L127 |
11,924 | bndr/gotabulate | tabulate.go | padCenter | func (t *Tabulate) padCenter(width int, str string) string {
b := createBuffer()
padding := int(math.Ceil(float64((width - runewidth.StringWidth(str))) / 2.0))
b.Write(" ", padding)
b.Write(str, 1)
b.Write(" ", (width - runewidth.StringWidth(b.String())))
return b.String()
} | go | func (t *Tabulate) padCenter(width int, str string) string {
b := createBuffer()
padding := int(math.Ceil(float64((width - runewidth.StringWidth(str))) / 2.0))
b.Write(" ", padding)
b.Write(str, 1)
b.Write(" ", (width - runewidth.StringWidth(b.String())))
return b.String()
} | [
"func",
"(",
"t",
"*",
"Tabulate",
")",
"padCenter",
"(",
"width",
"int",
",",
"str",
"string",
")",
"string",
"{",
"b",
":=",
"createBuffer",
"(",
")",
"\n",
"padding",
":=",
"int",
"(",
"math",
".",
"Ceil",
"(",
"float64",
"(",
"(",
"width",
"-",
"runewidth",
".",
"StringWidth",
"(",
"str",
")",
")",
")",
"/",
"2.0",
")",
")",
"\n",
"b",
".",
"Write",
"(",
"\"",
"\"",
",",
"padding",
")",
"\n",
"b",
".",
"Write",
"(",
"str",
",",
"1",
")",
"\n",
"b",
".",
"Write",
"(",
"\"",
"\"",
",",
"(",
"width",
"-",
"runewidth",
".",
"StringWidth",
"(",
"b",
".",
"String",
"(",
")",
")",
")",
")",
"\n\n",
"return",
"b",
".",
"String",
"(",
")",
"\n",
"}"
] | // Center the element in the cell | [
"Center",
"the",
"element",
"in",
"the",
"cell"
] | bc555436bfd5d4e93a2dd35b462ce37e067afdda | https://github.com/bndr/gotabulate/blob/bc555436bfd5d4e93a2dd35b462ce37e067afdda/tabulate.go#L146-L154 |
11,925 | bndr/gotabulate | tabulate.go | getWidths | func (t *Tabulate) getWidths(headers []string, data []*TabulateRow) []int {
widths := make([]int, len(headers))
current_max := len(t.EmptyVar)
for i := 0; i < len(headers); i++ {
current_max = runewidth.StringWidth(headers[i])
for _, item := range data {
if len(item.Elements) > i && len(widths) > i {
element := item.Elements[i]
strLength := runewidth.StringWidth(element)
if strLength > current_max {
widths[i] = strLength
current_max = strLength
} else {
widths[i] = current_max
}
}
}
}
return widths
} | go | func (t *Tabulate) getWidths(headers []string, data []*TabulateRow) []int {
widths := make([]int, len(headers))
current_max := len(t.EmptyVar)
for i := 0; i < len(headers); i++ {
current_max = runewidth.StringWidth(headers[i])
for _, item := range data {
if len(item.Elements) > i && len(widths) > i {
element := item.Elements[i]
strLength := runewidth.StringWidth(element)
if strLength > current_max {
widths[i] = strLength
current_max = strLength
} else {
widths[i] = current_max
}
}
}
}
return widths
} | [
"func",
"(",
"t",
"*",
"Tabulate",
")",
"getWidths",
"(",
"headers",
"[",
"]",
"string",
",",
"data",
"[",
"]",
"*",
"TabulateRow",
")",
"[",
"]",
"int",
"{",
"widths",
":=",
"make",
"(",
"[",
"]",
"int",
",",
"len",
"(",
"headers",
")",
")",
"\n",
"current_max",
":=",
"len",
"(",
"t",
".",
"EmptyVar",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"headers",
")",
";",
"i",
"++",
"{",
"current_max",
"=",
"runewidth",
".",
"StringWidth",
"(",
"headers",
"[",
"i",
"]",
")",
"\n",
"for",
"_",
",",
"item",
":=",
"range",
"data",
"{",
"if",
"len",
"(",
"item",
".",
"Elements",
")",
">",
"i",
"&&",
"len",
"(",
"widths",
")",
">",
"i",
"{",
"element",
":=",
"item",
".",
"Elements",
"[",
"i",
"]",
"\n",
"strLength",
":=",
"runewidth",
".",
"StringWidth",
"(",
"element",
")",
"\n",
"if",
"strLength",
">",
"current_max",
"{",
"widths",
"[",
"i",
"]",
"=",
"strLength",
"\n",
"current_max",
"=",
"strLength",
"\n",
"}",
"else",
"{",
"widths",
"[",
"i",
"]",
"=",
"current_max",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"widths",
"\n",
"}"
] | // Calculate the max column width for each element | [
"Calculate",
"the",
"max",
"column",
"width",
"for",
"each",
"element"
] | bc555436bfd5d4e93a2dd35b462ce37e067afdda | https://github.com/bndr/gotabulate/blob/bc555436bfd5d4e93a2dd35b462ce37e067afdda/tabulate.go#L316-L336 |
11,926 | bndr/gotabulate | tabulate.go | SetTitle | func (t *Tabulate) SetTitle(title ...string) *Tabulate {
t.Title = title[0]
if len(title) > 1 {
t.TitleAlign = title[1]
}
return t
} | go | func (t *Tabulate) SetTitle(title ...string) *Tabulate {
t.Title = title[0]
if len(title) > 1 {
t.TitleAlign = title[1]
}
return t
} | [
"func",
"(",
"t",
"*",
"Tabulate",
")",
"SetTitle",
"(",
"title",
"...",
"string",
")",
"*",
"Tabulate",
"{",
"t",
".",
"Title",
"=",
"title",
"[",
"0",
"]",
"\n",
"if",
"len",
"(",
"title",
")",
">",
"1",
"{",
"t",
".",
"TitleAlign",
"=",
"title",
"[",
"1",
"]",
"\n",
"}",
"\n\n",
"return",
"t",
"\n",
"}"
] | // SetTitle sets the title of the table can also accept a second string to define an alignment for the title | [
"SetTitle",
"sets",
"the",
"title",
"of",
"the",
"table",
"can",
"also",
"accept",
"a",
"second",
"string",
"to",
"define",
"an",
"alignment",
"for",
"the",
"title"
] | bc555436bfd5d4e93a2dd35b462ce37e067afdda | https://github.com/bndr/gotabulate/blob/bc555436bfd5d4e93a2dd35b462ce37e067afdda/tabulate.go#L339-L347 |
11,927 | bndr/gotabulate | tabulate.go | SetHeaders | func (t *Tabulate) SetHeaders(headers []string) *Tabulate {
t.Headers = headers
return t
} | go | func (t *Tabulate) SetHeaders(headers []string) *Tabulate {
t.Headers = headers
return t
} | [
"func",
"(",
"t",
"*",
"Tabulate",
")",
"SetHeaders",
"(",
"headers",
"[",
"]",
"string",
")",
"*",
"Tabulate",
"{",
"t",
".",
"Headers",
"=",
"headers",
"\n",
"return",
"t",
"\n",
"}"
] | // Set Headers of the table
// If Headers count is less than the data row count, the headers will be padded to the right | [
"Set",
"Headers",
"of",
"the",
"table",
"If",
"Headers",
"count",
"is",
"less",
"than",
"the",
"data",
"row",
"count",
"the",
"headers",
"will",
"be",
"padded",
"to",
"the",
"right"
] | bc555436bfd5d4e93a2dd35b462ce37e067afdda | https://github.com/bndr/gotabulate/blob/bc555436bfd5d4e93a2dd35b462ce37e067afdda/tabulate.go#L351-L354 |
11,928 | bndr/gotabulate | tabulate.go | getAlignFunc | func (t *Tabulate) getAlignFunc() func(int, string) string {
if len(t.Align) < 1 || t.Align == "right" {
return t.padLeft
} else if t.Align == "left" {
return t.padRight
} else {
return t.padCenter
}
} | go | func (t *Tabulate) getAlignFunc() func(int, string) string {
if len(t.Align) < 1 || t.Align == "right" {
return t.padLeft
} else if t.Align == "left" {
return t.padRight
} else {
return t.padCenter
}
} | [
"func",
"(",
"t",
"*",
"Tabulate",
")",
"getAlignFunc",
"(",
")",
"func",
"(",
"int",
",",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"t",
".",
"Align",
")",
"<",
"1",
"||",
"t",
".",
"Align",
"==",
"\"",
"\"",
"{",
"return",
"t",
".",
"padLeft",
"\n",
"}",
"else",
"if",
"t",
".",
"Align",
"==",
"\"",
"\"",
"{",
"return",
"t",
".",
"padRight",
"\n",
"}",
"else",
"{",
"return",
"t",
".",
"padCenter",
"\n",
"}",
"\n",
"}"
] | // Select the padding function based on the align type | [
"Select",
"the",
"padding",
"function",
"based",
"on",
"the",
"align",
"type"
] | bc555436bfd5d4e93a2dd35b462ce37e067afdda | https://github.com/bndr/gotabulate/blob/bc555436bfd5d4e93a2dd35b462ce37e067afdda/tabulate.go#L369-L377 |
11,929 | portworx/kvdb | kvdb_mgr.go | SetInstance | func SetInstance(kvdb Kvdb) error {
if instance == nil {
lock.Lock()
defer lock.Unlock()
if instance == nil {
instance = kvdb
return nil
}
}
return fmt.Errorf("Kvdb instance is already set to %q", instance.String())
} | go | func SetInstance(kvdb Kvdb) error {
if instance == nil {
lock.Lock()
defer lock.Unlock()
if instance == nil {
instance = kvdb
return nil
}
}
return fmt.Errorf("Kvdb instance is already set to %q", instance.String())
} | [
"func",
"SetInstance",
"(",
"kvdb",
"Kvdb",
")",
"error",
"{",
"if",
"instance",
"==",
"nil",
"{",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"instance",
"==",
"nil",
"{",
"instance",
"=",
"kvdb",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"instance",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // SetInstance sets the singleton instance. | [
"SetInstance",
"sets",
"the",
"singleton",
"instance",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/kvdb_mgr.go#L21-L31 |
11,930 | portworx/kvdb | kvdb_mgr.go | New | func New(
name string,
domain string,
machines []string,
options map[string]string,
errorCB FatalErrorCB,
) (Kvdb, error) {
lock.RLock()
defer lock.RUnlock()
if dsInit, exists := datastores[name]; exists {
kvdb, err := dsInit(domain, machines, options, errorCB)
return kvdb, err
}
return nil, ErrNotSupported
} | go | func New(
name string,
domain string,
machines []string,
options map[string]string,
errorCB FatalErrorCB,
) (Kvdb, error) {
lock.RLock()
defer lock.RUnlock()
if dsInit, exists := datastores[name]; exists {
kvdb, err := dsInit(domain, machines, options, errorCB)
return kvdb, err
}
return nil, ErrNotSupported
} | [
"func",
"New",
"(",
"name",
"string",
",",
"domain",
"string",
",",
"machines",
"[",
"]",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"string",
",",
"errorCB",
"FatalErrorCB",
",",
")",
"(",
"Kvdb",
",",
"error",
")",
"{",
"lock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"lock",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"dsInit",
",",
"exists",
":=",
"datastores",
"[",
"name",
"]",
";",
"exists",
"{",
"kvdb",
",",
"err",
":=",
"dsInit",
"(",
"domain",
",",
"machines",
",",
"options",
",",
"errorCB",
")",
"\n",
"return",
"kvdb",
",",
"err",
"\n",
"}",
"\n",
"return",
"nil",
",",
"ErrNotSupported",
"\n",
"}"
] | // New return a new instance of KVDB as specified by datastore name.
// If domain is set all requests to KVDB are prefixed by domain.
// options is interpreted by backend KVDB. | [
"New",
"return",
"a",
"new",
"instance",
"of",
"KVDB",
"as",
"specified",
"by",
"datastore",
"name",
".",
"If",
"domain",
"is",
"set",
"all",
"requests",
"to",
"KVDB",
"are",
"prefixed",
"by",
"domain",
".",
"options",
"is",
"interpreted",
"by",
"backend",
"KVDB",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/kvdb_mgr.go#L36-L51 |
11,931 | portworx/kvdb | kvdb_mgr.go | Register | func Register(name string, dsInit DatastoreInit, dsVersion DatastoreVersion) error {
lock.Lock()
defer lock.Unlock()
if _, exists := datastores[name]; exists {
return fmt.Errorf("Datastore provider %q is already registered", name)
}
datastores[name] = dsInit
if _, exists := datastoreVersions[name]; exists {
return fmt.Errorf("Datastore provider's %q version function already registered", name)
}
datastoreVersions[name] = dsVersion
return nil
} | go | func Register(name string, dsInit DatastoreInit, dsVersion DatastoreVersion) error {
lock.Lock()
defer lock.Unlock()
if _, exists := datastores[name]; exists {
return fmt.Errorf("Datastore provider %q is already registered", name)
}
datastores[name] = dsInit
if _, exists := datastoreVersions[name]; exists {
return fmt.Errorf("Datastore provider's %q version function already registered", name)
}
datastoreVersions[name] = dsVersion
return nil
} | [
"func",
"Register",
"(",
"name",
"string",
",",
"dsInit",
"DatastoreInit",
",",
"dsVersion",
"DatastoreVersion",
")",
"error",
"{",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"exists",
":=",
"datastores",
"[",
"name",
"]",
";",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"datastores",
"[",
"name",
"]",
"=",
"dsInit",
"\n\n",
"if",
"_",
",",
"exists",
":=",
"datastoreVersions",
"[",
"name",
"]",
";",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"datastoreVersions",
"[",
"name",
"]",
"=",
"dsVersion",
"\n",
"return",
"nil",
"\n",
"}"
] | // Register adds specified datastore backend to the list of options. | [
"Register",
"adds",
"specified",
"datastore",
"backend",
"to",
"the",
"list",
"of",
"options",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/kvdb_mgr.go#L54-L67 |
11,932 | portworx/kvdb | kvdb_mgr.go | Version | func Version(name string, url string, kvdbOptions map[string]string) (string, error) {
lock.RLock()
defer lock.RUnlock()
if dsVersion, exists := datastoreVersions[name]; exists {
return dsVersion(url, kvdbOptions)
}
return "", ErrNotSupported
} | go | func Version(name string, url string, kvdbOptions map[string]string) (string, error) {
lock.RLock()
defer lock.RUnlock()
if dsVersion, exists := datastoreVersions[name]; exists {
return dsVersion(url, kvdbOptions)
}
return "", ErrNotSupported
} | [
"func",
"Version",
"(",
"name",
"string",
",",
"url",
"string",
",",
"kvdbOptions",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"lock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"lock",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"dsVersion",
",",
"exists",
":=",
"datastoreVersions",
"[",
"name",
"]",
";",
"exists",
"{",
"return",
"dsVersion",
"(",
"url",
",",
"kvdbOptions",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"ErrNotSupported",
"\n",
"}"
] | // Version returns the supported version for the provided kvdb endpoint. | [
"Version",
"returns",
"the",
"supported",
"version",
"for",
"the",
"provided",
"kvdb",
"endpoint",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/kvdb_mgr.go#L70-L78 |
11,933 | portworx/kvdb | kvdb.go | NewUpdatesCollector | func NewUpdatesCollector(
db Kvdb,
prefix string,
startIndex uint64,
) (UpdatesCollector, error) {
collector := &updatesCollectorImpl{updates: make([]*kvdbUpdate, 0),
startIndex: startIndex}
logrus.Infof("Starting collector watch on %v at %v", prefix, startIndex)
if err := db.WatchTree(prefix, startIndex, nil, collector.watchCb); err != nil {
return nil, err
}
return collector, nil
} | go | func NewUpdatesCollector(
db Kvdb,
prefix string,
startIndex uint64,
) (UpdatesCollector, error) {
collector := &updatesCollectorImpl{updates: make([]*kvdbUpdate, 0),
startIndex: startIndex}
logrus.Infof("Starting collector watch on %v at %v", prefix, startIndex)
if err := db.WatchTree(prefix, startIndex, nil, collector.watchCb); err != nil {
return nil, err
}
return collector, nil
} | [
"func",
"NewUpdatesCollector",
"(",
"db",
"Kvdb",
",",
"prefix",
"string",
",",
"startIndex",
"uint64",
",",
")",
"(",
"UpdatesCollector",
",",
"error",
")",
"{",
"collector",
":=",
"&",
"updatesCollectorImpl",
"{",
"updates",
":",
"make",
"(",
"[",
"]",
"*",
"kvdbUpdate",
",",
"0",
")",
",",
"startIndex",
":",
"startIndex",
"}",
"\n",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"prefix",
",",
"startIndex",
")",
"\n",
"if",
"err",
":=",
"db",
".",
"WatchTree",
"(",
"prefix",
",",
"startIndex",
",",
"nil",
",",
"collector",
".",
"watchCb",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"collector",
",",
"nil",
"\n",
"}"
] | // NewUpdatesCollector creates new Kvdb collector that collects updates
// starting at startIndex + 1 index. | [
"NewUpdatesCollector",
"creates",
"new",
"Kvdb",
"collector",
"that",
"collects",
"updates",
"starting",
"at",
"startIndex",
"+",
"1",
"index",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/kvdb.go#L331-L343 |
11,934 | portworx/kvdb | common/common.go | ToBytes | func ToBytes(val interface{}) ([]byte, error) {
switch val.(type) {
case string:
return []byte(val.(string)), nil
case []byte:
b := make([]byte, len(val.([]byte)))
copy(b, val.([]byte))
return b, nil
default:
return json.Marshal(val)
}
} | go | func ToBytes(val interface{}) ([]byte, error) {
switch val.(type) {
case string:
return []byte(val.(string)), nil
case []byte:
b := make([]byte, len(val.([]byte)))
copy(b, val.([]byte))
return b, nil
default:
return json.Marshal(val)
}
} | [
"func",
"ToBytes",
"(",
"val",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"switch",
"val",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"return",
"[",
"]",
"byte",
"(",
"val",
".",
"(",
"string",
")",
")",
",",
"nil",
"\n",
"case",
"[",
"]",
"byte",
":",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"val",
".",
"(",
"[",
"]",
"byte",
")",
")",
")",
"\n",
"copy",
"(",
"b",
",",
"val",
".",
"(",
"[",
"]",
"byte",
")",
")",
"\n",
"return",
"b",
",",
"nil",
"\n",
"default",
":",
"return",
"json",
".",
"Marshal",
"(",
"val",
")",
"\n",
"}",
"\n",
"}"
] | // ToBytes converts to value to a byte slice. | [
"ToBytes",
"converts",
"to",
"value",
"to",
"a",
"byte",
"slice",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/common/common.go#L19-L30 |
11,935 | portworx/kvdb | common/common.go | SetFatalCb | func (b *BaseKvdb) SetFatalCb(f kvdb.FatalErrorCB) {
b.lock.Lock()
defer b.lock.Unlock()
b.FatalCb = f
} | go | func (b *BaseKvdb) SetFatalCb(f kvdb.FatalErrorCB) {
b.lock.Lock()
defer b.lock.Unlock()
b.FatalCb = f
} | [
"func",
"(",
"b",
"*",
"BaseKvdb",
")",
"SetFatalCb",
"(",
"f",
"kvdb",
".",
"FatalErrorCB",
")",
"{",
"b",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"b",
".",
"FatalCb",
"=",
"f",
"\n",
"}"
] | // SetFatalCb callback is invoked when an unrecoverable KVDB error happens. | [
"SetFatalCb",
"callback",
"is",
"invoked",
"when",
"an",
"unrecoverable",
"KVDB",
"error",
"happens",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/common/common.go#L43-L47 |
11,936 | portworx/kvdb | common/common.go | SetLockTimeout | func (b *BaseKvdb) SetLockTimeout(timeout time.Duration) {
b.lock.Lock()
defer b.lock.Unlock()
logrus.Infof("Setting lock timeout to: %v", timeout)
b.LockTimeout = timeout
} | go | func (b *BaseKvdb) SetLockTimeout(timeout time.Duration) {
b.lock.Lock()
defer b.lock.Unlock()
logrus.Infof("Setting lock timeout to: %v", timeout)
b.LockTimeout = timeout
} | [
"func",
"(",
"b",
"*",
"BaseKvdb",
")",
"SetLockTimeout",
"(",
"timeout",
"time",
".",
"Duration",
")",
"{",
"b",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"timeout",
")",
"\n",
"b",
".",
"LockTimeout",
"=",
"timeout",
"\n",
"}"
] | // SetLockTimeout has property such that if the lock is held past this duration,
// then a configured fatal callback is called. | [
"SetLockTimeout",
"has",
"property",
"such",
"that",
"if",
"the",
"lock",
"is",
"held",
"past",
"this",
"duration",
"then",
"a",
"configured",
"fatal",
"callback",
"is",
"called",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/common/common.go#L51-L56 |
11,937 | portworx/kvdb | common/common.go | CheckLockTimeout | func (b *BaseKvdb) CheckLockTimeout(
key string,
startTime time.Time,
lockTimeout time.Duration,
) {
b.lock.Lock()
defer b.lock.Unlock()
if lockTimeout > 0 && time.Since(startTime) > lockTimeout {
b.lockTimedout(key)
}
} | go | func (b *BaseKvdb) CheckLockTimeout(
key string,
startTime time.Time,
lockTimeout time.Duration,
) {
b.lock.Lock()
defer b.lock.Unlock()
if lockTimeout > 0 && time.Since(startTime) > lockTimeout {
b.lockTimedout(key)
}
} | [
"func",
"(",
"b",
"*",
"BaseKvdb",
")",
"CheckLockTimeout",
"(",
"key",
"string",
",",
"startTime",
"time",
".",
"Time",
",",
"lockTimeout",
"time",
".",
"Duration",
",",
")",
"{",
"b",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"lockTimeout",
">",
"0",
"&&",
"time",
".",
"Since",
"(",
"startTime",
")",
">",
"lockTimeout",
"{",
"b",
".",
"lockTimedout",
"(",
"key",
")",
"\n",
"}",
"\n",
"}"
] | // CheckLockTimeout checks lock timeout. | [
"CheckLockTimeout",
"checks",
"lock",
"timeout",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/common/common.go#L59-L69 |
11,938 | portworx/kvdb | common/common.go | GetLockTimeout | func (b *BaseKvdb) GetLockTimeout() time.Duration {
b.lock.Lock()
defer b.lock.Unlock()
return b.LockTimeout
} | go | func (b *BaseKvdb) GetLockTimeout() time.Duration {
b.lock.Lock()
defer b.lock.Unlock()
return b.LockTimeout
} | [
"func",
"(",
"b",
"*",
"BaseKvdb",
")",
"GetLockTimeout",
"(",
")",
"time",
".",
"Duration",
"{",
"b",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"b",
".",
"LockTimeout",
"\n",
"}"
] | // GetLockTimeout gets lock timeout. | [
"GetLockTimeout",
"gets",
"lock",
"timeout",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/common/common.go#L72-L76 |
11,939 | portworx/kvdb | common/common.go | LockTimedout | func (b *BaseKvdb) LockTimedout(key string) {
b.lock.Lock()
defer b.lock.Unlock()
b.lockTimedout(key)
} | go | func (b *BaseKvdb) LockTimedout(key string) {
b.lock.Lock()
defer b.lock.Unlock()
b.lockTimedout(key)
} | [
"func",
"(",
"b",
"*",
"BaseKvdb",
")",
"LockTimedout",
"(",
"key",
"string",
")",
"{",
"b",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"b",
".",
"lockTimedout",
"(",
"key",
")",
"\n",
"}"
] | // LockTimedout does lock timedout. | [
"LockTimedout",
"does",
"lock",
"timedout",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/common/common.go#L79-L83 |
11,940 | portworx/kvdb | common/common.go | SerializeAll | func (b *BaseKvdb) SerializeAll(kvps kvdb.KVPairs) ([]byte, error) {
out, err := json.Marshal(kvps)
if err != nil {
return nil, err
}
return out, nil
} | go | func (b *BaseKvdb) SerializeAll(kvps kvdb.KVPairs) ([]byte, error) {
out, err := json.Marshal(kvps)
if err != nil {
return nil, err
}
return out, nil
} | [
"func",
"(",
"b",
"*",
"BaseKvdb",
")",
"SerializeAll",
"(",
"kvps",
"kvdb",
".",
"KVPairs",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"out",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"kvps",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // SerializeAll Serializes all key value pairs to a byte array. | [
"SerializeAll",
"Serializes",
"all",
"key",
"value",
"pairs",
"to",
"a",
"byte",
"array",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/common/common.go#L91-L97 |
11,941 | portworx/kvdb | common/common.go | DeserializeAll | func (b *BaseKvdb) DeserializeAll(out []byte) (kvdb.KVPairs, error) {
var kvps kvdb.KVPairs
if err := json.Unmarshal(out, &kvps); err != nil {
return nil, err
}
return kvps, nil
} | go | func (b *BaseKvdb) DeserializeAll(out []byte) (kvdb.KVPairs, error) {
var kvps kvdb.KVPairs
if err := json.Unmarshal(out, &kvps); err != nil {
return nil, err
}
return kvps, nil
} | [
"func",
"(",
"b",
"*",
"BaseKvdb",
")",
"DeserializeAll",
"(",
"out",
"[",
"]",
"byte",
")",
"(",
"kvdb",
".",
"KVPairs",
",",
"error",
")",
"{",
"var",
"kvps",
"kvdb",
".",
"KVPairs",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"out",
",",
"&",
"kvps",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"kvps",
",",
"nil",
"\n",
"}"
] | // DeserializeAll Unmarshals a byte stream created from serializeAll into the kvdb tree. | [
"DeserializeAll",
"Unmarshals",
"a",
"byte",
"stream",
"created",
"from",
"serializeAll",
"into",
"the",
"kvdb",
"tree",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/common/common.go#L100-L106 |
11,942 | portworx/kvdb | common/common.go | NewWatchUpdateQueue | func NewWatchUpdateQueue() WatchUpdateQueue {
mtx := &sync.Mutex{}
return &watchQueue{
m: mtx,
cv: sync.NewCond(mtx),
updates: list.New()}
} | go | func NewWatchUpdateQueue() WatchUpdateQueue {
mtx := &sync.Mutex{}
return &watchQueue{
m: mtx,
cv: sync.NewCond(mtx),
updates: list.New()}
} | [
"func",
"NewWatchUpdateQueue",
"(",
")",
"WatchUpdateQueue",
"{",
"mtx",
":=",
"&",
"sync",
".",
"Mutex",
"{",
"}",
"\n",
"return",
"&",
"watchQueue",
"{",
"m",
":",
"mtx",
",",
"cv",
":",
"sync",
".",
"NewCond",
"(",
"mtx",
")",
",",
"updates",
":",
"list",
".",
"New",
"(",
")",
"}",
"\n",
"}"
] | // NewWatchUpdateQueue returns WatchUpdateQueue | [
"NewWatchUpdateQueue",
"returns",
"WatchUpdateQueue"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/common/common.go#L138-L144 |
11,943 | portworx/kvdb | common/common.go | Dequeue | func (w *watchQueue) Dequeue() (string, *kvdb.KVPair, error) {
w.m.Lock()
for {
if w.updates.Len() > 0 {
el := w.updates.Front()
w.updates.Remove(el)
w.m.Unlock()
update := el.Value.(*watchUpdate)
return update.key, update.kvp, update.err
}
w.cv.Wait()
}
} | go | func (w *watchQueue) Dequeue() (string, *kvdb.KVPair, error) {
w.m.Lock()
for {
if w.updates.Len() > 0 {
el := w.updates.Front()
w.updates.Remove(el)
w.m.Unlock()
update := el.Value.(*watchUpdate)
return update.key, update.kvp, update.err
}
w.cv.Wait()
}
} | [
"func",
"(",
"w",
"*",
"watchQueue",
")",
"Dequeue",
"(",
")",
"(",
"string",
",",
"*",
"kvdb",
".",
"KVPair",
",",
"error",
")",
"{",
"w",
".",
"m",
".",
"Lock",
"(",
")",
"\n",
"for",
"{",
"if",
"w",
".",
"updates",
".",
"Len",
"(",
")",
">",
"0",
"{",
"el",
":=",
"w",
".",
"updates",
".",
"Front",
"(",
")",
"\n",
"w",
".",
"updates",
".",
"Remove",
"(",
"el",
")",
"\n",
"w",
".",
"m",
".",
"Unlock",
"(",
")",
"\n",
"update",
":=",
"el",
".",
"Value",
".",
"(",
"*",
"watchUpdate",
")",
"\n",
"return",
"update",
".",
"key",
",",
"update",
".",
"kvp",
",",
"update",
".",
"err",
"\n",
"}",
"\n",
"w",
".",
"cv",
".",
"Wait",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Dequeue removes from queue. | [
"Dequeue",
"removes",
"from",
"queue",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/common/common.go#L147-L159 |
11,944 | portworx/kvdb | common/common.go | PrunePrefixes | func PrunePrefixes(prefixes []string) []string {
prunedPrefixes := []string{}
for i := 0; i < len(prefixes); i++ {
foundPrefix := false
for j := 0; j < len(prefixes); j++ {
if i == j {
continue
}
if strings.HasPrefix(prefixes[i], prefixes[j]) {
foundPrefix = true
}
}
if !foundPrefix {
prunedPrefixes = append(prunedPrefixes, prefixes[i])
}
}
return prunedPrefixes
} | go | func PrunePrefixes(prefixes []string) []string {
prunedPrefixes := []string{}
for i := 0; i < len(prefixes); i++ {
foundPrefix := false
for j := 0; j < len(prefixes); j++ {
if i == j {
continue
}
if strings.HasPrefix(prefixes[i], prefixes[j]) {
foundPrefix = true
}
}
if !foundPrefix {
prunedPrefixes = append(prunedPrefixes, prefixes[i])
}
}
return prunedPrefixes
} | [
"func",
"PrunePrefixes",
"(",
"prefixes",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"prunedPrefixes",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"prefixes",
")",
";",
"i",
"++",
"{",
"foundPrefix",
":=",
"false",
"\n",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"len",
"(",
"prefixes",
")",
";",
"j",
"++",
"{",
"if",
"i",
"==",
"j",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"prefixes",
"[",
"i",
"]",
",",
"prefixes",
"[",
"j",
"]",
")",
"{",
"foundPrefix",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"foundPrefix",
"{",
"prunedPrefixes",
"=",
"append",
"(",
"prunedPrefixes",
",",
"prefixes",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"prunedPrefixes",
"\n",
"}"
] | // PrunePrefixes will return all the top level prefixes from a given list
// so that any enumerate on these prefixes will not end up returning duplicate keys | [
"PrunePrefixes",
"will",
"return",
"all",
"the",
"top",
"level",
"prefixes",
"from",
"a",
"given",
"list",
"so",
"that",
"any",
"enumerate",
"on",
"these",
"prefixes",
"will",
"not",
"end",
"up",
"returning",
"duplicate",
"keys"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/common/common.go#L171-L188 |
11,945 | portworx/kvdb | zookeeper/kv_zookeeper.go | New | func New(
domain string,
servers []string,
options map[string]string,
fatalErrorCb kvdb.FatalErrorCB,
) (kvdb.Kvdb, error) {
return newClient(domain, servers, options, fatalErrorCb)
} | go | func New(
domain string,
servers []string,
options map[string]string,
fatalErrorCb kvdb.FatalErrorCB,
) (kvdb.Kvdb, error) {
return newClient(domain, servers, options, fatalErrorCb)
} | [
"func",
"New",
"(",
"domain",
"string",
",",
"servers",
"[",
"]",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"string",
",",
"fatalErrorCb",
"kvdb",
".",
"FatalErrorCB",
",",
")",
"(",
"kvdb",
".",
"Kvdb",
",",
"error",
")",
"{",
"return",
"newClient",
"(",
"domain",
",",
"servers",
",",
"options",
",",
"fatalErrorCb",
")",
"\n",
"}"
] | // New constructs a new kvdb.Kvdb with zookeeper implementation | [
"New",
"constructs",
"a",
"new",
"kvdb",
".",
"Kvdb",
"with",
"zookeeper",
"implementation"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/zookeeper/kv_zookeeper.go#L59-L66 |
11,946 | portworx/kvdb | zookeeper/kv_zookeeper.go | Version | func Version(url string, kvdbOptions map[string]string) (string, error) {
return kvdb.ZookeeperVersion1, nil
} | go | func Version(url string, kvdbOptions map[string]string) (string, error) {
return kvdb.ZookeeperVersion1, nil
} | [
"func",
"Version",
"(",
"url",
"string",
",",
"kvdbOptions",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"kvdb",
".",
"ZookeeperVersion1",
",",
"nil",
"\n",
"}"
] | // Version returns the supported version of the zookeeper implementation | [
"Version",
"returns",
"the",
"supported",
"version",
"of",
"the",
"zookeeper",
"implementation"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/zookeeper/kv_zookeeper.go#L69-L71 |
11,947 | portworx/kvdb | zookeeper/kv_zookeeper.go | newClient | func newClient(
domain string,
servers []string,
options map[string]string,
fatalErrorCb kvdb.FatalErrorCB,
) (*zookeeperKV, error) {
if len(servers) == 0 {
servers = defaultServers
}
if domain != "" {
domain = normalize(domain)
}
zkClient, _, err := zk.Connect(servers, defaultSessionTimeout)
if err != nil {
return nil, err
}
return &zookeeperKV{
BaseKvdb: common.BaseKvdb{
FatalCb: fatalErrorCb,
},
client: zkClient,
domain: domain,
Controller: kvdb.ControllerNotSupported,
}, nil
} | go | func newClient(
domain string,
servers []string,
options map[string]string,
fatalErrorCb kvdb.FatalErrorCB,
) (*zookeeperKV, error) {
if len(servers) == 0 {
servers = defaultServers
}
if domain != "" {
domain = normalize(domain)
}
zkClient, _, err := zk.Connect(servers, defaultSessionTimeout)
if err != nil {
return nil, err
}
return &zookeeperKV{
BaseKvdb: common.BaseKvdb{
FatalCb: fatalErrorCb,
},
client: zkClient,
domain: domain,
Controller: kvdb.ControllerNotSupported,
}, nil
} | [
"func",
"newClient",
"(",
"domain",
"string",
",",
"servers",
"[",
"]",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"string",
",",
"fatalErrorCb",
"kvdb",
".",
"FatalErrorCB",
",",
")",
"(",
"*",
"zookeeperKV",
",",
"error",
")",
"{",
"if",
"len",
"(",
"servers",
")",
"==",
"0",
"{",
"servers",
"=",
"defaultServers",
"\n",
"}",
"\n\n",
"if",
"domain",
"!=",
"\"",
"\"",
"{",
"domain",
"=",
"normalize",
"(",
"domain",
")",
"\n",
"}",
"\n\n",
"zkClient",
",",
"_",
",",
"err",
":=",
"zk",
".",
"Connect",
"(",
"servers",
",",
"defaultSessionTimeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"zookeeperKV",
"{",
"BaseKvdb",
":",
"common",
".",
"BaseKvdb",
"{",
"FatalCb",
":",
"fatalErrorCb",
",",
"}",
",",
"client",
":",
"zkClient",
",",
"domain",
":",
"domain",
",",
"Controller",
":",
"kvdb",
".",
"ControllerNotSupported",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Used to create a zookeeper client for testing | [
"Used",
"to",
"create",
"a",
"zookeeper",
"client",
"for",
"testing"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/zookeeper/kv_zookeeper.go#L74-L101 |
11,948 | portworx/kvdb | zookeeper/kv_zookeeper.go | Create | func (z *zookeeperKV) Create(
key string,
val interface{},
ttl uint64,
) (*kvdb.KVPair, error) {
if ttl != 0 {
return nil, kvdb.ErrTTLNotSupported
}
bval, err := common.ToBytes(val)
if err != nil {
return nil, err
}
if len(bval) == 0 {
return nil, kvdb.ErrEmptyValue
}
err = z.createFullPath(key, false)
if err == zk.ErrNodeExists {
return nil, kvdb.ErrExist
} else if err != nil {
return nil, err
}
key = z.domain + normalize(key)
meta, err := z.client.Set(key, bval, -1)
if err != nil {
return nil, err
}
return z.resultToKvPair(key, bval, "create", meta), nil
} | go | func (z *zookeeperKV) Create(
key string,
val interface{},
ttl uint64,
) (*kvdb.KVPair, error) {
if ttl != 0 {
return nil, kvdb.ErrTTLNotSupported
}
bval, err := common.ToBytes(val)
if err != nil {
return nil, err
}
if len(bval) == 0 {
return nil, kvdb.ErrEmptyValue
}
err = z.createFullPath(key, false)
if err == zk.ErrNodeExists {
return nil, kvdb.ErrExist
} else if err != nil {
return nil, err
}
key = z.domain + normalize(key)
meta, err := z.client.Set(key, bval, -1)
if err != nil {
return nil, err
}
return z.resultToKvPair(key, bval, "create", meta), nil
} | [
"func",
"(",
"z",
"*",
"zookeeperKV",
")",
"Create",
"(",
"key",
"string",
",",
"val",
"interface",
"{",
"}",
",",
"ttl",
"uint64",
",",
")",
"(",
"*",
"kvdb",
".",
"KVPair",
",",
"error",
")",
"{",
"if",
"ttl",
"!=",
"0",
"{",
"return",
"nil",
",",
"kvdb",
".",
"ErrTTLNotSupported",
"\n",
"}",
"\n\n",
"bval",
",",
"err",
":=",
"common",
".",
"ToBytes",
"(",
"val",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"bval",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"kvdb",
".",
"ErrEmptyValue",
"\n",
"}",
"\n\n",
"err",
"=",
"z",
".",
"createFullPath",
"(",
"key",
",",
"false",
")",
"\n",
"if",
"err",
"==",
"zk",
".",
"ErrNodeExists",
"{",
"return",
"nil",
",",
"kvdb",
".",
"ErrExist",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"key",
"=",
"z",
".",
"domain",
"+",
"normalize",
"(",
"key",
")",
"\n",
"meta",
",",
"err",
":=",
"z",
".",
"client",
".",
"Set",
"(",
"key",
",",
"bval",
",",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"z",
".",
"resultToKvPair",
"(",
"key",
",",
"bval",
",",
"\"",
"\"",
",",
"meta",
")",
",",
"nil",
"\n",
"}"
] | // Creates a zk node only if it does not exist. | [
"Creates",
"a",
"zk",
"node",
"only",
"if",
"it",
"does",
"not",
"exist",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/zookeeper/kv_zookeeper.go#L196-L226 |
11,949 | portworx/kvdb | zookeeper/kv_zookeeper.go | createFullPath | func (z *zookeeperKV) createFullPath(key string, ephemeral bool) error {
key = z.domain + normalize(key)
path := strings.Split(strings.TrimPrefix(key, "/"), "/")
for i := 1; i <= len(path); i++ {
newPath := "/" + strings.Join(path[:i], "/")
if i == len(path) {
flags := int32(0)
if ephemeral {
flags = zk.FlagEphemeral
}
_, err := z.client.Create(newPath, []byte{},
flags, zk.WorldACL(zk.PermAll))
return err
}
_, err := z.client.Create(newPath, []byte{},
0, zk.WorldACL(zk.PermAll))
if err != nil && err != zk.ErrNodeExists {
return err
}
}
return nil
} | go | func (z *zookeeperKV) createFullPath(key string, ephemeral bool) error {
key = z.domain + normalize(key)
path := strings.Split(strings.TrimPrefix(key, "/"), "/")
for i := 1; i <= len(path); i++ {
newPath := "/" + strings.Join(path[:i], "/")
if i == len(path) {
flags := int32(0)
if ephemeral {
flags = zk.FlagEphemeral
}
_, err := z.client.Create(newPath, []byte{},
flags, zk.WorldACL(zk.PermAll))
return err
}
_, err := z.client.Create(newPath, []byte{},
0, zk.WorldACL(zk.PermAll))
if err != nil && err != zk.ErrNodeExists {
return err
}
}
return nil
} | [
"func",
"(",
"z",
"*",
"zookeeperKV",
")",
"createFullPath",
"(",
"key",
"string",
",",
"ephemeral",
"bool",
")",
"error",
"{",
"key",
"=",
"z",
".",
"domain",
"+",
"normalize",
"(",
"key",
")",
"\n",
"path",
":=",
"strings",
".",
"Split",
"(",
"strings",
".",
"TrimPrefix",
"(",
"key",
",",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n\n",
"for",
"i",
":=",
"1",
";",
"i",
"<=",
"len",
"(",
"path",
")",
";",
"i",
"++",
"{",
"newPath",
":=",
"\"",
"\"",
"+",
"strings",
".",
"Join",
"(",
"path",
"[",
":",
"i",
"]",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"i",
"==",
"len",
"(",
"path",
")",
"{",
"flags",
":=",
"int32",
"(",
"0",
")",
"\n",
"if",
"ephemeral",
"{",
"flags",
"=",
"zk",
".",
"FlagEphemeral",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"z",
".",
"client",
".",
"Create",
"(",
"newPath",
",",
"[",
"]",
"byte",
"{",
"}",
",",
"flags",
",",
"zk",
".",
"WorldACL",
"(",
"zk",
".",
"PermAll",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"_",
",",
"err",
":=",
"z",
".",
"client",
".",
"Create",
"(",
"newPath",
",",
"[",
"]",
"byte",
"{",
"}",
",",
"0",
",",
"zk",
".",
"WorldACL",
"(",
"zk",
".",
"PermAll",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"zk",
".",
"ErrNodeExists",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // createFullPath creates the entire path for a directory | [
"createFullPath",
"creates",
"the",
"entire",
"path",
"for",
"a",
"directory"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/zookeeper/kv_zookeeper.go#L586-L610 |
11,950 | portworx/kvdb | zookeeper/kv_zookeeper.go | exists | func (z *zookeeperKV) exists(key string) (bool, error) {
key = z.domain + normalize(key)
exists, _, err := z.client.Exists(key)
if err != nil {
return false, err
}
return exists, nil
} | go | func (z *zookeeperKV) exists(key string) (bool, error) {
key = z.domain + normalize(key)
exists, _, err := z.client.Exists(key)
if err != nil {
return false, err
}
return exists, nil
} | [
"func",
"(",
"z",
"*",
"zookeeperKV",
")",
"exists",
"(",
"key",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"key",
"=",
"z",
".",
"domain",
"+",
"normalize",
"(",
"key",
")",
"\n",
"exists",
",",
"_",
",",
"err",
":=",
"z",
".",
"client",
".",
"Exists",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"exists",
",",
"nil",
"\n",
"}"
] | // exists checks if the key exists | [
"exists",
"checks",
"if",
"the",
"key",
"exists"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/zookeeper/kv_zookeeper.go#L613-L620 |
11,951 | portworx/kvdb | consul/kv_consul.go | shuffle | func shuffle(input []string) []string {
tmp := make([]string, len(input))
r := rand.New(rand.NewSource(time.Now().Unix()))
for i, j := range r.Perm(len(input)) {
tmp[i] = input[j]
}
return tmp
} | go | func shuffle(input []string) []string {
tmp := make([]string, len(input))
r := rand.New(rand.NewSource(time.Now().Unix()))
for i, j := range r.Perm(len(input)) {
tmp[i] = input[j]
}
return tmp
} | [
"func",
"shuffle",
"(",
"input",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"tmp",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"input",
")",
")",
"\n",
"r",
":=",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
")",
")",
"\n",
"for",
"i",
",",
"j",
":=",
"range",
"r",
".",
"Perm",
"(",
"len",
"(",
"input",
")",
")",
"{",
"tmp",
"[",
"i",
"]",
"=",
"input",
"[",
"j",
"]",
"\n",
"}",
"\n",
"return",
"tmp",
"\n",
"}"
] | // shuffle list of input strings | [
"shuffle",
"list",
"of",
"input",
"strings"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/consul/kv_consul.go#L100-L107 |
11,952 | portworx/kvdb | consul/kv_consul.go | New | func New(
domain string,
servers []string,
options map[string]string,
fatalErrorCb kvdb.FatalErrorCB,
) (kvdb.Kvdb, error) {
// check for unsupported options
for _, opt := range []string{kvdb.UsernameKey, kvdb.PasswordKey, kvdb.CAFileKey} {
// Check if username provided
if _, ok := options[opt]; ok {
return nil, kvdb.ErrAuthNotSupported
}
}
if domain != "" && !strings.HasSuffix(domain, "/") {
domain = domain + "/"
}
hasHttpsPrefix := false
for _, machine := range servers {
if strings.HasPrefix(machine, "https://") {
hasHttpsPrefix = true
break
}
}
if options == nil {
options = make(map[string]string)
}
if hasHttpsPrefix {
options[kvdb.TransportScheme] = "https"
} else {
options[kvdb.TransportScheme] = "http"
}
connParams := connectionParams{
machines: shuffle(servers),
options: options,
fatalErrorCb: fatalErrorCb,
}
if len(connParams.machines) == 0 {
connParams.machines = defaultMachines
}
var err error
var config *api.Config
var client *api.Client
for _, machine := range connParams.machines {
if strings.HasPrefix(machine, "http://") {
machine = strings.TrimPrefix(machine, "http://")
} else if strings.HasPrefix(machine, "https://") {
machine = strings.TrimPrefix(machine, "https://")
}
if config, client, err = newKvClient(machine, connParams); err == nil {
return &consulKV{
BaseKvdb: common.BaseKvdb{FatalCb: connParams.fatalErrorCb},
domain: domain,
Controller: kvdb.ControllerNotSupported,
client: newConsulClient(config, client, refreshDelay, connParams),
}, nil
}
}
return nil, err
} | go | func New(
domain string,
servers []string,
options map[string]string,
fatalErrorCb kvdb.FatalErrorCB,
) (kvdb.Kvdb, error) {
// check for unsupported options
for _, opt := range []string{kvdb.UsernameKey, kvdb.PasswordKey, kvdb.CAFileKey} {
// Check if username provided
if _, ok := options[opt]; ok {
return nil, kvdb.ErrAuthNotSupported
}
}
if domain != "" && !strings.HasSuffix(domain, "/") {
domain = domain + "/"
}
hasHttpsPrefix := false
for _, machine := range servers {
if strings.HasPrefix(machine, "https://") {
hasHttpsPrefix = true
break
}
}
if options == nil {
options = make(map[string]string)
}
if hasHttpsPrefix {
options[kvdb.TransportScheme] = "https"
} else {
options[kvdb.TransportScheme] = "http"
}
connParams := connectionParams{
machines: shuffle(servers),
options: options,
fatalErrorCb: fatalErrorCb,
}
if len(connParams.machines) == 0 {
connParams.machines = defaultMachines
}
var err error
var config *api.Config
var client *api.Client
for _, machine := range connParams.machines {
if strings.HasPrefix(machine, "http://") {
machine = strings.TrimPrefix(machine, "http://")
} else if strings.HasPrefix(machine, "https://") {
machine = strings.TrimPrefix(machine, "https://")
}
if config, client, err = newKvClient(machine, connParams); err == nil {
return &consulKV{
BaseKvdb: common.BaseKvdb{FatalCb: connParams.fatalErrorCb},
domain: domain,
Controller: kvdb.ControllerNotSupported,
client: newConsulClient(config, client, refreshDelay, connParams),
}, nil
}
}
return nil, err
} | [
"func",
"New",
"(",
"domain",
"string",
",",
"servers",
"[",
"]",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"string",
",",
"fatalErrorCb",
"kvdb",
".",
"FatalErrorCB",
",",
")",
"(",
"kvdb",
".",
"Kvdb",
",",
"error",
")",
"{",
"// check for unsupported options",
"for",
"_",
",",
"opt",
":=",
"range",
"[",
"]",
"string",
"{",
"kvdb",
".",
"UsernameKey",
",",
"kvdb",
".",
"PasswordKey",
",",
"kvdb",
".",
"CAFileKey",
"}",
"{",
"// Check if username provided",
"if",
"_",
",",
"ok",
":=",
"options",
"[",
"opt",
"]",
";",
"ok",
"{",
"return",
"nil",
",",
"kvdb",
".",
"ErrAuthNotSupported",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"domain",
"!=",
"\"",
"\"",
"&&",
"!",
"strings",
".",
"HasSuffix",
"(",
"domain",
",",
"\"",
"\"",
")",
"{",
"domain",
"=",
"domain",
"+",
"\"",
"\"",
"\n",
"}",
"\n\n",
"hasHttpsPrefix",
":=",
"false",
"\n",
"for",
"_",
",",
"machine",
":=",
"range",
"servers",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"machine",
",",
"\"",
"\"",
")",
"{",
"hasHttpsPrefix",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"options",
"==",
"nil",
"{",
"options",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"}",
"\n\n",
"if",
"hasHttpsPrefix",
"{",
"options",
"[",
"kvdb",
".",
"TransportScheme",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"options",
"[",
"kvdb",
".",
"TransportScheme",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"connParams",
":=",
"connectionParams",
"{",
"machines",
":",
"shuffle",
"(",
"servers",
")",
",",
"options",
":",
"options",
",",
"fatalErrorCb",
":",
"fatalErrorCb",
",",
"}",
"\n",
"if",
"len",
"(",
"connParams",
".",
"machines",
")",
"==",
"0",
"{",
"connParams",
".",
"machines",
"=",
"defaultMachines",
"\n",
"}",
"\n\n",
"var",
"err",
"error",
"\n",
"var",
"config",
"*",
"api",
".",
"Config",
"\n",
"var",
"client",
"*",
"api",
".",
"Client",
"\n\n",
"for",
"_",
",",
"machine",
":=",
"range",
"connParams",
".",
"machines",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"machine",
",",
"\"",
"\"",
")",
"{",
"machine",
"=",
"strings",
".",
"TrimPrefix",
"(",
"machine",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"machine",
",",
"\"",
"\"",
")",
"{",
"machine",
"=",
"strings",
".",
"TrimPrefix",
"(",
"machine",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"config",
",",
"client",
",",
"err",
"=",
"newKvClient",
"(",
"machine",
",",
"connParams",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"&",
"consulKV",
"{",
"BaseKvdb",
":",
"common",
".",
"BaseKvdb",
"{",
"FatalCb",
":",
"connParams",
".",
"fatalErrorCb",
"}",
",",
"domain",
":",
"domain",
",",
"Controller",
":",
"kvdb",
".",
"ControllerNotSupported",
",",
"client",
":",
"newConsulClient",
"(",
"config",
",",
"client",
",",
"refreshDelay",
",",
"connParams",
")",
",",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}"
] | // New constructs a new kvdb.Kvdb given a list of end points to conntect to. | [
"New",
"constructs",
"a",
"new",
"kvdb",
".",
"Kvdb",
"given",
"a",
"list",
"of",
"end",
"points",
"to",
"conntect",
"to",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/consul/kv_consul.go#L110-L176 |
11,953 | portworx/kvdb | consul/kv_consul.go | Version | func Version(url string, kvdbOptions map[string]string) (string, error) {
// Currently we support only v1
return kvdb.ConsulVersion1, nil
} | go | func Version(url string, kvdbOptions map[string]string) (string, error) {
// Currently we support only v1
return kvdb.ConsulVersion1, nil
} | [
"func",
"Version",
"(",
"url",
"string",
",",
"kvdbOptions",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Currently we support only v1",
"return",
"kvdb",
".",
"ConsulVersion1",
",",
"nil",
"\n",
"}"
] | // Version returns the supported version for consul api | [
"Version",
"returns",
"the",
"supported",
"version",
"for",
"consul",
"api"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/consul/kv_consul.go#L179-L182 |
11,954 | portworx/kvdb | consul/kv_consul.go | getActiveSession | func (kv *consulKV) getActiveSession(key string) (string, error) {
pair, _, err := kv.client.Get(key, nil)
if err != nil {
return "", err
}
if pair != nil && pair.Session != "" {
return pair.Session, nil
}
return "", nil
} | go | func (kv *consulKV) getActiveSession(key string) (string, error) {
pair, _, err := kv.client.Get(key, nil)
if err != nil {
return "", err
}
if pair != nil && pair.Session != "" {
return pair.Session, nil
}
return "", nil
} | [
"func",
"(",
"kv",
"*",
"consulKV",
")",
"getActiveSession",
"(",
"key",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"pair",
",",
"_",
",",
"err",
":=",
"kv",
".",
"client",
".",
"Get",
"(",
"key",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"pair",
"!=",
"nil",
"&&",
"pair",
".",
"Session",
"!=",
"\"",
"\"",
"{",
"return",
"pair",
".",
"Session",
",",
"nil",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}"
] | // getActiveSession checks if the key already has
// a session attached | [
"getActiveSession",
"checks",
"if",
"the",
"key",
"already",
"has",
"a",
"session",
"attached"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/consul/kv_consul.go#L1206-L1215 |
11,955 | portworx/kvdb | consul/client.go | newConsulClient | func newConsulClient(config *api.Config,
client *api.Client,
reconnectDelay time.Duration,
p connectionParams,
) consulClient {
c := &consulClientImpl{
conn: &consulConnection{
config: config,
client: client,
once: new(sync.Once)},
connParams: p,
reconnectDelay: reconnectDelay,
}
c.maxRetries = 12 /// with default 5 second delay this would be a minute
return c
} | go | func newConsulClient(config *api.Config,
client *api.Client,
reconnectDelay time.Duration,
p connectionParams,
) consulClient {
c := &consulClientImpl{
conn: &consulConnection{
config: config,
client: client,
once: new(sync.Once)},
connParams: p,
reconnectDelay: reconnectDelay,
}
c.maxRetries = 12 /// with default 5 second delay this would be a minute
return c
} | [
"func",
"newConsulClient",
"(",
"config",
"*",
"api",
".",
"Config",
",",
"client",
"*",
"api",
".",
"Client",
",",
"reconnectDelay",
"time",
".",
"Duration",
",",
"p",
"connectionParams",
",",
")",
"consulClient",
"{",
"c",
":=",
"&",
"consulClientImpl",
"{",
"conn",
":",
"&",
"consulConnection",
"{",
"config",
":",
"config",
",",
"client",
":",
"client",
",",
"once",
":",
"new",
"(",
"sync",
".",
"Once",
")",
"}",
",",
"connParams",
":",
"p",
",",
"reconnectDelay",
":",
"reconnectDelay",
",",
"}",
"\n",
"c",
".",
"maxRetries",
"=",
"12",
"/// with default 5 second delay this would be a minute",
"\n",
"return",
"c",
"\n",
"}"
] | // newConsulClient provides an instance of clientConsul interface. | [
"newConsulClient",
"provides",
"an",
"instance",
"of",
"clientConsul",
"interface",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/consul/client.go#L107-L122 |
11,956 | portworx/kvdb | consul/client.go | LockOpts | func (c *consulClientImpl) LockOpts(opts *api.LockOptions) (*api.Lock, error) {
return c.conn.client.LockOpts(opts)
} | go | func (c *consulClientImpl) LockOpts(opts *api.LockOptions) (*api.Lock, error) {
return c.conn.client.LockOpts(opts)
} | [
"func",
"(",
"c",
"*",
"consulClientImpl",
")",
"LockOpts",
"(",
"opts",
"*",
"api",
".",
"LockOptions",
")",
"(",
"*",
"api",
".",
"Lock",
",",
"error",
")",
"{",
"return",
"c",
".",
"conn",
".",
"client",
".",
"LockOpts",
"(",
"opts",
")",
"\n",
"}"
] | // LockOpts returns pointer to underlying Lock object and an error. | [
"LockOpts",
"returns",
"pointer",
"to",
"underlying",
"Lock",
"object",
"and",
"an",
"error",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/consul/client.go#L125-L127 |
11,957 | portworx/kvdb | consul/client.go | reconnect | func (c *consulClientImpl) reconnect(conn *consulConnection) error {
var err error
// once.Do executes func() only once across concurrently executing threads
conn.once.Do(func() {
var config *api.Config
var client *api.Client
for _, machine := range c.connParams.machines {
if strings.HasPrefix(machine, "http://") {
machine = strings.TrimPrefix(machine, "http://")
} else if strings.HasPrefix(machine, "https://") {
machine = strings.TrimPrefix(machine, "https://")
}
// sleep for requested delay before testing new connection
time.Sleep(c.reconnectDelay)
if config, client, err = newKvClient(machine, c.connParams); err == nil {
c.conn = &consulConnection{
client: client,
config: config,
once: new(sync.Once),
}
logrus.Infof("%s: %s\n", "successfully connected to", machine)
break
} else {
logrus.Errorf("failed to reconnect client on: %s", machine)
}
}
})
if err != nil {
logrus.Infof("Failed to reconnect client: %v", err)
}
return err
} | go | func (c *consulClientImpl) reconnect(conn *consulConnection) error {
var err error
// once.Do executes func() only once across concurrently executing threads
conn.once.Do(func() {
var config *api.Config
var client *api.Client
for _, machine := range c.connParams.machines {
if strings.HasPrefix(machine, "http://") {
machine = strings.TrimPrefix(machine, "http://")
} else if strings.HasPrefix(machine, "https://") {
machine = strings.TrimPrefix(machine, "https://")
}
// sleep for requested delay before testing new connection
time.Sleep(c.reconnectDelay)
if config, client, err = newKvClient(machine, c.connParams); err == nil {
c.conn = &consulConnection{
client: client,
config: config,
once: new(sync.Once),
}
logrus.Infof("%s: %s\n", "successfully connected to", machine)
break
} else {
logrus.Errorf("failed to reconnect client on: %s", machine)
}
}
})
if err != nil {
logrus.Infof("Failed to reconnect client: %v", err)
}
return err
} | [
"func",
"(",
"c",
"*",
"consulClientImpl",
")",
"reconnect",
"(",
"conn",
"*",
"consulConnection",
")",
"error",
"{",
"var",
"err",
"error",
"\n\n",
"// once.Do executes func() only once across concurrently executing threads",
"conn",
".",
"once",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"var",
"config",
"*",
"api",
".",
"Config",
"\n",
"var",
"client",
"*",
"api",
".",
"Client",
"\n\n",
"for",
"_",
",",
"machine",
":=",
"range",
"c",
".",
"connParams",
".",
"machines",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"machine",
",",
"\"",
"\"",
")",
"{",
"machine",
"=",
"strings",
".",
"TrimPrefix",
"(",
"machine",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"machine",
",",
"\"",
"\"",
")",
"{",
"machine",
"=",
"strings",
".",
"TrimPrefix",
"(",
"machine",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// sleep for requested delay before testing new connection",
"time",
".",
"Sleep",
"(",
"c",
".",
"reconnectDelay",
")",
"\n",
"if",
"config",
",",
"client",
",",
"err",
"=",
"newKvClient",
"(",
"machine",
",",
"c",
".",
"connParams",
")",
";",
"err",
"==",
"nil",
"{",
"c",
".",
"conn",
"=",
"&",
"consulConnection",
"{",
"client",
":",
"client",
",",
"config",
":",
"config",
",",
"once",
":",
"new",
"(",
"sync",
".",
"Once",
")",
",",
"}",
"\n",
"logrus",
".",
"Infof",
"(",
"\"",
"\\n",
"\"",
",",
"\"",
"\"",
",",
"machine",
")",
"\n",
"break",
"\n",
"}",
"else",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"machine",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // reconnect reconnectes to any online and healthy consul server.. | [
"reconnect",
"reconnectes",
"to",
"any",
"online",
"and",
"healthy",
"consul",
"server",
".."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/consul/client.go#L130-L165 |
11,958 | portworx/kvdb | consul/client.go | isConsulErrNeedingRetry | func isConsulErrNeedingRetry(err error) bool {
return strings.Contains(err.Error(), httpError) ||
strings.Contains(err.Error(), eofError) ||
strings.Contains(err.Error(), connRefused) ||
strings.Contains(err.Error(), nameResolutionError)
} | go | func isConsulErrNeedingRetry(err error) bool {
return strings.Contains(err.Error(), httpError) ||
strings.Contains(err.Error(), eofError) ||
strings.Contains(err.Error(), connRefused) ||
strings.Contains(err.Error(), nameResolutionError)
} | [
"func",
"isConsulErrNeedingRetry",
"(",
"err",
"error",
")",
"bool",
"{",
"return",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"httpError",
")",
"||",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"eofError",
")",
"||",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"connRefused",
")",
"||",
"strings",
".",
"Contains",
"(",
"err",
".",
"Error",
"(",
")",
",",
"nameResolutionError",
")",
"\n",
"}"
] | // isConsulErrNeedingRetry is a type of consul error on which we should try reconnecting consul client. | [
"isConsulErrNeedingRetry",
"is",
"a",
"type",
"of",
"consul",
"error",
"on",
"which",
"we",
"should",
"try",
"reconnecting",
"consul",
"client",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/consul/client.go#L168-L173 |
11,959 | portworx/kvdb | consul/client.go | newKvClient | func newKvClient(machine string, p connectionParams) (*api.Config, *api.Client, error) {
config := api.DefaultConfig()
config.HttpClient = http.DefaultClient
config.Address = machine
config.Scheme = "http"
config.Token = p.options[kvdb.ACLTokenKey]
// check if TLS is required
if p.options[kvdb.TransportScheme] == "https" {
tlsConfig := &api.TLSConfig{
CAFile: p.options[kvdb.CAFileKey],
CertFile: p.options[kvdb.CertFileKey],
KeyFile: p.options[kvdb.CertKeyFileKey],
Address: p.options[kvdb.CAAuthAddress],
InsecureSkipVerify: strings.ToLower(p.options[kvdb.InsecureSkipVerify]) == "true",
}
consulTLSConfig, err := api.SetupTLSConfig(tlsConfig)
if err != nil {
logrus.Fatal(err)
}
config.Scheme = p.options[kvdb.TransportScheme]
config.HttpClient = new(http.Client)
config.HttpClient.Transport = &http.Transport{
TLSClientConfig: consulTLSConfig,
}
}
client, err := api.NewClient(config)
if err != nil {
logrus.Info("consul: failed to get new api client: %v", err)
return nil, nil, err
}
// check health to ensure communication with consul are working
if _, _, err := client.Health().State(api.HealthAny, nil); err != nil {
logrus.Errorf("consul: health check failed for %v : %v", machine, err)
return nil, nil, err
}
return config, client, nil
} | go | func newKvClient(machine string, p connectionParams) (*api.Config, *api.Client, error) {
config := api.DefaultConfig()
config.HttpClient = http.DefaultClient
config.Address = machine
config.Scheme = "http"
config.Token = p.options[kvdb.ACLTokenKey]
// check if TLS is required
if p.options[kvdb.TransportScheme] == "https" {
tlsConfig := &api.TLSConfig{
CAFile: p.options[kvdb.CAFileKey],
CertFile: p.options[kvdb.CertFileKey],
KeyFile: p.options[kvdb.CertKeyFileKey],
Address: p.options[kvdb.CAAuthAddress],
InsecureSkipVerify: strings.ToLower(p.options[kvdb.InsecureSkipVerify]) == "true",
}
consulTLSConfig, err := api.SetupTLSConfig(tlsConfig)
if err != nil {
logrus.Fatal(err)
}
config.Scheme = p.options[kvdb.TransportScheme]
config.HttpClient = new(http.Client)
config.HttpClient.Transport = &http.Transport{
TLSClientConfig: consulTLSConfig,
}
}
client, err := api.NewClient(config)
if err != nil {
logrus.Info("consul: failed to get new api client: %v", err)
return nil, nil, err
}
// check health to ensure communication with consul are working
if _, _, err := client.Health().State(api.HealthAny, nil); err != nil {
logrus.Errorf("consul: health check failed for %v : %v", machine, err)
return nil, nil, err
}
return config, client, nil
} | [
"func",
"newKvClient",
"(",
"machine",
"string",
",",
"p",
"connectionParams",
")",
"(",
"*",
"api",
".",
"Config",
",",
"*",
"api",
".",
"Client",
",",
"error",
")",
"{",
"config",
":=",
"api",
".",
"DefaultConfig",
"(",
")",
"\n",
"config",
".",
"HttpClient",
"=",
"http",
".",
"DefaultClient",
"\n",
"config",
".",
"Address",
"=",
"machine",
"\n",
"config",
".",
"Scheme",
"=",
"\"",
"\"",
"\n",
"config",
".",
"Token",
"=",
"p",
".",
"options",
"[",
"kvdb",
".",
"ACLTokenKey",
"]",
"\n\n",
"// check if TLS is required",
"if",
"p",
".",
"options",
"[",
"kvdb",
".",
"TransportScheme",
"]",
"==",
"\"",
"\"",
"{",
"tlsConfig",
":=",
"&",
"api",
".",
"TLSConfig",
"{",
"CAFile",
":",
"p",
".",
"options",
"[",
"kvdb",
".",
"CAFileKey",
"]",
",",
"CertFile",
":",
"p",
".",
"options",
"[",
"kvdb",
".",
"CertFileKey",
"]",
",",
"KeyFile",
":",
"p",
".",
"options",
"[",
"kvdb",
".",
"CertKeyFileKey",
"]",
",",
"Address",
":",
"p",
".",
"options",
"[",
"kvdb",
".",
"CAAuthAddress",
"]",
",",
"InsecureSkipVerify",
":",
"strings",
".",
"ToLower",
"(",
"p",
".",
"options",
"[",
"kvdb",
".",
"InsecureSkipVerify",
"]",
")",
"==",
"\"",
"\"",
",",
"}",
"\n\n",
"consulTLSConfig",
",",
"err",
":=",
"api",
".",
"SetupTLSConfig",
"(",
"tlsConfig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"config",
".",
"Scheme",
"=",
"p",
".",
"options",
"[",
"kvdb",
".",
"TransportScheme",
"]",
"\n",
"config",
".",
"HttpClient",
"=",
"new",
"(",
"http",
".",
"Client",
")",
"\n",
"config",
".",
"HttpClient",
".",
"Transport",
"=",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"consulTLSConfig",
",",
"}",
"\n",
"}",
"\n\n",
"client",
",",
"err",
":=",
"api",
".",
"NewClient",
"(",
"config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Info",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// check health to ensure communication with consul are working",
"if",
"_",
",",
"_",
",",
"err",
":=",
"client",
".",
"Health",
"(",
")",
".",
"State",
"(",
"api",
".",
"HealthAny",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"machine",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"config",
",",
"client",
",",
"nil",
"\n",
"}"
] | // newKvClient constructs new kvdb.Kvdb given a single end-point to connect to. | [
"newKvClient",
"constructs",
"new",
"kvdb",
".",
"Kvdb",
"given",
"a",
"single",
"end",
"-",
"point",
"to",
"connect",
"to",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/consul/client.go#L181-L223 |
11,960 | portworx/kvdb | consul/client.go | runWithRetry | func (c *consulClientImpl) runWithRetry(f consulFunc) {
for i := 0; i < c.maxRetries; i++ {
if !f() {
break
}
}
} | go | func (c *consulClientImpl) runWithRetry(f consulFunc) {
for i := 0; i < c.maxRetries; i++ {
if !f() {
break
}
}
} | [
"func",
"(",
"c",
"*",
"consulClientImpl",
")",
"runWithRetry",
"(",
"f",
"consulFunc",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"c",
".",
"maxRetries",
";",
"i",
"++",
"{",
"if",
"!",
"f",
"(",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // runWithRetry runs consulFunc with retries if required | [
"runWithRetry",
"runs",
"consulFunc",
"with",
"retries",
"if",
"required"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/consul/client.go#L229-L235 |
11,961 | portworx/kvdb | consul/client.go | writeRetryFunc | func (c *consulClientImpl) writeRetryFunc(f writeFunc) (*api.WriteMeta, error) {
var err error
var meta *api.WriteMeta
retry := false
c.runWithRetry(func() bool {
conn := c.conn
meta, err = f(conn)
retry, err = c.reconnectIfConnectionError(conn, err)
return retry
})
return meta, err
} | go | func (c *consulClientImpl) writeRetryFunc(f writeFunc) (*api.WriteMeta, error) {
var err error
var meta *api.WriteMeta
retry := false
c.runWithRetry(func() bool {
conn := c.conn
meta, err = f(conn)
retry, err = c.reconnectIfConnectionError(conn, err)
return retry
})
return meta, err
} | [
"func",
"(",
"c",
"*",
"consulClientImpl",
")",
"writeRetryFunc",
"(",
"f",
"writeFunc",
")",
"(",
"*",
"api",
".",
"WriteMeta",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"var",
"meta",
"*",
"api",
".",
"WriteMeta",
"\n",
"retry",
":=",
"false",
"\n",
"c",
".",
"runWithRetry",
"(",
"func",
"(",
")",
"bool",
"{",
"conn",
":=",
"c",
".",
"conn",
"\n",
"meta",
",",
"err",
"=",
"f",
"(",
"conn",
")",
"\n",
"retry",
",",
"err",
"=",
"c",
".",
"reconnectIfConnectionError",
"(",
"conn",
",",
"err",
")",
"\n",
"return",
"retry",
"\n",
"}",
")",
"\n",
"return",
"meta",
",",
"err",
"\n",
"}"
] | // writeRetryFunc runs writeFunc with retries if required | [
"writeRetryFunc",
"runs",
"writeFunc",
"with",
"retries",
"if",
"required"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/consul/client.go#L241-L252 |
11,962 | portworx/kvdb | etcd/common/common.go | Version | func Version(uri string, options map[string]string) (string, error) {
useTLS := false
tlsConfig := &tls.Config{}
// Check if CA file provided
caFile, ok := options[kvdb.CAFileKey]
if ok && caFile != "" {
useTLS = true
// Load CA cert
caCert, err := ioutil.ReadFile(caFile)
if err != nil {
return "", err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = caCertPool
}
// Check if certificate file provided
certFile, certOk := options[kvdb.CertFileKey]
// Check if certificate key is provided
keyFile, keyOk := options[kvdb.CertKeyFileKey]
if certOk && keyOk && certFile != "" && keyFile != "" {
useTLS = true
// Load client cert
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return "", err
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
var client *http.Client
if useTLS {
tlsConfig.BuildNameToCertificate()
client = &http.Client{Transport: &http.Transport{TLSClientConfig: tlsConfig}}
} else {
tempURL, _ := url.Parse(uri)
if tempURL.Scheme == "https" {
transport := &http.Transport{TLSClientConfig: &tls.Config{}}
client = &http.Client{Transport: transport}
} else {
client = &http.Client{}
}
}
// Do GET something
resp, err := client.Get(uri + "/version")
if err != nil {
return "", fmt.Errorf("error in obtaining etcd version: %v", err)
}
defer resp.Body.Close()
// Dump response
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("error in obtaining etcd version: %v", err)
}
var ver version.Versions
err = json.Unmarshal(data, &ver)
if err != nil {
// Probably a version less than 2.3. Default to using v2 apis
return kvdb.EtcdBaseVersion, nil
}
if ver.Server == "" {
// This should never happen in an ideal scenario unless
// etcd messes up. To avoid a crash further in this code
// we return an error
return "", fmt.Errorf("unable to determine etcd version (empty response from etcd)")
}
if ver.Server[0] == '2' || ver.Server[0] == '1' {
return kvdb.EtcdBaseVersion, nil
} else if ver.Server[0] == '3' {
return kvdb.EtcdVersion3, nil
} else {
return "", fmt.Errorf("unsupported etcd version: %v", ver.Server)
}
} | go | func Version(uri string, options map[string]string) (string, error) {
useTLS := false
tlsConfig := &tls.Config{}
// Check if CA file provided
caFile, ok := options[kvdb.CAFileKey]
if ok && caFile != "" {
useTLS = true
// Load CA cert
caCert, err := ioutil.ReadFile(caFile)
if err != nil {
return "", err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = caCertPool
}
// Check if certificate file provided
certFile, certOk := options[kvdb.CertFileKey]
// Check if certificate key is provided
keyFile, keyOk := options[kvdb.CertKeyFileKey]
if certOk && keyOk && certFile != "" && keyFile != "" {
useTLS = true
// Load client cert
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return "", err
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
var client *http.Client
if useTLS {
tlsConfig.BuildNameToCertificate()
client = &http.Client{Transport: &http.Transport{TLSClientConfig: tlsConfig}}
} else {
tempURL, _ := url.Parse(uri)
if tempURL.Scheme == "https" {
transport := &http.Transport{TLSClientConfig: &tls.Config{}}
client = &http.Client{Transport: transport}
} else {
client = &http.Client{}
}
}
// Do GET something
resp, err := client.Get(uri + "/version")
if err != nil {
return "", fmt.Errorf("error in obtaining etcd version: %v", err)
}
defer resp.Body.Close()
// Dump response
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("error in obtaining etcd version: %v", err)
}
var ver version.Versions
err = json.Unmarshal(data, &ver)
if err != nil {
// Probably a version less than 2.3. Default to using v2 apis
return kvdb.EtcdBaseVersion, nil
}
if ver.Server == "" {
// This should never happen in an ideal scenario unless
// etcd messes up. To avoid a crash further in this code
// we return an error
return "", fmt.Errorf("unable to determine etcd version (empty response from etcd)")
}
if ver.Server[0] == '2' || ver.Server[0] == '1' {
return kvdb.EtcdBaseVersion, nil
} else if ver.Server[0] == '3' {
return kvdb.EtcdVersion3, nil
} else {
return "", fmt.Errorf("unsupported etcd version: %v", ver.Server)
}
} | [
"func",
"Version",
"(",
"uri",
"string",
",",
"options",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"useTLS",
":=",
"false",
"\n",
"tlsConfig",
":=",
"&",
"tls",
".",
"Config",
"{",
"}",
"\n",
"// Check if CA file provided",
"caFile",
",",
"ok",
":=",
"options",
"[",
"kvdb",
".",
"CAFileKey",
"]",
"\n",
"if",
"ok",
"&&",
"caFile",
"!=",
"\"",
"\"",
"{",
"useTLS",
"=",
"true",
"\n",
"// Load CA cert",
"caCert",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"caFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"caCertPool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"caCertPool",
".",
"AppendCertsFromPEM",
"(",
"caCert",
")",
"\n",
"tlsConfig",
".",
"RootCAs",
"=",
"caCertPool",
"\n",
"}",
"\n",
"// Check if certificate file provided",
"certFile",
",",
"certOk",
":=",
"options",
"[",
"kvdb",
".",
"CertFileKey",
"]",
"\n",
"// Check if certificate key is provided",
"keyFile",
",",
"keyOk",
":=",
"options",
"[",
"kvdb",
".",
"CertKeyFileKey",
"]",
"\n",
"if",
"certOk",
"&&",
"keyOk",
"&&",
"certFile",
"!=",
"\"",
"\"",
"&&",
"keyFile",
"!=",
"\"",
"\"",
"{",
"useTLS",
"=",
"true",
"\n",
"// Load client cert",
"cert",
",",
"err",
":=",
"tls",
".",
"LoadX509KeyPair",
"(",
"certFile",
",",
"keyFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"tlsConfig",
".",
"Certificates",
"=",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"cert",
"}",
"\n",
"}",
"\n\n",
"var",
"client",
"*",
"http",
".",
"Client",
"\n",
"if",
"useTLS",
"{",
"tlsConfig",
".",
"BuildNameToCertificate",
"(",
")",
"\n",
"client",
"=",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"tlsConfig",
"}",
"}",
"\n",
"}",
"else",
"{",
"tempURL",
",",
"_",
":=",
"url",
".",
"Parse",
"(",
"uri",
")",
"\n",
"if",
"tempURL",
".",
"Scheme",
"==",
"\"",
"\"",
"{",
"transport",
":=",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"&",
"tls",
".",
"Config",
"{",
"}",
"}",
"\n",
"client",
"=",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"transport",
"}",
"\n",
"}",
"else",
"{",
"client",
"=",
"&",
"http",
".",
"Client",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Do GET something",
"resp",
",",
"err",
":=",
"client",
".",
"Get",
"(",
"uri",
"+",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"// Dump response",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"ver",
"version",
".",
"Versions",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"ver",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Probably a version less than 2.3. Default to using v2 apis",
"return",
"kvdb",
".",
"EtcdBaseVersion",
",",
"nil",
"\n",
"}",
"\n",
"if",
"ver",
".",
"Server",
"==",
"\"",
"\"",
"{",
"// This should never happen in an ideal scenario unless",
"// etcd messes up. To avoid a crash further in this code",
"// we return an error",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ver",
".",
"Server",
"[",
"0",
"]",
"==",
"'2'",
"||",
"ver",
".",
"Server",
"[",
"0",
"]",
"==",
"'1'",
"{",
"return",
"kvdb",
".",
"EtcdBaseVersion",
",",
"nil",
"\n",
"}",
"else",
"if",
"ver",
".",
"Server",
"[",
"0",
"]",
"==",
"'3'",
"{",
"return",
"kvdb",
".",
"EtcdVersion3",
",",
"nil",
"\n",
"}",
"else",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ver",
".",
"Server",
")",
"\n",
"}",
"\n",
"}"
] | // Version returns the version of the provided etcd server | [
"Version",
"returns",
"the",
"version",
"of",
"the",
"provided",
"etcd",
"server"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/etcd/common/common.go#L140-L216 |
11,963 | portworx/kvdb | bolt/kv_bolt.go | NewWatchUpdateQueue | func NewWatchUpdateQueue() WatchUpdateQueue {
mtx := &sync.Mutex{}
return &watchQueue{
m: mtx,
cv: sync.NewCond(mtx),
updates: make([]*watchUpdate, 0)}
} | go | func NewWatchUpdateQueue() WatchUpdateQueue {
mtx := &sync.Mutex{}
return &watchQueue{
m: mtx,
cv: sync.NewCond(mtx),
updates: make([]*watchUpdate, 0)}
} | [
"func",
"NewWatchUpdateQueue",
"(",
")",
"WatchUpdateQueue",
"{",
"mtx",
":=",
"&",
"sync",
".",
"Mutex",
"{",
"}",
"\n",
"return",
"&",
"watchQueue",
"{",
"m",
":",
"mtx",
",",
"cv",
":",
"sync",
".",
"NewCond",
"(",
"mtx",
")",
",",
"updates",
":",
"make",
"(",
"[",
"]",
"*",
"watchUpdate",
",",
"0",
")",
"}",
"\n",
"}"
] | // NewWatchUpdateQueue returns an instance of WatchUpdateQueue | [
"NewWatchUpdateQueue",
"returns",
"an",
"instance",
"of",
"WatchUpdateQueue"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/bolt/kv_bolt.go#L176-L182 |
11,964 | portworx/kvdb | bolt/kv_bolt.go | Update | func (kv *boltKV) Update(
key string,
value interface{},
ttl uint64,
) (*kvdb.KVPair, error) {
kv.mutex.Lock()
defer kv.mutex.Unlock()
if _, err := kv.exists(key); err != nil {
return nil, kvdb.ErrNotFound
}
kvp, err := kv.put(key, value, ttl, kvdb.KVSet)
if err != nil {
return nil, err
}
kvp.Action = kvdb.KVSet
return kvp, nil
} | go | func (kv *boltKV) Update(
key string,
value interface{},
ttl uint64,
) (*kvdb.KVPair, error) {
kv.mutex.Lock()
defer kv.mutex.Unlock()
if _, err := kv.exists(key); err != nil {
return nil, kvdb.ErrNotFound
}
kvp, err := kv.put(key, value, ttl, kvdb.KVSet)
if err != nil {
return nil, err
}
kvp.Action = kvdb.KVSet
return kvp, nil
} | [
"func",
"(",
"kv",
"*",
"boltKV",
")",
"Update",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
",",
"ttl",
"uint64",
",",
")",
"(",
"*",
"kvdb",
".",
"KVPair",
",",
"error",
")",
"{",
"kv",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"kv",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"_",
",",
"err",
":=",
"kv",
".",
"exists",
"(",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"kvdb",
".",
"ErrNotFound",
"\n",
"}",
"\n",
"kvp",
",",
"err",
":=",
"kv",
".",
"put",
"(",
"key",
",",
"value",
",",
"ttl",
",",
"kvdb",
".",
"KVSet",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"kvp",
".",
"Action",
"=",
"kvdb",
".",
"KVSet",
"\n",
"return",
"kvp",
",",
"nil",
"\n",
"}"
] | // XXX needs to be atomic | [
"XXX",
"needs",
"to",
"be",
"atomic"
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/bolt/kv_bolt.go#L641-L659 |
11,965 | portworx/kvdb | etcd/v3/kv_etcd.go | isRetryNeeded | func isRetryNeeded(err error, fn string, key string, retryCount int) (bool, error) {
switch err {
case kvdb.ErrNotSupported, kvdb.ErrWatchStopped, kvdb.ErrNotFound, kvdb.ErrExist, kvdb.ErrUnmarshal, kvdb.ErrValueMismatch, kvdb.ErrModified:
// For all known kvdb errors no retry is needed
return false, err
case rpctypes.ErrGRPCEmptyKey:
return false, kvdb.ErrNotFound
default:
// For all other errors retry
logrus.Errorf("[%v: %v] kvdb error: %v, retry count %v \n", fn, key, err, retryCount)
return true, err
}
} | go | func isRetryNeeded(err error, fn string, key string, retryCount int) (bool, error) {
switch err {
case kvdb.ErrNotSupported, kvdb.ErrWatchStopped, kvdb.ErrNotFound, kvdb.ErrExist, kvdb.ErrUnmarshal, kvdb.ErrValueMismatch, kvdb.ErrModified:
// For all known kvdb errors no retry is needed
return false, err
case rpctypes.ErrGRPCEmptyKey:
return false, kvdb.ErrNotFound
default:
// For all other errors retry
logrus.Errorf("[%v: %v] kvdb error: %v, retry count %v \n", fn, key, err, retryCount)
return true, err
}
} | [
"func",
"isRetryNeeded",
"(",
"err",
"error",
",",
"fn",
"string",
",",
"key",
"string",
",",
"retryCount",
"int",
")",
"(",
"bool",
",",
"error",
")",
"{",
"switch",
"err",
"{",
"case",
"kvdb",
".",
"ErrNotSupported",
",",
"kvdb",
".",
"ErrWatchStopped",
",",
"kvdb",
".",
"ErrNotFound",
",",
"kvdb",
".",
"ErrExist",
",",
"kvdb",
".",
"ErrUnmarshal",
",",
"kvdb",
".",
"ErrValueMismatch",
",",
"kvdb",
".",
"ErrModified",
":",
"// For all known kvdb errors no retry is needed",
"return",
"false",
",",
"err",
"\n",
"case",
"rpctypes",
".",
"ErrGRPCEmptyKey",
":",
"return",
"false",
",",
"kvdb",
".",
"ErrNotFound",
"\n",
"default",
":",
"// For all other errors retry",
"logrus",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"fn",
",",
"key",
",",
"err",
",",
"retryCount",
")",
"\n",
"return",
"true",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // isRetryNeeded checks if for the given error does a kvdb retry required.
// It returns the provided error. | [
"isRetryNeeded",
"checks",
"if",
"for",
"the",
"given",
"error",
"does",
"a",
"kvdb",
"retry",
"required",
".",
"It",
"returns",
"the",
"provided",
"error",
"."
] | 135442da7421636125eff4d02835fcfb325f0828 | https://github.com/portworx/kvdb/blob/135442da7421636125eff4d02835fcfb325f0828/etcd/v3/kv_etcd.go#L1575-L1587 |
11,966 | joliv/spark | spark.go | Line | func Line(nums []float64) string {
if len(nums) == 0 {
return ""
}
indices := normalize(nums)
var sparkline bytes.Buffer
for _, index := range indices {
sparkline.WriteRune(steps[index])
}
return sparkline.String()
} | go | func Line(nums []float64) string {
if len(nums) == 0 {
return ""
}
indices := normalize(nums)
var sparkline bytes.Buffer
for _, index := range indices {
sparkline.WriteRune(steps[index])
}
return sparkline.String()
} | [
"func",
"Line",
"(",
"nums",
"[",
"]",
"float64",
")",
"string",
"{",
"if",
"len",
"(",
"nums",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"indices",
":=",
"normalize",
"(",
"nums",
")",
"\n",
"var",
"sparkline",
"bytes",
".",
"Buffer",
"\n",
"for",
"_",
",",
"index",
":=",
"range",
"indices",
"{",
"sparkline",
".",
"WriteRune",
"(",
"steps",
"[",
"index",
"]",
")",
"\n",
"}",
"\n",
"return",
"sparkline",
".",
"String",
"(",
")",
"\n",
"}"
] | // Line generates a sparkline string from a slice of
// float64s. | [
"Line",
"generates",
"a",
"sparkline",
"string",
"from",
"a",
"slice",
"of",
"float64s",
"."
] | 2d625891bea13083312494f03e686dde519d3f5a | https://github.com/joliv/spark/blob/2d625891bea13083312494f03e686dde519d3f5a/spark.go#L12-L22 |
11,967 | shurcooL/httpfs | filter/filter.go | Keep | func Keep(source http.FileSystem, keep Func) http.FileSystem {
return &filterFS{source: source, keep: keep}
} | go | func Keep(source http.FileSystem, keep Func) http.FileSystem {
return &filterFS{source: source, keep: keep}
} | [
"func",
"Keep",
"(",
"source",
"http",
".",
"FileSystem",
",",
"keep",
"Func",
")",
"http",
".",
"FileSystem",
"{",
"return",
"&",
"filterFS",
"{",
"source",
":",
"source",
",",
"keep",
":",
"keep",
"}",
"\n",
"}"
] | // Keep returns a filesystem that contains only those entries in source for which
// keep returns true. | [
"Keep",
"returns",
"a",
"filesystem",
"that",
"contains",
"only",
"those",
"entries",
"in",
"source",
"for",
"which",
"keep",
"returns",
"true",
"."
] | 74dc9339e414ad069a8d04bba7e7aafd08043a25 | https://github.com/shurcooL/httpfs/blob/74dc9339e414ad069a8d04bba7e7aafd08043a25/filter/filter.go#L25-L27 |
11,968 | shurcooL/httpfs | filter/filter.go | Skip | func Skip(source http.FileSystem, skip Func) http.FileSystem {
keep := func(path string, fi os.FileInfo) bool {
return !skip(path, fi)
}
return &filterFS{source: source, keep: keep}
} | go | func Skip(source http.FileSystem, skip Func) http.FileSystem {
keep := func(path string, fi os.FileInfo) bool {
return !skip(path, fi)
}
return &filterFS{source: source, keep: keep}
} | [
"func",
"Skip",
"(",
"source",
"http",
".",
"FileSystem",
",",
"skip",
"Func",
")",
"http",
".",
"FileSystem",
"{",
"keep",
":=",
"func",
"(",
"path",
"string",
",",
"fi",
"os",
".",
"FileInfo",
")",
"bool",
"{",
"return",
"!",
"skip",
"(",
"path",
",",
"fi",
")",
"\n",
"}",
"\n",
"return",
"&",
"filterFS",
"{",
"source",
":",
"source",
",",
"keep",
":",
"keep",
"}",
"\n",
"}"
] | // Skip returns a filesystem that contains everything in source, except entries
// for which skip returns true. | [
"Skip",
"returns",
"a",
"filesystem",
"that",
"contains",
"everything",
"in",
"source",
"except",
"entries",
"for",
"which",
"skip",
"returns",
"true",
"."
] | 74dc9339e414ad069a8d04bba7e7aafd08043a25 | https://github.com/shurcooL/httpfs/blob/74dc9339e414ad069a8d04bba7e7aafd08043a25/filter/filter.go#L31-L36 |
11,969 | shurcooL/httpfs | html/vfstemplate/vfstemplate.go | ParseGlob | func ParseGlob(fs http.FileSystem, t *template.Template, pattern string) (*template.Template, error) {
filenames, err := vfspath.Glob(fs, pattern)
if err != nil {
return nil, err
}
if len(filenames) == 0 {
return nil, fmt.Errorf("vfs/html/vfstemplate: pattern matches no files: %#q", pattern)
}
return parseFiles(fs, t, filenames...)
} | go | func ParseGlob(fs http.FileSystem, t *template.Template, pattern string) (*template.Template, error) {
filenames, err := vfspath.Glob(fs, pattern)
if err != nil {
return nil, err
}
if len(filenames) == 0 {
return nil, fmt.Errorf("vfs/html/vfstemplate: pattern matches no files: %#q", pattern)
}
return parseFiles(fs, t, filenames...)
} | [
"func",
"ParseGlob",
"(",
"fs",
"http",
".",
"FileSystem",
",",
"t",
"*",
"template",
".",
"Template",
",",
"pattern",
"string",
")",
"(",
"*",
"template",
".",
"Template",
",",
"error",
")",
"{",
"filenames",
",",
"err",
":=",
"vfspath",
".",
"Glob",
"(",
"fs",
",",
"pattern",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"filenames",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"pattern",
")",
"\n",
"}",
"\n",
"return",
"parseFiles",
"(",
"fs",
",",
"t",
",",
"filenames",
"...",
")",
"\n",
"}"
] | // ParseGlob parses the template definitions in the files identified by the
// pattern and associates the resulting templates with t. The pattern is
// processed by vfspath.Glob and must match at least one file. ParseGlob is
// equivalent to calling t.ParseFiles with the list of files matched by the
// pattern. | [
"ParseGlob",
"parses",
"the",
"template",
"definitions",
"in",
"the",
"files",
"identified",
"by",
"the",
"pattern",
"and",
"associates",
"the",
"resulting",
"templates",
"with",
"t",
".",
"The",
"pattern",
"is",
"processed",
"by",
"vfspath",
".",
"Glob",
"and",
"must",
"match",
"at",
"least",
"one",
"file",
".",
"ParseGlob",
"is",
"equivalent",
"to",
"calling",
"t",
".",
"ParseFiles",
"with",
"the",
"list",
"of",
"files",
"matched",
"by",
"the",
"pattern",
"."
] | 74dc9339e414ad069a8d04bba7e7aafd08043a25 | https://github.com/shurcooL/httpfs/blob/74dc9339e414ad069a8d04bba7e7aafd08043a25/html/vfstemplate/vfstemplate.go#L27-L36 |
11,970 | shurcooL/httpfs | union/union.go | Open | func (u *unionFS) Open(path string) (http.File, error) {
// TODO: Maybe clean path?
if path == "/" {
return &dir{
dirInfo: u.root,
}, nil
}
for prefix, fs := range u.ns {
if path == prefix || strings.HasPrefix(path, prefix+"/") {
innerPath := path[len(prefix):]
if innerPath == "" {
innerPath = "/"
}
return fs.Open(innerPath)
}
}
return nil, &os.PathError{Op: "open", Path: path, Err: os.ErrNotExist}
} | go | func (u *unionFS) Open(path string) (http.File, error) {
// TODO: Maybe clean path?
if path == "/" {
return &dir{
dirInfo: u.root,
}, nil
}
for prefix, fs := range u.ns {
if path == prefix || strings.HasPrefix(path, prefix+"/") {
innerPath := path[len(prefix):]
if innerPath == "" {
innerPath = "/"
}
return fs.Open(innerPath)
}
}
return nil, &os.PathError{Op: "open", Path: path, Err: os.ErrNotExist}
} | [
"func",
"(",
"u",
"*",
"unionFS",
")",
"Open",
"(",
"path",
"string",
")",
"(",
"http",
".",
"File",
",",
"error",
")",
"{",
"// TODO: Maybe clean path?",
"if",
"path",
"==",
"\"",
"\"",
"{",
"return",
"&",
"dir",
"{",
"dirInfo",
":",
"u",
".",
"root",
",",
"}",
",",
"nil",
"\n",
"}",
"\n",
"for",
"prefix",
",",
"fs",
":=",
"range",
"u",
".",
"ns",
"{",
"if",
"path",
"==",
"prefix",
"||",
"strings",
".",
"HasPrefix",
"(",
"path",
",",
"prefix",
"+",
"\"",
"\"",
")",
"{",
"innerPath",
":=",
"path",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"\n",
"if",
"innerPath",
"==",
"\"",
"\"",
"{",
"innerPath",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"fs",
".",
"Open",
"(",
"innerPath",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"&",
"os",
".",
"PathError",
"{",
"Op",
":",
"\"",
"\"",
",",
"Path",
":",
"path",
",",
"Err",
":",
"os",
".",
"ErrNotExist",
"}",
"\n",
"}"
] | // Open opens the named file. | [
"Open",
"opens",
"the",
"named",
"file",
"."
] | 74dc9339e414ad069a8d04bba7e7aafd08043a25 | https://github.com/shurcooL/httpfs/blob/74dc9339e414ad069a8d04bba7e7aafd08043a25/union/union.go#L44-L61 |
11,971 | shurcooL/httpfs | vfsutil/walk.go | Walk | func Walk(fs http.FileSystem, root string, walkFn filepath.WalkFunc) error {
info, err := Stat(fs, root)
if err != nil {
return walkFn(root, nil, err)
}
return walk(fs, root, info, walkFn)
} | go | func Walk(fs http.FileSystem, root string, walkFn filepath.WalkFunc) error {
info, err := Stat(fs, root)
if err != nil {
return walkFn(root, nil, err)
}
return walk(fs, root, info, walkFn)
} | [
"func",
"Walk",
"(",
"fs",
"http",
".",
"FileSystem",
",",
"root",
"string",
",",
"walkFn",
"filepath",
".",
"WalkFunc",
")",
"error",
"{",
"info",
",",
"err",
":=",
"Stat",
"(",
"fs",
",",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"walkFn",
"(",
"root",
",",
"nil",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"walk",
"(",
"fs",
",",
"root",
",",
"info",
",",
"walkFn",
")",
"\n",
"}"
] | // Walk walks the filesystem rooted at root, calling walkFn for each file or
// directory in the filesystem, including root. All errors that arise visiting files
// and directories are filtered by walkFn. The files are walked in lexical
// order. | [
"Walk",
"walks",
"the",
"filesystem",
"rooted",
"at",
"root",
"calling",
"walkFn",
"for",
"each",
"file",
"or",
"directory",
"in",
"the",
"filesystem",
"including",
"root",
".",
"All",
"errors",
"that",
"arise",
"visiting",
"files",
"and",
"directories",
"are",
"filtered",
"by",
"walkFn",
".",
"The",
"files",
"are",
"walked",
"in",
"lexical",
"order",
"."
] | 74dc9339e414ad069a8d04bba7e7aafd08043a25 | https://github.com/shurcooL/httpfs/blob/74dc9339e414ad069a8d04bba7e7aafd08043a25/vfsutil/walk.go#L16-L22 |
11,972 | shurcooL/httpfs | vfsutil/walk.go | WalkFiles | func WalkFiles(fs http.FileSystem, root string, walkFn WalkFilesFunc) error {
file, info, err := openStat(fs, root)
if err != nil {
return walkFn(root, nil, nil, err)
}
return walkFiles(fs, root, info, file, walkFn)
} | go | func WalkFiles(fs http.FileSystem, root string, walkFn WalkFilesFunc) error {
file, info, err := openStat(fs, root)
if err != nil {
return walkFn(root, nil, nil, err)
}
return walkFiles(fs, root, info, file, walkFn)
} | [
"func",
"WalkFiles",
"(",
"fs",
"http",
".",
"FileSystem",
",",
"root",
"string",
",",
"walkFn",
"WalkFilesFunc",
")",
"error",
"{",
"file",
",",
"info",
",",
"err",
":=",
"openStat",
"(",
"fs",
",",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"walkFn",
"(",
"root",
",",
"nil",
",",
"nil",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"walkFiles",
"(",
"fs",
",",
"root",
",",
"info",
",",
"file",
",",
"walkFn",
")",
"\n",
"}"
] | // WalkFiles walks the filesystem rooted at root, calling walkFn for each file or
// directory in the filesystem, including root. In addition to FileInfo, it passes an
// ReadSeeker to walkFn for each file it visits. | [
"WalkFiles",
"walks",
"the",
"filesystem",
"rooted",
"at",
"root",
"calling",
"walkFn",
"for",
"each",
"file",
"or",
"directory",
"in",
"the",
"filesystem",
"including",
"root",
".",
"In",
"addition",
"to",
"FileInfo",
"it",
"passes",
"an",
"ReadSeeker",
"to",
"walkFn",
"for",
"each",
"file",
"it",
"visits",
"."
] | 74dc9339e414ad069a8d04bba7e7aafd08043a25 | https://github.com/shurcooL/httpfs/blob/74dc9339e414ad069a8d04bba7e7aafd08043a25/vfsutil/walk.go#L84-L90 |
11,973 | shurcooL/httpfs | vfsutil/walk.go | walkFiles | func walkFiles(fs http.FileSystem, path string, info os.FileInfo, file http.File, walkFn WalkFilesFunc) error {
err := walkFn(path, info, file, nil)
file.Close()
if err != nil {
if info.IsDir() && err == filepath.SkipDir {
return nil
}
return err
}
if !info.IsDir() {
return nil
}
names, err := readDirNames(fs, path)
if err != nil {
return walkFn(path, info, nil, err)
}
for _, name := range names {
filename := pathpkg.Join(path, name)
file, fileInfo, err := openStat(fs, filename)
if err != nil {
if err := walkFn(filename, nil, nil, err); err != nil && err != filepath.SkipDir {
return err
}
} else {
err = walkFiles(fs, filename, fileInfo, file, walkFn)
// file is closed by walkFiles, so we don't need to close it here.
if err != nil {
if !fileInfo.IsDir() || err != filepath.SkipDir {
return err
}
}
}
}
return nil
} | go | func walkFiles(fs http.FileSystem, path string, info os.FileInfo, file http.File, walkFn WalkFilesFunc) error {
err := walkFn(path, info, file, nil)
file.Close()
if err != nil {
if info.IsDir() && err == filepath.SkipDir {
return nil
}
return err
}
if !info.IsDir() {
return nil
}
names, err := readDirNames(fs, path)
if err != nil {
return walkFn(path, info, nil, err)
}
for _, name := range names {
filename := pathpkg.Join(path, name)
file, fileInfo, err := openStat(fs, filename)
if err != nil {
if err := walkFn(filename, nil, nil, err); err != nil && err != filepath.SkipDir {
return err
}
} else {
err = walkFiles(fs, filename, fileInfo, file, walkFn)
// file is closed by walkFiles, so we don't need to close it here.
if err != nil {
if !fileInfo.IsDir() || err != filepath.SkipDir {
return err
}
}
}
}
return nil
} | [
"func",
"walkFiles",
"(",
"fs",
"http",
".",
"FileSystem",
",",
"path",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"file",
"http",
".",
"File",
",",
"walkFn",
"WalkFilesFunc",
")",
"error",
"{",
"err",
":=",
"walkFn",
"(",
"path",
",",
"info",
",",
"file",
",",
"nil",
")",
"\n",
"file",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"info",
".",
"IsDir",
"(",
")",
"&&",
"err",
"==",
"filepath",
".",
"SkipDir",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"info",
".",
"IsDir",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"names",
",",
"err",
":=",
"readDirNames",
"(",
"fs",
",",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"walkFn",
"(",
"path",
",",
"info",
",",
"nil",
",",
"err",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"filename",
":=",
"pathpkg",
".",
"Join",
"(",
"path",
",",
"name",
")",
"\n",
"file",
",",
"fileInfo",
",",
"err",
":=",
"openStat",
"(",
"fs",
",",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
":=",
"walkFn",
"(",
"filename",
",",
"nil",
",",
"nil",
",",
"err",
")",
";",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"filepath",
".",
"SkipDir",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"err",
"=",
"walkFiles",
"(",
"fs",
",",
"filename",
",",
"fileInfo",
",",
"file",
",",
"walkFn",
")",
"\n",
"// file is closed by walkFiles, so we don't need to close it here.",
"if",
"err",
"!=",
"nil",
"{",
"if",
"!",
"fileInfo",
".",
"IsDir",
"(",
")",
"||",
"err",
"!=",
"filepath",
".",
"SkipDir",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // walkFiles recursively descends path, calling walkFn.
// It closes the input file after it's done with it, so the caller shouldn't. | [
"walkFiles",
"recursively",
"descends",
"path",
"calling",
"walkFn",
".",
"It",
"closes",
"the",
"input",
"file",
"after",
"it",
"s",
"done",
"with",
"it",
"so",
"the",
"caller",
"shouldn",
"t",
"."
] | 74dc9339e414ad069a8d04bba7e7aafd08043a25 | https://github.com/shurcooL/httpfs/blob/74dc9339e414ad069a8d04bba7e7aafd08043a25/vfsutil/walk.go#L94-L131 |
11,974 | shurcooL/httpfs | vfsutil/walk.go | openStat | func openStat(fs http.FileSystem, name string) (http.File, os.FileInfo, error) {
f, err := fs.Open(name)
if err != nil {
return nil, nil, err
}
fi, err := f.Stat()
if err != nil {
f.Close()
return nil, nil, err
}
return f, fi, nil
} | go | func openStat(fs http.FileSystem, name string) (http.File, os.FileInfo, error) {
f, err := fs.Open(name)
if err != nil {
return nil, nil, err
}
fi, err := f.Stat()
if err != nil {
f.Close()
return nil, nil, err
}
return f, fi, nil
} | [
"func",
"openStat",
"(",
"fs",
"http",
".",
"FileSystem",
",",
"name",
"string",
")",
"(",
"http",
".",
"File",
",",
"os",
".",
"FileInfo",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"fs",
".",
"Open",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"fi",
",",
"err",
":=",
"f",
".",
"Stat",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"f",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"f",
",",
"fi",
",",
"nil",
"\n",
"}"
] | // openStat performs Open and Stat and returns results, or first error encountered.
// The caller is responsible for closing the returned file when done. | [
"openStat",
"performs",
"Open",
"and",
"Stat",
"and",
"returns",
"results",
"or",
"first",
"error",
"encountered",
".",
"The",
"caller",
"is",
"responsible",
"for",
"closing",
"the",
"returned",
"file",
"when",
"done",
"."
] | 74dc9339e414ad069a8d04bba7e7aafd08043a25 | https://github.com/shurcooL/httpfs/blob/74dc9339e414ad069a8d04bba7e7aafd08043a25/vfsutil/walk.go#L135-L146 |
11,975 | shurcooL/httpfs | vfsutil/vfsutil.go | Stat | func Stat(fs http.FileSystem, name string) (os.FileInfo, error) {
f, err := fs.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
return f.Stat()
} | go | func Stat(fs http.FileSystem, name string) (os.FileInfo, error) {
f, err := fs.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
return f.Stat()
} | [
"func",
"Stat",
"(",
"fs",
"http",
".",
"FileSystem",
",",
"name",
"string",
")",
"(",
"os",
".",
"FileInfo",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"fs",
".",
"Open",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"return",
"f",
".",
"Stat",
"(",
")",
"\n",
"}"
] | // Stat returns the FileInfo structure describing file. | [
"Stat",
"returns",
"the",
"FileInfo",
"structure",
"describing",
"file",
"."
] | 74dc9339e414ad069a8d04bba7e7aafd08043a25 | https://github.com/shurcooL/httpfs/blob/74dc9339e414ad069a8d04bba7e7aafd08043a25/vfsutil/vfsutil.go#L22-L29 |
11,976 | nozzle/throttler | throttler.go | New | func New(maxWorkers, totalJobs int) *Throttler {
if maxWorkers < 1 {
panic("maxWorkers has to be at least 1")
}
return &Throttler{
maxWorkers: int32(maxWorkers),
batchSize: 1,
totalJobs: int32(totalJobs),
doneChan: make(chan struct{}, totalJobs),
errsMutex: &sync.Mutex{},
}
} | go | func New(maxWorkers, totalJobs int) *Throttler {
if maxWorkers < 1 {
panic("maxWorkers has to be at least 1")
}
return &Throttler{
maxWorkers: int32(maxWorkers),
batchSize: 1,
totalJobs: int32(totalJobs),
doneChan: make(chan struct{}, totalJobs),
errsMutex: &sync.Mutex{},
}
} | [
"func",
"New",
"(",
"maxWorkers",
",",
"totalJobs",
"int",
")",
"*",
"Throttler",
"{",
"if",
"maxWorkers",
"<",
"1",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"Throttler",
"{",
"maxWorkers",
":",
"int32",
"(",
"maxWorkers",
")",
",",
"batchSize",
":",
"1",
",",
"totalJobs",
":",
"int32",
"(",
"totalJobs",
")",
",",
"doneChan",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"totalJobs",
")",
",",
"errsMutex",
":",
"&",
"sync",
".",
"Mutex",
"{",
"}",
",",
"}",
"\n",
"}"
] | // New returns a Throttler that will govern the max number of workers and will
// work with the total number of jobs. It panics if maxWorkers < 1. | [
"New",
"returns",
"a",
"Throttler",
"that",
"will",
"govern",
"the",
"max",
"number",
"of",
"workers",
"and",
"will",
"work",
"with",
"the",
"total",
"number",
"of",
"jobs",
".",
"It",
"panics",
"if",
"maxWorkers",
"<",
"1",
"."
] | 2ea982251481626167b7f83be1434b5c42540c1a | https://github.com/nozzle/throttler/blob/2ea982251481626167b7f83be1434b5c42540c1a/throttler.go#L39-L50 |
11,977 | nozzle/throttler | throttler.go | Throttle | func (t *Throttler) Throttle() int {
if atomic.LoadInt32(&t.totalJobs) < 1 {
return int(atomic.LoadInt32(&t.errorCount))
}
atomic.AddInt32(&t.jobsStarted, 1)
atomic.AddInt32(&t.workerCount, 1)
// check to see if the current number of workers equals the max number of workers
// if they are equal, wait for one to finish before continuing
if atomic.LoadInt32(&t.workerCount) == atomic.LoadInt32(&t.maxWorkers) {
atomic.AddInt32(&t.jobsCompleted, 1)
atomic.AddInt32(&t.workerCount, -1)
<-t.doneChan
}
// check to see if all of the jobs have been started, and if so, wait until all
// jobs have been completed before continuing
if atomic.LoadInt32(&t.jobsStarted) == atomic.LoadInt32(&t.totalJobs) {
for atomic.LoadInt32(&t.jobsCompleted) < atomic.LoadInt32(&t.totalJobs) {
atomic.AddInt32(&t.jobsCompleted, 1)
<-t.doneChan
}
}
return int(atomic.LoadInt32(&t.errorCount))
} | go | func (t *Throttler) Throttle() int {
if atomic.LoadInt32(&t.totalJobs) < 1 {
return int(atomic.LoadInt32(&t.errorCount))
}
atomic.AddInt32(&t.jobsStarted, 1)
atomic.AddInt32(&t.workerCount, 1)
// check to see if the current number of workers equals the max number of workers
// if they are equal, wait for one to finish before continuing
if atomic.LoadInt32(&t.workerCount) == atomic.LoadInt32(&t.maxWorkers) {
atomic.AddInt32(&t.jobsCompleted, 1)
atomic.AddInt32(&t.workerCount, -1)
<-t.doneChan
}
// check to see if all of the jobs have been started, and if so, wait until all
// jobs have been completed before continuing
if atomic.LoadInt32(&t.jobsStarted) == atomic.LoadInt32(&t.totalJobs) {
for atomic.LoadInt32(&t.jobsCompleted) < atomic.LoadInt32(&t.totalJobs) {
atomic.AddInt32(&t.jobsCompleted, 1)
<-t.doneChan
}
}
return int(atomic.LoadInt32(&t.errorCount))
} | [
"func",
"(",
"t",
"*",
"Throttler",
")",
"Throttle",
"(",
")",
"int",
"{",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"totalJobs",
")",
"<",
"1",
"{",
"return",
"int",
"(",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"errorCount",
")",
")",
"\n",
"}",
"\n",
"atomic",
".",
"AddInt32",
"(",
"&",
"t",
".",
"jobsStarted",
",",
"1",
")",
"\n",
"atomic",
".",
"AddInt32",
"(",
"&",
"t",
".",
"workerCount",
",",
"1",
")",
"\n\n",
"// check to see if the current number of workers equals the max number of workers",
"// if they are equal, wait for one to finish before continuing",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"workerCount",
")",
"==",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"maxWorkers",
")",
"{",
"atomic",
".",
"AddInt32",
"(",
"&",
"t",
".",
"jobsCompleted",
",",
"1",
")",
"\n",
"atomic",
".",
"AddInt32",
"(",
"&",
"t",
".",
"workerCount",
",",
"-",
"1",
")",
"\n",
"<-",
"t",
".",
"doneChan",
"\n",
"}",
"\n\n",
"// check to see if all of the jobs have been started, and if so, wait until all",
"// jobs have been completed before continuing",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"jobsStarted",
")",
"==",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"totalJobs",
")",
"{",
"for",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"jobsCompleted",
")",
"<",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"totalJobs",
")",
"{",
"atomic",
".",
"AddInt32",
"(",
"&",
"t",
".",
"jobsCompleted",
",",
"1",
")",
"\n",
"<-",
"t",
".",
"doneChan",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"int",
"(",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"errorCount",
")",
")",
"\n",
"}"
] | // Throttle works similarly to sync.WaitGroup, except inside your goroutine dispatch
// loop rather than after. It will not block until the number of active workers
// matches the max number of workers designated in the call to NewThrottler or
// all of the jobs have been dispatched. It stops blocking when Done has been called
// as many times as totalJobs. | [
"Throttle",
"works",
"similarly",
"to",
"sync",
".",
"WaitGroup",
"except",
"inside",
"your",
"goroutine",
"dispatch",
"loop",
"rather",
"than",
"after",
".",
"It",
"will",
"not",
"block",
"until",
"the",
"number",
"of",
"active",
"workers",
"matches",
"the",
"max",
"number",
"of",
"workers",
"designated",
"in",
"the",
"call",
"to",
"NewThrottler",
"or",
"all",
"of",
"the",
"jobs",
"have",
"been",
"dispatched",
".",
"It",
"stops",
"blocking",
"when",
"Done",
"has",
"been",
"called",
"as",
"many",
"times",
"as",
"totalJobs",
"."
] | 2ea982251481626167b7f83be1434b5c42540c1a | https://github.com/nozzle/throttler/blob/2ea982251481626167b7f83be1434b5c42540c1a/throttler.go#L76-L101 |
11,978 | nozzle/throttler | throttler.go | Done | func (t *Throttler) Done(err error) {
if err != nil {
t.errsMutex.Lock()
t.errs = append(t.errs, err)
atomic.AddInt32(&t.errorCount, 1)
t.errsMutex.Unlock()
}
t.doneChan <- struct{}{}
} | go | func (t *Throttler) Done(err error) {
if err != nil {
t.errsMutex.Lock()
t.errs = append(t.errs, err)
atomic.AddInt32(&t.errorCount, 1)
t.errsMutex.Unlock()
}
t.doneChan <- struct{}{}
} | [
"func",
"(",
"t",
"*",
"Throttler",
")",
"Done",
"(",
"err",
"error",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"t",
".",
"errsMutex",
".",
"Lock",
"(",
")",
"\n",
"t",
".",
"errs",
"=",
"append",
"(",
"t",
".",
"errs",
",",
"err",
")",
"\n",
"atomic",
".",
"AddInt32",
"(",
"&",
"t",
".",
"errorCount",
",",
"1",
")",
"\n",
"t",
".",
"errsMutex",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"t",
".",
"doneChan",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}"
] | // Done lets Throttler know that a job has been completed so that another worker
// can be activated. If Done is called less times than totalJobs,
// Throttle will block forever | [
"Done",
"lets",
"Throttler",
"know",
"that",
"a",
"job",
"has",
"been",
"completed",
"so",
"that",
"another",
"worker",
"can",
"be",
"activated",
".",
"If",
"Done",
"is",
"called",
"less",
"times",
"than",
"totalJobs",
"Throttle",
"will",
"block",
"forever"
] | 2ea982251481626167b7f83be1434b5c42540c1a | https://github.com/nozzle/throttler/blob/2ea982251481626167b7f83be1434b5c42540c1a/throttler.go#L106-L114 |
11,979 | nozzle/throttler | throttler.go | Err | func (t *Throttler) Err() error {
t.errsMutex.Lock()
defer t.errsMutex.Unlock()
if atomic.LoadInt32(&t.errorCount) == 0 {
return nil
}
return multiError(t.errs)
} | go | func (t *Throttler) Err() error {
t.errsMutex.Lock()
defer t.errsMutex.Unlock()
if atomic.LoadInt32(&t.errorCount) == 0 {
return nil
}
return multiError(t.errs)
} | [
"func",
"(",
"t",
"*",
"Throttler",
")",
"Err",
"(",
")",
"error",
"{",
"t",
".",
"errsMutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"t",
".",
"errsMutex",
".",
"Unlock",
"(",
")",
"\n",
"if",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"errorCount",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"multiError",
"(",
"t",
".",
"errs",
")",
"\n",
"}"
] | // Err returns an error representative of all errors caught by throttler | [
"Err",
"returns",
"an",
"error",
"representative",
"of",
"all",
"errors",
"caught",
"by",
"throttler"
] | 2ea982251481626167b7f83be1434b5c42540c1a | https://github.com/nozzle/throttler/blob/2ea982251481626167b7f83be1434b5c42540c1a/throttler.go#L117-L124 |
11,980 | drone/routes | routes.go | FilterParam | func (m *RouteMux) FilterParam(param string, filter http.HandlerFunc) {
if !strings.HasPrefix(param,":") {
param = ":"+param
}
m.Filter(func(w http.ResponseWriter, r *http.Request) {
p := r.URL.Query().Get(param)
if len(p) > 0 { filter(w, r) }
})
} | go | func (m *RouteMux) FilterParam(param string, filter http.HandlerFunc) {
if !strings.HasPrefix(param,":") {
param = ":"+param
}
m.Filter(func(w http.ResponseWriter, r *http.Request) {
p := r.URL.Query().Get(param)
if len(p) > 0 { filter(w, r) }
})
} | [
"func",
"(",
"m",
"*",
"RouteMux",
")",
"FilterParam",
"(",
"param",
"string",
",",
"filter",
"http",
".",
"HandlerFunc",
")",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"param",
",",
"\"",
"\"",
")",
"{",
"param",
"=",
"\"",
"\"",
"+",
"param",
"\n",
"}",
"\n\n",
"m",
".",
"Filter",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"p",
":=",
"r",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"param",
")",
"\n",
"if",
"len",
"(",
"p",
")",
">",
"0",
"{",
"filter",
"(",
"w",
",",
"r",
")",
"}",
"\n",
"}",
")",
"\n",
"}"
] | // FilterParam adds the middleware filter iff the REST URL parameter exists. | [
"FilterParam",
"adds",
"the",
"middleware",
"filter",
"iff",
"the",
"REST",
"URL",
"parameter",
"exists",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/routes.go#L140-L149 |
11,981 | drone/routes | routes.go | Write | func (w *responseWriter) Write(p []byte) (int, error) {
w.started = true
return w.writer.Write(p)
} | go | func (w *responseWriter) Write(p []byte) (int, error) {
w.started = true
return w.writer.Write(p)
} | [
"func",
"(",
"w",
"*",
"responseWriter",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"w",
".",
"started",
"=",
"true",
"\n",
"return",
"w",
".",
"writer",
".",
"Write",
"(",
"p",
")",
"\n",
"}"
] | // Write writes the data to the connection as part of an HTTP reply,
// and sets `started` to true | [
"Write",
"writes",
"the",
"data",
"to",
"the",
"connection",
"as",
"part",
"of",
"an",
"HTTP",
"reply",
"and",
"sets",
"started",
"to",
"true"
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/routes.go#L233-L236 |
11,982 | drone/routes | routes.go | WriteHeader | func (w *responseWriter) WriteHeader(code int) {
w.status = code
w.started = true
w.writer.WriteHeader(code)
} | go | func (w *responseWriter) WriteHeader(code int) {
w.status = code
w.started = true
w.writer.WriteHeader(code)
} | [
"func",
"(",
"w",
"*",
"responseWriter",
")",
"WriteHeader",
"(",
"code",
"int",
")",
"{",
"w",
".",
"status",
"=",
"code",
"\n",
"w",
".",
"started",
"=",
"true",
"\n",
"w",
".",
"writer",
".",
"WriteHeader",
"(",
"code",
")",
"\n",
"}"
] | // WriteHeader sends an HTTP response header with status code,
// and sets `started` to true | [
"WriteHeader",
"sends",
"an",
"HTTP",
"response",
"header",
"with",
"status",
"code",
"and",
"sets",
"started",
"to",
"true"
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/routes.go#L240-L244 |
11,983 | drone/routes | routes.go | ReadJson | func ReadJson(r *http.Request, v interface{}) error {
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
return err
}
return json.Unmarshal(body, v)
} | go | func ReadJson(r *http.Request, v interface{}) error {
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
return err
}
return json.Unmarshal(body, v)
} | [
"func",
"ReadJson",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"json",
".",
"Unmarshal",
"(",
"body",
",",
"v",
")",
"\n",
"}"
] | // ReadJson will parses the JSON-encoded data in the http
// Request object and stores the result in the value
// pointed to by v. | [
"ReadJson",
"will",
"parses",
"the",
"JSON",
"-",
"encoded",
"data",
"in",
"the",
"http",
"Request",
"object",
"and",
"stores",
"the",
"result",
"in",
"the",
"value",
"pointed",
"to",
"by",
"v",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/routes.go#L267-L274 |
11,984 | drone/routes | routes.go | ServeXml | func ServeXml(w http.ResponseWriter, v interface{}) {
content, err := xml.Marshal(v)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(content)))
w.Header().Set("Content-Type", "text/xml; charset=utf-8")
w.Write(content)
} | go | func ServeXml(w http.ResponseWriter, v interface{}) {
content, err := xml.Marshal(v)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(content)))
w.Header().Set("Content-Type", "text/xml; charset=utf-8")
w.Write(content)
} | [
"func",
"ServeXml",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"v",
"interface",
"{",
"}",
")",
"{",
"content",
",",
"err",
":=",
"xml",
".",
"Marshal",
"(",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"len",
"(",
"content",
")",
")",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Write",
"(",
"content",
")",
"\n",
"}"
] | // ServeXml replies to the request with an XML
// representation of resource v. | [
"ServeXml",
"replies",
"to",
"the",
"request",
"with",
"an",
"XML",
"representation",
"of",
"resource",
"v",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/routes.go#L278-L287 |
11,985 | drone/routes | routes.go | ReadXml | func ReadXml(r *http.Request, v interface{}) error {
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
return err
}
return xml.Unmarshal(body, v)
} | go | func ReadXml(r *http.Request, v interface{}) error {
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
return err
}
return xml.Unmarshal(body, v)
} | [
"func",
"ReadXml",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"xml",
".",
"Unmarshal",
"(",
"body",
",",
"v",
")",
"\n",
"}"
] | // ReadXml will parses the XML-encoded data in the http
// Request object and stores the result in the value
// pointed to by v. | [
"ReadXml",
"will",
"parses",
"the",
"XML",
"-",
"encoded",
"data",
"in",
"the",
"http",
"Request",
"object",
"and",
"stores",
"the",
"result",
"in",
"the",
"value",
"pointed",
"to",
"by",
"v",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/routes.go#L292-L299 |
11,986 | drone/routes | routes.go | ServeFormatted | func ServeFormatted(w http.ResponseWriter, r *http.Request, v interface{}) {
accept := r.Header.Get("Accept")
switch accept {
case applicationJson:
ServeJson(w, v)
case applicationXml, textXml:
ServeXml(w, v)
default:
ServeJson(w, v)
}
return
} | go | func ServeFormatted(w http.ResponseWriter, r *http.Request, v interface{}) {
accept := r.Header.Get("Accept")
switch accept {
case applicationJson:
ServeJson(w, v)
case applicationXml, textXml:
ServeXml(w, v)
default:
ServeJson(w, v)
}
return
} | [
"func",
"ServeFormatted",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"v",
"interface",
"{",
"}",
")",
"{",
"accept",
":=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"switch",
"accept",
"{",
"case",
"applicationJson",
":",
"ServeJson",
"(",
"w",
",",
"v",
")",
"\n",
"case",
"applicationXml",
",",
"textXml",
":",
"ServeXml",
"(",
"w",
",",
"v",
")",
"\n",
"default",
":",
"ServeJson",
"(",
"w",
",",
"v",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // ServeFormatted replies to the request with
// a formatted representation of resource v, in the
// format requested by the client specified in the
// Accept header. | [
"ServeFormatted",
"replies",
"to",
"the",
"request",
"with",
"a",
"formatted",
"representation",
"of",
"resource",
"v",
"in",
"the",
"format",
"requested",
"by",
"the",
"client",
"specified",
"in",
"the",
"Accept",
"header",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/routes.go#L305-L317 |
11,987 | drone/routes | exp/routes/routes.go | FilterParam | func (r *Router) FilterParam(param string, filter http.HandlerFunc) {
r.Filter(func(w http.ResponseWriter, req *http.Request) {
c := NewContext(req)
if len(c.Params.Get(param)) > 0 { filter(w, req) }
})
} | go | func (r *Router) FilterParam(param string, filter http.HandlerFunc) {
r.Filter(func(w http.ResponseWriter, req *http.Request) {
c := NewContext(req)
if len(c.Params.Get(param)) > 0 { filter(w, req) }
})
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"FilterParam",
"(",
"param",
"string",
",",
"filter",
"http",
".",
"HandlerFunc",
")",
"{",
"r",
".",
"Filter",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"c",
":=",
"NewContext",
"(",
"req",
")",
"\n",
"if",
"len",
"(",
"c",
".",
"Params",
".",
"Get",
"(",
"param",
")",
")",
">",
"0",
"{",
"filter",
"(",
"w",
",",
"req",
")",
"}",
"\n",
"}",
")",
"\n",
"}"
] | // FilterParam adds the middleware filter iff the URL parameter exists. | [
"FilterParam",
"adds",
"the",
"middleware",
"filter",
"iff",
"the",
"URL",
"parameter",
"exists",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/exp/routes/routes.go#L136-L141 |
11,988 | drone/routes | exp/routes/routes.go | Template | func (r *Router) Template(t *template.Template) {
r.Lock()
defer r.Unlock()
r.views = template.Must(t.Clone())
} | go | func (r *Router) Template(t *template.Template) {
r.Lock()
defer r.Unlock()
r.views = template.Must(t.Clone())
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Template",
"(",
"t",
"*",
"template",
".",
"Template",
")",
"{",
"r",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"Unlock",
"(",
")",
"\n",
"r",
".",
"views",
"=",
"template",
".",
"Must",
"(",
"t",
".",
"Clone",
"(",
")",
")",
"\n",
"}"
] | // Template uses the provided template definitions. | [
"Template",
"uses",
"the",
"provided",
"template",
"definitions",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/exp/routes/routes.go#L218-L222 |
11,989 | drone/routes | exp/routes/routes.go | TemplateFiles | func (r *Router) TemplateFiles(filenames ...string) {
r.Lock()
defer r.Unlock()
r.views = template.Must(template.ParseFiles(filenames...))
} | go | func (r *Router) TemplateFiles(filenames ...string) {
r.Lock()
defer r.Unlock()
r.views = template.Must(template.ParseFiles(filenames...))
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"TemplateFiles",
"(",
"filenames",
"...",
"string",
")",
"{",
"r",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"Unlock",
"(",
")",
"\n",
"r",
".",
"views",
"=",
"template",
".",
"Must",
"(",
"template",
".",
"ParseFiles",
"(",
"filenames",
"...",
")",
")",
"\n",
"}"
] | // TemplateFiles parses the template definitions from the named files. | [
"TemplateFiles",
"parses",
"the",
"template",
"definitions",
"from",
"the",
"named",
"files",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/exp/routes/routes.go#L225-L229 |
11,990 | drone/routes | exp/routes/routes.go | TemplateGlob | func (r *Router) TemplateGlob(pattern string) {
r.Lock()
defer r.Unlock()
r.views = template.Must(template.ParseGlob(pattern))
} | go | func (r *Router) TemplateGlob(pattern string) {
r.Lock()
defer r.Unlock()
r.views = template.Must(template.ParseGlob(pattern))
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"TemplateGlob",
"(",
"pattern",
"string",
")",
"{",
"r",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"Unlock",
"(",
")",
"\n",
"r",
".",
"views",
"=",
"template",
".",
"Must",
"(",
"template",
".",
"ParseGlob",
"(",
"pattern",
")",
")",
"\n",
"}"
] | // TemplateGlob parses the template definitions from the files identified
// by the pattern, which must match at least one file. | [
"TemplateGlob",
"parses",
"the",
"template",
"definitions",
"from",
"the",
"files",
"identified",
"by",
"the",
"pattern",
"which",
"must",
"match",
"at",
"least",
"one",
"file",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/exp/routes/routes.go#L233-L237 |
11,991 | drone/routes | exp/user/user.go | Decode | func Decode(v string) *User {
values, err := url.ParseQuery(v)
if err != nil {
return nil
}
attrs := map[string]string{}
for key, _ := range values {
attrs[key]=values.Get(key)
}
return &User {
Id : values.Get("id"),
Name : values.Get("name"),
Email : values.Get("email"),
Photo : values.Get("photo"),
Attrs : attrs,
}
} | go | func Decode(v string) *User {
values, err := url.ParseQuery(v)
if err != nil {
return nil
}
attrs := map[string]string{}
for key, _ := range values {
attrs[key]=values.Get(key)
}
return &User {
Id : values.Get("id"),
Name : values.Get("name"),
Email : values.Get("email"),
Photo : values.Get("photo"),
Attrs : attrs,
}
} | [
"func",
"Decode",
"(",
"v",
"string",
")",
"*",
"User",
"{",
"values",
",",
"err",
":=",
"url",
".",
"ParseQuery",
"(",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"attrs",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"key",
",",
"_",
":=",
"range",
"values",
"{",
"attrs",
"[",
"key",
"]",
"=",
"values",
".",
"Get",
"(",
"key",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"User",
"{",
"Id",
":",
"values",
".",
"Get",
"(",
"\"",
"\"",
")",
",",
"Name",
":",
"values",
".",
"Get",
"(",
"\"",
"\"",
")",
",",
"Email",
":",
"values",
".",
"Get",
"(",
"\"",
"\"",
")",
",",
"Photo",
":",
"values",
".",
"Get",
"(",
"\"",
"\"",
")",
",",
"Attrs",
":",
"attrs",
",",
"}",
"\n",
"}"
] | // Decode will create a user from a URL Query string. | [
"Decode",
"will",
"create",
"a",
"user",
"from",
"a",
"URL",
"Query",
"string",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/exp/user/user.go#L26-L44 |
11,992 | drone/routes | exp/user/user.go | Encode | func (u *User) Encode() string {
values := url.Values{}
// add custom attributes
if u.Attrs != nil {
for key, val := range u.Attrs {
values.Set(key, val)
}
}
values.Set("id", u.Id)
values.Set("name", u.Name)
values.Set("email", u.Email)
values.Set("photo", u.Photo)
return values.Encode()
} | go | func (u *User) Encode() string {
values := url.Values{}
// add custom attributes
if u.Attrs != nil {
for key, val := range u.Attrs {
values.Set(key, val)
}
}
values.Set("id", u.Id)
values.Set("name", u.Name)
values.Set("email", u.Email)
values.Set("photo", u.Photo)
return values.Encode()
} | [
"func",
"(",
"u",
"*",
"User",
")",
"Encode",
"(",
")",
"string",
"{",
"values",
":=",
"url",
".",
"Values",
"{",
"}",
"\n\n",
"// add custom attributes",
"if",
"u",
".",
"Attrs",
"!=",
"nil",
"{",
"for",
"key",
",",
"val",
":=",
"range",
"u",
".",
"Attrs",
"{",
"values",
".",
"Set",
"(",
"key",
",",
"val",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"values",
".",
"Set",
"(",
"\"",
"\"",
",",
"u",
".",
"Id",
")",
"\n",
"values",
".",
"Set",
"(",
"\"",
"\"",
",",
"u",
".",
"Name",
")",
"\n",
"values",
".",
"Set",
"(",
"\"",
"\"",
",",
"u",
".",
"Email",
")",
"\n",
"values",
".",
"Set",
"(",
"\"",
"\"",
",",
"u",
".",
"Photo",
")",
"\n",
"return",
"values",
".",
"Encode",
"(",
")",
"\n",
"}"
] | // Encode will encode a user as a URL query string. | [
"Encode",
"will",
"encode",
"a",
"user",
"as",
"a",
"URL",
"query",
"string",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/exp/user/user.go#L47-L62 |
11,993 | drone/routes | exp/user/user.go | Current | func Current(c *context.Context) *User {
v := c.Values.Get(userKey)
if v == nil {
return nil
}
u, ok := v.(*User)
if !ok {
return nil
}
return u
} | go | func Current(c *context.Context) *User {
v := c.Values.Get(userKey)
if v == nil {
return nil
}
u, ok := v.(*User)
if !ok {
return nil
}
return u
} | [
"func",
"Current",
"(",
"c",
"*",
"context",
".",
"Context",
")",
"*",
"User",
"{",
"v",
":=",
"c",
".",
"Values",
".",
"Get",
"(",
"userKey",
")",
"\n",
"if",
"v",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"u",
",",
"ok",
":=",
"v",
".",
"(",
"*",
"User",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"u",
"\n",
"}"
] | // Current returns the currently logged-in user, or nil if the user is not
// signed in. | [
"Current",
"returns",
"the",
"currently",
"logged",
"-",
"in",
"user",
"or",
"nil",
"if",
"the",
"user",
"is",
"not",
"signed",
"in",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/exp/user/user.go#L66-L78 |
11,994 | drone/routes | exp/user/user.go | Set | func Set(c *context.Context, u *User) {
c.Values.Set(userKey, u)
} | go | func Set(c *context.Context, u *User) {
c.Values.Set(userKey, u)
} | [
"func",
"Set",
"(",
"c",
"*",
"context",
".",
"Context",
",",
"u",
"*",
"User",
")",
"{",
"c",
".",
"Values",
".",
"Set",
"(",
"userKey",
",",
"u",
")",
"\n",
"}"
] | // Set sets the currently logged-in user. This is typically used by middleware
// that handles user authentication. | [
"Set",
"sets",
"the",
"currently",
"logged",
"-",
"in",
"user",
".",
"This",
"is",
"typically",
"used",
"by",
"middleware",
"that",
"handles",
"user",
"authentication",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/exp/user/user.go#L82-L84 |
11,995 | drone/routes | exp/cookie/cookie.go | Sign | func Sign(cookie *http.Cookie, secret string, expires time.Time) {
val := SignStr(cookie.Value, secret, expires)
cookie.Value = val
} | go | func Sign(cookie *http.Cookie, secret string, expires time.Time) {
val := SignStr(cookie.Value, secret, expires)
cookie.Value = val
} | [
"func",
"Sign",
"(",
"cookie",
"*",
"http",
".",
"Cookie",
",",
"secret",
"string",
",",
"expires",
"time",
".",
"Time",
")",
"{",
"val",
":=",
"SignStr",
"(",
"cookie",
".",
"Value",
",",
"secret",
",",
"expires",
")",
"\n",
"cookie",
".",
"Value",
"=",
"val",
"\n",
"}"
] | // Sign signs and timestamps a cookie so it cannot be forged. | [
"Sign",
"signs",
"and",
"timestamps",
"a",
"cookie",
"so",
"it",
"cannot",
"be",
"forged",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/exp/cookie/cookie.go#L11-L14 |
11,996 | drone/routes | exp/cookie/cookie.go | SignStr | func SignStr(value, secret string, expires time.Time) string {
return authcookie.New(value, expires, []byte(secret))
} | go | func SignStr(value, secret string, expires time.Time) string {
return authcookie.New(value, expires, []byte(secret))
} | [
"func",
"SignStr",
"(",
"value",
",",
"secret",
"string",
",",
"expires",
"time",
".",
"Time",
")",
"string",
"{",
"return",
"authcookie",
".",
"New",
"(",
"value",
",",
"expires",
",",
"[",
"]",
"byte",
"(",
"secret",
")",
")",
"\n",
"}"
] | // SignStr signs and timestamps a string so it cannot be forged.
//
// Normally used via Sign, but provided as a separate method for
// non-cookie uses. To decode a value not stored as a cookie use the
// DecodeStr function. | [
"SignStr",
"signs",
"and",
"timestamps",
"a",
"string",
"so",
"it",
"cannot",
"be",
"forged",
".",
"Normally",
"used",
"via",
"Sign",
"but",
"provided",
"as",
"a",
"separate",
"method",
"for",
"non",
"-",
"cookie",
"uses",
".",
"To",
"decode",
"a",
"value",
"not",
"stored",
"as",
"a",
"cookie",
"use",
"the",
"DecodeStr",
"function",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/exp/cookie/cookie.go#L21-L23 |
11,997 | drone/routes | exp/cookie/cookie.go | Decode | func Decode(cookie *http.Cookie, secret string) string {
return DecodeStr(cookie.Value, secret)
} | go | func Decode(cookie *http.Cookie, secret string) string {
return DecodeStr(cookie.Value, secret)
} | [
"func",
"Decode",
"(",
"cookie",
"*",
"http",
".",
"Cookie",
",",
"secret",
"string",
")",
"string",
"{",
"return",
"DecodeStr",
"(",
"cookie",
".",
"Value",
",",
"secret",
")",
"\n",
"}"
] | // DecodeStr returns the given signed cookie value if it validates,
// else returns an empty string. | [
"DecodeStr",
"returns",
"the",
"given",
"signed",
"cookie",
"value",
"if",
"it",
"validates",
"else",
"returns",
"an",
"empty",
"string",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/exp/cookie/cookie.go#L27-L29 |
11,998 | drone/routes | exp/cookie/cookie.go | DecodeStr | func DecodeStr(value, secret string) string {
return authcookie.Login(value, []byte(secret))
} | go | func DecodeStr(value, secret string) string {
return authcookie.Login(value, []byte(secret))
} | [
"func",
"DecodeStr",
"(",
"value",
",",
"secret",
"string",
")",
"string",
"{",
"return",
"authcookie",
".",
"Login",
"(",
"value",
",",
"[",
"]",
"byte",
"(",
"secret",
")",
")",
"\n",
"}"
] | // DecodeStr returns the given signed value if it validates,
// else returns an empty string. | [
"DecodeStr",
"returns",
"the",
"given",
"signed",
"value",
"if",
"it",
"validates",
"else",
"returns",
"an",
"empty",
"string",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/exp/cookie/cookie.go#L33-L35 |
11,999 | drone/routes | exp/cookie/cookie.go | Clear | func Clear(w http.ResponseWriter, r *http.Request, name string) {
cookie := http.Cookie{
Name: name,
Value: "deleted",
Path: "/",
Domain: r.URL.Host,
MaxAge: -1,
}
http.SetCookie(w, &cookie)
} | go | func Clear(w http.ResponseWriter, r *http.Request, name string) {
cookie := http.Cookie{
Name: name,
Value: "deleted",
Path: "/",
Domain: r.URL.Host,
MaxAge: -1,
}
http.SetCookie(w, &cookie)
} | [
"func",
"Clear",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"name",
"string",
")",
"{",
"cookie",
":=",
"http",
".",
"Cookie",
"{",
"Name",
":",
"name",
",",
"Value",
":",
"\"",
"\"",
",",
"Path",
":",
"\"",
"\"",
",",
"Domain",
":",
"r",
".",
"URL",
".",
"Host",
",",
"MaxAge",
":",
"-",
"1",
",",
"}",
"\n\n",
"http",
".",
"SetCookie",
"(",
"w",
",",
"&",
"cookie",
")",
"\n",
"}"
] | // Clear deletes the cookie with the given name. | [
"Clear",
"deletes",
"the",
"cookie",
"with",
"the",
"given",
"name",
"."
] | 853bef2b231162bb7b09355720416d3af1510d88 | https://github.com/drone/routes/blob/853bef2b231162bb7b09355720416d3af1510d88/exp/cookie/cookie.go#L38-L48 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.