repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
brianvoe/gofakeit | datetime.go | TimeZoneOffset | func TimeZoneOffset() float32 {
value, _ := strconv.ParseFloat(getRandValue([]string{"timezone", "offset"}), 32)
return float32(value)
} | go | func TimeZoneOffset() float32 {
value, _ := strconv.ParseFloat(getRandValue([]string{"timezone", "offset"}), 32)
return float32(value)
} | [
"func",
"TimeZoneOffset",
"(",
")",
"float32",
"{",
"value",
",",
"_",
":=",
"strconv",
".",
"ParseFloat",
"(",
"getRandValue",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
",",
"32",
")",
"\n",
"return",
"float32",
"(",
"va... | // TimeZoneOffset will select a random timezone offset | [
"TimeZoneOffset",
"will",
"select",
"a",
"random",
"timezone",
"offset"
] | a5ac7cef41d64b726c51e8826e02dad0c34f55b4 | https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/datetime.go#L74-L77 | train |
brianvoe/gofakeit | internet.go | URL | func URL() string {
url := "http" + RandString([]string{"s", ""}) + "://www."
url += DomainName()
// Slugs
num := Number(1, 4)
slug := make([]string, num)
for i := 0; i < num; i++ {
slug[i] = BS()
}
url += "/" + strings.ToLower(strings.Join(slug, "/"))
return url
} | go | func URL() string {
url := "http" + RandString([]string{"s", ""}) + "://www."
url += DomainName()
// Slugs
num := Number(1, 4)
slug := make([]string, num)
for i := 0; i < num; i++ {
slug[i] = BS()
}
url += "/" + strings.ToLower(strings.Join(slug, "/"))
return url
} | [
"func",
"URL",
"(",
")",
"string",
"{",
"url",
":=",
"\"",
"\"",
"+",
"RandString",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
"+",
"\"",
"\"",
"\n",
"url",
"+=",
"DomainName",
"(",
")",
"\n\n",
"// Slugs",
"num",
":="... | // URL will generate a random url string | [
"URL",
"will",
"generate",
"a",
"random",
"url",
"string"
] | a5ac7cef41d64b726c51e8826e02dad0c34f55b4 | https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/internet.go#L20-L33 | train |
brianvoe/gofakeit | internet.go | IPv4Address | func IPv4Address() string {
num := func() int { return 2 + rand.Intn(254) }
return fmt.Sprintf("%d.%d.%d.%d", num(), num(), num(), num())
} | go | func IPv4Address() string {
num := func() int { return 2 + rand.Intn(254) }
return fmt.Sprintf("%d.%d.%d.%d", num(), num(), num(), num())
} | [
"func",
"IPv4Address",
"(",
")",
"string",
"{",
"num",
":=",
"func",
"(",
")",
"int",
"{",
"return",
"2",
"+",
"rand",
".",
"Intn",
"(",
"254",
")",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"num",
"(",
")",
",",
"num",
... | // IPv4Address will generate a random version 4 ip address | [
"IPv4Address",
"will",
"generate",
"a",
"random",
"version",
"4",
"ip",
"address"
] | a5ac7cef41d64b726c51e8826e02dad0c34f55b4 | https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/internet.go#L41-L44 | train |
brianvoe/gofakeit | internet.go | IPv6Address | func IPv6Address() string {
num := 65536
return fmt.Sprintf("2001:cafe:%x:%x:%x:%x:%x:%x", rand.Intn(num), rand.Intn(num), rand.Intn(num), rand.Intn(num), rand.Intn(num), rand.Intn(num))
} | go | func IPv6Address() string {
num := 65536
return fmt.Sprintf("2001:cafe:%x:%x:%x:%x:%x:%x", rand.Intn(num), rand.Intn(num), rand.Intn(num), rand.Intn(num), rand.Intn(num), rand.Intn(num))
} | [
"func",
"IPv6Address",
"(",
")",
"string",
"{",
"num",
":=",
"65536",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"rand",
".",
"Intn",
"(",
"num",
")",
",",
"rand",
".",
"Intn",
"(",
"num",
")",
",",
"rand",
".",
"Intn",
"(",
"... | // IPv6Address will generate a random version 6 ip address | [
"IPv6Address",
"will",
"generate",
"a",
"random",
"version",
"6",
"ip",
"address"
] | a5ac7cef41d64b726c51e8826e02dad0c34f55b4 | https://github.com/brianvoe/gofakeit/blob/a5ac7cef41d64b726c51e8826e02dad0c34f55b4/internet.go#L47-L50 | train |
gorilla/handlers | cors.go | AllowedMethods | func AllowedMethods(methods []string) CORSOption {
return func(ch *cors) error {
ch.allowedMethods = []string{}
for _, v := range methods {
normalizedMethod := strings.ToUpper(strings.TrimSpace(v))
if normalizedMethod == "" {
continue
}
if !ch.isMatch(normalizedMethod, ch.allowedMethods) {
ch.allowedMethods = append(ch.allowedMethods, normalizedMethod)
}
}
return nil
}
} | go | func AllowedMethods(methods []string) CORSOption {
return func(ch *cors) error {
ch.allowedMethods = []string{}
for _, v := range methods {
normalizedMethod := strings.ToUpper(strings.TrimSpace(v))
if normalizedMethod == "" {
continue
}
if !ch.isMatch(normalizedMethod, ch.allowedMethods) {
ch.allowedMethods = append(ch.allowedMethods, normalizedMethod)
}
}
return nil
}
} | [
"func",
"AllowedMethods",
"(",
"methods",
"[",
"]",
"string",
")",
"CORSOption",
"{",
"return",
"func",
"(",
"ch",
"*",
"cors",
")",
"error",
"{",
"ch",
".",
"allowedMethods",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"ra... | // AllowedMethods can be used to explicitly allow methods in the
// Access-Control-Allow-Methods header.
// This is a replacement operation so you must also
// pass GET, HEAD, and POST if you wish to support those methods. | [
"AllowedMethods",
"can",
"be",
"used",
"to",
"explicitly",
"allow",
"methods",
"in",
"the",
"Access",
"-",
"Control",
"-",
"Allow",
"-",
"Methods",
"header",
".",
"This",
"is",
"a",
"replacement",
"operation",
"so",
"you",
"must",
"also",
"pass",
"GET",
"H... | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/cors.go#L214-L230 | train |
gorilla/handlers | cors.go | AllowedOriginValidator | func AllowedOriginValidator(fn OriginValidator) CORSOption {
return func(ch *cors) error {
ch.allowedOriginValidator = fn
return nil
}
} | go | func AllowedOriginValidator(fn OriginValidator) CORSOption {
return func(ch *cors) error {
ch.allowedOriginValidator = fn
return nil
}
} | [
"func",
"AllowedOriginValidator",
"(",
"fn",
"OriginValidator",
")",
"CORSOption",
"{",
"return",
"func",
"(",
"ch",
"*",
"cors",
")",
"error",
"{",
"ch",
".",
"allowedOriginValidator",
"=",
"fn",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // AllowedOriginValidator sets a function for evaluating allowed origins in CORS requests, represented by the
// 'Allow-Access-Control-Origin' HTTP header. | [
"AllowedOriginValidator",
"sets",
"a",
"function",
"for",
"evaluating",
"allowed",
"origins",
"in",
"CORS",
"requests",
"represented",
"by",
"the",
"Allow",
"-",
"Access",
"-",
"Control",
"-",
"Origin",
"HTTP",
"header",
"."
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/cors.go#L251-L256 | train |
gorilla/handlers | cors.go | ExposedHeaders | func ExposedHeaders(headers []string) CORSOption {
return func(ch *cors) error {
ch.exposedHeaders = []string{}
for _, v := range headers {
normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))
if normalizedHeader == "" {
continue
}
if !ch.isMatch(normalizedHeader, ch.exposedHeaders) {
ch.exposedHeaders = append(ch.exposedHeaders, normalizedHeader)
}
}
return nil
}
} | go | func ExposedHeaders(headers []string) CORSOption {
return func(ch *cors) error {
ch.exposedHeaders = []string{}
for _, v := range headers {
normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))
if normalizedHeader == "" {
continue
}
if !ch.isMatch(normalizedHeader, ch.exposedHeaders) {
ch.exposedHeaders = append(ch.exposedHeaders, normalizedHeader)
}
}
return nil
}
} | [
"func",
"ExposedHeaders",
"(",
"headers",
"[",
"]",
"string",
")",
"CORSOption",
"{",
"return",
"func",
"(",
"ch",
"*",
"cors",
")",
"error",
"{",
"ch",
".",
"exposedHeaders",
"=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"ra... | // ExposedHeaders can be used to specify headers that are available
// and will not be stripped out by the user-agent. | [
"ExposedHeaders",
"can",
"be",
"used",
"to",
"specify",
"headers",
"that",
"are",
"available",
"and",
"will",
"not",
"be",
"stripped",
"out",
"by",
"the",
"user",
"-",
"agent",
"."
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/cors.go#L273-L289 | train |
gorilla/handlers | logging.go | buildCommonLogLine | func buildCommonLogLine(req *http.Request, url url.URL, ts time.Time, status int, size int) []byte {
username := "-"
if url.User != nil {
if name := url.User.Username(); name != "" {
username = name
}
}
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
host = req.RemoteAddr
}
uri := req.RequestURI
// Requests using the CONNECT method over HTTP/2.0 must use
// the authority field (aka r.Host) to identify the target.
// Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT
if req.ProtoMajor == 2 && req.Method == "CONNECT" {
uri = req.Host
}
if uri == "" {
uri = url.RequestURI()
}
buf := make([]byte, 0, 3*(len(host)+len(username)+len(req.Method)+len(uri)+len(req.Proto)+50)/2)
buf = append(buf, host...)
buf = append(buf, " - "...)
buf = append(buf, username...)
buf = append(buf, " ["...)
buf = append(buf, ts.Format("02/Jan/2006:15:04:05 -0700")...)
buf = append(buf, `] "`...)
buf = append(buf, req.Method...)
buf = append(buf, " "...)
buf = appendQuoted(buf, uri)
buf = append(buf, " "...)
buf = append(buf, req.Proto...)
buf = append(buf, `" `...)
buf = append(buf, strconv.Itoa(status)...)
buf = append(buf, " "...)
buf = append(buf, strconv.Itoa(size)...)
return buf
} | go | func buildCommonLogLine(req *http.Request, url url.URL, ts time.Time, status int, size int) []byte {
username := "-"
if url.User != nil {
if name := url.User.Username(); name != "" {
username = name
}
}
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
host = req.RemoteAddr
}
uri := req.RequestURI
// Requests using the CONNECT method over HTTP/2.0 must use
// the authority field (aka r.Host) to identify the target.
// Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT
if req.ProtoMajor == 2 && req.Method == "CONNECT" {
uri = req.Host
}
if uri == "" {
uri = url.RequestURI()
}
buf := make([]byte, 0, 3*(len(host)+len(username)+len(req.Method)+len(uri)+len(req.Proto)+50)/2)
buf = append(buf, host...)
buf = append(buf, " - "...)
buf = append(buf, username...)
buf = append(buf, " ["...)
buf = append(buf, ts.Format("02/Jan/2006:15:04:05 -0700")...)
buf = append(buf, `] "`...)
buf = append(buf, req.Method...)
buf = append(buf, " "...)
buf = appendQuoted(buf, uri)
buf = append(buf, " "...)
buf = append(buf, req.Proto...)
buf = append(buf, `" `...)
buf = append(buf, strconv.Itoa(status)...)
buf = append(buf, " "...)
buf = append(buf, strconv.Itoa(size)...)
return buf
} | [
"func",
"buildCommonLogLine",
"(",
"req",
"*",
"http",
".",
"Request",
",",
"url",
"url",
".",
"URL",
",",
"ts",
"time",
".",
"Time",
",",
"status",
"int",
",",
"size",
"int",
")",
"[",
"]",
"byte",
"{",
"username",
":=",
"\"",
"\"",
"\n",
"if",
... | // buildCommonLogLine builds a log entry for req in Apache Common Log Format.
// ts is the timestamp with which the entry should be logged.
// status and size are used to provide the response HTTP status and size. | [
"buildCommonLogLine",
"builds",
"a",
"log",
"entry",
"for",
"req",
"in",
"Apache",
"Common",
"Log",
"Format",
".",
"ts",
"is",
"the",
"timestamp",
"with",
"which",
"the",
"entry",
"should",
"be",
"logged",
".",
"status",
"and",
"size",
"are",
"used",
"to",... | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/logging.go#L151-L194 | train |
gorilla/handlers | logging.go | writeLog | func writeLog(writer io.Writer, params LogFormatterParams) {
buf := buildCommonLogLine(params.Request, params.URL, params.TimeStamp, params.StatusCode, params.Size)
buf = append(buf, '\n')
writer.Write(buf)
} | go | func writeLog(writer io.Writer, params LogFormatterParams) {
buf := buildCommonLogLine(params.Request, params.URL, params.TimeStamp, params.StatusCode, params.Size)
buf = append(buf, '\n')
writer.Write(buf)
} | [
"func",
"writeLog",
"(",
"writer",
"io",
".",
"Writer",
",",
"params",
"LogFormatterParams",
")",
"{",
"buf",
":=",
"buildCommonLogLine",
"(",
"params",
".",
"Request",
",",
"params",
".",
"URL",
",",
"params",
".",
"TimeStamp",
",",
"params",
".",
"Status... | // writeLog writes a log entry for req to w in Apache Common Log Format.
// ts is the timestamp with which the entry should be logged.
// status and size are used to provide the response HTTP status and size. | [
"writeLog",
"writes",
"a",
"log",
"entry",
"for",
"req",
"to",
"w",
"in",
"Apache",
"Common",
"Log",
"Format",
".",
"ts",
"is",
"the",
"timestamp",
"with",
"which",
"the",
"entry",
"should",
"be",
"logged",
".",
"status",
"and",
"size",
"are",
"used",
... | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/logging.go#L199-L203 | train |
gorilla/handlers | logging.go | writeCombinedLog | func writeCombinedLog(writer io.Writer, params LogFormatterParams) {
buf := buildCommonLogLine(params.Request, params.URL, params.TimeStamp, params.StatusCode, params.Size)
buf = append(buf, ` "`...)
buf = appendQuoted(buf, params.Request.Referer())
buf = append(buf, `" "`...)
buf = appendQuoted(buf, params.Request.UserAgent())
buf = append(buf, '"', '\n')
writer.Write(buf)
} | go | func writeCombinedLog(writer io.Writer, params LogFormatterParams) {
buf := buildCommonLogLine(params.Request, params.URL, params.TimeStamp, params.StatusCode, params.Size)
buf = append(buf, ` "`...)
buf = appendQuoted(buf, params.Request.Referer())
buf = append(buf, `" "`...)
buf = appendQuoted(buf, params.Request.UserAgent())
buf = append(buf, '"', '\n')
writer.Write(buf)
} | [
"func",
"writeCombinedLog",
"(",
"writer",
"io",
".",
"Writer",
",",
"params",
"LogFormatterParams",
")",
"{",
"buf",
":=",
"buildCommonLogLine",
"(",
"params",
".",
"Request",
",",
"params",
".",
"URL",
",",
"params",
".",
"TimeStamp",
",",
"params",
".",
... | // writeCombinedLog writes a log entry for req to w in Apache Combined Log Format.
// ts is the timestamp with which the entry should be logged.
// status and size are used to provide the response HTTP status and size. | [
"writeCombinedLog",
"writes",
"a",
"log",
"entry",
"for",
"req",
"to",
"w",
"in",
"Apache",
"Combined",
"Log",
"Format",
".",
"ts",
"is",
"the",
"timestamp",
"with",
"which",
"the",
"entry",
"should",
"be",
"logged",
".",
"status",
"and",
"size",
"are",
... | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/logging.go#L208-L216 | train |
gorilla/handlers | logging.go | CustomLoggingHandler | func CustomLoggingHandler(out io.Writer, h http.Handler, f LogFormatter) http.Handler {
return loggingHandler{out, h, f}
} | go | func CustomLoggingHandler(out io.Writer, h http.Handler, f LogFormatter) http.Handler {
return loggingHandler{out, h, f}
} | [
"func",
"CustomLoggingHandler",
"(",
"out",
"io",
".",
"Writer",
",",
"h",
"http",
".",
"Handler",
",",
"f",
"LogFormatter",
")",
"http",
".",
"Handler",
"{",
"return",
"loggingHandler",
"{",
"out",
",",
"h",
",",
"f",
"}",
"\n",
"}"
] | // CustomLoggingHandler provides a way to supply a custom log formatter
// while taking advantage of the mechanisms in this package | [
"CustomLoggingHandler",
"provides",
"a",
"way",
"to",
"supply",
"a",
"custom",
"log",
"formatter",
"while",
"taking",
"advantage",
"of",
"the",
"mechanisms",
"in",
"this",
"package"
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/logging.go#L250-L252 | train |
gorilla/handlers | handlers.go | isContentType | func isContentType(h http.Header, contentType string) bool {
ct := h.Get("Content-Type")
if i := strings.IndexRune(ct, ';'); i != -1 {
ct = ct[0:i]
}
return ct == contentType
} | go | func isContentType(h http.Header, contentType string) bool {
ct := h.Get("Content-Type")
if i := strings.IndexRune(ct, ';'); i != -1 {
ct = ct[0:i]
}
return ct == contentType
} | [
"func",
"isContentType",
"(",
"h",
"http",
".",
"Header",
",",
"contentType",
"string",
")",
"bool",
"{",
"ct",
":=",
"h",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"i",
":=",
"strings",
".",
"IndexRune",
"(",
"ct",
",",
"';'",
")",
";",
"i",... | // isContentType validates the Content-Type header matches the supplied
// contentType. That is, its type and subtype match. | [
"isContentType",
"validates",
"the",
"Content",
"-",
"Type",
"header",
"matches",
"the",
"supplied",
"contentType",
".",
"That",
"is",
"its",
"type",
"and",
"subtype",
"match",
"."
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/handlers.go#L112-L118 | train |
gorilla/handlers | handlers.go | ContentTypeHandler | func ContentTypeHandler(h http.Handler, contentTypes ...string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !(r.Method == "PUT" || r.Method == "POST" || r.Method == "PATCH") {
h.ServeHTTP(w, r)
return
}
for _, ct := range contentTypes {
if isContentType(r.Header, ct) {
h.ServeHTTP(w, r)
return
}
}
http.Error(w, fmt.Sprintf("Unsupported content type %q; expected one of %q", r.Header.Get("Content-Type"), contentTypes), http.StatusUnsupportedMediaType)
})
} | go | func ContentTypeHandler(h http.Handler, contentTypes ...string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !(r.Method == "PUT" || r.Method == "POST" || r.Method == "PATCH") {
h.ServeHTTP(w, r)
return
}
for _, ct := range contentTypes {
if isContentType(r.Header, ct) {
h.ServeHTTP(w, r)
return
}
}
http.Error(w, fmt.Sprintf("Unsupported content type %q; expected one of %q", r.Header.Get("Content-Type"), contentTypes), http.StatusUnsupportedMediaType)
})
} | [
"func",
"ContentTypeHandler",
"(",
"h",
"http",
".",
"Handler",
",",
"contentTypes",
"...",
"string",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
"."... | // ContentTypeHandler wraps and returns a http.Handler, validating the request
// content type is compatible with the contentTypes list. It writes a HTTP 415
// error if that fails.
//
// Only PUT, POST, and PATCH requests are considered. | [
"ContentTypeHandler",
"wraps",
"and",
"returns",
"a",
"http",
".",
"Handler",
"validating",
"the",
"request",
"content",
"type",
"is",
"compatible",
"with",
"the",
"contentTypes",
"list",
".",
"It",
"writes",
"a",
"HTTP",
"415",
"error",
"if",
"that",
"fails",... | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/handlers.go#L125-L140 | train |
gorilla/handlers | recovery.go | RecoveryLogger | func RecoveryLogger(logger RecoveryHandlerLogger) RecoveryOption {
return func(h http.Handler) {
r := h.(*recoveryHandler)
r.logger = logger
}
} | go | func RecoveryLogger(logger RecoveryHandlerLogger) RecoveryOption {
return func(h http.Handler) {
r := h.(*recoveryHandler)
r.logger = logger
}
} | [
"func",
"RecoveryLogger",
"(",
"logger",
"RecoveryHandlerLogger",
")",
"RecoveryOption",
"{",
"return",
"func",
"(",
"h",
"http",
".",
"Handler",
")",
"{",
"r",
":=",
"h",
".",
"(",
"*",
"recoveryHandler",
")",
"\n",
"r",
".",
"logger",
"=",
"logger",
"\... | // RecoveryLogger is a functional option to override
// the default logger | [
"RecoveryLogger",
"is",
"a",
"functional",
"option",
"to",
"override",
"the",
"default",
"logger"
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/recovery.go#L54-L59 | train |
gorilla/handlers | recovery.go | PrintRecoveryStack | func PrintRecoveryStack(print bool) RecoveryOption {
return func(h http.Handler) {
r := h.(*recoveryHandler)
r.printStack = print
}
} | go | func PrintRecoveryStack(print bool) RecoveryOption {
return func(h http.Handler) {
r := h.(*recoveryHandler)
r.printStack = print
}
} | [
"func",
"PrintRecoveryStack",
"(",
"print",
"bool",
")",
"RecoveryOption",
"{",
"return",
"func",
"(",
"h",
"http",
".",
"Handler",
")",
"{",
"r",
":=",
"h",
".",
"(",
"*",
"recoveryHandler",
")",
"\n",
"r",
".",
"printStack",
"=",
"print",
"\n",
"}",
... | // PrintRecoveryStack is a functional option to enable
// or disable printing stack traces on panic. | [
"PrintRecoveryStack",
"is",
"a",
"functional",
"option",
"to",
"enable",
"or",
"disable",
"printing",
"stack",
"traces",
"on",
"panic",
"."
] | ac6d24f88de4584385a0cb3a88f953d08a2f7a05 | https://github.com/gorilla/handlers/blob/ac6d24f88de4584385a0cb3a88f953d08a2f7a05/recovery.go#L63-L68 | train |
colinmarc/hdfs | internal/rpc/block_writer.go | SetDeadline | func (bw *BlockWriter) SetDeadline(t time.Time) error {
bw.deadline = t
if bw.conn != nil {
return bw.conn.SetDeadline(t)
}
// Return the error at connection time.
return nil
} | go | func (bw *BlockWriter) SetDeadline(t time.Time) error {
bw.deadline = t
if bw.conn != nil {
return bw.conn.SetDeadline(t)
}
// Return the error at connection time.
return nil
} | [
"func",
"(",
"bw",
"*",
"BlockWriter",
")",
"SetDeadline",
"(",
"t",
"time",
".",
"Time",
")",
"error",
"{",
"bw",
".",
"deadline",
"=",
"t",
"\n",
"if",
"bw",
".",
"conn",
"!=",
"nil",
"{",
"return",
"bw",
".",
"conn",
".",
"SetDeadline",
"(",
"... | // SetDeadline sets the deadline for future Write, Flush, and Close calls. A
// zero value for t means those calls will not time out. | [
"SetDeadline",
"sets",
"the",
"deadline",
"for",
"future",
"Write",
"Flush",
"and",
"Close",
"calls",
".",
"A",
"zero",
"value",
"for",
"t",
"means",
"those",
"calls",
"will",
"not",
"time",
"out",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/block_writer.go#L49-L57 | train |
colinmarc/hdfs | internal/rpc/block_writer.go | Flush | func (bw *BlockWriter) Flush() error {
if bw.stream != nil {
return bw.stream.flush(true)
}
return nil
} | go | func (bw *BlockWriter) Flush() error {
if bw.stream != nil {
return bw.stream.flush(true)
}
return nil
} | [
"func",
"(",
"bw",
"*",
"BlockWriter",
")",
"Flush",
"(",
")",
"error",
"{",
"if",
"bw",
".",
"stream",
"!=",
"nil",
"{",
"return",
"bw",
".",
"stream",
".",
"flush",
"(",
"true",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Flush flushes any unwritten packets out to the datanode. | [
"Flush",
"flushes",
"any",
"unwritten",
"packets",
"out",
"to",
"the",
"datanode",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/block_writer.go#L94-L100 | train |
colinmarc/hdfs | internal/rpc/block_writer.go | Close | func (bw *BlockWriter) Close() error {
bw.closed = true
if bw.conn != nil {
defer bw.conn.Close()
}
if bw.stream != nil {
// TODO: handle failures, set up recovery pipeline
err := bw.stream.finish()
if err != nil {
return err
}
}
return nil
} | go | func (bw *BlockWriter) Close() error {
bw.closed = true
if bw.conn != nil {
defer bw.conn.Close()
}
if bw.stream != nil {
// TODO: handle failures, set up recovery pipeline
err := bw.stream.finish()
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"bw",
"*",
"BlockWriter",
")",
"Close",
"(",
")",
"error",
"{",
"bw",
".",
"closed",
"=",
"true",
"\n",
"if",
"bw",
".",
"conn",
"!=",
"nil",
"{",
"defer",
"bw",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"bw",
... | // Close implements io.Closer. It flushes any unwritten packets out to the
// datanode, and sends a final packet indicating the end of the block. The
// block must still be finalized with the namenode. | [
"Close",
"implements",
"io",
".",
"Closer",
".",
"It",
"flushes",
"any",
"unwritten",
"packets",
"out",
"to",
"the",
"datanode",
"and",
"sends",
"a",
"final",
"packet",
"indicating",
"the",
"end",
"of",
"the",
"block",
".",
"The",
"block",
"must",
"still",... | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/block_writer.go#L105-L120 | train |
colinmarc/hdfs | internal/rpc/namenode.go | NewNamenodeConnection | func NewNamenodeConnection(options NamenodeConnectionOptions) (*NamenodeConnection, error) {
// Build the list of hosts to be used for failover.
hostList := make([]*namenodeHost, len(options.Addresses))
for i, addr := range options.Addresses {
hostList[i] = &namenodeHost{address: addr}
}
var user, realm string
user = options.User
if user == "" {
if options.KerberosClient != nil {
creds := options.KerberosClient.Credentials
user = creds.Username
realm = creds.Realm
} else {
return nil, errors.New("user not specified")
}
}
// The ClientID is reused here both in the RPC headers (which requires a
// "globally unique" ID) and as the "client name" in various requests.
clientId := newClientID()
c := &NamenodeConnection{
ClientID: clientId,
ClientName: "go-hdfs-" + string(clientId),
User: user,
kerberosClient: options.KerberosClient,
kerberosServicePrincipleName: options.KerberosServicePrincipleName,
kerberosRealm: realm,
dialFunc: options.DialFunc,
hostList: hostList,
}
err := c.resolveConnection()
if err != nil {
return nil, err
}
return c, nil
} | go | func NewNamenodeConnection(options NamenodeConnectionOptions) (*NamenodeConnection, error) {
// Build the list of hosts to be used for failover.
hostList := make([]*namenodeHost, len(options.Addresses))
for i, addr := range options.Addresses {
hostList[i] = &namenodeHost{address: addr}
}
var user, realm string
user = options.User
if user == "" {
if options.KerberosClient != nil {
creds := options.KerberosClient.Credentials
user = creds.Username
realm = creds.Realm
} else {
return nil, errors.New("user not specified")
}
}
// The ClientID is reused here both in the RPC headers (which requires a
// "globally unique" ID) and as the "client name" in various requests.
clientId := newClientID()
c := &NamenodeConnection{
ClientID: clientId,
ClientName: "go-hdfs-" + string(clientId),
User: user,
kerberosClient: options.KerberosClient,
kerberosServicePrincipleName: options.KerberosServicePrincipleName,
kerberosRealm: realm,
dialFunc: options.DialFunc,
hostList: hostList,
}
err := c.resolveConnection()
if err != nil {
return nil, err
}
return c, nil
} | [
"func",
"NewNamenodeConnection",
"(",
"options",
"NamenodeConnectionOptions",
")",
"(",
"*",
"NamenodeConnection",
",",
"error",
")",
"{",
"// Build the list of hosts to be used for failover.",
"hostList",
":=",
"make",
"(",
"[",
"]",
"*",
"namenodeHost",
",",
"len",
... | // NewNamenodeConnectionWithOptions creates a new connection to a namenode with
// the given options and performs an initial handshake. | [
"NewNamenodeConnectionWithOptions",
"creates",
"a",
"new",
"connection",
"to",
"a",
"namenode",
"with",
"the",
"given",
"options",
"and",
"performs",
"an",
"initial",
"handshake",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/namenode.go#L82-L123 | train |
colinmarc/hdfs | internal/rpc/namenode.go | Execute | func (c *NamenodeConnection) Execute(method string, req proto.Message, resp proto.Message) error {
c.reqLock.Lock()
defer c.reqLock.Unlock()
c.currentRequestID++
for {
err := c.resolveConnection()
if err != nil {
return err
}
err = c.writeRequest(method, req)
if err != nil {
c.markFailure(err)
continue
}
err = c.readResponse(method, resp)
if err != nil {
// Only retry on a standby exception.
if nerr, ok := err.(*NamenodeError); ok && nerr.exception == standbyExceptionClass {
c.markFailure(err)
continue
}
return err
}
break
}
return nil
} | go | func (c *NamenodeConnection) Execute(method string, req proto.Message, resp proto.Message) error {
c.reqLock.Lock()
defer c.reqLock.Unlock()
c.currentRequestID++
for {
err := c.resolveConnection()
if err != nil {
return err
}
err = c.writeRequest(method, req)
if err != nil {
c.markFailure(err)
continue
}
err = c.readResponse(method, resp)
if err != nil {
// Only retry on a standby exception.
if nerr, ok := err.(*NamenodeError); ok && nerr.exception == standbyExceptionClass {
c.markFailure(err)
continue
}
return err
}
break
}
return nil
} | [
"func",
"(",
"c",
"*",
"NamenodeConnection",
")",
"Execute",
"(",
"method",
"string",
",",
"req",
"proto",
".",
"Message",
",",
"resp",
"proto",
".",
"Message",
")",
"error",
"{",
"c",
".",
"reqLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
... | // Execute performs an rpc call. It does this by sending req over the wire and
// unmarshaling the result into resp. | [
"Execute",
"performs",
"an",
"rpc",
"call",
".",
"It",
"does",
"this",
"by",
"sending",
"req",
"over",
"the",
"wire",
"and",
"unmarshaling",
"the",
"result",
"into",
"resp",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/namenode.go#L178-L211 | train |
colinmarc/hdfs | internal/rpc/namenode.go | Close | func (c *NamenodeConnection) Close() error {
if c.conn != nil {
return c.conn.Close()
}
return nil
} | go | func (c *NamenodeConnection) Close() error {
if c.conn != nil {
return c.conn.Close()
}
return nil
} | [
"func",
"(",
"c",
"*",
"NamenodeConnection",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"c",
".",
"conn",
"!=",
"nil",
"{",
"return",
"c",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close terminates all underlying socket connections to remote server. | [
"Close",
"terminates",
"all",
"underlying",
"socket",
"connections",
"to",
"remote",
"server",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/namenode.go#L326-L331 | train |
colinmarc/hdfs | file_reader.go | Open | func (c *Client) Open(name string) (*FileReader, error) {
info, err := c.getFileInfo(name)
if err != nil {
return nil, &os.PathError{"open", name, interpretException(err)}
}
return &FileReader{
client: c,
name: name,
info: info,
closed: false,
}, nil
} | go | func (c *Client) Open(name string) (*FileReader, error) {
info, err := c.getFileInfo(name)
if err != nil {
return nil, &os.PathError{"open", name, interpretException(err)}
}
return &FileReader{
client: c,
name: name,
info: info,
closed: false,
}, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Open",
"(",
"name",
"string",
")",
"(",
"*",
"FileReader",
",",
"error",
")",
"{",
"info",
",",
"err",
":=",
"c",
".",
"getFileInfo",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
... | // Open returns an FileReader which can be used for reading. | [
"Open",
"returns",
"an",
"FileReader",
"which",
"can",
"be",
"used",
"for",
"reading",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_reader.go#L35-L47 | train |
colinmarc/hdfs | file_reader.go | SetDeadline | func (f *FileReader) SetDeadline(t time.Time) error {
f.deadline = t
if f.blockReader != nil {
return f.blockReader.SetDeadline(t)
}
// Return the error at connection time.
return nil
} | go | func (f *FileReader) SetDeadline(t time.Time) error {
f.deadline = t
if f.blockReader != nil {
return f.blockReader.SetDeadline(t)
}
// Return the error at connection time.
return nil
} | [
"func",
"(",
"f",
"*",
"FileReader",
")",
"SetDeadline",
"(",
"t",
"time",
".",
"Time",
")",
"error",
"{",
"f",
".",
"deadline",
"=",
"t",
"\n",
"if",
"f",
".",
"blockReader",
"!=",
"nil",
"{",
"return",
"f",
".",
"blockReader",
".",
"SetDeadline",
... | // SetDeadline sets the deadline for future Read, ReadAt, and Checksum calls. A
// zero value for t means those calls will not time out. | [
"SetDeadline",
"sets",
"the",
"deadline",
"for",
"future",
"Read",
"ReadAt",
"and",
"Checksum",
"calls",
".",
"A",
"zero",
"value",
"for",
"t",
"means",
"those",
"calls",
"will",
"not",
"time",
"out",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_reader.go#L61-L69 | train |
colinmarc/hdfs | file_reader.go | Seek | func (f *FileReader) Seek(offset int64, whence int) (int64, error) {
if f.closed {
return 0, io.ErrClosedPipe
}
var off int64
if whence == 0 {
off = offset
} else if whence == 1 {
off = f.offset + offset
} else if whence == 2 {
off = f.info.Size() + offset
} else {
return f.offset, fmt.Errorf("invalid whence: %d", whence)
}
if off < 0 || off > f.info.Size() {
return f.offset, fmt.Errorf("invalid resulting offset: %d", off)
}
if f.offset != off {
f.offset = off
if f.blockReader != nil {
f.blockReader.Close()
f.blockReader = nil
}
}
return f.offset, nil
} | go | func (f *FileReader) Seek(offset int64, whence int) (int64, error) {
if f.closed {
return 0, io.ErrClosedPipe
}
var off int64
if whence == 0 {
off = offset
} else if whence == 1 {
off = f.offset + offset
} else if whence == 2 {
off = f.info.Size() + offset
} else {
return f.offset, fmt.Errorf("invalid whence: %d", whence)
}
if off < 0 || off > f.info.Size() {
return f.offset, fmt.Errorf("invalid resulting offset: %d", off)
}
if f.offset != off {
f.offset = off
if f.blockReader != nil {
f.blockReader.Close()
f.blockReader = nil
}
}
return f.offset, nil
} | [
"func",
"(",
"f",
"*",
"FileReader",
")",
"Seek",
"(",
"offset",
"int64",
",",
"whence",
"int",
")",
"(",
"int64",
",",
"error",
")",
"{",
"if",
"f",
".",
"closed",
"{",
"return",
"0",
",",
"io",
".",
"ErrClosedPipe",
"\n",
"}",
"\n\n",
"var",
"o... | // Seek implements io.Seeker.
//
// The seek is virtual - it starts a new block read at the new position. | [
"Seek",
"implements",
"io",
".",
"Seeker",
".",
"The",
"seek",
"is",
"virtual",
"-",
"it",
"starts",
"a",
"new",
"block",
"read",
"at",
"the",
"new",
"position",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_reader.go#L131-L159 | train |
colinmarc/hdfs | file_writer.go | CreateFile | func (c *Client) CreateFile(name string, replication int, blockSize int64, perm os.FileMode) (*FileWriter, error) {
createReq := &hdfs.CreateRequestProto{
Src: proto.String(name),
Masked: &hdfs.FsPermissionProto{Perm: proto.Uint32(uint32(perm))},
ClientName: proto.String(c.namenode.ClientName),
CreateFlag: proto.Uint32(1),
CreateParent: proto.Bool(false),
Replication: proto.Uint32(uint32(replication)),
BlockSize: proto.Uint64(uint64(blockSize)),
}
createResp := &hdfs.CreateResponseProto{}
err := c.namenode.Execute("create", createReq, createResp)
if err != nil {
return nil, &os.PathError{"create", name, interpretException(err)}
}
return &FileWriter{
client: c,
name: name,
replication: replication,
blockSize: blockSize,
}, nil
} | go | func (c *Client) CreateFile(name string, replication int, blockSize int64, perm os.FileMode) (*FileWriter, error) {
createReq := &hdfs.CreateRequestProto{
Src: proto.String(name),
Masked: &hdfs.FsPermissionProto{Perm: proto.Uint32(uint32(perm))},
ClientName: proto.String(c.namenode.ClientName),
CreateFlag: proto.Uint32(1),
CreateParent: proto.Bool(false),
Replication: proto.Uint32(uint32(replication)),
BlockSize: proto.Uint64(uint64(blockSize)),
}
createResp := &hdfs.CreateResponseProto{}
err := c.namenode.Execute("create", createReq, createResp)
if err != nil {
return nil, &os.PathError{"create", name, interpretException(err)}
}
return &FileWriter{
client: c,
name: name,
replication: replication,
blockSize: blockSize,
}, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"CreateFile",
"(",
"name",
"string",
",",
"replication",
"int",
",",
"blockSize",
"int64",
",",
"perm",
"os",
".",
"FileMode",
")",
"(",
"*",
"FileWriter",
",",
"error",
")",
"{",
"createReq",
":=",
"&",
"hdfs",
... | // CreateFile opens a new file in HDFS with the given replication, block size,
// and permissions, and returns an io.WriteCloser for writing to it. Because of
// the way that HDFS writes are buffered and acknowledged asynchronously, it is
// very important that Close is called after all data has been written. | [
"CreateFile",
"opens",
"a",
"new",
"file",
"in",
"HDFS",
"with",
"the",
"given",
"replication",
"block",
"size",
"and",
"permissions",
"and",
"returns",
"an",
"io",
".",
"WriteCloser",
"for",
"writing",
"to",
"it",
".",
"Because",
"of",
"the",
"way",
"that... | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_writer.go#L55-L78 | train |
colinmarc/hdfs | file_writer.go | Append | func (c *Client) Append(name string) (*FileWriter, error) {
_, err := c.getFileInfo(name)
if err != nil {
return nil, &os.PathError{"append", name, interpretException(err)}
}
appendReq := &hdfs.AppendRequestProto{
Src: proto.String(name),
ClientName: proto.String(c.namenode.ClientName),
}
appendResp := &hdfs.AppendResponseProto{}
err = c.namenode.Execute("append", appendReq, appendResp)
if err != nil {
return nil, &os.PathError{"append", name, interpretException(err)}
}
f := &FileWriter{
client: c,
name: name,
replication: int(appendResp.Stat.GetBlockReplication()),
blockSize: int64(appendResp.Stat.GetBlocksize()),
}
// This returns nil if there are no blocks (it's an empty file) or if the
// last block is full (so we have to start a fresh block).
block := appendResp.GetBlock()
if block == nil {
return f, nil
}
f.blockWriter = &rpc.BlockWriter{
ClientName: f.client.namenode.ClientName,
Block: block,
BlockSize: f.blockSize,
Offset: int64(block.B.GetNumBytes()),
Append: true,
UseDatanodeHostname: f.client.options.UseDatanodeHostname,
DialFunc: f.client.options.DatanodeDialFunc,
}
err = f.blockWriter.SetDeadline(f.deadline)
if err != nil {
return nil, err
}
return f, nil
} | go | func (c *Client) Append(name string) (*FileWriter, error) {
_, err := c.getFileInfo(name)
if err != nil {
return nil, &os.PathError{"append", name, interpretException(err)}
}
appendReq := &hdfs.AppendRequestProto{
Src: proto.String(name),
ClientName: proto.String(c.namenode.ClientName),
}
appendResp := &hdfs.AppendResponseProto{}
err = c.namenode.Execute("append", appendReq, appendResp)
if err != nil {
return nil, &os.PathError{"append", name, interpretException(err)}
}
f := &FileWriter{
client: c,
name: name,
replication: int(appendResp.Stat.GetBlockReplication()),
blockSize: int64(appendResp.Stat.GetBlocksize()),
}
// This returns nil if there are no blocks (it's an empty file) or if the
// last block is full (so we have to start a fresh block).
block := appendResp.GetBlock()
if block == nil {
return f, nil
}
f.blockWriter = &rpc.BlockWriter{
ClientName: f.client.namenode.ClientName,
Block: block,
BlockSize: f.blockSize,
Offset: int64(block.B.GetNumBytes()),
Append: true,
UseDatanodeHostname: f.client.options.UseDatanodeHostname,
DialFunc: f.client.options.DatanodeDialFunc,
}
err = f.blockWriter.SetDeadline(f.deadline)
if err != nil {
return nil, err
}
return f, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Append",
"(",
"name",
"string",
")",
"(",
"*",
"FileWriter",
",",
"error",
")",
"{",
"_",
",",
"err",
":=",
"c",
".",
"getFileInfo",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
... | // Append opens an existing file in HDFS and returns an io.WriteCloser for
// writing to it. Because of the way that HDFS writes are buffered and
// acknowledged asynchronously, it is very important that Close is called after
// all data has been written. | [
"Append",
"opens",
"an",
"existing",
"file",
"in",
"HDFS",
"and",
"returns",
"an",
"io",
".",
"WriteCloser",
"for",
"writing",
"to",
"it",
".",
"Because",
"of",
"the",
"way",
"that",
"HDFS",
"writes",
"are",
"buffered",
"and",
"acknowledged",
"asynchronously... | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_writer.go#L84-L131 | train |
colinmarc/hdfs | file_writer.go | CreateEmptyFile | func (c *Client) CreateEmptyFile(name string) error {
f, err := c.Create(name)
if err != nil {
return err
}
return f.Close()
} | go | func (c *Client) CreateEmptyFile(name string) error {
f, err := c.Create(name)
if err != nil {
return err
}
return f.Close()
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"CreateEmptyFile",
"(",
"name",
"string",
")",
"error",
"{",
"f",
",",
"err",
":=",
"c",
".",
"Create",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"f"... | // CreateEmptyFile creates a empty file at the given name, with the
// permissions 0644. | [
"CreateEmptyFile",
"creates",
"a",
"empty",
"file",
"at",
"the",
"given",
"name",
"with",
"the",
"permissions",
"0644",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_writer.go#L135-L142 | train |
colinmarc/hdfs | file_writer.go | SetDeadline | func (f *FileWriter) SetDeadline(t time.Time) error {
f.deadline = t
if f.blockWriter != nil {
return f.blockWriter.SetDeadline(t)
}
// Return the error at connection time.
return nil
} | go | func (f *FileWriter) SetDeadline(t time.Time) error {
f.deadline = t
if f.blockWriter != nil {
return f.blockWriter.SetDeadline(t)
}
// Return the error at connection time.
return nil
} | [
"func",
"(",
"f",
"*",
"FileWriter",
")",
"SetDeadline",
"(",
"t",
"time",
".",
"Time",
")",
"error",
"{",
"f",
".",
"deadline",
"=",
"t",
"\n",
"if",
"f",
".",
"blockWriter",
"!=",
"nil",
"{",
"return",
"f",
".",
"blockWriter",
".",
"SetDeadline",
... | // SetDeadline sets the deadline for future Write, Flush, and Close calls. A
// zero value for t means those calls will not time out.
//
// Note that because of buffering, Write calls that do not result in a blocking
// network call may still succeed after the deadline. | [
"SetDeadline",
"sets",
"the",
"deadline",
"for",
"future",
"Write",
"Flush",
"and",
"Close",
"calls",
".",
"A",
"zero",
"value",
"for",
"t",
"means",
"those",
"calls",
"will",
"not",
"time",
"out",
".",
"Note",
"that",
"because",
"of",
"buffering",
"Write"... | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_writer.go#L149-L157 | train |
colinmarc/hdfs | file_writer.go | Write | func (f *FileWriter) Write(b []byte) (int, error) {
if f.closed {
return 0, io.ErrClosedPipe
}
if f.blockWriter == nil {
err := f.startNewBlock()
if err != nil {
return 0, err
}
}
off := 0
for off < len(b) {
n, err := f.blockWriter.Write(b[off:])
off += n
if err == rpc.ErrEndOfBlock {
err = f.startNewBlock()
}
if err != nil {
return off, err
}
}
return off, nil
} | go | func (f *FileWriter) Write(b []byte) (int, error) {
if f.closed {
return 0, io.ErrClosedPipe
}
if f.blockWriter == nil {
err := f.startNewBlock()
if err != nil {
return 0, err
}
}
off := 0
for off < len(b) {
n, err := f.blockWriter.Write(b[off:])
off += n
if err == rpc.ErrEndOfBlock {
err = f.startNewBlock()
}
if err != nil {
return off, err
}
}
return off, nil
} | [
"func",
"(",
"f",
"*",
"FileWriter",
")",
"Write",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"f",
".",
"closed",
"{",
"return",
"0",
",",
"io",
".",
"ErrClosedPipe",
"\n",
"}",
"\n\n",
"if",
"f",
".",
"blockWrit... | // Write implements io.Writer for writing to a file in HDFS. Internally, it
// writes data to an internal buffer first, and then later out to HDFS. Because
// of this, it is important that Close is called after all data has been
// written. | [
"Write",
"implements",
"io",
".",
"Writer",
"for",
"writing",
"to",
"a",
"file",
"in",
"HDFS",
".",
"Internally",
"it",
"writes",
"data",
"to",
"an",
"internal",
"buffer",
"first",
"and",
"then",
"later",
"out",
"to",
"HDFS",
".",
"Because",
"of",
"this"... | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_writer.go#L163-L189 | train |
colinmarc/hdfs | file_writer.go | Flush | func (f *FileWriter) Flush() error {
if f.closed {
return io.ErrClosedPipe
}
if f.blockWriter != nil {
return f.blockWriter.Flush()
}
return nil
} | go | func (f *FileWriter) Flush() error {
if f.closed {
return io.ErrClosedPipe
}
if f.blockWriter != nil {
return f.blockWriter.Flush()
}
return nil
} | [
"func",
"(",
"f",
"*",
"FileWriter",
")",
"Flush",
"(",
")",
"error",
"{",
"if",
"f",
".",
"closed",
"{",
"return",
"io",
".",
"ErrClosedPipe",
"\n",
"}",
"\n\n",
"if",
"f",
".",
"blockWriter",
"!=",
"nil",
"{",
"return",
"f",
".",
"blockWriter",
"... | // Flush flushes any buffered data out to the datanodes. Even immediately after
// a call to Flush, it is still necessary to call Close once all data has been
// written. | [
"Flush",
"flushes",
"any",
"buffered",
"data",
"out",
"to",
"the",
"datanodes",
".",
"Even",
"immediately",
"after",
"a",
"call",
"to",
"Flush",
"it",
"is",
"still",
"necessary",
"to",
"call",
"Close",
"once",
"all",
"data",
"has",
"been",
"written",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_writer.go#L194-L204 | train |
colinmarc/hdfs | file_writer.go | Close | func (f *FileWriter) Close() error {
if f.closed {
return io.ErrClosedPipe
}
var lastBlock *hdfs.ExtendedBlockProto
if f.blockWriter != nil {
lastBlock = f.blockWriter.Block.GetB()
// Close the blockWriter, flushing any buffered packets.
err := f.finalizeBlock()
if err != nil {
return err
}
}
completeReq := &hdfs.CompleteRequestProto{
Src: proto.String(f.name),
ClientName: proto.String(f.client.namenode.ClientName),
Last: lastBlock,
}
completeResp := &hdfs.CompleteResponseProto{}
err := f.client.namenode.Execute("complete", completeReq, completeResp)
if err != nil {
return &os.PathError{"create", f.name, err}
}
return nil
} | go | func (f *FileWriter) Close() error {
if f.closed {
return io.ErrClosedPipe
}
var lastBlock *hdfs.ExtendedBlockProto
if f.blockWriter != nil {
lastBlock = f.blockWriter.Block.GetB()
// Close the blockWriter, flushing any buffered packets.
err := f.finalizeBlock()
if err != nil {
return err
}
}
completeReq := &hdfs.CompleteRequestProto{
Src: proto.String(f.name),
ClientName: proto.String(f.client.namenode.ClientName),
Last: lastBlock,
}
completeResp := &hdfs.CompleteResponseProto{}
err := f.client.namenode.Execute("complete", completeReq, completeResp)
if err != nil {
return &os.PathError{"create", f.name, err}
}
return nil
} | [
"func",
"(",
"f",
"*",
"FileWriter",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"f",
".",
"closed",
"{",
"return",
"io",
".",
"ErrClosedPipe",
"\n",
"}",
"\n\n",
"var",
"lastBlock",
"*",
"hdfs",
".",
"ExtendedBlockProto",
"\n",
"if",
"f",
".",
"bloc... | // Close closes the file, writing any remaining data out to disk and waiting
// for acknowledgements from the datanodes. It is important that Close is called
// after all data has been written. | [
"Close",
"closes",
"the",
"file",
"writing",
"any",
"remaining",
"data",
"out",
"to",
"disk",
"and",
"waiting",
"for",
"acknowledgements",
"from",
"the",
"datanodes",
".",
"It",
"is",
"important",
"that",
"Close",
"is",
"called",
"after",
"all",
"data",
"has... | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/file_writer.go#L209-L238 | train |
colinmarc/hdfs | content_summary.go | GetContentSummary | func (c *Client) GetContentSummary(name string) (*ContentSummary, error) {
cs, err := c.getContentSummary(name)
if err != nil {
err = &os.PathError{"content summary", name, interpretException(err)}
}
return cs, err
} | go | func (c *Client) GetContentSummary(name string) (*ContentSummary, error) {
cs, err := c.getContentSummary(name)
if err != nil {
err = &os.PathError{"content summary", name, interpretException(err)}
}
return cs, err
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetContentSummary",
"(",
"name",
"string",
")",
"(",
"*",
"ContentSummary",
",",
"error",
")",
"{",
"cs",
",",
"err",
":=",
"c",
".",
"getContentSummary",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
... | // GetContentSummary returns a ContentSummary representing the named file or
// directory. The summary contains information about the entire tree rooted
// in the named file; for instance, it can return the total size of all | [
"GetContentSummary",
"returns",
"a",
"ContentSummary",
"representing",
"the",
"named",
"file",
"or",
"directory",
".",
"The",
"summary",
"contains",
"information",
"about",
"the",
"entire",
"tree",
"rooted",
"in",
"the",
"named",
"file",
";",
"for",
"instance",
... | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/content_summary.go#L21-L28 | train |
colinmarc/hdfs | mkdir.go | Mkdir | func (c *Client) Mkdir(dirname string, perm os.FileMode) error {
return c.mkdir(dirname, perm, false)
} | go | func (c *Client) Mkdir(dirname string, perm os.FileMode) error {
return c.mkdir(dirname, perm, false)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Mkdir",
"(",
"dirname",
"string",
",",
"perm",
"os",
".",
"FileMode",
")",
"error",
"{",
"return",
"c",
".",
"mkdir",
"(",
"dirname",
",",
"perm",
",",
"false",
")",
"\n",
"}"
] | // Mkdir creates a new directory with the specified name and permission bits. | [
"Mkdir",
"creates",
"a",
"new",
"directory",
"with",
"the",
"specified",
"name",
"and",
"permission",
"bits",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/mkdir.go#L12-L14 | train |
colinmarc/hdfs | mkdir.go | MkdirAll | func (c *Client) MkdirAll(dirname string, perm os.FileMode) error {
return c.mkdir(dirname, perm, true)
} | go | func (c *Client) MkdirAll(dirname string, perm os.FileMode) error {
return c.mkdir(dirname, perm, true)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"MkdirAll",
"(",
"dirname",
"string",
",",
"perm",
"os",
".",
"FileMode",
")",
"error",
"{",
"return",
"c",
".",
"mkdir",
"(",
"dirname",
",",
"perm",
",",
"true",
")",
"\n",
"}"
] | // MkdirAll creates a directory for dirname, along with any necessary parents,
// and returns nil, or else returns an error. The permission bits perm are used
// for all directories that MkdirAll creates. If dirname is already a directory,
// MkdirAll does nothing and returns nil. | [
"MkdirAll",
"creates",
"a",
"directory",
"for",
"dirname",
"along",
"with",
"any",
"necessary",
"parents",
"and",
"returns",
"nil",
"or",
"else",
"returns",
"an",
"error",
".",
"The",
"permission",
"bits",
"perm",
"are",
"used",
"for",
"all",
"directories",
... | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/mkdir.go#L20-L22 | train |
colinmarc/hdfs | hadoopconf/hadoopconf.go | Load | func Load(path string) (HadoopConf, error) {
var conf HadoopConf
for _, file := range confFiles {
pList := propertyList{}
f, err := ioutil.ReadFile(filepath.Join(path, file))
if os.IsNotExist(err) {
continue
} else if err != nil {
return conf, err
}
err = xml.Unmarshal(f, &pList)
if err != nil {
return conf, fmt.Errorf("%s: %s", path, err)
}
if conf == nil {
conf = make(HadoopConf)
}
for _, prop := range pList.Property {
conf[prop.Name] = prop.Value
}
}
return conf, nil
} | go | func Load(path string) (HadoopConf, error) {
var conf HadoopConf
for _, file := range confFiles {
pList := propertyList{}
f, err := ioutil.ReadFile(filepath.Join(path, file))
if os.IsNotExist(err) {
continue
} else if err != nil {
return conf, err
}
err = xml.Unmarshal(f, &pList)
if err != nil {
return conf, fmt.Errorf("%s: %s", path, err)
}
if conf == nil {
conf = make(HadoopConf)
}
for _, prop := range pList.Property {
conf[prop.Name] = prop.Value
}
}
return conf, nil
} | [
"func",
"Load",
"(",
"path",
"string",
")",
"(",
"HadoopConf",
",",
"error",
")",
"{",
"var",
"conf",
"HadoopConf",
"\n\n",
"for",
"_",
",",
"file",
":=",
"range",
"confFiles",
"{",
"pList",
":=",
"propertyList",
"{",
"}",
"\n",
"f",
",",
"err",
":="... | // Load returns a HadoopConf object representing configuration from the
// specified path. It will parse core-site.xml, hdfs-site.xml, and
// mapred-site.xml.
//
// If no configuration files could be found, Load returns a nil map. If the
// configuration files exist but there was an error opening or parsing them,
// that is returned as well. | [
"Load",
"returns",
"a",
"HadoopConf",
"object",
"representing",
"configuration",
"from",
"the",
"specified",
"path",
".",
"It",
"will",
"parse",
"core",
"-",
"site",
".",
"xml",
"hdfs",
"-",
"site",
".",
"xml",
"and",
"mapred",
"-",
"site",
".",
"xml",
"... | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/hadoopconf/hadoopconf.go#L64-L91 | train |
colinmarc/hdfs | perms.go | Chmod | func (c *Client) Chmod(name string, perm os.FileMode) error {
req := &hdfs.SetPermissionRequestProto{
Src: proto.String(name),
Permission: &hdfs.FsPermissionProto{Perm: proto.Uint32(uint32(perm))},
}
resp := &hdfs.SetPermissionResponseProto{}
err := c.namenode.Execute("setPermission", req, resp)
if err != nil {
return &os.PathError{"chmod", name, interpretException(err)}
}
return nil
} | go | func (c *Client) Chmod(name string, perm os.FileMode) error {
req := &hdfs.SetPermissionRequestProto{
Src: proto.String(name),
Permission: &hdfs.FsPermissionProto{Perm: proto.Uint32(uint32(perm))},
}
resp := &hdfs.SetPermissionResponseProto{}
err := c.namenode.Execute("setPermission", req, resp)
if err != nil {
return &os.PathError{"chmod", name, interpretException(err)}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Chmod",
"(",
"name",
"string",
",",
"perm",
"os",
".",
"FileMode",
")",
"error",
"{",
"req",
":=",
"&",
"hdfs",
".",
"SetPermissionRequestProto",
"{",
"Src",
":",
"proto",
".",
"String",
"(",
"name",
")",
",",
... | // Chmod changes the mode of the named file to mode. | [
"Chmod",
"changes",
"the",
"mode",
"of",
"the",
"named",
"file",
"to",
"mode",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/perms.go#L12-L25 | train |
colinmarc/hdfs | internal/rpc/block_reader.go | SetDeadline | func (br *BlockReader) SetDeadline(t time.Time) error {
br.deadline = t
if br.conn != nil {
return br.conn.SetDeadline(t)
}
// Return the error at connection time.
return nil
} | go | func (br *BlockReader) SetDeadline(t time.Time) error {
br.deadline = t
if br.conn != nil {
return br.conn.SetDeadline(t)
}
// Return the error at connection time.
return nil
} | [
"func",
"(",
"br",
"*",
"BlockReader",
")",
"SetDeadline",
"(",
"t",
"time",
".",
"Time",
")",
"error",
"{",
"br",
".",
"deadline",
"=",
"t",
"\n",
"if",
"br",
".",
"conn",
"!=",
"nil",
"{",
"return",
"br",
".",
"conn",
".",
"SetDeadline",
"(",
"... | // SetDeadline sets the deadline for future Read calls. A zero value for t
// means Read will not time out. | [
"SetDeadline",
"sets",
"the",
"deadline",
"for",
"future",
"Read",
"calls",
".",
"A",
"zero",
"value",
"for",
"t",
"means",
"Read",
"will",
"not",
"time",
"out",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/block_reader.go#L44-L52 | train |
colinmarc/hdfs | internal/rpc/block_reader.go | connectNext | func (br *BlockReader) connectNext() error {
address := br.datanodes.next()
if br.DialFunc == nil {
br.DialFunc = (&net.Dialer{}).DialContext
}
conn, err := br.DialFunc(context.Background(), "tcp", address)
if err != nil {
return err
}
err = br.writeBlockReadRequest(conn)
if err != nil {
return err
}
resp, err := readBlockOpResponse(conn)
if err != nil {
return err
} else if resp.GetStatus() != hdfs.Status_SUCCESS {
return fmt.Errorf("read failed: %s (%s)", resp.GetStatus().String(), resp.GetMessage())
}
readInfo := resp.GetReadOpChecksumInfo()
checksumInfo := readInfo.GetChecksum()
var checksumTab *crc32.Table
checksumType := checksumInfo.GetType()
switch checksumType {
case hdfs.ChecksumTypeProto_CHECKSUM_CRC32:
checksumTab = crc32.IEEETable
case hdfs.ChecksumTypeProto_CHECKSUM_CRC32C:
checksumTab = crc32.MakeTable(crc32.Castagnoli)
default:
return fmt.Errorf("unsupported checksum type: %d", checksumType)
}
chunkSize := int(checksumInfo.GetBytesPerChecksum())
stream := newBlockReadStream(conn, chunkSize, checksumTab)
// The read will start aligned to a chunk boundary, so we need to seek forward
// to the requested offset.
amountToDiscard := br.Offset - int64(readInfo.GetChunkOffset())
if amountToDiscard > 0 {
_, err := io.CopyN(ioutil.Discard, stream, amountToDiscard)
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
conn.Close()
return err
}
}
br.stream = stream
br.conn = conn
err = br.conn.SetDeadline(br.deadline)
if err != nil {
return err
}
return nil
} | go | func (br *BlockReader) connectNext() error {
address := br.datanodes.next()
if br.DialFunc == nil {
br.DialFunc = (&net.Dialer{}).DialContext
}
conn, err := br.DialFunc(context.Background(), "tcp", address)
if err != nil {
return err
}
err = br.writeBlockReadRequest(conn)
if err != nil {
return err
}
resp, err := readBlockOpResponse(conn)
if err != nil {
return err
} else if resp.GetStatus() != hdfs.Status_SUCCESS {
return fmt.Errorf("read failed: %s (%s)", resp.GetStatus().String(), resp.GetMessage())
}
readInfo := resp.GetReadOpChecksumInfo()
checksumInfo := readInfo.GetChecksum()
var checksumTab *crc32.Table
checksumType := checksumInfo.GetType()
switch checksumType {
case hdfs.ChecksumTypeProto_CHECKSUM_CRC32:
checksumTab = crc32.IEEETable
case hdfs.ChecksumTypeProto_CHECKSUM_CRC32C:
checksumTab = crc32.MakeTable(crc32.Castagnoli)
default:
return fmt.Errorf("unsupported checksum type: %d", checksumType)
}
chunkSize := int(checksumInfo.GetBytesPerChecksum())
stream := newBlockReadStream(conn, chunkSize, checksumTab)
// The read will start aligned to a chunk boundary, so we need to seek forward
// to the requested offset.
amountToDiscard := br.Offset - int64(readInfo.GetChunkOffset())
if amountToDiscard > 0 {
_, err := io.CopyN(ioutil.Discard, stream, amountToDiscard)
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
conn.Close()
return err
}
}
br.stream = stream
br.conn = conn
err = br.conn.SetDeadline(br.deadline)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"br",
"*",
"BlockReader",
")",
"connectNext",
"(",
")",
"error",
"{",
"address",
":=",
"br",
".",
"datanodes",
".",
"next",
"(",
")",
"\n\n",
"if",
"br",
".",
"DialFunc",
"==",
"nil",
"{",
"br",
".",
"DialFunc",
"=",
"(",
"&",
"net",
... | // connectNext pops a datanode from the list based on previous failures, and
// connects to it. | [
"connectNext",
"pops",
"a",
"datanode",
"from",
"the",
"list",
"based",
"on",
"previous",
"failures",
"and",
"connects",
"to",
"it",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/block_reader.go#L130-L194 | train |
colinmarc/hdfs | internal/rpc/kerberos.go | getKerberosTicket | func (c *NamenodeConnection) getKerberosTicket() (gssapi.NegTokenInit, krbtypes.EncryptionKey, error) {
host, _, _ := net.SplitHostPort(c.host.address)
spn := replaceSPNHostWildcard(c.kerberosServicePrincipleName, host)
ticket, key, err := c.kerberosClient.GetServiceTicket(spn)
if err != nil {
return gssapi.NegTokenInit{}, key, err
}
token, err := gssapi.NewNegTokenInitKrb5(*c.kerberosClient.Credentials, ticket, key)
return token, key, err
} | go | func (c *NamenodeConnection) getKerberosTicket() (gssapi.NegTokenInit, krbtypes.EncryptionKey, error) {
host, _, _ := net.SplitHostPort(c.host.address)
spn := replaceSPNHostWildcard(c.kerberosServicePrincipleName, host)
ticket, key, err := c.kerberosClient.GetServiceTicket(spn)
if err != nil {
return gssapi.NegTokenInit{}, key, err
}
token, err := gssapi.NewNegTokenInitKrb5(*c.kerberosClient.Credentials, ticket, key)
return token, key, err
} | [
"func",
"(",
"c",
"*",
"NamenodeConnection",
")",
"getKerberosTicket",
"(",
")",
"(",
"gssapi",
".",
"NegTokenInit",
",",
"krbtypes",
".",
"EncryptionKey",
",",
"error",
")",
"{",
"host",
",",
"_",
",",
"_",
":=",
"net",
".",
"SplitHostPort",
"(",
"c",
... | // getKerberosTicket returns an initial kerberos negotiation token and the
// paired session key, along with an error if any occured. | [
"getKerberosTicket",
"returns",
"an",
"initial",
"kerberos",
"negotiation",
"token",
"and",
"the",
"paired",
"session",
"key",
"along",
"with",
"an",
"error",
"if",
"any",
"occured",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/kerberos.go#L128-L139 | train |
colinmarc/hdfs | internal/rpc/block_write_stream.go | finish | func (s *blockWriteStream) finish() error {
if s.closed {
return nil
}
s.closed = true
if err := s.getAckError(); err != nil {
return err
}
err := s.flush(true)
if err != nil {
return err
}
// The last packet has no data; it's just a marker that the block is finished.
lastPacket := outboundPacket{
seqno: s.seqno,
offset: s.offset,
last: true,
checksums: []byte{},
data: []byte{},
}
s.packets <- lastPacket
err = s.writePacket(lastPacket)
if err != nil {
return err
}
close(s.packets)
// Wait for the ack loop to finish.
<-s.acksDone
// Check one more time for any ack errors.
if err := s.getAckError(); err != nil {
return err
}
return nil
} | go | func (s *blockWriteStream) finish() error {
if s.closed {
return nil
}
s.closed = true
if err := s.getAckError(); err != nil {
return err
}
err := s.flush(true)
if err != nil {
return err
}
// The last packet has no data; it's just a marker that the block is finished.
lastPacket := outboundPacket{
seqno: s.seqno,
offset: s.offset,
last: true,
checksums: []byte{},
data: []byte{},
}
s.packets <- lastPacket
err = s.writePacket(lastPacket)
if err != nil {
return err
}
close(s.packets)
// Wait for the ack loop to finish.
<-s.acksDone
// Check one more time for any ack errors.
if err := s.getAckError(); err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"blockWriteStream",
")",
"finish",
"(",
")",
"error",
"{",
"if",
"s",
".",
"closed",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"s",
".",
"closed",
"=",
"true",
"\n\n",
"if",
"err",
":=",
"s",
".",
"getAckError",
"(",
")",
";",... | // finish flushes the rest of the buffered bytes, and then sends a final empty
// packet signifying the end of the block. | [
"finish",
"flushes",
"the",
"rest",
"of",
"the",
"buffered",
"bytes",
"and",
"then",
"sends",
"a",
"final",
"empty",
"packet",
"signifying",
"the",
"end",
"of",
"the",
"block",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/block_write_stream.go#L108-L147 | train |
colinmarc/hdfs | internal/rpc/block_write_stream.go | flush | func (s *blockWriteStream) flush(force bool) error {
if err := s.getAckError(); err != nil {
return err
}
for s.buf.Len() > 0 && (force || s.buf.Len() >= outboundPacketSize) {
packet := s.makePacket()
s.packets <- packet
s.offset += int64(len(packet.data))
s.seqno++
err := s.writePacket(packet)
if err != nil {
return err
}
}
return nil
} | go | func (s *blockWriteStream) flush(force bool) error {
if err := s.getAckError(); err != nil {
return err
}
for s.buf.Len() > 0 && (force || s.buf.Len() >= outboundPacketSize) {
packet := s.makePacket()
s.packets <- packet
s.offset += int64(len(packet.data))
s.seqno++
err := s.writePacket(packet)
if err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"s",
"*",
"blockWriteStream",
")",
"flush",
"(",
"force",
"bool",
")",
"error",
"{",
"if",
"err",
":=",
"s",
".",
"getAckError",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"s",
".",
"buf",
".",... | // flush parcels out the buffered bytes into packets, which it then flushes to
// the datanode. We keep around a reference to the packet, in case the ack
// fails, and we need to send it again later. | [
"flush",
"parcels",
"out",
"the",
"buffered",
"bytes",
"into",
"packets",
"which",
"it",
"then",
"flushes",
"to",
"the",
"datanode",
".",
"We",
"keep",
"around",
"a",
"reference",
"to",
"the",
"packet",
"in",
"case",
"the",
"ack",
"fails",
"and",
"we",
"... | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/block_write_stream.go#L152-L170 | train |
colinmarc/hdfs | internal/rpc/block_write_stream.go | ackPackets | func (s *blockWriteStream) ackPackets() {
reader := bufio.NewReader(s.conn)
for {
p, ok := <-s.packets
if !ok {
// All packets all acked.
return
}
// If we fail to read the ack at all, that counts as a failure from the
// first datanode (the one we're connected to).
ack := &hdfs.PipelineAckProto{}
err := readPrefixedMessage(reader, ack)
if err != nil {
s.ackError = err
break
}
seqno := int(ack.GetSeqno())
for i, status := range ack.GetReply() {
if status != hdfs.Status_SUCCESS {
s.ackError = ackError{status: status, seqno: seqno, pipelineIndex: i}
break
}
}
if seqno != p.seqno {
s.ackError = ErrInvalidSeqno
break
}
}
// Once we've seen an error, just keep reading packets off the channel (but
// not off the socket) until the writing thread figures it out. If we don't,
// the upstream thread could deadlock waiting for the channel to have space.
for _ = range s.packets {
}
} | go | func (s *blockWriteStream) ackPackets() {
reader := bufio.NewReader(s.conn)
for {
p, ok := <-s.packets
if !ok {
// All packets all acked.
return
}
// If we fail to read the ack at all, that counts as a failure from the
// first datanode (the one we're connected to).
ack := &hdfs.PipelineAckProto{}
err := readPrefixedMessage(reader, ack)
if err != nil {
s.ackError = err
break
}
seqno := int(ack.GetSeqno())
for i, status := range ack.GetReply() {
if status != hdfs.Status_SUCCESS {
s.ackError = ackError{status: status, seqno: seqno, pipelineIndex: i}
break
}
}
if seqno != p.seqno {
s.ackError = ErrInvalidSeqno
break
}
}
// Once we've seen an error, just keep reading packets off the channel (but
// not off the socket) until the writing thread figures it out. If we don't,
// the upstream thread could deadlock waiting for the channel to have space.
for _ = range s.packets {
}
} | [
"func",
"(",
"s",
"*",
"blockWriteStream",
")",
"ackPackets",
"(",
")",
"{",
"reader",
":=",
"bufio",
".",
"NewReader",
"(",
"s",
".",
"conn",
")",
"\n\n",
"for",
"{",
"p",
",",
"ok",
":=",
"<-",
"s",
".",
"packets",
"\n",
"if",
"!",
"ok",
"{",
... | // ackPackets is meant to run in the background, reading acks and setting
// ackError if one fails. | [
"ackPackets",
"is",
"meant",
"to",
"run",
"in",
"the",
"background",
"reading",
"acks",
"and",
"setting",
"ackError",
"if",
"one",
"fails",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/block_write_stream.go#L217-L255 | train |
colinmarc/hdfs | stat.go | Stat | func (c *Client) Stat(name string) (os.FileInfo, error) {
fi, err := c.getFileInfo(name)
if err != nil {
err = &os.PathError{"stat", name, interpretException(err)}
}
return fi, err
} | go | func (c *Client) Stat(name string) (os.FileInfo, error) {
fi, err := c.getFileInfo(name)
if err != nil {
err = &os.PathError{"stat", name, interpretException(err)}
}
return fi, err
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Stat",
"(",
"name",
"string",
")",
"(",
"os",
".",
"FileInfo",
",",
"error",
")",
"{",
"fi",
",",
"err",
":=",
"c",
".",
"getFileInfo",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
... | // Stat returns an os.FileInfo describing the named file or directory. | [
"Stat",
"returns",
"an",
"os",
".",
"FileInfo",
"describing",
"the",
"named",
"file",
"or",
"directory",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/stat.go#L20-L27 | train |
colinmarc/hdfs | stat.go | AccessTime | func (fi *FileInfo) AccessTime() time.Time {
return time.Unix(int64(fi.status.GetAccessTime())/1000, 0)
} | go | func (fi *FileInfo) AccessTime() time.Time {
return time.Unix(int64(fi.status.GetAccessTime())/1000, 0)
} | [
"func",
"(",
"fi",
"*",
"FileInfo",
")",
"AccessTime",
"(",
")",
"time",
".",
"Time",
"{",
"return",
"time",
".",
"Unix",
"(",
"int64",
"(",
"fi",
".",
"status",
".",
"GetAccessTime",
"(",
")",
")",
"/",
"1000",
",",
"0",
")",
"\n",
"}"
] | // AccessTime returns the last time the file was accessed. It's not part of the
// os.FileInfo interface. | [
"AccessTime",
"returns",
"the",
"last",
"time",
"the",
"file",
"was",
"accessed",
".",
"It",
"s",
"not",
"part",
"of",
"the",
"os",
".",
"FileInfo",
"interface",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/stat.go#L104-L106 | train |
colinmarc/hdfs | client.go | NewClient | func NewClient(options ClientOptions) (*Client, error) {
var err error
if options.KerberosClient != nil && options.KerberosClient.Credentials == nil {
return nil, errors.New("kerberos enabled, but kerberos client is missing credentials")
}
if options.KerberosClient != nil && options.KerberosServicePrincipleName == "" {
return nil, errors.New("kerberos enabled, but kerberos namenode SPN is not provided")
}
namenode, err := rpc.NewNamenodeConnection(
rpc.NamenodeConnectionOptions{
Addresses: options.Addresses,
User: options.User,
DialFunc: options.NamenodeDialFunc,
KerberosClient: options.KerberosClient,
KerberosServicePrincipleName: options.KerberosServicePrincipleName,
},
)
if err != nil {
return nil, err
}
return &Client{namenode: namenode, options: options}, nil
} | go | func NewClient(options ClientOptions) (*Client, error) {
var err error
if options.KerberosClient != nil && options.KerberosClient.Credentials == nil {
return nil, errors.New("kerberos enabled, but kerberos client is missing credentials")
}
if options.KerberosClient != nil && options.KerberosServicePrincipleName == "" {
return nil, errors.New("kerberos enabled, but kerberos namenode SPN is not provided")
}
namenode, err := rpc.NewNamenodeConnection(
rpc.NamenodeConnectionOptions{
Addresses: options.Addresses,
User: options.User,
DialFunc: options.NamenodeDialFunc,
KerberosClient: options.KerberosClient,
KerberosServicePrincipleName: options.KerberosServicePrincipleName,
},
)
if err != nil {
return nil, err
}
return &Client{namenode: namenode, options: options}, nil
} | [
"func",
"NewClient",
"(",
"options",
"ClientOptions",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"if",
"options",
".",
"KerberosClient",
"!=",
"nil",
"&&",
"options",
".",
"KerberosClient",
".",
"Credentials",
"==",
"nil"... | // NewClient returns a connected Client for the given options, or an error if
// the client could not be created. | [
"NewClient",
"returns",
"a",
"connected",
"Client",
"for",
"the",
"given",
"options",
"or",
"an",
"error",
"if",
"the",
"client",
"could",
"not",
"be",
"created",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/client.go#L122-L147 | train |
colinmarc/hdfs | client.go | CopyToLocal | func (c *Client) CopyToLocal(src string, dst string) error {
remote, err := c.Open(src)
if err != nil {
return err
}
defer remote.Close()
local, err := os.Create(dst)
if err != nil {
return err
}
defer local.Close()
_, err = io.Copy(local, remote)
return err
} | go | func (c *Client) CopyToLocal(src string, dst string) error {
remote, err := c.Open(src)
if err != nil {
return err
}
defer remote.Close()
local, err := os.Create(dst)
if err != nil {
return err
}
defer local.Close()
_, err = io.Copy(local, remote)
return err
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"CopyToLocal",
"(",
"src",
"string",
",",
"dst",
"string",
")",
"error",
"{",
"remote",
",",
"err",
":=",
"c",
".",
"Open",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
... | // CopyToLocal copies the HDFS file specified by src to the local file at dst.
// If dst already exists, it will be overwritten. | [
"CopyToLocal",
"copies",
"the",
"HDFS",
"file",
"specified",
"by",
"src",
"to",
"the",
"local",
"file",
"at",
"dst",
".",
"If",
"dst",
"already",
"exists",
"it",
"will",
"be",
"overwritten",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/client.go#L200-L215 | train |
colinmarc/hdfs | internal/rpc/checksum_reader.go | SetDeadline | func (cr *ChecksumReader) SetDeadline(t time.Time) error {
cr.deadline = t
// Return the error at connection time.
return nil
} | go | func (cr *ChecksumReader) SetDeadline(t time.Time) error {
cr.deadline = t
// Return the error at connection time.
return nil
} | [
"func",
"(",
"cr",
"*",
"ChecksumReader",
")",
"SetDeadline",
"(",
"t",
"time",
".",
"Time",
")",
"error",
"{",
"cr",
".",
"deadline",
"=",
"t",
"\n",
"// Return the error at connection time.",
"return",
"nil",
"\n",
"}"
] | // SetDeadline sets the deadline for future ReadChecksum calls. A zero value
// for t means Read will not time out. | [
"SetDeadline",
"sets",
"the",
"deadline",
"for",
"future",
"ReadChecksum",
"calls",
".",
"A",
"zero",
"value",
"for",
"t",
"means",
"Read",
"will",
"not",
"time",
"out",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/checksum_reader.go#L32-L36 | train |
colinmarc/hdfs | internal/rpc/checksum_reader.go | ReadChecksum | func (cr *ChecksumReader) ReadChecksum() ([]byte, error) {
if cr.datanodes == nil {
locs := cr.Block.GetLocs()
datanodes := make([]string, len(locs))
for i, loc := range locs {
dn := loc.GetId()
datanodes[i] = getDatanodeAddress(dn, cr.UseDatanodeHostname)
}
cr.datanodes = newDatanodeFailover(datanodes)
}
for cr.datanodes.numRemaining() > 0 {
address := cr.datanodes.next()
checksum, err := cr.readChecksum(address)
if err != nil {
cr.datanodes.recordFailure(err)
continue
}
return checksum, nil
}
err := cr.datanodes.lastError()
if err != nil {
err = errors.New("No available datanodes for block.")
}
return nil, err
} | go | func (cr *ChecksumReader) ReadChecksum() ([]byte, error) {
if cr.datanodes == nil {
locs := cr.Block.GetLocs()
datanodes := make([]string, len(locs))
for i, loc := range locs {
dn := loc.GetId()
datanodes[i] = getDatanodeAddress(dn, cr.UseDatanodeHostname)
}
cr.datanodes = newDatanodeFailover(datanodes)
}
for cr.datanodes.numRemaining() > 0 {
address := cr.datanodes.next()
checksum, err := cr.readChecksum(address)
if err != nil {
cr.datanodes.recordFailure(err)
continue
}
return checksum, nil
}
err := cr.datanodes.lastError()
if err != nil {
err = errors.New("No available datanodes for block.")
}
return nil, err
} | [
"func",
"(",
"cr",
"*",
"ChecksumReader",
")",
"ReadChecksum",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"cr",
".",
"datanodes",
"==",
"nil",
"{",
"locs",
":=",
"cr",
".",
"Block",
".",
"GetLocs",
"(",
")",
"\n",
"datanodes",
... | // ReadChecksum returns the checksum of the block. | [
"ReadChecksum",
"returns",
"the",
"checksum",
"of",
"the",
"block",
"."
] | 6f7e441ec688730014b4ca08657db358d7a45b87 | https://github.com/colinmarc/hdfs/blob/6f7e441ec688730014b4ca08657db358d7a45b87/internal/rpc/checksum_reader.go#L39-L68 | train |
gocelery/gocelery | convert.go | GetRealValue | func GetRealValue(val *reflect.Value) interface{} {
if val == nil {
return nil
}
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return val.Int()
case reflect.String:
return val.String()
case reflect.Bool:
return val.Bool()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return val.Uint()
case reflect.Float32, reflect.Float64:
return val.Float()
default:
return nil
}
} | go | func GetRealValue(val *reflect.Value) interface{} {
if val == nil {
return nil
}
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return val.Int()
case reflect.String:
return val.String()
case reflect.Bool:
return val.Bool()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return val.Uint()
case reflect.Float32, reflect.Float64:
return val.Float()
default:
return nil
}
} | [
"func",
"GetRealValue",
"(",
"val",
"*",
"reflect",
".",
"Value",
")",
"interface",
"{",
"}",
"{",
"if",
"val",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"switch",
"val",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Int",
",",
"... | // GetRealValue returns real value of reflect.Value
// Required for JSON Marshalling | [
"GetRealValue",
"returns",
"real",
"value",
"of",
"reflect",
".",
"Value",
"Required",
"for",
"JSON",
"Marshalling"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/convert.go#L13-L31 | train |
gocelery/gocelery | message.go | GetTaskMessage | func (cm *CeleryMessage) GetTaskMessage() *TaskMessage {
// ensure content-type is 'application/json'
if cm.ContentType != "application/json" {
log.Println("unsupported content type " + cm.ContentType)
return nil
}
// ensure body encoding is base64
if cm.Properties.BodyEncoding != "base64" {
log.Println("unsupported body encoding " + cm.Properties.BodyEncoding)
return nil
}
// ensure content encoding is utf-8
if cm.ContentEncoding != "utf-8" {
log.Println("unsupported encoding " + cm.ContentEncoding)
return nil
}
// decode body
taskMessage, err := DecodeTaskMessage(cm.Body)
if err != nil {
log.Println("failed to decode task message")
return nil
}
return taskMessage
} | go | func (cm *CeleryMessage) GetTaskMessage() *TaskMessage {
// ensure content-type is 'application/json'
if cm.ContentType != "application/json" {
log.Println("unsupported content type " + cm.ContentType)
return nil
}
// ensure body encoding is base64
if cm.Properties.BodyEncoding != "base64" {
log.Println("unsupported body encoding " + cm.Properties.BodyEncoding)
return nil
}
// ensure content encoding is utf-8
if cm.ContentEncoding != "utf-8" {
log.Println("unsupported encoding " + cm.ContentEncoding)
return nil
}
// decode body
taskMessage, err := DecodeTaskMessage(cm.Body)
if err != nil {
log.Println("failed to decode task message")
return nil
}
return taskMessage
} | [
"func",
"(",
"cm",
"*",
"CeleryMessage",
")",
"GetTaskMessage",
"(",
")",
"*",
"TaskMessage",
"{",
"// ensure content-type is 'application/json'",
"if",
"cm",
".",
"ContentType",
"!=",
"\"",
"\"",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
"+",
"cm",
".",
... | // GetTaskMessage retrieve and decode task messages from broker | [
"GetTaskMessage",
"retrieve",
"and",
"decode",
"task",
"messages",
"from",
"broker"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/message.go#L87-L110 | train |
gocelery/gocelery | message.go | DecodeTaskMessage | func DecodeTaskMessage(encodedBody string) (*TaskMessage, error) {
body, err := base64.StdEncoding.DecodeString(encodedBody)
if err != nil {
return nil, err
}
message := taskMessagePool.Get().(*TaskMessage)
err = json.Unmarshal(body, message)
if err != nil {
return nil, err
}
return message, nil
} | go | func DecodeTaskMessage(encodedBody string) (*TaskMessage, error) {
body, err := base64.StdEncoding.DecodeString(encodedBody)
if err != nil {
return nil, err
}
message := taskMessagePool.Get().(*TaskMessage)
err = json.Unmarshal(body, message)
if err != nil {
return nil, err
}
return message, nil
} | [
"func",
"DecodeTaskMessage",
"(",
"encodedBody",
"string",
")",
"(",
"*",
"TaskMessage",
",",
"error",
")",
"{",
"body",
",",
"err",
":=",
"base64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"encodedBody",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"r... | // DecodeTaskMessage decodes base64 encrypted body and return TaskMessage object | [
"DecodeTaskMessage",
"decodes",
"base64",
"encrypted",
"body",
"and",
"return",
"TaskMessage",
"object"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/message.go#L156-L167 | train |
gocelery/gocelery | message.go | Encode | func (tm *TaskMessage) Encode() (string, error) {
jsonData, err := json.Marshal(tm)
if err != nil {
return "", err
}
encodedData := base64.StdEncoding.EncodeToString(jsonData)
return encodedData, err
} | go | func (tm *TaskMessage) Encode() (string, error) {
jsonData, err := json.Marshal(tm)
if err != nil {
return "", err
}
encodedData := base64.StdEncoding.EncodeToString(jsonData)
return encodedData, err
} | [
"func",
"(",
"tm",
"*",
"TaskMessage",
")",
"Encode",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"jsonData",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"tm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
... | // Encode returns base64 json encoded string | [
"Encode",
"returns",
"base64",
"json",
"encoded",
"string"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/message.go#L170-L177 | train |
gocelery/gocelery | amqp.go | deliveryAck | func deliveryAck(delivery amqp.Delivery) {
retryCount := 3
var err error
for retryCount > 0 {
if err = delivery.Ack(false); err == nil {
break
}
}
if err != nil {
log.Printf("amqp_backend: failed to acknowledge result message %+v: %+v", delivery.MessageId, err)
}
} | go | func deliveryAck(delivery amqp.Delivery) {
retryCount := 3
var err error
for retryCount > 0 {
if err = delivery.Ack(false); err == nil {
break
}
}
if err != nil {
log.Printf("amqp_backend: failed to acknowledge result message %+v: %+v", delivery.MessageId, err)
}
} | [
"func",
"deliveryAck",
"(",
"delivery",
"amqp",
".",
"Delivery",
")",
"{",
"retryCount",
":=",
"3",
"\n",
"var",
"err",
"error",
"\n",
"for",
"retryCount",
">",
"0",
"{",
"if",
"err",
"=",
"delivery",
".",
"Ack",
"(",
"false",
")",
";",
"err",
"==",
... | // deliveryAck acknowledges delivery message with retries on error | [
"deliveryAck",
"acknowledges",
"delivery",
"message",
"with",
"retries",
"on",
"error"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp.go#L14-L25 | train |
gocelery/gocelery | worker.go | NewCeleryWorker | func NewCeleryWorker(broker CeleryBroker, backend CeleryBackend, numWorkers int) *CeleryWorker {
return &CeleryWorker{
broker: broker,
backend: backend,
numWorkers: numWorkers,
registeredTasks: map[string]interface{}{},
rateLimitPeriod: 100 * time.Millisecond,
}
} | go | func NewCeleryWorker(broker CeleryBroker, backend CeleryBackend, numWorkers int) *CeleryWorker {
return &CeleryWorker{
broker: broker,
backend: backend,
numWorkers: numWorkers,
registeredTasks: map[string]interface{}{},
rateLimitPeriod: 100 * time.Millisecond,
}
} | [
"func",
"NewCeleryWorker",
"(",
"broker",
"CeleryBroker",
",",
"backend",
"CeleryBackend",
",",
"numWorkers",
"int",
")",
"*",
"CeleryWorker",
"{",
"return",
"&",
"CeleryWorker",
"{",
"broker",
":",
"broker",
",",
"backend",
":",
"backend",
",",
"numWorkers",
... | // NewCeleryWorker returns new celery worker | [
"NewCeleryWorker",
"returns",
"new",
"celery",
"worker"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/worker.go#L29-L37 | train |
gocelery/gocelery | worker.go | GetTask | func (w *CeleryWorker) GetTask(name string) interface{} {
w.taskLock.RLock()
task, ok := w.registeredTasks[name]
if !ok {
w.taskLock.RUnlock()
return nil
}
w.taskLock.RUnlock()
return task
} | go | func (w *CeleryWorker) GetTask(name string) interface{} {
w.taskLock.RLock()
task, ok := w.registeredTasks[name]
if !ok {
w.taskLock.RUnlock()
return nil
}
w.taskLock.RUnlock()
return task
} | [
"func",
"(",
"w",
"*",
"CeleryWorker",
")",
"GetTask",
"(",
"name",
"string",
")",
"interface",
"{",
"}",
"{",
"w",
".",
"taskLock",
".",
"RLock",
"(",
")",
"\n",
"task",
",",
"ok",
":=",
"w",
".",
"registeredTasks",
"[",
"name",
"]",
"\n",
"if",
... | // GetTask retrieves registered task | [
"GetTask",
"retrieves",
"registered",
"task"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/worker.go#L108-L117 | train |
gocelery/gocelery | worker.go | RunTask | func (w *CeleryWorker) RunTask(message *TaskMessage) (*ResultMessage, error) {
// get task
task := w.GetTask(message.Task)
if task == nil {
return nil, fmt.Errorf("task %s is not registered", message.Task)
}
// convert to task interface
taskInterface, ok := task.(CeleryTask)
if ok {
if err := taskInterface.ParseKwargs(message.Kwargs); err != nil {
return nil, err
}
val, err := taskInterface.RunTask()
if err != nil {
return nil, err
}
return getResultMessage(val), err
}
// use reflection to execute function ptr
taskFunc := reflect.ValueOf(task)
return runTaskFunc(&taskFunc, message)
} | go | func (w *CeleryWorker) RunTask(message *TaskMessage) (*ResultMessage, error) {
// get task
task := w.GetTask(message.Task)
if task == nil {
return nil, fmt.Errorf("task %s is not registered", message.Task)
}
// convert to task interface
taskInterface, ok := task.(CeleryTask)
if ok {
if err := taskInterface.ParseKwargs(message.Kwargs); err != nil {
return nil, err
}
val, err := taskInterface.RunTask()
if err != nil {
return nil, err
}
return getResultMessage(val), err
}
// use reflection to execute function ptr
taskFunc := reflect.ValueOf(task)
return runTaskFunc(&taskFunc, message)
} | [
"func",
"(",
"w",
"*",
"CeleryWorker",
")",
"RunTask",
"(",
"message",
"*",
"TaskMessage",
")",
"(",
"*",
"ResultMessage",
",",
"error",
")",
"{",
"// get task",
"task",
":=",
"w",
".",
"GetTask",
"(",
"message",
".",
"Task",
")",
"\n",
"if",
"task",
... | // RunTask runs celery task | [
"RunTask",
"runs",
"celery",
"task"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/worker.go#L120-L144 | train |
gocelery/gocelery | redis_backend.go | GetResult | func (cb *RedisCeleryBackend) GetResult(taskID string) (*ResultMessage, error) {
conn := cb.Get()
defer conn.Close()
val, err := conn.Do("GET", fmt.Sprintf("celery-task-meta-%s", taskID))
if err != nil {
return nil, err
}
if val == nil {
return nil, fmt.Errorf("result not available")
}
var resultMessage ResultMessage
err = json.Unmarshal(val.([]byte), &resultMessage)
if err != nil {
return nil, err
}
return &resultMessage, nil
} | go | func (cb *RedisCeleryBackend) GetResult(taskID string) (*ResultMessage, error) {
conn := cb.Get()
defer conn.Close()
val, err := conn.Do("GET", fmt.Sprintf("celery-task-meta-%s", taskID))
if err != nil {
return nil, err
}
if val == nil {
return nil, fmt.Errorf("result not available")
}
var resultMessage ResultMessage
err = json.Unmarshal(val.([]byte), &resultMessage)
if err != nil {
return nil, err
}
return &resultMessage, nil
} | [
"func",
"(",
"cb",
"*",
"RedisCeleryBackend",
")",
"GetResult",
"(",
"taskID",
"string",
")",
"(",
"*",
"ResultMessage",
",",
"error",
")",
"{",
"conn",
":=",
"cb",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"val",
"... | // GetResult queries redis backend to get asynchronous result | [
"GetResult",
"queries",
"redis",
"backend",
"to",
"get",
"asynchronous",
"result"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/redis_backend.go#L27-L43 | train |
gocelery/gocelery | redis_backend.go | SetResult | func (cb *RedisCeleryBackend) SetResult(taskID string, result *ResultMessage) error {
resBytes, err := json.Marshal(result)
if err != nil {
return err
}
conn := cb.Get()
defer conn.Close()
_, err = conn.Do("SETEX", fmt.Sprintf("celery-task-meta-%s", taskID), 86400, resBytes)
return err
} | go | func (cb *RedisCeleryBackend) SetResult(taskID string, result *ResultMessage) error {
resBytes, err := json.Marshal(result)
if err != nil {
return err
}
conn := cb.Get()
defer conn.Close()
_, err = conn.Do("SETEX", fmt.Sprintf("celery-task-meta-%s", taskID), 86400, resBytes)
return err
} | [
"func",
"(",
"cb",
"*",
"RedisCeleryBackend",
")",
"SetResult",
"(",
"taskID",
"string",
",",
"result",
"*",
"ResultMessage",
")",
"error",
"{",
"resBytes",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"... | // SetResult pushes result back into redis backend | [
"SetResult",
"pushes",
"result",
"back",
"into",
"redis",
"backend"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/redis_backend.go#L46-L55 | train |
gocelery/gocelery | gocelery.go | NewCeleryClient | func NewCeleryClient(broker CeleryBroker, backend CeleryBackend, numWorkers int) (*CeleryClient, error) {
return &CeleryClient{
broker,
backend,
NewCeleryWorker(broker, backend, numWorkers),
}, nil
} | go | func NewCeleryClient(broker CeleryBroker, backend CeleryBackend, numWorkers int) (*CeleryClient, error) {
return &CeleryClient{
broker,
backend,
NewCeleryWorker(broker, backend, numWorkers),
}, nil
} | [
"func",
"NewCeleryClient",
"(",
"broker",
"CeleryBroker",
",",
"backend",
"CeleryBackend",
",",
"numWorkers",
"int",
")",
"(",
"*",
"CeleryClient",
",",
"error",
")",
"{",
"return",
"&",
"CeleryClient",
"{",
"broker",
",",
"backend",
",",
"NewCeleryWorker",
"(... | // NewCeleryClient creates new celery client | [
"NewCeleryClient",
"creates",
"new",
"celery",
"client"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/gocelery.go#L33-L39 | train |
gocelery/gocelery | gocelery.go | StartWorkerWithContext | func (cc *CeleryClient) StartWorkerWithContext(ctx context.Context) {
cc.worker.StartWorkerWithContext(ctx)
} | go | func (cc *CeleryClient) StartWorkerWithContext(ctx context.Context) {
cc.worker.StartWorkerWithContext(ctx)
} | [
"func",
"(",
"cc",
"*",
"CeleryClient",
")",
"StartWorkerWithContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"{",
"cc",
".",
"worker",
".",
"StartWorkerWithContext",
"(",
"ctx",
")",
"\n",
"}"
] | // StartWorkerWithContext starts celery workers with given parent context | [
"StartWorkerWithContext",
"starts",
"celery",
"workers",
"with",
"given",
"parent",
"context"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/gocelery.go#L47-L49 | train |
gocelery/gocelery | gocelery.go | Delay | func (cc *CeleryClient) Delay(task string, args ...interface{}) (*AsyncResult, error) {
celeryTask := getTaskMessage(task)
celeryTask.Args = args
return cc.delay(celeryTask)
} | go | func (cc *CeleryClient) Delay(task string, args ...interface{}) (*AsyncResult, error) {
celeryTask := getTaskMessage(task)
celeryTask.Args = args
return cc.delay(celeryTask)
} | [
"func",
"(",
"cc",
"*",
"CeleryClient",
")",
"Delay",
"(",
"task",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"*",
"AsyncResult",
",",
"error",
")",
"{",
"celeryTask",
":=",
"getTaskMessage",
"(",
"task",
")",
"\n",
"celeryTask",
".... | // Delay gets asynchronous result | [
"Delay",
"gets",
"asynchronous",
"result"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/gocelery.go#L67-L71 | train |
gocelery/gocelery | gocelery.go | DelayKwargs | func (cc *CeleryClient) DelayKwargs(task string, args map[string]interface{}) (*AsyncResult, error) {
celeryTask := getTaskMessage(task)
celeryTask.Kwargs = args
return cc.delay(celeryTask)
} | go | func (cc *CeleryClient) DelayKwargs(task string, args map[string]interface{}) (*AsyncResult, error) {
celeryTask := getTaskMessage(task)
celeryTask.Kwargs = args
return cc.delay(celeryTask)
} | [
"func",
"(",
"cc",
"*",
"CeleryClient",
")",
"DelayKwargs",
"(",
"task",
"string",
",",
"args",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"*",
"AsyncResult",
",",
"error",
")",
"{",
"celeryTask",
":=",
"getTaskMessage",
"(",
"task",
"... | // DelayKwargs gets asynchronous results with argument map | [
"DelayKwargs",
"gets",
"asynchronous",
"results",
"with",
"argument",
"map"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/gocelery.go#L74-L78 | train |
gocelery/gocelery | gocelery.go | Get | func (ar *AsyncResult) Get(timeout time.Duration) (interface{}, error) {
ticker := time.NewTicker(50 * time.Millisecond)
timeoutChan := time.After(timeout)
for {
select {
case <-timeoutChan:
err := fmt.Errorf("%v timeout getting result for %s", timeout, ar.TaskID)
return nil, err
case <-ticker.C:
val, err := ar.AsyncGet()
if err != nil {
continue
}
return val, nil
}
}
} | go | func (ar *AsyncResult) Get(timeout time.Duration) (interface{}, error) {
ticker := time.NewTicker(50 * time.Millisecond)
timeoutChan := time.After(timeout)
for {
select {
case <-timeoutChan:
err := fmt.Errorf("%v timeout getting result for %s", timeout, ar.TaskID)
return nil, err
case <-ticker.C:
val, err := ar.AsyncGet()
if err != nil {
continue
}
return val, nil
}
}
} | [
"func",
"(",
"ar",
"*",
"AsyncResult",
")",
"Get",
"(",
"timeout",
"time",
".",
"Duration",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"50",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"t... | // Get gets actual result from backend
// It blocks for period of time set by timeout and returns error if unavailable | [
"Get",
"gets",
"actual",
"result",
"from",
"backend",
"It",
"blocks",
"for",
"period",
"of",
"time",
"set",
"by",
"timeout",
"and",
"returns",
"error",
"if",
"unavailable"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/gocelery.go#L120-L136 | train |
gocelery/gocelery | gocelery.go | AsyncGet | func (ar *AsyncResult) AsyncGet() (interface{}, error) {
if ar.result != nil {
return ar.result.Result, nil
}
val, err := ar.backend.GetResult(ar.TaskID)
if err != nil {
return nil, err
}
if val == nil {
return nil, err
}
if val.Status != "SUCCESS" {
return nil, fmt.Errorf("error response status %v", val)
}
ar.result = val
return val.Result, nil
} | go | func (ar *AsyncResult) AsyncGet() (interface{}, error) {
if ar.result != nil {
return ar.result.Result, nil
}
val, err := ar.backend.GetResult(ar.TaskID)
if err != nil {
return nil, err
}
if val == nil {
return nil, err
}
if val.Status != "SUCCESS" {
return nil, fmt.Errorf("error response status %v", val)
}
ar.result = val
return val.Result, nil
} | [
"func",
"(",
"ar",
"*",
"AsyncResult",
")",
"AsyncGet",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"ar",
".",
"result",
"!=",
"nil",
"{",
"return",
"ar",
".",
"result",
".",
"Result",
",",
"nil",
"\n",
"}",
"\n",
"val",
... | // AsyncGet gets actual result from backend and returns nil if not available | [
"AsyncGet",
"gets",
"actual",
"result",
"from",
"backend",
"and",
"returns",
"nil",
"if",
"not",
"available"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/gocelery.go#L139-L155 | train |
gocelery/gocelery | gocelery.go | Ready | func (ar *AsyncResult) Ready() (bool, error) {
if ar.result != nil {
return true, nil
}
val, err := ar.backend.GetResult(ar.TaskID)
if err != nil {
return false, err
}
ar.result = val
return (val != nil), nil
} | go | func (ar *AsyncResult) Ready() (bool, error) {
if ar.result != nil {
return true, nil
}
val, err := ar.backend.GetResult(ar.TaskID)
if err != nil {
return false, err
}
ar.result = val
return (val != nil), nil
} | [
"func",
"(",
"ar",
"*",
"AsyncResult",
")",
"Ready",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"ar",
".",
"result",
"!=",
"nil",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"val",
",",
"err",
":=",
"ar",
".",
"backend",
".",
... | // Ready checks if actual result is ready | [
"Ready",
"checks",
"if",
"actual",
"result",
"is",
"ready"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/gocelery.go#L158-L168 | train |
gocelery/gocelery | amqp_broker.go | NewAMQPExchange | func NewAMQPExchange(name string) *AMQPExchange {
return &AMQPExchange{
Name: name,
Type: "direct",
Durable: true,
AutoDelete: true,
}
} | go | func NewAMQPExchange(name string) *AMQPExchange {
return &AMQPExchange{
Name: name,
Type: "direct",
Durable: true,
AutoDelete: true,
}
} | [
"func",
"NewAMQPExchange",
"(",
"name",
"string",
")",
"*",
"AMQPExchange",
"{",
"return",
"&",
"AMQPExchange",
"{",
"Name",
":",
"name",
",",
"Type",
":",
"\"",
"\"",
",",
"Durable",
":",
"true",
",",
"AutoDelete",
":",
"true",
",",
"}",
"\n",
"}"
] | // NewAMQPExchange creates new AMQPExchange | [
"NewAMQPExchange",
"creates",
"new",
"AMQPExchange"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_broker.go#L24-L31 | train |
gocelery/gocelery | amqp_broker.go | NewAMQPQueue | func NewAMQPQueue(name string) *AMQPQueue {
return &AMQPQueue{
Name: name,
Durable: true,
AutoDelete: false,
}
} | go | func NewAMQPQueue(name string) *AMQPQueue {
return &AMQPQueue{
Name: name,
Durable: true,
AutoDelete: false,
}
} | [
"func",
"NewAMQPQueue",
"(",
"name",
"string",
")",
"*",
"AMQPQueue",
"{",
"return",
"&",
"AMQPQueue",
"{",
"Name",
":",
"name",
",",
"Durable",
":",
"true",
",",
"AutoDelete",
":",
"false",
",",
"}",
"\n",
"}"
] | // NewAMQPQueue creates new AMQPQueue | [
"NewAMQPQueue",
"creates",
"new",
"AMQPQueue"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_broker.go#L41-L47 | train |
gocelery/gocelery | amqp_broker.go | NewAMQPConnection | func NewAMQPConnection(host string) (*amqp.Connection, *amqp.Channel) {
connection, err := amqp.Dial(host)
if err != nil {
panic(err)
}
channel, err := connection.Channel()
if err != nil {
panic(err)
}
return connection, channel
} | go | func NewAMQPConnection(host string) (*amqp.Connection, *amqp.Channel) {
connection, err := amqp.Dial(host)
if err != nil {
panic(err)
}
channel, err := connection.Channel()
if err != nil {
panic(err)
}
return connection, channel
} | [
"func",
"NewAMQPConnection",
"(",
"host",
"string",
")",
"(",
"*",
"amqp",
".",
"Connection",
",",
"*",
"amqp",
".",
"Channel",
")",
"{",
"connection",
",",
"err",
":=",
"amqp",
".",
"Dial",
"(",
"host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"p... | // NewAMQPConnection creates new AMQP channel | [
"NewAMQPConnection",
"creates",
"new",
"AMQP",
"channel"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_broker.go#L60-L71 | train |
gocelery/gocelery | amqp_broker.go | NewAMQPCeleryBrokerByConnAndChannel | func NewAMQPCeleryBrokerByConnAndChannel(conn *amqp.Connection, channel *amqp.Channel) *AMQPCeleryBroker {
broker := &AMQPCeleryBroker{
Channel: channel,
connection: conn,
exchange: NewAMQPExchange("default"),
queue: NewAMQPQueue("celery"),
rate: 4,
}
if err := broker.CreateExchange(); err != nil {
panic(err)
}
if err := broker.CreateQueue(); err != nil {
panic(err)
}
if err := broker.Qos(broker.rate, 0, false); err != nil {
panic(err)
}
if err := broker.StartConsumingChannel(); err != nil {
panic(err)
}
return broker
} | go | func NewAMQPCeleryBrokerByConnAndChannel(conn *amqp.Connection, channel *amqp.Channel) *AMQPCeleryBroker {
broker := &AMQPCeleryBroker{
Channel: channel,
connection: conn,
exchange: NewAMQPExchange("default"),
queue: NewAMQPQueue("celery"),
rate: 4,
}
if err := broker.CreateExchange(); err != nil {
panic(err)
}
if err := broker.CreateQueue(); err != nil {
panic(err)
}
if err := broker.Qos(broker.rate, 0, false); err != nil {
panic(err)
}
if err := broker.StartConsumingChannel(); err != nil {
panic(err)
}
return broker
} | [
"func",
"NewAMQPCeleryBrokerByConnAndChannel",
"(",
"conn",
"*",
"amqp",
".",
"Connection",
",",
"channel",
"*",
"amqp",
".",
"Channel",
")",
"*",
"AMQPCeleryBroker",
"{",
"broker",
":=",
"&",
"AMQPCeleryBroker",
"{",
"Channel",
":",
"channel",
",",
"connection"... | // NewAMQPCeleryBrokerByConnAndChannel creates new AMQPCeleryBroker using AMQP conn and channel | [
"NewAMQPCeleryBrokerByConnAndChannel",
"creates",
"new",
"AMQPCeleryBroker",
"using",
"AMQP",
"conn",
"and",
"channel"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_broker.go#L79-L100 | train |
gocelery/gocelery | amqp_broker.go | StartConsumingChannel | func (b *AMQPCeleryBroker) StartConsumingChannel() error {
channel, err := b.Consume(b.queue.Name, "", false, false, false, false, nil)
if err != nil {
return err
}
b.consumingChannel = channel
return nil
} | go | func (b *AMQPCeleryBroker) StartConsumingChannel() error {
channel, err := b.Consume(b.queue.Name, "", false, false, false, false, nil)
if err != nil {
return err
}
b.consumingChannel = channel
return nil
} | [
"func",
"(",
"b",
"*",
"AMQPCeleryBroker",
")",
"StartConsumingChannel",
"(",
")",
"error",
"{",
"channel",
",",
"err",
":=",
"b",
".",
"Consume",
"(",
"b",
".",
"queue",
".",
"Name",
",",
"\"",
"\"",
",",
"false",
",",
"false",
",",
"false",
",",
... | // StartConsumingChannel spawns receiving channel on AMQP queue | [
"StartConsumingChannel",
"spawns",
"receiving",
"channel",
"on",
"AMQP",
"queue"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_broker.go#L103-L110 | train |
gocelery/gocelery | amqp_broker.go | SendCeleryMessage | func (b *AMQPCeleryBroker) SendCeleryMessage(message *CeleryMessage) error {
taskMessage := message.GetTaskMessage()
queueName := "celery"
_, err := b.QueueDeclare(
queueName, // name
true, // durable
false, // autoDelete
false, // exclusive
false, // noWait
nil, // args
)
if err != nil {
return err
}
err = b.ExchangeDeclare(
"default",
"direct",
true,
true,
false,
false,
nil,
)
if err != nil {
return err
}
resBytes, err := json.Marshal(taskMessage)
if err != nil {
return err
}
publishMessage := amqp.Publishing{
DeliveryMode: amqp.Persistent,
Timestamp: time.Now(),
ContentType: "application/json",
Body: resBytes,
}
return b.Publish(
"",
queueName,
false,
false,
publishMessage,
)
} | go | func (b *AMQPCeleryBroker) SendCeleryMessage(message *CeleryMessage) error {
taskMessage := message.GetTaskMessage()
queueName := "celery"
_, err := b.QueueDeclare(
queueName, // name
true, // durable
false, // autoDelete
false, // exclusive
false, // noWait
nil, // args
)
if err != nil {
return err
}
err = b.ExchangeDeclare(
"default",
"direct",
true,
true,
false,
false,
nil,
)
if err != nil {
return err
}
resBytes, err := json.Marshal(taskMessage)
if err != nil {
return err
}
publishMessage := amqp.Publishing{
DeliveryMode: amqp.Persistent,
Timestamp: time.Now(),
ContentType: "application/json",
Body: resBytes,
}
return b.Publish(
"",
queueName,
false,
false,
publishMessage,
)
} | [
"func",
"(",
"b",
"*",
"AMQPCeleryBroker",
")",
"SendCeleryMessage",
"(",
"message",
"*",
"CeleryMessage",
")",
"error",
"{",
"taskMessage",
":=",
"message",
".",
"GetTaskMessage",
"(",
")",
"\n",
"queueName",
":=",
"\"",
"\"",
"\n",
"_",
",",
"err",
":=",... | // SendCeleryMessage sends CeleryMessage to broker | [
"SendCeleryMessage",
"sends",
"CeleryMessage",
"to",
"broker"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_broker.go#L113-L159 | train |
gocelery/gocelery | amqp_broker.go | GetTaskMessage | func (b *AMQPCeleryBroker) GetTaskMessage() (*TaskMessage, error) {
select {
case delivery := <-b.consumingChannel:
deliveryAck(delivery)
var taskMessage TaskMessage
if err := json.Unmarshal(delivery.Body, &taskMessage); err != nil {
return nil, err
}
return &taskMessage, nil
default:
return nil, fmt.Errorf("consuming channel is empty")
}
} | go | func (b *AMQPCeleryBroker) GetTaskMessage() (*TaskMessage, error) {
select {
case delivery := <-b.consumingChannel:
deliveryAck(delivery)
var taskMessage TaskMessage
if err := json.Unmarshal(delivery.Body, &taskMessage); err != nil {
return nil, err
}
return &taskMessage, nil
default:
return nil, fmt.Errorf("consuming channel is empty")
}
} | [
"func",
"(",
"b",
"*",
"AMQPCeleryBroker",
")",
"GetTaskMessage",
"(",
")",
"(",
"*",
"TaskMessage",
",",
"error",
")",
"{",
"select",
"{",
"case",
"delivery",
":=",
"<-",
"b",
".",
"consumingChannel",
":",
"deliveryAck",
"(",
"delivery",
")",
"\n",
"var... | // GetTaskMessage retrieves task message from AMQP queue | [
"GetTaskMessage",
"retrieves",
"task",
"message",
"from",
"AMQP",
"queue"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_broker.go#L162-L174 | train |
gocelery/gocelery | amqp_broker.go | CreateExchange | func (b *AMQPCeleryBroker) CreateExchange() error {
return b.ExchangeDeclare(
b.exchange.Name,
b.exchange.Type,
b.exchange.Durable,
b.exchange.AutoDelete,
false,
false,
nil,
)
} | go | func (b *AMQPCeleryBroker) CreateExchange() error {
return b.ExchangeDeclare(
b.exchange.Name,
b.exchange.Type,
b.exchange.Durable,
b.exchange.AutoDelete,
false,
false,
nil,
)
} | [
"func",
"(",
"b",
"*",
"AMQPCeleryBroker",
")",
"CreateExchange",
"(",
")",
"error",
"{",
"return",
"b",
".",
"ExchangeDeclare",
"(",
"b",
".",
"exchange",
".",
"Name",
",",
"b",
".",
"exchange",
".",
"Type",
",",
"b",
".",
"exchange",
".",
"Durable",
... | // CreateExchange declares AMQP exchange with stored configuration | [
"CreateExchange",
"declares",
"AMQP",
"exchange",
"with",
"stored",
"configuration"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_broker.go#L177-L187 | train |
gocelery/gocelery | amqp_broker.go | CreateQueue | func (b *AMQPCeleryBroker) CreateQueue() error {
_, err := b.QueueDeclare(
b.queue.Name,
b.queue.Durable,
b.queue.AutoDelete,
false,
false,
nil,
)
return err
} | go | func (b *AMQPCeleryBroker) CreateQueue() error {
_, err := b.QueueDeclare(
b.queue.Name,
b.queue.Durable,
b.queue.AutoDelete,
false,
false,
nil,
)
return err
} | [
"func",
"(",
"b",
"*",
"AMQPCeleryBroker",
")",
"CreateQueue",
"(",
")",
"error",
"{",
"_",
",",
"err",
":=",
"b",
".",
"QueueDeclare",
"(",
"b",
".",
"queue",
".",
"Name",
",",
"b",
".",
"queue",
".",
"Durable",
",",
"b",
".",
"queue",
".",
"Aut... | // CreateQueue declares AMQP Queue with stored configuration | [
"CreateQueue",
"declares",
"AMQP",
"Queue",
"with",
"stored",
"configuration"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_broker.go#L190-L200 | train |
gocelery/gocelery | amqp_backend.go | NewAMQPCeleryBackendByConnAndChannel | func NewAMQPCeleryBackendByConnAndChannel(conn *amqp.Connection, channel *amqp.Channel) *AMQPCeleryBackend {
backend := &AMQPCeleryBackend{
Channel: channel,
connection: conn,
}
return backend
} | go | func NewAMQPCeleryBackendByConnAndChannel(conn *amqp.Connection, channel *amqp.Channel) *AMQPCeleryBackend {
backend := &AMQPCeleryBackend{
Channel: channel,
connection: conn,
}
return backend
} | [
"func",
"NewAMQPCeleryBackendByConnAndChannel",
"(",
"conn",
"*",
"amqp",
".",
"Connection",
",",
"channel",
"*",
"amqp",
".",
"Channel",
")",
"*",
"AMQPCeleryBackend",
"{",
"backend",
":=",
"&",
"AMQPCeleryBackend",
"{",
"Channel",
":",
"channel",
",",
"connect... | // NewAMQPCeleryBackendByConnAndChannel creates new AMQPCeleryBackend by AMQP connection and channel | [
"NewAMQPCeleryBackendByConnAndChannel",
"creates",
"new",
"AMQPCeleryBackend",
"by",
"AMQP",
"connection",
"and",
"channel"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_backend.go#L23-L29 | train |
gocelery/gocelery | amqp_backend.go | NewAMQPCeleryBackend | func NewAMQPCeleryBackend(host string) *AMQPCeleryBackend {
backend := NewAMQPCeleryBackendByConnAndChannel(NewAMQPConnection(host))
backend.host = host
return backend
} | go | func NewAMQPCeleryBackend(host string) *AMQPCeleryBackend {
backend := NewAMQPCeleryBackendByConnAndChannel(NewAMQPConnection(host))
backend.host = host
return backend
} | [
"func",
"NewAMQPCeleryBackend",
"(",
"host",
"string",
")",
"*",
"AMQPCeleryBackend",
"{",
"backend",
":=",
"NewAMQPCeleryBackendByConnAndChannel",
"(",
"NewAMQPConnection",
"(",
"host",
")",
")",
"\n",
"backend",
".",
"host",
"=",
"host",
"\n",
"return",
"backend... | // NewAMQPCeleryBackend creates new AMQPCeleryBackend | [
"NewAMQPCeleryBackend",
"creates",
"new",
"AMQPCeleryBackend"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_backend.go#L32-L36 | train |
gocelery/gocelery | amqp_backend.go | Reconnect | func (b *AMQPCeleryBackend) Reconnect() {
b.connection.Close()
conn, channel := NewAMQPConnection(b.host)
b.Channel = channel
b.connection = conn
} | go | func (b *AMQPCeleryBackend) Reconnect() {
b.connection.Close()
conn, channel := NewAMQPConnection(b.host)
b.Channel = channel
b.connection = conn
} | [
"func",
"(",
"b",
"*",
"AMQPCeleryBackend",
")",
"Reconnect",
"(",
")",
"{",
"b",
".",
"connection",
".",
"Close",
"(",
")",
"\n",
"conn",
",",
"channel",
":=",
"NewAMQPConnection",
"(",
"b",
".",
"host",
")",
"\n",
"b",
".",
"Channel",
"=",
"channel... | // Reconnect reconnects to AMQP server | [
"Reconnect",
"reconnects",
"to",
"AMQP",
"server"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_backend.go#L39-L44 | train |
gocelery/gocelery | amqp_backend.go | GetResult | func (b *AMQPCeleryBackend) GetResult(taskID string) (*ResultMessage, error) {
queueName := strings.Replace(taskID, "-", "", -1)
args := amqp.Table{"x-expires": int32(86400000)}
_, err := b.QueueDeclare(
queueName, // name
true, // durable
true, // autoDelete
false, // exclusive
false, // noWait
args, // args
)
if err != nil {
return nil, err
}
err = b.ExchangeDeclare(
"default",
"direct",
true,
true,
false,
false,
nil,
)
if err != nil {
return nil, err
}
// open channel temporarily
channel, err := b.Consume(queueName, "", false, false, false, false, nil)
if err != nil {
return nil, err
}
var resultMessage ResultMessage
delivery := <-channel
deliveryAck(delivery)
if err := json.Unmarshal(delivery.Body, &resultMessage); err != nil {
return nil, err
}
return &resultMessage, nil
} | go | func (b *AMQPCeleryBackend) GetResult(taskID string) (*ResultMessage, error) {
queueName := strings.Replace(taskID, "-", "", -1)
args := amqp.Table{"x-expires": int32(86400000)}
_, err := b.QueueDeclare(
queueName, // name
true, // durable
true, // autoDelete
false, // exclusive
false, // noWait
args, // args
)
if err != nil {
return nil, err
}
err = b.ExchangeDeclare(
"default",
"direct",
true,
true,
false,
false,
nil,
)
if err != nil {
return nil, err
}
// open channel temporarily
channel, err := b.Consume(queueName, "", false, false, false, false, nil)
if err != nil {
return nil, err
}
var resultMessage ResultMessage
delivery := <-channel
deliveryAck(delivery)
if err := json.Unmarshal(delivery.Body, &resultMessage); err != nil {
return nil, err
}
return &resultMessage, nil
} | [
"func",
"(",
"b",
"*",
"AMQPCeleryBackend",
")",
"GetResult",
"(",
"taskID",
"string",
")",
"(",
"*",
"ResultMessage",
",",
"error",
")",
"{",
"queueName",
":=",
"strings",
".",
"Replace",
"(",
"taskID",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1... | // GetResult retrieves result from AMQP queue | [
"GetResult",
"retrieves",
"result",
"from",
"AMQP",
"queue"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_backend.go#L47-L92 | train |
gocelery/gocelery | amqp_backend.go | SetResult | func (b *AMQPCeleryBackend) SetResult(taskID string, result *ResultMessage) error {
result.ID = taskID
//queueName := taskID
queueName := strings.Replace(taskID, "-", "", -1)
// autodelete is automatically set to true by python
// (406) PRECONDITION_FAILED - inequivalent arg 'durable' for queue 'bc58c0d895c7421eb7cb2b9bbbd8b36f' in vhost '/': received 'true' but current is 'false'
args := amqp.Table{"x-expires": int32(86400000)}
_, err := b.QueueDeclare(
queueName, // name
true, // durable
true, // autoDelete
false, // exclusive
false, // noWait
args, // args
)
if err != nil {
return err
}
err = b.ExchangeDeclare(
"default",
"direct",
true,
true,
false,
false,
nil,
)
if err != nil {
return err
}
resBytes, err := json.Marshal(result)
if err != nil {
return err
}
message := amqp.Publishing{
DeliveryMode: amqp.Persistent,
Timestamp: time.Now(),
ContentType: "application/json",
Body: resBytes,
}
return b.Publish(
"",
queueName,
false,
false,
message,
)
} | go | func (b *AMQPCeleryBackend) SetResult(taskID string, result *ResultMessage) error {
result.ID = taskID
//queueName := taskID
queueName := strings.Replace(taskID, "-", "", -1)
// autodelete is automatically set to true by python
// (406) PRECONDITION_FAILED - inequivalent arg 'durable' for queue 'bc58c0d895c7421eb7cb2b9bbbd8b36f' in vhost '/': received 'true' but current is 'false'
args := amqp.Table{"x-expires": int32(86400000)}
_, err := b.QueueDeclare(
queueName, // name
true, // durable
true, // autoDelete
false, // exclusive
false, // noWait
args, // args
)
if err != nil {
return err
}
err = b.ExchangeDeclare(
"default",
"direct",
true,
true,
false,
false,
nil,
)
if err != nil {
return err
}
resBytes, err := json.Marshal(result)
if err != nil {
return err
}
message := amqp.Publishing{
DeliveryMode: amqp.Persistent,
Timestamp: time.Now(),
ContentType: "application/json",
Body: resBytes,
}
return b.Publish(
"",
queueName,
false,
false,
message,
)
} | [
"func",
"(",
"b",
"*",
"AMQPCeleryBackend",
")",
"SetResult",
"(",
"taskID",
"string",
",",
"result",
"*",
"ResultMessage",
")",
"error",
"{",
"result",
".",
"ID",
"=",
"taskID",
"\n\n",
"//queueName := taskID",
"queueName",
":=",
"strings",
".",
"Replace",
... | // SetResult sets result back to AMQP queue | [
"SetResult",
"sets",
"result",
"back",
"to",
"AMQP",
"queue"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/amqp_backend.go#L95-L149 | train |
gocelery/gocelery | redis_broker.go | NewRedisPool | func NewRedisPool(uri string) *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.DialURL(uri)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
} | go | func NewRedisPool(uri string) *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.DialURL(uri)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
} | [
"func",
"NewRedisPool",
"(",
"uri",
"string",
")",
"*",
"redis",
".",
"Pool",
"{",
"return",
"&",
"redis",
".",
"Pool",
"{",
"MaxIdle",
":",
"3",
",",
"IdleTimeout",
":",
"240",
"*",
"time",
".",
"Second",
",",
"Dial",
":",
"func",
"(",
")",
"(",
... | // NewRedisPool creates pool of redis connections from given connection string | [
"NewRedisPool",
"creates",
"pool",
"of",
"redis",
"connections",
"from",
"given",
"connection",
"string"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/redis_broker.go#L22-L38 | train |
gocelery/gocelery | redis_broker.go | SendCeleryMessage | func (cb *RedisCeleryBroker) SendCeleryMessage(message *CeleryMessage) error {
jsonBytes, err := json.Marshal(message)
if err != nil {
return err
}
conn := cb.Get()
defer conn.Close()
_, err = conn.Do("LPUSH", cb.queueName, jsonBytes)
if err != nil {
return err
}
return nil
} | go | func (cb *RedisCeleryBroker) SendCeleryMessage(message *CeleryMessage) error {
jsonBytes, err := json.Marshal(message)
if err != nil {
return err
}
conn := cb.Get()
defer conn.Close()
_, err = conn.Do("LPUSH", cb.queueName, jsonBytes)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"cb",
"*",
"RedisCeleryBroker",
")",
"SendCeleryMessage",
"(",
"message",
"*",
"CeleryMessage",
")",
"error",
"{",
"jsonBytes",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"message",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"er... | // SendCeleryMessage sends CeleryMessage to redis queue | [
"SendCeleryMessage",
"sends",
"CeleryMessage",
"to",
"redis",
"queue"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/redis_broker.go#L49-L61 | train |
gocelery/gocelery | redis_broker.go | GetCeleryMessage | func (cb *RedisCeleryBroker) GetCeleryMessage() (*CeleryMessage, error) {
conn := cb.Get()
defer conn.Close()
messageJSON, err := conn.Do("BLPOP", cb.queueName, "1")
if err != nil {
return nil, err
}
if messageJSON == nil {
return nil, fmt.Errorf("null message received from redis")
}
messageList := messageJSON.([]interface{})
if string(messageList[0].([]byte)) != "celery" {
return nil, fmt.Errorf("not a celery message: %v", messageList[0])
}
var message CeleryMessage
if err := json.Unmarshal(messageList[1].([]byte), &message); err != nil {
return nil, err
}
return &message, nil
} | go | func (cb *RedisCeleryBroker) GetCeleryMessage() (*CeleryMessage, error) {
conn := cb.Get()
defer conn.Close()
messageJSON, err := conn.Do("BLPOP", cb.queueName, "1")
if err != nil {
return nil, err
}
if messageJSON == nil {
return nil, fmt.Errorf("null message received from redis")
}
messageList := messageJSON.([]interface{})
if string(messageList[0].([]byte)) != "celery" {
return nil, fmt.Errorf("not a celery message: %v", messageList[0])
}
var message CeleryMessage
if err := json.Unmarshal(messageList[1].([]byte), &message); err != nil {
return nil, err
}
return &message, nil
} | [
"func",
"(",
"cb",
"*",
"RedisCeleryBroker",
")",
"GetCeleryMessage",
"(",
")",
"(",
"*",
"CeleryMessage",
",",
"error",
")",
"{",
"conn",
":=",
"cb",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"messageJSON",
",",
"err... | // GetCeleryMessage retrieves celery message from redis queue | [
"GetCeleryMessage",
"retrieves",
"celery",
"message",
"from",
"redis",
"queue"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/redis_broker.go#L64-L83 | train |
gocelery/gocelery | redis_broker.go | GetTaskMessage | func (cb *RedisCeleryBroker) GetTaskMessage() (*TaskMessage, error) {
celeryMessage, err := cb.GetCeleryMessage()
if err != nil {
return nil, err
}
return celeryMessage.GetTaskMessage(), nil
} | go | func (cb *RedisCeleryBroker) GetTaskMessage() (*TaskMessage, error) {
celeryMessage, err := cb.GetCeleryMessage()
if err != nil {
return nil, err
}
return celeryMessage.GetTaskMessage(), nil
} | [
"func",
"(",
"cb",
"*",
"RedisCeleryBroker",
")",
"GetTaskMessage",
"(",
")",
"(",
"*",
"TaskMessage",
",",
"error",
")",
"{",
"celeryMessage",
",",
"err",
":=",
"cb",
".",
"GetCeleryMessage",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"n... | // GetTaskMessage retrieves task message from redis queue | [
"GetTaskMessage",
"retrieves",
"task",
"message",
"from",
"redis",
"queue"
] | b32fedd18857d5975170395a2b8145ed7d1b5885 | https://github.com/gocelery/gocelery/blob/b32fedd18857d5975170395a2b8145ed7d1b5885/redis_broker.go#L86-L92 | train |
pseudomuto/protoc-gen-doc | filters.go | NoBrFilter | func NoBrFilter(content string) string {
normalized := strings.Replace(content, "\r\n", "\n", -1)
paragraphs := multiNewlinePattern.Split(normalized, -1)
for i, p := range paragraphs {
withoutCR := strings.Replace(p, "\r", " ", -1)
withoutLF := strings.Replace(withoutCR, "\n", " ", -1)
paragraphs[i] = spacePattern.ReplaceAllString(withoutLF, " ")
}
return strings.Join(paragraphs, "\n\n")
} | go | func NoBrFilter(content string) string {
normalized := strings.Replace(content, "\r\n", "\n", -1)
paragraphs := multiNewlinePattern.Split(normalized, -1)
for i, p := range paragraphs {
withoutCR := strings.Replace(p, "\r", " ", -1)
withoutLF := strings.Replace(withoutCR, "\n", " ", -1)
paragraphs[i] = spacePattern.ReplaceAllString(withoutLF, " ")
}
return strings.Join(paragraphs, "\n\n")
} | [
"func",
"NoBrFilter",
"(",
"content",
"string",
")",
"string",
"{",
"normalized",
":=",
"strings",
".",
"Replace",
"(",
"content",
",",
"\"",
"\\r",
"\\n",
"\"",
",",
"\"",
"\\n",
"\"",
",",
"-",
"1",
")",
"\n",
"paragraphs",
":=",
"multiNewlinePattern",... | // NoBrFilter removes single CR and LF from content. | [
"NoBrFilter",
"removes",
"single",
"CR",
"and",
"LF",
"from",
"content",
"."
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/filters.go#L29-L38 | train |
pseudomuto/protoc-gen-doc | template.go | NewTemplate | func NewTemplate(descs []*protokit.FileDescriptor) *Template {
files := make([]*File, 0, len(descs))
for _, f := range descs {
file := &File{
Name: f.GetName(),
Description: description(f.GetSyntaxComments().String()),
Package: f.GetPackage(),
HasEnums: len(f.Enums) > 0,
HasExtensions: len(f.Extensions) > 0,
HasMessages: len(f.Messages) > 0,
HasServices: len(f.Services) > 0,
Enums: make(orderedEnums, 0, len(f.Enums)),
Extensions: make(orderedExtensions, 0, len(f.Extensions)),
Messages: make(orderedMessages, 0, len(f.Messages)),
Services: make(orderedServices, 0, len(f.Services)),
Options: mergeOptions(extractOptions(f.GetOptions()), extensions.Transform(f.OptionExtensions)),
}
for _, e := range f.Enums {
file.Enums = append(file.Enums, parseEnum(e))
}
for _, e := range f.Extensions {
file.Extensions = append(file.Extensions, parseFileExtension(e))
}
// Recursively add nested types from messages
var addFromMessage func(*protokit.Descriptor)
addFromMessage = func(m *protokit.Descriptor) {
file.Messages = append(file.Messages, parseMessage(m))
for _, e := range m.Enums {
file.Enums = append(file.Enums, parseEnum(e))
}
for _, n := range m.Messages {
addFromMessage(n)
}
}
for _, m := range f.Messages {
addFromMessage(m)
}
for _, s := range f.Services {
file.Services = append(file.Services, parseService(s))
}
sort.Sort(file.Enums)
sort.Sort(file.Extensions)
sort.Sort(file.Messages)
sort.Sort(file.Services)
files = append(files, file)
}
return &Template{Files: files, Scalars: makeScalars()}
} | go | func NewTemplate(descs []*protokit.FileDescriptor) *Template {
files := make([]*File, 0, len(descs))
for _, f := range descs {
file := &File{
Name: f.GetName(),
Description: description(f.GetSyntaxComments().String()),
Package: f.GetPackage(),
HasEnums: len(f.Enums) > 0,
HasExtensions: len(f.Extensions) > 0,
HasMessages: len(f.Messages) > 0,
HasServices: len(f.Services) > 0,
Enums: make(orderedEnums, 0, len(f.Enums)),
Extensions: make(orderedExtensions, 0, len(f.Extensions)),
Messages: make(orderedMessages, 0, len(f.Messages)),
Services: make(orderedServices, 0, len(f.Services)),
Options: mergeOptions(extractOptions(f.GetOptions()), extensions.Transform(f.OptionExtensions)),
}
for _, e := range f.Enums {
file.Enums = append(file.Enums, parseEnum(e))
}
for _, e := range f.Extensions {
file.Extensions = append(file.Extensions, parseFileExtension(e))
}
// Recursively add nested types from messages
var addFromMessage func(*protokit.Descriptor)
addFromMessage = func(m *protokit.Descriptor) {
file.Messages = append(file.Messages, parseMessage(m))
for _, e := range m.Enums {
file.Enums = append(file.Enums, parseEnum(e))
}
for _, n := range m.Messages {
addFromMessage(n)
}
}
for _, m := range f.Messages {
addFromMessage(m)
}
for _, s := range f.Services {
file.Services = append(file.Services, parseService(s))
}
sort.Sort(file.Enums)
sort.Sort(file.Extensions)
sort.Sort(file.Messages)
sort.Sort(file.Services)
files = append(files, file)
}
return &Template{Files: files, Scalars: makeScalars()}
} | [
"func",
"NewTemplate",
"(",
"descs",
"[",
"]",
"*",
"protokit",
".",
"FileDescriptor",
")",
"*",
"Template",
"{",
"files",
":=",
"make",
"(",
"[",
"]",
"*",
"File",
",",
"0",
",",
"len",
"(",
"descs",
")",
")",
"\n\n",
"for",
"_",
",",
"f",
":=",... | // NewTemplate creates a Template object from a set of descriptors. | [
"NewTemplate",
"creates",
"a",
"Template",
"object",
"from",
"a",
"set",
"of",
"descriptors",
"."
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/template.go#L24-L79 | train |
pseudomuto/protoc-gen-doc | template.go | FieldOptions | func (m Message) FieldOptions() []string {
optionSet := make(map[string]struct{})
for _, field := range m.Fields {
for option := range field.Options {
optionSet[option] = struct{}{}
}
}
if len(optionSet) == 0 {
return nil
}
options := make([]string, 0, len(optionSet))
for option := range optionSet {
options = append(options, option)
}
sort.Strings(options)
return options
} | go | func (m Message) FieldOptions() []string {
optionSet := make(map[string]struct{})
for _, field := range m.Fields {
for option := range field.Options {
optionSet[option] = struct{}{}
}
}
if len(optionSet) == 0 {
return nil
}
options := make([]string, 0, len(optionSet))
for option := range optionSet {
options = append(options, option)
}
sort.Strings(options)
return options
} | [
"func",
"(",
"m",
"Message",
")",
"FieldOptions",
"(",
")",
"[",
"]",
"string",
"{",
"optionSet",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"field",
":=",
"range",
"m",
".",
"Fields",
"{",
"for"... | // FieldOptions returns all options that are set on the fields in this message. | [
"FieldOptions",
"returns",
"all",
"options",
"that",
"are",
"set",
"on",
"the",
"fields",
"in",
"this",
"message",
"."
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/template.go#L190-L206 | train |
pseudomuto/protoc-gen-doc | template.go | FieldsWithOption | func (m Message) FieldsWithOption(optionName string) []*MessageField {
fields := make([]*MessageField, 0, len(m.Fields))
for _, field := range m.Fields {
if _, ok := field.Options[optionName]; ok {
fields = append(fields, field)
}
}
if len(fields) > 0 {
return fields
}
return nil
} | go | func (m Message) FieldsWithOption(optionName string) []*MessageField {
fields := make([]*MessageField, 0, len(m.Fields))
for _, field := range m.Fields {
if _, ok := field.Options[optionName]; ok {
fields = append(fields, field)
}
}
if len(fields) > 0 {
return fields
}
return nil
} | [
"func",
"(",
"m",
"Message",
")",
"FieldsWithOption",
"(",
"optionName",
"string",
")",
"[",
"]",
"*",
"MessageField",
"{",
"fields",
":=",
"make",
"(",
"[",
"]",
"*",
"MessageField",
",",
"0",
",",
"len",
"(",
"m",
".",
"Fields",
")",
")",
"\n",
"... | // FieldsWithOption returns all fields that have the given option set.
// If no single value has the option set, this returns nil. | [
"FieldsWithOption",
"returns",
"all",
"fields",
"that",
"have",
"the",
"given",
"option",
"set",
".",
"If",
"no",
"single",
"value",
"has",
"the",
"option",
"set",
"this",
"returns",
"nil",
"."
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/template.go#L210-L221 | train |
pseudomuto/protoc-gen-doc | template.go | ValueOptions | func (e Enum) ValueOptions() []string {
optionSet := make(map[string]struct{})
for _, value := range e.Values {
for option := range value.Options {
optionSet[option] = struct{}{}
}
}
if len(optionSet) == 0 {
return nil
}
options := make([]string, 0, len(optionSet))
for option := range optionSet {
options = append(options, option)
}
sort.Strings(options)
return options
} | go | func (e Enum) ValueOptions() []string {
optionSet := make(map[string]struct{})
for _, value := range e.Values {
for option := range value.Options {
optionSet[option] = struct{}{}
}
}
if len(optionSet) == 0 {
return nil
}
options := make([]string, 0, len(optionSet))
for option := range optionSet {
options = append(options, option)
}
sort.Strings(options)
return options
} | [
"func",
"(",
"e",
"Enum",
")",
"ValueOptions",
"(",
")",
"[",
"]",
"string",
"{",
"optionSet",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"value",
":=",
"range",
"e",
".",
"Values",
"{",
"for",
... | // ValueOptions returns all options that are set on the values in this enum. | [
"ValueOptions",
"returns",
"all",
"options",
"that",
"are",
"set",
"on",
"the",
"values",
"in",
"this",
"enum",
"."
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/template.go#L267-L283 | train |
pseudomuto/protoc-gen-doc | template.go | ValuesWithOption | func (e Enum) ValuesWithOption(optionName string) []*EnumValue {
values := make([]*EnumValue, 0, len(e.Values))
for _, value := range e.Values {
if _, ok := value.Options[optionName]; ok {
values = append(values, value)
}
}
if len(values) > 0 {
return values
}
return nil
} | go | func (e Enum) ValuesWithOption(optionName string) []*EnumValue {
values := make([]*EnumValue, 0, len(e.Values))
for _, value := range e.Values {
if _, ok := value.Options[optionName]; ok {
values = append(values, value)
}
}
if len(values) > 0 {
return values
}
return nil
} | [
"func",
"(",
"e",
"Enum",
")",
"ValuesWithOption",
"(",
"optionName",
"string",
")",
"[",
"]",
"*",
"EnumValue",
"{",
"values",
":=",
"make",
"(",
"[",
"]",
"*",
"EnumValue",
",",
"0",
",",
"len",
"(",
"e",
".",
"Values",
")",
")",
"\n",
"for",
"... | // ValuesWithOption returns all values that have the given option set.
// If no single value has the option set, this returns nil. | [
"ValuesWithOption",
"returns",
"all",
"values",
"that",
"have",
"the",
"given",
"option",
"set",
".",
"If",
"no",
"single",
"value",
"has",
"the",
"option",
"set",
"this",
"returns",
"nil",
"."
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/template.go#L287-L298 | train |
pseudomuto/protoc-gen-doc | template.go | MethodOptions | func (s Service) MethodOptions() []string {
optionSet := make(map[string]struct{})
for _, method := range s.Methods {
for option := range method.Options {
optionSet[option] = struct{}{}
}
}
if len(optionSet) == 0 {
return nil
}
options := make([]string, 0, len(optionSet))
for option := range optionSet {
options = append(options, option)
}
sort.Strings(options)
return options
} | go | func (s Service) MethodOptions() []string {
optionSet := make(map[string]struct{})
for _, method := range s.Methods {
for option := range method.Options {
optionSet[option] = struct{}{}
}
}
if len(optionSet) == 0 {
return nil
}
options := make([]string, 0, len(optionSet))
for option := range optionSet {
options = append(options, option)
}
sort.Strings(options)
return options
} | [
"func",
"(",
"s",
"Service",
")",
"MethodOptions",
"(",
")",
"[",
"]",
"string",
"{",
"optionSet",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"method",
":=",
"range",
"s",
".",
"Methods",
"{",
"f... | // MethodOptions returns all options that are set on the methods in this service. | [
"MethodOptions",
"returns",
"all",
"options",
"that",
"are",
"set",
"on",
"the",
"methods",
"in",
"this",
"service",
"."
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/template.go#L327-L343 | train |
pseudomuto/protoc-gen-doc | template.go | MethodsWithOption | func (s Service) MethodsWithOption(optionName string) []*ServiceMethod {
methods := make([]*ServiceMethod, 0, len(s.Methods))
for _, method := range s.Methods {
if _, ok := method.Options[optionName]; ok {
methods = append(methods, method)
}
}
if len(methods) > 0 {
return methods
}
return nil
} | go | func (s Service) MethodsWithOption(optionName string) []*ServiceMethod {
methods := make([]*ServiceMethod, 0, len(s.Methods))
for _, method := range s.Methods {
if _, ok := method.Options[optionName]; ok {
methods = append(methods, method)
}
}
if len(methods) > 0 {
return methods
}
return nil
} | [
"func",
"(",
"s",
"Service",
")",
"MethodsWithOption",
"(",
"optionName",
"string",
")",
"[",
"]",
"*",
"ServiceMethod",
"{",
"methods",
":=",
"make",
"(",
"[",
"]",
"*",
"ServiceMethod",
",",
"0",
",",
"len",
"(",
"s",
".",
"Methods",
")",
")",
"\n"... | // MethodsWithOption returns all methods that have the given option set.
// If no single method has the option set, this returns nil. | [
"MethodsWithOption",
"returns",
"all",
"methods",
"that",
"have",
"the",
"given",
"option",
"set",
".",
"If",
"no",
"single",
"method",
"has",
"the",
"option",
"set",
"this",
"returns",
"nil",
"."
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/template.go#L347-L358 | train |
pseudomuto/protoc-gen-doc | plugin.go | Generate | func (p *Plugin) Generate(r *plugin_go.CodeGeneratorRequest) (*plugin_go.CodeGeneratorResponse, error) {
options, err := ParseOptions(r)
if err != nil {
return nil, err
}
result := excludeUnwantedProtos(protokit.ParseCodeGenRequest(r), options.ExcludePatterns)
template := NewTemplate(result)
customTemplate := ""
if options.TemplateFile != "" {
data, err := ioutil.ReadFile(options.TemplateFile)
if err != nil {
return nil, err
}
customTemplate = string(data)
}
output, err := RenderTemplate(options.Type, template, customTemplate)
if err != nil {
return nil, err
}
resp := new(plugin_go.CodeGeneratorResponse)
resp.File = append(resp.File, &plugin_go.CodeGeneratorResponse_File{
Name: proto.String(options.OutputFile),
Content: proto.String(string(output)),
})
return resp, nil
} | go | func (p *Plugin) Generate(r *plugin_go.CodeGeneratorRequest) (*plugin_go.CodeGeneratorResponse, error) {
options, err := ParseOptions(r)
if err != nil {
return nil, err
}
result := excludeUnwantedProtos(protokit.ParseCodeGenRequest(r), options.ExcludePatterns)
template := NewTemplate(result)
customTemplate := ""
if options.TemplateFile != "" {
data, err := ioutil.ReadFile(options.TemplateFile)
if err != nil {
return nil, err
}
customTemplate = string(data)
}
output, err := RenderTemplate(options.Type, template, customTemplate)
if err != nil {
return nil, err
}
resp := new(plugin_go.CodeGeneratorResponse)
resp.File = append(resp.File, &plugin_go.CodeGeneratorResponse_File{
Name: proto.String(options.OutputFile),
Content: proto.String(string(output)),
})
return resp, nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"Generate",
"(",
"r",
"*",
"plugin_go",
".",
"CodeGeneratorRequest",
")",
"(",
"*",
"plugin_go",
".",
"CodeGeneratorResponse",
",",
"error",
")",
"{",
"options",
",",
"err",
":=",
"ParseOptions",
"(",
"r",
")",
"\n",... | // Generate compiles the documentation and generates the CodeGeneratorResponse to send back to protoc. It does this
// by rendering a template based on the options parsed from the CodeGeneratorRequest. | [
"Generate",
"compiles",
"the",
"documentation",
"and",
"generates",
"the",
"CodeGeneratorResponse",
"to",
"send",
"back",
"to",
"protoc",
".",
"It",
"does",
"this",
"by",
"rendering",
"a",
"template",
"based",
"on",
"the",
"options",
"parsed",
"from",
"the",
"... | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/plugin.go#L29-L61 | train |
pseudomuto/protoc-gen-doc | extensions/extensions.go | Transform | func Transform(extensions map[string]interface{}) map[string]interface{} {
if extensions == nil {
return nil
}
out := make(map[string]interface{}, len(extensions))
for name, payload := range extensions {
transform, ok := transformers[name]
if !ok {
// No transformer registered, skip.
continue
}
transformedPayload := transform(payload)
if transformedPayload == nil {
// Transformer returned nothing, skip.
continue
}
out[name] = transformedPayload
}
return out
} | go | func Transform(extensions map[string]interface{}) map[string]interface{} {
if extensions == nil {
return nil
}
out := make(map[string]interface{}, len(extensions))
for name, payload := range extensions {
transform, ok := transformers[name]
if !ok {
// No transformer registered, skip.
continue
}
transformedPayload := transform(payload)
if transformedPayload == nil {
// Transformer returned nothing, skip.
continue
}
out[name] = transformedPayload
}
return out
} | [
"func",
"Transform",
"(",
"extensions",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"if",
"extensions",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"out",
":=",
"make",
"(",
... | // Transform the extensions using the registered transformers. | [
"Transform",
"the",
"extensions",
"using",
"the",
"registered",
"transformers",
"."
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/extensions/extensions.go#L16-L35 | train |
pseudomuto/protoc-gen-doc | extensions/lyft_validate/lyft_validate.go | Rules | func (v ValidateExtension) Rules() []ValidateRule {
if v.FieldRules == nil {
return nil
}
if v.rules == nil {
v.rules = flattenRules("", reflect.ValueOf(v.FieldRules))
}
return v.rules
} | go | func (v ValidateExtension) Rules() []ValidateRule {
if v.FieldRules == nil {
return nil
}
if v.rules == nil {
v.rules = flattenRules("", reflect.ValueOf(v.FieldRules))
}
return v.rules
} | [
"func",
"(",
"v",
"ValidateExtension",
")",
"Rules",
"(",
")",
"[",
"]",
"ValidateRule",
"{",
"if",
"v",
".",
"FieldRules",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"v",
".",
"rules",
"==",
"nil",
"{",
"v",
".",
"rules",
"=",
"fl... | // Rules returns the set of rules for this extension. | [
"Rules",
"returns",
"the",
"set",
"of",
"rules",
"for",
"this",
"extension",
"."
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/extensions/lyft_validate/lyft_validate.go#L28-L36 | train |
pseudomuto/protoc-gen-doc | cmd/protoc-gen-doc/flags.go | PrintHelp | func (f *Flags) PrintHelp() {
fmt.Fprintf(f.writer, "Usage of %s:\n", f.appName)
fmt.Fprintf(f.writer, "%s\n", helpMessage)
fmt.Fprintf(f.writer, "FLAGS\n")
f.flagSet.PrintDefaults()
} | go | func (f *Flags) PrintHelp() {
fmt.Fprintf(f.writer, "Usage of %s:\n", f.appName)
fmt.Fprintf(f.writer, "%s\n", helpMessage)
fmt.Fprintf(f.writer, "FLAGS\n")
f.flagSet.PrintDefaults()
} | [
"func",
"(",
"f",
"*",
"Flags",
")",
"PrintHelp",
"(",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"f",
".",
"writer",
",",
"\"",
"\\n",
"\"",
",",
"f",
".",
"appName",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"f",
".",
"writer",
",",
"\"",
"\\n",
"\... | // PrintHelp prints the usage string including all flags to the `io.Writer` that was supplied to the `Flags` object. | [
"PrintHelp",
"prints",
"the",
"usage",
"string",
"including",
"all",
"flags",
"to",
"the",
"io",
".",
"Writer",
"that",
"was",
"supplied",
"to",
"the",
"Flags",
"object",
"."
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/cmd/protoc-gen-doc/flags.go#L68-L73 | train |
pseudomuto/protoc-gen-doc | cmd/protoc-gen-doc/flags.go | PrintVersion | func (f *Flags) PrintVersion() {
fmt.Fprintf(f.writer, "%s version %s\n", f.appName, Version())
} | go | func (f *Flags) PrintVersion() {
fmt.Fprintf(f.writer, "%s version %s\n", f.appName, Version())
} | [
"func",
"(",
"f",
"*",
"Flags",
")",
"PrintVersion",
"(",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"f",
".",
"writer",
",",
"\"",
"\\n",
"\"",
",",
"f",
".",
"appName",
",",
"Version",
"(",
")",
")",
"\n",
"}"
] | // PrintVersion prints the version string to the `io.Writer` that was supplied to the `Flags` object. | [
"PrintVersion",
"prints",
"the",
"version",
"string",
"to",
"the",
"io",
".",
"Writer",
"that",
"was",
"supplied",
"to",
"the",
"Flags",
"object",
"."
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/cmd/protoc-gen-doc/flags.go#L76-L78 | train |
pseudomuto/protoc-gen-doc | extensions/validator_field/validator_field.go | Rules | func (v ValidatorExtension) Rules() []ValidatorRule {
if v.FieldValidator == nil {
return nil
}
if v.rules != nil {
return v.rules
}
vv := reflect.ValueOf(*v.FieldValidator)
vt := vv.Type()
for i := 0; i < vt.NumField(); i++ {
tag, ok := vt.Field(i).Tag.Lookup("protobuf")
if !ok {
continue
}
for _, opt := range strings.Split(tag, ",") {
if strings.HasPrefix(opt, "name=") {
tag = strings.TrimPrefix(opt, "name=")
break
}
}
value := vv.Field(i)
if value.IsNil() {
continue
}
value = reflect.Indirect(value)
v.rules = append(v.rules, ValidatorRule{Name: tag, Value: value.Interface()})
}
return v.rules
} | go | func (v ValidatorExtension) Rules() []ValidatorRule {
if v.FieldValidator == nil {
return nil
}
if v.rules != nil {
return v.rules
}
vv := reflect.ValueOf(*v.FieldValidator)
vt := vv.Type()
for i := 0; i < vt.NumField(); i++ {
tag, ok := vt.Field(i).Tag.Lookup("protobuf")
if !ok {
continue
}
for _, opt := range strings.Split(tag, ",") {
if strings.HasPrefix(opt, "name=") {
tag = strings.TrimPrefix(opt, "name=")
break
}
}
value := vv.Field(i)
if value.IsNil() {
continue
}
value = reflect.Indirect(value)
v.rules = append(v.rules, ValidatorRule{Name: tag, Value: value.Interface()})
}
return v.rules
} | [
"func",
"(",
"v",
"ValidatorExtension",
")",
"Rules",
"(",
")",
"[",
"]",
"ValidatorRule",
"{",
"if",
"v",
".",
"FieldValidator",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"v",
".",
"rules",
"!=",
"nil",
"{",
"return",
"v",
".",
"ru... | // Rules returns all active rules | [
"Rules",
"returns",
"all",
"active",
"rules"
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/extensions/validator_field/validator_field.go#L45-L73 | train |
pseudomuto/protoc-gen-doc | cmd/protoc-gen-doc/main.go | HandleFlags | func HandleFlags(f *Flags) bool {
if !f.HasMatch() {
return false
}
if f.ShowHelp() {
f.PrintHelp()
}
if f.ShowVersion() {
f.PrintVersion()
}
return true
} | go | func HandleFlags(f *Flags) bool {
if !f.HasMatch() {
return false
}
if f.ShowHelp() {
f.PrintHelp()
}
if f.ShowVersion() {
f.PrintVersion()
}
return true
} | [
"func",
"HandleFlags",
"(",
"f",
"*",
"Flags",
")",
"bool",
"{",
"if",
"!",
"f",
".",
"HasMatch",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"f",
".",
"ShowHelp",
"(",
")",
"{",
"f",
".",
"PrintHelp",
"(",
")",
"\n",
"}",
"\n\n"... | // HandleFlags checks if there's a match and returns true if it was "handled" | [
"HandleFlags",
"checks",
"if",
"there",
"s",
"a",
"match",
"and",
"returns",
"true",
"if",
"it",
"was",
"handled"
] | f824a8908ce33f213b2dba1bf7be83384c5c51e8 | https://github.com/pseudomuto/protoc-gen-doc/blob/f824a8908ce33f213b2dba1bf7be83384c5c51e8/cmd/protoc-gen-doc/main.go#L39-L53 | train |
pressly/sup | ssh.go | initAuthMethod | func initAuthMethod() {
var signers []ssh.Signer
// If there's a running SSH Agent, try to use its Private keys.
sock, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err == nil {
agent := agent.NewClient(sock)
signers, _ = agent.Signers()
}
// Try to read user's SSH private keys form the standard paths.
files, _ := filepath.Glob(os.Getenv("HOME") + "/.ssh/id_*")
for _, file := range files {
if strings.HasSuffix(file, ".pub") {
continue // Skip public keys.
}
data, err := ioutil.ReadFile(file)
if err != nil {
continue
}
signer, err := ssh.ParsePrivateKey(data)
if err != nil {
continue
}
signers = append(signers, signer)
}
authMethod = ssh.PublicKeys(signers...)
} | go | func initAuthMethod() {
var signers []ssh.Signer
// If there's a running SSH Agent, try to use its Private keys.
sock, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err == nil {
agent := agent.NewClient(sock)
signers, _ = agent.Signers()
}
// Try to read user's SSH private keys form the standard paths.
files, _ := filepath.Glob(os.Getenv("HOME") + "/.ssh/id_*")
for _, file := range files {
if strings.HasSuffix(file, ".pub") {
continue // Skip public keys.
}
data, err := ioutil.ReadFile(file)
if err != nil {
continue
}
signer, err := ssh.ParsePrivateKey(data)
if err != nil {
continue
}
signers = append(signers, signer)
}
authMethod = ssh.PublicKeys(signers...)
} | [
"func",
"initAuthMethod",
"(",
")",
"{",
"var",
"signers",
"[",
"]",
"ssh",
".",
"Signer",
"\n\n",
"// If there's a running SSH Agent, try to use its Private keys.",
"sock",
",",
"err",
":=",
"net",
".",
"Dial",
"(",
"\"",
"\"",
",",
"os",
".",
"Getenv",
"(",
... | // initAuthMethod initiates SSH authentication method. | [
"initAuthMethod",
"initiates",
"SSH",
"authentication",
"method",
"."
] | be6dff41589b713547415b72660885dd7a045f8f | https://github.com/pressly/sup/blob/be6dff41589b713547415b72660885dd7a045f8f/ssh.go#L83-L111 | train |
pressly/sup | ssh.go | Run | func (c *SSHClient) Run(task *Task) error {
if c.running {
return fmt.Errorf("Session already running")
}
if c.sessOpened {
return fmt.Errorf("Session already connected")
}
sess, err := c.conn.NewSession()
if err != nil {
return err
}
c.remoteStdin, err = sess.StdinPipe()
if err != nil {
return err
}
c.remoteStdout, err = sess.StdoutPipe()
if err != nil {
return err
}
c.remoteStderr, err = sess.StderrPipe()
if err != nil {
return err
}
if task.TTY {
// Set up terminal modes
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
// Request pseudo terminal
if err := sess.RequestPty("xterm", 80, 40, modes); err != nil {
return ErrTask{task, fmt.Sprintf("request for pseudo terminal failed: %s", err)}
}
}
// Start the remote command.
if err := sess.Start(c.env + task.Run); err != nil {
return ErrTask{task, err.Error()}
}
c.sess = sess
c.sessOpened = true
c.running = true
return nil
} | go | func (c *SSHClient) Run(task *Task) error {
if c.running {
return fmt.Errorf("Session already running")
}
if c.sessOpened {
return fmt.Errorf("Session already connected")
}
sess, err := c.conn.NewSession()
if err != nil {
return err
}
c.remoteStdin, err = sess.StdinPipe()
if err != nil {
return err
}
c.remoteStdout, err = sess.StdoutPipe()
if err != nil {
return err
}
c.remoteStderr, err = sess.StderrPipe()
if err != nil {
return err
}
if task.TTY {
// Set up terminal modes
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
// Request pseudo terminal
if err := sess.RequestPty("xterm", 80, 40, modes); err != nil {
return ErrTask{task, fmt.Sprintf("request for pseudo terminal failed: %s", err)}
}
}
// Start the remote command.
if err := sess.Start(c.env + task.Run); err != nil {
return ErrTask{task, err.Error()}
}
c.sess = sess
c.sessOpened = true
c.running = true
return nil
} | [
"func",
"(",
"c",
"*",
"SSHClient",
")",
"Run",
"(",
"task",
"*",
"Task",
")",
"error",
"{",
"if",
"c",
".",
"running",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"c",
".",
"sessOpened",
"{",
"return",
"fm... | // Run runs the task.Run command remotely on c.host. | [
"Run",
"runs",
"the",
"task",
".",
"Run",
"command",
"remotely",
"on",
"c",
".",
"host",
"."
] | be6dff41589b713547415b72660885dd7a045f8f | https://github.com/pressly/sup/blob/be6dff41589b713547415b72660885dd7a045f8f/ssh.go#L154-L204 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.