repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
sendgrid/sendgrid-go | sendgrid.go | requestNew | func requestNew(options options) rest.Request {
if options.Host == "" {
options.Host = "https://api.sendgrid.com"
}
requestHeaders := map[string]string{
"Authorization": "Bearer " + options.Key,
"User-Agent": "sendgrid/" + Version + ";go",
"Accept": "application/json",
}
if len(options.Subuser) != 0 {
requestHeaders["On-Behalf-Of"] = options.Subuser
}
return rest.Request{
BaseURL: options.baseURL(),
Headers: requestHeaders,
}
} | go | func requestNew(options options) rest.Request {
if options.Host == "" {
options.Host = "https://api.sendgrid.com"
}
requestHeaders := map[string]string{
"Authorization": "Bearer " + options.Key,
"User-Agent": "sendgrid/" + Version + ";go",
"Accept": "application/json",
}
if len(options.Subuser) != 0 {
requestHeaders["On-Behalf-Of"] = options.Subuser
}
return rest.Request{
BaseURL: options.baseURL(),
Headers: requestHeaders,
}
} | [
"func",
"requestNew",
"(",
"options",
"options",
")",
"rest",
".",
"Request",
"{",
"if",
"options",
".",
"Host",
"==",
"\"\"",
"{",
"options",
".",
"Host",
"=",
"\"https://api.sendgrid.com\"",
"\n",
"}",
"\n",
"requestHeaders",
":=",
"map",
"[",
"string",
... | // requestNew create Request
// @return [Request] a default request object | [
"requestNew",
"create",
"Request"
] | df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5 | https://github.com/sendgrid/sendgrid-go/blob/df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5/sendgrid.go#L53-L72 | train |
sendgrid/sendgrid-go | sendgrid.go | Send | func (cl *Client) Send(email *mail.SGMailV3) (*rest.Response, error) {
cl.Body = mail.GetRequestBody(email)
return MakeRequest(cl.Request)
} | go | func (cl *Client) Send(email *mail.SGMailV3) (*rest.Response, error) {
cl.Body = mail.GetRequestBody(email)
return MakeRequest(cl.Request)
} | [
"func",
"(",
"cl",
"*",
"Client",
")",
"Send",
"(",
"email",
"*",
"mail",
".",
"SGMailV3",
")",
"(",
"*",
"rest",
".",
"Response",
",",
"error",
")",
"{",
"cl",
".",
"Body",
"=",
"mail",
".",
"GetRequestBody",
"(",
"email",
")",
"\n",
"return",
"... | // Send sends an email through SendGrid | [
"Send",
"sends",
"an",
"email",
"through",
"SendGrid"
] | df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5 | https://github.com/sendgrid/sendgrid-go/blob/df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5/sendgrid.go#L75-L78 | train |
sendgrid/sendgrid-go | sendgrid.go | NewSendClient | func NewSendClient(key string) *Client {
request := GetRequest(key, "/v3/mail/send", "")
request.Method = "POST"
return &Client{request}
} | go | func NewSendClient(key string) *Client {
request := GetRequest(key, "/v3/mail/send", "")
request.Method = "POST"
return &Client{request}
} | [
"func",
"NewSendClient",
"(",
"key",
"string",
")",
"*",
"Client",
"{",
"request",
":=",
"GetRequest",
"(",
"key",
",",
"\"/v3/mail/send\"",
",",
"\"\"",
")",
"\n",
"request",
".",
"Method",
"=",
"\"POST\"",
"\n",
"return",
"&",
"Client",
"{",
"request",
... | // NewSendClient constructs a new SendGrid client given an API key | [
"NewSendClient",
"constructs",
"a",
"new",
"SendGrid",
"client",
"given",
"an",
"API",
"key"
] | df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5 | https://github.com/sendgrid/sendgrid-go/blob/df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5/sendgrid.go#L81-L85 | train |
sendgrid/sendgrid-go | sendgrid.go | NewSendClientSubuser | func NewSendClientSubuser(key, subuser string) *Client {
request := GetRequestSubuser(key, "/v3/mail/send", "", subuser)
request.Method = "POST"
return &Client{request}
} | go | func NewSendClientSubuser(key, subuser string) *Client {
request := GetRequestSubuser(key, "/v3/mail/send", "", subuser)
request.Method = "POST"
return &Client{request}
} | [
"func",
"NewSendClientSubuser",
"(",
"key",
",",
"subuser",
"string",
")",
"*",
"Client",
"{",
"request",
":=",
"GetRequestSubuser",
"(",
"key",
",",
"\"/v3/mail/send\"",
",",
"\"\"",
",",
"subuser",
")",
"\n",
"request",
".",
"Method",
"=",
"\"POST\"",
"\n"... | // GetRequestSubuser like NewSendClient but with On-Behalf of Subuser
// @return [Client] | [
"GetRequestSubuser",
"like",
"NewSendClient",
"but",
"with",
"On",
"-",
"Behalf",
"of",
"Subuser"
] | df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5 | https://github.com/sendgrid/sendgrid-go/blob/df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5/sendgrid.go#L89-L93 | train |
sendgrid/sendgrid-go | sendgrid.go | MakeRequest | func MakeRequest(request rest.Request) (*rest.Response, error) {
return DefaultClient.Send(request)
} | go | func MakeRequest(request rest.Request) (*rest.Response, error) {
return DefaultClient.Send(request)
} | [
"func",
"MakeRequest",
"(",
"request",
"rest",
".",
"Request",
")",
"(",
"*",
"rest",
".",
"Response",
",",
"error",
")",
"{",
"return",
"DefaultClient",
".",
"Send",
"(",
"request",
")",
"\n",
"}"
] | // MakeRequest attempts a SendGrid request synchronously. | [
"MakeRequest",
"attempts",
"a",
"SendGrid",
"request",
"synchronously",
"."
] | df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5 | https://github.com/sendgrid/sendgrid-go/blob/df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5/sendgrid.go#L106-L108 | train |
sendgrid/sendgrid-go | sendgrid.go | MakeRequestRetry | func MakeRequestRetry(request rest.Request) (*rest.Response, error) {
retry := 0
var response *rest.Response
var err error
for {
response, err = MakeRequest(request)
if err != nil {
return nil, err
}
if response.StatusCode != http.StatusTooManyRequests {
return response, nil
}
if retry > rateLimitRetry {
return nil, errors.New("Rate limit retry exceeded")
}
retry++
resetTime := time.Now().Add(rateLimitSleep * time.Millisecond)
reset, ok := response.Headers["X-RateLimit-Reset"]
if ok && len(reset) > 0 {
t, err := strconv.Atoi(reset[0])
if err == nil {
resetTime = time.Unix(int64(t), 0)
}
}
time.Sleep(resetTime.Sub(time.Now()))
}
} | go | func MakeRequestRetry(request rest.Request) (*rest.Response, error) {
retry := 0
var response *rest.Response
var err error
for {
response, err = MakeRequest(request)
if err != nil {
return nil, err
}
if response.StatusCode != http.StatusTooManyRequests {
return response, nil
}
if retry > rateLimitRetry {
return nil, errors.New("Rate limit retry exceeded")
}
retry++
resetTime := time.Now().Add(rateLimitSleep * time.Millisecond)
reset, ok := response.Headers["X-RateLimit-Reset"]
if ok && len(reset) > 0 {
t, err := strconv.Atoi(reset[0])
if err == nil {
resetTime = time.Unix(int64(t), 0)
}
}
time.Sleep(resetTime.Sub(time.Now()))
}
} | [
"func",
"MakeRequestRetry",
"(",
"request",
"rest",
".",
"Request",
")",
"(",
"*",
"rest",
".",
"Response",
",",
"error",
")",
"{",
"retry",
":=",
"0",
"\n",
"var",
"response",
"*",
"rest",
".",
"Response",
"\n",
"var",
"err",
"error",
"\n",
"for",
"... | // MakeRequestRetry a synchronous request, but retry in the event of a rate
// limited response. | [
"MakeRequestRetry",
"a",
"synchronous",
"request",
"but",
"retry",
"in",
"the",
"event",
"of",
"a",
"rate",
"limited",
"response",
"."
] | df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5 | https://github.com/sendgrid/sendgrid-go/blob/df2105ec04e32aff6b9e9a2fd1ca8e5c16a836c5/sendgrid.go#L112-L143 | train |
golang/tour | local.go | isRoot | func isRoot(path string) bool {
_, err := os.Stat(filepath.Join(path, "content", "welcome.article"))
if err == nil {
_, err = os.Stat(filepath.Join(path, "template", "index.tmpl"))
}
return err == nil
} | go | func isRoot(path string) bool {
_, err := os.Stat(filepath.Join(path, "content", "welcome.article"))
if err == nil {
_, err = os.Stat(filepath.Join(path, "template", "index.tmpl"))
}
return err == nil
} | [
"func",
"isRoot",
"(",
"path",
"string",
")",
"bool",
"{",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"filepath",
".",
"Join",
"(",
"path",
",",
"\"content\"",
",",
"\"welcome.article\"",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"_",
",",... | // isRoot reports whether path is the root directory of the tour tree.
// To be the root, it must have content and template subdirectories. | [
"isRoot",
"reports",
"whether",
"path",
"is",
"the",
"root",
"directory",
"of",
"the",
"tour",
"tree",
".",
"To",
"be",
"the",
"root",
"it",
"must",
"have",
"content",
"and",
"template",
"subdirectories",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/local.go#L50-L56 | train |
golang/tour | local.go | registerStatic | func registerStatic(root string) {
// Keep these static file handlers in sync with app.yaml.
http.Handle("/favicon.ico", http.FileServer(http.Dir(filepath.Join(root, "static", "img"))))
static := http.FileServer(http.Dir(root))
http.Handle("/content/img/", static)
http.Handle("/static/", static)
} | go | func registerStatic(root string) {
// Keep these static file handlers in sync with app.yaml.
http.Handle("/favicon.ico", http.FileServer(http.Dir(filepath.Join(root, "static", "img"))))
static := http.FileServer(http.Dir(root))
http.Handle("/content/img/", static)
http.Handle("/static/", static)
} | [
"func",
"registerStatic",
"(",
"root",
"string",
")",
"{",
"http",
".",
"Handle",
"(",
"\"/favicon.ico\"",
",",
"http",
".",
"FileServer",
"(",
"http",
".",
"Dir",
"(",
"filepath",
".",
"Join",
"(",
"root",
",",
"\"static\"",
",",
"\"img\"",
")",
")",
... | // registerStatic registers handlers to serve static content
// from the directory root. | [
"registerStatic",
"registers",
"handlers",
"to",
"serve",
"static",
"content",
"from",
"the",
"directory",
"root",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/local.go#L128-L134 | train |
golang/tour | local.go | rootHandler | func rootHandler(w http.ResponseWriter, r *http.Request) {
if err := renderUI(w); err != nil {
log.Println(err)
}
} | go | func rootHandler(w http.ResponseWriter, r *http.Request) {
if err := renderUI(w); err != nil {
log.Println(err)
}
} | [
"func",
"rootHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"err",
":=",
"renderUI",
"(",
"w",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"err",
")",
"\n",
"}",
"\n",
... | // rootHandler returns a handler for all the requests except the ones for lessons. | [
"rootHandler",
"returns",
"a",
"handler",
"for",
"all",
"the",
"requests",
"except",
"the",
"ones",
"for",
"lessons",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/local.go#L137-L141 | train |
golang/tour | local.go | lessonHandler | func lessonHandler(w http.ResponseWriter, r *http.Request) {
lesson := strings.TrimPrefix(r.URL.Path, "/lesson/")
if err := writeLesson(lesson, w); err != nil {
if err == lessonNotFound {
http.NotFound(w, r)
} else {
log.Println(err)
}
}
} | go | func lessonHandler(w http.ResponseWriter, r *http.Request) {
lesson := strings.TrimPrefix(r.URL.Path, "/lesson/")
if err := writeLesson(lesson, w); err != nil {
if err == lessonNotFound {
http.NotFound(w, r)
} else {
log.Println(err)
}
}
} | [
"func",
"lessonHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"lesson",
":=",
"strings",
".",
"TrimPrefix",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"\"/lesson/\"",
")",
"\n",
"if",
"err",
":=",
"wr... | // lessonHandler handler the HTTP requests for lessons. | [
"lessonHandler",
"handler",
"the",
"HTTP",
"requests",
"for",
"lessons",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/local.go#L144-L153 | train |
golang/tour | local.go | waitServer | func waitServer(url string) bool {
tries := 20
for tries > 0 {
resp, err := http.Get(url)
if err == nil {
resp.Body.Close()
return true
}
time.Sleep(100 * time.Millisecond)
tries--
}
return false
} | go | func waitServer(url string) bool {
tries := 20
for tries > 0 {
resp, err := http.Get(url)
if err == nil {
resp.Body.Close()
return true
}
time.Sleep(100 * time.Millisecond)
tries--
}
return false
} | [
"func",
"waitServer",
"(",
"url",
"string",
")",
"bool",
"{",
"tries",
":=",
"20",
"\n",
"for",
"tries",
">",
"0",
"{",
"resp",
",",
"err",
":=",
"http",
".",
"Get",
"(",
"url",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"resp",
".",
"Body",
"."... | // waitServer waits some time for the http Server to start
// serving url. The return value reports whether it starts. | [
"waitServer",
"waits",
"some",
"time",
"for",
"the",
"http",
"Server",
"to",
"start",
"serving",
"url",
".",
"The",
"return",
"value",
"reports",
"whether",
"it",
"starts",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/local.go#L191-L203 | train |
golang/tour | local.go | startBrowser | func startBrowser(url string) bool {
// try to start the browser
var args []string
switch runtime.GOOS {
case "darwin":
args = []string{"open"}
case "windows":
args = []string{"cmd", "/c", "start"}
default:
args = []string{"xdg-open"}
}
cmd := exec.Command(args[0], append(args[1:], url)...)
return cmd.Start() == nil
} | go | func startBrowser(url string) bool {
// try to start the browser
var args []string
switch runtime.GOOS {
case "darwin":
args = []string{"open"}
case "windows":
args = []string{"cmd", "/c", "start"}
default:
args = []string{"xdg-open"}
}
cmd := exec.Command(args[0], append(args[1:], url)...)
return cmd.Start() == nil
} | [
"func",
"startBrowser",
"(",
"url",
"string",
")",
"bool",
"{",
"var",
"args",
"[",
"]",
"string",
"\n",
"switch",
"runtime",
".",
"GOOS",
"{",
"case",
"\"darwin\"",
":",
"args",
"=",
"[",
"]",
"string",
"{",
"\"open\"",
"}",
"\n",
"case",
"\"windows\"... | // startBrowser tries to open the URL in a browser, and returns
// whether it succeed. | [
"startBrowser",
"tries",
"to",
"open",
"the",
"URL",
"in",
"a",
"browser",
"and",
"returns",
"whether",
"it",
"succeed",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/local.go#L207-L220 | train |
golang/tour | appengine.go | hstsHandler | func hstsHandler(fn http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Strict-Transport-Security", "max-age=31536000; preload")
fn(w, r)
})
} | go | func hstsHandler(fn http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Strict-Transport-Security", "max-age=31536000; preload")
fn(w, r)
})
} | [
"func",
"hstsHandler",
"(",
"fn",
"http",
".",
"HandlerFunc",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"He... | // hstsHandler wraps an http.HandlerFunc such that it sets the HSTS header. | [
"hstsHandler",
"wraps",
"an",
"http",
".",
"HandlerFunc",
"such",
"that",
"it",
"sets",
"the",
"HSTS",
"header",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/appengine.go#L83-L88 | train |
golang/tour | tree/tree.go | New | func New(k int) *Tree {
var t *Tree
for _, v := range rand.Perm(10) {
t = insert(t, (1+v)*k)
}
return t
} | go | func New(k int) *Tree {
var t *Tree
for _, v := range rand.Perm(10) {
t = insert(t, (1+v)*k)
}
return t
} | [
"func",
"New",
"(",
"k",
"int",
")",
"*",
"Tree",
"{",
"var",
"t",
"*",
"Tree",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"rand",
".",
"Perm",
"(",
"10",
")",
"{",
"t",
"=",
"insert",
"(",
"t",
",",
"(",
"1",
"+",
"v",
")",
"*",
"k",
"... | // New returns a new, random binary tree holding the values k, 2k, ..., 10k. | [
"New",
"returns",
"a",
"new",
"random",
"binary",
"tree",
"holding",
"the",
"values",
"k",
"2k",
"...",
"10k",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/tree/tree.go#L20-L26 | train |
golang/tour | solutions/fib.go | fibonacci | func fibonacci() func() int {
f, g := 1, 0
return func() int {
f, g = g, f+g
return f
}
} | go | func fibonacci() func() int {
f, g := 1, 0
return func() int {
f, g = g, f+g
return f
}
} | [
"func",
"fibonacci",
"(",
")",
"func",
"(",
")",
"int",
"{",
"f",
",",
"g",
":=",
"1",
",",
"0",
"\n",
"return",
"func",
"(",
")",
"int",
"{",
"f",
",",
"g",
"=",
"g",
",",
"f",
"+",
"g",
"\n",
"return",
"f",
"\n",
"}",
"\n",
"}"
] | // fibonacci is a function that returns
// a function that returns an int. | [
"fibonacci",
"is",
"a",
"function",
"that",
"returns",
"a",
"function",
"that",
"returns",
"an",
"int",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/solutions/fib.go#L13-L19 | train |
golang/tour | solutions/binarytrees_quit.go | Walk | func Walk(t *tree.Tree, ch, quit chan int) {
walkImpl(t, ch, quit)
close(ch)
} | go | func Walk(t *tree.Tree, ch, quit chan int) {
walkImpl(t, ch, quit)
close(ch)
} | [
"func",
"Walk",
"(",
"t",
"*",
"tree",
".",
"Tree",
",",
"ch",
",",
"quit",
"chan",
"int",
")",
"{",
"walkImpl",
"(",
"t",
",",
"ch",
",",
"quit",
")",
"\n",
"close",
"(",
"ch",
")",
"\n",
"}"
] | // Walk walks the tree t sending all values
// from the tree to the channel ch. | [
"Walk",
"walks",
"the",
"tree",
"t",
"sending",
"all",
"values",
"from",
"the",
"tree",
"to",
"the",
"channel",
"ch",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/solutions/binarytrees_quit.go#L31-L34 | train |
golang/tour | solutions/binarytrees_quit.go | Same | func Same(t1, t2 *tree.Tree) bool {
w1, w2 := make(chan int), make(chan int)
quit := make(chan int)
defer close(quit)
go Walk(t1, w1, quit)
go Walk(t2, w2, quit)
for {
v1, ok1 := <-w1
v2, ok2 := <-w2
if !ok1 || !ok2 {
return ok1 == ok2
}
if v1 != v2 {
return false
}
}
} | go | func Same(t1, t2 *tree.Tree) bool {
w1, w2 := make(chan int), make(chan int)
quit := make(chan int)
defer close(quit)
go Walk(t1, w1, quit)
go Walk(t2, w2, quit)
for {
v1, ok1 := <-w1
v2, ok2 := <-w2
if !ok1 || !ok2 {
return ok1 == ok2
}
if v1 != v2 {
return false
}
}
} | [
"func",
"Same",
"(",
"t1",
",",
"t2",
"*",
"tree",
".",
"Tree",
")",
"bool",
"{",
"w1",
",",
"w2",
":=",
"make",
"(",
"chan",
"int",
")",
",",
"make",
"(",
"chan",
"int",
")",
"\n",
"quit",
":=",
"make",
"(",
"chan",
"int",
")",
"\n",
"defer"... | // Same determines whether the trees
// t1 and t2 contain the same values. | [
"Same",
"determines",
"whether",
"the",
"trees",
"t1",
"and",
"t2",
"contain",
"the",
"same",
"values",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/solutions/binarytrees_quit.go#L38-L56 | train |
golang/tour | content/concurrency/mutex-counter.go | Inc | func (c *SafeCounter) Inc(key string) {
c.mux.Lock()
// Lock so only one goroutine at a time can access the map c.v.
c.v[key]++
c.mux.Unlock()
} | go | func (c *SafeCounter) Inc(key string) {
c.mux.Lock()
// Lock so only one goroutine at a time can access the map c.v.
c.v[key]++
c.mux.Unlock()
} | [
"func",
"(",
"c",
"*",
"SafeCounter",
")",
"Inc",
"(",
"key",
"string",
")",
"{",
"c",
".",
"mux",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"v",
"[",
"key",
"]",
"++",
"\n",
"c",
".",
"mux",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Inc increments the counter for the given key. | [
"Inc",
"increments",
"the",
"counter",
"for",
"the",
"given",
"key",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/content/concurrency/mutex-counter.go#L18-L23 | train |
golang/tour | content/concurrency/mutex-counter.go | Value | func (c *SafeCounter) Value(key string) int {
c.mux.Lock()
// Lock so only one goroutine at a time can access the map c.v.
defer c.mux.Unlock()
return c.v[key]
} | go | func (c *SafeCounter) Value(key string) int {
c.mux.Lock()
// Lock so only one goroutine at a time can access the map c.v.
defer c.mux.Unlock()
return c.v[key]
} | [
"func",
"(",
"c",
"*",
"SafeCounter",
")",
"Value",
"(",
"key",
"string",
")",
"int",
"{",
"c",
".",
"mux",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mux",
".",
"Unlock",
"(",
")",
"\n",
"return",
"c",
".",
"v",
"[",
"key",
"]",
"\n",
... | // Value returns the current value of the counter for the given key. | [
"Value",
"returns",
"the",
"current",
"value",
"of",
"the",
"counter",
"for",
"the",
"given",
"key",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/content/concurrency/mutex-counter.go#L26-L31 | train |
golang/tour | tour.go | initTour | func initTour(root, transport string) error {
// Make sure playground is enabled before rendering.
present.PlayEnabled = true
// Set up templates.
action := filepath.Join(root, "template", "action.tmpl")
tmpl, err := present.Template().ParseFiles(action)
if err != nil {
return fmt.Errorf("parse templates: %v", err)
}
// Init lessons.
contentPath := filepath.Join(root, "content")
if err := initLessons(tmpl, contentPath); err != nil {
return fmt.Errorf("init lessons: %v", err)
}
// Init UI
index := filepath.Join(root, "template", "index.tmpl")
ui, err := template.ParseFiles(index)
if err != nil {
return fmt.Errorf("parse index.tmpl: %v", err)
}
buf := new(bytes.Buffer)
data := struct {
SocketAddr string
Transport template.JS
}{socketAddr(), template.JS(transport)}
if err := ui.Execute(buf, data); err != nil {
return fmt.Errorf("render UI: %v", err)
}
uiContent = buf.Bytes()
return initScript(root)
} | go | func initTour(root, transport string) error {
// Make sure playground is enabled before rendering.
present.PlayEnabled = true
// Set up templates.
action := filepath.Join(root, "template", "action.tmpl")
tmpl, err := present.Template().ParseFiles(action)
if err != nil {
return fmt.Errorf("parse templates: %v", err)
}
// Init lessons.
contentPath := filepath.Join(root, "content")
if err := initLessons(tmpl, contentPath); err != nil {
return fmt.Errorf("init lessons: %v", err)
}
// Init UI
index := filepath.Join(root, "template", "index.tmpl")
ui, err := template.ParseFiles(index)
if err != nil {
return fmt.Errorf("parse index.tmpl: %v", err)
}
buf := new(bytes.Buffer)
data := struct {
SocketAddr string
Transport template.JS
}{socketAddr(), template.JS(transport)}
if err := ui.Execute(buf, data); err != nil {
return fmt.Errorf("render UI: %v", err)
}
uiContent = buf.Bytes()
return initScript(root)
} | [
"func",
"initTour",
"(",
"root",
",",
"transport",
"string",
")",
"error",
"{",
"present",
".",
"PlayEnabled",
"=",
"true",
"\n",
"action",
":=",
"filepath",
".",
"Join",
"(",
"root",
",",
"\"template\"",
",",
"\"action.tmpl\"",
")",
"\n",
"tmpl",
",",
"... | // initTour loads tour.article and the relevant HTML templates from the given
// tour root, and renders the template to the tourContent global variable. | [
"initTour",
"loads",
"tour",
".",
"article",
"and",
"the",
"relevant",
"HTML",
"templates",
"from",
"the",
"given",
"tour",
"root",
"and",
"renders",
"the",
"template",
"to",
"the",
"tourContent",
"global",
"variable",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/tour.go#L34-L70 | train |
golang/tour | tour.go | initLessons | func initLessons(tmpl *template.Template, content string) error {
dir, err := os.Open(content)
if err != nil {
return err
}
files, err := dir.Readdirnames(0)
if err != nil {
return err
}
for _, f := range files {
if filepath.Ext(f) != ".article" {
continue
}
content, err := parseLesson(tmpl, filepath.Join(content, f))
if err != nil {
return fmt.Errorf("parsing %v: %v", f, err)
}
name := strings.TrimSuffix(f, ".article")
lessons[name] = content
}
return nil
} | go | func initLessons(tmpl *template.Template, content string) error {
dir, err := os.Open(content)
if err != nil {
return err
}
files, err := dir.Readdirnames(0)
if err != nil {
return err
}
for _, f := range files {
if filepath.Ext(f) != ".article" {
continue
}
content, err := parseLesson(tmpl, filepath.Join(content, f))
if err != nil {
return fmt.Errorf("parsing %v: %v", f, err)
}
name := strings.TrimSuffix(f, ".article")
lessons[name] = content
}
return nil
} | [
"func",
"initLessons",
"(",
"tmpl",
"*",
"template",
".",
"Template",
",",
"content",
"string",
")",
"error",
"{",
"dir",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"content",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n... | // initLessonss finds all the lessons in the passed directory, renders them,
// using the given template and saves the content in the lessons map. | [
"initLessonss",
"finds",
"all",
"the",
"lessons",
"in",
"the",
"passed",
"directory",
"renders",
"them",
"using",
"the",
"given",
"template",
"and",
"saves",
"the",
"content",
"in",
"the",
"lessons",
"map",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/tour.go#L74-L95 | train |
golang/tour | tour.go | parseLesson | func parseLesson(tmpl *template.Template, path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
doc, err := present.Parse(prepContent(f), path, 0)
if err != nil {
return nil, err
}
lesson := Lesson{
doc.Title,
doc.Subtitle,
make([]Page, len(doc.Sections)),
}
for i, sec := range doc.Sections {
p := &lesson.Pages[i]
w := new(bytes.Buffer)
if err := sec.Render(w, tmpl); err != nil {
return nil, fmt.Errorf("render section: %v", err)
}
p.Title = sec.Title
p.Content = w.String()
codes := findPlayCode(sec)
p.Files = make([]File, len(codes))
for i, c := range codes {
f := &p.Files[i]
f.Name = c.FileName
f.Content = string(c.Raw)
hash := sha1.Sum(c.Raw)
f.Hash = base64.StdEncoding.EncodeToString(hash[:])
}
}
w := new(bytes.Buffer)
if err := json.NewEncoder(w).Encode(lesson); err != nil {
return nil, fmt.Errorf("encode lesson: %v", err)
}
return w.Bytes(), nil
} | go | func parseLesson(tmpl *template.Template, path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
doc, err := present.Parse(prepContent(f), path, 0)
if err != nil {
return nil, err
}
lesson := Lesson{
doc.Title,
doc.Subtitle,
make([]Page, len(doc.Sections)),
}
for i, sec := range doc.Sections {
p := &lesson.Pages[i]
w := new(bytes.Buffer)
if err := sec.Render(w, tmpl); err != nil {
return nil, fmt.Errorf("render section: %v", err)
}
p.Title = sec.Title
p.Content = w.String()
codes := findPlayCode(sec)
p.Files = make([]File, len(codes))
for i, c := range codes {
f := &p.Files[i]
f.Name = c.FileName
f.Content = string(c.Raw)
hash := sha1.Sum(c.Raw)
f.Hash = base64.StdEncoding.EncodeToString(hash[:])
}
}
w := new(bytes.Buffer)
if err := json.NewEncoder(w).Encode(lesson); err != nil {
return nil, fmt.Errorf("encode lesson: %v", err)
}
return w.Bytes(), nil
} | [
"func",
"parseLesson",
"(",
"tmpl",
"*",
"template",
".",
"Template",
",",
"path",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"r... | // parseLesson parses and returns a lesson content given its name and
// the template to render it. | [
"parseLesson",
"parses",
"and",
"returns",
"a",
"lesson",
"content",
"given",
"its",
"name",
"and",
"the",
"template",
"to",
"render",
"it",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/tour.go#L120-L161 | train |
golang/tour | tour.go | findPlayCode | func findPlayCode(e present.Elem) []*present.Code {
var r []*present.Code
switch v := e.(type) {
case present.Code:
if v.Play {
r = append(r, &v)
}
case present.Section:
for _, s := range v.Elem {
r = append(r, findPlayCode(s)...)
}
}
return r
} | go | func findPlayCode(e present.Elem) []*present.Code {
var r []*present.Code
switch v := e.(type) {
case present.Code:
if v.Play {
r = append(r, &v)
}
case present.Section:
for _, s := range v.Elem {
r = append(r, findPlayCode(s)...)
}
}
return r
} | [
"func",
"findPlayCode",
"(",
"e",
"present",
".",
"Elem",
")",
"[",
"]",
"*",
"present",
".",
"Code",
"{",
"var",
"r",
"[",
"]",
"*",
"present",
".",
"Code",
"\n",
"switch",
"v",
":=",
"e",
".",
"(",
"type",
")",
"{",
"case",
"present",
".",
"C... | // findPlayCode returns a slide with all the Code elements in the given
// Elem with Play set to true. | [
"findPlayCode",
"returns",
"a",
"slide",
"with",
"all",
"the",
"Code",
"elements",
"in",
"the",
"given",
"Elem",
"with",
"Play",
"set",
"to",
"true",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/tour.go#L165-L178 | train |
golang/tour | tour.go | writeLesson | func writeLesson(name string, w io.Writer) error {
if uiContent == nil {
panic("writeLesson called before successful initTour")
}
if len(name) == 0 {
return writeAllLessons(w)
}
l, ok := lessons[name]
if !ok {
return lessonNotFound
}
_, err := w.Write(l)
return err
} | go | func writeLesson(name string, w io.Writer) error {
if uiContent == nil {
panic("writeLesson called before successful initTour")
}
if len(name) == 0 {
return writeAllLessons(w)
}
l, ok := lessons[name]
if !ok {
return lessonNotFound
}
_, err := w.Write(l)
return err
} | [
"func",
"writeLesson",
"(",
"name",
"string",
",",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"if",
"uiContent",
"==",
"nil",
"{",
"panic",
"(",
"\"writeLesson called before successful initTour\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"name",
")",
"==... | // writeLesson writes the tour content to the provided Writer. | [
"writeLesson",
"writes",
"the",
"tour",
"content",
"to",
"the",
"provided",
"Writer",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/tour.go#L181-L194 | train |
golang/tour | tour.go | renderUI | func renderUI(w io.Writer) error {
if uiContent == nil {
panic("renderUI called before successful initTour")
}
_, err := w.Write(uiContent)
return err
} | go | func renderUI(w io.Writer) error {
if uiContent == nil {
panic("renderUI called before successful initTour")
}
_, err := w.Write(uiContent)
return err
} | [
"func",
"renderUI",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"if",
"uiContent",
"==",
"nil",
"{",
"panic",
"(",
"\"renderUI called before successful initTour\"",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"uiContent",
"... | // renderUI writes the tour UI to the provided Writer. | [
"renderUI",
"writes",
"the",
"tour",
"UI",
"to",
"the",
"provided",
"Writer",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/tour.go#L217-L223 | train |
golang/tour | tour.go | nocode | func nocode(s present.Section) bool {
for _, e := range s.Elem {
if c, ok := e.(present.Code); ok && c.Play {
return false
}
}
return true
} | go | func nocode(s present.Section) bool {
for _, e := range s.Elem {
if c, ok := e.(present.Code); ok && c.Play {
return false
}
}
return true
} | [
"func",
"nocode",
"(",
"s",
"present",
".",
"Section",
")",
"bool",
"{",
"for",
"_",
",",
"e",
":=",
"range",
"s",
".",
"Elem",
"{",
"if",
"c",
",",
"ok",
":=",
"e",
".",
"(",
"present",
".",
"Code",
")",
";",
"ok",
"&&",
"c",
".",
"Play",
... | // nocode returns true if the provided Section contains
// no Code elements with Play enabled. | [
"nocode",
"returns",
"true",
"if",
"the",
"provided",
"Section",
"contains",
"no",
"Code",
"elements",
"with",
"Play",
"enabled",
"."
] | db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77 | https://github.com/golang/tour/blob/db40fe78fefcfdeefb4ac4a94c72cfb20f40ee77/tour.go#L227-L234 | train |
kahing/goofys | internal/goofys.go | GetFullName | func (fs *Goofys) GetFullName(id fuseops.InodeID) *string {
fs.mu.Lock()
inode := fs.inodes[id]
fs.mu.Unlock()
if inode == nil {
return nil
}
return inode.FullName()
} | go | func (fs *Goofys) GetFullName(id fuseops.InodeID) *string {
fs.mu.Lock()
inode := fs.inodes[id]
fs.mu.Unlock()
if inode == nil {
return nil
}
return inode.FullName()
} | [
"func",
"(",
"fs",
"*",
"Goofys",
")",
"GetFullName",
"(",
"id",
"fuseops",
".",
"InodeID",
")",
"*",
"string",
"{",
"fs",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"inode",
":=",
"fs",
".",
"inodes",
"[",
"id",
"]",
"\n",
"fs",
".",
"mu",
".",
... | // GetFullName returns full name of the given inode | [
"GetFullName",
"returns",
"full",
"name",
"of",
"the",
"given",
"inode"
] | 224a69530a8fefa8f07e51582b928739127134f2 | https://github.com/kahing/goofys/blob/224a69530a8fefa8f07e51582b928739127134f2/internal/goofys.go#L1174-L1183 | train |
kahing/goofys | internal/flags.go | filterCategory | func filterCategory(flags []cli.Flag, category string) (ret []cli.Flag) {
for _, f := range flags {
if flagCategories[f.GetName()] == category {
ret = append(ret, f)
}
}
return
} | go | func filterCategory(flags []cli.Flag, category string) (ret []cli.Flag) {
for _, f := range flags {
if flagCategories[f.GetName()] == category {
ret = append(ret, f)
}
}
return
} | [
"func",
"filterCategory",
"(",
"flags",
"[",
"]",
"cli",
".",
"Flag",
",",
"category",
"string",
")",
"(",
"ret",
"[",
"]",
"cli",
".",
"Flag",
")",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"flags",
"{",
"if",
"flagCategories",
"[",
"f",
".",
"G... | // Set up custom help text for goofys; in particular the usage section. | [
"Set",
"up",
"custom",
"help",
"text",
"for",
"goofys",
";",
"in",
"particular",
"the",
"usage",
"section",
"."
] | 224a69530a8fefa8f07e51582b928739127134f2 | https://github.com/kahing/goofys/blob/224a69530a8fefa8f07e51582b928739127134f2/internal/flags.go#L35-L42 | train |
kahing/goofys | main.go | mount | func mount(
ctx context.Context,
bucketName string,
flags *FlagStorage) (fs *Goofys, mfs *fuse.MountedFileSystem, err error) {
// XXX really silly copy here! in goofys.Mount we will copy it
// back to FlagStorage. But I don't see a easier way to expose
// Config in the api package
var config goofys.Config
copier.Copy(&config, *flags)
return goofys.Mount(ctx, bucketName, &config)
} | go | func mount(
ctx context.Context,
bucketName string,
flags *FlagStorage) (fs *Goofys, mfs *fuse.MountedFileSystem, err error) {
// XXX really silly copy here! in goofys.Mount we will copy it
// back to FlagStorage. But I don't see a easier way to expose
// Config in the api package
var config goofys.Config
copier.Copy(&config, *flags)
return goofys.Mount(ctx, bucketName, &config)
} | [
"func",
"mount",
"(",
"ctx",
"context",
".",
"Context",
",",
"bucketName",
"string",
",",
"flags",
"*",
"FlagStorage",
")",
"(",
"fs",
"*",
"Goofys",
",",
"mfs",
"*",
"fuse",
".",
"MountedFileSystem",
",",
"err",
"error",
")",
"{",
"var",
"config",
"go... | // Mount the file system based on the supplied arguments, returning a
// fuse.MountedFileSystem that can be joined to wait for unmounting. | [
"Mount",
"the",
"file",
"system",
"based",
"on",
"the",
"supplied",
"arguments",
"returning",
"a",
"fuse",
".",
"MountedFileSystem",
"that",
"can",
"be",
"joined",
"to",
"wait",
"for",
"unmounting",
"."
] | 224a69530a8fefa8f07e51582b928739127134f2 | https://github.com/kahing/goofys/blob/224a69530a8fefa8f07e51582b928739127134f2/main.go#L106-L118 | train |
kahing/goofys | internal/perms.go | MyUserAndGroup | func MyUserAndGroup() (uid int, gid int) {
// Ask for the current user.
user, err := user.Current()
if err != nil {
panic(err)
}
// Parse UID.
uid64, err := strconv.ParseInt(user.Uid, 10, 32)
if err != nil {
log.Fatalf("Parsing UID (%s): %v", user.Uid, err)
return
}
// Parse GID.
gid64, err := strconv.ParseInt(user.Gid, 10, 32)
if err != nil {
log.Fatalf("Parsing GID (%s): %v", user.Gid, err)
return
}
uid = int(uid64)
gid = int(gid64)
return
} | go | func MyUserAndGroup() (uid int, gid int) {
// Ask for the current user.
user, err := user.Current()
if err != nil {
panic(err)
}
// Parse UID.
uid64, err := strconv.ParseInt(user.Uid, 10, 32)
if err != nil {
log.Fatalf("Parsing UID (%s): %v", user.Uid, err)
return
}
// Parse GID.
gid64, err := strconv.ParseInt(user.Gid, 10, 32)
if err != nil {
log.Fatalf("Parsing GID (%s): %v", user.Gid, err)
return
}
uid = int(uid64)
gid = int(gid64)
return
} | [
"func",
"MyUserAndGroup",
"(",
")",
"(",
"uid",
"int",
",",
"gid",
"int",
")",
"{",
"user",
",",
"err",
":=",
"user",
".",
"Current",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"uid64",
",",
"err",... | // MyUserAndGroup returns the UID and GID of this process. | [
"MyUserAndGroup",
"returns",
"the",
"UID",
"and",
"GID",
"of",
"this",
"process",
"."
] | 224a69530a8fefa8f07e51582b928739127134f2 | https://github.com/kahing/goofys/blob/224a69530a8fefa8f07e51582b928739127134f2/internal/perms.go#L25-L50 | train |
kahing/goofys | internal/buffer_pool.go | Seek | func (mb *MBuf) Seek(offset int64, whence int) (int64, error) {
switch whence {
case 0: // relative to beginning
if offset == 0 {
mb.rbuf = 0
mb.rp = 0
return 0, nil
}
case 1: // relative to current position
if offset == 0 {
for i := 0; i < mb.rbuf; i++ {
offset += int64(len(mb.buffers[i]))
}
offset += int64(mb.rp)
return offset, nil
}
case 2: // relative to the end
if offset == 0 {
for i := 0; i < len(mb.buffers); i++ {
offset += int64(len(mb.buffers[i]))
}
mb.rbuf = len(mb.buffers)
mb.rp = 0
return offset, nil
}
}
log.Errorf("Seek %d %d", offset, whence)
panic(fuse.EINVAL)
return 0, fuse.EINVAL
} | go | func (mb *MBuf) Seek(offset int64, whence int) (int64, error) {
switch whence {
case 0: // relative to beginning
if offset == 0 {
mb.rbuf = 0
mb.rp = 0
return 0, nil
}
case 1: // relative to current position
if offset == 0 {
for i := 0; i < mb.rbuf; i++ {
offset += int64(len(mb.buffers[i]))
}
offset += int64(mb.rp)
return offset, nil
}
case 2: // relative to the end
if offset == 0 {
for i := 0; i < len(mb.buffers); i++ {
offset += int64(len(mb.buffers[i]))
}
mb.rbuf = len(mb.buffers)
mb.rp = 0
return offset, nil
}
}
log.Errorf("Seek %d %d", offset, whence)
panic(fuse.EINVAL)
return 0, fuse.EINVAL
} | [
"func",
"(",
"mb",
"*",
"MBuf",
")",
"Seek",
"(",
"offset",
"int64",
",",
"whence",
"int",
")",
"(",
"int64",
",",
"error",
")",
"{",
"switch",
"whence",
"{",
"case",
"0",
":",
"if",
"offset",
"==",
"0",
"{",
"mb",
".",
"rbuf",
"=",
"0",
"\n",
... | // seek only seeks the reader | [
"seek",
"only",
"seeks",
"the",
"reader"
] | 224a69530a8fefa8f07e51582b928739127134f2 | https://github.com/kahing/goofys/blob/224a69530a8fefa8f07e51582b928739127134f2/internal/buffer_pool.go#L210-L242 | train |
cloudflare/cloudflare-go | duration.go | UnmarshalJSON | func (d *Duration) UnmarshalJSON(buf []byte) error {
var str string
err := json.Unmarshal(buf, &str)
if err != nil {
return err
}
dur, err := time.ParseDuration(str)
if err != nil {
return err
}
d.Duration = dur
return nil
} | go | func (d *Duration) UnmarshalJSON(buf []byte) error {
var str string
err := json.Unmarshal(buf, &str)
if err != nil {
return err
}
dur, err := time.ParseDuration(str)
if err != nil {
return err
}
d.Duration = dur
return nil
} | [
"func",
"(",
"d",
"*",
"Duration",
")",
"UnmarshalJSON",
"(",
"buf",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"str",
"string",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"buf",
",",
"&",
"str",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
... | // UnmarshalJSON decodes a Duration from a JSON string parsed using time.ParseDuration. | [
"UnmarshalJSON",
"decodes",
"a",
"Duration",
"from",
"a",
"JSON",
"string",
"parsed",
"using",
"time",
".",
"ParseDuration",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/duration.go#L20-L35 | train |
cloudflare/cloudflare-go | cmd/flarectl/misc.go | writeTable | func writeTable(data [][]string, cols ...string) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader(cols)
table.SetBorder(false)
table.AppendBulk(data)
table.Render()
} | go | func writeTable(data [][]string, cols ...string) {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader(cols)
table.SetBorder(false)
table.AppendBulk(data)
table.Render()
} | [
"func",
"writeTable",
"(",
"data",
"[",
"]",
"[",
"]",
"string",
",",
"cols",
"...",
"string",
")",
"{",
"table",
":=",
"tablewriter",
".",
"NewWriter",
"(",
"os",
".",
"Stdout",
")",
"\n",
"table",
".",
"SetHeader",
"(",
"cols",
")",
"\n",
"table",
... | // writeTable outputs tabular data to stdout. | [
"writeTable",
"outputs",
"tabular",
"data",
"to",
"stdout",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cmd/flarectl/misc.go#L16-L23 | train |
cloudflare/cloudflare-go | cmd/flarectl/misc.go | checkFlags | func checkFlags(c *cli.Context, flags ...string) error {
for _, flag := range flags {
if c.String(flag) == "" {
cli.ShowSubcommandHelp(c)
err := errors.Errorf("error: the required flag %q was empty or not provided", flag)
fmt.Fprintln(os.Stderr, err)
return err
}
}
return nil
} | go | func checkFlags(c *cli.Context, flags ...string) error {
for _, flag := range flags {
if c.String(flag) == "" {
cli.ShowSubcommandHelp(c)
err := errors.Errorf("error: the required flag %q was empty or not provided", flag)
fmt.Fprintln(os.Stderr, err)
return err
}
}
return nil
} | [
"func",
"checkFlags",
"(",
"c",
"*",
"cli",
".",
"Context",
",",
"flags",
"...",
"string",
")",
"error",
"{",
"for",
"_",
",",
"flag",
":=",
"range",
"flags",
"{",
"if",
"c",
".",
"String",
"(",
"flag",
")",
"==",
"\"\"",
"{",
"cli",
".",
"ShowSu... | // Utility function to check if CLI flags were given. | [
"Utility",
"function",
"to",
"check",
"if",
"CLI",
"flags",
"were",
"given",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cmd/flarectl/misc.go#L45-L56 | train |
cloudflare/cloudflare-go | cmd/flarectl/misc.go | _getIps | func _getIps(ipType string, showMsgType bool) {
ips, _ := cloudflare.IPs()
switch ipType {
case "ipv4":
if showMsgType != true {
fmt.Println("IPv4 ranges:")
}
for _, r := range ips.IPv4CIDRs {
fmt.Println(" ", r)
}
case "ipv6":
if showMsgType != true {
fmt.Println("IPv6 ranges:")
}
for _, r := range ips.IPv6CIDRs {
fmt.Println(" ", r)
}
}
} | go | func _getIps(ipType string, showMsgType bool) {
ips, _ := cloudflare.IPs()
switch ipType {
case "ipv4":
if showMsgType != true {
fmt.Println("IPv4 ranges:")
}
for _, r := range ips.IPv4CIDRs {
fmt.Println(" ", r)
}
case "ipv6":
if showMsgType != true {
fmt.Println("IPv6 ranges:")
}
for _, r := range ips.IPv6CIDRs {
fmt.Println(" ", r)
}
}
} | [
"func",
"_getIps",
"(",
"ipType",
"string",
",",
"showMsgType",
"bool",
")",
"{",
"ips",
",",
"_",
":=",
"cloudflare",
".",
"IPs",
"(",
")",
"\n",
"switch",
"ipType",
"{",
"case",
"\"ipv4\"",
":",
"if",
"showMsgType",
"!=",
"true",
"{",
"fmt",
".",
"... | //
// gets type of IPs to retrieve and returns results
// | [
"gets",
"type",
"of",
"IPs",
"to",
"retrieve",
"and",
"returns",
"results"
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cmd/flarectl/misc.go#L71-L90 | train |
cloudflare/cloudflare-go | auditlogs.go | String | func (a AuditLogFilter) String() string {
params := "?"
if a.ID != "" {
params += "&id=" + a.ID
}
if a.ActorIP != "" {
params += "&actor.ip=" + a.ActorIP
}
if a.ActorEmail != "" {
params += "&actor.email=" + a.ActorEmail
}
if a.ZoneName != "" {
params += "&zone.name=" + a.ZoneName
}
if a.Direction != "" {
params += "&direction=" + a.Direction
}
if a.Since != "" {
params += "&since=" + a.Since
}
if a.Before != "" {
params += "&before=" + a.Before
}
if a.PerPage > 0 {
params += "&per_page=" + fmt.Sprintf("%d", a.PerPage)
}
if a.Page > 0 {
params += "&page=" + fmt.Sprintf("%d", a.Page)
}
return params
} | go | func (a AuditLogFilter) String() string {
params := "?"
if a.ID != "" {
params += "&id=" + a.ID
}
if a.ActorIP != "" {
params += "&actor.ip=" + a.ActorIP
}
if a.ActorEmail != "" {
params += "&actor.email=" + a.ActorEmail
}
if a.ZoneName != "" {
params += "&zone.name=" + a.ZoneName
}
if a.Direction != "" {
params += "&direction=" + a.Direction
}
if a.Since != "" {
params += "&since=" + a.Since
}
if a.Before != "" {
params += "&before=" + a.Before
}
if a.PerPage > 0 {
params += "&per_page=" + fmt.Sprintf("%d", a.PerPage)
}
if a.Page > 0 {
params += "&page=" + fmt.Sprintf("%d", a.Page)
}
return params
} | [
"func",
"(",
"a",
"AuditLogFilter",
")",
"String",
"(",
")",
"string",
"{",
"params",
":=",
"\"?\"",
"\n",
"if",
"a",
".",
"ID",
"!=",
"\"\"",
"{",
"params",
"+=",
"\"&id=\"",
"+",
"a",
".",
"ID",
"\n",
"}",
"\n",
"if",
"a",
".",
"ActorIP",
"!=",... | // String turns an audit log filter in to an HTTP Query Param
// list. It will not inclue empty members of the struct in the
// query parameters. | [
"String",
"turns",
"an",
"audit",
"log",
"filter",
"in",
"to",
"an",
"HTTP",
"Query",
"Param",
"list",
".",
"It",
"will",
"not",
"inclue",
"empty",
"members",
"of",
"the",
"struct",
"in",
"the",
"query",
"parameters",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/auditlogs.go#L71-L101 | train |
cloudflare/cloudflare-go | auditlogs.go | unmarshalReturn | func unmarshalReturn(res []byte) (AuditLogResponse, error) {
var auditResponse AuditLogResponse
err := json.Unmarshal(res, &auditResponse)
if err != nil {
return auditResponse, err
}
return auditResponse, nil
} | go | func unmarshalReturn(res []byte) (AuditLogResponse, error) {
var auditResponse AuditLogResponse
err := json.Unmarshal(res, &auditResponse)
if err != nil {
return auditResponse, err
}
return auditResponse, nil
} | [
"func",
"unmarshalReturn",
"(",
"res",
"[",
"]",
"byte",
")",
"(",
"AuditLogResponse",
",",
"error",
")",
"{",
"var",
"auditResponse",
"AuditLogResponse",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"res",
",",
"&",
"auditResponse",
")",
"\n",
"if",
... | // unmarshalReturn will unmarshal bytes and return an auditlogresponse | [
"unmarshalReturn",
"will",
"unmarshal",
"bytes",
"and",
"return",
"an",
"auditlogresponse"
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/auditlogs.go#L123-L130 | train |
cloudflare/cloudflare-go | zone.go | ListZonesContext | func (api *API) ListZonesContext(ctx context.Context, opts ...ReqOption) (r ZonesResponse, err error) {
var res []byte
opt := reqOption{
params: url.Values{},
}
for _, of := range opts {
of(&opt)
}
res, err = api.makeRequestContext(ctx, "GET", "/zones?"+opt.params.Encode(), nil)
if err != nil {
return ZonesResponse{}, errors.Wrap(err, errMakeRequestError)
}
err = json.Unmarshal(res, &r)
if err != nil {
return ZonesResponse{}, errors.Wrap(err, errUnmarshalError)
}
return r, nil
} | go | func (api *API) ListZonesContext(ctx context.Context, opts ...ReqOption) (r ZonesResponse, err error) {
var res []byte
opt := reqOption{
params: url.Values{},
}
for _, of := range opts {
of(&opt)
}
res, err = api.makeRequestContext(ctx, "GET", "/zones?"+opt.params.Encode(), nil)
if err != nil {
return ZonesResponse{}, errors.Wrap(err, errMakeRequestError)
}
err = json.Unmarshal(res, &r)
if err != nil {
return ZonesResponse{}, errors.Wrap(err, errUnmarshalError)
}
return r, nil
} | [
"func",
"(",
"api",
"*",
"API",
")",
"ListZonesContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"...",
"ReqOption",
")",
"(",
"r",
"ZonesResponse",
",",
"err",
"error",
")",
"{",
"var",
"res",
"[",
"]",
"byte",
"\n",
"opt",
":=",
"reqOpt... | // ListZonesContext lists zones on an account. Optionally takes a list of ReqOptions. | [
"ListZonesContext",
"lists",
"zones",
"on",
"an",
"account",
".",
"Optionally",
"takes",
"a",
"list",
"of",
"ReqOptions",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/zone.go#L401-L420 | train |
cloudflare/cloudflare-go | zone.go | ZoneSetPaused | func (api *API) ZoneSetPaused(zoneID string, paused bool) (Zone, error) {
zoneopts := ZoneOptions{Paused: &paused}
zone, err := api.EditZone(zoneID, zoneopts)
if err != nil {
return Zone{}, err
}
return zone, nil
} | go | func (api *API) ZoneSetPaused(zoneID string, paused bool) (Zone, error) {
zoneopts := ZoneOptions{Paused: &paused}
zone, err := api.EditZone(zoneID, zoneopts)
if err != nil {
return Zone{}, err
}
return zone, nil
} | [
"func",
"(",
"api",
"*",
"API",
")",
"ZoneSetPaused",
"(",
"zoneID",
"string",
",",
"paused",
"bool",
")",
"(",
"Zone",
",",
"error",
")",
"{",
"zoneopts",
":=",
"ZoneOptions",
"{",
"Paused",
":",
"&",
"paused",
"}",
"\n",
"zone",
",",
"err",
":=",
... | // ZoneSetPaused pauses Cloudflare service for the entire zone, sending all
// traffic direct to the origin. | [
"ZoneSetPaused",
"pauses",
"Cloudflare",
"service",
"for",
"the",
"entire",
"zone",
"sending",
"all",
"traffic",
"direct",
"to",
"the",
"origin",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/zone.go#L447-L455 | train |
cloudflare/cloudflare-go | zone.go | ZoneSetVanityNS | func (api *API) ZoneSetVanityNS(zoneID string, ns []string) (Zone, error) {
zoneopts := ZoneOptions{VanityNS: ns}
zone, err := api.EditZone(zoneID, zoneopts)
if err != nil {
return Zone{}, err
}
return zone, nil
} | go | func (api *API) ZoneSetVanityNS(zoneID string, ns []string) (Zone, error) {
zoneopts := ZoneOptions{VanityNS: ns}
zone, err := api.EditZone(zoneID, zoneopts)
if err != nil {
return Zone{}, err
}
return zone, nil
} | [
"func",
"(",
"api",
"*",
"API",
")",
"ZoneSetVanityNS",
"(",
"zoneID",
"string",
",",
"ns",
"[",
"]",
"string",
")",
"(",
"Zone",
",",
"error",
")",
"{",
"zoneopts",
":=",
"ZoneOptions",
"{",
"VanityNS",
":",
"ns",
"}",
"\n",
"zone",
",",
"err",
":... | // ZoneSetVanityNS sets custom nameservers for the zone.
// These names must be within the same zone. | [
"ZoneSetVanityNS",
"sets",
"custom",
"nameservers",
"for",
"the",
"zone",
".",
"These",
"names",
"must",
"be",
"within",
"the",
"same",
"zone",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/zone.go#L459-L467 | train |
cloudflare/cloudflare-go | zone.go | ZoneSetPlan | func (api *API) ZoneSetPlan(zoneID string, plan ZonePlan) (Zone, error) {
zoneopts := ZoneOptions{Plan: &plan}
zone, err := api.EditZone(zoneID, zoneopts)
if err != nil {
return Zone{}, err
}
return zone, nil
} | go | func (api *API) ZoneSetPlan(zoneID string, plan ZonePlan) (Zone, error) {
zoneopts := ZoneOptions{Plan: &plan}
zone, err := api.EditZone(zoneID, zoneopts)
if err != nil {
return Zone{}, err
}
return zone, nil
} | [
"func",
"(",
"api",
"*",
"API",
")",
"ZoneSetPlan",
"(",
"zoneID",
"string",
",",
"plan",
"ZonePlan",
")",
"(",
"Zone",
",",
"error",
")",
"{",
"zoneopts",
":=",
"ZoneOptions",
"{",
"Plan",
":",
"&",
"plan",
"}",
"\n",
"zone",
",",
"err",
":=",
"ap... | // ZoneSetPlan changes the zone plan. | [
"ZoneSetPlan",
"changes",
"the",
"zone",
"plan",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/zone.go#L470-L478 | train |
cloudflare/cloudflare-go | options.go | UsingRateLimit | func UsingRateLimit(rps float64) Option {
return func(api *API) error {
// because ratelimiter doesnt do any windowing
// setting burst makes it difficult to enforce a fixed rate
// so setting it equal to 1 this effectively disables bursting
// this doesn't check for sensible values, ultimately the api will enforce that the value is ok
api.rateLimiter = rate.NewLimiter(rate.Limit(rps), 1)
return nil
}
} | go | func UsingRateLimit(rps float64) Option {
return func(api *API) error {
// because ratelimiter doesnt do any windowing
// setting burst makes it difficult to enforce a fixed rate
// so setting it equal to 1 this effectively disables bursting
// this doesn't check for sensible values, ultimately the api will enforce that the value is ok
api.rateLimiter = rate.NewLimiter(rate.Limit(rps), 1)
return nil
}
} | [
"func",
"UsingRateLimit",
"(",
"rps",
"float64",
")",
"Option",
"{",
"return",
"func",
"(",
"api",
"*",
"API",
")",
"error",
"{",
"api",
".",
"rateLimiter",
"=",
"rate",
".",
"NewLimiter",
"(",
"rate",
".",
"Limit",
"(",
"rps",
")",
",",
"1",
")",
... | // UsingRateLimit applies a non-default rate limit to client API requests
// If not specified the default of 4rps will be applied | [
"UsingRateLimit",
"applies",
"a",
"non",
"-",
"default",
"rate",
"limit",
"to",
"client",
"API",
"requests",
"If",
"not",
"specified",
"the",
"default",
"of",
"4rps",
"will",
"be",
"applied"
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/options.go#L42-L51 | train |
cloudflare/cloudflare-go | options.go | UsingLogger | func UsingLogger(logger Logger) Option {
return func(api *API) error {
api.logger = logger
return nil
}
} | go | func UsingLogger(logger Logger) Option {
return func(api *API) error {
api.logger = logger
return nil
}
} | [
"func",
"UsingLogger",
"(",
"logger",
"Logger",
")",
"Option",
"{",
"return",
"func",
"(",
"api",
"*",
"API",
")",
"error",
"{",
"api",
".",
"logger",
"=",
"logger",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // UsingLogger can be set if you want to get log output from this API instance
// By default no log output is emitted | [
"UsingLogger",
"can",
"be",
"set",
"if",
"you",
"want",
"to",
"get",
"log",
"output",
"from",
"this",
"API",
"instance",
"By",
"default",
"no",
"log",
"output",
"is",
"emitted"
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/options.go#L69-L74 | train |
cloudflare/cloudflare-go | virtualdns.go | VirtualDNSUserAnalytics | func (api *API) VirtualDNSUserAnalytics(virtualDNSID string, o VirtualDNSUserAnalyticsOptions) (VirtualDNSAnalytics, error) {
uri := "/user/virtual_dns/" + virtualDNSID + "/dns_analytics/report?" + o.encode()
res, err := api.makeRequest("GET", uri, nil)
if err != nil {
return VirtualDNSAnalytics{}, errors.Wrap(err, errMakeRequestError)
}
response := VirtualDNSAnalyticsResponse{}
err = json.Unmarshal(res, &response)
if err != nil {
return VirtualDNSAnalytics{}, errors.Wrap(err, errUnmarshalError)
}
return response.Result, nil
} | go | func (api *API) VirtualDNSUserAnalytics(virtualDNSID string, o VirtualDNSUserAnalyticsOptions) (VirtualDNSAnalytics, error) {
uri := "/user/virtual_dns/" + virtualDNSID + "/dns_analytics/report?" + o.encode()
res, err := api.makeRequest("GET", uri, nil)
if err != nil {
return VirtualDNSAnalytics{}, errors.Wrap(err, errMakeRequestError)
}
response := VirtualDNSAnalyticsResponse{}
err = json.Unmarshal(res, &response)
if err != nil {
return VirtualDNSAnalytics{}, errors.Wrap(err, errUnmarshalError)
}
return response.Result, nil
} | [
"func",
"(",
"api",
"*",
"API",
")",
"VirtualDNSUserAnalytics",
"(",
"virtualDNSID",
"string",
",",
"o",
"VirtualDNSUserAnalyticsOptions",
")",
"(",
"VirtualDNSAnalytics",
",",
"error",
")",
"{",
"uri",
":=",
"\"/user/virtual_dns/\"",
"+",
"virtualDNSID",
"+",
"\"... | // VirtualDNSUserAnalytics retrieves analytics report for a specified dimension and time range | [
"VirtualDNSUserAnalytics",
"retrieves",
"analytics",
"report",
"for",
"a",
"specified",
"dimension",
"and",
"time",
"range"
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/virtualdns.go#L178-L192 | train |
cloudflare/cloudflare-go | custom_hostname.go | CustomHostnameIDByName | func (api *API) CustomHostnameIDByName(zoneID string, hostname string) (string, error) {
customHostnames, _, err := api.CustomHostnames(zoneID, 1, CustomHostname{Hostname: hostname})
if err != nil {
return "", errors.Wrap(err, "CustomHostnames command failed")
}
for _, ch := range customHostnames {
if ch.Hostname == hostname {
return ch.ID, nil
}
}
return "", errors.New("CustomHostname could not be found")
} | go | func (api *API) CustomHostnameIDByName(zoneID string, hostname string) (string, error) {
customHostnames, _, err := api.CustomHostnames(zoneID, 1, CustomHostname{Hostname: hostname})
if err != nil {
return "", errors.Wrap(err, "CustomHostnames command failed")
}
for _, ch := range customHostnames {
if ch.Hostname == hostname {
return ch.ID, nil
}
}
return "", errors.New("CustomHostname could not be found")
} | [
"func",
"(",
"api",
"*",
"API",
")",
"CustomHostnameIDByName",
"(",
"zoneID",
"string",
",",
"hostname",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"customHostnames",
",",
"_",
",",
"err",
":=",
"api",
".",
"CustomHostnames",
"(",
"zoneID",
",... | // CustomHostnameIDByName retrieves the ID for the given hostname in the given zone. | [
"CustomHostnameIDByName",
"retrieves",
"the",
"ID",
"for",
"the",
"given",
"hostname",
"in",
"the",
"given",
"zone",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/custom_hostname.go#L149-L160 | train |
cloudflare/cloudflare-go | cloudflare.go | newClient | func newClient(opts ...Option) (*API, error) {
silentLogger := log.New(ioutil.Discard, "", log.LstdFlags)
api := &API{
BaseURL: apiURL,
headers: make(http.Header),
rateLimiter: rate.NewLimiter(rate.Limit(4), 1), // 4rps equates to default api limit (1200 req/5 min)
retryPolicy: RetryPolicy{
MaxRetries: 3,
MinRetryDelay: time.Duration(1) * time.Second,
MaxRetryDelay: time.Duration(30) * time.Second,
},
logger: silentLogger,
}
err := api.parseOptions(opts...)
if err != nil {
return nil, errors.Wrap(err, "options parsing failed")
}
// Fall back to http.DefaultClient if the package user does not provide
// their own.
if api.httpClient == nil {
api.httpClient = http.DefaultClient
}
return api, nil
} | go | func newClient(opts ...Option) (*API, error) {
silentLogger := log.New(ioutil.Discard, "", log.LstdFlags)
api := &API{
BaseURL: apiURL,
headers: make(http.Header),
rateLimiter: rate.NewLimiter(rate.Limit(4), 1), // 4rps equates to default api limit (1200 req/5 min)
retryPolicy: RetryPolicy{
MaxRetries: 3,
MinRetryDelay: time.Duration(1) * time.Second,
MaxRetryDelay: time.Duration(30) * time.Second,
},
logger: silentLogger,
}
err := api.parseOptions(opts...)
if err != nil {
return nil, errors.Wrap(err, "options parsing failed")
}
// Fall back to http.DefaultClient if the package user does not provide
// their own.
if api.httpClient == nil {
api.httpClient = http.DefaultClient
}
return api, nil
} | [
"func",
"newClient",
"(",
"opts",
"...",
"Option",
")",
"(",
"*",
"API",
",",
"error",
")",
"{",
"silentLogger",
":=",
"log",
".",
"New",
"(",
"ioutil",
".",
"Discard",
",",
"\"\"",
",",
"log",
".",
"LstdFlags",
")",
"\n",
"api",
":=",
"&",
"API",
... | // newClient provides shared logic for New and NewWithUserServiceKey | [
"newClient",
"provides",
"shared",
"logic",
"for",
"New",
"and",
"NewWithUserServiceKey"
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L48-L75 | train |
cloudflare/cloudflare-go | cloudflare.go | New | func New(key, email string, opts ...Option) (*API, error) {
if key == "" || email == "" {
return nil, errors.New(errEmptyCredentials)
}
api, err := newClient(opts...)
if err != nil {
return nil, err
}
api.APIKey = key
api.APIEmail = email
api.authType = AuthKeyEmail
return api, nil
} | go | func New(key, email string, opts ...Option) (*API, error) {
if key == "" || email == "" {
return nil, errors.New(errEmptyCredentials)
}
api, err := newClient(opts...)
if err != nil {
return nil, err
}
api.APIKey = key
api.APIEmail = email
api.authType = AuthKeyEmail
return api, nil
} | [
"func",
"New",
"(",
"key",
",",
"email",
"string",
",",
"opts",
"...",
"Option",
")",
"(",
"*",
"API",
",",
"error",
")",
"{",
"if",
"key",
"==",
"\"\"",
"||",
"email",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"errEmpty... | // New creates a new Cloudflare v4 API client. | [
"New",
"creates",
"a",
"new",
"Cloudflare",
"v4",
"API",
"client",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L78-L93 | train |
cloudflare/cloudflare-go | cloudflare.go | NewWithUserServiceKey | func NewWithUserServiceKey(key string, opts ...Option) (*API, error) {
if key == "" {
return nil, errors.New(errEmptyCredentials)
}
api, err := newClient(opts...)
if err != nil {
return nil, err
}
api.APIUserServiceKey = key
api.authType = AuthUserService
return api, nil
} | go | func NewWithUserServiceKey(key string, opts ...Option) (*API, error) {
if key == "" {
return nil, errors.New(errEmptyCredentials)
}
api, err := newClient(opts...)
if err != nil {
return nil, err
}
api.APIUserServiceKey = key
api.authType = AuthUserService
return api, nil
} | [
"func",
"NewWithUserServiceKey",
"(",
"key",
"string",
",",
"opts",
"...",
"Option",
")",
"(",
"*",
"API",
",",
"error",
")",
"{",
"if",
"key",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"errEmptyCredentials",
")",
"\n",
"}",
... | // NewWithUserServiceKey creates a new Cloudflare v4 API client using service key authentication. | [
"NewWithUserServiceKey",
"creates",
"a",
"new",
"Cloudflare",
"v4",
"API",
"client",
"using",
"service",
"key",
"authentication",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L96-L110 | train |
cloudflare/cloudflare-go | cloudflare.go | ZoneIDByName | func (api *API) ZoneIDByName(zoneName string) (string, error) {
res, err := api.ListZonesContext(context.TODO(), WithZoneFilter(zoneName))
if err != nil {
return "", errors.Wrap(err, "ListZonesContext command failed")
}
if len(res.Result) > 1 && api.OrganizationID == "" {
return "", errors.New("ambiguous zone name used without an account ID")
}
for _, zone := range res.Result {
if api.OrganizationID != "" {
if zone.Name == zoneName && api.OrganizationID == zone.Account.ID {
return zone.ID, nil
}
} else {
if zone.Name == zoneName {
return zone.ID, nil
}
}
}
return "", errors.New("Zone could not be found")
} | go | func (api *API) ZoneIDByName(zoneName string) (string, error) {
res, err := api.ListZonesContext(context.TODO(), WithZoneFilter(zoneName))
if err != nil {
return "", errors.Wrap(err, "ListZonesContext command failed")
}
if len(res.Result) > 1 && api.OrganizationID == "" {
return "", errors.New("ambiguous zone name used without an account ID")
}
for _, zone := range res.Result {
if api.OrganizationID != "" {
if zone.Name == zoneName && api.OrganizationID == zone.Account.ID {
return zone.ID, nil
}
} else {
if zone.Name == zoneName {
return zone.ID, nil
}
}
}
return "", errors.New("Zone could not be found")
} | [
"func",
"(",
"api",
"*",
"API",
")",
"ZoneIDByName",
"(",
"zoneName",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"api",
".",
"ListZonesContext",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"WithZoneFilter",
"(",
"z... | // ZoneIDByName retrieves a zone's ID from the name. | [
"ZoneIDByName",
"retrieves",
"a",
"zone",
"s",
"ID",
"from",
"the",
"name",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L118-L141 | train |
cloudflare/cloudflare-go | cloudflare.go | makeRequest | func (api *API) makeRequest(method, uri string, params interface{}) ([]byte, error) {
return api.makeRequestWithAuthType(context.TODO(), method, uri, params, api.authType)
} | go | func (api *API) makeRequest(method, uri string, params interface{}) ([]byte, error) {
return api.makeRequestWithAuthType(context.TODO(), method, uri, params, api.authType)
} | [
"func",
"(",
"api",
"*",
"API",
")",
"makeRequest",
"(",
"method",
",",
"uri",
"string",
",",
"params",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"api",
".",
"makeRequestWithAuthType",
"(",
"context",
".",
"... | // makeRequest makes a HTTP request and returns the body as a byte slice,
// closing it before returnng. params will be serialized to JSON. | [
"makeRequest",
"makes",
"a",
"HTTP",
"request",
"and",
"returns",
"the",
"body",
"as",
"a",
"byte",
"slice",
"closing",
"it",
"before",
"returnng",
".",
"params",
"will",
"be",
"serialized",
"to",
"JSON",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L145-L147 | train |
cloudflare/cloudflare-go | cloudflare.go | userBaseURL | func (api *API) userBaseURL(accountBase string) string {
if api.OrganizationID != "" {
return "/accounts/" + api.OrganizationID
}
return accountBase
} | go | func (api *API) userBaseURL(accountBase string) string {
if api.OrganizationID != "" {
return "/accounts/" + api.OrganizationID
}
return accountBase
} | [
"func",
"(",
"api",
"*",
"API",
")",
"userBaseURL",
"(",
"accountBase",
"string",
")",
"string",
"{",
"if",
"api",
".",
"OrganizationID",
"!=",
"\"\"",
"{",
"return",
"\"/accounts/\"",
"+",
"api",
".",
"OrganizationID",
"\n",
"}",
"\n",
"return",
"accountB... | // Returns the base URL to use for API endpoints that exist for both accounts and organizations.
// If an Organization option was used when creating the API instance, returns the org URL.
//
// accountBase is the base URL for endpoints referring to the current user. It exists as a
// parameter because it is not consistent across APIs. | [
"Returns",
"the",
"base",
"URL",
"to",
"use",
"for",
"API",
"endpoints",
"that",
"exist",
"for",
"both",
"accounts",
"and",
"organizations",
".",
"If",
"an",
"Organization",
"option",
"was",
"used",
"when",
"creating",
"the",
"API",
"instance",
"returns",
"t... | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L308-L313 | train |
cloudflare/cloudflare-go | cloudflare.go | Raw | func (api *API) Raw(method, endpoint string, data interface{}) (json.RawMessage, error) {
res, err := api.makeRequest(method, endpoint, data)
if err != nil {
return nil, errors.Wrap(err, errMakeRequestError)
}
var r RawResponse
if err := json.Unmarshal(res, &r); err != nil {
return nil, errors.Wrap(err, errUnmarshalError)
}
return r.Result, nil
} | go | func (api *API) Raw(method, endpoint string, data interface{}) (json.RawMessage, error) {
res, err := api.makeRequest(method, endpoint, data)
if err != nil {
return nil, errors.Wrap(err, errMakeRequestError)
}
var r RawResponse
if err := json.Unmarshal(res, &r); err != nil {
return nil, errors.Wrap(err, errUnmarshalError)
}
return r.Result, nil
} | [
"func",
"(",
"api",
"*",
"API",
")",
"Raw",
"(",
"method",
",",
"endpoint",
"string",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"json",
".",
"RawMessage",
",",
"error",
")",
"{",
"res",
",",
"err",
":=",
"api",
".",
"makeRequest",
"(",
"method"... | // Raw makes a HTTP request with user provided params and returns the
// result as untouched JSON. | [
"Raw",
"makes",
"a",
"HTTP",
"request",
"with",
"user",
"provided",
"params",
"and",
"returns",
"the",
"result",
"as",
"untouched",
"JSON",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L355-L366 | train |
cloudflare/cloudflare-go | cloudflare.go | WithZoneFilter | func WithZoneFilter(zone string) ReqOption {
return func(opt *reqOption) {
opt.params.Set("name", zone)
}
} | go | func WithZoneFilter(zone string) ReqOption {
return func(opt *reqOption) {
opt.params.Set("name", zone)
}
} | [
"func",
"WithZoneFilter",
"(",
"zone",
"string",
")",
"ReqOption",
"{",
"return",
"func",
"(",
"opt",
"*",
"reqOption",
")",
"{",
"opt",
".",
"params",
".",
"Set",
"(",
"\"name\"",
",",
"zone",
")",
"\n",
"}",
"\n",
"}"
] | // WithZoneFilter applies a filter based on zone name. | [
"WithZoneFilter",
"applies",
"a",
"filter",
"based",
"on",
"zone",
"name",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L396-L400 | train |
cloudflare/cloudflare-go | cloudflare.go | WithPagination | func WithPagination(opts PaginationOptions) ReqOption {
return func(opt *reqOption) {
opt.params.Set("page", strconv.Itoa(opts.Page))
opt.params.Set("per_page", strconv.Itoa(opts.PerPage))
}
} | go | func WithPagination(opts PaginationOptions) ReqOption {
return func(opt *reqOption) {
opt.params.Set("page", strconv.Itoa(opts.Page))
opt.params.Set("per_page", strconv.Itoa(opts.PerPage))
}
} | [
"func",
"WithPagination",
"(",
"opts",
"PaginationOptions",
")",
"ReqOption",
"{",
"return",
"func",
"(",
"opt",
"*",
"reqOption",
")",
"{",
"opt",
".",
"params",
".",
"Set",
"(",
"\"page\"",
",",
"strconv",
".",
"Itoa",
"(",
"opts",
".",
"Page",
")",
... | // WithPagination configures the pagination for a response. | [
"WithPagination",
"configures",
"the",
"pagination",
"for",
"a",
"response",
"."
] | 024278eb1b129df5cf9fdaf301c08b99283e81bc | https://github.com/cloudflare/cloudflare-go/blob/024278eb1b129df5cf9fdaf301c08b99283e81bc/cloudflare.go#L403-L408 | train |
prometheus/tsdb | record.go | Type | func (d *RecordDecoder) Type(rec []byte) RecordType {
if len(rec) < 1 {
return RecordInvalid
}
switch t := RecordType(rec[0]); t {
case RecordSeries, RecordSamples, RecordTombstones:
return t
}
return RecordInvalid
} | go | func (d *RecordDecoder) Type(rec []byte) RecordType {
if len(rec) < 1 {
return RecordInvalid
}
switch t := RecordType(rec[0]); t {
case RecordSeries, RecordSamples, RecordTombstones:
return t
}
return RecordInvalid
} | [
"func",
"(",
"d",
"*",
"RecordDecoder",
")",
"Type",
"(",
"rec",
"[",
"]",
"byte",
")",
"RecordType",
"{",
"if",
"len",
"(",
"rec",
")",
"<",
"1",
"{",
"return",
"RecordInvalid",
"\n",
"}",
"\n",
"switch",
"t",
":=",
"RecordType",
"(",
"rec",
"[",
... | // Type returns the type of the record.
// Return RecordInvalid if no valid record type is found. | [
"Type",
"returns",
"the",
"type",
"of",
"the",
"record",
".",
"Return",
"RecordInvalid",
"if",
"no",
"valid",
"record",
"type",
"is",
"found",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L47-L56 | train |
prometheus/tsdb | record.go | Series | func (d *RecordDecoder) Series(rec []byte, series []RefSeries) ([]RefSeries, error) {
dec := encoding.Decbuf{B: rec}
if RecordType(dec.Byte()) != RecordSeries {
return nil, errors.New("invalid record type")
}
for len(dec.B) > 0 && dec.Err() == nil {
ref := dec.Be64()
lset := make(labels.Labels, dec.Uvarint())
for i := range lset {
lset[i].Name = dec.UvarintStr()
lset[i].Value = dec.UvarintStr()
}
sort.Sort(lset)
series = append(series, RefSeries{
Ref: ref,
Labels: lset,
})
}
if dec.Err() != nil {
return nil, dec.Err()
}
if len(dec.B) > 0 {
return nil, errors.Errorf("unexpected %d bytes left in entry", len(dec.B))
}
return series, nil
} | go | func (d *RecordDecoder) Series(rec []byte, series []RefSeries) ([]RefSeries, error) {
dec := encoding.Decbuf{B: rec}
if RecordType(dec.Byte()) != RecordSeries {
return nil, errors.New("invalid record type")
}
for len(dec.B) > 0 && dec.Err() == nil {
ref := dec.Be64()
lset := make(labels.Labels, dec.Uvarint())
for i := range lset {
lset[i].Name = dec.UvarintStr()
lset[i].Value = dec.UvarintStr()
}
sort.Sort(lset)
series = append(series, RefSeries{
Ref: ref,
Labels: lset,
})
}
if dec.Err() != nil {
return nil, dec.Err()
}
if len(dec.B) > 0 {
return nil, errors.Errorf("unexpected %d bytes left in entry", len(dec.B))
}
return series, nil
} | [
"func",
"(",
"d",
"*",
"RecordDecoder",
")",
"Series",
"(",
"rec",
"[",
"]",
"byte",
",",
"series",
"[",
"]",
"RefSeries",
")",
"(",
"[",
"]",
"RefSeries",
",",
"error",
")",
"{",
"dec",
":=",
"encoding",
".",
"Decbuf",
"{",
"B",
":",
"rec",
"}",... | // Series appends series in rec to the given slice. | [
"Series",
"appends",
"series",
"in",
"rec",
"to",
"the",
"given",
"slice",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L59-L88 | train |
prometheus/tsdb | record.go | Samples | func (d *RecordDecoder) Samples(rec []byte, samples []RefSample) ([]RefSample, error) {
dec := encoding.Decbuf{B: rec}
if RecordType(dec.Byte()) != RecordSamples {
return nil, errors.New("invalid record type")
}
if dec.Len() == 0 {
return samples, nil
}
var (
baseRef = dec.Be64()
baseTime = dec.Be64int64()
)
for len(dec.B) > 0 && dec.Err() == nil {
dref := dec.Varint64()
dtime := dec.Varint64()
val := dec.Be64()
samples = append(samples, RefSample{
Ref: uint64(int64(baseRef) + dref),
T: baseTime + dtime,
V: math.Float64frombits(val),
})
}
if dec.Err() != nil {
return nil, errors.Wrapf(dec.Err(), "decode error after %d samples", len(samples))
}
if len(dec.B) > 0 {
return nil, errors.Errorf("unexpected %d bytes left in entry", len(dec.B))
}
return samples, nil
} | go | func (d *RecordDecoder) Samples(rec []byte, samples []RefSample) ([]RefSample, error) {
dec := encoding.Decbuf{B: rec}
if RecordType(dec.Byte()) != RecordSamples {
return nil, errors.New("invalid record type")
}
if dec.Len() == 0 {
return samples, nil
}
var (
baseRef = dec.Be64()
baseTime = dec.Be64int64()
)
for len(dec.B) > 0 && dec.Err() == nil {
dref := dec.Varint64()
dtime := dec.Varint64()
val := dec.Be64()
samples = append(samples, RefSample{
Ref: uint64(int64(baseRef) + dref),
T: baseTime + dtime,
V: math.Float64frombits(val),
})
}
if dec.Err() != nil {
return nil, errors.Wrapf(dec.Err(), "decode error after %d samples", len(samples))
}
if len(dec.B) > 0 {
return nil, errors.Errorf("unexpected %d bytes left in entry", len(dec.B))
}
return samples, nil
} | [
"func",
"(",
"d",
"*",
"RecordDecoder",
")",
"Samples",
"(",
"rec",
"[",
"]",
"byte",
",",
"samples",
"[",
"]",
"RefSample",
")",
"(",
"[",
"]",
"RefSample",
",",
"error",
")",
"{",
"dec",
":=",
"encoding",
".",
"Decbuf",
"{",
"B",
":",
"rec",
"}... | // Samples appends samples in rec to the given slice. | [
"Samples",
"appends",
"samples",
"in",
"rec",
"to",
"the",
"given",
"slice",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L91-L123 | train |
prometheus/tsdb | record.go | Tombstones | func (d *RecordDecoder) Tombstones(rec []byte, tstones []Stone) ([]Stone, error) {
dec := encoding.Decbuf{B: rec}
if RecordType(dec.Byte()) != RecordTombstones {
return nil, errors.New("invalid record type")
}
for dec.Len() > 0 && dec.Err() == nil {
tstones = append(tstones, Stone{
ref: dec.Be64(),
intervals: Intervals{
{Mint: dec.Varint64(), Maxt: dec.Varint64()},
},
})
}
if dec.Err() != nil {
return nil, dec.Err()
}
if len(dec.B) > 0 {
return nil, errors.Errorf("unexpected %d bytes left in entry", len(dec.B))
}
return tstones, nil
} | go | func (d *RecordDecoder) Tombstones(rec []byte, tstones []Stone) ([]Stone, error) {
dec := encoding.Decbuf{B: rec}
if RecordType(dec.Byte()) != RecordTombstones {
return nil, errors.New("invalid record type")
}
for dec.Len() > 0 && dec.Err() == nil {
tstones = append(tstones, Stone{
ref: dec.Be64(),
intervals: Intervals{
{Mint: dec.Varint64(), Maxt: dec.Varint64()},
},
})
}
if dec.Err() != nil {
return nil, dec.Err()
}
if len(dec.B) > 0 {
return nil, errors.Errorf("unexpected %d bytes left in entry", len(dec.B))
}
return tstones, nil
} | [
"func",
"(",
"d",
"*",
"RecordDecoder",
")",
"Tombstones",
"(",
"rec",
"[",
"]",
"byte",
",",
"tstones",
"[",
"]",
"Stone",
")",
"(",
"[",
"]",
"Stone",
",",
"error",
")",
"{",
"dec",
":=",
"encoding",
".",
"Decbuf",
"{",
"B",
":",
"rec",
"}",
... | // Tombstones appends tombstones in rec to the given slice. | [
"Tombstones",
"appends",
"tombstones",
"in",
"rec",
"to",
"the",
"given",
"slice",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L126-L147 | train |
prometheus/tsdb | record.go | Series | func (e *RecordEncoder) Series(series []RefSeries, b []byte) []byte {
buf := encoding.Encbuf{B: b}
buf.PutByte(byte(RecordSeries))
for _, s := range series {
buf.PutBE64(s.Ref)
buf.PutUvarint(len(s.Labels))
for _, l := range s.Labels {
buf.PutUvarintStr(l.Name)
buf.PutUvarintStr(l.Value)
}
}
return buf.Get()
} | go | func (e *RecordEncoder) Series(series []RefSeries, b []byte) []byte {
buf := encoding.Encbuf{B: b}
buf.PutByte(byte(RecordSeries))
for _, s := range series {
buf.PutBE64(s.Ref)
buf.PutUvarint(len(s.Labels))
for _, l := range s.Labels {
buf.PutUvarintStr(l.Name)
buf.PutUvarintStr(l.Value)
}
}
return buf.Get()
} | [
"func",
"(",
"e",
"*",
"RecordEncoder",
")",
"Series",
"(",
"series",
"[",
"]",
"RefSeries",
",",
"b",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"buf",
":=",
"encoding",
".",
"Encbuf",
"{",
"B",
":",
"b",
"}",
"\n",
"buf",
".",
"PutByte",
"... | // Series appends the encoded series to b and returns the resulting slice. | [
"Series",
"appends",
"the",
"encoded",
"series",
"to",
"b",
"and",
"returns",
"the",
"resulting",
"slice",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L155-L169 | train |
prometheus/tsdb | record.go | Samples | func (e *RecordEncoder) Samples(samples []RefSample, b []byte) []byte {
buf := encoding.Encbuf{B: b}
buf.PutByte(byte(RecordSamples))
if len(samples) == 0 {
return buf.Get()
}
// Store base timestamp and base reference number of first sample.
// All samples encode their timestamp and ref as delta to those.
first := samples[0]
buf.PutBE64(first.Ref)
buf.PutBE64int64(first.T)
for _, s := range samples {
buf.PutVarint64(int64(s.Ref) - int64(first.Ref))
buf.PutVarint64(s.T - first.T)
buf.PutBE64(math.Float64bits(s.V))
}
return buf.Get()
} | go | func (e *RecordEncoder) Samples(samples []RefSample, b []byte) []byte {
buf := encoding.Encbuf{B: b}
buf.PutByte(byte(RecordSamples))
if len(samples) == 0 {
return buf.Get()
}
// Store base timestamp and base reference number of first sample.
// All samples encode their timestamp and ref as delta to those.
first := samples[0]
buf.PutBE64(first.Ref)
buf.PutBE64int64(first.T)
for _, s := range samples {
buf.PutVarint64(int64(s.Ref) - int64(first.Ref))
buf.PutVarint64(s.T - first.T)
buf.PutBE64(math.Float64bits(s.V))
}
return buf.Get()
} | [
"func",
"(",
"e",
"*",
"RecordEncoder",
")",
"Samples",
"(",
"samples",
"[",
"]",
"RefSample",
",",
"b",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"buf",
":=",
"encoding",
".",
"Encbuf",
"{",
"B",
":",
"b",
"}",
"\n",
"buf",
".",
"PutByte",
... | // Samples appends the encoded samples to b and returns the resulting slice. | [
"Samples",
"appends",
"the",
"encoded",
"samples",
"to",
"b",
"and",
"returns",
"the",
"resulting",
"slice",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L172-L193 | train |
prometheus/tsdb | record.go | Tombstones | func (e *RecordEncoder) Tombstones(tstones []Stone, b []byte) []byte {
buf := encoding.Encbuf{B: b}
buf.PutByte(byte(RecordTombstones))
for _, s := range tstones {
for _, iv := range s.intervals {
buf.PutBE64(s.ref)
buf.PutVarint64(iv.Mint)
buf.PutVarint64(iv.Maxt)
}
}
return buf.Get()
} | go | func (e *RecordEncoder) Tombstones(tstones []Stone, b []byte) []byte {
buf := encoding.Encbuf{B: b}
buf.PutByte(byte(RecordTombstones))
for _, s := range tstones {
for _, iv := range s.intervals {
buf.PutBE64(s.ref)
buf.PutVarint64(iv.Mint)
buf.PutVarint64(iv.Maxt)
}
}
return buf.Get()
} | [
"func",
"(",
"e",
"*",
"RecordEncoder",
")",
"Tombstones",
"(",
"tstones",
"[",
"]",
"Stone",
",",
"b",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"buf",
":=",
"encoding",
".",
"Encbuf",
"{",
"B",
":",
"b",
"}",
"\n",
"buf",
".",
"PutByte",
... | // Tombstones appends the encoded tombstones to b and returns the resulting slice. | [
"Tombstones",
"appends",
"the",
"encoded",
"tombstones",
"to",
"b",
"and",
"returns",
"the",
"resulting",
"slice",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/record.go#L196-L208 | train |
prometheus/tsdb | tsdbutil/buffer.go | NewBuffer | func NewBuffer(it SeriesIterator, delta int64) *BufferedSeriesIterator {
return &BufferedSeriesIterator{
it: it,
buf: newSampleRing(delta, 16),
lastTime: math.MinInt64,
}
} | go | func NewBuffer(it SeriesIterator, delta int64) *BufferedSeriesIterator {
return &BufferedSeriesIterator{
it: it,
buf: newSampleRing(delta, 16),
lastTime: math.MinInt64,
}
} | [
"func",
"NewBuffer",
"(",
"it",
"SeriesIterator",
",",
"delta",
"int64",
")",
"*",
"BufferedSeriesIterator",
"{",
"return",
"&",
"BufferedSeriesIterator",
"{",
"it",
":",
"it",
",",
"buf",
":",
"newSampleRing",
"(",
"delta",
",",
"16",
")",
",",
"lastTime",
... | // NewBuffer returns a new iterator that buffers the values within the time range
// of the current element and the duration of delta before. | [
"NewBuffer",
"returns",
"a",
"new",
"iterator",
"that",
"buffers",
"the",
"values",
"within",
"the",
"time",
"range",
"of",
"the",
"current",
"element",
"and",
"the",
"duration",
"of",
"delta",
"before",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/tsdbutil/buffer.go#L44-L50 | train |
prometheus/tsdb | tsdbutil/buffer.go | PeekBack | func (b *BufferedSeriesIterator) PeekBack() (t int64, v float64, ok bool) {
return b.buf.last()
} | go | func (b *BufferedSeriesIterator) PeekBack() (t int64, v float64, ok bool) {
return b.buf.last()
} | [
"func",
"(",
"b",
"*",
"BufferedSeriesIterator",
")",
"PeekBack",
"(",
")",
"(",
"t",
"int64",
",",
"v",
"float64",
",",
"ok",
"bool",
")",
"{",
"return",
"b",
".",
"buf",
".",
"last",
"(",
")",
"\n",
"}"
] | // PeekBack returns the previous element of the iterator. If there is none buffered,
// ok is false. | [
"PeekBack",
"returns",
"the",
"previous",
"element",
"of",
"the",
"iterator",
".",
"If",
"there",
"is",
"none",
"buffered",
"ok",
"is",
"false",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/tsdbutil/buffer.go#L54-L56 | train |
prometheus/tsdb | tsdbutil/buffer.go | add | func (r *sampleRing) add(t int64, v float64) {
l := len(r.buf)
// Grow the ring buffer if it fits no more elements.
if l == r.l {
buf := make([]sample, 2*l)
copy(buf[l+r.f:], r.buf[r.f:])
copy(buf, r.buf[:r.f])
r.buf = buf
r.i = r.f
r.f += l
} else {
r.i++
if r.i >= l {
r.i -= l
}
}
r.buf[r.i] = sample{t: t, v: v}
r.l++
// Free head of the buffer of samples that just fell out of the range.
for r.buf[r.f].t < t-r.delta {
r.f++
if r.f >= l {
r.f -= l
}
r.l--
}
} | go | func (r *sampleRing) add(t int64, v float64) {
l := len(r.buf)
// Grow the ring buffer if it fits no more elements.
if l == r.l {
buf := make([]sample, 2*l)
copy(buf[l+r.f:], r.buf[r.f:])
copy(buf, r.buf[:r.f])
r.buf = buf
r.i = r.f
r.f += l
} else {
r.i++
if r.i >= l {
r.i -= l
}
}
r.buf[r.i] = sample{t: t, v: v}
r.l++
// Free head of the buffer of samples that just fell out of the range.
for r.buf[r.f].t < t-r.delta {
r.f++
if r.f >= l {
r.f -= l
}
r.l--
}
} | [
"func",
"(",
"r",
"*",
"sampleRing",
")",
"add",
"(",
"t",
"int64",
",",
"v",
"float64",
")",
"{",
"l",
":=",
"len",
"(",
"r",
".",
"buf",
")",
"\n",
"if",
"l",
"==",
"r",
".",
"l",
"{",
"buf",
":=",
"make",
"(",
"[",
"]",
"sample",
",",
... | // add adds a sample to the ring buffer and frees all samples that fall
// out of the delta range. | [
"add",
"adds",
"a",
"sample",
"to",
"the",
"ring",
"buffer",
"and",
"frees",
"all",
"samples",
"that",
"fall",
"out",
"of",
"the",
"delta",
"range",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/tsdbutil/buffer.go#L182-L211 | train |
prometheus/tsdb | tsdbutil/buffer.go | last | func (r *sampleRing) last() (int64, float64, bool) {
if r.l == 0 {
return 0, 0, false
}
s := r.buf[r.i]
return s.t, s.v, true
} | go | func (r *sampleRing) last() (int64, float64, bool) {
if r.l == 0 {
return 0, 0, false
}
s := r.buf[r.i]
return s.t, s.v, true
} | [
"func",
"(",
"r",
"*",
"sampleRing",
")",
"last",
"(",
")",
"(",
"int64",
",",
"float64",
",",
"bool",
")",
"{",
"if",
"r",
".",
"l",
"==",
"0",
"{",
"return",
"0",
",",
"0",
",",
"false",
"\n",
"}",
"\n",
"s",
":=",
"r",
".",
"buf",
"[",
... | // last returns the most recent element added to the ring. | [
"last",
"returns",
"the",
"most",
"recent",
"element",
"added",
"to",
"the",
"ring",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/tsdbutil/buffer.go#L214-L220 | train |
prometheus/tsdb | labels/labels.go | Equals | func (ls Labels) Equals(o Labels) bool {
if len(ls) != len(o) {
return false
}
for i, l := range ls {
if o[i] != l {
return false
}
}
return true
} | go | func (ls Labels) Equals(o Labels) bool {
if len(ls) != len(o) {
return false
}
for i, l := range ls {
if o[i] != l {
return false
}
}
return true
} | [
"func",
"(",
"ls",
"Labels",
")",
"Equals",
"(",
"o",
"Labels",
")",
"bool",
"{",
"if",
"len",
"(",
"ls",
")",
"!=",
"len",
"(",
"o",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"i",
",",
"l",
":=",
"range",
"ls",
"{",
"if",
"o",
"... | // Equals returns whether the two label sets are equal. | [
"Equals",
"returns",
"whether",
"the",
"two",
"label",
"sets",
"are",
"equal",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/labels/labels.go#L85-L95 | train |
prometheus/tsdb | labels/labels.go | FromMap | func FromMap(m map[string]string) Labels {
l := make(Labels, 0, len(m))
for k, v := range m {
l = append(l, Label{Name: k, Value: v})
}
sort.Sort(l)
return l
} | go | func FromMap(m map[string]string) Labels {
l := make(Labels, 0, len(m))
for k, v := range m {
l = append(l, Label{Name: k, Value: v})
}
sort.Sort(l)
return l
} | [
"func",
"FromMap",
"(",
"m",
"map",
"[",
"string",
"]",
"string",
")",
"Labels",
"{",
"l",
":=",
"make",
"(",
"Labels",
",",
"0",
",",
"len",
"(",
"m",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"m",
"{",
"l",
"=",
"append",
"(",
... | // FromMap returns new sorted Labels from the given map. | [
"FromMap",
"returns",
"new",
"sorted",
"Labels",
"from",
"the",
"given",
"map",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/labels/labels.go#L119-L127 | train |
prometheus/tsdb | labels/labels.go | ReadLabels | func ReadLabels(fn string, n int) ([]Labels, error) {
f, err := os.Open(fn)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
var mets []Labels
hashes := map[uint64]struct{}{}
i := 0
for scanner.Scan() && i < n {
m := make(Labels, 0, 10)
r := strings.NewReplacer("\"", "", "{", "", "}", "")
s := r.Replace(scanner.Text())
labelChunks := strings.Split(s, ",")
for _, labelChunk := range labelChunks {
split := strings.Split(labelChunk, ":")
m = append(m, Label{Name: split[0], Value: split[1]})
}
// Order of the k/v labels matters, don't assume we'll always receive them already sorted.
sort.Sort(m)
h := m.Hash()
if _, ok := hashes[h]; ok {
continue
}
mets = append(mets, m)
hashes[h] = struct{}{}
i++
}
if i != n {
return mets, errors.Errorf("requested %d metrics but found %d", n, i)
}
return mets, nil
} | go | func ReadLabels(fn string, n int) ([]Labels, error) {
f, err := os.Open(fn)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
var mets []Labels
hashes := map[uint64]struct{}{}
i := 0
for scanner.Scan() && i < n {
m := make(Labels, 0, 10)
r := strings.NewReplacer("\"", "", "{", "", "}", "")
s := r.Replace(scanner.Text())
labelChunks := strings.Split(s, ",")
for _, labelChunk := range labelChunks {
split := strings.Split(labelChunk, ":")
m = append(m, Label{Name: split[0], Value: split[1]})
}
// Order of the k/v labels matters, don't assume we'll always receive them already sorted.
sort.Sort(m)
h := m.Hash()
if _, ok := hashes[h]; ok {
continue
}
mets = append(mets, m)
hashes[h] = struct{}{}
i++
}
if i != n {
return mets, errors.Errorf("requested %d metrics but found %d", n, i)
}
return mets, nil
} | [
"func",
"ReadLabels",
"(",
"fn",
"string",
",",
"n",
"int",
")",
"(",
"[",
"]",
"Labels",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"fn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n"... | // ReadLabels reads up to n label sets in a JSON formatted file fn. It is mostly useful
// to load testing data. | [
"ReadLabels",
"reads",
"up",
"to",
"n",
"label",
"sets",
"in",
"a",
"JSON",
"formatted",
"file",
"fn",
".",
"It",
"is",
"mostly",
"useful",
"to",
"load",
"testing",
"data",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/labels/labels.go#L172-L212 | train |
prometheus/tsdb | head.go | NewHead | func NewHead(r prometheus.Registerer, l log.Logger, wal *wal.WAL, chunkRange int64) (*Head, error) {
if l == nil {
l = log.NewNopLogger()
}
if chunkRange < 1 {
return nil, errors.Errorf("invalid chunk range %d", chunkRange)
}
h := &Head{
wal: wal,
logger: l,
chunkRange: chunkRange,
minTime: math.MaxInt64,
maxTime: math.MinInt64,
series: newStripeSeries(),
values: map[string]stringset{},
symbols: map[string]struct{}{},
postings: index.NewUnorderedMemPostings(),
deleted: map[uint64]int{},
}
h.metrics = newHeadMetrics(h, r)
return h, nil
} | go | func NewHead(r prometheus.Registerer, l log.Logger, wal *wal.WAL, chunkRange int64) (*Head, error) {
if l == nil {
l = log.NewNopLogger()
}
if chunkRange < 1 {
return nil, errors.Errorf("invalid chunk range %d", chunkRange)
}
h := &Head{
wal: wal,
logger: l,
chunkRange: chunkRange,
minTime: math.MaxInt64,
maxTime: math.MinInt64,
series: newStripeSeries(),
values: map[string]stringset{},
symbols: map[string]struct{}{},
postings: index.NewUnorderedMemPostings(),
deleted: map[uint64]int{},
}
h.metrics = newHeadMetrics(h, r)
return h, nil
} | [
"func",
"NewHead",
"(",
"r",
"prometheus",
".",
"Registerer",
",",
"l",
"log",
".",
"Logger",
",",
"wal",
"*",
"wal",
".",
"WAL",
",",
"chunkRange",
"int64",
")",
"(",
"*",
"Head",
",",
"error",
")",
"{",
"if",
"l",
"==",
"nil",
"{",
"l",
"=",
... | // NewHead opens the head block in dir. | [
"NewHead",
"opens",
"the",
"head",
"block",
"in",
"dir",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L223-L245 | train |
prometheus/tsdb | head.go | processWALSamples | func (h *Head) processWALSamples(
minValidTime int64,
input <-chan []RefSample, output chan<- []RefSample,
) (unknownRefs uint64) {
defer close(output)
// Mitigate lock contention in getByID.
refSeries := map[uint64]*memSeries{}
mint, maxt := int64(math.MaxInt64), int64(math.MinInt64)
for samples := range input {
for _, s := range samples {
if s.T < minValidTime {
continue
}
ms := refSeries[s.Ref]
if ms == nil {
ms = h.series.getByID(s.Ref)
if ms == nil {
unknownRefs++
continue
}
refSeries[s.Ref] = ms
}
_, chunkCreated := ms.append(s.T, s.V)
if chunkCreated {
h.metrics.chunksCreated.Inc()
h.metrics.chunks.Inc()
}
if s.T > maxt {
maxt = s.T
}
if s.T < mint {
mint = s.T
}
}
output <- samples
}
h.updateMinMaxTime(mint, maxt)
return unknownRefs
} | go | func (h *Head) processWALSamples(
minValidTime int64,
input <-chan []RefSample, output chan<- []RefSample,
) (unknownRefs uint64) {
defer close(output)
// Mitigate lock contention in getByID.
refSeries := map[uint64]*memSeries{}
mint, maxt := int64(math.MaxInt64), int64(math.MinInt64)
for samples := range input {
for _, s := range samples {
if s.T < minValidTime {
continue
}
ms := refSeries[s.Ref]
if ms == nil {
ms = h.series.getByID(s.Ref)
if ms == nil {
unknownRefs++
continue
}
refSeries[s.Ref] = ms
}
_, chunkCreated := ms.append(s.T, s.V)
if chunkCreated {
h.metrics.chunksCreated.Inc()
h.metrics.chunks.Inc()
}
if s.T > maxt {
maxt = s.T
}
if s.T < mint {
mint = s.T
}
}
output <- samples
}
h.updateMinMaxTime(mint, maxt)
return unknownRefs
} | [
"func",
"(",
"h",
"*",
"Head",
")",
"processWALSamples",
"(",
"minValidTime",
"int64",
",",
"input",
"<-",
"chan",
"[",
"]",
"RefSample",
",",
"output",
"chan",
"<-",
"[",
"]",
"RefSample",
",",
")",
"(",
"unknownRefs",
"uint64",
")",
"{",
"defer",
"cl... | // processWALSamples adds a partition of samples it receives to the head and passes
// them on to other workers.
// Samples before the mint timestamp are discarded. | [
"processWALSamples",
"adds",
"a",
"partition",
"of",
"samples",
"it",
"receives",
"to",
"the",
"head",
"and",
"passes",
"them",
"on",
"to",
"other",
"workers",
".",
"Samples",
"before",
"the",
"mint",
"timestamp",
"are",
"discarded",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L250-L292 | train |
prometheus/tsdb | head.go | Init | func (h *Head) Init(minValidTime int64) error {
h.minValidTime = minValidTime
defer h.postings.EnsureOrder()
defer h.gc() // After loading the wal remove the obsolete data from the head.
if h.wal == nil {
return nil
}
// Backfill the checkpoint first if it exists.
dir, startFrom, err := LastCheckpoint(h.wal.Dir())
if err != nil && err != ErrNotFound {
return errors.Wrap(err, "find last checkpoint")
}
if err == nil {
sr, err := wal.NewSegmentsReader(dir)
if err != nil {
return errors.Wrap(err, "open checkpoint")
}
defer sr.Close()
// A corrupted checkpoint is a hard error for now and requires user
// intervention. There's likely little data that can be recovered anyway.
if err := h.loadWAL(wal.NewReader(sr)); err != nil {
return errors.Wrap(err, "backfill checkpoint")
}
startFrom++
}
// Backfill segments from the last checkpoint onwards
sr, err := wal.NewSegmentsRangeReader(wal.SegmentRange{Dir: h.wal.Dir(), First: startFrom, Last: -1})
if err != nil {
return errors.Wrap(err, "open WAL segments")
}
err = h.loadWAL(wal.NewReader(sr))
sr.Close() // Close the reader so that if there was an error the repair can remove the corrupted file under Windows.
if err == nil {
return nil
}
level.Warn(h.logger).Log("msg", "encountered WAL error, attempting repair", "err", err)
h.metrics.walCorruptionsTotal.Inc()
if err := h.wal.Repair(err); err != nil {
return errors.Wrap(err, "repair corrupted WAL")
}
return nil
} | go | func (h *Head) Init(minValidTime int64) error {
h.minValidTime = minValidTime
defer h.postings.EnsureOrder()
defer h.gc() // After loading the wal remove the obsolete data from the head.
if h.wal == nil {
return nil
}
// Backfill the checkpoint first if it exists.
dir, startFrom, err := LastCheckpoint(h.wal.Dir())
if err != nil && err != ErrNotFound {
return errors.Wrap(err, "find last checkpoint")
}
if err == nil {
sr, err := wal.NewSegmentsReader(dir)
if err != nil {
return errors.Wrap(err, "open checkpoint")
}
defer sr.Close()
// A corrupted checkpoint is a hard error for now and requires user
// intervention. There's likely little data that can be recovered anyway.
if err := h.loadWAL(wal.NewReader(sr)); err != nil {
return errors.Wrap(err, "backfill checkpoint")
}
startFrom++
}
// Backfill segments from the last checkpoint onwards
sr, err := wal.NewSegmentsRangeReader(wal.SegmentRange{Dir: h.wal.Dir(), First: startFrom, Last: -1})
if err != nil {
return errors.Wrap(err, "open WAL segments")
}
err = h.loadWAL(wal.NewReader(sr))
sr.Close() // Close the reader so that if there was an error the repair can remove the corrupted file under Windows.
if err == nil {
return nil
}
level.Warn(h.logger).Log("msg", "encountered WAL error, attempting repair", "err", err)
h.metrics.walCorruptionsTotal.Inc()
if err := h.wal.Repair(err); err != nil {
return errors.Wrap(err, "repair corrupted WAL")
}
return nil
} | [
"func",
"(",
"h",
"*",
"Head",
")",
"Init",
"(",
"minValidTime",
"int64",
")",
"error",
"{",
"h",
".",
"minValidTime",
"=",
"minValidTime",
"\n",
"defer",
"h",
".",
"postings",
".",
"EnsureOrder",
"(",
")",
"\n",
"defer",
"h",
".",
"gc",
"(",
")",
... | // Init loads data from the write ahead log and prepares the head for writes.
// It should be called before using an appender so that
// limits the ingested samples to the head min valid time. | [
"Init",
"loads",
"data",
"from",
"the",
"write",
"ahead",
"log",
"and",
"prepares",
"the",
"head",
"for",
"writes",
".",
"It",
"should",
"be",
"called",
"before",
"using",
"an",
"appender",
"so",
"that",
"limits",
"the",
"ingested",
"samples",
"to",
"the",... | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L462-L508 | train |
prometheus/tsdb | head.go | initTime | func (h *Head) initTime(t int64) (initialized bool) {
if !atomic.CompareAndSwapInt64(&h.minTime, math.MaxInt64, t) {
return false
}
// Ensure that max time is initialized to at least the min time we just set.
// Concurrent appenders may already have set it to a higher value.
atomic.CompareAndSwapInt64(&h.maxTime, math.MinInt64, t)
return true
} | go | func (h *Head) initTime(t int64) (initialized bool) {
if !atomic.CompareAndSwapInt64(&h.minTime, math.MaxInt64, t) {
return false
}
// Ensure that max time is initialized to at least the min time we just set.
// Concurrent appenders may already have set it to a higher value.
atomic.CompareAndSwapInt64(&h.maxTime, math.MinInt64, t)
return true
} | [
"func",
"(",
"h",
"*",
"Head",
")",
"initTime",
"(",
"t",
"int64",
")",
"(",
"initialized",
"bool",
")",
"{",
"if",
"!",
"atomic",
".",
"CompareAndSwapInt64",
"(",
"&",
"h",
".",
"minTime",
",",
"math",
".",
"MaxInt64",
",",
"t",
")",
"{",
"return"... | // initTime initializes a head with the first timestamp. This only needs to be called
// for a completely fresh head with an empty WAL.
// Returns true if the initialization took an effect. | [
"initTime",
"initializes",
"a",
"head",
"with",
"the",
"first",
"timestamp",
".",
"This",
"only",
"needs",
"to",
"be",
"called",
"for",
"a",
"completely",
"fresh",
"head",
"with",
"an",
"empty",
"WAL",
".",
"Returns",
"true",
"if",
"the",
"initialization",
... | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L613-L622 | train |
prometheus/tsdb | head.go | Appender | func (h *Head) Appender() Appender {
h.metrics.activeAppenders.Inc()
// The head cache might not have a starting point yet. The init appender
// picks up the first appended timestamp as the base.
if h.MinTime() == math.MaxInt64 {
return &initAppender{head: h}
}
return h.appender()
} | go | func (h *Head) Appender() Appender {
h.metrics.activeAppenders.Inc()
// The head cache might not have a starting point yet. The init appender
// picks up the first appended timestamp as the base.
if h.MinTime() == math.MaxInt64 {
return &initAppender{head: h}
}
return h.appender()
} | [
"func",
"(",
"h",
"*",
"Head",
")",
"Appender",
"(",
")",
"Appender",
"{",
"h",
".",
"metrics",
".",
"activeAppenders",
".",
"Inc",
"(",
")",
"\n",
"if",
"h",
".",
"MinTime",
"(",
")",
"==",
"math",
".",
"MaxInt64",
"{",
"return",
"&",
"initAppende... | // Appender returns a new Appender on the database. | [
"Appender",
"returns",
"a",
"new",
"Appender",
"on",
"the",
"database",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L688-L697 | train |
prometheus/tsdb | head.go | chunkRewrite | func (h *Head) chunkRewrite(ref uint64, dranges Intervals) (err error) {
if len(dranges) == 0 {
return nil
}
ms := h.series.getByID(ref)
ms.Lock()
defer ms.Unlock()
if len(ms.chunks) == 0 {
return nil
}
metas := ms.chunksMetas()
mint, maxt := metas[0].MinTime, metas[len(metas)-1].MaxTime
it := newChunkSeriesIterator(metas, dranges, mint, maxt)
ms.reset()
for it.Next() {
t, v := it.At()
ok, _ := ms.append(t, v)
if !ok {
level.Warn(h.logger).Log("msg", "failed to add sample during delete")
}
}
return nil
} | go | func (h *Head) chunkRewrite(ref uint64, dranges Intervals) (err error) {
if len(dranges) == 0 {
return nil
}
ms := h.series.getByID(ref)
ms.Lock()
defer ms.Unlock()
if len(ms.chunks) == 0 {
return nil
}
metas := ms.chunksMetas()
mint, maxt := metas[0].MinTime, metas[len(metas)-1].MaxTime
it := newChunkSeriesIterator(metas, dranges, mint, maxt)
ms.reset()
for it.Next() {
t, v := it.At()
ok, _ := ms.append(t, v)
if !ok {
level.Warn(h.logger).Log("msg", "failed to add sample during delete")
}
}
return nil
} | [
"func",
"(",
"h",
"*",
"Head",
")",
"chunkRewrite",
"(",
"ref",
"uint64",
",",
"dranges",
"Intervals",
")",
"(",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"dranges",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"ms",
":=",
"h",
".",
... | // chunkRewrite re-writes the chunks which overlaps with deleted ranges
// and removes the samples in the deleted ranges.
// Chunks is deleted if no samples are left at the end. | [
"chunkRewrite",
"re",
"-",
"writes",
"the",
"chunks",
"which",
"overlaps",
"with",
"deleted",
"ranges",
"and",
"removes",
"the",
"samples",
"in",
"the",
"deleted",
"ranges",
".",
"Chunks",
"is",
"deleted",
"if",
"no",
"samples",
"are",
"left",
"at",
"the",
... | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L931-L957 | train |
prometheus/tsdb | head.go | gc | func (h *Head) gc() {
// Only data strictly lower than this timestamp must be deleted.
mint := h.MinTime()
// Drop old chunks and remember series IDs and hashes if they can be
// deleted entirely.
deleted, chunksRemoved := h.series.gc(mint)
seriesRemoved := len(deleted)
h.metrics.seriesRemoved.Add(float64(seriesRemoved))
h.metrics.series.Sub(float64(seriesRemoved))
h.metrics.chunksRemoved.Add(float64(chunksRemoved))
h.metrics.chunks.Sub(float64(chunksRemoved))
// Remove deleted series IDs from the postings lists.
h.postings.Delete(deleted)
if h.wal != nil {
_, last, _ := h.wal.Segments()
h.deletedMtx.Lock()
// Keep series records until we're past segment 'last'
// because the WAL will still have samples records with
// this ref ID. If we didn't keep these series records then
// on start up when we replay the WAL, or any other code
// that reads the WAL, wouldn't be able to use those
// samples since we would have no labels for that ref ID.
for ref := range deleted {
h.deleted[ref] = last
}
h.deletedMtx.Unlock()
}
// Rebuild symbols and label value indices from what is left in the postings terms.
symbols := make(map[string]struct{}, len(h.symbols))
values := make(map[string]stringset, len(h.values))
if err := h.postings.Iter(func(t labels.Label, _ index.Postings) error {
symbols[t.Name] = struct{}{}
symbols[t.Value] = struct{}{}
ss, ok := values[t.Name]
if !ok {
ss = stringset{}
values[t.Name] = ss
}
ss.set(t.Value)
return nil
}); err != nil {
// This should never happen, as the iteration function only returns nil.
panic(err)
}
h.symMtx.Lock()
h.symbols = symbols
h.values = values
h.symMtx.Unlock()
} | go | func (h *Head) gc() {
// Only data strictly lower than this timestamp must be deleted.
mint := h.MinTime()
// Drop old chunks and remember series IDs and hashes if they can be
// deleted entirely.
deleted, chunksRemoved := h.series.gc(mint)
seriesRemoved := len(deleted)
h.metrics.seriesRemoved.Add(float64(seriesRemoved))
h.metrics.series.Sub(float64(seriesRemoved))
h.metrics.chunksRemoved.Add(float64(chunksRemoved))
h.metrics.chunks.Sub(float64(chunksRemoved))
// Remove deleted series IDs from the postings lists.
h.postings.Delete(deleted)
if h.wal != nil {
_, last, _ := h.wal.Segments()
h.deletedMtx.Lock()
// Keep series records until we're past segment 'last'
// because the WAL will still have samples records with
// this ref ID. If we didn't keep these series records then
// on start up when we replay the WAL, or any other code
// that reads the WAL, wouldn't be able to use those
// samples since we would have no labels for that ref ID.
for ref := range deleted {
h.deleted[ref] = last
}
h.deletedMtx.Unlock()
}
// Rebuild symbols and label value indices from what is left in the postings terms.
symbols := make(map[string]struct{}, len(h.symbols))
values := make(map[string]stringset, len(h.values))
if err := h.postings.Iter(func(t labels.Label, _ index.Postings) error {
symbols[t.Name] = struct{}{}
symbols[t.Value] = struct{}{}
ss, ok := values[t.Name]
if !ok {
ss = stringset{}
values[t.Name] = ss
}
ss.set(t.Value)
return nil
}); err != nil {
// This should never happen, as the iteration function only returns nil.
panic(err)
}
h.symMtx.Lock()
h.symbols = symbols
h.values = values
h.symMtx.Unlock()
} | [
"func",
"(",
"h",
"*",
"Head",
")",
"gc",
"(",
")",
"{",
"mint",
":=",
"h",
".",
"MinTime",
"(",
")",
"\n",
"deleted",
",",
"chunksRemoved",
":=",
"h",
".",
"series",
".",
"gc",
"(",
"mint",
")",
"\n",
"seriesRemoved",
":=",
"len",
"(",
"deleted"... | // gc removes data before the minimum timestamp from the head. | [
"gc",
"removes",
"data",
"before",
"the",
"minimum",
"timestamp",
"from",
"the",
"head",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L960-L1018 | train |
prometheus/tsdb | head.go | Index | func (h *Head) Index() (IndexReader, error) {
return h.indexRange(math.MinInt64, math.MaxInt64), nil
} | go | func (h *Head) Index() (IndexReader, error) {
return h.indexRange(math.MinInt64, math.MaxInt64), nil
} | [
"func",
"(",
"h",
"*",
"Head",
")",
"Index",
"(",
")",
"(",
"IndexReader",
",",
"error",
")",
"{",
"return",
"h",
".",
"indexRange",
"(",
"math",
".",
"MinInt64",
",",
"math",
".",
"MaxInt64",
")",
",",
"nil",
"\n",
"}"
] | // Index returns an IndexReader against the block. | [
"Index",
"returns",
"an",
"IndexReader",
"against",
"the",
"block",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1026-L1028 | train |
prometheus/tsdb | head.go | Chunks | func (h *Head) Chunks() (ChunkReader, error) {
return h.chunksRange(math.MinInt64, math.MaxInt64), nil
} | go | func (h *Head) Chunks() (ChunkReader, error) {
return h.chunksRange(math.MinInt64, math.MaxInt64), nil
} | [
"func",
"(",
"h",
"*",
"Head",
")",
"Chunks",
"(",
")",
"(",
"ChunkReader",
",",
"error",
")",
"{",
"return",
"h",
".",
"chunksRange",
"(",
"math",
".",
"MinInt64",
",",
"math",
".",
"MaxInt64",
")",
",",
"nil",
"\n",
"}"
] | // Chunks returns a ChunkReader against the block. | [
"Chunks",
"returns",
"a",
"ChunkReader",
"against",
"the",
"block",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1038-L1040 | train |
prometheus/tsdb | head.go | compactable | func (h *Head) compactable() bool {
return h.MaxTime()-h.MinTime() > h.chunkRange/2*3
} | go | func (h *Head) compactable() bool {
return h.MaxTime()-h.MinTime() > h.chunkRange/2*3
} | [
"func",
"(",
"h",
"*",
"Head",
")",
"compactable",
"(",
")",
"bool",
"{",
"return",
"h",
".",
"MaxTime",
"(",
")",
"-",
"h",
".",
"MinTime",
"(",
")",
">",
"h",
".",
"chunkRange",
"/",
"2",
"*",
"3",
"\n",
"}"
] | // compactable returns whether the head has a compactable range.
// The head has a compactable range when the head time range is 1.5 times the chunk range.
// The 0.5 acts as a buffer of the appendable window. | [
"compactable",
"returns",
"whether",
"the",
"head",
"has",
"a",
"compactable",
"range",
".",
"The",
"head",
"has",
"a",
"compactable",
"range",
"when",
"the",
"head",
"time",
"range",
"is",
"1",
".",
"5",
"times",
"the",
"chunk",
"range",
".",
"The",
"0"... | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1062-L1064 | train |
prometheus/tsdb | head.go | Close | func (h *Head) Close() error {
if h.wal == nil {
return nil
}
return h.wal.Close()
} | go | func (h *Head) Close() error {
if h.wal == nil {
return nil
}
return h.wal.Close()
} | [
"func",
"(",
"h",
"*",
"Head",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"h",
".",
"wal",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"h",
".",
"wal",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Close flushes the WAL and closes the head. | [
"Close",
"flushes",
"the",
"WAL",
"and",
"closes",
"the",
"head",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1067-L1072 | train |
prometheus/tsdb | head.go | packChunkID | func packChunkID(seriesID, chunkID uint64) uint64 {
if seriesID > (1<<40)-1 {
panic("series ID exceeds 5 bytes")
}
if chunkID > (1<<24)-1 {
panic("chunk ID exceeds 3 bytes")
}
return (seriesID << 24) | chunkID
} | go | func packChunkID(seriesID, chunkID uint64) uint64 {
if seriesID > (1<<40)-1 {
panic("series ID exceeds 5 bytes")
}
if chunkID > (1<<24)-1 {
panic("chunk ID exceeds 3 bytes")
}
return (seriesID << 24) | chunkID
} | [
"func",
"packChunkID",
"(",
"seriesID",
",",
"chunkID",
"uint64",
")",
"uint64",
"{",
"if",
"seriesID",
">",
"(",
"1",
"<<",
"40",
")",
"-",
"1",
"{",
"panic",
"(",
"\"series ID exceeds 5 bytes\"",
")",
"\n",
"}",
"\n",
"if",
"chunkID",
">",
"(",
"1",
... | // packChunkID packs a seriesID and a chunkID within it into a global 8 byte ID.
// It panicks if the seriesID exceeds 5 bytes or the chunk ID 3 bytes. | [
"packChunkID",
"packs",
"a",
"seriesID",
"and",
"a",
"chunkID",
"within",
"it",
"into",
"a",
"global",
"8",
"byte",
"ID",
".",
"It",
"panicks",
"if",
"the",
"seriesID",
"exceeds",
"5",
"bytes",
"or",
"the",
"chunk",
"ID",
"3",
"bytes",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1085-L1093 | train |
prometheus/tsdb | head.go | Chunk | func (h *headChunkReader) Chunk(ref uint64) (chunkenc.Chunk, error) {
sid, cid := unpackChunkID(ref)
s := h.head.series.getByID(sid)
// This means that the series has been garbage collected.
if s == nil {
return nil, ErrNotFound
}
s.Lock()
c := s.chunk(int(cid))
// This means that the chunk has been garbage collected or is outside
// the specified range.
if c == nil || !c.OverlapsClosedInterval(h.mint, h.maxt) {
s.Unlock()
return nil, ErrNotFound
}
s.Unlock()
return &safeChunk{
Chunk: c.chunk,
s: s,
cid: int(cid),
}, nil
} | go | func (h *headChunkReader) Chunk(ref uint64) (chunkenc.Chunk, error) {
sid, cid := unpackChunkID(ref)
s := h.head.series.getByID(sid)
// This means that the series has been garbage collected.
if s == nil {
return nil, ErrNotFound
}
s.Lock()
c := s.chunk(int(cid))
// This means that the chunk has been garbage collected or is outside
// the specified range.
if c == nil || !c.OverlapsClosedInterval(h.mint, h.maxt) {
s.Unlock()
return nil, ErrNotFound
}
s.Unlock()
return &safeChunk{
Chunk: c.chunk,
s: s,
cid: int(cid),
}, nil
} | [
"func",
"(",
"h",
"*",
"headChunkReader",
")",
"Chunk",
"(",
"ref",
"uint64",
")",
"(",
"chunkenc",
".",
"Chunk",
",",
"error",
")",
"{",
"sid",
",",
"cid",
":=",
"unpackChunkID",
"(",
"ref",
")",
"\n",
"s",
":=",
"h",
".",
"head",
".",
"series",
... | // Chunk returns the chunk for the reference number. | [
"Chunk",
"returns",
"the",
"chunk",
"for",
"the",
"reference",
"number",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1100-L1125 | train |
prometheus/tsdb | head.go | LabelValues | func (h *headIndexReader) LabelValues(names ...string) (index.StringTuples, error) {
if len(names) != 1 {
return nil, encoding.ErrInvalidSize
}
h.head.symMtx.RLock()
sl := make([]string, 0, len(h.head.values[names[0]]))
for s := range h.head.values[names[0]] {
sl = append(sl, s)
}
h.head.symMtx.RUnlock()
sort.Strings(sl)
return index.NewStringTuples(sl, len(names))
} | go | func (h *headIndexReader) LabelValues(names ...string) (index.StringTuples, error) {
if len(names) != 1 {
return nil, encoding.ErrInvalidSize
}
h.head.symMtx.RLock()
sl := make([]string, 0, len(h.head.values[names[0]]))
for s := range h.head.values[names[0]] {
sl = append(sl, s)
}
h.head.symMtx.RUnlock()
sort.Strings(sl)
return index.NewStringTuples(sl, len(names))
} | [
"func",
"(",
"h",
"*",
"headIndexReader",
")",
"LabelValues",
"(",
"names",
"...",
"string",
")",
"(",
"index",
".",
"StringTuples",
",",
"error",
")",
"{",
"if",
"len",
"(",
"names",
")",
"!=",
"1",
"{",
"return",
"nil",
",",
"encoding",
".",
"ErrIn... | // LabelValues returns the possible label values | [
"LabelValues",
"returns",
"the",
"possible",
"label",
"values"
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1162-L1176 | train |
prometheus/tsdb | head.go | LabelNames | func (h *headIndexReader) LabelNames() ([]string, error) {
h.head.symMtx.RLock()
defer h.head.symMtx.RUnlock()
labelNames := make([]string, 0, len(h.head.values))
for name := range h.head.values {
if name == "" {
continue
}
labelNames = append(labelNames, name)
}
sort.Strings(labelNames)
return labelNames, nil
} | go | func (h *headIndexReader) LabelNames() ([]string, error) {
h.head.symMtx.RLock()
defer h.head.symMtx.RUnlock()
labelNames := make([]string, 0, len(h.head.values))
for name := range h.head.values {
if name == "" {
continue
}
labelNames = append(labelNames, name)
}
sort.Strings(labelNames)
return labelNames, nil
} | [
"func",
"(",
"h",
"*",
"headIndexReader",
")",
"LabelNames",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"h",
".",
"head",
".",
"symMtx",
".",
"RLock",
"(",
")",
"\n",
"defer",
"h",
".",
"head",
".",
"symMtx",
".",
"RUnlock",
"(",
... | // LabelNames returns all the unique label names present in the head. | [
"LabelNames",
"returns",
"all",
"the",
"unique",
"label",
"names",
"present",
"in",
"the",
"head",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1179-L1191 | train |
prometheus/tsdb | head.go | Postings | func (h *headIndexReader) Postings(name, value string) (index.Postings, error) {
return h.head.postings.Get(name, value), nil
} | go | func (h *headIndexReader) Postings(name, value string) (index.Postings, error) {
return h.head.postings.Get(name, value), nil
} | [
"func",
"(",
"h",
"*",
"headIndexReader",
")",
"Postings",
"(",
"name",
",",
"value",
"string",
")",
"(",
"index",
".",
"Postings",
",",
"error",
")",
"{",
"return",
"h",
".",
"head",
".",
"postings",
".",
"Get",
"(",
"name",
",",
"value",
")",
","... | // Postings returns the postings list iterator for the label pair. | [
"Postings",
"returns",
"the",
"postings",
"list",
"iterator",
"for",
"the",
"label",
"pair",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1194-L1196 | train |
prometheus/tsdb | head.go | Series | func (h *headIndexReader) Series(ref uint64, lbls *labels.Labels, chks *[]chunks.Meta) error {
s := h.head.series.getByID(ref)
if s == nil {
h.head.metrics.seriesNotFound.Inc()
return ErrNotFound
}
*lbls = append((*lbls)[:0], s.lset...)
s.Lock()
defer s.Unlock()
*chks = (*chks)[:0]
for i, c := range s.chunks {
// Do not expose chunks that are outside of the specified range.
if !c.OverlapsClosedInterval(h.mint, h.maxt) {
continue
}
*chks = append(*chks, chunks.Meta{
MinTime: c.minTime,
MaxTime: c.maxTime,
Ref: packChunkID(s.ref, uint64(s.chunkID(i))),
})
}
return nil
} | go | func (h *headIndexReader) Series(ref uint64, lbls *labels.Labels, chks *[]chunks.Meta) error {
s := h.head.series.getByID(ref)
if s == nil {
h.head.metrics.seriesNotFound.Inc()
return ErrNotFound
}
*lbls = append((*lbls)[:0], s.lset...)
s.Lock()
defer s.Unlock()
*chks = (*chks)[:0]
for i, c := range s.chunks {
// Do not expose chunks that are outside of the specified range.
if !c.OverlapsClosedInterval(h.mint, h.maxt) {
continue
}
*chks = append(*chks, chunks.Meta{
MinTime: c.minTime,
MaxTime: c.maxTime,
Ref: packChunkID(s.ref, uint64(s.chunkID(i))),
})
}
return nil
} | [
"func",
"(",
"h",
"*",
"headIndexReader",
")",
"Series",
"(",
"ref",
"uint64",
",",
"lbls",
"*",
"labels",
".",
"Labels",
",",
"chks",
"*",
"[",
"]",
"chunks",
".",
"Meta",
")",
"error",
"{",
"s",
":=",
"h",
".",
"head",
".",
"series",
".",
"getB... | // Series returns the series for the given reference. | [
"Series",
"returns",
"the",
"series",
"for",
"the",
"given",
"reference",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1227-L1254 | train |
prometheus/tsdb | head.go | gc | func (s *stripeSeries) gc(mint int64) (map[uint64]struct{}, int) {
var (
deleted = map[uint64]struct{}{}
rmChunks = 0
)
// Run through all series and truncate old chunks. Mark those with no
// chunks left as deleted and store their ID.
for i := 0; i < stripeSize; i++ {
s.locks[i].Lock()
for hash, all := range s.hashes[i] {
for _, series := range all {
series.Lock()
rmChunks += series.truncateChunksBefore(mint)
if len(series.chunks) > 0 || series.pendingCommit {
series.Unlock()
continue
}
// The series is gone entirely. We need to keep the series lock
// and make sure we have acquired the stripe locks for hash and ID of the
// series alike.
// If we don't hold them all, there's a very small chance that a series receives
// samples again while we are half-way into deleting it.
j := int(series.ref & stripeMask)
if i != j {
s.locks[j].Lock()
}
deleted[series.ref] = struct{}{}
s.hashes[i].del(hash, series.lset)
delete(s.series[j], series.ref)
if i != j {
s.locks[j].Unlock()
}
series.Unlock()
}
}
s.locks[i].Unlock()
}
return deleted, rmChunks
} | go | func (s *stripeSeries) gc(mint int64) (map[uint64]struct{}, int) {
var (
deleted = map[uint64]struct{}{}
rmChunks = 0
)
// Run through all series and truncate old chunks. Mark those with no
// chunks left as deleted and store their ID.
for i := 0; i < stripeSize; i++ {
s.locks[i].Lock()
for hash, all := range s.hashes[i] {
for _, series := range all {
series.Lock()
rmChunks += series.truncateChunksBefore(mint)
if len(series.chunks) > 0 || series.pendingCommit {
series.Unlock()
continue
}
// The series is gone entirely. We need to keep the series lock
// and make sure we have acquired the stripe locks for hash and ID of the
// series alike.
// If we don't hold them all, there's a very small chance that a series receives
// samples again while we are half-way into deleting it.
j := int(series.ref & stripeMask)
if i != j {
s.locks[j].Lock()
}
deleted[series.ref] = struct{}{}
s.hashes[i].del(hash, series.lset)
delete(s.series[j], series.ref)
if i != j {
s.locks[j].Unlock()
}
series.Unlock()
}
}
s.locks[i].Unlock()
}
return deleted, rmChunks
} | [
"func",
"(",
"s",
"*",
"stripeSeries",
")",
"gc",
"(",
"mint",
"int64",
")",
"(",
"map",
"[",
"uint64",
"]",
"struct",
"{",
"}",
",",
"int",
")",
"{",
"var",
"(",
"deleted",
"=",
"map",
"[",
"uint64",
"]",
"struct",
"{",
"}",
"{",
"}",
"\n",
... | // gc garbage collects old chunks that are strictly before mint and removes
// series entirely that have no chunks left. | [
"gc",
"garbage",
"collects",
"old",
"chunks",
"that",
"are",
"strictly",
"before",
"mint",
"and",
"removes",
"series",
"entirely",
"that",
"have",
"no",
"chunks",
"left",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1387-L1434 | train |
prometheus/tsdb | head.go | appendable | func (s *memSeries) appendable(t int64, v float64) error {
c := s.head()
if c == nil {
return nil
}
if t > c.maxTime {
return nil
}
if t < c.maxTime {
return ErrOutOfOrderSample
}
// We are allowing exact duplicates as we can encounter them in valid cases
// like federation and erroring out at that time would be extremely noisy.
if math.Float64bits(s.sampleBuf[3].v) != math.Float64bits(v) {
return ErrAmendSample
}
return nil
} | go | func (s *memSeries) appendable(t int64, v float64) error {
c := s.head()
if c == nil {
return nil
}
if t > c.maxTime {
return nil
}
if t < c.maxTime {
return ErrOutOfOrderSample
}
// We are allowing exact duplicates as we can encounter them in valid cases
// like federation and erroring out at that time would be extremely noisy.
if math.Float64bits(s.sampleBuf[3].v) != math.Float64bits(v) {
return ErrAmendSample
}
return nil
} | [
"func",
"(",
"s",
"*",
"memSeries",
")",
"appendable",
"(",
"t",
"int64",
",",
"v",
"float64",
")",
"error",
"{",
"c",
":=",
"s",
".",
"head",
"(",
")",
"\n",
"if",
"c",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"t",
">",
"c",... | // appendable checks whether the given sample is valid for appending to the series. | [
"appendable",
"checks",
"whether",
"the",
"given",
"sample",
"is",
"valid",
"for",
"appending",
"to",
"the",
"series",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1576-L1594 | train |
prometheus/tsdb | head.go | truncateChunksBefore | func (s *memSeries) truncateChunksBefore(mint int64) (removed int) {
var k int
for i, c := range s.chunks {
if c.maxTime >= mint {
break
}
k = i + 1
}
s.chunks = append(s.chunks[:0], s.chunks[k:]...)
s.firstChunkID += k
if len(s.chunks) == 0 {
s.headChunk = nil
} else {
s.headChunk = s.chunks[len(s.chunks)-1]
}
return k
} | go | func (s *memSeries) truncateChunksBefore(mint int64) (removed int) {
var k int
for i, c := range s.chunks {
if c.maxTime >= mint {
break
}
k = i + 1
}
s.chunks = append(s.chunks[:0], s.chunks[k:]...)
s.firstChunkID += k
if len(s.chunks) == 0 {
s.headChunk = nil
} else {
s.headChunk = s.chunks[len(s.chunks)-1]
}
return k
} | [
"func",
"(",
"s",
"*",
"memSeries",
")",
"truncateChunksBefore",
"(",
"mint",
"int64",
")",
"(",
"removed",
"int",
")",
"{",
"var",
"k",
"int",
"\n",
"for",
"i",
",",
"c",
":=",
"range",
"s",
".",
"chunks",
"{",
"if",
"c",
".",
"maxTime",
">=",
"... | // truncateChunksBefore removes all chunks from the series that have not timestamp
// at or after mint. Chunk IDs remain unchanged. | [
"truncateChunksBefore",
"removes",
"all",
"chunks",
"from",
"the",
"series",
"that",
"have",
"not",
"timestamp",
"at",
"or",
"after",
"mint",
".",
"Chunk",
"IDs",
"remain",
"unchanged",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/head.go#L1610-L1627 | train |
prometheus/tsdb | wal/reader.go | Next | func (r *Reader) Next() bool {
err := r.next()
if errors.Cause(err) == io.EOF {
// The last WAL segment record shouldn't be torn(should be full or last).
// The last record would be torn after a crash just before
// the last record part could be persisted to disk.
if recType(r.curRecTyp) == recFirst || recType(r.curRecTyp) == recMiddle {
r.err = errors.New("last record is torn")
}
return false
}
r.err = err
return r.err == nil
} | go | func (r *Reader) Next() bool {
err := r.next()
if errors.Cause(err) == io.EOF {
// The last WAL segment record shouldn't be torn(should be full or last).
// The last record would be torn after a crash just before
// the last record part could be persisted to disk.
if recType(r.curRecTyp) == recFirst || recType(r.curRecTyp) == recMiddle {
r.err = errors.New("last record is torn")
}
return false
}
r.err = err
return r.err == nil
} | [
"func",
"(",
"r",
"*",
"Reader",
")",
"Next",
"(",
")",
"bool",
"{",
"err",
":=",
"r",
".",
"next",
"(",
")",
"\n",
"if",
"errors",
".",
"Cause",
"(",
"err",
")",
"==",
"io",
".",
"EOF",
"{",
"if",
"recType",
"(",
"r",
".",
"curRecTyp",
")",
... | // Next advances the reader to the next records and returns true if it exists.
// It must not be called again after it returned false. | [
"Next",
"advances",
"the",
"reader",
"to",
"the",
"next",
"records",
"and",
"returns",
"true",
"if",
"it",
"exists",
".",
"It",
"must",
"not",
"be",
"called",
"again",
"after",
"it",
"returned",
"false",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/wal/reader.go#L42-L55 | train |
prometheus/tsdb | wal/reader.go | Err | func (r *Reader) Err() error {
if r.err == nil {
return nil
}
if b, ok := r.rdr.(*segmentBufReader); ok {
return &CorruptionErr{
Err: r.err,
Dir: b.segs[b.cur].Dir(),
Segment: b.segs[b.cur].Index(),
Offset: int64(b.off),
}
}
return &CorruptionErr{
Err: r.err,
Segment: -1,
Offset: r.total,
}
} | go | func (r *Reader) Err() error {
if r.err == nil {
return nil
}
if b, ok := r.rdr.(*segmentBufReader); ok {
return &CorruptionErr{
Err: r.err,
Dir: b.segs[b.cur].Dir(),
Segment: b.segs[b.cur].Index(),
Offset: int64(b.off),
}
}
return &CorruptionErr{
Err: r.err,
Segment: -1,
Offset: r.total,
}
} | [
"func",
"(",
"r",
"*",
"Reader",
")",
"Err",
"(",
")",
"error",
"{",
"if",
"r",
".",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"b",
",",
"ok",
":=",
"r",
".",
"rdr",
".",
"(",
"*",
"segmentBufReader",
")",
";",
"ok",
... | // Err returns the last encountered error wrapped in a corruption error.
// If the reader does not allow to infer a segment index and offset, a total
// offset in the reader stream will be provided. | [
"Err",
"returns",
"the",
"last",
"encountered",
"error",
"wrapped",
"in",
"a",
"corruption",
"error",
".",
"If",
"the",
"reader",
"does",
"not",
"allow",
"to",
"infer",
"a",
"segment",
"index",
"and",
"offset",
"a",
"total",
"offset",
"in",
"the",
"reader"... | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/wal/reader.go#L144-L161 | train |
prometheus/tsdb | wal/reader.go | Segment | func (r *Reader) Segment() int {
if b, ok := r.rdr.(*segmentBufReader); ok {
return b.segs[b.cur].Index()
}
return -1
} | go | func (r *Reader) Segment() int {
if b, ok := r.rdr.(*segmentBufReader); ok {
return b.segs[b.cur].Index()
}
return -1
} | [
"func",
"(",
"r",
"*",
"Reader",
")",
"Segment",
"(",
")",
"int",
"{",
"if",
"b",
",",
"ok",
":=",
"r",
".",
"rdr",
".",
"(",
"*",
"segmentBufReader",
")",
";",
"ok",
"{",
"return",
"b",
".",
"segs",
"[",
"b",
".",
"cur",
"]",
".",
"Index",
... | // Segment returns the current segment being read. | [
"Segment",
"returns",
"the",
"current",
"segment",
"being",
"read",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/wal/reader.go#L170-L175 | train |
prometheus/tsdb | wal/reader.go | Offset | func (r *Reader) Offset() int64 {
if b, ok := r.rdr.(*segmentBufReader); ok {
return int64(b.off)
}
return r.total
} | go | func (r *Reader) Offset() int64 {
if b, ok := r.rdr.(*segmentBufReader); ok {
return int64(b.off)
}
return r.total
} | [
"func",
"(",
"r",
"*",
"Reader",
")",
"Offset",
"(",
")",
"int64",
"{",
"if",
"b",
",",
"ok",
":=",
"r",
".",
"rdr",
".",
"(",
"*",
"segmentBufReader",
")",
";",
"ok",
"{",
"return",
"int64",
"(",
"b",
".",
"off",
")",
"\n",
"}",
"\n",
"retur... | // Offset returns the current position of the segment being read. | [
"Offset",
"returns",
"the",
"current",
"position",
"of",
"the",
"segment",
"being",
"read",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/wal/reader.go#L178-L183 | train |
prometheus/tsdb | querier.go | NewBlockQuerier | func NewBlockQuerier(b BlockReader, mint, maxt int64) (Querier, error) {
indexr, err := b.Index()
if err != nil {
return nil, errors.Wrapf(err, "open index reader")
}
chunkr, err := b.Chunks()
if err != nil {
indexr.Close()
return nil, errors.Wrapf(err, "open chunk reader")
}
tombsr, err := b.Tombstones()
if err != nil {
indexr.Close()
chunkr.Close()
return nil, errors.Wrapf(err, "open tombstone reader")
}
return &blockQuerier{
mint: mint,
maxt: maxt,
index: indexr,
chunks: chunkr,
tombstones: tombsr,
}, nil
} | go | func NewBlockQuerier(b BlockReader, mint, maxt int64) (Querier, error) {
indexr, err := b.Index()
if err != nil {
return nil, errors.Wrapf(err, "open index reader")
}
chunkr, err := b.Chunks()
if err != nil {
indexr.Close()
return nil, errors.Wrapf(err, "open chunk reader")
}
tombsr, err := b.Tombstones()
if err != nil {
indexr.Close()
chunkr.Close()
return nil, errors.Wrapf(err, "open tombstone reader")
}
return &blockQuerier{
mint: mint,
maxt: maxt,
index: indexr,
chunks: chunkr,
tombstones: tombsr,
}, nil
} | [
"func",
"NewBlockQuerier",
"(",
"b",
"BlockReader",
",",
"mint",
",",
"maxt",
"int64",
")",
"(",
"Querier",
",",
"error",
")",
"{",
"indexr",
",",
"err",
":=",
"b",
".",
"Index",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
... | // NewBlockQuerier returns a querier against the reader. | [
"NewBlockQuerier",
"returns",
"a",
"querier",
"against",
"the",
"reader",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/querier.go#L177-L200 | train |
prometheus/tsdb | querier.go | PostingsForMatchers | func PostingsForMatchers(ix IndexReader, ms ...labels.Matcher) (index.Postings, error) {
var its, notIts []index.Postings
// See which label must be non-empty.
labelMustBeSet := make(map[string]bool, len(ms))
for _, m := range ms {
if !m.Matches("") {
labelMustBeSet[m.Name()] = true
}
}
for _, m := range ms {
matchesEmpty := m.Matches("")
if labelMustBeSet[m.Name()] || !matchesEmpty {
// If this matcher must be non-empty, we can be smarter.
nm, isNot := m.(*labels.NotMatcher)
if isNot && matchesEmpty { // l!="foo"
// If the label can't be empty and is a Not and the inner matcher
// doesn't match empty, then subtract it out at the end.
it, err := postingsForMatcher(ix, nm.Matcher)
if err != nil {
return nil, err
}
notIts = append(notIts, it)
} else if isNot && !matchesEmpty { // l!=""
// If the label can't be empty and is a Not, but the inner matcher can
// be empty we need to use inversePostingsForMatcher.
it, err := inversePostingsForMatcher(ix, nm.Matcher)
if err != nil {
return nil, err
}
its = append(its, it)
} else { // l="a"
// Non-Not matcher, use normal postingsForMatcher.
it, err := postingsForMatcher(ix, m)
if err != nil {
return nil, err
}
its = append(its, it)
}
} else { // l=""
// If the matchers for a labelname selects an empty value, it selects all
// the series which don't have the label name set too. See:
// https://github.com/prometheus/prometheus/issues/3575 and
// https://github.com/prometheus/prometheus/pull/3578#issuecomment-351653555
it, err := inversePostingsForMatcher(ix, m)
if err != nil {
return nil, err
}
notIts = append(notIts, it)
}
}
// If there's nothing to subtract from, add in everything and remove the notIts later.
if len(its) == 0 && len(notIts) != 0 {
allPostings, err := ix.Postings(index.AllPostingsKey())
if err != nil {
return nil, err
}
its = append(its, allPostings)
}
it := index.Intersect(its...)
for _, n := range notIts {
if _, ok := n.(*index.ListPostings); !ok {
// Best to pre-calculate the merged lists via next rather than have a ton
// of seeks in Without.
pl, err := index.ExpandPostings(n)
if err != nil {
return nil, err
}
n = index.NewListPostings(pl)
}
it = index.Without(it, n)
}
return ix.SortedPostings(it), nil
} | go | func PostingsForMatchers(ix IndexReader, ms ...labels.Matcher) (index.Postings, error) {
var its, notIts []index.Postings
// See which label must be non-empty.
labelMustBeSet := make(map[string]bool, len(ms))
for _, m := range ms {
if !m.Matches("") {
labelMustBeSet[m.Name()] = true
}
}
for _, m := range ms {
matchesEmpty := m.Matches("")
if labelMustBeSet[m.Name()] || !matchesEmpty {
// If this matcher must be non-empty, we can be smarter.
nm, isNot := m.(*labels.NotMatcher)
if isNot && matchesEmpty { // l!="foo"
// If the label can't be empty and is a Not and the inner matcher
// doesn't match empty, then subtract it out at the end.
it, err := postingsForMatcher(ix, nm.Matcher)
if err != nil {
return nil, err
}
notIts = append(notIts, it)
} else if isNot && !matchesEmpty { // l!=""
// If the label can't be empty and is a Not, but the inner matcher can
// be empty we need to use inversePostingsForMatcher.
it, err := inversePostingsForMatcher(ix, nm.Matcher)
if err != nil {
return nil, err
}
its = append(its, it)
} else { // l="a"
// Non-Not matcher, use normal postingsForMatcher.
it, err := postingsForMatcher(ix, m)
if err != nil {
return nil, err
}
its = append(its, it)
}
} else { // l=""
// If the matchers for a labelname selects an empty value, it selects all
// the series which don't have the label name set too. See:
// https://github.com/prometheus/prometheus/issues/3575 and
// https://github.com/prometheus/prometheus/pull/3578#issuecomment-351653555
it, err := inversePostingsForMatcher(ix, m)
if err != nil {
return nil, err
}
notIts = append(notIts, it)
}
}
// If there's nothing to subtract from, add in everything and remove the notIts later.
if len(its) == 0 && len(notIts) != 0 {
allPostings, err := ix.Postings(index.AllPostingsKey())
if err != nil {
return nil, err
}
its = append(its, allPostings)
}
it := index.Intersect(its...)
for _, n := range notIts {
if _, ok := n.(*index.ListPostings); !ok {
// Best to pre-calculate the merged lists via next rather than have a ton
// of seeks in Without.
pl, err := index.ExpandPostings(n)
if err != nil {
return nil, err
}
n = index.NewListPostings(pl)
}
it = index.Without(it, n)
}
return ix.SortedPostings(it), nil
} | [
"func",
"PostingsForMatchers",
"(",
"ix",
"IndexReader",
",",
"ms",
"...",
"labels",
".",
"Matcher",
")",
"(",
"index",
".",
"Postings",
",",
"error",
")",
"{",
"var",
"its",
",",
"notIts",
"[",
"]",
"index",
".",
"Postings",
"\n",
"labelMustBeSet",
":="... | // PostingsForMatchers assembles a single postings iterator against the index reader
// based on the given matchers. | [
"PostingsForMatchers",
"assembles",
"a",
"single",
"postings",
"iterator",
"against",
"the",
"index",
"reader",
"based",
"on",
"the",
"given",
"matchers",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/querier.go#L271-L348 | train |
prometheus/tsdb | querier.go | inversePostingsForMatcher | func inversePostingsForMatcher(ix IndexReader, m labels.Matcher) (index.Postings, error) {
tpls, err := ix.LabelValues(m.Name())
if err != nil {
return nil, err
}
var res []string
for i := 0; i < tpls.Len(); i++ {
vals, err := tpls.At(i)
if err != nil {
return nil, err
}
if !m.Matches(vals[0]) {
res = append(res, vals[0])
}
}
var rit []index.Postings
for _, v := range res {
it, err := ix.Postings(m.Name(), v)
if err != nil {
return nil, err
}
rit = append(rit, it)
}
return index.Merge(rit...), nil
} | go | func inversePostingsForMatcher(ix IndexReader, m labels.Matcher) (index.Postings, error) {
tpls, err := ix.LabelValues(m.Name())
if err != nil {
return nil, err
}
var res []string
for i := 0; i < tpls.Len(); i++ {
vals, err := tpls.At(i)
if err != nil {
return nil, err
}
if !m.Matches(vals[0]) {
res = append(res, vals[0])
}
}
var rit []index.Postings
for _, v := range res {
it, err := ix.Postings(m.Name(), v)
if err != nil {
return nil, err
}
rit = append(rit, it)
}
return index.Merge(rit...), nil
} | [
"func",
"inversePostingsForMatcher",
"(",
"ix",
"IndexReader",
",",
"m",
"labels",
".",
"Matcher",
")",
"(",
"index",
".",
"Postings",
",",
"error",
")",
"{",
"tpls",
",",
"err",
":=",
"ix",
".",
"LabelValues",
"(",
"m",
".",
"Name",
"(",
")",
")",
"... | // inversePostingsForMatcher eeturns the postings for the series with the label name set but not matching the matcher. | [
"inversePostingsForMatcher",
"eeturns",
"the",
"postings",
"for",
"the",
"series",
"with",
"the",
"label",
"name",
"set",
"but",
"not",
"matching",
"the",
"matcher",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/querier.go#L392-L421 | train |
prometheus/tsdb | querier.go | LookupChunkSeries | func LookupChunkSeries(ir IndexReader, tr TombstoneReader, ms ...labels.Matcher) (ChunkSeriesSet, error) {
if tr == nil {
tr = newMemTombstones()
}
p, err := PostingsForMatchers(ir, ms...)
if err != nil {
return nil, err
}
return &baseChunkSeries{
p: p,
index: ir,
tombstones: tr,
}, nil
} | go | func LookupChunkSeries(ir IndexReader, tr TombstoneReader, ms ...labels.Matcher) (ChunkSeriesSet, error) {
if tr == nil {
tr = newMemTombstones()
}
p, err := PostingsForMatchers(ir, ms...)
if err != nil {
return nil, err
}
return &baseChunkSeries{
p: p,
index: ir,
tombstones: tr,
}, nil
} | [
"func",
"LookupChunkSeries",
"(",
"ir",
"IndexReader",
",",
"tr",
"TombstoneReader",
",",
"ms",
"...",
"labels",
".",
"Matcher",
")",
"(",
"ChunkSeriesSet",
",",
"error",
")",
"{",
"if",
"tr",
"==",
"nil",
"{",
"tr",
"=",
"newMemTombstones",
"(",
")",
"\... | // LookupChunkSeries retrieves all series for the given matchers and returns a ChunkSeriesSet
// over them. It drops chunks based on tombstones in the given reader. | [
"LookupChunkSeries",
"retrieves",
"all",
"series",
"for",
"the",
"given",
"matchers",
"and",
"returns",
"a",
"ChunkSeriesSet",
"over",
"them",
".",
"It",
"drops",
"chunks",
"based",
"on",
"tombstones",
"in",
"the",
"given",
"reader",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/querier.go#L624-L637 | train |
prometheus/tsdb | index/postings.go | NewMemPostings | func NewMemPostings() *MemPostings {
return &MemPostings{
m: make(map[string]map[string][]uint64, 512),
ordered: true,
}
} | go | func NewMemPostings() *MemPostings {
return &MemPostings{
m: make(map[string]map[string][]uint64, 512),
ordered: true,
}
} | [
"func",
"NewMemPostings",
"(",
")",
"*",
"MemPostings",
"{",
"return",
"&",
"MemPostings",
"{",
"m",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"[",
"]",
"uint64",
",",
"512",
")",
",",
"ordered",
":",
"true",
",",
"}",... | // NewMemPostings returns a memPostings that's ready for reads and writes. | [
"NewMemPostings",
"returns",
"a",
"memPostings",
"that",
"s",
"ready",
"for",
"reads",
"and",
"writes",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L45-L50 | train |
prometheus/tsdb | index/postings.go | NewUnorderedMemPostings | func NewUnorderedMemPostings() *MemPostings {
return &MemPostings{
m: make(map[string]map[string][]uint64, 512),
ordered: false,
}
} | go | func NewUnorderedMemPostings() *MemPostings {
return &MemPostings{
m: make(map[string]map[string][]uint64, 512),
ordered: false,
}
} | [
"func",
"NewUnorderedMemPostings",
"(",
")",
"*",
"MemPostings",
"{",
"return",
"&",
"MemPostings",
"{",
"m",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"[",
"]",
"uint64",
",",
"512",
")",
",",
"ordered",
":",
"false",
"... | // NewUnorderedMemPostings returns a memPostings that is not safe to be read from
// until ensureOrder was called once. | [
"NewUnorderedMemPostings",
"returns",
"a",
"memPostings",
"that",
"is",
"not",
"safe",
"to",
"be",
"read",
"from",
"until",
"ensureOrder",
"was",
"called",
"once",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L54-L59 | train |
prometheus/tsdb | index/postings.go | SortedKeys | func (p *MemPostings) SortedKeys() []labels.Label {
p.mtx.RLock()
keys := make([]labels.Label, 0, len(p.m))
for n, e := range p.m {
for v := range e {
keys = append(keys, labels.Label{Name: n, Value: v})
}
}
p.mtx.RUnlock()
sort.Slice(keys, func(i, j int) bool {
if d := strings.Compare(keys[i].Name, keys[j].Name); d != 0 {
return d < 0
}
return keys[i].Value < keys[j].Value
})
return keys
} | go | func (p *MemPostings) SortedKeys() []labels.Label {
p.mtx.RLock()
keys := make([]labels.Label, 0, len(p.m))
for n, e := range p.m {
for v := range e {
keys = append(keys, labels.Label{Name: n, Value: v})
}
}
p.mtx.RUnlock()
sort.Slice(keys, func(i, j int) bool {
if d := strings.Compare(keys[i].Name, keys[j].Name); d != 0 {
return d < 0
}
return keys[i].Value < keys[j].Value
})
return keys
} | [
"func",
"(",
"p",
"*",
"MemPostings",
")",
"SortedKeys",
"(",
")",
"[",
"]",
"labels",
".",
"Label",
"{",
"p",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"keys",
":=",
"make",
"(",
"[",
"]",
"labels",
".",
"Label",
",",
"0",
",",
"len",
"(",
"... | // SortedKeys returns a list of sorted label keys of the postings. | [
"SortedKeys",
"returns",
"a",
"list",
"of",
"sorted",
"label",
"keys",
"of",
"the",
"postings",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L62-L80 | train |
prometheus/tsdb | index/postings.go | Get | func (p *MemPostings) Get(name, value string) Postings {
var lp []uint64
p.mtx.RLock()
l := p.m[name]
if l != nil {
lp = l[value]
}
p.mtx.RUnlock()
if lp == nil {
return EmptyPostings()
}
return newListPostings(lp...)
} | go | func (p *MemPostings) Get(name, value string) Postings {
var lp []uint64
p.mtx.RLock()
l := p.m[name]
if l != nil {
lp = l[value]
}
p.mtx.RUnlock()
if lp == nil {
return EmptyPostings()
}
return newListPostings(lp...)
} | [
"func",
"(",
"p",
"*",
"MemPostings",
")",
"Get",
"(",
"name",
",",
"value",
"string",
")",
"Postings",
"{",
"var",
"lp",
"[",
"]",
"uint64",
"\n",
"p",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"l",
":=",
"p",
".",
"m",
"[",
"name",
"]",
"\n... | // Get returns a postings list for the given label pair. | [
"Get",
"returns",
"a",
"postings",
"list",
"for",
"the",
"given",
"label",
"pair",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/index/postings.go#L83-L96 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.