repository_name
stringlengths 5
54
| func_path_in_repository
stringlengths 4
155
| func_name
stringlengths 1
118
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 1
value | func_code_string
stringlengths 52
3.87M
| func_code_tokens
sequencelengths 21
188k
| func_documentation_string
stringlengths 4
26.3k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|
HouzuoGuo/tiedot | data/collection.go | Insert | func (col *Collection) Insert(data []byte) (id int, err error) {
room := len(data) << 1
if room > col.DocMaxRoom {
return 0, dberr.New(dberr.ErrorDocTooLarge, col.DocMaxRoom, room)
}
id = col.Used
docSize := DocHeader + room
if err = col.EnsureSize(docSize); err != nil {
return
}
col.Used += docSize
// Write validity, room, document data and padding
col.Buf[id] = 1
binary.PutVarint(col.Buf[id+1:id+11], int64(room))
copy(col.Buf[id+DocHeader:col.Used], data)
for padding := id + DocHeader + len(data); padding < col.Used; padding += col.LenPadding {
copySize := col.LenPadding
if padding+col.LenPadding >= col.Used {
copySize = col.Used - padding
}
copy(col.Buf[padding:padding+copySize], col.Padding)
}
return
} | go | func (col *Collection) Insert(data []byte) (id int, err error) {
room := len(data) << 1
if room > col.DocMaxRoom {
return 0, dberr.New(dberr.ErrorDocTooLarge, col.DocMaxRoom, room)
}
id = col.Used
docSize := DocHeader + room
if err = col.EnsureSize(docSize); err != nil {
return
}
col.Used += docSize
// Write validity, room, document data and padding
col.Buf[id] = 1
binary.PutVarint(col.Buf[id+1:id+11], int64(room))
copy(col.Buf[id+DocHeader:col.Used], data)
for padding := id + DocHeader + len(data); padding < col.Used; padding += col.LenPadding {
copySize := col.LenPadding
if padding+col.LenPadding >= col.Used {
copySize = col.Used - padding
}
copy(col.Buf[padding:padding+copySize], col.Padding)
}
return
} | [
"func",
"(",
"col",
"*",
"Collection",
")",
"Insert",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"id",
"int",
",",
"err",
"error",
")",
"{",
"room",
":=",
"len",
"(",
"data",
")",
"<<",
"1",
"\n",
"if",
"room",
">",
"col",
".",
"DocMaxRoom",
"{",
"return",
"0",
",",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorDocTooLarge",
",",
"col",
".",
"DocMaxRoom",
",",
"room",
")",
"\n",
"}",
"\n",
"id",
"=",
"col",
".",
"Used",
"\n",
"docSize",
":=",
"DocHeader",
"+",
"room",
"\n",
"if",
"err",
"=",
"col",
".",
"EnsureSize",
"(",
"docSize",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"col",
".",
"Used",
"+=",
"docSize",
"\n",
"// Write validity, room, document data and padding",
"col",
".",
"Buf",
"[",
"id",
"]",
"=",
"1",
"\n",
"binary",
".",
"PutVarint",
"(",
"col",
".",
"Buf",
"[",
"id",
"+",
"1",
":",
"id",
"+",
"11",
"]",
",",
"int64",
"(",
"room",
")",
")",
"\n",
"copy",
"(",
"col",
".",
"Buf",
"[",
"id",
"+",
"DocHeader",
":",
"col",
".",
"Used",
"]",
",",
"data",
")",
"\n",
"for",
"padding",
":=",
"id",
"+",
"DocHeader",
"+",
"len",
"(",
"data",
")",
";",
"padding",
"<",
"col",
".",
"Used",
";",
"padding",
"+=",
"col",
".",
"LenPadding",
"{",
"copySize",
":=",
"col",
".",
"LenPadding",
"\n",
"if",
"padding",
"+",
"col",
".",
"LenPadding",
">=",
"col",
".",
"Used",
"{",
"copySize",
"=",
"col",
".",
"Used",
"-",
"padding",
"\n",
"}",
"\n",
"copy",
"(",
"col",
".",
"Buf",
"[",
"padding",
":",
"padding",
"+",
"copySize",
"]",
",",
"col",
".",
"Padding",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Insert a new document, return the new document ID. | [
"Insert",
"a",
"new",
"document",
"return",
"the",
"new",
"document",
"ID",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/collection.go#L54-L77 |
HouzuoGuo/tiedot | data/collection.go | Update | func (col *Collection) Update(id int, data []byte) (newID int, err error) {
dataLen := len(data)
if dataLen > col.DocMaxRoom {
return 0, dberr.New(dberr.ErrorDocTooLarge, col.DocMaxRoom, dataLen)
}
if id < 0 || id >= col.Used-DocHeader || col.Buf[id] != 1 {
return 0, dberr.New(dberr.ErrorNoDoc, id)
}
currentDocRoom, _ := binary.Varint(col.Buf[id+1 : id+11])
if currentDocRoom > int64(col.DocMaxRoom) {
return 0, dberr.New(dberr.ErrorNoDoc, id)
}
if docEnd := id + DocHeader + int(currentDocRoom); docEnd >= col.Size {
return 0, dberr.New(dberr.ErrorNoDoc, id)
}
if dataLen <= int(currentDocRoom) {
padding := id + DocHeader + len(data)
paddingEnd := id + DocHeader + int(currentDocRoom)
// Overwrite data and then overwrite padding
copy(col.Buf[id+DocHeader:padding], data)
for ; padding < paddingEnd; padding += col.LenPadding {
copySize := col.LenPadding
if padding+col.LenPadding >= paddingEnd {
copySize = paddingEnd - padding
}
copy(col.Buf[padding:padding+copySize], col.Padding)
}
return id, nil
}
// No enough room - re-insert the document
col.Delete(id)
return col.Insert(data)
} | go | func (col *Collection) Update(id int, data []byte) (newID int, err error) {
dataLen := len(data)
if dataLen > col.DocMaxRoom {
return 0, dberr.New(dberr.ErrorDocTooLarge, col.DocMaxRoom, dataLen)
}
if id < 0 || id >= col.Used-DocHeader || col.Buf[id] != 1 {
return 0, dberr.New(dberr.ErrorNoDoc, id)
}
currentDocRoom, _ := binary.Varint(col.Buf[id+1 : id+11])
if currentDocRoom > int64(col.DocMaxRoom) {
return 0, dberr.New(dberr.ErrorNoDoc, id)
}
if docEnd := id + DocHeader + int(currentDocRoom); docEnd >= col.Size {
return 0, dberr.New(dberr.ErrorNoDoc, id)
}
if dataLen <= int(currentDocRoom) {
padding := id + DocHeader + len(data)
paddingEnd := id + DocHeader + int(currentDocRoom)
// Overwrite data and then overwrite padding
copy(col.Buf[id+DocHeader:padding], data)
for ; padding < paddingEnd; padding += col.LenPadding {
copySize := col.LenPadding
if padding+col.LenPadding >= paddingEnd {
copySize = paddingEnd - padding
}
copy(col.Buf[padding:padding+copySize], col.Padding)
}
return id, nil
}
// No enough room - re-insert the document
col.Delete(id)
return col.Insert(data)
} | [
"func",
"(",
"col",
"*",
"Collection",
")",
"Update",
"(",
"id",
"int",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"newID",
"int",
",",
"err",
"error",
")",
"{",
"dataLen",
":=",
"len",
"(",
"data",
")",
"\n",
"if",
"dataLen",
">",
"col",
".",
"DocMaxRoom",
"{",
"return",
"0",
",",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorDocTooLarge",
",",
"col",
".",
"DocMaxRoom",
",",
"dataLen",
")",
"\n",
"}",
"\n",
"if",
"id",
"<",
"0",
"||",
"id",
">=",
"col",
".",
"Used",
"-",
"DocHeader",
"||",
"col",
".",
"Buf",
"[",
"id",
"]",
"!=",
"1",
"{",
"return",
"0",
",",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorNoDoc",
",",
"id",
")",
"\n",
"}",
"\n",
"currentDocRoom",
",",
"_",
":=",
"binary",
".",
"Varint",
"(",
"col",
".",
"Buf",
"[",
"id",
"+",
"1",
":",
"id",
"+",
"11",
"]",
")",
"\n",
"if",
"currentDocRoom",
">",
"int64",
"(",
"col",
".",
"DocMaxRoom",
")",
"{",
"return",
"0",
",",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorNoDoc",
",",
"id",
")",
"\n",
"}",
"\n",
"if",
"docEnd",
":=",
"id",
"+",
"DocHeader",
"+",
"int",
"(",
"currentDocRoom",
")",
";",
"docEnd",
">=",
"col",
".",
"Size",
"{",
"return",
"0",
",",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorNoDoc",
",",
"id",
")",
"\n",
"}",
"\n",
"if",
"dataLen",
"<=",
"int",
"(",
"currentDocRoom",
")",
"{",
"padding",
":=",
"id",
"+",
"DocHeader",
"+",
"len",
"(",
"data",
")",
"\n",
"paddingEnd",
":=",
"id",
"+",
"DocHeader",
"+",
"int",
"(",
"currentDocRoom",
")",
"\n",
"// Overwrite data and then overwrite padding",
"copy",
"(",
"col",
".",
"Buf",
"[",
"id",
"+",
"DocHeader",
":",
"padding",
"]",
",",
"data",
")",
"\n",
"for",
";",
"padding",
"<",
"paddingEnd",
";",
"padding",
"+=",
"col",
".",
"LenPadding",
"{",
"copySize",
":=",
"col",
".",
"LenPadding",
"\n",
"if",
"padding",
"+",
"col",
".",
"LenPadding",
">=",
"paddingEnd",
"{",
"copySize",
"=",
"paddingEnd",
"-",
"padding",
"\n",
"}",
"\n",
"copy",
"(",
"col",
".",
"Buf",
"[",
"padding",
":",
"padding",
"+",
"copySize",
"]",
",",
"col",
".",
"Padding",
")",
"\n",
"}",
"\n",
"return",
"id",
",",
"nil",
"\n",
"}",
"\n\n",
"// No enough room - re-insert the document",
"col",
".",
"Delete",
"(",
"id",
")",
"\n",
"return",
"col",
".",
"Insert",
"(",
"data",
")",
"\n",
"}"
] | // Overwrite or re-insert a document, return the new document ID if re-inserted. | [
"Overwrite",
"or",
"re",
"-",
"insert",
"a",
"document",
"return",
"the",
"new",
"document",
"ID",
"if",
"re",
"-",
"inserted",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/collection.go#L80-L113 |
HouzuoGuo/tiedot | data/collection.go | Delete | func (col *Collection) Delete(id int) error {
if id < 0 || id > col.Used-DocHeader || col.Buf[id] != 1 {
return dberr.New(dberr.ErrorNoDoc, id)
}
if col.Buf[id] == 1 {
col.Buf[id] = 0
}
return nil
} | go | func (col *Collection) Delete(id int) error {
if id < 0 || id > col.Used-DocHeader || col.Buf[id] != 1 {
return dberr.New(dberr.ErrorNoDoc, id)
}
if col.Buf[id] == 1 {
col.Buf[id] = 0
}
return nil
} | [
"func",
"(",
"col",
"*",
"Collection",
")",
"Delete",
"(",
"id",
"int",
")",
"error",
"{",
"if",
"id",
"<",
"0",
"||",
"id",
">",
"col",
".",
"Used",
"-",
"DocHeader",
"||",
"col",
".",
"Buf",
"[",
"id",
"]",
"!=",
"1",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorNoDoc",
",",
"id",
")",
"\n",
"}",
"\n\n",
"if",
"col",
".",
"Buf",
"[",
"id",
"]",
"==",
"1",
"{",
"col",
".",
"Buf",
"[",
"id",
"]",
"=",
"0",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Delete a document by ID. | [
"Delete",
"a",
"document",
"by",
"ID",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/collection.go#L116-L127 |
HouzuoGuo/tiedot | data/collection.go | ForEachDoc | func (col *Collection) ForEachDoc(fun func(id int, doc []byte) bool) {
for id := 0; id < col.Used-DocHeader && id >= 0; {
validity := col.Buf[id]
room, _ := binary.Varint(col.Buf[id+1 : id+11])
docEnd := id + DocHeader + int(room)
if (validity == 0 || validity == 1) && room <= int64(col.DocMaxRoom) && docEnd > 0 && docEnd <= col.Used {
if validity == 1 && !fun(id, col.Buf[id+DocHeader:docEnd]) {
break
}
id = docEnd
} else {
// Corrupted document - move on
id++
}
}
} | go | func (col *Collection) ForEachDoc(fun func(id int, doc []byte) bool) {
for id := 0; id < col.Used-DocHeader && id >= 0; {
validity := col.Buf[id]
room, _ := binary.Varint(col.Buf[id+1 : id+11])
docEnd := id + DocHeader + int(room)
if (validity == 0 || validity == 1) && room <= int64(col.DocMaxRoom) && docEnd > 0 && docEnd <= col.Used {
if validity == 1 && !fun(id, col.Buf[id+DocHeader:docEnd]) {
break
}
id = docEnd
} else {
// Corrupted document - move on
id++
}
}
} | [
"func",
"(",
"col",
"*",
"Collection",
")",
"ForEachDoc",
"(",
"fun",
"func",
"(",
"id",
"int",
",",
"doc",
"[",
"]",
"byte",
")",
"bool",
")",
"{",
"for",
"id",
":=",
"0",
";",
"id",
"<",
"col",
".",
"Used",
"-",
"DocHeader",
"&&",
"id",
">=",
"0",
";",
"{",
"validity",
":=",
"col",
".",
"Buf",
"[",
"id",
"]",
"\n",
"room",
",",
"_",
":=",
"binary",
".",
"Varint",
"(",
"col",
".",
"Buf",
"[",
"id",
"+",
"1",
":",
"id",
"+",
"11",
"]",
")",
"\n",
"docEnd",
":=",
"id",
"+",
"DocHeader",
"+",
"int",
"(",
"room",
")",
"\n",
"if",
"(",
"validity",
"==",
"0",
"||",
"validity",
"==",
"1",
")",
"&&",
"room",
"<=",
"int64",
"(",
"col",
".",
"DocMaxRoom",
")",
"&&",
"docEnd",
">",
"0",
"&&",
"docEnd",
"<=",
"col",
".",
"Used",
"{",
"if",
"validity",
"==",
"1",
"&&",
"!",
"fun",
"(",
"id",
",",
"col",
".",
"Buf",
"[",
"id",
"+",
"DocHeader",
":",
"docEnd",
"]",
")",
"{",
"break",
"\n",
"}",
"\n",
"id",
"=",
"docEnd",
"\n",
"}",
"else",
"{",
"// Corrupted document - move on",
"id",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Run the function on every document; stop when the function returns false. | [
"Run",
"the",
"function",
"on",
"every",
"document",
";",
"stop",
"when",
"the",
"function",
"returns",
"false",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/collection.go#L130-L145 |
HouzuoGuo/tiedot | httpapi/index.go | Index | func Index(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, path string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "path", &path) {
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
if err := dbcol.Index(strings.Split(path, ",")); err != nil {
http.Error(w, fmt.Sprint(err), 400)
return
}
w.WriteHeader(201)
} | go | func Index(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, path string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "path", &path) {
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
if err := dbcol.Index(strings.Split(path, ",")); err != nil {
http.Error(w, fmt.Sprint(err), 400)
return
}
w.WriteHeader(201)
} | [
"func",
"Index",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"col",
",",
"path",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"col",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"path",
")",
"{",
"return",
"\n",
"}",
"\n",
"dbcol",
":=",
"HttpDB",
".",
"Use",
"(",
"col",
")",
"\n",
"if",
"dbcol",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"col",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
":=",
"dbcol",
".",
"Index",
"(",
"strings",
".",
"Split",
"(",
"path",
",",
"\"",
"\"",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"201",
")",
"\n",
"}"
] | // Put an index on a document path. | [
"Put",
"an",
"index",
"on",
"a",
"document",
"path",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/index.go#L13-L35 |
HouzuoGuo/tiedot | httpapi/index.go | Indexes | func Indexes(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col string
if !Require(w, r, "col", &col) {
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
indexes := make([][]string, 0)
for _, path := range dbcol.AllIndexes() {
indexes = append(indexes, path)
}
resp, err := json.Marshal(indexes)
if err != nil {
http.Error(w, fmt.Sprint("Server error."), 500)
return
}
w.Write(resp)
} | go | func Indexes(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col string
if !Require(w, r, "col", &col) {
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
indexes := make([][]string, 0)
for _, path := range dbcol.AllIndexes() {
indexes = append(indexes, path)
}
resp, err := json.Marshal(indexes)
if err != nil {
http.Error(w, fmt.Sprint("Server error."), 500)
return
}
w.Write(resp)
} | [
"func",
"Indexes",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"col",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"col",
")",
"{",
"return",
"\n",
"}",
"\n",
"dbcol",
":=",
"HttpDB",
".",
"Use",
"(",
"col",
")",
"\n",
"if",
"dbcol",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"col",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"indexes",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"for",
"_",
",",
"path",
":=",
"range",
"dbcol",
".",
"AllIndexes",
"(",
")",
"{",
"indexes",
"=",
"append",
"(",
"indexes",
",",
"path",
")",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"indexes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"\"",
"\"",
")",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"resp",
")",
"\n",
"}"
] | // Return all indexed paths. | [
"Return",
"all",
"indexed",
"paths",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/index.go#L38-L62 |
HouzuoGuo/tiedot | data/hashtable.go | OpenHashTable | func (conf *Config) OpenHashTable(path string) (ht *HashTable, err error) {
ht = &HashTable{Config: conf, Lock: new(sync.RWMutex)}
if ht.DataFile, err = OpenDataFile(path, ht.HTFileGrowth); err != nil {
return
}
conf.CalculateConfigConstants()
ht.calculateNumBuckets()
return
} | go | func (conf *Config) OpenHashTable(path string) (ht *HashTable, err error) {
ht = &HashTable{Config: conf, Lock: new(sync.RWMutex)}
if ht.DataFile, err = OpenDataFile(path, ht.HTFileGrowth); err != nil {
return
}
conf.CalculateConfigConstants()
ht.calculateNumBuckets()
return
} | [
"func",
"(",
"conf",
"*",
"Config",
")",
"OpenHashTable",
"(",
"path",
"string",
")",
"(",
"ht",
"*",
"HashTable",
",",
"err",
"error",
")",
"{",
"ht",
"=",
"&",
"HashTable",
"{",
"Config",
":",
"conf",
",",
"Lock",
":",
"new",
"(",
"sync",
".",
"RWMutex",
")",
"}",
"\n",
"if",
"ht",
".",
"DataFile",
",",
"err",
"=",
"OpenDataFile",
"(",
"path",
",",
"ht",
".",
"HTFileGrowth",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"conf",
".",
"CalculateConfigConstants",
"(",
")",
"\n",
"ht",
".",
"calculateNumBuckets",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Open a hash table file. | [
"Open",
"a",
"hash",
"table",
"file",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L30-L38 |
HouzuoGuo/tiedot | data/hashtable.go | calculateNumBuckets | func (ht *HashTable) calculateNumBuckets() {
ht.numBuckets = ht.Size / ht.BucketSize
largestBucketNum := ht.InitialBuckets - 1
for i := 0; i < ht.InitialBuckets; i++ {
lastBucket := ht.lastBucket(i)
if lastBucket > largestBucketNum && lastBucket < ht.numBuckets {
largestBucketNum = lastBucket
}
}
ht.numBuckets = largestBucketNum + 1
usedSize := ht.numBuckets * ht.BucketSize
if usedSize > ht.Size {
ht.Used = ht.Size
ht.EnsureSize(usedSize - ht.Used)
}
ht.Used = usedSize
tdlog.Infof("%s: calculated used size is %d", ht.Path, usedSize)
} | go | func (ht *HashTable) calculateNumBuckets() {
ht.numBuckets = ht.Size / ht.BucketSize
largestBucketNum := ht.InitialBuckets - 1
for i := 0; i < ht.InitialBuckets; i++ {
lastBucket := ht.lastBucket(i)
if lastBucket > largestBucketNum && lastBucket < ht.numBuckets {
largestBucketNum = lastBucket
}
}
ht.numBuckets = largestBucketNum + 1
usedSize := ht.numBuckets * ht.BucketSize
if usedSize > ht.Size {
ht.Used = ht.Size
ht.EnsureSize(usedSize - ht.Used)
}
ht.Used = usedSize
tdlog.Infof("%s: calculated used size is %d", ht.Path, usedSize)
} | [
"func",
"(",
"ht",
"*",
"HashTable",
")",
"calculateNumBuckets",
"(",
")",
"{",
"ht",
".",
"numBuckets",
"=",
"ht",
".",
"Size",
"/",
"ht",
".",
"BucketSize",
"\n",
"largestBucketNum",
":=",
"ht",
".",
"InitialBuckets",
"-",
"1",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"ht",
".",
"InitialBuckets",
";",
"i",
"++",
"{",
"lastBucket",
":=",
"ht",
".",
"lastBucket",
"(",
"i",
")",
"\n",
"if",
"lastBucket",
">",
"largestBucketNum",
"&&",
"lastBucket",
"<",
"ht",
".",
"numBuckets",
"{",
"largestBucketNum",
"=",
"lastBucket",
"\n",
"}",
"\n",
"}",
"\n",
"ht",
".",
"numBuckets",
"=",
"largestBucketNum",
"+",
"1",
"\n",
"usedSize",
":=",
"ht",
".",
"numBuckets",
"*",
"ht",
".",
"BucketSize",
"\n",
"if",
"usedSize",
">",
"ht",
".",
"Size",
"{",
"ht",
".",
"Used",
"=",
"ht",
".",
"Size",
"\n",
"ht",
".",
"EnsureSize",
"(",
"usedSize",
"-",
"ht",
".",
"Used",
")",
"\n",
"}",
"\n",
"ht",
".",
"Used",
"=",
"usedSize",
"\n",
"tdlog",
".",
"Infof",
"(",
"\"",
"\"",
",",
"ht",
".",
"Path",
",",
"usedSize",
")",
"\n",
"}"
] | // Follow the longest bucket chain to calculate total number of buckets, hence the "used size" of hash table file. | [
"Follow",
"the",
"longest",
"bucket",
"chain",
"to",
"calculate",
"total",
"number",
"of",
"buckets",
"hence",
"the",
"used",
"size",
"of",
"hash",
"table",
"file",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L41-L58 |
HouzuoGuo/tiedot | data/hashtable.go | nextBucket | func (ht *HashTable) nextBucket(bucket int) int {
if bucket >= ht.numBuckets {
return 0
}
bucketAddr := bucket * ht.BucketSize
nextUint, err := binary.Varint(ht.Buf[bucketAddr : bucketAddr+10])
next := int(nextUint)
if next == 0 {
return 0
} else if err < 0 || next <= bucket || next >= ht.numBuckets || next < ht.InitialBuckets {
tdlog.CritNoRepeat("Bad hash table - repair ASAP %s", ht.Path)
return 0
} else {
return next
}
} | go | func (ht *HashTable) nextBucket(bucket int) int {
if bucket >= ht.numBuckets {
return 0
}
bucketAddr := bucket * ht.BucketSize
nextUint, err := binary.Varint(ht.Buf[bucketAddr : bucketAddr+10])
next := int(nextUint)
if next == 0 {
return 0
} else if err < 0 || next <= bucket || next >= ht.numBuckets || next < ht.InitialBuckets {
tdlog.CritNoRepeat("Bad hash table - repair ASAP %s", ht.Path)
return 0
} else {
return next
}
} | [
"func",
"(",
"ht",
"*",
"HashTable",
")",
"nextBucket",
"(",
"bucket",
"int",
")",
"int",
"{",
"if",
"bucket",
">=",
"ht",
".",
"numBuckets",
"{",
"return",
"0",
"\n",
"}",
"\n",
"bucketAddr",
":=",
"bucket",
"*",
"ht",
".",
"BucketSize",
"\n",
"nextUint",
",",
"err",
":=",
"binary",
".",
"Varint",
"(",
"ht",
".",
"Buf",
"[",
"bucketAddr",
":",
"bucketAddr",
"+",
"10",
"]",
")",
"\n",
"next",
":=",
"int",
"(",
"nextUint",
")",
"\n",
"if",
"next",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"else",
"if",
"err",
"<",
"0",
"||",
"next",
"<=",
"bucket",
"||",
"next",
">=",
"ht",
".",
"numBuckets",
"||",
"next",
"<",
"ht",
".",
"InitialBuckets",
"{",
"tdlog",
".",
"CritNoRepeat",
"(",
"\"",
"\"",
",",
"ht",
".",
"Path",
")",
"\n",
"return",
"0",
"\n",
"}",
"else",
"{",
"return",
"next",
"\n",
"}",
"\n",
"}"
] | // Return number of the next chained bucket. | [
"Return",
"number",
"of",
"the",
"next",
"chained",
"bucket",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L61-L76 |
HouzuoGuo/tiedot | data/hashtable.go | lastBucket | func (ht *HashTable) lastBucket(bucket int) int {
for curr := bucket; ; {
next := ht.nextBucket(curr)
if next == 0 {
return curr
}
curr = next
}
} | go | func (ht *HashTable) lastBucket(bucket int) int {
for curr := bucket; ; {
next := ht.nextBucket(curr)
if next == 0 {
return curr
}
curr = next
}
} | [
"func",
"(",
"ht",
"*",
"HashTable",
")",
"lastBucket",
"(",
"bucket",
"int",
")",
"int",
"{",
"for",
"curr",
":=",
"bucket",
";",
";",
"{",
"next",
":=",
"ht",
".",
"nextBucket",
"(",
"curr",
")",
"\n",
"if",
"next",
"==",
"0",
"{",
"return",
"curr",
"\n",
"}",
"\n",
"curr",
"=",
"next",
"\n",
"}",
"\n",
"}"
] | // Return number of the last bucket in chain. | [
"Return",
"number",
"of",
"the",
"last",
"bucket",
"in",
"chain",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L79-L87 |
HouzuoGuo/tiedot | data/hashtable.go | growBucket | func (ht *HashTable) growBucket(bucket int) {
ht.EnsureSize(ht.BucketSize)
lastBucketAddr := ht.lastBucket(bucket) * ht.BucketSize
binary.PutVarint(ht.Buf[lastBucketAddr:lastBucketAddr+10], int64(ht.numBuckets))
ht.Used += ht.BucketSize
ht.numBuckets++
} | go | func (ht *HashTable) growBucket(bucket int) {
ht.EnsureSize(ht.BucketSize)
lastBucketAddr := ht.lastBucket(bucket) * ht.BucketSize
binary.PutVarint(ht.Buf[lastBucketAddr:lastBucketAddr+10], int64(ht.numBuckets))
ht.Used += ht.BucketSize
ht.numBuckets++
} | [
"func",
"(",
"ht",
"*",
"HashTable",
")",
"growBucket",
"(",
"bucket",
"int",
")",
"{",
"ht",
".",
"EnsureSize",
"(",
"ht",
".",
"BucketSize",
")",
"\n",
"lastBucketAddr",
":=",
"ht",
".",
"lastBucket",
"(",
"bucket",
")",
"*",
"ht",
".",
"BucketSize",
"\n",
"binary",
".",
"PutVarint",
"(",
"ht",
".",
"Buf",
"[",
"lastBucketAddr",
":",
"lastBucketAddr",
"+",
"10",
"]",
",",
"int64",
"(",
"ht",
".",
"numBuckets",
")",
")",
"\n",
"ht",
".",
"Used",
"+=",
"ht",
".",
"BucketSize",
"\n",
"ht",
".",
"numBuckets",
"++",
"\n",
"}"
] | // Create and chain a new bucket. | [
"Create",
"and",
"chain",
"a",
"new",
"bucket",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L90-L96 |
HouzuoGuo/tiedot | data/hashtable.go | Clear | func (ht *HashTable) Clear() (err error) {
if err = ht.DataFile.Clear(); err != nil {
return
}
ht.calculateNumBuckets()
return
} | go | func (ht *HashTable) Clear() (err error) {
if err = ht.DataFile.Clear(); err != nil {
return
}
ht.calculateNumBuckets()
return
} | [
"func",
"(",
"ht",
"*",
"HashTable",
")",
"Clear",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"err",
"=",
"ht",
".",
"DataFile",
".",
"Clear",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"ht",
".",
"calculateNumBuckets",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Clear the entire hash table. | [
"Clear",
"the",
"entire",
"hash",
"table",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L99-L105 |
HouzuoGuo/tiedot | data/hashtable.go | Put | func (ht *HashTable) Put(key, val int) {
for bucket, entry := ht.HashKey(key), 0; ; {
entryAddr := bucket*ht.BucketSize + BucketHeader + entry*EntrySize
if ht.Buf[entryAddr] != 1 {
ht.Buf[entryAddr] = 1
binary.PutVarint(ht.Buf[entryAddr+1:entryAddr+11], int64(key))
binary.PutVarint(ht.Buf[entryAddr+11:entryAddr+21], int64(val))
return
}
if entry++; entry == ht.PerBucket {
entry = 0
if bucket = ht.nextBucket(bucket); bucket == 0 {
ht.growBucket(ht.HashKey(key))
ht.Put(key, val)
return
}
}
}
} | go | func (ht *HashTable) Put(key, val int) {
for bucket, entry := ht.HashKey(key), 0; ; {
entryAddr := bucket*ht.BucketSize + BucketHeader + entry*EntrySize
if ht.Buf[entryAddr] != 1 {
ht.Buf[entryAddr] = 1
binary.PutVarint(ht.Buf[entryAddr+1:entryAddr+11], int64(key))
binary.PutVarint(ht.Buf[entryAddr+11:entryAddr+21], int64(val))
return
}
if entry++; entry == ht.PerBucket {
entry = 0
if bucket = ht.nextBucket(bucket); bucket == 0 {
ht.growBucket(ht.HashKey(key))
ht.Put(key, val)
return
}
}
}
} | [
"func",
"(",
"ht",
"*",
"HashTable",
")",
"Put",
"(",
"key",
",",
"val",
"int",
")",
"{",
"for",
"bucket",
",",
"entry",
":=",
"ht",
".",
"HashKey",
"(",
"key",
")",
",",
"0",
";",
";",
"{",
"entryAddr",
":=",
"bucket",
"*",
"ht",
".",
"BucketSize",
"+",
"BucketHeader",
"+",
"entry",
"*",
"EntrySize",
"\n",
"if",
"ht",
".",
"Buf",
"[",
"entryAddr",
"]",
"!=",
"1",
"{",
"ht",
".",
"Buf",
"[",
"entryAddr",
"]",
"=",
"1",
"\n",
"binary",
".",
"PutVarint",
"(",
"ht",
".",
"Buf",
"[",
"entryAddr",
"+",
"1",
":",
"entryAddr",
"+",
"11",
"]",
",",
"int64",
"(",
"key",
")",
")",
"\n",
"binary",
".",
"PutVarint",
"(",
"ht",
".",
"Buf",
"[",
"entryAddr",
"+",
"11",
":",
"entryAddr",
"+",
"21",
"]",
",",
"int64",
"(",
"val",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"entry",
"++",
";",
"entry",
"==",
"ht",
".",
"PerBucket",
"{",
"entry",
"=",
"0",
"\n",
"if",
"bucket",
"=",
"ht",
".",
"nextBucket",
"(",
"bucket",
")",
";",
"bucket",
"==",
"0",
"{",
"ht",
".",
"growBucket",
"(",
"ht",
".",
"HashKey",
"(",
"key",
")",
")",
"\n",
"ht",
".",
"Put",
"(",
"key",
",",
"val",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Store the entry into a vacant (invalidated or empty) place in the appropriate bucket. | [
"Store",
"the",
"entry",
"into",
"a",
"vacant",
"(",
"invalidated",
"or",
"empty",
")",
"place",
"in",
"the",
"appropriate",
"bucket",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L108-L126 |
HouzuoGuo/tiedot | data/hashtable.go | Get | func (ht *HashTable) Get(key, limit int) (vals []int) {
if limit == 0 {
vals = make([]int, 0, 10)
} else {
vals = make([]int, 0, limit)
}
for count, entry, bucket := 0, 0, ht.HashKey(key); ; {
entryAddr := bucket*ht.BucketSize + BucketHeader + entry*EntrySize
entryKey, _ := binary.Varint(ht.Buf[entryAddr+1 : entryAddr+11])
entryVal, _ := binary.Varint(ht.Buf[entryAddr+11 : entryAddr+21])
if ht.Buf[entryAddr] == 1 {
if int(entryKey) == key {
vals = append(vals, int(entryVal))
if count++; count == limit {
return
}
}
} else if entryKey == 0 && entryVal == 0 {
return
}
if entry++; entry == ht.PerBucket {
entry = 0
if bucket = ht.nextBucket(bucket); bucket == 0 {
return
}
}
}
} | go | func (ht *HashTable) Get(key, limit int) (vals []int) {
if limit == 0 {
vals = make([]int, 0, 10)
} else {
vals = make([]int, 0, limit)
}
for count, entry, bucket := 0, 0, ht.HashKey(key); ; {
entryAddr := bucket*ht.BucketSize + BucketHeader + entry*EntrySize
entryKey, _ := binary.Varint(ht.Buf[entryAddr+1 : entryAddr+11])
entryVal, _ := binary.Varint(ht.Buf[entryAddr+11 : entryAddr+21])
if ht.Buf[entryAddr] == 1 {
if int(entryKey) == key {
vals = append(vals, int(entryVal))
if count++; count == limit {
return
}
}
} else if entryKey == 0 && entryVal == 0 {
return
}
if entry++; entry == ht.PerBucket {
entry = 0
if bucket = ht.nextBucket(bucket); bucket == 0 {
return
}
}
}
} | [
"func",
"(",
"ht",
"*",
"HashTable",
")",
"Get",
"(",
"key",
",",
"limit",
"int",
")",
"(",
"vals",
"[",
"]",
"int",
")",
"{",
"if",
"limit",
"==",
"0",
"{",
"vals",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"0",
",",
"10",
")",
"\n",
"}",
"else",
"{",
"vals",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"0",
",",
"limit",
")",
"\n",
"}",
"\n",
"for",
"count",
",",
"entry",
",",
"bucket",
":=",
"0",
",",
"0",
",",
"ht",
".",
"HashKey",
"(",
"key",
")",
";",
";",
"{",
"entryAddr",
":=",
"bucket",
"*",
"ht",
".",
"BucketSize",
"+",
"BucketHeader",
"+",
"entry",
"*",
"EntrySize",
"\n",
"entryKey",
",",
"_",
":=",
"binary",
".",
"Varint",
"(",
"ht",
".",
"Buf",
"[",
"entryAddr",
"+",
"1",
":",
"entryAddr",
"+",
"11",
"]",
")",
"\n",
"entryVal",
",",
"_",
":=",
"binary",
".",
"Varint",
"(",
"ht",
".",
"Buf",
"[",
"entryAddr",
"+",
"11",
":",
"entryAddr",
"+",
"21",
"]",
")",
"\n",
"if",
"ht",
".",
"Buf",
"[",
"entryAddr",
"]",
"==",
"1",
"{",
"if",
"int",
"(",
"entryKey",
")",
"==",
"key",
"{",
"vals",
"=",
"append",
"(",
"vals",
",",
"int",
"(",
"entryVal",
")",
")",
"\n",
"if",
"count",
"++",
";",
"count",
"==",
"limit",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"if",
"entryKey",
"==",
"0",
"&&",
"entryVal",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"if",
"entry",
"++",
";",
"entry",
"==",
"ht",
".",
"PerBucket",
"{",
"entry",
"=",
"0",
"\n",
"if",
"bucket",
"=",
"ht",
".",
"nextBucket",
"(",
"bucket",
")",
";",
"bucket",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Look up values by key. | [
"Look",
"up",
"values",
"by",
"key",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L129-L156 |
HouzuoGuo/tiedot | data/hashtable.go | Remove | func (ht *HashTable) Remove(key, val int) {
for entry, bucket := 0, ht.HashKey(key); ; {
entryAddr := bucket*ht.BucketSize + BucketHeader + entry*EntrySize
entryKey, _ := binary.Varint(ht.Buf[entryAddr+1 : entryAddr+11])
entryVal, _ := binary.Varint(ht.Buf[entryAddr+11 : entryAddr+21])
if ht.Buf[entryAddr] == 1 {
if int(entryKey) == key && int(entryVal) == val {
ht.Buf[entryAddr] = 0
return
}
} else if entryKey == 0 && entryVal == 0 {
return
}
if entry++; entry == ht.PerBucket {
entry = 0
if bucket = ht.nextBucket(bucket); bucket == 0 {
return
}
}
}
} | go | func (ht *HashTable) Remove(key, val int) {
for entry, bucket := 0, ht.HashKey(key); ; {
entryAddr := bucket*ht.BucketSize + BucketHeader + entry*EntrySize
entryKey, _ := binary.Varint(ht.Buf[entryAddr+1 : entryAddr+11])
entryVal, _ := binary.Varint(ht.Buf[entryAddr+11 : entryAddr+21])
if ht.Buf[entryAddr] == 1 {
if int(entryKey) == key && int(entryVal) == val {
ht.Buf[entryAddr] = 0
return
}
} else if entryKey == 0 && entryVal == 0 {
return
}
if entry++; entry == ht.PerBucket {
entry = 0
if bucket = ht.nextBucket(bucket); bucket == 0 {
return
}
}
}
} | [
"func",
"(",
"ht",
"*",
"HashTable",
")",
"Remove",
"(",
"key",
",",
"val",
"int",
")",
"{",
"for",
"entry",
",",
"bucket",
":=",
"0",
",",
"ht",
".",
"HashKey",
"(",
"key",
")",
";",
";",
"{",
"entryAddr",
":=",
"bucket",
"*",
"ht",
".",
"BucketSize",
"+",
"BucketHeader",
"+",
"entry",
"*",
"EntrySize",
"\n",
"entryKey",
",",
"_",
":=",
"binary",
".",
"Varint",
"(",
"ht",
".",
"Buf",
"[",
"entryAddr",
"+",
"1",
":",
"entryAddr",
"+",
"11",
"]",
")",
"\n",
"entryVal",
",",
"_",
":=",
"binary",
".",
"Varint",
"(",
"ht",
".",
"Buf",
"[",
"entryAddr",
"+",
"11",
":",
"entryAddr",
"+",
"21",
"]",
")",
"\n",
"if",
"ht",
".",
"Buf",
"[",
"entryAddr",
"]",
"==",
"1",
"{",
"if",
"int",
"(",
"entryKey",
")",
"==",
"key",
"&&",
"int",
"(",
"entryVal",
")",
"==",
"val",
"{",
"ht",
".",
"Buf",
"[",
"entryAddr",
"]",
"=",
"0",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"else",
"if",
"entryKey",
"==",
"0",
"&&",
"entryVal",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"if",
"entry",
"++",
";",
"entry",
"==",
"ht",
".",
"PerBucket",
"{",
"entry",
"=",
"0",
"\n",
"if",
"bucket",
"=",
"ht",
".",
"nextBucket",
"(",
"bucket",
")",
";",
"bucket",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Flag an entry as invalid, so that Get will not return it later on. | [
"Flag",
"an",
"entry",
"as",
"invalid",
"so",
"that",
"Get",
"will",
"not",
"return",
"it",
"later",
"on",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L159-L179 |
HouzuoGuo/tiedot | data/hashtable.go | GetPartitionRange | func (conf *Config) GetPartitionRange(partNum, totalParts int) (start int, end int) {
perPart := conf.InitialBuckets / totalParts
leftOver := conf.InitialBuckets % totalParts
start = partNum * perPart
if leftOver > 0 {
if partNum == 0 {
end++
} else if partNum < leftOver {
start += partNum
end++
} else {
start += leftOver
}
}
end += start + perPart
if partNum == totalParts-1 {
end = conf.InitialBuckets
}
return
} | go | func (conf *Config) GetPartitionRange(partNum, totalParts int) (start int, end int) {
perPart := conf.InitialBuckets / totalParts
leftOver := conf.InitialBuckets % totalParts
start = partNum * perPart
if leftOver > 0 {
if partNum == 0 {
end++
} else if partNum < leftOver {
start += partNum
end++
} else {
start += leftOver
}
}
end += start + perPart
if partNum == totalParts-1 {
end = conf.InitialBuckets
}
return
} | [
"func",
"(",
"conf",
"*",
"Config",
")",
"GetPartitionRange",
"(",
"partNum",
",",
"totalParts",
"int",
")",
"(",
"start",
"int",
",",
"end",
"int",
")",
"{",
"perPart",
":=",
"conf",
".",
"InitialBuckets",
"/",
"totalParts",
"\n",
"leftOver",
":=",
"conf",
".",
"InitialBuckets",
"%",
"totalParts",
"\n",
"start",
"=",
"partNum",
"*",
"perPart",
"\n",
"if",
"leftOver",
">",
"0",
"{",
"if",
"partNum",
"==",
"0",
"{",
"end",
"++",
"\n",
"}",
"else",
"if",
"partNum",
"<",
"leftOver",
"{",
"start",
"+=",
"partNum",
"\n",
"end",
"++",
"\n",
"}",
"else",
"{",
"start",
"+=",
"leftOver",
"\n",
"}",
"\n",
"}",
"\n",
"end",
"+=",
"start",
"+",
"perPart",
"\n",
"if",
"partNum",
"==",
"totalParts",
"-",
"1",
"{",
"end",
"=",
"conf",
".",
"InitialBuckets",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Divide the entire hash table into roughly equally sized partitions, and return the start/end key range of the chosen partition. | [
"Divide",
"the",
"entire",
"hash",
"table",
"into",
"roughly",
"equally",
"sized",
"partitions",
"and",
"return",
"the",
"start",
"/",
"end",
"key",
"range",
"of",
"the",
"chosen",
"partition",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L182-L201 |
HouzuoGuo/tiedot | data/hashtable.go | collectEntries | func (ht *HashTable) collectEntries(head int) (keys, vals []int) {
keys = make([]int, 0, ht.PerBucket)
vals = make([]int, 0, ht.PerBucket)
var entry, bucket int = 0, head
for {
entryAddr := bucket*ht.BucketSize + BucketHeader + entry*EntrySize
entryKey, _ := binary.Varint(ht.Buf[entryAddr+1 : entryAddr+11])
entryVal, _ := binary.Varint(ht.Buf[entryAddr+11 : entryAddr+21])
if ht.Buf[entryAddr] == 1 {
keys = append(keys, int(entryKey))
vals = append(vals, int(entryVal))
} else if entryKey == 0 && entryVal == 0 {
return
}
if entry++; entry == ht.PerBucket {
entry = 0
if bucket = ht.nextBucket(bucket); bucket == 0 {
return
}
}
}
} | go | func (ht *HashTable) collectEntries(head int) (keys, vals []int) {
keys = make([]int, 0, ht.PerBucket)
vals = make([]int, 0, ht.PerBucket)
var entry, bucket int = 0, head
for {
entryAddr := bucket*ht.BucketSize + BucketHeader + entry*EntrySize
entryKey, _ := binary.Varint(ht.Buf[entryAddr+1 : entryAddr+11])
entryVal, _ := binary.Varint(ht.Buf[entryAddr+11 : entryAddr+21])
if ht.Buf[entryAddr] == 1 {
keys = append(keys, int(entryKey))
vals = append(vals, int(entryVal))
} else if entryKey == 0 && entryVal == 0 {
return
}
if entry++; entry == ht.PerBucket {
entry = 0
if bucket = ht.nextBucket(bucket); bucket == 0 {
return
}
}
}
} | [
"func",
"(",
"ht",
"*",
"HashTable",
")",
"collectEntries",
"(",
"head",
"int",
")",
"(",
"keys",
",",
"vals",
"[",
"]",
"int",
")",
"{",
"keys",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"0",
",",
"ht",
".",
"PerBucket",
")",
"\n",
"vals",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"0",
",",
"ht",
".",
"PerBucket",
")",
"\n",
"var",
"entry",
",",
"bucket",
"int",
"=",
"0",
",",
"head",
"\n",
"for",
"{",
"entryAddr",
":=",
"bucket",
"*",
"ht",
".",
"BucketSize",
"+",
"BucketHeader",
"+",
"entry",
"*",
"EntrySize",
"\n",
"entryKey",
",",
"_",
":=",
"binary",
".",
"Varint",
"(",
"ht",
".",
"Buf",
"[",
"entryAddr",
"+",
"1",
":",
"entryAddr",
"+",
"11",
"]",
")",
"\n",
"entryVal",
",",
"_",
":=",
"binary",
".",
"Varint",
"(",
"ht",
".",
"Buf",
"[",
"entryAddr",
"+",
"11",
":",
"entryAddr",
"+",
"21",
"]",
")",
"\n",
"if",
"ht",
".",
"Buf",
"[",
"entryAddr",
"]",
"==",
"1",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"int",
"(",
"entryKey",
")",
")",
"\n",
"vals",
"=",
"append",
"(",
"vals",
",",
"int",
"(",
"entryVal",
")",
")",
"\n",
"}",
"else",
"if",
"entryKey",
"==",
"0",
"&&",
"entryVal",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"if",
"entry",
"++",
";",
"entry",
"==",
"ht",
".",
"PerBucket",
"{",
"entry",
"=",
"0",
"\n",
"if",
"bucket",
"=",
"ht",
".",
"nextBucket",
"(",
"bucket",
")",
";",
"bucket",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Collect entries all the way from "head" bucket to the end of its chained buckets. | [
"Collect",
"entries",
"all",
"the",
"way",
"from",
"head",
"bucket",
"to",
"the",
"end",
"of",
"its",
"chained",
"buckets",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L204-L225 |
HouzuoGuo/tiedot | data/hashtable.go | GetPartition | func (ht *HashTable) GetPartition(partNum, partSize int) (keys, vals []int) {
rangeStart, rangeEnd := ht.GetPartitionRange(partNum, partSize)
prealloc := (rangeEnd - rangeStart) * ht.PerBucket
keys = make([]int, 0, prealloc)
vals = make([]int, 0, prealloc)
for head := rangeStart; head < rangeEnd; head++ {
k, v := ht.collectEntries(head)
keys = append(keys, k...)
vals = append(vals, v...)
}
return
} | go | func (ht *HashTable) GetPartition(partNum, partSize int) (keys, vals []int) {
rangeStart, rangeEnd := ht.GetPartitionRange(partNum, partSize)
prealloc := (rangeEnd - rangeStart) * ht.PerBucket
keys = make([]int, 0, prealloc)
vals = make([]int, 0, prealloc)
for head := rangeStart; head < rangeEnd; head++ {
k, v := ht.collectEntries(head)
keys = append(keys, k...)
vals = append(vals, v...)
}
return
} | [
"func",
"(",
"ht",
"*",
"HashTable",
")",
"GetPartition",
"(",
"partNum",
",",
"partSize",
"int",
")",
"(",
"keys",
",",
"vals",
"[",
"]",
"int",
")",
"{",
"rangeStart",
",",
"rangeEnd",
":=",
"ht",
".",
"GetPartitionRange",
"(",
"partNum",
",",
"partSize",
")",
"\n",
"prealloc",
":=",
"(",
"rangeEnd",
"-",
"rangeStart",
")",
"*",
"ht",
".",
"PerBucket",
"\n",
"keys",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"0",
",",
"prealloc",
")",
"\n",
"vals",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"0",
",",
"prealloc",
")",
"\n",
"for",
"head",
":=",
"rangeStart",
";",
"head",
"<",
"rangeEnd",
";",
"head",
"++",
"{",
"k",
",",
"v",
":=",
"ht",
".",
"collectEntries",
"(",
"head",
")",
"\n",
"keys",
"=",
"append",
"(",
"keys",
",",
"k",
"...",
")",
"\n",
"vals",
"=",
"append",
"(",
"vals",
",",
"v",
"...",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Return all entries in the chosen partition. | [
"Return",
"all",
"entries",
"in",
"the",
"chosen",
"partition",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L228-L239 |
HouzuoGuo/tiedot | httpapi/document.go | Insert | func Insert(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, doc string
if !Require(w, r, "col", &col) {
return
}
defer r.Body.Close()
bodyBytes, _ := ioutil.ReadAll(r.Body)
doc = string(bodyBytes)
if doc == "" && !Require(w, r, "doc", &doc) {
return
}
var jsonDoc map[string]interface{}
if err := json.Unmarshal([]byte(doc), &jsonDoc); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON document.", doc), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
id, err := dbcol.Insert(jsonDoc)
if err != nil {
http.Error(w, fmt.Sprint(err), 500)
return
}
w.WriteHeader(201)
w.Write([]byte(fmt.Sprint(id)))
} | go | func Insert(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, doc string
if !Require(w, r, "col", &col) {
return
}
defer r.Body.Close()
bodyBytes, _ := ioutil.ReadAll(r.Body)
doc = string(bodyBytes)
if doc == "" && !Require(w, r, "doc", &doc) {
return
}
var jsonDoc map[string]interface{}
if err := json.Unmarshal([]byte(doc), &jsonDoc); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON document.", doc), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
id, err := dbcol.Insert(jsonDoc)
if err != nil {
http.Error(w, fmt.Sprint(err), 500)
return
}
w.WriteHeader(201)
w.Write([]byte(fmt.Sprint(id)))
} | [
"func",
"Insert",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"col",
",",
"doc",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"col",
")",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"bodyBytes",
",",
"_",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"doc",
"=",
"string",
"(",
"bodyBytes",
")",
"\n",
"if",
"doc",
"==",
"\"",
"\"",
"&&",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"doc",
")",
"{",
"return",
"\n",
"}",
"\n",
"var",
"jsonDoc",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"doc",
")",
",",
"&",
"jsonDoc",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"doc",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"dbcol",
":=",
"HttpDB",
".",
"Use",
"(",
"col",
")",
"\n",
"if",
"dbcol",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"col",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"id",
",",
"err",
":=",
"dbcol",
".",
"Insert",
"(",
"jsonDoc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"201",
")",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"fmt",
".",
"Sprint",
"(",
"id",
")",
")",
")",
"\n",
"}"
] | // Insert a document into collection. | [
"Insert",
"a",
"document",
"into",
"collection",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/document.go#L14-L46 |
HouzuoGuo/tiedot | httpapi/document.go | Get | func Get(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, id string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "id", &id) {
return
}
docID, err := strconv.Atoi(id)
if err != nil {
http.Error(w, fmt.Sprintf("Invalid document ID '%v'.", id), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
doc, err := dbcol.Read(docID)
if doc == nil {
http.Error(w, fmt.Sprintf("No such document ID %d.", docID), 404)
return
}
resp, err := json.Marshal(doc)
if err != nil {
http.Error(w, fmt.Sprint(err), 500)
return
}
w.Write(resp)
} | go | func Get(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, id string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "id", &id) {
return
}
docID, err := strconv.Atoi(id)
if err != nil {
http.Error(w, fmt.Sprintf("Invalid document ID '%v'.", id), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
doc, err := dbcol.Read(docID)
if doc == nil {
http.Error(w, fmt.Sprintf("No such document ID %d.", docID), 404)
return
}
resp, err := json.Marshal(doc)
if err != nil {
http.Error(w, fmt.Sprint(err), 500)
return
}
w.Write(resp)
} | [
"func",
"Get",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"col",
",",
"id",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"col",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"id",
")",
"{",
"return",
"\n",
"}",
"\n",
"docID",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"id",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"dbcol",
":=",
"HttpDB",
".",
"Use",
"(",
"col",
")",
"\n",
"if",
"dbcol",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"col",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"doc",
",",
"err",
":=",
"dbcol",
".",
"Read",
"(",
"docID",
")",
"\n",
"if",
"doc",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"docID",
")",
",",
"404",
")",
"\n",
"return",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"doc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"resp",
")",
"\n",
"}"
] | // Find and retrieve a document by ID. | [
"Find",
"and",
"retrieve",
"a",
"document",
"by",
"ID",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/document.go#L49-L82 |
HouzuoGuo/tiedot | httpapi/document.go | GetPage | func GetPage(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, page, total string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "page", &page) {
return
}
if !Require(w, r, "total", &total) {
return
}
totalPage, err := strconv.Atoi(total)
if err != nil || totalPage < 1 {
http.Error(w, fmt.Sprintf("Invalid total page number '%v'.", totalPage), 400)
return
}
pageNum, err := strconv.Atoi(page)
if err != nil || pageNum < 0 || pageNum >= totalPage {
http.Error(w, fmt.Sprintf("Invalid page number '%v'.", page), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
docs := make(map[string]interface{})
dbcol.ForEachDocInPage(pageNum, totalPage, func(id int, doc []byte) bool {
var docObj map[string]interface{}
if err := json.Unmarshal(doc, &docObj); err == nil {
docs[strconv.Itoa(id)] = docObj
}
return true
})
resp, err := json.Marshal(docs)
if err != nil {
http.Error(w, fmt.Sprint(err), 500)
return
}
w.Write(resp)
} | go | func GetPage(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, page, total string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "page", &page) {
return
}
if !Require(w, r, "total", &total) {
return
}
totalPage, err := strconv.Atoi(total)
if err != nil || totalPage < 1 {
http.Error(w, fmt.Sprintf("Invalid total page number '%v'.", totalPage), 400)
return
}
pageNum, err := strconv.Atoi(page)
if err != nil || pageNum < 0 || pageNum >= totalPage {
http.Error(w, fmt.Sprintf("Invalid page number '%v'.", page), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
docs := make(map[string]interface{})
dbcol.ForEachDocInPage(pageNum, totalPage, func(id int, doc []byte) bool {
var docObj map[string]interface{}
if err := json.Unmarshal(doc, &docObj); err == nil {
docs[strconv.Itoa(id)] = docObj
}
return true
})
resp, err := json.Marshal(docs)
if err != nil {
http.Error(w, fmt.Sprint(err), 500)
return
}
w.Write(resp)
} | [
"func",
"GetPage",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"col",
",",
"page",
",",
"total",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"col",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"page",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"total",
")",
"{",
"return",
"\n",
"}",
"\n",
"totalPage",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"total",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"totalPage",
"<",
"1",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"totalPage",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"pageNum",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"page",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"pageNum",
"<",
"0",
"||",
"pageNum",
">=",
"totalPage",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"page",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"dbcol",
":=",
"HttpDB",
".",
"Use",
"(",
"col",
")",
"\n",
"if",
"dbcol",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"col",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"docs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"dbcol",
".",
"ForEachDocInPage",
"(",
"pageNum",
",",
"totalPage",
",",
"func",
"(",
"id",
"int",
",",
"doc",
"[",
"]",
"byte",
")",
"bool",
"{",
"var",
"docObj",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"doc",
",",
"&",
"docObj",
")",
";",
"err",
"==",
"nil",
"{",
"docs",
"[",
"strconv",
".",
"Itoa",
"(",
"id",
")",
"]",
"=",
"docObj",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"resp",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"docs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"resp",
")",
"\n",
"}"
] | // Divide documents into roughly equally sized pages, and return documents in the specified page. | [
"Divide",
"documents",
"into",
"roughly",
"equally",
"sized",
"pages",
"and",
"return",
"documents",
"in",
"the",
"specified",
"page",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/document.go#L85-L129 |
HouzuoGuo/tiedot | httpapi/document.go | Update | func Update(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, id, doc string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "id", &id) {
return
}
defer r.Body.Close()
bodyBytes, _ := ioutil.ReadAll(r.Body)
doc = string(bodyBytes)
if doc == "" && !Require(w, r, "doc", &doc) {
return
}
docID, err := strconv.Atoi(id)
if err != nil {
http.Error(w, fmt.Sprintf("Invalid document ID '%v'.", id), 400)
return
}
var newDoc map[string]interface{}
if err := json.Unmarshal([]byte(doc), &newDoc); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON document.", newDoc), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
err = dbcol.Update(docID, newDoc)
if err != nil {
http.Error(w, fmt.Sprint(err), 500)
return
}
} | go | func Update(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, id, doc string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "id", &id) {
return
}
defer r.Body.Close()
bodyBytes, _ := ioutil.ReadAll(r.Body)
doc = string(bodyBytes)
if doc == "" && !Require(w, r, "doc", &doc) {
return
}
docID, err := strconv.Atoi(id)
if err != nil {
http.Error(w, fmt.Sprintf("Invalid document ID '%v'.", id), 400)
return
}
var newDoc map[string]interface{}
if err := json.Unmarshal([]byte(doc), &newDoc); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON document.", newDoc), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
err = dbcol.Update(docID, newDoc)
if err != nil {
http.Error(w, fmt.Sprint(err), 500)
return
}
} | [
"func",
"Update",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"col",
",",
"id",
",",
"doc",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"col",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"id",
")",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"bodyBytes",
",",
"_",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"doc",
"=",
"string",
"(",
"bodyBytes",
")",
"\n",
"if",
"doc",
"==",
"\"",
"\"",
"&&",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"doc",
")",
"{",
"return",
"\n",
"}",
"\n",
"docID",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"id",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"newDoc",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"doc",
")",
",",
"&",
"newDoc",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"newDoc",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"dbcol",
":=",
"HttpDB",
".",
"Use",
"(",
"col",
")",
"\n",
"if",
"dbcol",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"col",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"err",
"=",
"dbcol",
".",
"Update",
"(",
"docID",
",",
"newDoc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // Update a document. | [
"Update",
"a",
"document",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/document.go#L132-L170 |
HouzuoGuo/tiedot | httpapi/document.go | Delete | func Delete(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, id string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "id", &id) {
return
}
docID, err := strconv.Atoi(id)
if err != nil {
http.Error(w, fmt.Sprintf("Invalid document ID '%v'.", id), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
dbcol.Delete(docID)
} | go | func Delete(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, id string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "id", &id) {
return
}
docID, err := strconv.Atoi(id)
if err != nil {
http.Error(w, fmt.Sprintf("Invalid document ID '%v'.", id), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
dbcol.Delete(docID)
} | [
"func",
"Delete",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"col",
",",
"id",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"col",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"id",
")",
"{",
"return",
"\n",
"}",
"\n",
"docID",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"id",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"dbcol",
":=",
"HttpDB",
".",
"Use",
"(",
"col",
")",
"\n",
"if",
"dbcol",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"col",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"dbcol",
".",
"Delete",
"(",
"docID",
")",
"\n",
"}"
] | // Delete a document. | [
"Delete",
"a",
"document",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/document.go#L173-L196 |
HouzuoGuo/tiedot | httpapi/document.go | ApproxDocCount | func ApproxDocCount(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col string
if !Require(w, r, "col", &col) {
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
w.Write([]byte(strconv.Itoa(dbcol.ApproxDocCount())))
} | go | func ApproxDocCount(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col string
if !Require(w, r, "col", &col) {
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
w.Write([]byte(strconv.Itoa(dbcol.ApproxDocCount())))
} | [
"func",
"ApproxDocCount",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"col",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"col",
")",
"{",
"return",
"\n",
"}",
"\n",
"dbcol",
":=",
"HttpDB",
".",
"Use",
"(",
"col",
")",
"\n",
"if",
"dbcol",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"col",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"strconv",
".",
"Itoa",
"(",
"dbcol",
".",
"ApproxDocCount",
"(",
")",
")",
")",
")",
"\n",
"}"
] | // Return approximate number of documents in the collection. | [
"Return",
"approximate",
"number",
"of",
"documents",
"in",
"the",
"collection",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/document.go#L199-L214 |
HouzuoGuo/tiedot | data/hash64.go | HashKey | func (conf *Config) HashKey(key int) int {
// ========== Integer-smear start =======
key = key ^ (key >> 4)
key = (key ^ 0xdeadbeef) + (key << 5)
key = key ^ (key >> 11)
// ========== Integer-smear end =========
return key & ((1 << conf.HashBits) - 1)
} | go | func (conf *Config) HashKey(key int) int {
// ========== Integer-smear start =======
key = key ^ (key >> 4)
key = (key ^ 0xdeadbeef) + (key << 5)
key = key ^ (key >> 11)
// ========== Integer-smear end =========
return key & ((1 << conf.HashBits) - 1)
} | [
"func",
"(",
"conf",
"*",
"Config",
")",
"HashKey",
"(",
"key",
"int",
")",
"int",
"{",
"// ========== Integer-smear start =======",
"key",
"=",
"key",
"^",
"(",
"key",
">>",
"4",
")",
"\n",
"key",
"=",
"(",
"key",
"^",
"0xdeadbeef",
")",
"+",
"(",
"key",
"<<",
"5",
")",
"\n",
"key",
"=",
"key",
"^",
"(",
"key",
">>",
"11",
")",
"\n",
"// ========== Integer-smear end =========",
"return",
"key",
"&",
"(",
"(",
"1",
"<<",
"conf",
".",
"HashBits",
")",
"-",
"1",
")",
"\n",
"}"
] | // Smear the integer entry key and return the portion (first HASH_BITS bytes) used for allocating the entry. | [
"Smear",
"the",
"integer",
"entry",
"key",
"and",
"return",
"the",
"portion",
"(",
"first",
"HASH_BITS",
"bytes",
")",
"used",
"for",
"allocating",
"the",
"entry",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hash64.go#L11-L18 |
HouzuoGuo/tiedot | httpapi/misc.go | Shutdown | func Shutdown(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
HttpDB.Close()
os.Exit(0)
} | go | func Shutdown(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
HttpDB.Close()
os.Exit(0)
} | [
"func",
"Shutdown",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"HttpDB",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Exit",
"(",
"0",
")",
"\n",
"}"
] | // Flush and close all data files and shutdown the entire program. | [
"Flush",
"and",
"close",
"all",
"data",
"files",
"and",
"shutdown",
"the",
"entire",
"program",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/misc.go#L14-L21 |
HouzuoGuo/tiedot | httpapi/misc.go | Dump | func Dump(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var dest string
if !Require(w, r, "dest", &dest) {
return
}
if err := HttpDB.Dump(dest); err != nil {
http.Error(w, fmt.Sprint(err), 500)
return
}
} | go | func Dump(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var dest string
if !Require(w, r, "dest", &dest) {
return
}
if err := HttpDB.Dump(dest); err != nil {
http.Error(w, fmt.Sprint(err), 500)
return
}
} | [
"func",
"Dump",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"dest",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"dest",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"err",
":=",
"HttpDB",
".",
"Dump",
"(",
"dest",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // Copy this database into destination directory. | [
"Copy",
"this",
"database",
"into",
"destination",
"directory",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/misc.go#L24-L37 |
HouzuoGuo/tiedot | httpapi/misc.go | MemStats | func MemStats(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
stats := new(runtime.MemStats)
runtime.ReadMemStats(stats)
resp, err := json.Marshal(stats)
if err != nil {
http.Error(w, "Cannot serialize MemStats to JSON.", 500)
return
}
w.Write(resp)
} | go | func MemStats(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
stats := new(runtime.MemStats)
runtime.ReadMemStats(stats)
resp, err := json.Marshal(stats)
if err != nil {
http.Error(w, "Cannot serialize MemStats to JSON.", 500)
return
}
w.Write(resp)
} | [
"func",
"MemStats",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"stats",
":=",
"new",
"(",
"runtime",
".",
"MemStats",
")",
"\n",
"runtime",
".",
"ReadMemStats",
"(",
"stats",
")",
"\n\n",
"resp",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"stats",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"resp",
")",
"\n",
"}"
] | // Return server memory statistics. | [
"Return",
"server",
"memory",
"statistics",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/misc.go#L40-L54 |
HouzuoGuo/tiedot | httpapi/misc.go | Version | func Version(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
w.Write([]byte("6"))
} | go | func Version(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
w.Write([]byte("6"))
} | [
"func",
"Version",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // Return server protocol version number. | [
"Return",
"server",
"protocol",
"version",
"number",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/misc.go#L57-L63 |
HouzuoGuo/tiedot | gommap/mmap_windows.go | mmap | func mmap(length int, hfile uintptr) ([]byte, error) {
h, errno := syscall.CreateFileMapping(syscall.Handle(hfile), nil, syscall.PAGE_READWRITE, 0, 0, nil)
if h == 0 {
return nil, os.NewSyscallError("CreateFileMapping", errno)
}
addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_WRITE, 0, 0, 0)
if addr == 0 {
return nil, os.NewSyscallError("MapViewOfFile", errno)
}
handleLock.Lock()
handleMap[addr] = h
handleLock.Unlock()
m := MMap{}
dh := m.header()
dh.Data = addr
dh.Len = length
dh.Cap = length
return m, nil
} | go | func mmap(length int, hfile uintptr) ([]byte, error) {
h, errno := syscall.CreateFileMapping(syscall.Handle(hfile), nil, syscall.PAGE_READWRITE, 0, 0, nil)
if h == 0 {
return nil, os.NewSyscallError("CreateFileMapping", errno)
}
addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_WRITE, 0, 0, 0)
if addr == 0 {
return nil, os.NewSyscallError("MapViewOfFile", errno)
}
handleLock.Lock()
handleMap[addr] = h
handleLock.Unlock()
m := MMap{}
dh := m.header()
dh.Data = addr
dh.Len = length
dh.Cap = length
return m, nil
} | [
"func",
"mmap",
"(",
"length",
"int",
",",
"hfile",
"uintptr",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"h",
",",
"errno",
":=",
"syscall",
".",
"CreateFileMapping",
"(",
"syscall",
".",
"Handle",
"(",
"hfile",
")",
",",
"nil",
",",
"syscall",
".",
"PAGE_READWRITE",
",",
"0",
",",
"0",
",",
"nil",
")",
"\n",
"if",
"h",
"==",
"0",
"{",
"return",
"nil",
",",
"os",
".",
"NewSyscallError",
"(",
"\"",
"\"",
",",
"errno",
")",
"\n",
"}",
"\n\n",
"addr",
",",
"errno",
":=",
"syscall",
".",
"MapViewOfFile",
"(",
"h",
",",
"syscall",
".",
"FILE_MAP_WRITE",
",",
"0",
",",
"0",
",",
"0",
")",
"\n",
"if",
"addr",
"==",
"0",
"{",
"return",
"nil",
",",
"os",
".",
"NewSyscallError",
"(",
"\"",
"\"",
",",
"errno",
")",
"\n",
"}",
"\n",
"handleLock",
".",
"Lock",
"(",
")",
"\n",
"handleMap",
"[",
"addr",
"]",
"=",
"h",
"\n",
"handleLock",
".",
"Unlock",
"(",
")",
"\n\n",
"m",
":=",
"MMap",
"{",
"}",
"\n",
"dh",
":=",
"m",
".",
"header",
"(",
")",
"\n",
"dh",
".",
"Data",
"=",
"addr",
"\n",
"dh",
".",
"Len",
"=",
"length",
"\n",
"dh",
".",
"Cap",
"=",
"length",
"\n\n",
"return",
"m",
",",
"nil",
"\n",
"}"
] | // Windows mmap always mapes the entire file regardless of the specified length. | [
"Windows",
"mmap",
"always",
"mapes",
"the",
"entire",
"file",
"regardless",
"of",
"the",
"specified",
"length",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/gommap/mmap_windows.go#L25-L46 |
HouzuoGuo/tiedot | data/config.go | CalculateConfigConstants | func (conf *Config) CalculateConfigConstants() {
conf.Padding = strings.Repeat(" ", 128)
conf.LenPadding = len(conf.Padding)
conf.BucketSize = BucketHeader + conf.PerBucket*EntrySize
conf.InitialBuckets = 1 << conf.HashBits
} | go | func (conf *Config) CalculateConfigConstants() {
conf.Padding = strings.Repeat(" ", 128)
conf.LenPadding = len(conf.Padding)
conf.BucketSize = BucketHeader + conf.PerBucket*EntrySize
conf.InitialBuckets = 1 << conf.HashBits
} | [
"func",
"(",
"conf",
"*",
"Config",
")",
"CalculateConfigConstants",
"(",
")",
"{",
"conf",
".",
"Padding",
"=",
"strings",
".",
"Repeat",
"(",
"\"",
"\"",
",",
"128",
")",
"\n",
"conf",
".",
"LenPadding",
"=",
"len",
"(",
"conf",
".",
"Padding",
")",
"\n\n",
"conf",
".",
"BucketSize",
"=",
"BucketHeader",
"+",
"conf",
".",
"PerBucket",
"*",
"EntrySize",
"\n",
"conf",
".",
"InitialBuckets",
"=",
"1",
"<<",
"conf",
".",
"HashBits",
"\n",
"}"
] | // CalculateConfigConstants assignes internal field values to calculation results derived from other fields. | [
"CalculateConfigConstants",
"assignes",
"internal",
"field",
"values",
"to",
"calculation",
"results",
"derived",
"from",
"other",
"fields",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/config.go#L36-L42 |
HouzuoGuo/tiedot | data/config.go | CreateOrReadConfig | func CreateOrReadConfig(path string) (conf *Config, err error) {
var file *os.File
var j []byte
if err = os.MkdirAll(path, 0700); err != nil {
return
}
filePath := fmt.Sprintf("%s/data-config.json", path)
// set the default dataConfig
conf = defaultConfig()
// try to open the file
if file, err = os.OpenFile(filePath, os.O_RDONLY, 0644); err != nil {
if _, ok := err.(*os.PathError); ok {
// if we could not find the file because it doesn't exist, lets create it
// so the database always runs with these settings
err = nil
if file, err = os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0644); err != nil {
return
}
j, err = json.MarshalIndent(conf, "", " ")
if err != nil {
return
}
if _, err = file.Write(j); err != nil {
return
}
_ = file.Close()
} else {
return
}
} else {
// if we find the file we will leave it as it is and merge
// it into the default
var b []byte
if b, err = ioutil.ReadAll(file); err != nil {
return
}
if err = json.Unmarshal(b, conf); err != nil {
return
}
_ = file.Close()
}
conf.CalculateConfigConstants()
return
} | go | func CreateOrReadConfig(path string) (conf *Config, err error) {
var file *os.File
var j []byte
if err = os.MkdirAll(path, 0700); err != nil {
return
}
filePath := fmt.Sprintf("%s/data-config.json", path)
// set the default dataConfig
conf = defaultConfig()
// try to open the file
if file, err = os.OpenFile(filePath, os.O_RDONLY, 0644); err != nil {
if _, ok := err.(*os.PathError); ok {
// if we could not find the file because it doesn't exist, lets create it
// so the database always runs with these settings
err = nil
if file, err = os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0644); err != nil {
return
}
j, err = json.MarshalIndent(conf, "", " ")
if err != nil {
return
}
if _, err = file.Write(j); err != nil {
return
}
_ = file.Close()
} else {
return
}
} else {
// if we find the file we will leave it as it is and merge
// it into the default
var b []byte
if b, err = ioutil.ReadAll(file); err != nil {
return
}
if err = json.Unmarshal(b, conf); err != nil {
return
}
_ = file.Close()
}
conf.CalculateConfigConstants()
return
} | [
"func",
"CreateOrReadConfig",
"(",
"path",
"string",
")",
"(",
"conf",
"*",
"Config",
",",
"err",
"error",
")",
"{",
"var",
"file",
"*",
"os",
".",
"File",
"\n",
"var",
"j",
"[",
"]",
"byte",
"\n\n",
"if",
"err",
"=",
"os",
".",
"MkdirAll",
"(",
"path",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"filePath",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n\n",
"// set the default dataConfig",
"conf",
"=",
"defaultConfig",
"(",
")",
"\n\n",
"// try to open the file",
"if",
"file",
",",
"err",
"=",
"os",
".",
"OpenFile",
"(",
"filePath",
",",
"os",
".",
"O_RDONLY",
",",
"0644",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"os",
".",
"PathError",
")",
";",
"ok",
"{",
"// if we could not find the file because it doesn't exist, lets create it",
"// so the database always runs with these settings",
"err",
"=",
"nil",
"\n\n",
"if",
"file",
",",
"err",
"=",
"os",
".",
"OpenFile",
"(",
"filePath",
",",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_WRONLY",
",",
"0644",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"j",
",",
"err",
"=",
"json",
".",
"MarshalIndent",
"(",
"conf",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
"=",
"file",
".",
"Write",
"(",
"j",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"_",
"=",
"file",
".",
"Close",
"(",
")",
"\n",
"}",
"else",
"{",
"return",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// if we find the file we will leave it as it is and merge",
"// it into the default",
"var",
"b",
"[",
"]",
"byte",
"\n",
"if",
"b",
",",
"err",
"=",
"ioutil",
".",
"ReadAll",
"(",
"file",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"conf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"_",
"=",
"file",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"conf",
".",
"CalculateConfigConstants",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // CreateOrReadConfig creates default performance configuration underneath the input database directory. | [
"CreateOrReadConfig",
"creates",
"default",
"performance",
"configuration",
"underneath",
"the",
"input",
"database",
"directory",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/config.go#L45-L98 |
HouzuoGuo/tiedot | httpapi/jwt.go | jwtInitSetup | func jwtInitSetup() {
// Create collection
if HttpDB.Use(JWT_COL_NAME) == nil {
if err := HttpDB.Create(JWT_COL_NAME); err != nil {
tdlog.Panicf("JWT: failed to create JWT identity collection - %v", err)
}
}
jwtCol := HttpDB.Use(JWT_COL_NAME)
// Create indexes on ID attribute
indexPaths := make(map[string]struct{})
for _, oneIndex := range jwtCol.AllIndexes() {
indexPaths[strings.Join(oneIndex, db.INDEX_PATH_SEP)] = struct{}{}
}
if _, exists := indexPaths[JWT_USER_ATTR]; !exists {
if err := jwtCol.Index([]string{JWT_USER_ATTR}); err != nil {
tdlog.Panicf("JWT: failed to create collection index - %v", err)
}
}
// Create default user "admin"
adminQuery := map[string]interface{}{
"eq": JWT_USER_ADMIN,
"in": []interface{}{JWT_USER_ATTR}}
adminQueryResult := make(map[int]struct{})
if err := db.EvalQuery(adminQuery, jwtCol, &adminQueryResult); err != nil {
tdlog.Panicf("JWT: failed to query admin user ID - %v", err)
}
if len(adminQueryResult) == 0 {
if _, err := jwtCol.Insert(map[string]interface{}{
JWT_USER_ATTR: JWT_USER_ADMIN,
JWT_PASS_ATTR: "",
JWT_COLLECTIONS_ATTR: []interface{}{},
JWT_ENDPOINTS_ATTR: []interface{}{}}); err != nil {
tdlog.Panicf("JWT: failed to create default admin user - %v", err)
}
tdlog.Notice("JWT: successfully initialized DB for JWT features. The default user 'admin' has been created.")
}
} | go | func jwtInitSetup() {
// Create collection
if HttpDB.Use(JWT_COL_NAME) == nil {
if err := HttpDB.Create(JWT_COL_NAME); err != nil {
tdlog.Panicf("JWT: failed to create JWT identity collection - %v", err)
}
}
jwtCol := HttpDB.Use(JWT_COL_NAME)
// Create indexes on ID attribute
indexPaths := make(map[string]struct{})
for _, oneIndex := range jwtCol.AllIndexes() {
indexPaths[strings.Join(oneIndex, db.INDEX_PATH_SEP)] = struct{}{}
}
if _, exists := indexPaths[JWT_USER_ATTR]; !exists {
if err := jwtCol.Index([]string{JWT_USER_ATTR}); err != nil {
tdlog.Panicf("JWT: failed to create collection index - %v", err)
}
}
// Create default user "admin"
adminQuery := map[string]interface{}{
"eq": JWT_USER_ADMIN,
"in": []interface{}{JWT_USER_ATTR}}
adminQueryResult := make(map[int]struct{})
if err := db.EvalQuery(adminQuery, jwtCol, &adminQueryResult); err != nil {
tdlog.Panicf("JWT: failed to query admin user ID - %v", err)
}
if len(adminQueryResult) == 0 {
if _, err := jwtCol.Insert(map[string]interface{}{
JWT_USER_ATTR: JWT_USER_ADMIN,
JWT_PASS_ATTR: "",
JWT_COLLECTIONS_ATTR: []interface{}{},
JWT_ENDPOINTS_ATTR: []interface{}{}}); err != nil {
tdlog.Panicf("JWT: failed to create default admin user - %v", err)
}
tdlog.Notice("JWT: successfully initialized DB for JWT features. The default user 'admin' has been created.")
}
} | [
"func",
"jwtInitSetup",
"(",
")",
"{",
"// Create collection",
"if",
"HttpDB",
".",
"Use",
"(",
"JWT_COL_NAME",
")",
"==",
"nil",
"{",
"if",
"err",
":=",
"HttpDB",
".",
"Create",
"(",
"JWT_COL_NAME",
")",
";",
"err",
"!=",
"nil",
"{",
"tdlog",
".",
"Panicf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"jwtCol",
":=",
"HttpDB",
".",
"Use",
"(",
"JWT_COL_NAME",
")",
"\n",
"// Create indexes on ID attribute",
"indexPaths",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"oneIndex",
":=",
"range",
"jwtCol",
".",
"AllIndexes",
"(",
")",
"{",
"indexPaths",
"[",
"strings",
".",
"Join",
"(",
"oneIndex",
",",
"db",
".",
"INDEX_PATH_SEP",
")",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"if",
"_",
",",
"exists",
":=",
"indexPaths",
"[",
"JWT_USER_ATTR",
"]",
";",
"!",
"exists",
"{",
"if",
"err",
":=",
"jwtCol",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"JWT_USER_ATTR",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"tdlog",
".",
"Panicf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Create default user \"admin\"",
"adminQuery",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"JWT_USER_ADMIN",
",",
"\"",
"\"",
":",
"[",
"]",
"interface",
"{",
"}",
"{",
"JWT_USER_ATTR",
"}",
"}",
"\n",
"adminQueryResult",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"\n",
"if",
"err",
":=",
"db",
".",
"EvalQuery",
"(",
"adminQuery",
",",
"jwtCol",
",",
"&",
"adminQueryResult",
")",
";",
"err",
"!=",
"nil",
"{",
"tdlog",
".",
"Panicf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"adminQueryResult",
")",
"==",
"0",
"{",
"if",
"_",
",",
"err",
":=",
"jwtCol",
".",
"Insert",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"JWT_USER_ATTR",
":",
"JWT_USER_ADMIN",
",",
"JWT_PASS_ATTR",
":",
"\"",
"\"",
",",
"JWT_COLLECTIONS_ATTR",
":",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
",",
"JWT_ENDPOINTS_ATTR",
":",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"tdlog",
".",
"Panicf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"tdlog",
".",
"Notice",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // If necessary, create the JWT identity collection, indexes, and the default/special user identity "admin". | [
"If",
"necessary",
"create",
"the",
"JWT",
"identity",
"collection",
"indexes",
"and",
"the",
"default",
"/",
"special",
"user",
"identity",
"admin",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/jwt.go#L67-L103 |
HouzuoGuo/tiedot | httpapi/jwt.go | getJWT | func getJWT(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
addCommonJwtRespHeaders(w, r)
// Verify identity
user := r.FormValue(JWT_USER_ATTR)
if user == "" {
http.Error(w, "Please pass JWT 'user' parameter", http.StatusBadRequest)
return
}
jwtCol := HttpDB.Use(JWT_COL_NAME)
if jwtCol == nil {
http.Error(w, "Server is missing JWT identity collection, please restart the server.", http.StatusInternalServerError)
return
}
userQuery := map[string]interface{}{
"eq": user,
"in": []interface{}{JWT_USER_ATTR}}
userQueryResult := make(map[int]struct{})
if err := db.EvalQuery(userQuery, jwtCol, &userQueryResult); err != nil {
tdlog.CritNoRepeat("Query failed in JWT identity collection : %v", err)
http.Error(w, "Query failed in JWT identity collection", http.StatusInternalServerError)
return
}
// Verify password
pass := r.FormValue(JWT_PASS_ATTR)
for recID := range userQueryResult {
rec, err := jwtCol.Read(recID)
if err != nil {
break
}
if rec[JWT_PASS_ATTR] != pass {
tdlog.CritNoRepeat("JWT: identitify verification failed from request sent by %s", r.RemoteAddr)
break
}
// Successful password match
token := jwt.New(jwt.GetSigningMethod("RS256"))
token.Claims = jwt.MapClaims{
JWT_USER_ATTR: rec[JWT_USER_ATTR],
JWT_COLLECTIONS_ATTR: rec[JWT_COLLECTIONS_ATTR],
JWT_ENDPOINTS_ATTR: rec[JWT_ENDPOINTS_ATTR],
JWT_EXPIRY: time.Now().Add(time.Hour * 72).Unix(),
}
var tokenString string
var e error
if tokenString, e = token.SignedString(privateKey); e != nil {
panic(e)
}
w.Header().Set("Authorization", "Bearer "+tokenString)
w.WriteHeader(http.StatusOK)
return
}
// ... password mismatch
http.Error(w, "Invalid password", http.StatusUnauthorized)
} | go | func getJWT(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
addCommonJwtRespHeaders(w, r)
// Verify identity
user := r.FormValue(JWT_USER_ATTR)
if user == "" {
http.Error(w, "Please pass JWT 'user' parameter", http.StatusBadRequest)
return
}
jwtCol := HttpDB.Use(JWT_COL_NAME)
if jwtCol == nil {
http.Error(w, "Server is missing JWT identity collection, please restart the server.", http.StatusInternalServerError)
return
}
userQuery := map[string]interface{}{
"eq": user,
"in": []interface{}{JWT_USER_ATTR}}
userQueryResult := make(map[int]struct{})
if err := db.EvalQuery(userQuery, jwtCol, &userQueryResult); err != nil {
tdlog.CritNoRepeat("Query failed in JWT identity collection : %v", err)
http.Error(w, "Query failed in JWT identity collection", http.StatusInternalServerError)
return
}
// Verify password
pass := r.FormValue(JWT_PASS_ATTR)
for recID := range userQueryResult {
rec, err := jwtCol.Read(recID)
if err != nil {
break
}
if rec[JWT_PASS_ATTR] != pass {
tdlog.CritNoRepeat("JWT: identitify verification failed from request sent by %s", r.RemoteAddr)
break
}
// Successful password match
token := jwt.New(jwt.GetSigningMethod("RS256"))
token.Claims = jwt.MapClaims{
JWT_USER_ATTR: rec[JWT_USER_ATTR],
JWT_COLLECTIONS_ATTR: rec[JWT_COLLECTIONS_ATTR],
JWT_ENDPOINTS_ATTR: rec[JWT_ENDPOINTS_ATTR],
JWT_EXPIRY: time.Now().Add(time.Hour * 72).Unix(),
}
var tokenString string
var e error
if tokenString, e = token.SignedString(privateKey); e != nil {
panic(e)
}
w.Header().Set("Authorization", "Bearer "+tokenString)
w.WriteHeader(http.StatusOK)
return
}
// ... password mismatch
http.Error(w, "Invalid password", http.StatusUnauthorized)
} | [
"func",
"getJWT",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"addCommonJwtRespHeaders",
"(",
"w",
",",
"r",
")",
"\n",
"// Verify identity",
"user",
":=",
"r",
".",
"FormValue",
"(",
"JWT_USER_ATTR",
")",
"\n",
"if",
"user",
"==",
"\"",
"\"",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"jwtCol",
":=",
"HttpDB",
".",
"Use",
"(",
"JWT_COL_NAME",
")",
"\n",
"if",
"jwtCol",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"userQuery",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"user",
",",
"\"",
"\"",
":",
"[",
"]",
"interface",
"{",
"}",
"{",
"JWT_USER_ATTR",
"}",
"}",
"\n",
"userQueryResult",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"\n",
"if",
"err",
":=",
"db",
".",
"EvalQuery",
"(",
"userQuery",
",",
"jwtCol",
",",
"&",
"userQueryResult",
")",
";",
"err",
"!=",
"nil",
"{",
"tdlog",
".",
"CritNoRepeat",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// Verify password",
"pass",
":=",
"r",
".",
"FormValue",
"(",
"JWT_PASS_ATTR",
")",
"\n",
"for",
"recID",
":=",
"range",
"userQueryResult",
"{",
"rec",
",",
"err",
":=",
"jwtCol",
".",
"Read",
"(",
"recID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"if",
"rec",
"[",
"JWT_PASS_ATTR",
"]",
"!=",
"pass",
"{",
"tdlog",
".",
"CritNoRepeat",
"(",
"\"",
"\"",
",",
"r",
".",
"RemoteAddr",
")",
"\n",
"break",
"\n",
"}",
"\n",
"// Successful password match",
"token",
":=",
"jwt",
".",
"New",
"(",
"jwt",
".",
"GetSigningMethod",
"(",
"\"",
"\"",
")",
")",
"\n",
"token",
".",
"Claims",
"=",
"jwt",
".",
"MapClaims",
"{",
"JWT_USER_ATTR",
":",
"rec",
"[",
"JWT_USER_ATTR",
"]",
",",
"JWT_COLLECTIONS_ATTR",
":",
"rec",
"[",
"JWT_COLLECTIONS_ATTR",
"]",
",",
"JWT_ENDPOINTS_ATTR",
":",
"rec",
"[",
"JWT_ENDPOINTS_ATTR",
"]",
",",
"JWT_EXPIRY",
":",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"time",
".",
"Hour",
"*",
"72",
")",
".",
"Unix",
"(",
")",
",",
"}",
"\n",
"var",
"tokenString",
"string",
"\n",
"var",
"e",
"error",
"\n",
"if",
"tokenString",
",",
"e",
"=",
"token",
".",
"SignedString",
"(",
"privateKey",
")",
";",
"e",
"!=",
"nil",
"{",
"panic",
"(",
"e",
")",
"\n",
"}",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"tokenString",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// ... password mismatch",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"}"
] | // Verify user identity and hand out a JWT. | [
"Verify",
"user",
"identity",
"and",
"hand",
"out",
"a",
"JWT",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/jwt.go#L117-L170 |
HouzuoGuo/tiedot | httpapi/jwt.go | checkJWT | func checkJWT(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
addCommonJwtRespHeaders(w, r)
// Look for JWT in both headers and request value "access_token".
token, err := request.ParseFromRequest(r, TokenExtractor{}, func(token *jwt.Token) (interface{}, error) {
// Token was signed with RSA method when it was initially granted
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return publicKey, nil
})
if err != nil || !token.Valid {
http.Error(w, fmt.Sprintf("{\"error\": \"%s %s\"}", "JWT not valid,", err), http.StatusUnauthorized)
} else {
w.WriteHeader(http.StatusOK)
}
} | go | func checkJWT(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
addCommonJwtRespHeaders(w, r)
// Look for JWT in both headers and request value "access_token".
token, err := request.ParseFromRequest(r, TokenExtractor{}, func(token *jwt.Token) (interface{}, error) {
// Token was signed with RSA method when it was initially granted
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return publicKey, nil
})
if err != nil || !token.Valid {
http.Error(w, fmt.Sprintf("{\"error\": \"%s %s\"}", "JWT not valid,", err), http.StatusUnauthorized)
} else {
w.WriteHeader(http.StatusOK)
}
} | [
"func",
"checkJWT",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"addCommonJwtRespHeaders",
"(",
"w",
",",
"r",
")",
"\n",
"// Look for JWT in both headers and request value \"access_token\".",
"token",
",",
"err",
":=",
"request",
".",
"ParseFromRequest",
"(",
"r",
",",
"TokenExtractor",
"{",
"}",
",",
"func",
"(",
"token",
"*",
"jwt",
".",
"Token",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"// Token was signed with RSA method when it was initially granted",
"if",
"_",
",",
"ok",
":=",
"token",
".",
"Method",
".",
"(",
"*",
"jwt",
".",
"SigningMethodRSA",
")",
";",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"token",
".",
"Header",
"[",
"\"",
"\"",
"]",
")",
"\n",
"}",
"\n",
"return",
"publicKey",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"!",
"token",
".",
"Valid",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
",",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"}",
"else",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}",
"\n",
"}"
] | // Verify user's JWT. | [
"Verify",
"user",
"s",
"JWT",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/jwt.go#L189-L205 |
HouzuoGuo/tiedot | httpapi/jwt.go | jwtWrap | func jwtWrap(originalHandler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
addCommonJwtRespHeaders(w, r)
// Look for JWT in both headers and request value "access_token".
token, err := request.ParseFromRequest(r, TokenExtractor{}, func(token *jwt.Token) (interface{}, error) {
// Token was signed with RSA method when it was initially granted
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return publicKey, nil
})
if err != nil || !token.Valid {
http.Error(w, "", http.StatusUnauthorized)
return
}
tokenClaims := token.Claims.(jwt.MapClaims)
var url = strings.TrimPrefix(r.URL.Path, "/")
var col = r.FormValue("col")
// Call the API endpoint handler if authorization allows
if tokenClaims[JWT_USER_ATTR] == JWT_USER_ADMIN {
originalHandler(w, r)
return
}
if !sliceContainsStr(tokenClaims[JWT_ENDPOINTS_ATTR], url) {
http.Error(w, "", http.StatusUnauthorized)
return
} else if col != "" && !sliceContainsStr(tokenClaims[JWT_COLLECTIONS_ATTR], col) {
http.Error(w, "", http.StatusUnauthorized)
return
}
originalHandler(w, r)
}
} | go | func jwtWrap(originalHandler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
addCommonJwtRespHeaders(w, r)
// Look for JWT in both headers and request value "access_token".
token, err := request.ParseFromRequest(r, TokenExtractor{}, func(token *jwt.Token) (interface{}, error) {
// Token was signed with RSA method when it was initially granted
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return publicKey, nil
})
if err != nil || !token.Valid {
http.Error(w, "", http.StatusUnauthorized)
return
}
tokenClaims := token.Claims.(jwt.MapClaims)
var url = strings.TrimPrefix(r.URL.Path, "/")
var col = r.FormValue("col")
// Call the API endpoint handler if authorization allows
if tokenClaims[JWT_USER_ATTR] == JWT_USER_ADMIN {
originalHandler(w, r)
return
}
if !sliceContainsStr(tokenClaims[JWT_ENDPOINTS_ATTR], url) {
http.Error(w, "", http.StatusUnauthorized)
return
} else if col != "" && !sliceContainsStr(tokenClaims[JWT_COLLECTIONS_ATTR], col) {
http.Error(w, "", http.StatusUnauthorized)
return
}
originalHandler(w, r)
}
} | [
"func",
"jwtWrap",
"(",
"originalHandler",
"http",
".",
"HandlerFunc",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"addCommonJwtRespHeaders",
"(",
"w",
",",
"r",
")",
"\n",
"// Look for JWT in both headers and request value \"access_token\".",
"token",
",",
"err",
":=",
"request",
".",
"ParseFromRequest",
"(",
"r",
",",
"TokenExtractor",
"{",
"}",
",",
"func",
"(",
"token",
"*",
"jwt",
".",
"Token",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"// Token was signed with RSA method when it was initially granted",
"if",
"_",
",",
"ok",
":=",
"token",
".",
"Method",
".",
"(",
"*",
"jwt",
".",
"SigningMethodRSA",
")",
";",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"token",
".",
"Header",
"[",
"\"",
"\"",
"]",
")",
"\n",
"}",
"\n",
"return",
"publicKey",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"!",
"token",
".",
"Valid",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"return",
"\n",
"}",
"\n",
"tokenClaims",
":=",
"token",
".",
"Claims",
".",
"(",
"jwt",
".",
"MapClaims",
")",
"\n",
"var",
"url",
"=",
"strings",
".",
"TrimPrefix",
"(",
"r",
".",
"URL",
".",
"Path",
",",
"\"",
"\"",
")",
"\n",
"var",
"col",
"=",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"\n",
"// Call the API endpoint handler if authorization allows",
"if",
"tokenClaims",
"[",
"JWT_USER_ATTR",
"]",
"==",
"JWT_USER_ADMIN",
"{",
"originalHandler",
"(",
"w",
",",
"r",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"!",
"sliceContainsStr",
"(",
"tokenClaims",
"[",
"JWT_ENDPOINTS_ATTR",
"]",
",",
"url",
")",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"return",
"\n",
"}",
"else",
"if",
"col",
"!=",
"\"",
"\"",
"&&",
"!",
"sliceContainsStr",
"(",
"tokenClaims",
"[",
"JWT_COLLECTIONS_ATTR",
"]",
",",
"col",
")",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"return",
"\n",
"}",
"\n",
"originalHandler",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}"
] | // Enable JWT authorization check on the HTTP handler function. | [
"Enable",
"JWT",
"authorization",
"check",
"on",
"the",
"HTTP",
"handler",
"function",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/jwt.go#L208-L240 |
HouzuoGuo/tiedot | httpapi/jwt.go | sliceContainsStr | func sliceContainsStr(possibleSlice interface{}, str string) bool {
switch possibleSlice.(type) {
case []string:
for _, elem := range possibleSlice.([]string) {
if elem == str {
return true
}
}
}
return false
} | go | func sliceContainsStr(possibleSlice interface{}, str string) bool {
switch possibleSlice.(type) {
case []string:
for _, elem := range possibleSlice.([]string) {
if elem == str {
return true
}
}
}
return false
} | [
"func",
"sliceContainsStr",
"(",
"possibleSlice",
"interface",
"{",
"}",
",",
"str",
"string",
")",
"bool",
"{",
"switch",
"possibleSlice",
".",
"(",
"type",
")",
"{",
"case",
"[",
"]",
"string",
":",
"for",
"_",
",",
"elem",
":=",
"range",
"possibleSlice",
".",
"(",
"[",
"]",
"string",
")",
"{",
"if",
"elem",
"==",
"str",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Return true if the string appears in string slice. | [
"Return",
"true",
"if",
"the",
"string",
"appears",
"in",
"string",
"slice",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/jwt.go#L243-L253 |
HouzuoGuo/tiedot | db/db.go | OpenDB | func OpenDB(dbPath string) (*DB, error) {
rand.Seed(time.Now().UnixNano()) // document ID generation relies on this RNG
d, err := data.CreateOrReadConfig(dbPath)
if err != nil {
return nil, err
}
db := &DB{Config: d, path: dbPath, schemaLock: new(sync.RWMutex)}
db.Config.CalculateConfigConstants()
return db, db.load()
} | go | func OpenDB(dbPath string) (*DB, error) {
rand.Seed(time.Now().UnixNano()) // document ID generation relies on this RNG
d, err := data.CreateOrReadConfig(dbPath)
if err != nil {
return nil, err
}
db := &DB{Config: d, path: dbPath, schemaLock: new(sync.RWMutex)}
db.Config.CalculateConfigConstants()
return db, db.load()
} | [
"func",
"OpenDB",
"(",
"dbPath",
"string",
")",
"(",
"*",
"DB",
",",
"error",
")",
"{",
"rand",
".",
"Seed",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"// document ID generation relies on this RNG",
"\n",
"d",
",",
"err",
":=",
"data",
".",
"CreateOrReadConfig",
"(",
"dbPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"db",
":=",
"&",
"DB",
"{",
"Config",
":",
"d",
",",
"path",
":",
"dbPath",
",",
"schemaLock",
":",
"new",
"(",
"sync",
".",
"RWMutex",
")",
"}",
"\n",
"db",
".",
"Config",
".",
"CalculateConfigConstants",
"(",
")",
"\n",
"return",
"db",
",",
"db",
".",
"load",
"(",
")",
"\n",
"}"
] | // Open database and load all collections & indexes. | [
"Open",
"database",
"and",
"load",
"all",
"collections",
"&",
"indexes",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L38-L47 |
HouzuoGuo/tiedot | db/db.go | load | func (db *DB) load() error {
// Create DB directory and PART_NUM_FILE if necessary
var numPartsAssumed = false
numPartsFilePath := path.Join(db.path, PART_NUM_FILE)
if err := os.MkdirAll(db.path, 0700); err != nil {
return err
}
if partNumFile, err := os.Stat(numPartsFilePath); err != nil {
// The new database has as many partitions as number of CPUs recognized by OS
if err := ioutil.WriteFile(numPartsFilePath, []byte(strconv.Itoa(runtime.NumCPU())), 0600); err != nil {
return err
}
numPartsAssumed = true
} else if partNumFile.IsDir() {
return fmt.Errorf("Database config file %s is actually a directory, is database path correct?", PART_NUM_FILE)
}
// Get number of partitions from the text file
if numParts, err := ioutil.ReadFile(numPartsFilePath); err != nil {
return err
} else if db.numParts, err = strconv.Atoi(strings.Trim(string(numParts), "\r\n ")); err != nil {
return err
}
// Look for collection directories and open the collections
db.cols = make(map[string]*Col)
dirContent, err := ioutil.ReadDir(db.path)
if err != nil {
return err
}
for _, maybeColDir := range dirContent {
if !maybeColDir.IsDir() {
continue
}
if numPartsAssumed {
return fmt.Errorf("Please manually repair database partition number config file %s", numPartsFilePath)
}
if db.cols[maybeColDir.Name()], err = OpenCol(db, maybeColDir.Name()); err != nil {
return err
}
}
return err
} | go | func (db *DB) load() error {
// Create DB directory and PART_NUM_FILE if necessary
var numPartsAssumed = false
numPartsFilePath := path.Join(db.path, PART_NUM_FILE)
if err := os.MkdirAll(db.path, 0700); err != nil {
return err
}
if partNumFile, err := os.Stat(numPartsFilePath); err != nil {
// The new database has as many partitions as number of CPUs recognized by OS
if err := ioutil.WriteFile(numPartsFilePath, []byte(strconv.Itoa(runtime.NumCPU())), 0600); err != nil {
return err
}
numPartsAssumed = true
} else if partNumFile.IsDir() {
return fmt.Errorf("Database config file %s is actually a directory, is database path correct?", PART_NUM_FILE)
}
// Get number of partitions from the text file
if numParts, err := ioutil.ReadFile(numPartsFilePath); err != nil {
return err
} else if db.numParts, err = strconv.Atoi(strings.Trim(string(numParts), "\r\n ")); err != nil {
return err
}
// Look for collection directories and open the collections
db.cols = make(map[string]*Col)
dirContent, err := ioutil.ReadDir(db.path)
if err != nil {
return err
}
for _, maybeColDir := range dirContent {
if !maybeColDir.IsDir() {
continue
}
if numPartsAssumed {
return fmt.Errorf("Please manually repair database partition number config file %s", numPartsFilePath)
}
if db.cols[maybeColDir.Name()], err = OpenCol(db, maybeColDir.Name()); err != nil {
return err
}
}
return err
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"load",
"(",
")",
"error",
"{",
"// Create DB directory and PART_NUM_FILE if necessary",
"var",
"numPartsAssumed",
"=",
"false",
"\n",
"numPartsFilePath",
":=",
"path",
".",
"Join",
"(",
"db",
".",
"path",
",",
"PART_NUM_FILE",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"db",
".",
"path",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"partNumFile",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"numPartsFilePath",
")",
";",
"err",
"!=",
"nil",
"{",
"// The new database has as many partitions as number of CPUs recognized by OS",
"if",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",
"numPartsFilePath",
",",
"[",
"]",
"byte",
"(",
"strconv",
".",
"Itoa",
"(",
"runtime",
".",
"NumCPU",
"(",
")",
")",
")",
",",
"0600",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"numPartsAssumed",
"=",
"true",
"\n",
"}",
"else",
"if",
"partNumFile",
".",
"IsDir",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"PART_NUM_FILE",
")",
"\n",
"}",
"\n",
"// Get number of partitions from the text file",
"if",
"numParts",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"numPartsFilePath",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"db",
".",
"numParts",
",",
"err",
"=",
"strconv",
".",
"Atoi",
"(",
"strings",
".",
"Trim",
"(",
"string",
"(",
"numParts",
")",
",",
"\"",
"\\r",
"\\n",
"\"",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Look for collection directories and open the collections",
"db",
".",
"cols",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Col",
")",
"\n",
"dirContent",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"db",
".",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"maybeColDir",
":=",
"range",
"dirContent",
"{",
"if",
"!",
"maybeColDir",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"numPartsAssumed",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"numPartsFilePath",
")",
"\n",
"}",
"\n",
"if",
"db",
".",
"cols",
"[",
"maybeColDir",
".",
"Name",
"(",
")",
"]",
",",
"err",
"=",
"OpenCol",
"(",
"db",
",",
"maybeColDir",
".",
"Name",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // Load all collection schema. | [
"Load",
"all",
"collection",
"schema",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L50-L90 |
HouzuoGuo/tiedot | db/db.go | Close | func (db *DB) Close() error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
errs := make([]error, 0, 0)
for _, col := range db.cols {
if err := col.close(); err != nil {
errs = append(errs, err)
}
}
if len(errs) == 0 {
return nil
}
return fmt.Errorf("%v", errs)
} | go | func (db *DB) Close() error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
errs := make([]error, 0, 0)
for _, col := range db.cols {
if err := col.close(); err != nil {
errs = append(errs, err)
}
}
if len(errs) == 0 {
return nil
}
return fmt.Errorf("%v", errs)
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"Close",
"(",
")",
"error",
"{",
"db",
".",
"schemaLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"db",
".",
"schemaLock",
".",
"Unlock",
"(",
")",
"\n",
"errs",
":=",
"make",
"(",
"[",
"]",
"error",
",",
"0",
",",
"0",
")",
"\n",
"for",
"_",
",",
"col",
":=",
"range",
"db",
".",
"cols",
"{",
"if",
"err",
":=",
"col",
".",
"close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"errs",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"errs",
")",
"\n",
"}"
] | // Close all database files. Do not use the DB afterwards! | [
"Close",
"all",
"database",
"files",
".",
"Do",
"not",
"use",
"the",
"DB",
"afterwards!"
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L93-L106 |
HouzuoGuo/tiedot | db/db.go | create | func (db *DB) create(name string) error {
if _, exists := db.cols[name]; exists {
return fmt.Errorf("Collection %s already exists", name)
} else if err := os.MkdirAll(path.Join(db.path, name), 0700); err != nil {
return err
} else if db.cols[name], err = OpenCol(db, name); err != nil {
return err
}
return nil
} | go | func (db *DB) create(name string) error {
if _, exists := db.cols[name]; exists {
return fmt.Errorf("Collection %s already exists", name)
} else if err := os.MkdirAll(path.Join(db.path, name), 0700); err != nil {
return err
} else if db.cols[name], err = OpenCol(db, name); err != nil {
return err
}
return nil
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"create",
"(",
"name",
"string",
")",
"error",
"{",
"if",
"_",
",",
"exists",
":=",
"db",
".",
"cols",
"[",
"name",
"]",
";",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"else",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"path",
".",
"Join",
"(",
"db",
".",
"path",
",",
"name",
")",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"db",
".",
"cols",
"[",
"name",
"]",
",",
"err",
"=",
"OpenCol",
"(",
"db",
",",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // create creates collection files. The function does not place a schema lock. | [
"create",
"creates",
"collection",
"files",
".",
"The",
"function",
"does",
"not",
"place",
"a",
"schema",
"lock",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L109-L118 |
HouzuoGuo/tiedot | db/db.go | Create | func (db *DB) Create(name string) error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
return db.create(name)
} | go | func (db *DB) Create(name string) error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
return db.create(name)
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"Create",
"(",
"name",
"string",
")",
"error",
"{",
"db",
".",
"schemaLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"db",
".",
"schemaLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"db",
".",
"create",
"(",
"name",
")",
"\n",
"}"
] | // Create a new collection. | [
"Create",
"a",
"new",
"collection",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L121-L125 |
HouzuoGuo/tiedot | db/db.go | AllCols | func (db *DB) AllCols() (ret []string) {
db.schemaLock.RLock()
defer db.schemaLock.RUnlock()
ret = make([]string, 0, len(db.cols))
for name := range db.cols {
ret = append(ret, name)
}
return
} | go | func (db *DB) AllCols() (ret []string) {
db.schemaLock.RLock()
defer db.schemaLock.RUnlock()
ret = make([]string, 0, len(db.cols))
for name := range db.cols {
ret = append(ret, name)
}
return
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"AllCols",
"(",
")",
"(",
"ret",
"[",
"]",
"string",
")",
"{",
"db",
".",
"schemaLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"ret",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"db",
".",
"cols",
")",
")",
"\n",
"for",
"name",
":=",
"range",
"db",
".",
"cols",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"name",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Return all collection names. | [
"Return",
"all",
"collection",
"names",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L128-L136 |
HouzuoGuo/tiedot | db/db.go | Use | func (db *DB) Use(name string) *Col {
db.schemaLock.RLock()
defer db.schemaLock.RUnlock()
if col, exists := db.cols[name]; exists {
return col
}
return nil
} | go | func (db *DB) Use(name string) *Col {
db.schemaLock.RLock()
defer db.schemaLock.RUnlock()
if col, exists := db.cols[name]; exists {
return col
}
return nil
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"Use",
"(",
"name",
"string",
")",
"*",
"Col",
"{",
"db",
".",
"schemaLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"col",
",",
"exists",
":=",
"db",
".",
"cols",
"[",
"name",
"]",
";",
"exists",
"{",
"return",
"col",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Use the return value to interact with collection. Return value may be nil if the collection does not exist. | [
"Use",
"the",
"return",
"value",
"to",
"interact",
"with",
"collection",
".",
"Return",
"value",
"may",
"be",
"nil",
"if",
"the",
"collection",
"does",
"not",
"exist",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L139-L146 |
HouzuoGuo/tiedot | db/db.go | Rename | func (db *DB) Rename(oldName, newName string) error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
if _, exists := db.cols[oldName]; !exists {
return fmt.Errorf("Collection %s does not exist", oldName)
} else if _, exists := db.cols[newName]; exists {
return fmt.Errorf("Collection %s already exists", newName)
} else if err := db.cols[oldName].close(); err != nil {
return err
} else if err := os.Rename(path.Join(db.path, oldName), path.Join(db.path, newName)); err != nil {
return err
} else if db.cols[newName], err = OpenCol(db, newName); err != nil {
return err
}
delete(db.cols, oldName)
return nil
} | go | func (db *DB) Rename(oldName, newName string) error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
if _, exists := db.cols[oldName]; !exists {
return fmt.Errorf("Collection %s does not exist", oldName)
} else if _, exists := db.cols[newName]; exists {
return fmt.Errorf("Collection %s already exists", newName)
} else if err := db.cols[oldName].close(); err != nil {
return err
} else if err := os.Rename(path.Join(db.path, oldName), path.Join(db.path, newName)); err != nil {
return err
} else if db.cols[newName], err = OpenCol(db, newName); err != nil {
return err
}
delete(db.cols, oldName)
return nil
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"Rename",
"(",
"oldName",
",",
"newName",
"string",
")",
"error",
"{",
"db",
".",
"schemaLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"db",
".",
"schemaLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"exists",
":=",
"db",
".",
"cols",
"[",
"oldName",
"]",
";",
"!",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"oldName",
")",
"\n",
"}",
"else",
"if",
"_",
",",
"exists",
":=",
"db",
".",
"cols",
"[",
"newName",
"]",
";",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"newName",
")",
"\n",
"}",
"else",
"if",
"err",
":=",
"db",
".",
"cols",
"[",
"oldName",
"]",
".",
"close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"err",
":=",
"os",
".",
"Rename",
"(",
"path",
".",
"Join",
"(",
"db",
".",
"path",
",",
"oldName",
")",
",",
"path",
".",
"Join",
"(",
"db",
".",
"path",
",",
"newName",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"db",
".",
"cols",
"[",
"newName",
"]",
",",
"err",
"=",
"OpenCol",
"(",
"db",
",",
"newName",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"delete",
"(",
"db",
".",
"cols",
",",
"oldName",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Rename a collection. | [
"Rename",
"a",
"collection",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L149-L165 |
HouzuoGuo/tiedot | db/db.go | Truncate | func (db *DB) Truncate(name string) error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
if _, exists := db.cols[name]; !exists {
return fmt.Errorf("Collection %s does not exist", name)
}
col := db.cols[name]
for i := 0; i < db.numParts; i++ {
if err := col.parts[i].Clear(); err != nil {
return err
}
for _, ht := range col.hts[i] {
if err := ht.Clear(); err != nil {
return err
}
}
}
return nil
} | go | func (db *DB) Truncate(name string) error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
if _, exists := db.cols[name]; !exists {
return fmt.Errorf("Collection %s does not exist", name)
}
col := db.cols[name]
for i := 0; i < db.numParts; i++ {
if err := col.parts[i].Clear(); err != nil {
return err
}
for _, ht := range col.hts[i] {
if err := ht.Clear(); err != nil {
return err
}
}
}
return nil
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"Truncate",
"(",
"name",
"string",
")",
"error",
"{",
"db",
".",
"schemaLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"db",
".",
"schemaLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"exists",
":=",
"db",
".",
"cols",
"[",
"name",
"]",
";",
"!",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"col",
":=",
"db",
".",
"cols",
"[",
"name",
"]",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"db",
".",
"numParts",
";",
"i",
"++",
"{",
"if",
"err",
":=",
"col",
".",
"parts",
"[",
"i",
"]",
".",
"Clear",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"ht",
":=",
"range",
"col",
".",
"hts",
"[",
"i",
"]",
"{",
"if",
"err",
":=",
"ht",
".",
"Clear",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Truncate a collection - delete all documents and clear | [
"Truncate",
"a",
"collection",
"-",
"delete",
"all",
"documents",
"and",
"clear"
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L168-L186 |
HouzuoGuo/tiedot | db/db.go | Scrub | func (db *DB) Scrub(name string) error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
if _, exists := db.cols[name]; !exists {
return fmt.Errorf("Collection %s does not exist", name)
}
// Prepare a temporary collection in file system
tmpColName := fmt.Sprintf("scrub-%s-%d", name, time.Now().UnixNano())
tmpColDir := path.Join(db.path, tmpColName)
if err := os.MkdirAll(tmpColDir, 0700); err != nil {
return err
}
// Mirror indexes from original collection
for _, idxPath := range db.cols[name].indexPaths {
if err := os.MkdirAll(path.Join(tmpColDir, strings.Join(idxPath, INDEX_PATH_SEP)), 0700); err != nil {
return err
}
}
// Iterate through all documents and put them into the temporary collection
tmpCol, err := OpenCol(db, tmpColName)
if err != nil {
return err
}
db.cols[name].forEachDoc(func(id int, doc []byte) bool {
var docObj map[string]interface{}
if err := json.Unmarshal([]byte(doc), &docObj); err != nil {
// Skip corrupted document
return true
}
if err := tmpCol.InsertRecovery(id, docObj); err != nil {
tdlog.Noticef("Scrub %s: failed to insert back document %v", name, docObj)
}
return true
}, false)
if err := tmpCol.close(); err != nil {
return err
}
// Replace the original collection with the "temporary" one
db.cols[name].close()
if err := os.RemoveAll(path.Join(db.path, name)); err != nil {
return err
}
if err := os.Rename(path.Join(db.path, tmpColName), path.Join(db.path, name)); err != nil {
return err
}
if db.cols[name], err = OpenCol(db, name); err != nil {
return err
}
return nil
} | go | func (db *DB) Scrub(name string) error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
if _, exists := db.cols[name]; !exists {
return fmt.Errorf("Collection %s does not exist", name)
}
// Prepare a temporary collection in file system
tmpColName := fmt.Sprintf("scrub-%s-%d", name, time.Now().UnixNano())
tmpColDir := path.Join(db.path, tmpColName)
if err := os.MkdirAll(tmpColDir, 0700); err != nil {
return err
}
// Mirror indexes from original collection
for _, idxPath := range db.cols[name].indexPaths {
if err := os.MkdirAll(path.Join(tmpColDir, strings.Join(idxPath, INDEX_PATH_SEP)), 0700); err != nil {
return err
}
}
// Iterate through all documents and put them into the temporary collection
tmpCol, err := OpenCol(db, tmpColName)
if err != nil {
return err
}
db.cols[name].forEachDoc(func(id int, doc []byte) bool {
var docObj map[string]interface{}
if err := json.Unmarshal([]byte(doc), &docObj); err != nil {
// Skip corrupted document
return true
}
if err := tmpCol.InsertRecovery(id, docObj); err != nil {
tdlog.Noticef("Scrub %s: failed to insert back document %v", name, docObj)
}
return true
}, false)
if err := tmpCol.close(); err != nil {
return err
}
// Replace the original collection with the "temporary" one
db.cols[name].close()
if err := os.RemoveAll(path.Join(db.path, name)); err != nil {
return err
}
if err := os.Rename(path.Join(db.path, tmpColName), path.Join(db.path, name)); err != nil {
return err
}
if db.cols[name], err = OpenCol(db, name); err != nil {
return err
}
return nil
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"Scrub",
"(",
"name",
"string",
")",
"error",
"{",
"db",
".",
"schemaLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"db",
".",
"schemaLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"exists",
":=",
"db",
".",
"cols",
"[",
"name",
"]",
";",
"!",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"// Prepare a temporary collection in file system",
"tmpColName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
",",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n",
"tmpColDir",
":=",
"path",
".",
"Join",
"(",
"db",
".",
"path",
",",
"tmpColName",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"tmpColDir",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Mirror indexes from original collection",
"for",
"_",
",",
"idxPath",
":=",
"range",
"db",
".",
"cols",
"[",
"name",
"]",
".",
"indexPaths",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"path",
".",
"Join",
"(",
"tmpColDir",
",",
"strings",
".",
"Join",
"(",
"idxPath",
",",
"INDEX_PATH_SEP",
")",
")",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// Iterate through all documents and put them into the temporary collection",
"tmpCol",
",",
"err",
":=",
"OpenCol",
"(",
"db",
",",
"tmpColName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"db",
".",
"cols",
"[",
"name",
"]",
".",
"forEachDoc",
"(",
"func",
"(",
"id",
"int",
",",
"doc",
"[",
"]",
"byte",
")",
"bool",
"{",
"var",
"docObj",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"doc",
")",
",",
"&",
"docObj",
")",
";",
"err",
"!=",
"nil",
"{",
"// Skip corrupted document",
"return",
"true",
"\n",
"}",
"\n",
"if",
"err",
":=",
"tmpCol",
".",
"InsertRecovery",
"(",
"id",
",",
"docObj",
")",
";",
"err",
"!=",
"nil",
"{",
"tdlog",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"name",
",",
"docObj",
")",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
",",
"false",
")",
"\n",
"if",
"err",
":=",
"tmpCol",
".",
"close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Replace the original collection with the \"temporary\" one",
"db",
".",
"cols",
"[",
"name",
"]",
".",
"close",
"(",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"RemoveAll",
"(",
"path",
".",
"Join",
"(",
"db",
".",
"path",
",",
"name",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"os",
".",
"Rename",
"(",
"path",
".",
"Join",
"(",
"db",
".",
"path",
",",
"tmpColName",
")",
",",
"path",
".",
"Join",
"(",
"db",
".",
"path",
",",
"name",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"db",
".",
"cols",
"[",
"name",
"]",
",",
"err",
"=",
"OpenCol",
"(",
"db",
",",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Scrub a collection - fix corrupted documents and de-fragment free space. | [
"Scrub",
"a",
"collection",
"-",
"fix",
"corrupted",
"documents",
"and",
"de",
"-",
"fragment",
"free",
"space",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L189-L238 |
HouzuoGuo/tiedot | db/db.go | Drop | func (db *DB) Drop(name string) error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
if _, exists := db.cols[name]; !exists {
return fmt.Errorf("Collection %s does not exist", name)
} else if err := db.cols[name].close(); err != nil {
return err
} else if err := os.RemoveAll(path.Join(db.path, name)); err != nil {
return err
}
delete(db.cols, name)
return nil
} | go | func (db *DB) Drop(name string) error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
if _, exists := db.cols[name]; !exists {
return fmt.Errorf("Collection %s does not exist", name)
} else if err := db.cols[name].close(); err != nil {
return err
} else if err := os.RemoveAll(path.Join(db.path, name)); err != nil {
return err
}
delete(db.cols, name)
return nil
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"Drop",
"(",
"name",
"string",
")",
"error",
"{",
"db",
".",
"schemaLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"db",
".",
"schemaLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"exists",
":=",
"db",
".",
"cols",
"[",
"name",
"]",
";",
"!",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"else",
"if",
"err",
":=",
"db",
".",
"cols",
"[",
"name",
"]",
".",
"close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"err",
":=",
"os",
".",
"RemoveAll",
"(",
"path",
".",
"Join",
"(",
"db",
".",
"path",
",",
"name",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"delete",
"(",
"db",
".",
"cols",
",",
"name",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Drop a collection and lose all of its documents and indexes. | [
"Drop",
"a",
"collection",
"and",
"lose",
"all",
"of",
"its",
"documents",
"and",
"indexes",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L241-L253 |
HouzuoGuo/tiedot | db/db.go | Dump | func (db *DB) Dump(dest string) error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
cpFun := func(currPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
relPath, err := filepath.Rel(db.path, currPath)
if err != nil {
return err
}
destDir := path.Join(dest, relPath)
if err := os.MkdirAll(destDir, 0700); err != nil {
return err
}
tdlog.Noticef("Dump: created directory %s", destDir)
} else {
src, err := os.Open(currPath)
if err != nil {
return err
}
relPath, err := filepath.Rel(db.path, currPath)
if err != nil {
return err
}
destPath := path.Join(dest, relPath)
if _, fileExists := os.Open(destPath); fileExists == nil {
return fmt.Errorf("Destination file %s already exists", destPath)
}
destFile, err := os.Create(destPath)
if err != nil {
return err
}
written, err := io.Copy(destFile, src)
if err != nil {
return err
}
_ = destFile.Close()
_ = src.Close()
tdlog.Noticef("Dump: copied file %s, size is %d", destPath, written)
}
return nil
}
return filepath.Walk(db.path, cpFun)
} | go | func (db *DB) Dump(dest string) error {
db.schemaLock.Lock()
defer db.schemaLock.Unlock()
cpFun := func(currPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
relPath, err := filepath.Rel(db.path, currPath)
if err != nil {
return err
}
destDir := path.Join(dest, relPath)
if err := os.MkdirAll(destDir, 0700); err != nil {
return err
}
tdlog.Noticef("Dump: created directory %s", destDir)
} else {
src, err := os.Open(currPath)
if err != nil {
return err
}
relPath, err := filepath.Rel(db.path, currPath)
if err != nil {
return err
}
destPath := path.Join(dest, relPath)
if _, fileExists := os.Open(destPath); fileExists == nil {
return fmt.Errorf("Destination file %s already exists", destPath)
}
destFile, err := os.Create(destPath)
if err != nil {
return err
}
written, err := io.Copy(destFile, src)
if err != nil {
return err
}
_ = destFile.Close()
_ = src.Close()
tdlog.Noticef("Dump: copied file %s, size is %d", destPath, written)
}
return nil
}
return filepath.Walk(db.path, cpFun)
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"Dump",
"(",
"dest",
"string",
")",
"error",
"{",
"db",
".",
"schemaLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"db",
".",
"schemaLock",
".",
"Unlock",
"(",
")",
"\n",
"cpFun",
":=",
"func",
"(",
"currPath",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"info",
".",
"IsDir",
"(",
")",
"{",
"relPath",
",",
"err",
":=",
"filepath",
".",
"Rel",
"(",
"db",
".",
"path",
",",
"currPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"destDir",
":=",
"path",
".",
"Join",
"(",
"dest",
",",
"relPath",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"destDir",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"tdlog",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"destDir",
")",
"\n",
"}",
"else",
"{",
"src",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"currPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"relPath",
",",
"err",
":=",
"filepath",
".",
"Rel",
"(",
"db",
".",
"path",
",",
"currPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"destPath",
":=",
"path",
".",
"Join",
"(",
"dest",
",",
"relPath",
")",
"\n",
"if",
"_",
",",
"fileExists",
":=",
"os",
".",
"Open",
"(",
"destPath",
")",
";",
"fileExists",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"destPath",
")",
"\n",
"}",
"\n",
"destFile",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"destPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"written",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"destFile",
",",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
"=",
"destFile",
".",
"Close",
"(",
")",
"\n",
"_",
"=",
"src",
".",
"Close",
"(",
")",
"\n",
"tdlog",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"destPath",
",",
"written",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"filepath",
".",
"Walk",
"(",
"db",
".",
"path",
",",
"cpFun",
")",
"\n",
"}"
] | // Copy this database into destination directory (for backup). | [
"Copy",
"this",
"database",
"into",
"destination",
"directory",
"(",
"for",
"backup",
")",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L256-L301 |
HouzuoGuo/tiedot | db/db.go | ForceUse | func (db *DB) ForceUse(name string) *Col {
db.schemaLock.RLock()
defer db.schemaLock.RUnlock()
if db.cols[name] == nil {
if err := db.create(name); err != nil {
tdlog.Panicf("ForceUse: failed to create collection - %v", err)
}
}
return db.cols[name]
} | go | func (db *DB) ForceUse(name string) *Col {
db.schemaLock.RLock()
defer db.schemaLock.RUnlock()
if db.cols[name] == nil {
if err := db.create(name); err != nil {
tdlog.Panicf("ForceUse: failed to create collection - %v", err)
}
}
return db.cols[name]
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"ForceUse",
"(",
"name",
"string",
")",
"*",
"Col",
"{",
"db",
".",
"schemaLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"db",
".",
"cols",
"[",
"name",
"]",
"==",
"nil",
"{",
"if",
"err",
":=",
"db",
".",
"create",
"(",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"tdlog",
".",
"Panicf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"db",
".",
"cols",
"[",
"name",
"]",
"\n",
"}"
] | // ForceUse creates a collection if one does not yet exist. Returns collection handle. Panics on error. | [
"ForceUse",
"creates",
"a",
"collection",
"if",
"one",
"does",
"not",
"yet",
"exist",
".",
"Returns",
"collection",
"handle",
".",
"Panics",
"on",
"error",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L304-L313 |
HouzuoGuo/tiedot | db/db.go | ColExists | func (db *DB) ColExists(name string) bool {
db.schemaLock.RLock()
defer db.schemaLock.RUnlock()
return db.cols[name] != nil
} | go | func (db *DB) ColExists(name string) bool {
db.schemaLock.RLock()
defer db.schemaLock.RUnlock()
return db.cols[name] != nil
} | [
"func",
"(",
"db",
"*",
"DB",
")",
"ColExists",
"(",
"name",
"string",
")",
"bool",
"{",
"db",
".",
"schemaLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"db",
".",
"cols",
"[",
"name",
"]",
"!=",
"nil",
"\n",
"}"
] | // ColExists returns true only if the given collection name exists in the database. | [
"ColExists",
"returns",
"true",
"only",
"if",
"the",
"given",
"collection",
"name",
"exists",
"in",
"the",
"database",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L316-L320 |
HouzuoGuo/tiedot | main.go | linuxPerfAdvice | func linuxPerfAdvice() {
readFileIntContent := func(filePath string) (contentInt int, err error) {
content, err := ioutil.ReadFile(filePath)
if err != nil {
return
}
contentInt, err = strconv.Atoi(strings.TrimSpace(string(content)))
return
}
swappiness, err := readFileIntContent("/proc/sys/vm/swappiness")
if err != nil {
tdlog.Notice("Non-fatal - unable to offer performance advice based on vm.swappiness.")
} else if swappiness > 30 {
tdlog.Noticef("System vm.swappiness is very high (%d), lower it below 30 for optimal burst performance.", swappiness)
}
dirtyRatio, err := readFileIntContent("/proc/sys/vm/dirty_ratio")
if err != nil {
tdlog.Notice("Non-fatal - unable to offer performance advice based on vm.dirty_ratio.")
} else if dirtyRatio < 40 {
tdlog.Noticef("System vm.dirty_ratio is very low (%d), raise it above 40 for optimal burst performance.", dirtyRatio)
}
} | go | func linuxPerfAdvice() {
readFileIntContent := func(filePath string) (contentInt int, err error) {
content, err := ioutil.ReadFile(filePath)
if err != nil {
return
}
contentInt, err = strconv.Atoi(strings.TrimSpace(string(content)))
return
}
swappiness, err := readFileIntContent("/proc/sys/vm/swappiness")
if err != nil {
tdlog.Notice("Non-fatal - unable to offer performance advice based on vm.swappiness.")
} else if swappiness > 30 {
tdlog.Noticef("System vm.swappiness is very high (%d), lower it below 30 for optimal burst performance.", swappiness)
}
dirtyRatio, err := readFileIntContent("/proc/sys/vm/dirty_ratio")
if err != nil {
tdlog.Notice("Non-fatal - unable to offer performance advice based on vm.dirty_ratio.")
} else if dirtyRatio < 40 {
tdlog.Noticef("System vm.dirty_ratio is very low (%d), raise it above 40 for optimal burst performance.", dirtyRatio)
}
} | [
"func",
"linuxPerfAdvice",
"(",
")",
"{",
"readFileIntContent",
":=",
"func",
"(",
"filePath",
"string",
")",
"(",
"contentInt",
"int",
",",
"err",
"error",
")",
"{",
"content",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"contentInt",
",",
"err",
"=",
"strconv",
".",
"Atoi",
"(",
"strings",
".",
"TrimSpace",
"(",
"string",
"(",
"content",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"swappiness",
",",
"err",
":=",
"readFileIntContent",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"tdlog",
".",
"Notice",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"swappiness",
">",
"30",
"{",
"tdlog",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"swappiness",
")",
"\n",
"}",
"\n",
"dirtyRatio",
",",
"err",
":=",
"readFileIntContent",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"tdlog",
".",
"Notice",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"dirtyRatio",
"<",
"40",
"{",
"tdlog",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"dirtyRatio",
")",
"\n",
"}",
"\n",
"}"
] | // Read Linux system VM parameters and print performance configuration advice when necessary. | [
"Read",
"Linux",
"system",
"VM",
"parameters",
"and",
"print",
"performance",
"configuration",
"advice",
"when",
"necessary",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/main.go#L21-L42 |
HouzuoGuo/tiedot | benchmark/benchmark.go | average | func average(name string, fun func(), benchSize int) {
numThreads := runtime.GOMAXPROCS(-1)
wp := new(sync.WaitGroup)
iter := float64(benchSize)
start := float64(time.Now().UTC().UnixNano())
// Run function across multiple goroutines
for i := 0; i < benchSize; i += benchSize / numThreads {
wp.Add(1)
go func() {
defer wp.Done()
for j := 0; j < benchSize/numThreads; j++ {
fun()
}
}()
}
wp.Wait()
end := float64(time.Now().UTC().UnixNano())
fmt.Printf("%s %d: %d ns/iter, %d iter/sec\n", name, int(benchSize), int((end-start)/iter), int(1000000000/((end-start)/iter)))
} | go | func average(name string, fun func(), benchSize int) {
numThreads := runtime.GOMAXPROCS(-1)
wp := new(sync.WaitGroup)
iter := float64(benchSize)
start := float64(time.Now().UTC().UnixNano())
// Run function across multiple goroutines
for i := 0; i < benchSize; i += benchSize / numThreads {
wp.Add(1)
go func() {
defer wp.Done()
for j := 0; j < benchSize/numThreads; j++ {
fun()
}
}()
}
wp.Wait()
end := float64(time.Now().UTC().UnixNano())
fmt.Printf("%s %d: %d ns/iter, %d iter/sec\n", name, int(benchSize), int((end-start)/iter), int(1000000000/((end-start)/iter)))
} | [
"func",
"average",
"(",
"name",
"string",
",",
"fun",
"func",
"(",
")",
",",
"benchSize",
"int",
")",
"{",
"numThreads",
":=",
"runtime",
".",
"GOMAXPROCS",
"(",
"-",
"1",
")",
"\n",
"wp",
":=",
"new",
"(",
"sync",
".",
"WaitGroup",
")",
"\n",
"iter",
":=",
"float64",
"(",
"benchSize",
")",
"\n",
"start",
":=",
"float64",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n",
"// Run function across multiple goroutines",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"benchSize",
";",
"i",
"+=",
"benchSize",
"/",
"numThreads",
"{",
"wp",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"defer",
"wp",
".",
"Done",
"(",
")",
"\n",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"benchSize",
"/",
"numThreads",
";",
"j",
"++",
"{",
"fun",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"wp",
".",
"Wait",
"(",
")",
"\n",
"end",
":=",
"float64",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"name",
",",
"int",
"(",
"benchSize",
")",
",",
"int",
"(",
"(",
"end",
"-",
"start",
")",
"/",
"iter",
")",
",",
"int",
"(",
"1000000000",
"/",
"(",
"(",
"end",
"-",
"start",
")",
"/",
"iter",
")",
")",
")",
"\n",
"}"
] | // Run the benchmark function a number of times across multiple goroutines, and print out performance data. | [
"Run",
"the",
"benchmark",
"function",
"a",
"number",
"of",
"times",
"across",
"multiple",
"goroutines",
"and",
"print",
"out",
"performance",
"data",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/benchmark/benchmark.go#L18-L36 |
HouzuoGuo/tiedot | benchmark/benchmark.go | mkTmpDBAndCol | func mkTmpDBAndCol(dbPath string, colName string) (*db.DB, *db.Col) {
os.RemoveAll(dbPath)
tmpDB, err := db.OpenDB(dbPath)
if err != nil {
panic(err)
}
if err = tmpDB.Create(colName); err != nil {
panic(err)
}
return tmpDB, tmpDB.Use(colName)
} | go | func mkTmpDBAndCol(dbPath string, colName string) (*db.DB, *db.Col) {
os.RemoveAll(dbPath)
tmpDB, err := db.OpenDB(dbPath)
if err != nil {
panic(err)
}
if err = tmpDB.Create(colName); err != nil {
panic(err)
}
return tmpDB, tmpDB.Use(colName)
} | [
"func",
"mkTmpDBAndCol",
"(",
"dbPath",
"string",
",",
"colName",
"string",
")",
"(",
"*",
"db",
".",
"DB",
",",
"*",
"db",
".",
"Col",
")",
"{",
"os",
".",
"RemoveAll",
"(",
"dbPath",
")",
"\n",
"tmpDB",
",",
"err",
":=",
"db",
".",
"OpenDB",
"(",
"dbPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
"=",
"tmpDB",
".",
"Create",
"(",
"colName",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"tmpDB",
",",
"tmpDB",
".",
"Use",
"(",
"colName",
")",
"\n",
"}"
] | // Create a temporary database and collection for benchmark use. | [
"Create",
"a",
"temporary",
"database",
"and",
"collection",
"for",
"benchmark",
"use",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/benchmark/benchmark.go#L39-L49 |
HouzuoGuo/tiedot | benchmark/benchmark.go | Benchmark | func Benchmark(benchSize int, benchCleanup bool) {
ids := make([]int, 0, benchSize)
// Prepare a collection with two indexes
tmp := "/tmp/tiedot_bench"
os.RemoveAll(tmp)
if benchCleanup {
defer os.RemoveAll(tmp)
}
benchDB, col := mkTmpDBAndCol(tmp, "tmp")
defer benchDB.Close()
col.Index([]string{"nested", "nested", "str"})
col.Index([]string{"nested", "nested", "int"})
col.Index([]string{"nested", "nested", "float"})
col.Index([]string{"strs"})
col.Index([]string{"ints"})
col.Index([]string{"floats"})
// Benchmark document insert
average("insert", func() {
if _, err := col.Insert(sampleDoc(benchSize)); err != nil {
fmt.Println("Insert error", err)
}
}, benchSize)
// Collect all document IDs and benchmark document read
col.ForEachDoc(func(id int, _ []byte) bool {
ids = append(ids, id)
return true
})
average("read", func() {
doc, err := col.Read(ids[rand.Intn(benchSize)])
if doc == nil || err != nil {
fmt.Println("Read error", doc, err)
}
}, benchSize)
// Benchmark lookup query (two attributes)
average("lookup", func() {
result := make(map[int]struct{})
if err := db.EvalQuery(sampleQuery(benchSize), col, &result); err != nil {
fmt.Println("Query error", err)
}
}, benchSize)
// Benchmark document update
average("update", func() {
if err := col.Update(ids[rand.Intn(benchSize)], sampleDoc(benchSize)); err != nil {
fmt.Println("Update error", err)
}
}, benchSize)
// Benchmark document delete
var delCount int64
average("delete", func() {
if err := col.Delete(ids[rand.Intn(benchSize)]); err == nil {
atomic.AddInt64(&delCount, 1)
}
}, benchSize)
fmt.Printf("Deleted %d documents\n", delCount)
} | go | func Benchmark(benchSize int, benchCleanup bool) {
ids := make([]int, 0, benchSize)
// Prepare a collection with two indexes
tmp := "/tmp/tiedot_bench"
os.RemoveAll(tmp)
if benchCleanup {
defer os.RemoveAll(tmp)
}
benchDB, col := mkTmpDBAndCol(tmp, "tmp")
defer benchDB.Close()
col.Index([]string{"nested", "nested", "str"})
col.Index([]string{"nested", "nested", "int"})
col.Index([]string{"nested", "nested", "float"})
col.Index([]string{"strs"})
col.Index([]string{"ints"})
col.Index([]string{"floats"})
// Benchmark document insert
average("insert", func() {
if _, err := col.Insert(sampleDoc(benchSize)); err != nil {
fmt.Println("Insert error", err)
}
}, benchSize)
// Collect all document IDs and benchmark document read
col.ForEachDoc(func(id int, _ []byte) bool {
ids = append(ids, id)
return true
})
average("read", func() {
doc, err := col.Read(ids[rand.Intn(benchSize)])
if doc == nil || err != nil {
fmt.Println("Read error", doc, err)
}
}, benchSize)
// Benchmark lookup query (two attributes)
average("lookup", func() {
result := make(map[int]struct{})
if err := db.EvalQuery(sampleQuery(benchSize), col, &result); err != nil {
fmt.Println("Query error", err)
}
}, benchSize)
// Benchmark document update
average("update", func() {
if err := col.Update(ids[rand.Intn(benchSize)], sampleDoc(benchSize)); err != nil {
fmt.Println("Update error", err)
}
}, benchSize)
// Benchmark document delete
var delCount int64
average("delete", func() {
if err := col.Delete(ids[rand.Intn(benchSize)]); err == nil {
atomic.AddInt64(&delCount, 1)
}
}, benchSize)
fmt.Printf("Deleted %d documents\n", delCount)
} | [
"func",
"Benchmark",
"(",
"benchSize",
"int",
",",
"benchCleanup",
"bool",
")",
"{",
"ids",
":=",
"make",
"(",
"[",
"]",
"int",
",",
"0",
",",
"benchSize",
")",
"\n",
"// Prepare a collection with two indexes",
"tmp",
":=",
"\"",
"\"",
"\n",
"os",
".",
"RemoveAll",
"(",
"tmp",
")",
"\n",
"if",
"benchCleanup",
"{",
"defer",
"os",
".",
"RemoveAll",
"(",
"tmp",
")",
"\n",
"}",
"\n",
"benchDB",
",",
"col",
":=",
"mkTmpDBAndCol",
"(",
"tmp",
",",
"\"",
"\"",
")",
"\n",
"defer",
"benchDB",
".",
"Close",
"(",
")",
"\n",
"col",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
"\n",
"col",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
"\n",
"col",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
"\n",
"col",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
")",
"\n",
"col",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
")",
"\n",
"col",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
")",
"\n\n",
"// Benchmark document insert",
"average",
"(",
"\"",
"\"",
",",
"func",
"(",
")",
"{",
"if",
"_",
",",
"err",
":=",
"col",
".",
"Insert",
"(",
"sampleDoc",
"(",
"benchSize",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
",",
"benchSize",
")",
"\n\n",
"// Collect all document IDs and benchmark document read",
"col",
".",
"ForEachDoc",
"(",
"func",
"(",
"id",
"int",
",",
"_",
"[",
"]",
"byte",
")",
"bool",
"{",
"ids",
"=",
"append",
"(",
"ids",
",",
"id",
")",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"average",
"(",
"\"",
"\"",
",",
"func",
"(",
")",
"{",
"doc",
",",
"err",
":=",
"col",
".",
"Read",
"(",
"ids",
"[",
"rand",
".",
"Intn",
"(",
"benchSize",
")",
"]",
")",
"\n",
"if",
"doc",
"==",
"nil",
"||",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"doc",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
",",
"benchSize",
")",
"\n\n",
"// Benchmark lookup query (two attributes)",
"average",
"(",
"\"",
"\"",
",",
"func",
"(",
")",
"{",
"result",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"\n",
"if",
"err",
":=",
"db",
".",
"EvalQuery",
"(",
"sampleQuery",
"(",
"benchSize",
")",
",",
"col",
",",
"&",
"result",
")",
";",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
",",
"benchSize",
")",
"\n\n",
"// Benchmark document update",
"average",
"(",
"\"",
"\"",
",",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"col",
".",
"Update",
"(",
"ids",
"[",
"rand",
".",
"Intn",
"(",
"benchSize",
")",
"]",
",",
"sampleDoc",
"(",
"benchSize",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
",",
"benchSize",
")",
"\n\n",
"// Benchmark document delete",
"var",
"delCount",
"int64",
"\n",
"average",
"(",
"\"",
"\"",
",",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"col",
".",
"Delete",
"(",
"ids",
"[",
"rand",
".",
"Intn",
"(",
"benchSize",
")",
"]",
")",
";",
"err",
"==",
"nil",
"{",
"atomic",
".",
"AddInt64",
"(",
"&",
"delCount",
",",
"1",
")",
"\n",
"}",
"\n",
"}",
",",
"benchSize",
")",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"delCount",
")",
"\n",
"}"
] | // Document CRUD benchmark (insert/read/query/update/delete), intended for catching performance regressions. | [
"Document",
"CRUD",
"benchmark",
"(",
"insert",
"/",
"read",
"/",
"query",
"/",
"update",
"/",
"delete",
")",
"intended",
"for",
"catching",
"performance",
"regressions",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/benchmark/benchmark.go#L93-L152 |
HouzuoGuo/tiedot | benchmark/benchmark.go | Benchmark2 | func Benchmark2(benchSize int, benchCleanup bool) {
docs := make([]int, 0, benchSize*2+1000)
wp := new(sync.WaitGroup)
numThreads := runtime.GOMAXPROCS(-1)
// There are goroutines doing document operations: insert, read, query, update, delete
wp.Add(5 * numThreads)
// And one more changing schema and stuff
wp.Add(1)
// Prepare a collection with two indexes
tmp := "/tmp/tiedot_bench2"
os.RemoveAll(tmp)
if benchCleanup {
defer os.RemoveAll(tmp)
}
benchdb, col := mkTmpDBAndCol(tmp, "tmp")
defer benchdb.Close()
col.Index([]string{"nested", "nested", "str"})
col.Index([]string{"nested", "nested", "int"})
col.Index([]string{"nested", "nested", "float"})
col.Index([]string{"strs"})
col.Index([]string{"ints"})
col.Index([]string{"floats"})
// Insert 1000 documents to make a start
for j := 0; j < 1000; j++ {
if newID, err := col.Insert(sampleDoc(benchSize)); err == nil {
docs = append(docs, newID)
} else {
fmt.Println("Insert error", err)
}
}
start := float64(time.Now().UTC().UnixNano())
// Insert benchSize * 2 documents
for i := 0; i < numThreads; i++ {
go func(i int) {
fmt.Printf("Insert thread %d starting\n", i)
defer wp.Done()
for j := 0; j < benchSize/numThreads*2; j++ {
if newID, err := col.Insert(sampleDoc(benchSize)); err == nil {
docs = append(docs, newID)
} else {
fmt.Println("Insert error", err)
}
}
fmt.Printf("Insert thread %d completed\n", i)
}(i)
}
// Read benchSize * 2 documents
var readCount int64
for i := 0; i < numThreads; i++ {
go func(i int) {
fmt.Printf("Read thread %d starting\n", i)
defer wp.Done()
for j := 0; j < benchSize/numThreads*2; j++ {
if _, err := col.Read(docs[rand.Intn(len(docs))]); err == nil {
atomic.AddInt64(&readCount, 1)
}
}
fmt.Printf("Read thread %d completed\n", i)
}(i)
}
// Query benchSize times (lookup on two attributes)
for i := 0; i < numThreads; i++ {
go func(i int) {
fmt.Printf("Query thread %d starting\n", i)
defer wp.Done()
var err error
for j := 0; j < benchSize/numThreads; j++ {
result := make(map[int]struct{})
if err = db.EvalQuery(sampleQuery(benchSize), col, &result); err != nil {
fmt.Println("Query error", err)
}
}
fmt.Printf("Query thread %d completed\n", i)
}(i)
}
// Update benchSize documents
var updateCount int64
for i := 0; i < numThreads; i++ {
go func(i int) {
fmt.Printf("Update thread %d starting\n", i)
defer wp.Done()
for j := 0; j < benchSize/numThreads; j++ {
if err := col.Update(docs[rand.Intn(len(docs))], sampleDoc(benchSize)); err == nil {
atomic.AddInt64(&updateCount, 1)
}
}
fmt.Printf("Update thread %d completed\n", i)
}(i)
}
// Delete benchSize documents
var delCount int64
for i := 0; i < numThreads; i++ {
go func(i int) {
fmt.Printf("Delete thread %d starting\n", i)
defer wp.Done()
for j := 0; j < benchSize/numThreads; j++ {
if err := col.Delete(docs[rand.Intn(len(docs))]); err == nil {
atomic.AddInt64(&delCount, 1)
}
}
fmt.Printf("Delete thread %d completed\n", i)
}(i)
}
// This one does a bunch of schema-changing stuff, testing the engine while document operations are busy
go func() {
time.Sleep(2 * time.Second)
if err := benchdb.Create("foo"); err != nil {
panic(err)
} else if err := benchdb.Rename("foo", "bar"); err != nil {
panic(err)
} else if err := benchdb.Truncate("bar"); err != nil {
panic(err)
} else if err := benchdb.Scrub("bar"); err != nil {
panic(err)
} else if benchdb.Use("bar") == nil {
panic("Missing collection")
}
for _, colName := range benchdb.AllCols() {
if colName != "bar" && colName != "tmp" {
panic("Wrong collections in benchmark db")
}
}
defer os.RemoveAll("/tmp/tiedot_bench2_dump")
if err := benchdb.Dump("/tmp/tiedot_bench2_dump"); err != nil {
panic(err)
} else if err := benchdb.Drop("bar"); err != nil {
panic(err)
}
defer wp.Done()
}()
// Wait for all goroutines to finish, then print summary
wp.Wait()
end := float64(time.Now().UTC().UnixNano())
fmt.Printf("Total operations %d: %d ns/iter, %d iter/sec\n", benchSize*7, int((end-start)/float64(benchSize)/7), int(1000000000/((end-start)/float64(benchSize)/7)))
fmt.Printf("Read %d documents\n", readCount)
fmt.Printf("Updated %d documents\n", updateCount)
fmt.Printf("Deleted %d documents\n", delCount)
} | go | func Benchmark2(benchSize int, benchCleanup bool) {
docs := make([]int, 0, benchSize*2+1000)
wp := new(sync.WaitGroup)
numThreads := runtime.GOMAXPROCS(-1)
// There are goroutines doing document operations: insert, read, query, update, delete
wp.Add(5 * numThreads)
// And one more changing schema and stuff
wp.Add(1)
// Prepare a collection with two indexes
tmp := "/tmp/tiedot_bench2"
os.RemoveAll(tmp)
if benchCleanup {
defer os.RemoveAll(tmp)
}
benchdb, col := mkTmpDBAndCol(tmp, "tmp")
defer benchdb.Close()
col.Index([]string{"nested", "nested", "str"})
col.Index([]string{"nested", "nested", "int"})
col.Index([]string{"nested", "nested", "float"})
col.Index([]string{"strs"})
col.Index([]string{"ints"})
col.Index([]string{"floats"})
// Insert 1000 documents to make a start
for j := 0; j < 1000; j++ {
if newID, err := col.Insert(sampleDoc(benchSize)); err == nil {
docs = append(docs, newID)
} else {
fmt.Println("Insert error", err)
}
}
start := float64(time.Now().UTC().UnixNano())
// Insert benchSize * 2 documents
for i := 0; i < numThreads; i++ {
go func(i int) {
fmt.Printf("Insert thread %d starting\n", i)
defer wp.Done()
for j := 0; j < benchSize/numThreads*2; j++ {
if newID, err := col.Insert(sampleDoc(benchSize)); err == nil {
docs = append(docs, newID)
} else {
fmt.Println("Insert error", err)
}
}
fmt.Printf("Insert thread %d completed\n", i)
}(i)
}
// Read benchSize * 2 documents
var readCount int64
for i := 0; i < numThreads; i++ {
go func(i int) {
fmt.Printf("Read thread %d starting\n", i)
defer wp.Done()
for j := 0; j < benchSize/numThreads*2; j++ {
if _, err := col.Read(docs[rand.Intn(len(docs))]); err == nil {
atomic.AddInt64(&readCount, 1)
}
}
fmt.Printf("Read thread %d completed\n", i)
}(i)
}
// Query benchSize times (lookup on two attributes)
for i := 0; i < numThreads; i++ {
go func(i int) {
fmt.Printf("Query thread %d starting\n", i)
defer wp.Done()
var err error
for j := 0; j < benchSize/numThreads; j++ {
result := make(map[int]struct{})
if err = db.EvalQuery(sampleQuery(benchSize), col, &result); err != nil {
fmt.Println("Query error", err)
}
}
fmt.Printf("Query thread %d completed\n", i)
}(i)
}
// Update benchSize documents
var updateCount int64
for i := 0; i < numThreads; i++ {
go func(i int) {
fmt.Printf("Update thread %d starting\n", i)
defer wp.Done()
for j := 0; j < benchSize/numThreads; j++ {
if err := col.Update(docs[rand.Intn(len(docs))], sampleDoc(benchSize)); err == nil {
atomic.AddInt64(&updateCount, 1)
}
}
fmt.Printf("Update thread %d completed\n", i)
}(i)
}
// Delete benchSize documents
var delCount int64
for i := 0; i < numThreads; i++ {
go func(i int) {
fmt.Printf("Delete thread %d starting\n", i)
defer wp.Done()
for j := 0; j < benchSize/numThreads; j++ {
if err := col.Delete(docs[rand.Intn(len(docs))]); err == nil {
atomic.AddInt64(&delCount, 1)
}
}
fmt.Printf("Delete thread %d completed\n", i)
}(i)
}
// This one does a bunch of schema-changing stuff, testing the engine while document operations are busy
go func() {
time.Sleep(2 * time.Second)
if err := benchdb.Create("foo"); err != nil {
panic(err)
} else if err := benchdb.Rename("foo", "bar"); err != nil {
panic(err)
} else if err := benchdb.Truncate("bar"); err != nil {
panic(err)
} else if err := benchdb.Scrub("bar"); err != nil {
panic(err)
} else if benchdb.Use("bar") == nil {
panic("Missing collection")
}
for _, colName := range benchdb.AllCols() {
if colName != "bar" && colName != "tmp" {
panic("Wrong collections in benchmark db")
}
}
defer os.RemoveAll("/tmp/tiedot_bench2_dump")
if err := benchdb.Dump("/tmp/tiedot_bench2_dump"); err != nil {
panic(err)
} else if err := benchdb.Drop("bar"); err != nil {
panic(err)
}
defer wp.Done()
}()
// Wait for all goroutines to finish, then print summary
wp.Wait()
end := float64(time.Now().UTC().UnixNano())
fmt.Printf("Total operations %d: %d ns/iter, %d iter/sec\n", benchSize*7, int((end-start)/float64(benchSize)/7), int(1000000000/((end-start)/float64(benchSize)/7)))
fmt.Printf("Read %d documents\n", readCount)
fmt.Printf("Updated %d documents\n", updateCount)
fmt.Printf("Deleted %d documents\n", delCount)
} | [
"func",
"Benchmark2",
"(",
"benchSize",
"int",
",",
"benchCleanup",
"bool",
")",
"{",
"docs",
":=",
"make",
"(",
"[",
"]",
"int",
",",
"0",
",",
"benchSize",
"*",
"2",
"+",
"1000",
")",
"\n",
"wp",
":=",
"new",
"(",
"sync",
".",
"WaitGroup",
")",
"\n",
"numThreads",
":=",
"runtime",
".",
"GOMAXPROCS",
"(",
"-",
"1",
")",
"\n",
"// There are goroutines doing document operations: insert, read, query, update, delete",
"wp",
".",
"Add",
"(",
"5",
"*",
"numThreads",
")",
"\n",
"// And one more changing schema and stuff",
"wp",
".",
"Add",
"(",
"1",
")",
"\n\n",
"// Prepare a collection with two indexes",
"tmp",
":=",
"\"",
"\"",
"\n",
"os",
".",
"RemoveAll",
"(",
"tmp",
")",
"\n",
"if",
"benchCleanup",
"{",
"defer",
"os",
".",
"RemoveAll",
"(",
"tmp",
")",
"\n",
"}",
"\n",
"benchdb",
",",
"col",
":=",
"mkTmpDBAndCol",
"(",
"tmp",
",",
"\"",
"\"",
")",
"\n",
"defer",
"benchdb",
".",
"Close",
"(",
")",
"\n",
"col",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
"\n",
"col",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
"\n",
"col",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
"\n",
"col",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
")",
"\n",
"col",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
")",
"\n",
"col",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
")",
"\n\n",
"// Insert 1000 documents to make a start",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"1000",
";",
"j",
"++",
"{",
"if",
"newID",
",",
"err",
":=",
"col",
".",
"Insert",
"(",
"sampleDoc",
"(",
"benchSize",
")",
")",
";",
"err",
"==",
"nil",
"{",
"docs",
"=",
"append",
"(",
"docs",
",",
"newID",
")",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"start",
":=",
"float64",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n\n",
"// Insert benchSize * 2 documents",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numThreads",
";",
"i",
"++",
"{",
"go",
"func",
"(",
"i",
"int",
")",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"i",
")",
"\n",
"defer",
"wp",
".",
"Done",
"(",
")",
"\n",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"benchSize",
"/",
"numThreads",
"*",
"2",
";",
"j",
"++",
"{",
"if",
"newID",
",",
"err",
":=",
"col",
".",
"Insert",
"(",
"sampleDoc",
"(",
"benchSize",
")",
")",
";",
"err",
"==",
"nil",
"{",
"docs",
"=",
"append",
"(",
"docs",
",",
"newID",
")",
"\n",
"}",
"else",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"i",
")",
"\n",
"}",
"(",
"i",
")",
"\n",
"}",
"\n\n",
"// Read benchSize * 2 documents",
"var",
"readCount",
"int64",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numThreads",
";",
"i",
"++",
"{",
"go",
"func",
"(",
"i",
"int",
")",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"i",
")",
"\n",
"defer",
"wp",
".",
"Done",
"(",
")",
"\n",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"benchSize",
"/",
"numThreads",
"*",
"2",
";",
"j",
"++",
"{",
"if",
"_",
",",
"err",
":=",
"col",
".",
"Read",
"(",
"docs",
"[",
"rand",
".",
"Intn",
"(",
"len",
"(",
"docs",
")",
")",
"]",
")",
";",
"err",
"==",
"nil",
"{",
"atomic",
".",
"AddInt64",
"(",
"&",
"readCount",
",",
"1",
")",
"\n",
"}",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"i",
")",
"\n",
"}",
"(",
"i",
")",
"\n",
"}",
"\n\n",
"// Query benchSize times (lookup on two attributes)",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numThreads",
";",
"i",
"++",
"{",
"go",
"func",
"(",
"i",
"int",
")",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"i",
")",
"\n",
"defer",
"wp",
".",
"Done",
"(",
")",
"\n",
"var",
"err",
"error",
"\n",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"benchSize",
"/",
"numThreads",
";",
"j",
"++",
"{",
"result",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"\n",
"if",
"err",
"=",
"db",
".",
"EvalQuery",
"(",
"sampleQuery",
"(",
"benchSize",
")",
",",
"col",
",",
"&",
"result",
")",
";",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"i",
")",
"\n",
"}",
"(",
"i",
")",
"\n",
"}",
"\n\n",
"// Update benchSize documents",
"var",
"updateCount",
"int64",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numThreads",
";",
"i",
"++",
"{",
"go",
"func",
"(",
"i",
"int",
")",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"i",
")",
"\n",
"defer",
"wp",
".",
"Done",
"(",
")",
"\n",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"benchSize",
"/",
"numThreads",
";",
"j",
"++",
"{",
"if",
"err",
":=",
"col",
".",
"Update",
"(",
"docs",
"[",
"rand",
".",
"Intn",
"(",
"len",
"(",
"docs",
")",
")",
"]",
",",
"sampleDoc",
"(",
"benchSize",
")",
")",
";",
"err",
"==",
"nil",
"{",
"atomic",
".",
"AddInt64",
"(",
"&",
"updateCount",
",",
"1",
")",
"\n",
"}",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"i",
")",
"\n",
"}",
"(",
"i",
")",
"\n",
"}",
"\n\n",
"// Delete benchSize documents",
"var",
"delCount",
"int64",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"numThreads",
";",
"i",
"++",
"{",
"go",
"func",
"(",
"i",
"int",
")",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"i",
")",
"\n",
"defer",
"wp",
".",
"Done",
"(",
")",
"\n",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"benchSize",
"/",
"numThreads",
";",
"j",
"++",
"{",
"if",
"err",
":=",
"col",
".",
"Delete",
"(",
"docs",
"[",
"rand",
".",
"Intn",
"(",
"len",
"(",
"docs",
")",
")",
"]",
")",
";",
"err",
"==",
"nil",
"{",
"atomic",
".",
"AddInt64",
"(",
"&",
"delCount",
",",
"1",
")",
"\n",
"}",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"i",
")",
"\n",
"}",
"(",
"i",
")",
"\n",
"}",
"\n\n",
"// This one does a bunch of schema-changing stuff, testing the engine while document operations are busy",
"go",
"func",
"(",
")",
"{",
"time",
".",
"Sleep",
"(",
"2",
"*",
"time",
".",
"Second",
")",
"\n",
"if",
"err",
":=",
"benchdb",
".",
"Create",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"err",
":=",
"benchdb",
".",
"Rename",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"err",
":=",
"benchdb",
".",
"Truncate",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"err",
":=",
"benchdb",
".",
"Scrub",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"benchdb",
".",
"Use",
"(",
"\"",
"\"",
")",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"colName",
":=",
"range",
"benchdb",
".",
"AllCols",
"(",
")",
"{",
"if",
"colName",
"!=",
"\"",
"\"",
"&&",
"colName",
"!=",
"\"",
"\"",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"defer",
"os",
".",
"RemoveAll",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"benchdb",
".",
"Dump",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"err",
":=",
"benchdb",
".",
"Drop",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
"wp",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"// Wait for all goroutines to finish, then print summary",
"wp",
".",
"Wait",
"(",
")",
"\n",
"end",
":=",
"float64",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"benchSize",
"*",
"7",
",",
"int",
"(",
"(",
"end",
"-",
"start",
")",
"/",
"float64",
"(",
"benchSize",
")",
"/",
"7",
")",
",",
"int",
"(",
"1000000000",
"/",
"(",
"(",
"end",
"-",
"start",
")",
"/",
"float64",
"(",
"benchSize",
")",
"/",
"7",
")",
")",
")",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"readCount",
")",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"updateCount",
")",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"delCount",
")",
"\n",
"}"
] | // Document CRUD operations running in parallel, intended for catching concurrency related bugs. | [
"Document",
"CRUD",
"operations",
"running",
"in",
"parallel",
"intended",
"for",
"catching",
"concurrency",
"related",
"bugs",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/benchmark/benchmark.go#L155-L301 |
HouzuoGuo/tiedot | httpapi/collection.go | Create | func Create(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col string
if !Require(w, r, "col", &col) {
return
}
if err := HttpDB.Create(col); err != nil {
http.Error(w, fmt.Sprint(err), http.StatusBadRequest)
} else {
w.WriteHeader(http.StatusCreated)
}
} | go | func Create(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col string
if !Require(w, r, "col", &col) {
return
}
if err := HttpDB.Create(col); err != nil {
http.Error(w, fmt.Sprint(err), http.StatusBadRequest)
} else {
w.WriteHeader(http.StatusCreated)
}
} | [
"func",
"Create",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"col",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"col",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"err",
":=",
"HttpDB",
".",
"Create",
"(",
"col",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"}",
"else",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusCreated",
")",
"\n",
"}",
"\n",
"}"
] | // Create a collection. | [
"Create",
"a",
"collection",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/collection.go#L12-L26 |
HouzuoGuo/tiedot | httpapi/collection.go | All | func All(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
cols := make([]string, 0)
for _, v := range HttpDB.AllCols() {
cols = append(cols, v)
}
resp, err := json.Marshal(cols)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
}
w.Write(resp)
} | go | func All(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
cols := make([]string, 0)
for _, v := range HttpDB.AllCols() {
cols = append(cols, v)
}
resp, err := json.Marshal(cols)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
}
w.Write(resp)
} | [
"func",
"All",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cols",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"HttpDB",
".",
"AllCols",
"(",
")",
"{",
"cols",
"=",
"append",
"(",
"cols",
",",
"v",
")",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"cols",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"resp",
")",
"\n",
"}"
] | // Return all collection names. | [
"Return",
"all",
"collection",
"names",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/collection.go#L29-L44 |
HouzuoGuo/tiedot | httpapi/collection.go | Rename | func Rename(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var oldName, newName string
if !Require(w, r, "old", &oldName) {
return
}
if !Require(w, r, "new", &newName) {
return
}
if err := HttpDB.Rename(oldName, newName); err != nil {
http.Error(w, fmt.Sprint(err), http.StatusBadRequest)
}
} | go | func Rename(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var oldName, newName string
if !Require(w, r, "old", &oldName) {
return
}
if !Require(w, r, "new", &newName) {
return
}
if err := HttpDB.Rename(oldName, newName); err != nil {
http.Error(w, fmt.Sprint(err), http.StatusBadRequest)
}
} | [
"func",
"Rename",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"oldName",
",",
"newName",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"oldName",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"newName",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"err",
":=",
"HttpDB",
".",
"Rename",
"(",
"oldName",
",",
"newName",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"}",
"\n",
"}"
] | // Rename a collection. | [
"Rename",
"a",
"collection",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/collection.go#L47-L62 |
HouzuoGuo/tiedot | httpapi/collection.go | Scrub | func Scrub(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col string
if !Require(w, r, "col", &col) {
return
}
dbCol := HttpDB.Use(col)
if dbCol == nil {
http.Error(w, fmt.Sprintf("Collection %s does not exist", col), http.StatusBadRequest)
} else {
HttpDB.Scrub(col)
}
} | go | func Scrub(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col string
if !Require(w, r, "col", &col) {
return
}
dbCol := HttpDB.Use(col)
if dbCol == nil {
http.Error(w, fmt.Sprintf("Collection %s does not exist", col), http.StatusBadRequest)
} else {
HttpDB.Scrub(col)
}
} | [
"func",
"Scrub",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"col",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"col",
")",
"{",
"return",
"\n",
"}",
"\n",
"dbCol",
":=",
"HttpDB",
".",
"Use",
"(",
"col",
")",
"\n",
"if",
"dbCol",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"col",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"}",
"else",
"{",
"HttpDB",
".",
"Scrub",
"(",
"col",
")",
"\n",
"}",
"\n",
"}"
] | // De-fragment collection free space and fix corrupted documents. | [
"De",
"-",
"fragment",
"collection",
"free",
"space",
"and",
"fix",
"corrupted",
"documents",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/collection.go#L80-L95 |
HouzuoGuo/tiedot | httpapi/collection.go | Sync | func Sync(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
} | go | func Sync(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
} | [
"func",
"Sync",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}"
] | /*
Noop
*/ | [
"/",
"*",
"Noop"
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/collection.go#L100-L103 |
HouzuoGuo/tiedot | httpapi/srv.go | Require | func Require(w http.ResponseWriter, r *http.Request, key string, val *string) bool {
*val = r.FormValue(key)
if *val == "" {
http.Error(w, fmt.Sprintf("Please pass POST/PUT/GET parameter value of '%s'.", key), 400)
return false
}
return true
} | go | func Require(w http.ResponseWriter, r *http.Request, key string, val *string) bool {
*val = r.FormValue(key)
if *val == "" {
http.Error(w, fmt.Sprintf("Please pass POST/PUT/GET parameter value of '%s'.", key), 400)
return false
}
return true
} | [
"func",
"Require",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"key",
"string",
",",
"val",
"*",
"string",
")",
"bool",
"{",
"*",
"val",
"=",
"r",
".",
"FormValue",
"(",
"key",
")",
"\n",
"if",
"*",
"val",
"==",
"\"",
"\"",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"key",
")",
",",
"400",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // Store form parameter value of specified key to *val and return true; if key does not exist, set HTTP status 400 and return false. | [
"Store",
"form",
"parameter",
"value",
"of",
"specified",
"key",
"to",
"*",
"val",
"and",
"return",
"true",
";",
"if",
"key",
"does",
"not",
"exist",
"set",
"HTTP",
"status",
"400",
"and",
"return",
"false",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/srv.go#L36-L43 |
HouzuoGuo/tiedot | httpapi/srv.go | Start | func Start(dir string, port int, tlsCrt, tlsKey, jwtPubKey, jwtPrivateKey, bind, authToken string) {
var err error
HttpDB, err = db.OpenDB(dir)
if err != nil {
panic(err)
}
// These endpoints are always available and do not require authentication
http.HandleFunc("/", Welcome)
http.HandleFunc("/version", Version)
http.HandleFunc("/memstats", MemStats)
// Install API endpoint handlers that may require authorization
var authWrap func(http.HandlerFunc) http.HandlerFunc
if authToken != "" {
tdlog.Noticef("API endpoints now require the pre-shared token in Authorization header.")
authWrap = func(originalHandler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if "token "+authToken != r.Header.Get("Authorization") {
http.Error(w, "", http.StatusUnauthorized)
return
}
originalHandler(w, r)
}
}
} else if jwtPubKey != "" && jwtPrivateKey != "" {
tdlog.Noticef("API endpoints now require JWT in Authorization header.")
var publicKeyContent, privateKeyContent []byte
if publicKeyContent, err = ioutil.ReadFile(jwtPubKey); err != nil {
panic(err)
} else if publicKey, err = jwt.ParseRSAPublicKeyFromPEM(publicKeyContent); err != nil {
panic(err)
} else if privateKeyContent, err = ioutil.ReadFile(jwtPrivateKey); err != nil {
panic(err)
} else if privateKey, err = jwt.ParseRSAPrivateKeyFromPEM(privateKeyContent); err != nil {
panic(err)
}
jwtInitSetup()
authWrap = jwtWrap
// does not require JWT auth
http.HandleFunc("/getjwt", getJWT)
http.HandleFunc("/checkjwt", checkJWT)
} else {
tdlog.Noticef("API endpoints do not require Authorization header.")
authWrap = func(originalHandler http.HandlerFunc) http.HandlerFunc {
return originalHandler
}
}
// collection management (stop-the-world)
http.HandleFunc("/create", authWrap(Create))
http.HandleFunc("/rename", authWrap(Rename))
http.HandleFunc("/drop", authWrap(Drop))
http.HandleFunc("/all", authWrap(All))
http.HandleFunc("/scrub", authWrap(Scrub))
http.HandleFunc("/sync", authWrap(Sync))
// query
http.HandleFunc("/query", authWrap(Query))
http.HandleFunc("/count", authWrap(Count))
// document management
http.HandleFunc("/insert", authWrap(Insert))
http.HandleFunc("/get", authWrap(Get))
http.HandleFunc("/getpage", authWrap(GetPage))
http.HandleFunc("/update", authWrap(Update))
http.HandleFunc("/delete", authWrap(Delete))
http.HandleFunc("/approxdoccount", authWrap(ApproxDocCount))
// index management (stop-the-world)
http.HandleFunc("/index", authWrap(Index))
http.HandleFunc("/indexes", authWrap(Indexes))
http.HandleFunc("/unindex", authWrap(Unindex))
// misc (stop-the-world)
http.HandleFunc("/shutdown", authWrap(Shutdown))
http.HandleFunc("/dump", authWrap(Dump))
iface := "all interfaces"
if bind != "" {
iface = bind
}
if tlsCrt != "" {
tdlog.Noticef("Will listen on %s (HTTPS), port %d.", iface, port)
if err := http.ListenAndServeTLS(fmt.Sprintf("%s:%d", bind, port), tlsCrt, tlsKey, nil); err != nil {
tdlog.Panicf("Failed to start HTTPS service - %s", err)
}
} else {
tdlog.Noticef("Will listen on %s (HTTP), port %d.", iface, port)
http.ListenAndServe(fmt.Sprintf("%s:%d", bind, port), nil)
}
} | go | func Start(dir string, port int, tlsCrt, tlsKey, jwtPubKey, jwtPrivateKey, bind, authToken string) {
var err error
HttpDB, err = db.OpenDB(dir)
if err != nil {
panic(err)
}
// These endpoints are always available and do not require authentication
http.HandleFunc("/", Welcome)
http.HandleFunc("/version", Version)
http.HandleFunc("/memstats", MemStats)
// Install API endpoint handlers that may require authorization
var authWrap func(http.HandlerFunc) http.HandlerFunc
if authToken != "" {
tdlog.Noticef("API endpoints now require the pre-shared token in Authorization header.")
authWrap = func(originalHandler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if "token "+authToken != r.Header.Get("Authorization") {
http.Error(w, "", http.StatusUnauthorized)
return
}
originalHandler(w, r)
}
}
} else if jwtPubKey != "" && jwtPrivateKey != "" {
tdlog.Noticef("API endpoints now require JWT in Authorization header.")
var publicKeyContent, privateKeyContent []byte
if publicKeyContent, err = ioutil.ReadFile(jwtPubKey); err != nil {
panic(err)
} else if publicKey, err = jwt.ParseRSAPublicKeyFromPEM(publicKeyContent); err != nil {
panic(err)
} else if privateKeyContent, err = ioutil.ReadFile(jwtPrivateKey); err != nil {
panic(err)
} else if privateKey, err = jwt.ParseRSAPrivateKeyFromPEM(privateKeyContent); err != nil {
panic(err)
}
jwtInitSetup()
authWrap = jwtWrap
// does not require JWT auth
http.HandleFunc("/getjwt", getJWT)
http.HandleFunc("/checkjwt", checkJWT)
} else {
tdlog.Noticef("API endpoints do not require Authorization header.")
authWrap = func(originalHandler http.HandlerFunc) http.HandlerFunc {
return originalHandler
}
}
// collection management (stop-the-world)
http.HandleFunc("/create", authWrap(Create))
http.HandleFunc("/rename", authWrap(Rename))
http.HandleFunc("/drop", authWrap(Drop))
http.HandleFunc("/all", authWrap(All))
http.HandleFunc("/scrub", authWrap(Scrub))
http.HandleFunc("/sync", authWrap(Sync))
// query
http.HandleFunc("/query", authWrap(Query))
http.HandleFunc("/count", authWrap(Count))
// document management
http.HandleFunc("/insert", authWrap(Insert))
http.HandleFunc("/get", authWrap(Get))
http.HandleFunc("/getpage", authWrap(GetPage))
http.HandleFunc("/update", authWrap(Update))
http.HandleFunc("/delete", authWrap(Delete))
http.HandleFunc("/approxdoccount", authWrap(ApproxDocCount))
// index management (stop-the-world)
http.HandleFunc("/index", authWrap(Index))
http.HandleFunc("/indexes", authWrap(Indexes))
http.HandleFunc("/unindex", authWrap(Unindex))
// misc (stop-the-world)
http.HandleFunc("/shutdown", authWrap(Shutdown))
http.HandleFunc("/dump", authWrap(Dump))
iface := "all interfaces"
if bind != "" {
iface = bind
}
if tlsCrt != "" {
tdlog.Noticef("Will listen on %s (HTTPS), port %d.", iface, port)
if err := http.ListenAndServeTLS(fmt.Sprintf("%s:%d", bind, port), tlsCrt, tlsKey, nil); err != nil {
tdlog.Panicf("Failed to start HTTPS service - %s", err)
}
} else {
tdlog.Noticef("Will listen on %s (HTTP), port %d.", iface, port)
http.ListenAndServe(fmt.Sprintf("%s:%d", bind, port), nil)
}
} | [
"func",
"Start",
"(",
"dir",
"string",
",",
"port",
"int",
",",
"tlsCrt",
",",
"tlsKey",
",",
"jwtPubKey",
",",
"jwtPrivateKey",
",",
"bind",
",",
"authToken",
"string",
")",
"{",
"var",
"err",
"error",
"\n",
"HttpDB",
",",
"err",
"=",
"db",
".",
"OpenDB",
"(",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// These endpoints are always available and do not require authentication",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"Welcome",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"Version",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"MemStats",
")",
"\n\n",
"// Install API endpoint handlers that may require authorization",
"var",
"authWrap",
"func",
"(",
"http",
".",
"HandlerFunc",
")",
"http",
".",
"HandlerFunc",
"\n",
"if",
"authToken",
"!=",
"\"",
"\"",
"{",
"tdlog",
".",
"Noticef",
"(",
"\"",
"\"",
")",
"\n",
"authWrap",
"=",
"func",
"(",
"originalHandler",
"http",
".",
"HandlerFunc",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"\"",
"\"",
"+",
"authToken",
"!=",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"return",
"\n",
"}",
"\n",
"originalHandler",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"if",
"jwtPubKey",
"!=",
"\"",
"\"",
"&&",
"jwtPrivateKey",
"!=",
"\"",
"\"",
"{",
"tdlog",
".",
"Noticef",
"(",
"\"",
"\"",
")",
"\n",
"var",
"publicKeyContent",
",",
"privateKeyContent",
"[",
"]",
"byte",
"\n",
"if",
"publicKeyContent",
",",
"err",
"=",
"ioutil",
".",
"ReadFile",
"(",
"jwtPubKey",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"publicKey",
",",
"err",
"=",
"jwt",
".",
"ParseRSAPublicKeyFromPEM",
"(",
"publicKeyContent",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"privateKeyContent",
",",
"err",
"=",
"ioutil",
".",
"ReadFile",
"(",
"jwtPrivateKey",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"privateKey",
",",
"err",
"=",
"jwt",
".",
"ParseRSAPrivateKeyFromPEM",
"(",
"privateKeyContent",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"jwtInitSetup",
"(",
")",
"\n",
"authWrap",
"=",
"jwtWrap",
"\n",
"// does not require JWT auth",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"getJWT",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"checkJWT",
")",
"\n",
"}",
"else",
"{",
"tdlog",
".",
"Noticef",
"(",
"\"",
"\"",
")",
"\n",
"authWrap",
"=",
"func",
"(",
"originalHandler",
"http",
".",
"HandlerFunc",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"originalHandler",
"\n",
"}",
"\n",
"}",
"\n",
"// collection management (stop-the-world)",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Create",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Rename",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Drop",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"All",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Scrub",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Sync",
")",
")",
"\n",
"// query",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Query",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Count",
")",
")",
"\n",
"// document management",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Insert",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Get",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"GetPage",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Update",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Delete",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"ApproxDocCount",
")",
")",
"\n",
"// index management (stop-the-world)",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Index",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Indexes",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Unindex",
")",
")",
"\n",
"// misc (stop-the-world)",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Shutdown",
")",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"authWrap",
"(",
"Dump",
")",
")",
"\n\n",
"iface",
":=",
"\"",
"\"",
"\n",
"if",
"bind",
"!=",
"\"",
"\"",
"{",
"iface",
"=",
"bind",
"\n",
"}",
"\n\n",
"if",
"tlsCrt",
"!=",
"\"",
"\"",
"{",
"tdlog",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"iface",
",",
"port",
")",
"\n",
"if",
"err",
":=",
"http",
".",
"ListenAndServeTLS",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"bind",
",",
"port",
")",
",",
"tlsCrt",
",",
"tlsKey",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"tdlog",
".",
"Panicf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"tdlog",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"iface",
",",
"port",
")",
"\n",
"http",
".",
"ListenAndServe",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"bind",
",",
"port",
")",
",",
"nil",
")",
"\n",
"}",
"\n",
"}"
] | // Start HTTP server and block until the server shuts down. Panic on error. | [
"Start",
"HTTP",
"server",
"and",
"block",
"until",
"the",
"server",
"shuts",
"down",
".",
"Panic",
"on",
"error",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/srv.go#L46-L133 |
HouzuoGuo/tiedot | httpapi/srv.go | Welcome | func Welcome(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Invalid API endpoint", 404)
return
}
w.Write([]byte("Welcome to tiedot"))
} | go | func Welcome(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Invalid API endpoint", 404)
return
}
w.Write([]byte("Welcome to tiedot"))
} | [
"func",
"Welcome",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"URL",
".",
"Path",
"!=",
"\"",
"\"",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"404",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // Greet user with a welcome message. | [
"Greet",
"user",
"with",
"a",
"welcome",
"message",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/srv.go#L136-L142 |
google/logger | logger_windows.go | Write | func (w *writer) Write(b []byte) (int, error) {
switch w.pri {
case sInfo:
return len(b), w.el.Info(1, string(b))
case sWarning:
return len(b), w.el.Warning(3, string(b))
case sError:
return len(b), w.el.Error(2, string(b))
}
return 0, fmt.Errorf("unrecognized severity: %v", w.pri)
} | go | func (w *writer) Write(b []byte) (int, error) {
switch w.pri {
case sInfo:
return len(b), w.el.Info(1, string(b))
case sWarning:
return len(b), w.el.Warning(3, string(b))
case sError:
return len(b), w.el.Error(2, string(b))
}
return 0, fmt.Errorf("unrecognized severity: %v", w.pri)
} | [
"func",
"(",
"w",
"*",
"writer",
")",
"Write",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"switch",
"w",
".",
"pri",
"{",
"case",
"sInfo",
":",
"return",
"len",
"(",
"b",
")",
",",
"w",
".",
"el",
".",
"Info",
"(",
"1",
",",
"string",
"(",
"b",
")",
")",
"\n",
"case",
"sWarning",
":",
"return",
"len",
"(",
"b",
")",
",",
"w",
".",
"el",
".",
"Warning",
"(",
"3",
",",
"string",
"(",
"b",
")",
")",
"\n",
"case",
"sError",
":",
"return",
"len",
"(",
"b",
")",
",",
"w",
".",
"el",
".",
"Error",
"(",
"2",
",",
"string",
"(",
"b",
")",
")",
"\n",
"}",
"\n",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"w",
".",
"pri",
")",
"\n",
"}"
] | // Write sends a log message to the Event Log. | [
"Write",
"sends",
"a",
"log",
"message",
"to",
"the",
"Event",
"Log",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger_windows.go#L31-L41 |
google/logger | logger.go | initialize | func initialize() {
defaultLogger = &Logger{
infoLog: log.New(os.Stderr, initText+tagInfo, flags),
warningLog: log.New(os.Stderr, initText+tagWarning, flags),
errorLog: log.New(os.Stderr, initText+tagError, flags),
fatalLog: log.New(os.Stderr, initText+tagFatal, flags),
}
} | go | func initialize() {
defaultLogger = &Logger{
infoLog: log.New(os.Stderr, initText+tagInfo, flags),
warningLog: log.New(os.Stderr, initText+tagWarning, flags),
errorLog: log.New(os.Stderr, initText+tagError, flags),
fatalLog: log.New(os.Stderr, initText+tagFatal, flags),
}
} | [
"func",
"initialize",
"(",
")",
"{",
"defaultLogger",
"=",
"&",
"Logger",
"{",
"infoLog",
":",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"initText",
"+",
"tagInfo",
",",
"flags",
")",
",",
"warningLog",
":",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"initText",
"+",
"tagWarning",
",",
"flags",
")",
",",
"errorLog",
":",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"initText",
"+",
"tagError",
",",
"flags",
")",
",",
"fatalLog",
":",
"log",
".",
"New",
"(",
"os",
".",
"Stderr",
",",
"initText",
"+",
"tagFatal",
",",
"flags",
")",
",",
"}",
"\n",
"}"
] | // initialize resets defaultLogger. Which allows tests to reset environment. | [
"initialize",
"resets",
"defaultLogger",
".",
"Which",
"allows",
"tests",
"to",
"reset",
"environment",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L56-L63 |
google/logger | logger.go | Init | func Init(name string, verbose, systemLog bool, logFile io.Writer) *Logger {
var il, wl, el io.Writer
var syslogErr error
if systemLog {
il, wl, el, syslogErr = setup(name)
}
iLogs := []io.Writer{logFile}
wLogs := []io.Writer{logFile}
eLogs := []io.Writer{logFile}
if il != nil {
iLogs = append(iLogs, il)
}
if wl != nil {
wLogs = append(wLogs, wl)
}
if el != nil {
eLogs = append(eLogs, el)
}
// Windows services don't have stdout/stderr. Writes will fail, so try them last.
eLogs = append(eLogs, os.Stderr)
if verbose {
iLogs = append(iLogs, os.Stdout)
wLogs = append(wLogs, os.Stdout)
}
l := Logger{
infoLog: log.New(io.MultiWriter(iLogs...), tagInfo, flags),
warningLog: log.New(io.MultiWriter(wLogs...), tagWarning, flags),
errorLog: log.New(io.MultiWriter(eLogs...), tagError, flags),
fatalLog: log.New(io.MultiWriter(eLogs...), tagFatal, flags),
}
for _, w := range []io.Writer{logFile, il, wl, el} {
if c, ok := w.(io.Closer); ok && c != nil {
l.closers = append(l.closers, c)
}
}
l.initialized = true
logLock.Lock()
defer logLock.Unlock()
if !defaultLogger.initialized {
defaultLogger = &l
}
if syslogErr != nil {
Error(syslogErr)
}
return &l
} | go | func Init(name string, verbose, systemLog bool, logFile io.Writer) *Logger {
var il, wl, el io.Writer
var syslogErr error
if systemLog {
il, wl, el, syslogErr = setup(name)
}
iLogs := []io.Writer{logFile}
wLogs := []io.Writer{logFile}
eLogs := []io.Writer{logFile}
if il != nil {
iLogs = append(iLogs, il)
}
if wl != nil {
wLogs = append(wLogs, wl)
}
if el != nil {
eLogs = append(eLogs, el)
}
// Windows services don't have stdout/stderr. Writes will fail, so try them last.
eLogs = append(eLogs, os.Stderr)
if verbose {
iLogs = append(iLogs, os.Stdout)
wLogs = append(wLogs, os.Stdout)
}
l := Logger{
infoLog: log.New(io.MultiWriter(iLogs...), tagInfo, flags),
warningLog: log.New(io.MultiWriter(wLogs...), tagWarning, flags),
errorLog: log.New(io.MultiWriter(eLogs...), tagError, flags),
fatalLog: log.New(io.MultiWriter(eLogs...), tagFatal, flags),
}
for _, w := range []io.Writer{logFile, il, wl, el} {
if c, ok := w.(io.Closer); ok && c != nil {
l.closers = append(l.closers, c)
}
}
l.initialized = true
logLock.Lock()
defer logLock.Unlock()
if !defaultLogger.initialized {
defaultLogger = &l
}
if syslogErr != nil {
Error(syslogErr)
}
return &l
} | [
"func",
"Init",
"(",
"name",
"string",
",",
"verbose",
",",
"systemLog",
"bool",
",",
"logFile",
"io",
".",
"Writer",
")",
"*",
"Logger",
"{",
"var",
"il",
",",
"wl",
",",
"el",
"io",
".",
"Writer",
"\n",
"var",
"syslogErr",
"error",
"\n",
"if",
"systemLog",
"{",
"il",
",",
"wl",
",",
"el",
",",
"syslogErr",
"=",
"setup",
"(",
"name",
")",
"\n",
"}",
"\n\n",
"iLogs",
":=",
"[",
"]",
"io",
".",
"Writer",
"{",
"logFile",
"}",
"\n",
"wLogs",
":=",
"[",
"]",
"io",
".",
"Writer",
"{",
"logFile",
"}",
"\n",
"eLogs",
":=",
"[",
"]",
"io",
".",
"Writer",
"{",
"logFile",
"}",
"\n",
"if",
"il",
"!=",
"nil",
"{",
"iLogs",
"=",
"append",
"(",
"iLogs",
",",
"il",
")",
"\n",
"}",
"\n",
"if",
"wl",
"!=",
"nil",
"{",
"wLogs",
"=",
"append",
"(",
"wLogs",
",",
"wl",
")",
"\n",
"}",
"\n",
"if",
"el",
"!=",
"nil",
"{",
"eLogs",
"=",
"append",
"(",
"eLogs",
",",
"el",
")",
"\n",
"}",
"\n",
"// Windows services don't have stdout/stderr. Writes will fail, so try them last.",
"eLogs",
"=",
"append",
"(",
"eLogs",
",",
"os",
".",
"Stderr",
")",
"\n",
"if",
"verbose",
"{",
"iLogs",
"=",
"append",
"(",
"iLogs",
",",
"os",
".",
"Stdout",
")",
"\n",
"wLogs",
"=",
"append",
"(",
"wLogs",
",",
"os",
".",
"Stdout",
")",
"\n",
"}",
"\n\n",
"l",
":=",
"Logger",
"{",
"infoLog",
":",
"log",
".",
"New",
"(",
"io",
".",
"MultiWriter",
"(",
"iLogs",
"...",
")",
",",
"tagInfo",
",",
"flags",
")",
",",
"warningLog",
":",
"log",
".",
"New",
"(",
"io",
".",
"MultiWriter",
"(",
"wLogs",
"...",
")",
",",
"tagWarning",
",",
"flags",
")",
",",
"errorLog",
":",
"log",
".",
"New",
"(",
"io",
".",
"MultiWriter",
"(",
"eLogs",
"...",
")",
",",
"tagError",
",",
"flags",
")",
",",
"fatalLog",
":",
"log",
".",
"New",
"(",
"io",
".",
"MultiWriter",
"(",
"eLogs",
"...",
")",
",",
"tagFatal",
",",
"flags",
")",
",",
"}",
"\n",
"for",
"_",
",",
"w",
":=",
"range",
"[",
"]",
"io",
".",
"Writer",
"{",
"logFile",
",",
"il",
",",
"wl",
",",
"el",
"}",
"{",
"if",
"c",
",",
"ok",
":=",
"w",
".",
"(",
"io",
".",
"Closer",
")",
";",
"ok",
"&&",
"c",
"!=",
"nil",
"{",
"l",
".",
"closers",
"=",
"append",
"(",
"l",
".",
"closers",
",",
"c",
")",
"\n",
"}",
"\n",
"}",
"\n",
"l",
".",
"initialized",
"=",
"true",
"\n\n",
"logLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"logLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"defaultLogger",
".",
"initialized",
"{",
"defaultLogger",
"=",
"&",
"l",
"\n",
"}",
"\n\n",
"if",
"syslogErr",
"!=",
"nil",
"{",
"Error",
"(",
"syslogErr",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"l",
"\n",
"}"
] | // Init sets up logging and should be called before log functions, usually in
// the caller's main(). Default log functions can be called before Init(), but log
// output will only go to stderr (along with a warning).
// The first call to Init populates the default logger and returns the
// generated logger, subsequent calls to Init will only return the generated
// logger.
// If the logFile passed in also satisfies io.Closer, logFile.Close will be called
// when closing the logger. | [
"Init",
"sets",
"up",
"logging",
"and",
"should",
"be",
"called",
"before",
"log",
"functions",
"usually",
"in",
"the",
"caller",
"s",
"main",
"()",
".",
"Default",
"log",
"functions",
"can",
"be",
"called",
"before",
"Init",
"()",
"but",
"log",
"output",
"will",
"only",
"go",
"to",
"stderr",
"(",
"along",
"with",
"a",
"warning",
")",
".",
"The",
"first",
"call",
"to",
"Init",
"populates",
"the",
"default",
"logger",
"and",
"returns",
"the",
"generated",
"logger",
"subsequent",
"calls",
"to",
"Init",
"will",
"only",
"return",
"the",
"generated",
"logger",
".",
"If",
"the",
"logFile",
"passed",
"in",
"also",
"satisfies",
"io",
".",
"Closer",
"logFile",
".",
"Close",
"will",
"be",
"called",
"when",
"closing",
"the",
"logger",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L77-L127 |
google/logger | logger.go | Close | func (l *Logger) Close() {
logLock.Lock()
defer logLock.Unlock()
for _, c := range l.closers {
if err := c.Close(); err != nil {
fmt.Fprintf(os.Stderr, "Failed to close log %v: %v\n", c, err)
}
}
} | go | func (l *Logger) Close() {
logLock.Lock()
defer logLock.Unlock()
for _, c := range l.closers {
if err := c.Close(); err != nil {
fmt.Fprintf(os.Stderr, "Failed to close log %v: %v\n", c, err)
}
}
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Close",
"(",
")",
"{",
"logLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"logLock",
".",
"Unlock",
"(",
")",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"l",
".",
"closers",
"{",
"if",
"err",
":=",
"c",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"c",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Close closes all the underlying log writers, which will flush any cached logs.
// Any errors from closing the underlying log writers will be printed to stderr.
// Once Close is called, all future calls to the logger will panic. | [
"Close",
"closes",
"all",
"the",
"underlying",
"log",
"writers",
"which",
"will",
"flush",
"any",
"cached",
"logs",
".",
"Any",
"errors",
"from",
"closing",
"the",
"underlying",
"log",
"writers",
"will",
"be",
"printed",
"to",
"stderr",
".",
"Once",
"Close",
"is",
"called",
"all",
"future",
"calls",
"to",
"the",
"logger",
"will",
"panic",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L160-L168 |
google/logger | logger.go | Info | func (l *Logger) Info(v ...interface{}) {
l.output(sInfo, 0, fmt.Sprint(v...))
} | go | func (l *Logger) Info(v ...interface{}) {
l.output(sInfo, 0, fmt.Sprint(v...))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Info",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sInfo",
",",
"0",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
"\n",
"}"
] | // Info logs with the Info severity.
// Arguments are handled in the manner of fmt.Print. | [
"Info",
"logs",
"with",
"the",
"Info",
"severity",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Print",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L172-L174 |
google/logger | logger.go | InfoDepth | func (l *Logger) InfoDepth(depth int, v ...interface{}) {
l.output(sInfo, depth, fmt.Sprint(v...))
} | go | func (l *Logger) InfoDepth(depth int, v ...interface{}) {
l.output(sInfo, depth, fmt.Sprint(v...))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"InfoDepth",
"(",
"depth",
"int",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sInfo",
",",
"depth",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
"\n",
"}"
] | // InfoDepth acts as Info but uses depth to determine which call frame to log.
// InfoDepth(0, "msg") is the same as Info("msg"). | [
"InfoDepth",
"acts",
"as",
"Info",
"but",
"uses",
"depth",
"to",
"determine",
"which",
"call",
"frame",
"to",
"log",
".",
"InfoDepth",
"(",
"0",
"msg",
")",
"is",
"the",
"same",
"as",
"Info",
"(",
"msg",
")",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L178-L180 |
google/logger | logger.go | Infoln | func (l *Logger) Infoln(v ...interface{}) {
l.output(sInfo, 0, fmt.Sprintln(v...))
} | go | func (l *Logger) Infoln(v ...interface{}) {
l.output(sInfo, 0, fmt.Sprintln(v...))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Infoln",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sInfo",
",",
"0",
",",
"fmt",
".",
"Sprintln",
"(",
"v",
"...",
")",
")",
"\n",
"}"
] | // Infoln logs with the Info severity.
// Arguments are handled in the manner of fmt.Println. | [
"Infoln",
"logs",
"with",
"the",
"Info",
"severity",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Println",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L184-L186 |
google/logger | logger.go | Infof | func (l *Logger) Infof(format string, v ...interface{}) {
l.output(sInfo, 0, fmt.Sprintf(format, v...))
} | go | func (l *Logger) Infof(format string, v ...interface{}) {
l.output(sInfo, 0, fmt.Sprintf(format, v...))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Infof",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sInfo",
",",
"0",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"v",
"...",
")",
")",
"\n",
"}"
] | // Infof logs with the Info severity.
// Arguments are handled in the manner of fmt.Printf. | [
"Infof",
"logs",
"with",
"the",
"Info",
"severity",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Printf",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L190-L192 |
google/logger | logger.go | Warning | func (l *Logger) Warning(v ...interface{}) {
l.output(sWarning, 0, fmt.Sprint(v...))
} | go | func (l *Logger) Warning(v ...interface{}) {
l.output(sWarning, 0, fmt.Sprint(v...))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Warning",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sWarning",
",",
"0",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
"\n",
"}"
] | // Warning logs with the Warning severity.
// Arguments are handled in the manner of fmt.Print. | [
"Warning",
"logs",
"with",
"the",
"Warning",
"severity",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Print",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L196-L198 |
google/logger | logger.go | WarningDepth | func (l *Logger) WarningDepth(depth int, v ...interface{}) {
l.output(sWarning, depth, fmt.Sprint(v...))
} | go | func (l *Logger) WarningDepth(depth int, v ...interface{}) {
l.output(sWarning, depth, fmt.Sprint(v...))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"WarningDepth",
"(",
"depth",
"int",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sWarning",
",",
"depth",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
"\n",
"}"
] | // WarningDepth acts as Warning but uses depth to determine which call frame to log.
// WarningDepth(0, "msg") is the same as Warning("msg"). | [
"WarningDepth",
"acts",
"as",
"Warning",
"but",
"uses",
"depth",
"to",
"determine",
"which",
"call",
"frame",
"to",
"log",
".",
"WarningDepth",
"(",
"0",
"msg",
")",
"is",
"the",
"same",
"as",
"Warning",
"(",
"msg",
")",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L202-L204 |
google/logger | logger.go | Warningln | func (l *Logger) Warningln(v ...interface{}) {
l.output(sWarning, 0, fmt.Sprintln(v...))
} | go | func (l *Logger) Warningln(v ...interface{}) {
l.output(sWarning, 0, fmt.Sprintln(v...))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Warningln",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sWarning",
",",
"0",
",",
"fmt",
".",
"Sprintln",
"(",
"v",
"...",
")",
")",
"\n",
"}"
] | // Warningln logs with the Warning severity.
// Arguments are handled in the manner of fmt.Println. | [
"Warningln",
"logs",
"with",
"the",
"Warning",
"severity",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Println",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L208-L210 |
google/logger | logger.go | Warningf | func (l *Logger) Warningf(format string, v ...interface{}) {
l.output(sWarning, 0, fmt.Sprintf(format, v...))
} | go | func (l *Logger) Warningf(format string, v ...interface{}) {
l.output(sWarning, 0, fmt.Sprintf(format, v...))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Warningf",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sWarning",
",",
"0",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"v",
"...",
")",
")",
"\n",
"}"
] | // Warningf logs with the Warning severity.
// Arguments are handled in the manner of fmt.Printf. | [
"Warningf",
"logs",
"with",
"the",
"Warning",
"severity",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Printf",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L214-L216 |
google/logger | logger.go | Error | func (l *Logger) Error(v ...interface{}) {
l.output(sError, 0, fmt.Sprint(v...))
} | go | func (l *Logger) Error(v ...interface{}) {
l.output(sError, 0, fmt.Sprint(v...))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Error",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sError",
",",
"0",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
"\n",
"}"
] | // Error logs with the ERROR severity.
// Arguments are handled in the manner of fmt.Print. | [
"Error",
"logs",
"with",
"the",
"ERROR",
"severity",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Print",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L220-L222 |
google/logger | logger.go | ErrorDepth | func (l *Logger) ErrorDepth(depth int, v ...interface{}) {
l.output(sError, depth, fmt.Sprint(v...))
} | go | func (l *Logger) ErrorDepth(depth int, v ...interface{}) {
l.output(sError, depth, fmt.Sprint(v...))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"ErrorDepth",
"(",
"depth",
"int",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sError",
",",
"depth",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
"\n",
"}"
] | // ErrorDepth acts as Error but uses depth to determine which call frame to log.
// ErrorDepth(0, "msg") is the same as Error("msg"). | [
"ErrorDepth",
"acts",
"as",
"Error",
"but",
"uses",
"depth",
"to",
"determine",
"which",
"call",
"frame",
"to",
"log",
".",
"ErrorDepth",
"(",
"0",
"msg",
")",
"is",
"the",
"same",
"as",
"Error",
"(",
"msg",
")",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L226-L228 |
google/logger | logger.go | Errorln | func (l *Logger) Errorln(v ...interface{}) {
l.output(sError, 0, fmt.Sprintln(v...))
} | go | func (l *Logger) Errorln(v ...interface{}) {
l.output(sError, 0, fmt.Sprintln(v...))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Errorln",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sError",
",",
"0",
",",
"fmt",
".",
"Sprintln",
"(",
"v",
"...",
")",
")",
"\n",
"}"
] | // Errorln logs with the ERROR severity.
// Arguments are handled in the manner of fmt.Println. | [
"Errorln",
"logs",
"with",
"the",
"ERROR",
"severity",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Println",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L232-L234 |
google/logger | logger.go | Errorf | func (l *Logger) Errorf(format string, v ...interface{}) {
l.output(sError, 0, fmt.Sprintf(format, v...))
} | go | func (l *Logger) Errorf(format string, v ...interface{}) {
l.output(sError, 0, fmt.Sprintf(format, v...))
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Errorf",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sError",
",",
"0",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"v",
"...",
")",
")",
"\n",
"}"
] | // Errorf logs with the Error severity.
// Arguments are handled in the manner of fmt.Printf. | [
"Errorf",
"logs",
"with",
"the",
"Error",
"severity",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Printf",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L238-L240 |
google/logger | logger.go | Fatal | func (l *Logger) Fatal(v ...interface{}) {
l.output(sFatal, 0, fmt.Sprint(v...))
l.Close()
os.Exit(1)
} | go | func (l *Logger) Fatal(v ...interface{}) {
l.output(sFatal, 0, fmt.Sprint(v...))
l.Close()
os.Exit(1)
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Fatal",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sFatal",
",",
"0",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
"\n",
"l",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | // Fatal logs with the Fatal severity, and ends with os.Exit(1).
// Arguments are handled in the manner of fmt.Print. | [
"Fatal",
"logs",
"with",
"the",
"Fatal",
"severity",
"and",
"ends",
"with",
"os",
".",
"Exit",
"(",
"1",
")",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Print",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L244-L248 |
google/logger | logger.go | FatalDepth | func (l *Logger) FatalDepth(depth int, v ...interface{}) {
l.output(sFatal, depth, fmt.Sprint(v...))
l.Close()
os.Exit(1)
} | go | func (l *Logger) FatalDepth(depth int, v ...interface{}) {
l.output(sFatal, depth, fmt.Sprint(v...))
l.Close()
os.Exit(1)
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"FatalDepth",
"(",
"depth",
"int",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sFatal",
",",
"depth",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
"\n",
"l",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | // FatalDepth acts as Fatal but uses depth to determine which call frame to log.
// FatalDepth(0, "msg") is the same as Fatal("msg"). | [
"FatalDepth",
"acts",
"as",
"Fatal",
"but",
"uses",
"depth",
"to",
"determine",
"which",
"call",
"frame",
"to",
"log",
".",
"FatalDepth",
"(",
"0",
"msg",
")",
"is",
"the",
"same",
"as",
"Fatal",
"(",
"msg",
")",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L252-L256 |
google/logger | logger.go | Fatalln | func (l *Logger) Fatalln(v ...interface{}) {
l.output(sFatal, 0, fmt.Sprintln(v...))
l.Close()
os.Exit(1)
} | go | func (l *Logger) Fatalln(v ...interface{}) {
l.output(sFatal, 0, fmt.Sprintln(v...))
l.Close()
os.Exit(1)
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Fatalln",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sFatal",
",",
"0",
",",
"fmt",
".",
"Sprintln",
"(",
"v",
"...",
")",
")",
"\n",
"l",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | // Fatalln logs with the Fatal severity, and ends with os.Exit(1).
// Arguments are handled in the manner of fmt.Println. | [
"Fatalln",
"logs",
"with",
"the",
"Fatal",
"severity",
"and",
"ends",
"with",
"os",
".",
"Exit",
"(",
"1",
")",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Println",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L260-L264 |
google/logger | logger.go | Fatalf | func (l *Logger) Fatalf(format string, v ...interface{}) {
l.output(sFatal, 0, fmt.Sprintf(format, v...))
l.Close()
os.Exit(1)
} | go | func (l *Logger) Fatalf(format string, v ...interface{}) {
l.output(sFatal, 0, fmt.Sprintf(format, v...))
l.Close()
os.Exit(1)
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Fatalf",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"output",
"(",
"sFatal",
",",
"0",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"v",
"...",
")",
")",
"\n",
"l",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | // Fatalf logs with the Fatal severity, and ends with os.Exit(1).
// Arguments are handled in the manner of fmt.Printf. | [
"Fatalf",
"logs",
"with",
"the",
"Fatal",
"severity",
"and",
"ends",
"with",
"os",
".",
"Exit",
"(",
"1",
")",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Printf",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L268-L272 |
google/logger | logger.go | SetFlags | func SetFlags(flag int) {
defaultLogger.infoLog.SetFlags(flag)
defaultLogger.warningLog.SetFlags(flag)
defaultLogger.errorLog.SetFlags(flag)
defaultLogger.fatalLog.SetFlags(flag)
} | go | func SetFlags(flag int) {
defaultLogger.infoLog.SetFlags(flag)
defaultLogger.warningLog.SetFlags(flag)
defaultLogger.errorLog.SetFlags(flag)
defaultLogger.fatalLog.SetFlags(flag)
} | [
"func",
"SetFlags",
"(",
"flag",
"int",
")",
"{",
"defaultLogger",
".",
"infoLog",
".",
"SetFlags",
"(",
"flag",
")",
"\n",
"defaultLogger",
".",
"warningLog",
".",
"SetFlags",
"(",
"flag",
")",
"\n",
"defaultLogger",
".",
"errorLog",
".",
"SetFlags",
"(",
"flag",
")",
"\n",
"defaultLogger",
".",
"fatalLog",
".",
"SetFlags",
"(",
"flag",
")",
"\n",
"}"
] | // SetFlags sets the output flags for the logger. | [
"SetFlags",
"sets",
"the",
"output",
"flags",
"for",
"the",
"logger",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L275-L280 |
google/logger | logger.go | InfoDepth | func InfoDepth(depth int, v ...interface{}) {
defaultLogger.output(sInfo, depth, fmt.Sprint(v...))
} | go | func InfoDepth(depth int, v ...interface{}) {
defaultLogger.output(sInfo, depth, fmt.Sprint(v...))
} | [
"func",
"InfoDepth",
"(",
"depth",
"int",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"defaultLogger",
".",
"output",
"(",
"sInfo",
",",
"depth",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
"\n",
"}"
] | // InfoDepth acts as Info but uses depth to determine which call frame to log.
// InfoDepth(0, "msg") is the same as Info("msg"). | [
"InfoDepth",
"acts",
"as",
"Info",
"but",
"uses",
"depth",
"to",
"determine",
"which",
"call",
"frame",
"to",
"log",
".",
"InfoDepth",
"(",
"0",
"msg",
")",
"is",
"the",
"same",
"as",
"Info",
"(",
"msg",
")",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L290-L292 |
google/logger | logger.go | Infof | func Infof(format string, v ...interface{}) {
defaultLogger.output(sInfo, 0, fmt.Sprintf(format, v...))
} | go | func Infof(format string, v ...interface{}) {
defaultLogger.output(sInfo, 0, fmt.Sprintf(format, v...))
} | [
"func",
"Infof",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"defaultLogger",
".",
"output",
"(",
"sInfo",
",",
"0",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"v",
"...",
")",
")",
"\n",
"}"
] | // Infof uses the default logger and logs with the Info severity.
// Arguments are handled in the manner of fmt.Printf. | [
"Infof",
"uses",
"the",
"default",
"logger",
"and",
"logs",
"with",
"the",
"Info",
"severity",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Printf",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L302-L304 |
google/logger | logger.go | WarningDepth | func WarningDepth(depth int, v ...interface{}) {
defaultLogger.output(sWarning, depth, fmt.Sprint(v...))
} | go | func WarningDepth(depth int, v ...interface{}) {
defaultLogger.output(sWarning, depth, fmt.Sprint(v...))
} | [
"func",
"WarningDepth",
"(",
"depth",
"int",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"defaultLogger",
".",
"output",
"(",
"sWarning",
",",
"depth",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
"\n",
"}"
] | // WarningDepth acts as Warning but uses depth to determine which call frame to log.
// WarningDepth(0, "msg") is the same as Warning("msg"). | [
"WarningDepth",
"acts",
"as",
"Warning",
"but",
"uses",
"depth",
"to",
"determine",
"which",
"call",
"frame",
"to",
"log",
".",
"WarningDepth",
"(",
"0",
"msg",
")",
"is",
"the",
"same",
"as",
"Warning",
"(",
"msg",
")",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L314-L316 |
google/logger | logger.go | Warningf | func Warningf(format string, v ...interface{}) {
defaultLogger.output(sWarning, 0, fmt.Sprintf(format, v...))
} | go | func Warningf(format string, v ...interface{}) {
defaultLogger.output(sWarning, 0, fmt.Sprintf(format, v...))
} | [
"func",
"Warningf",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"defaultLogger",
".",
"output",
"(",
"sWarning",
",",
"0",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"v",
"...",
")",
")",
"\n",
"}"
] | // Warningf uses the default logger and logs with the Warning severity.
// Arguments are handled in the manner of fmt.Printf. | [
"Warningf",
"uses",
"the",
"default",
"logger",
"and",
"logs",
"with",
"the",
"Warning",
"severity",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Printf",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L326-L328 |
google/logger | logger.go | ErrorDepth | func ErrorDepth(depth int, v ...interface{}) {
defaultLogger.output(sError, depth, fmt.Sprint(v...))
} | go | func ErrorDepth(depth int, v ...interface{}) {
defaultLogger.output(sError, depth, fmt.Sprint(v...))
} | [
"func",
"ErrorDepth",
"(",
"depth",
"int",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"defaultLogger",
".",
"output",
"(",
"sError",
",",
"depth",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
"\n",
"}"
] | // ErrorDepth acts as Error but uses depth to determine which call frame to log.
// ErrorDepth(0, "msg") is the same as Error("msg"). | [
"ErrorDepth",
"acts",
"as",
"Error",
"but",
"uses",
"depth",
"to",
"determine",
"which",
"call",
"frame",
"to",
"log",
".",
"ErrorDepth",
"(",
"0",
"msg",
")",
"is",
"the",
"same",
"as",
"Error",
"(",
"msg",
")",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L338-L340 |
google/logger | logger.go | Errorf | func Errorf(format string, v ...interface{}) {
defaultLogger.output(sError, 0, fmt.Sprintf(format, v...))
} | go | func Errorf(format string, v ...interface{}) {
defaultLogger.output(sError, 0, fmt.Sprintf(format, v...))
} | [
"func",
"Errorf",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"defaultLogger",
".",
"output",
"(",
"sError",
",",
"0",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"v",
"...",
")",
")",
"\n",
"}"
] | // Errorf uses the default logger and logs with the Error severity.
// Arguments are handled in the manner of fmt.Printf. | [
"Errorf",
"uses",
"the",
"default",
"logger",
"and",
"logs",
"with",
"the",
"Error",
"severity",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Printf",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L350-L352 |
google/logger | logger.go | Fatal | func Fatal(v ...interface{}) {
defaultLogger.output(sFatal, 0, fmt.Sprint(v...))
defaultLogger.Close()
os.Exit(1)
} | go | func Fatal(v ...interface{}) {
defaultLogger.output(sFatal, 0, fmt.Sprint(v...))
defaultLogger.Close()
os.Exit(1)
} | [
"func",
"Fatal",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"defaultLogger",
".",
"output",
"(",
"sFatal",
",",
"0",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
"\n",
"defaultLogger",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | // Fatalln uses the default logger, logs with the Fatal severity,
// and ends with os.Exit(1).
// Arguments are handled in the manner of fmt.Print. | [
"Fatalln",
"uses",
"the",
"default",
"logger",
"logs",
"with",
"the",
"Fatal",
"severity",
"and",
"ends",
"with",
"os",
".",
"Exit",
"(",
"1",
")",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Print",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L357-L361 |
google/logger | logger.go | FatalDepth | func FatalDepth(depth int, v ...interface{}) {
defaultLogger.output(sFatal, depth, fmt.Sprint(v...))
defaultLogger.Close()
os.Exit(1)
} | go | func FatalDepth(depth int, v ...interface{}) {
defaultLogger.output(sFatal, depth, fmt.Sprint(v...))
defaultLogger.Close()
os.Exit(1)
} | [
"func",
"FatalDepth",
"(",
"depth",
"int",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"defaultLogger",
".",
"output",
"(",
"sFatal",
",",
"depth",
",",
"fmt",
".",
"Sprint",
"(",
"v",
"...",
")",
")",
"\n",
"defaultLogger",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | // FatalDepth acts as Fatal but uses depth to determine which call frame to log.
// FatalDepth(0, "msg") is the same as Fatal("msg"). | [
"FatalDepth",
"acts",
"as",
"Fatal",
"but",
"uses",
"depth",
"to",
"determine",
"which",
"call",
"frame",
"to",
"log",
".",
"FatalDepth",
"(",
"0",
"msg",
")",
"is",
"the",
"same",
"as",
"Fatal",
"(",
"msg",
")",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L365-L369 |
google/logger | logger.go | Fatalln | func Fatalln(v ...interface{}) {
defaultLogger.output(sFatal, 0, fmt.Sprintln(v...))
defaultLogger.Close()
os.Exit(1)
} | go | func Fatalln(v ...interface{}) {
defaultLogger.output(sFatal, 0, fmt.Sprintln(v...))
defaultLogger.Close()
os.Exit(1)
} | [
"func",
"Fatalln",
"(",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"defaultLogger",
".",
"output",
"(",
"sFatal",
",",
"0",
",",
"fmt",
".",
"Sprintln",
"(",
"v",
"...",
")",
")",
"\n",
"defaultLogger",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | // Fatalln uses the default logger, logs with the Fatal severity,
// and ends with os.Exit(1).
// Arguments are handled in the manner of fmt.Println. | [
"Fatalln",
"uses",
"the",
"default",
"logger",
"logs",
"with",
"the",
"Fatal",
"severity",
"and",
"ends",
"with",
"os",
".",
"Exit",
"(",
"1",
")",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Println",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L374-L378 |
google/logger | logger.go | Fatalf | func Fatalf(format string, v ...interface{}) {
defaultLogger.output(sFatal, 0, fmt.Sprintf(format, v...))
defaultLogger.Close()
os.Exit(1)
} | go | func Fatalf(format string, v ...interface{}) {
defaultLogger.output(sFatal, 0, fmt.Sprintf(format, v...))
defaultLogger.Close()
os.Exit(1)
} | [
"func",
"Fatalf",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"defaultLogger",
".",
"output",
"(",
"sFatal",
",",
"0",
",",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"v",
"...",
")",
")",
"\n",
"defaultLogger",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | // Fatalf uses the default logger, logs with the Fatal severity,
// and ends with os.Exit(1).
// Arguments are handled in the manner of fmt.Printf. | [
"Fatalf",
"uses",
"the",
"default",
"logger",
"logs",
"with",
"the",
"Fatal",
"severity",
"and",
"ends",
"with",
"os",
".",
"Exit",
"(",
"1",
")",
".",
"Arguments",
"are",
"handled",
"in",
"the",
"manner",
"of",
"fmt",
".",
"Printf",
"."
] | train | https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L383-L387 |
jinzhu/copier | copier.go | Copy | func Copy(toValue interface{}, fromValue interface{}) (err error) {
var (
isSlice bool
amount = 1
from = indirect(reflect.ValueOf(fromValue))
to = indirect(reflect.ValueOf(toValue))
)
if !to.CanAddr() {
return errors.New("copy to value is unaddressable")
}
// Return is from value is invalid
if !from.IsValid() {
return
}
// Just set it if possible to assign
if from.Type().AssignableTo(to.Type()) {
to.Set(from)
return
}
fromType := indirectType(from.Type())
toType := indirectType(to.Type())
if fromType.Kind() != reflect.Struct || toType.Kind() != reflect.Struct {
return
}
if to.Kind() == reflect.Slice {
isSlice = true
if from.Kind() == reflect.Slice {
amount = from.Len()
}
}
for i := 0; i < amount; i++ {
var dest, source reflect.Value
if isSlice {
// source
if from.Kind() == reflect.Slice {
source = indirect(from.Index(i))
} else {
source = indirect(from)
}
// dest
dest = indirect(reflect.New(toType).Elem())
} else {
source = indirect(from)
dest = indirect(to)
}
// Copy from field to field or method
for _, field := range deepFields(fromType) {
name := field.Name
if fromField := source.FieldByName(name); fromField.IsValid() {
// has field
if toField := dest.FieldByName(name); toField.IsValid() {
if toField.CanSet() {
if !set(toField, fromField) {
if err := Copy(toField.Addr().Interface(), fromField.Interface()); err != nil {
return err
}
}
}
} else {
// try to set to method
var toMethod reflect.Value
if dest.CanAddr() {
toMethod = dest.Addr().MethodByName(name)
} else {
toMethod = dest.MethodByName(name)
}
if toMethod.IsValid() && toMethod.Type().NumIn() == 1 && fromField.Type().AssignableTo(toMethod.Type().In(0)) {
toMethod.Call([]reflect.Value{fromField})
}
}
}
}
// Copy from method to field
for _, field := range deepFields(toType) {
name := field.Name
var fromMethod reflect.Value
if source.CanAddr() {
fromMethod = source.Addr().MethodByName(name)
} else {
fromMethod = source.MethodByName(name)
}
if fromMethod.IsValid() && fromMethod.Type().NumIn() == 0 && fromMethod.Type().NumOut() == 1 {
if toField := dest.FieldByName(name); toField.IsValid() && toField.CanSet() {
values := fromMethod.Call([]reflect.Value{})
if len(values) >= 1 {
set(toField, values[0])
}
}
}
}
if isSlice {
if dest.Addr().Type().AssignableTo(to.Type().Elem()) {
to.Set(reflect.Append(to, dest.Addr()))
} else if dest.Type().AssignableTo(to.Type().Elem()) {
to.Set(reflect.Append(to, dest))
}
}
}
return
} | go | func Copy(toValue interface{}, fromValue interface{}) (err error) {
var (
isSlice bool
amount = 1
from = indirect(reflect.ValueOf(fromValue))
to = indirect(reflect.ValueOf(toValue))
)
if !to.CanAddr() {
return errors.New("copy to value is unaddressable")
}
// Return is from value is invalid
if !from.IsValid() {
return
}
// Just set it if possible to assign
if from.Type().AssignableTo(to.Type()) {
to.Set(from)
return
}
fromType := indirectType(from.Type())
toType := indirectType(to.Type())
if fromType.Kind() != reflect.Struct || toType.Kind() != reflect.Struct {
return
}
if to.Kind() == reflect.Slice {
isSlice = true
if from.Kind() == reflect.Slice {
amount = from.Len()
}
}
for i := 0; i < amount; i++ {
var dest, source reflect.Value
if isSlice {
// source
if from.Kind() == reflect.Slice {
source = indirect(from.Index(i))
} else {
source = indirect(from)
}
// dest
dest = indirect(reflect.New(toType).Elem())
} else {
source = indirect(from)
dest = indirect(to)
}
// Copy from field to field or method
for _, field := range deepFields(fromType) {
name := field.Name
if fromField := source.FieldByName(name); fromField.IsValid() {
// has field
if toField := dest.FieldByName(name); toField.IsValid() {
if toField.CanSet() {
if !set(toField, fromField) {
if err := Copy(toField.Addr().Interface(), fromField.Interface()); err != nil {
return err
}
}
}
} else {
// try to set to method
var toMethod reflect.Value
if dest.CanAddr() {
toMethod = dest.Addr().MethodByName(name)
} else {
toMethod = dest.MethodByName(name)
}
if toMethod.IsValid() && toMethod.Type().NumIn() == 1 && fromField.Type().AssignableTo(toMethod.Type().In(0)) {
toMethod.Call([]reflect.Value{fromField})
}
}
}
}
// Copy from method to field
for _, field := range deepFields(toType) {
name := field.Name
var fromMethod reflect.Value
if source.CanAddr() {
fromMethod = source.Addr().MethodByName(name)
} else {
fromMethod = source.MethodByName(name)
}
if fromMethod.IsValid() && fromMethod.Type().NumIn() == 0 && fromMethod.Type().NumOut() == 1 {
if toField := dest.FieldByName(name); toField.IsValid() && toField.CanSet() {
values := fromMethod.Call([]reflect.Value{})
if len(values) >= 1 {
set(toField, values[0])
}
}
}
}
if isSlice {
if dest.Addr().Type().AssignableTo(to.Type().Elem()) {
to.Set(reflect.Append(to, dest.Addr()))
} else if dest.Type().AssignableTo(to.Type().Elem()) {
to.Set(reflect.Append(to, dest))
}
}
}
return
} | [
"func",
"Copy",
"(",
"toValue",
"interface",
"{",
"}",
",",
"fromValue",
"interface",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"var",
"(",
"isSlice",
"bool",
"\n",
"amount",
"=",
"1",
"\n",
"from",
"=",
"indirect",
"(",
"reflect",
".",
"ValueOf",
"(",
"fromValue",
")",
")",
"\n",
"to",
"=",
"indirect",
"(",
"reflect",
".",
"ValueOf",
"(",
"toValue",
")",
")",
"\n",
")",
"\n\n",
"if",
"!",
"to",
".",
"CanAddr",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Return is from value is invalid",
"if",
"!",
"from",
".",
"IsValid",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// Just set it if possible to assign",
"if",
"from",
".",
"Type",
"(",
")",
".",
"AssignableTo",
"(",
"to",
".",
"Type",
"(",
")",
")",
"{",
"to",
".",
"Set",
"(",
"from",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"fromType",
":=",
"indirectType",
"(",
"from",
".",
"Type",
"(",
")",
")",
"\n",
"toType",
":=",
"indirectType",
"(",
"to",
".",
"Type",
"(",
")",
")",
"\n\n",
"if",
"fromType",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Struct",
"||",
"toType",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Struct",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"to",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Slice",
"{",
"isSlice",
"=",
"true",
"\n",
"if",
"from",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Slice",
"{",
"amount",
"=",
"from",
".",
"Len",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"amount",
";",
"i",
"++",
"{",
"var",
"dest",
",",
"source",
"reflect",
".",
"Value",
"\n\n",
"if",
"isSlice",
"{",
"// source",
"if",
"from",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Slice",
"{",
"source",
"=",
"indirect",
"(",
"from",
".",
"Index",
"(",
"i",
")",
")",
"\n",
"}",
"else",
"{",
"source",
"=",
"indirect",
"(",
"from",
")",
"\n",
"}",
"\n\n",
"// dest",
"dest",
"=",
"indirect",
"(",
"reflect",
".",
"New",
"(",
"toType",
")",
".",
"Elem",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"source",
"=",
"indirect",
"(",
"from",
")",
"\n",
"dest",
"=",
"indirect",
"(",
"to",
")",
"\n",
"}",
"\n\n",
"// Copy from field to field or method",
"for",
"_",
",",
"field",
":=",
"range",
"deepFields",
"(",
"fromType",
")",
"{",
"name",
":=",
"field",
".",
"Name",
"\n\n",
"if",
"fromField",
":=",
"source",
".",
"FieldByName",
"(",
"name",
")",
";",
"fromField",
".",
"IsValid",
"(",
")",
"{",
"// has field",
"if",
"toField",
":=",
"dest",
".",
"FieldByName",
"(",
"name",
")",
";",
"toField",
".",
"IsValid",
"(",
")",
"{",
"if",
"toField",
".",
"CanSet",
"(",
")",
"{",
"if",
"!",
"set",
"(",
"toField",
",",
"fromField",
")",
"{",
"if",
"err",
":=",
"Copy",
"(",
"toField",
".",
"Addr",
"(",
")",
".",
"Interface",
"(",
")",
",",
"fromField",
".",
"Interface",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// try to set to method",
"var",
"toMethod",
"reflect",
".",
"Value",
"\n",
"if",
"dest",
".",
"CanAddr",
"(",
")",
"{",
"toMethod",
"=",
"dest",
".",
"Addr",
"(",
")",
".",
"MethodByName",
"(",
"name",
")",
"\n",
"}",
"else",
"{",
"toMethod",
"=",
"dest",
".",
"MethodByName",
"(",
"name",
")",
"\n",
"}",
"\n\n",
"if",
"toMethod",
".",
"IsValid",
"(",
")",
"&&",
"toMethod",
".",
"Type",
"(",
")",
".",
"NumIn",
"(",
")",
"==",
"1",
"&&",
"fromField",
".",
"Type",
"(",
")",
".",
"AssignableTo",
"(",
"toMethod",
".",
"Type",
"(",
")",
".",
"In",
"(",
"0",
")",
")",
"{",
"toMethod",
".",
"Call",
"(",
"[",
"]",
"reflect",
".",
"Value",
"{",
"fromField",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Copy from method to field",
"for",
"_",
",",
"field",
":=",
"range",
"deepFields",
"(",
"toType",
")",
"{",
"name",
":=",
"field",
".",
"Name",
"\n\n",
"var",
"fromMethod",
"reflect",
".",
"Value",
"\n",
"if",
"source",
".",
"CanAddr",
"(",
")",
"{",
"fromMethod",
"=",
"source",
".",
"Addr",
"(",
")",
".",
"MethodByName",
"(",
"name",
")",
"\n",
"}",
"else",
"{",
"fromMethod",
"=",
"source",
".",
"MethodByName",
"(",
"name",
")",
"\n",
"}",
"\n\n",
"if",
"fromMethod",
".",
"IsValid",
"(",
")",
"&&",
"fromMethod",
".",
"Type",
"(",
")",
".",
"NumIn",
"(",
")",
"==",
"0",
"&&",
"fromMethod",
".",
"Type",
"(",
")",
".",
"NumOut",
"(",
")",
"==",
"1",
"{",
"if",
"toField",
":=",
"dest",
".",
"FieldByName",
"(",
"name",
")",
";",
"toField",
".",
"IsValid",
"(",
")",
"&&",
"toField",
".",
"CanSet",
"(",
")",
"{",
"values",
":=",
"fromMethod",
".",
"Call",
"(",
"[",
"]",
"reflect",
".",
"Value",
"{",
"}",
")",
"\n",
"if",
"len",
"(",
"values",
")",
">=",
"1",
"{",
"set",
"(",
"toField",
",",
"values",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"isSlice",
"{",
"if",
"dest",
".",
"Addr",
"(",
")",
".",
"Type",
"(",
")",
".",
"AssignableTo",
"(",
"to",
".",
"Type",
"(",
")",
".",
"Elem",
"(",
")",
")",
"{",
"to",
".",
"Set",
"(",
"reflect",
".",
"Append",
"(",
"to",
",",
"dest",
".",
"Addr",
"(",
")",
")",
")",
"\n",
"}",
"else",
"if",
"dest",
".",
"Type",
"(",
")",
".",
"AssignableTo",
"(",
"to",
".",
"Type",
"(",
")",
".",
"Elem",
"(",
")",
")",
"{",
"to",
".",
"Set",
"(",
"reflect",
".",
"Append",
"(",
"to",
",",
"dest",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Copy copy things | [
"Copy",
"copy",
"things"
] | train | https://github.com/jinzhu/copier/blob/7e38e58719c33e0d44d585c4ab477a30f8cb82dd/copier.go#L10-L125 |
joho/godotenv | godotenv.go | Load | func Load(filenames ...string) (err error) {
filenames = filenamesOrDefault(filenames)
for _, filename := range filenames {
err = loadFile(filename, false)
if err != nil {
return // return early on a spazout
}
}
return
} | go | func Load(filenames ...string) (err error) {
filenames = filenamesOrDefault(filenames)
for _, filename := range filenames {
err = loadFile(filename, false)
if err != nil {
return // return early on a spazout
}
}
return
} | [
"func",
"Load",
"(",
"filenames",
"...",
"string",
")",
"(",
"err",
"error",
")",
"{",
"filenames",
"=",
"filenamesOrDefault",
"(",
"filenames",
")",
"\n\n",
"for",
"_",
",",
"filename",
":=",
"range",
"filenames",
"{",
"err",
"=",
"loadFile",
"(",
"filename",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"// return early on a spazout",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Load will read your env file(s) and load them into ENV for this process.
//
// Call this function as close as possible to the start of your program (ideally in main)
//
// If you call Load without any args it will default to loading .env in the current path
//
// You can otherwise tell it which files to load (there can be more than one) like
//
// godotenv.Load("fileone", "filetwo")
//
// It's important to note that it WILL NOT OVERRIDE an env variable that already exists - consider the .env file to set dev vars or sensible defaults | [
"Load",
"will",
"read",
"your",
"env",
"file",
"(",
"s",
")",
"and",
"load",
"them",
"into",
"ENV",
"for",
"this",
"process",
".",
"Call",
"this",
"function",
"as",
"close",
"as",
"possible",
"to",
"the",
"start",
"of",
"your",
"program",
"(",
"ideally",
"in",
"main",
")",
"If",
"you",
"call",
"Load",
"without",
"any",
"args",
"it",
"will",
"default",
"to",
"loading",
".",
"env",
"in",
"the",
"current",
"path",
"You",
"can",
"otherwise",
"tell",
"it",
"which",
"files",
"to",
"load",
"(",
"there",
"can",
"be",
"more",
"than",
"one",
")",
"like",
"godotenv",
".",
"Load",
"(",
"fileone",
"filetwo",
")",
"It",
"s",
"important",
"to",
"note",
"that",
"it",
"WILL",
"NOT",
"OVERRIDE",
"an",
"env",
"variable",
"that",
"already",
"exists",
"-",
"consider",
"the",
".",
"env",
"file",
"to",
"set",
"dev",
"vars",
"or",
"sensible",
"defaults"
] | train | https://github.com/joho/godotenv/blob/5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941/godotenv.go#L41-L51 |
joho/godotenv | godotenv.go | Overload | func Overload(filenames ...string) (err error) {
filenames = filenamesOrDefault(filenames)
for _, filename := range filenames {
err = loadFile(filename, true)
if err != nil {
return // return early on a spazout
}
}
return
} | go | func Overload(filenames ...string) (err error) {
filenames = filenamesOrDefault(filenames)
for _, filename := range filenames {
err = loadFile(filename, true)
if err != nil {
return // return early on a spazout
}
}
return
} | [
"func",
"Overload",
"(",
"filenames",
"...",
"string",
")",
"(",
"err",
"error",
")",
"{",
"filenames",
"=",
"filenamesOrDefault",
"(",
"filenames",
")",
"\n\n",
"for",
"_",
",",
"filename",
":=",
"range",
"filenames",
"{",
"err",
"=",
"loadFile",
"(",
"filename",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"// return early on a spazout",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Overload will read your env file(s) and load them into ENV for this process.
//
// Call this function as close as possible to the start of your program (ideally in main)
//
// If you call Overload without any args it will default to loading .env in the current path
//
// You can otherwise tell it which files to load (there can be more than one) like
//
// godotenv.Overload("fileone", "filetwo")
//
// It's important to note this WILL OVERRIDE an env variable that already exists - consider the .env file to forcefilly set all vars. | [
"Overload",
"will",
"read",
"your",
"env",
"file",
"(",
"s",
")",
"and",
"load",
"them",
"into",
"ENV",
"for",
"this",
"process",
".",
"Call",
"this",
"function",
"as",
"close",
"as",
"possible",
"to",
"the",
"start",
"of",
"your",
"program",
"(",
"ideally",
"in",
"main",
")",
"If",
"you",
"call",
"Overload",
"without",
"any",
"args",
"it",
"will",
"default",
"to",
"loading",
".",
"env",
"in",
"the",
"current",
"path",
"You",
"can",
"otherwise",
"tell",
"it",
"which",
"files",
"to",
"load",
"(",
"there",
"can",
"be",
"more",
"than",
"one",
")",
"like",
"godotenv",
".",
"Overload",
"(",
"fileone",
"filetwo",
")",
"It",
"s",
"important",
"to",
"note",
"this",
"WILL",
"OVERRIDE",
"an",
"env",
"variable",
"that",
"already",
"exists",
"-",
"consider",
"the",
".",
"env",
"file",
"to",
"forcefilly",
"set",
"all",
"vars",
"."
] | train | https://github.com/joho/godotenv/blob/5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941/godotenv.go#L64-L74 |
joho/godotenv | godotenv.go | Read | func Read(filenames ...string) (envMap map[string]string, err error) {
filenames = filenamesOrDefault(filenames)
envMap = make(map[string]string)
for _, filename := range filenames {
individualEnvMap, individualErr := readFile(filename)
if individualErr != nil {
err = individualErr
return // return early on a spazout
}
for key, value := range individualEnvMap {
envMap[key] = value
}
}
return
} | go | func Read(filenames ...string) (envMap map[string]string, err error) {
filenames = filenamesOrDefault(filenames)
envMap = make(map[string]string)
for _, filename := range filenames {
individualEnvMap, individualErr := readFile(filename)
if individualErr != nil {
err = individualErr
return // return early on a spazout
}
for key, value := range individualEnvMap {
envMap[key] = value
}
}
return
} | [
"func",
"Read",
"(",
"filenames",
"...",
"string",
")",
"(",
"envMap",
"map",
"[",
"string",
"]",
"string",
",",
"err",
"error",
")",
"{",
"filenames",
"=",
"filenamesOrDefault",
"(",
"filenames",
")",
"\n",
"envMap",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n\n",
"for",
"_",
",",
"filename",
":=",
"range",
"filenames",
"{",
"individualEnvMap",
",",
"individualErr",
":=",
"readFile",
"(",
"filename",
")",
"\n\n",
"if",
"individualErr",
"!=",
"nil",
"{",
"err",
"=",
"individualErr",
"\n",
"return",
"// return early on a spazout",
"\n",
"}",
"\n\n",
"for",
"key",
",",
"value",
":=",
"range",
"individualEnvMap",
"{",
"envMap",
"[",
"key",
"]",
"=",
"value",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Read all env (with same file loading semantics as Load) but return values as
// a map rather than automatically writing values into env | [
"Read",
"all",
"env",
"(",
"with",
"same",
"file",
"loading",
"semantics",
"as",
"Load",
")",
"but",
"return",
"values",
"as",
"a",
"map",
"rather",
"than",
"automatically",
"writing",
"values",
"into",
"env"
] | train | https://github.com/joho/godotenv/blob/5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941/godotenv.go#L78-L96 |
joho/godotenv | godotenv.go | Parse | func Parse(r io.Reader) (envMap map[string]string, err error) {
envMap = make(map[string]string)
var lines []string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err = scanner.Err(); err != nil {
return
}
for _, fullLine := range lines {
if !isIgnoredLine(fullLine) {
var key, value string
key, value, err = parseLine(fullLine, envMap)
if err != nil {
return
}
envMap[key] = value
}
}
return
} | go | func Parse(r io.Reader) (envMap map[string]string, err error) {
envMap = make(map[string]string)
var lines []string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if err = scanner.Err(); err != nil {
return
}
for _, fullLine := range lines {
if !isIgnoredLine(fullLine) {
var key, value string
key, value, err = parseLine(fullLine, envMap)
if err != nil {
return
}
envMap[key] = value
}
}
return
} | [
"func",
"Parse",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"envMap",
"map",
"[",
"string",
"]",
"string",
",",
"err",
"error",
")",
"{",
"envMap",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n\n",
"var",
"lines",
"[",
"]",
"string",
"\n",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"r",
")",
"\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"{",
"lines",
"=",
"append",
"(",
"lines",
",",
"scanner",
".",
"Text",
"(",
")",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"=",
"scanner",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"fullLine",
":=",
"range",
"lines",
"{",
"if",
"!",
"isIgnoredLine",
"(",
"fullLine",
")",
"{",
"var",
"key",
",",
"value",
"string",
"\n",
"key",
",",
"value",
",",
"err",
"=",
"parseLine",
"(",
"fullLine",
",",
"envMap",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"envMap",
"[",
"key",
"]",
"=",
"value",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Parse reads an env file from io.Reader, returning a map of keys and values. | [
"Parse",
"reads",
"an",
"env",
"file",
"from",
"io",
".",
"Reader",
"returning",
"a",
"map",
"of",
"keys",
"and",
"values",
"."
] | train | https://github.com/joho/godotenv/blob/5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941/godotenv.go#L99-L124 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.