repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
HouzuoGuo/tiedot
db/query.go
EvalUnion
func EvalUnion(exprs []interface{}, src *Col, result *map[int]struct{}) (err error) { for _, subExpr := range exprs { if err = evalQuery(subExpr, src, result, false); err != nil { return } } return }
go
func EvalUnion(exprs []interface{}, src *Col, result *map[int]struct{}) (err error) { for _, subExpr := range exprs { if err = evalQuery(subExpr, src, result, false); err != nil { return } } return }
[ "func", "EvalUnion", "(", "exprs", "[", "]", "interface", "{", "}", ",", "src", "*", "Col", ",", "result", "*", "map", "[", "int", "]", "struct", "{", "}", ")", "(", "err", "error", ")", "{", "for", "_", ",", "subExpr", ":=", "range", "exprs", ...
// Calculate union of sub-query results.
[ "Calculate", "union", "of", "sub", "-", "query", "results", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/query.go#L16-L23
train
HouzuoGuo/tiedot
db/query.go
EvalAllIDs
func EvalAllIDs(src *Col, result *map[int]struct{}) (err error) { src.forEachDoc(func(id int, _ []byte) bool { (*result)[id] = struct{}{} return true }, false) return }
go
func EvalAllIDs(src *Col, result *map[int]struct{}) (err error) { src.forEachDoc(func(id int, _ []byte) bool { (*result)[id] = struct{}{} return true }, false) return }
[ "func", "EvalAllIDs", "(", "src", "*", "Col", ",", "result", "*", "map", "[", "int", "]", "struct", "{", "}", ")", "(", "err", "error", ")", "{", "src", ".", "forEachDoc", "(", "func", "(", "id", "int", ",", "_", "[", "]", "byte", ")", "bool", ...
// Put all document IDs into result.
[ "Put", "all", "document", "IDs", "into", "result", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/query.go#L26-L32
train
HouzuoGuo/tiedot
db/query.go
Intersect
func Intersect(subExprs interface{}, src *Col, result *map[int]struct{}) (err error) { myResult := make(map[int]struct{}) if subExprVecs, ok := subExprs.([]interface{}); ok { first := true for _, subExpr := range subExprVecs { subResult := make(map[int]struct{}) intersection := make(map[int]struct{}) if err = evalQuery(subExpr, src, &subResult, false); err != nil { return } if first { myResult = subResult first = false } else { for k := range subResult { if _, inBoth := myResult[k]; inBoth { intersection[k] = struct{}{} } } myResult = intersection } } for docID := range myResult { (*result)[docID] = struct{}{} } } else { return dberr.New(dberr.ErrorExpectingSubQuery, subExprs) } return }
go
func Intersect(subExprs interface{}, src *Col, result *map[int]struct{}) (err error) { myResult := make(map[int]struct{}) if subExprVecs, ok := subExprs.([]interface{}); ok { first := true for _, subExpr := range subExprVecs { subResult := make(map[int]struct{}) intersection := make(map[int]struct{}) if err = evalQuery(subExpr, src, &subResult, false); err != nil { return } if first { myResult = subResult first = false } else { for k := range subResult { if _, inBoth := myResult[k]; inBoth { intersection[k] = struct{}{} } } myResult = intersection } } for docID := range myResult { (*result)[docID] = struct{}{} } } else { return dberr.New(dberr.ErrorExpectingSubQuery, subExprs) } return }
[ "func", "Intersect", "(", "subExprs", "interface", "{", "}", ",", "src", "*", "Col", ",", "result", "*", "map", "[", "int", "]", "struct", "{", "}", ")", "(", "err", "error", ")", "{", "myResult", ":=", "make", "(", "map", "[", "int", "]", "struc...
// Calculate intersection of sub-query results.
[ "Calculate", "intersection", "of", "sub", "-", "query", "results", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/query.go#L135-L164
train
HouzuoGuo/tiedot
db/query.go
Complement
func Complement(subExprs interface{}, src *Col, result *map[int]struct{}) (err error) { myResult := make(map[int]struct{}) if subExprVecs, ok := subExprs.([]interface{}); ok { for _, subExpr := range subExprVecs { subResult := make(map[int]struct{}) complement := make(map[int]struct{}) if err = evalQuery(subExpr, src, &subResult, false); err != nil { return } for k := range subResult { if _, inBoth := myResult[k]; !inBoth { complement[k] = struct{}{} } } for k := range myResult { if _, inBoth := subResult[k]; !inBoth { complement[k] = struct{}{} } } myResult = complement } for docID := range myResult { (*result)[docID] = struct{}{} } } else { return dberr.New(dberr.ErrorExpectingSubQuery, subExprs) } return }
go
func Complement(subExprs interface{}, src *Col, result *map[int]struct{}) (err error) { myResult := make(map[int]struct{}) if subExprVecs, ok := subExprs.([]interface{}); ok { for _, subExpr := range subExprVecs { subResult := make(map[int]struct{}) complement := make(map[int]struct{}) if err = evalQuery(subExpr, src, &subResult, false); err != nil { return } for k := range subResult { if _, inBoth := myResult[k]; !inBoth { complement[k] = struct{}{} } } for k := range myResult { if _, inBoth := subResult[k]; !inBoth { complement[k] = struct{}{} } } myResult = complement } for docID := range myResult { (*result)[docID] = struct{}{} } } else { return dberr.New(dberr.ErrorExpectingSubQuery, subExprs) } return }
[ "func", "Complement", "(", "subExprs", "interface", "{", "}", ",", "src", "*", "Col", ",", "result", "*", "map", "[", "int", "]", "struct", "{", "}", ")", "(", "err", "error", ")", "{", "myResult", ":=", "make", "(", "map", "[", "int", "]", "stru...
// Calculate complement of sub-query results.
[ "Calculate", "complement", "of", "sub", "-", "query", "results", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/query.go#L167-L195
train
HouzuoGuo/tiedot
data/file.go
LooksEmpty
func LooksEmpty(buf gommap.MMap) bool { upTo := 1024 if upTo >= len(buf) { upTo = len(buf) - 1 } for i := 0; i < upTo; i++ { if buf[i] != 0 { return false } } return true }
go
func LooksEmpty(buf gommap.MMap) bool { upTo := 1024 if upTo >= len(buf) { upTo = len(buf) - 1 } for i := 0; i < upTo; i++ { if buf[i] != 0 { return false } } return true }
[ "func", "LooksEmpty", "(", "buf", "gommap", ".", "MMap", ")", "bool", "{", "upTo", ":=", "1024", "\n", "if", "upTo", ">=", "len", "(", "buf", ")", "{", "upTo", "=", "len", "(", "buf", ")", "-", "1", "\n", "}", "\n", "for", "i", ":=", "0", ";"...
// Return true if the buffer begins with 64 consecutive zero bytes.
[ "Return", "true", "if", "the", "buffer", "begins", "with", "64", "consecutive", "zero", "bytes", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/file.go#L21-L32
train
HouzuoGuo/tiedot
data/file.go
OpenDataFile
func OpenDataFile(path string, growth int) (file *DataFile, err error) { file = &DataFile{Path: path, Growth: growth} if file.Fh, err = os.OpenFile(file.Path, os.O_CREATE|os.O_RDWR, 0600); err != nil { return } var size int64 if size, err = file.Fh.Seek(0, os.SEEK_END); err != nil { return } // Ensure the file is not smaller than file growth if file.Size = int(size); file.Size < file.Growth { if err = file.EnsureSize(file.Growth); err != nil { return } } if file.Buf == nil { file.Buf, err = gommap.Map(file.Fh) } defer tdlog.Infof("%s opened: %d of %d bytes in-use", file.Path, file.Used, file.Size) // Bi-sect file buffer to find out how much space is in-use for low, mid, high := 0, file.Size/2, file.Size; ; { switch { case high-mid == 1: if LooksEmpty(file.Buf[mid:]) { if mid > 0 && LooksEmpty(file.Buf[mid-1:]) { file.Used = mid - 1 } else { file.Used = mid } return } file.Used = high return case LooksEmpty(file.Buf[mid:]): high = mid mid = low + (mid-low)/2 default: low = mid mid = mid + (high-mid)/2 } } return }
go
func OpenDataFile(path string, growth int) (file *DataFile, err error) { file = &DataFile{Path: path, Growth: growth} if file.Fh, err = os.OpenFile(file.Path, os.O_CREATE|os.O_RDWR, 0600); err != nil { return } var size int64 if size, err = file.Fh.Seek(0, os.SEEK_END); err != nil { return } // Ensure the file is not smaller than file growth if file.Size = int(size); file.Size < file.Growth { if err = file.EnsureSize(file.Growth); err != nil { return } } if file.Buf == nil { file.Buf, err = gommap.Map(file.Fh) } defer tdlog.Infof("%s opened: %d of %d bytes in-use", file.Path, file.Used, file.Size) // Bi-sect file buffer to find out how much space is in-use for low, mid, high := 0, file.Size/2, file.Size; ; { switch { case high-mid == 1: if LooksEmpty(file.Buf[mid:]) { if mid > 0 && LooksEmpty(file.Buf[mid-1:]) { file.Used = mid - 1 } else { file.Used = mid } return } file.Used = high return case LooksEmpty(file.Buf[mid:]): high = mid mid = low + (mid-low)/2 default: low = mid mid = mid + (high-mid)/2 } } return }
[ "func", "OpenDataFile", "(", "path", "string", ",", "growth", "int", ")", "(", "file", "*", "DataFile", ",", "err", "error", ")", "{", "file", "=", "&", "DataFile", "{", "Path", ":", "path", ",", "Growth", ":", "growth", "}", "\n", "if", "file", "....
// Open a data file that grows by the specified size.
[ "Open", "a", "data", "file", "that", "grows", "by", "the", "specified", "size", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/file.go#L35-L77
train
HouzuoGuo/tiedot
data/file.go
overwriteWithZero
func (file *DataFile) overwriteWithZero(from int, size int) (err error) { if _, err = file.Fh.Seek(int64(from), os.SEEK_SET); err != nil { return } zeroSize := 1048576 * 8 // Fill 8 MB at a time zero := make([]byte, zeroSize) for i := 0; i < size; i += zeroSize { var zeroSlice []byte if i+zeroSize > size { zeroSlice = zero[0 : size-i] } else { zeroSlice = zero } if _, err = file.Fh.Write(zeroSlice); err != nil { return } } return file.Fh.Sync() }
go
func (file *DataFile) overwriteWithZero(from int, size int) (err error) { if _, err = file.Fh.Seek(int64(from), os.SEEK_SET); err != nil { return } zeroSize := 1048576 * 8 // Fill 8 MB at a time zero := make([]byte, zeroSize) for i := 0; i < size; i += zeroSize { var zeroSlice []byte if i+zeroSize > size { zeroSlice = zero[0 : size-i] } else { zeroSlice = zero } if _, err = file.Fh.Write(zeroSlice); err != nil { return } } return file.Fh.Sync() }
[ "func", "(", "file", "*", "DataFile", ")", "overwriteWithZero", "(", "from", "int", ",", "size", "int", ")", "(", "err", "error", ")", "{", "if", "_", ",", "err", "=", "file", ".", "Fh", ".", "Seek", "(", "int64", "(", "from", ")", ",", "os", "...
// Fill up portion of a file with 0s.
[ "Fill", "up", "portion", "of", "a", "file", "with", "0s", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/file.go#L80-L98
train
HouzuoGuo/tiedot
data/file.go
EnsureSize
func (file *DataFile) EnsureSize(more int) (err error) { if file.Used+more <= file.Size { return } else if file.Buf != nil { if err = file.Buf.Unmap(); err != nil { return } } if err = file.overwriteWithZero(file.Size, file.Growth); err != nil { return } else if file.Buf, err = gommap.Map(file.Fh); err != nil { return } file.Size += file.Growth tdlog.Infof("%s grown: %d -> %d bytes (%d bytes in-use)", file.Path, file.Size-file.Growth, file.Size, file.Used) return file.EnsureSize(more) }
go
func (file *DataFile) EnsureSize(more int) (err error) { if file.Used+more <= file.Size { return } else if file.Buf != nil { if err = file.Buf.Unmap(); err != nil { return } } if err = file.overwriteWithZero(file.Size, file.Growth); err != nil { return } else if file.Buf, err = gommap.Map(file.Fh); err != nil { return } file.Size += file.Growth tdlog.Infof("%s grown: %d -> %d bytes (%d bytes in-use)", file.Path, file.Size-file.Growth, file.Size, file.Used) return file.EnsureSize(more) }
[ "func", "(", "file", "*", "DataFile", ")", "EnsureSize", "(", "more", "int", ")", "(", "err", "error", ")", "{", "if", "file", ".", "Used", "+", "more", "<=", "file", ".", "Size", "{", "return", "\n", "}", "else", "if", "file", ".", "Buf", "!=", ...
// Ensure there is enough room for that many bytes of data.
[ "Ensure", "there", "is", "enough", "room", "for", "that", "many", "bytes", "of", "data", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/file.go#L101-L117
train
HouzuoGuo/tiedot
data/file.go
Close
func (file *DataFile) Close() (err error) { if err = file.Buf.Unmap(); err != nil { return } return file.Fh.Close() }
go
func (file *DataFile) Close() (err error) { if err = file.Buf.Unmap(); err != nil { return } return file.Fh.Close() }
[ "func", "(", "file", "*", "DataFile", ")", "Close", "(", ")", "(", "err", "error", ")", "{", "if", "err", "=", "file", ".", "Buf", ".", "Unmap", "(", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "return", "file", ".", "Fh", "...
// Un-map the file buffer and close the file handle.
[ "Un", "-", "map", "the", "file", "buffer", "and", "close", "the", "file", "handle", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/file.go#L120-L125
train
HouzuoGuo/tiedot
data/file.go
Clear
func (file *DataFile) Clear() (err error) { if err = file.Close(); err != nil { return } else if err = os.Truncate(file.Path, 0); err != nil { return } else if file.Fh, err = os.OpenFile(file.Path, os.O_CREATE|os.O_RDWR, 0600); err != nil { return } else if err = file.overwriteWithZero(0, file.Growth); err != nil { return } else if file.Buf, err = gommap.Map(file.Fh); err != nil { return } file.Used, file.Size = 0, file.Growth tdlog.Infof("%s cleared: %d of %d bytes in-use", file.Path, file.Used, file.Size) return }
go
func (file *DataFile) Clear() (err error) { if err = file.Close(); err != nil { return } else if err = os.Truncate(file.Path, 0); err != nil { return } else if file.Fh, err = os.OpenFile(file.Path, os.O_CREATE|os.O_RDWR, 0600); err != nil { return } else if err = file.overwriteWithZero(0, file.Growth); err != nil { return } else if file.Buf, err = gommap.Map(file.Fh); err != nil { return } file.Used, file.Size = 0, file.Growth tdlog.Infof("%s cleared: %d of %d bytes in-use", file.Path, file.Used, file.Size) return }
[ "func", "(", "file", "*", "DataFile", ")", "Clear", "(", ")", "(", "err", "error", ")", "{", "if", "err", "=", "file", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "else", "if", "err", "=", "os", ".", "Truncate", ...
// Clear the entire file and resize it to initial size.
[ "Clear", "the", "entire", "file", "and", "resize", "it", "to", "initial", "size", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/file.go#L128-L143
train
HouzuoGuo/tiedot
data/collection.go
OpenCollection
func (conf *Config) OpenCollection(path string) (col *Collection, err error) { col = new(Collection) col.DataFile, err = OpenDataFile(path, conf.ColFileGrowth) col.Config = conf col.Config.CalculateConfigConstants() return }
go
func (conf *Config) OpenCollection(path string) (col *Collection, err error) { col = new(Collection) col.DataFile, err = OpenDataFile(path, conf.ColFileGrowth) col.Config = conf col.Config.CalculateConfigConstants() return }
[ "func", "(", "conf", "*", "Config", ")", "OpenCollection", "(", "path", "string", ")", "(", "col", "*", "Collection", ",", "err", "error", ")", "{", "col", "=", "new", "(", "Collection", ")", "\n", "col", ".", "DataFile", ",", "err", "=", "OpenDataFi...
// Open a collection file.
[ "Open", "a", "collection", "file", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/collection.go#L30-L36
train
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", "{",...
// Insert a new document, return the new document ID.
[ "Insert", "a", "new", "document", "return", "the", "new", "document", "ID", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/collection.go#L54-L77
train
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", ".", "D...
// 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", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/collection.go#L80-L113
train
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", ...
// Delete a document by ID.
[ "Delete", "a", "document", "by", "ID", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/collection.go#L116-L127
train
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", ">=",...
// Run the function on every document; stop when the function returns false.
[ "Run", "the", "function", "on", "every", "document", ";", "stop", "when", "the", "function", "returns", "false", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/collection.go#L130-L145
train
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", "(", "\"Cache-Control\"", ",", "\"must-revalidate\"", ")", "\n", "w", ".", "Header", "(", ")", ".", ...
// Put an index on a document path.
[ "Put", "an", "index", "on", "a", "document", "path", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/index.go#L13-L35
train
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", ".", ...
// Open a hash table file.
[ "Open", "a", "hash", "table", "file", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L30-L38
train
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", ":="...
// 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", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L41-L58
train
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", "next...
// Return number of the next chained bucket.
[ "Return", "number", "of", "the", "next", "chained", "bucket", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L61-L76
train
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", "c...
// Return number of the last bucket in chain.
[ "Return", "number", "of", "the", "last", "bucket", "in", "chain", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L79-L87
train
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",...
// Create and chain a new bucket.
[ "Create", "and", "chain", "a", "new", "bucket", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L90-L96
train
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"...
// Clear the entire hash table.
[ "Clear", "the", "entire", "hash", "table", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L99-L105
train
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", "}", ...
// Look up values by key.
[ "Look", "up", "values", "by", "key", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L129-L156
train
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", ".", "Buck...
// 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", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L159-L179
train
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", "=", ...
// 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", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L204-L225
train
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", ",", "partS...
// Return all entries in the chosen partition.
[ "Return", "all", "entries", "in", "the", "chosen", "partition", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/hashtable.go#L228-L239
train
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", "(", "\"Cache-Control\"", ",", "\"must-revalidate\"", ")", "\n", "w", ".", "Header", "(", ")", ".", ...
// Insert a document into collection.
[ "Insert", "a", "document", "into", "collection", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/document.go#L14-L46
train
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", "(", "\"Cache-Control\"", ",", "\"must-revalidate\"", ")", "\n", "w", ".", "Header", "(", ")", ".",...
// 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", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/document.go#L85-L129
train
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", "(", "\"Cache-Control\"", ",", "\"must-revalidate\"", ")", "\n", "w", ".", "Header", "(", ")",...
// Return approximate number of documents in the collection.
[ "Return", "approximate", "number", "of", "documents", "in", "the", "collection", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/document.go#L199-L214
train
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", "(", "\"Cache-Control\"", ",", "\"must-revalidate\"", ")", "\n", "w", ".", "Header", "(", ")", "."...
// Flush and close all data files and shutdown the entire program.
[ "Flush", "and", "close", "all", "data", "files", "and", "shutdown", "the", "entire", "program", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/misc.go#L14-L21
train
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", "(", "\"Cache-Control\"", ",", "\"must-revalidate\"", ")", "\n", "w", ".", "Header", "(", ")", ".", ...
// Copy this database into destination directory.
[ "Copy", "this", "database", "into", "destination", "directory", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/misc.go#L24-L37
train
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", "(", "\"Cache-Control\"", ",", "\"must-revalidate\"", ")", "\n", "w", ".", "Header", "(", ")", "."...
// Return server memory statistics.
[ "Return", "server", "memory", "statistics", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/misc.go#L40-L54
train
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", "(", "\"Cache-Control\"", ",", "\"must-revalidate\"", ")", "\n", "w", ".", "Header", "(", ")", ".",...
// Return server protocol version number.
[ "Return", "server", "protocol", "version", "number", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/misc.go#L57-L63
train
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", ",", "sys...
// Windows mmap always mapes the entire file regardless of the specified length.
[ "Windows", "mmap", "always", "mapes", "the", "entire", "file", "regardless", "of", "the", "specified", "length", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/gommap/mmap_windows.go#L25-L46
train
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", ")", "...
// CalculateConfigConstants assignes internal field values to calculation results derived from other fields.
[ "CalculateConfigConstants", "assignes", "internal", "field", "values", "to", "calculation", "results", "derived", "from", "other", "fields", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/config.go#L36-L42
train
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", "if", "err", "=", "os", ".", "MkdirAll", "(", "p...
// CreateOrReadConfig creates default performance configuration underneath the input database directory.
[ "CreateOrReadConfig", "creates", "default", "performance", "configuration", "underneath", "the", "input", "database", "directory", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/config.go#L45-L98
train
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", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", "\n", "addCommonJwtRespHeaders", "(", "w", ",...
// Verify user identity and hand out a JWT.
[ "Verify", "user", "identity", "and", "hand", "out", "a", "JWT", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/jwt.go#L117-L170
train
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", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", "\n", "addCommonJwtRespHeaders", "(", "w", ...
// Verify user's JWT.
[ "Verify", "user", "s", "JWT", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/jwt.go#L189-L205
train
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", ",...
// Enable JWT authorization check on the HTTP handler function.
[ "Enable", "JWT", "authorization", "check", "on", "the", "HTTP", "handler", "function", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/jwt.go#L208-L240
train
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", "possibleSlic...
// Return true if the string appears in string slice.
[ "Return", "true", "if", "the", "string", "appears", "in", "string", "slice", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/jwt.go#L243-L253
train
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", "(", ")", ")", "\n", "d", ",", "err", ":=", "data", ".", "CreateOrReadConfig", "(", ...
// Open database and load all collections & indexes.
[ "Open", "database", "and", "load", "all", "collections", "&", "indexes", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L38-L47
train
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", "{", "var", "numPartsAssumed", "=", "false", "\n", "numPartsFilePath", ":=", "path", ".", "Join", "(", "db", ".", "path", ",", "PART_NUM_FILE", ")", "\n", "if", "err", ":=", "os", ".", "...
// Load all collection schema.
[ "Load", "all", "collection", "schema", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L50-L90
train
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", ...
// Close all database files. Do not use the DB afterwards!
[ "Close", "all", "database", "files", ".", "Do", "not", "use", "the", "DB", "afterwards!" ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L93-L106
train
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", "(", "\"Collection %s already exists\"", "...
// create creates collection files. The function does not place a schema lock.
[ "create", "creates", "collection", "files", ".", "The", "function", "does", "not", "place", "a", "schema", "lock", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L109-L118
train
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", "(", "nam...
// Create a new collection.
[ "Create", "a", "new", "collection", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L121-L125
train
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", ":=", "d...
// 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", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L139-L146
train
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", ...
// Truncate a collection - delete all documents and clear
[ "Truncate", "a", "collection", "-", "delete", "all", "documents", "and", "clear" ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L168-L186
train
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", "...
// Scrub a collection - fix corrupted documents and de-fragment free space.
[ "Scrub", "a", "collection", "-", "fix", "corrupted", "documents", "and", "de", "-", "fragment", "free", "space", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L189-L238
train
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", "....
// Drop a collection and lose all of its documents and indexes.
[ "Drop", "a", "collection", "and", "lose", "all", "of", "its", "documents", "and", "indexes", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L241-L253
train
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", "[", "...
// 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", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L304-L313
train
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", "[", "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", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/db.go#L316-L320
train
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...
// Read Linux system VM parameters and print performance configuration advice when necessary.
[ "Read", "Linux", "system", "VM", "parameters", "and", "print", "performance", "configuration", "advice", "when", "necessary", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/main.go#L21-L42
train
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", "ite...
// 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", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/benchmark/benchmark.go#L18-L36
train
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", "(...
// Create a temporary database and collection for benchmark use.
[ "Create", "a", "temporary", "database", "and", "collection", "for", "benchmark", "use", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/benchmark/benchmark.go#L39-L49
train
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", "(", "\"Cache-Control\"", ",", "\"must-revalidate\"", ")", "\n", "w", ".", "Header", "(", ")", ".", ...
// Create a collection.
[ "Create", "a", "collection", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/collection.go#L12-L26
train
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", "(", "\"Cache-Control\"", ",", "\"must-revalidate\"", ")", "\n", "w", ".", "Header", "(", ")", ".", ...
// De-fragment collection free space and fix corrupted documents.
[ "De", "-", "fragment", "collection", "free", "space", "and", "fix", "corrupted", "documents", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/collection.go#L80-L95
train
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", ",", "\"Invalid API endpoint\"", ",", "404", ")", "...
// Greet user with a welcome message.
[ "Greet", "user", "with", "a", "welcome", "message", "." ]
be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39
https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/srv.go#L136-L142
train
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", "(",...
// Write sends a log message to the Event Log.
[ "Write", "sends", "a", "log", "message", "to", "the", "Event", "Log", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger_windows.go#L31-L41
train
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", "....
// initialize resets defaultLogger. Which allows tests to reset environment.
[ "initialize", "resets", "defaultLogger", ".", "Which", "allows", "tests", "to", "reset", "environment", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L56-L63
train
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 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",...
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L160-L168
train
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", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L172-L174
train
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", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L184-L186
train
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", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L190-L192
train
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", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L196-L198
train
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", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L208-L210
train
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", "...", ")", ")", "\...
// 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", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L214-L216
train
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", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L220-L222
train
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", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L232-L234
train
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", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L238-L240
train
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", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L302-L304
train
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", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L326-L328
train
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", "." ]
945e2bd9ed8f9313ef1d14b674500421a51e960b
https://github.com/google/logger/blob/945e2bd9ed8f9313ef1d14b674500421a51e960b/logger.go#L350-L352
train
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", "var", "lines", "[", "]", "string"...
// 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", "." ]
5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941
https://github.com/joho/godotenv/blob/5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941/godotenv.go#L99-L124
train
joho/godotenv
godotenv.go
Unmarshal
func Unmarshal(str string) (envMap map[string]string, err error) { return Parse(strings.NewReader(str)) }
go
func Unmarshal(str string) (envMap map[string]string, err error) { return Parse(strings.NewReader(str)) }
[ "func", "Unmarshal", "(", "str", "string", ")", "(", "envMap", "map", "[", "string", "]", "string", ",", "err", "error", ")", "{", "return", "Parse", "(", "strings", ".", "NewReader", "(", "str", ")", ")", "\n", "}" ]
//Unmarshal reads an env file from a string, returning a map of keys and values.
[ "Unmarshal", "reads", "an", "env", "file", "from", "a", "string", "returning", "a", "map", "of", "keys", "and", "values", "." ]
5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941
https://github.com/joho/godotenv/blob/5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941/godotenv.go#L127-L129
train
joho/godotenv
godotenv.go
Write
func Write(envMap map[string]string, filename string) error { content, error := Marshal(envMap) if error != nil { return error } file, error := os.Create(filename) if error != nil { return error } _, err := file.WriteString(content) return err }
go
func Write(envMap map[string]string, filename string) error { content, error := Marshal(envMap) if error != nil { return error } file, error := os.Create(filename) if error != nil { return error } _, err := file.WriteString(content) return err }
[ "func", "Write", "(", "envMap", "map", "[", "string", "]", "string", ",", "filename", "string", ")", "error", "{", "content", ",", "error", ":=", "Marshal", "(", "envMap", ")", "\n", "if", "error", "!=", "nil", "{", "return", "error", "\n", "}", "\n"...
// Write serializes the given environment and writes it to a file
[ "Write", "serializes", "the", "given", "environment", "and", "writes", "it", "to", "a", "file" ]
5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941
https://github.com/joho/godotenv/blob/5c0e6c6ab1a0a9ef0a8822cba3a05d62f7dad941/godotenv.go#L149-L160
train
sourcegraph/go-langserver
buildserver/pinned.go
Find
func (p pinnedPkgs) Find(pkg string) string { if len(p) == 0 { return "" } pkg = pkg + "/" i := sort.Search(len(p), func(i int) bool { return p[i].Pkg > pkg }) if i > 0 && strings.HasPrefix(pkg, p[i-1].Pkg) { return p[i-1].Rev } return "" }
go
func (p pinnedPkgs) Find(pkg string) string { if len(p) == 0 { return "" } pkg = pkg + "/" i := sort.Search(len(p), func(i int) bool { return p[i].Pkg > pkg }) if i > 0 && strings.HasPrefix(pkg, p[i-1].Pkg) { return p[i-1].Rev } return "" }
[ "func", "(", "p", "pinnedPkgs", ")", "Find", "(", "pkg", "string", ")", "string", "{", "if", "len", "(", "p", ")", "==", "0", "{", "return", "\"\"", "\n", "}", "\n", "pkg", "=", "pkg", "+", "\"/\"", "\n", "i", ":=", "sort", ".", "Search", "(", ...
// Find returns the revision a pkg is pinned at, or the empty string.
[ "Find", "returns", "the", "revision", "a", "pkg", "is", "pinned", "at", "or", "the", "empty", "string", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/pinned.go#L24-L34
train
sourcegraph/go-langserver
langserver/cancel.go
WithCancel
func (c *cancel) WithCancel(ctx context.Context, id jsonrpc2.ID) (context.Context, func()) { ctx, cancel := context.WithCancel(ctx) c.mu.Lock() if c.m == nil { c.m = make(map[jsonrpc2.ID]func()) } c.m[id] = cancel c.mu.Unlock() return ctx, func() { c.mu.Lock() delete(c.m, id) c.mu.Unlock() cancel() } }
go
func (c *cancel) WithCancel(ctx context.Context, id jsonrpc2.ID) (context.Context, func()) { ctx, cancel := context.WithCancel(ctx) c.mu.Lock() if c.m == nil { c.m = make(map[jsonrpc2.ID]func()) } c.m[id] = cancel c.mu.Unlock() return ctx, func() { c.mu.Lock() delete(c.m, id) c.mu.Unlock() cancel() } }
[ "func", "(", "c", "*", "cancel", ")", "WithCancel", "(", "ctx", "context", ".", "Context", ",", "id", "jsonrpc2", ".", "ID", ")", "(", "context", ".", "Context", ",", "func", "(", ")", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithCanc...
// WithCancel is like context.WithCancel, except you can also cancel via // calling c.Cancel with the same id.
[ "WithCancel", "is", "like", "context", ".", "WithCancel", "except", "you", "can", "also", "cancel", "via", "calling", "c", ".", "Cancel", "with", "the", "same", "id", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/cancel.go#L18-L32
train
sourcegraph/go-langserver
langserver/cancel.go
Cancel
func (c *cancel) Cancel(id jsonrpc2.ID) { var cancel func() c.mu.Lock() if c.m != nil { cancel = c.m[id] delete(c.m, id) } c.mu.Unlock() if cancel != nil { cancel() } }
go
func (c *cancel) Cancel(id jsonrpc2.ID) { var cancel func() c.mu.Lock() if c.m != nil { cancel = c.m[id] delete(c.m, id) } c.mu.Unlock() if cancel != nil { cancel() } }
[ "func", "(", "c", "*", "cancel", ")", "Cancel", "(", "id", "jsonrpc2", ".", "ID", ")", "{", "var", "cancel", "func", "(", ")", "\n", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "c", ".", "m", "!=", "nil", "{", "cancel", "=", "c", "."...
// Cancel will cancel the request with id. If the request has already been // cancelled or not been tracked before, Cancel is a noop.
[ "Cancel", "will", "cancel", "the", "request", "with", "id", ".", "If", "the", "request", "has", "already", "been", "cancelled", "or", "not", "been", "tracked", "before", "Cancel", "is", "a", "noop", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/cancel.go#L36-L47
train
sourcegraph/go-langserver
buildserver/build_server.go
Close
func (h *BuildHandler) Close() error { var result error for _, closer := range h.closers { err := closer.Close() if err != nil { result = multierror.Append(result, err) } } return result }
go
func (h *BuildHandler) Close() error { var result error for _, closer := range h.closers { err := closer.Close() if err != nil { result = multierror.Append(result, err) } } return result }
[ "func", "(", "h", "*", "BuildHandler", ")", "Close", "(", ")", "error", "{", "var", "result", "error", "\n", "for", "_", ",", "closer", ":=", "range", "h", ".", "closers", "{", "err", ":=", "closer", ".", "Close", "(", ")", "\n", "if", "err", "!=...
// Close implements io.Closer
[ "Close", "implements", "io", ".", "Closer" ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/build_server.go#L581-L590
train
sourcegraph/go-langserver
langserver/symbol.go
String
func (q Query) String() string { s := "" switch q.Filter { case FilterExported: s = queryJoin(s, "is:exported") case FilterDir: s = queryJoin(s, fmt.Sprintf("%s:%s", q.Filter, q.Dir)) default: // no filter. } if q.Kind != 0 { for kwd, kind := range keywords { if kind == q.Kind { s = queryJoin(s, kwd) } } } for _, token := range q.Tokens { s = queryJoin(s, token) } return s }
go
func (q Query) String() string { s := "" switch q.Filter { case FilterExported: s = queryJoin(s, "is:exported") case FilterDir: s = queryJoin(s, fmt.Sprintf("%s:%s", q.Filter, q.Dir)) default: // no filter. } if q.Kind != 0 { for kwd, kind := range keywords { if kind == q.Kind { s = queryJoin(s, kwd) } } } for _, token := range q.Tokens { s = queryJoin(s, token) } return s }
[ "func", "(", "q", "Query", ")", "String", "(", ")", "string", "{", "s", ":=", "\"\"", "\n", "switch", "q", ".", "Filter", "{", "case", "FilterExported", ":", "s", "=", "queryJoin", "(", "s", ",", "\"is:exported\"", ")", "\n", "case", "FilterDir", ":"...
// String converts the query back into a logically equivalent, but not strictly // byte-wise equal, query string. It is useful for converting a modified query // structure back into a query string.
[ "String", "converts", "the", "query", "back", "into", "a", "logically", "equivalent", "but", "not", "strictly", "byte", "-", "wise", "equal", "query", "string", ".", "It", "is", "useful", "for", "converting", "a", "modified", "query", "structure", "back", "i...
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L42-L63
train
sourcegraph/go-langserver
langserver/symbol.go
ParseQuery
func ParseQuery(q string) (qu Query) { // All queries are case insensitive. q = strings.ToLower(q) // Split the query into space-delimited fields. for _, field := range strings.Fields(q) { // Check if the field is a filter like `is:exported`. if strings.HasPrefix(field, "dir:") { qu.Filter = FilterDir qu.Dir = strings.TrimPrefix(field, "dir:") continue } if field == "is:exported" { qu.Filter = FilterExported continue } // Each field is split into tokens, delimited by periods or slashes. tokens := strings.FieldsFunc(field, func(c rune) bool { return c == '.' || c == '/' }) for _, tok := range tokens { if kind, isKeyword := keywords[tok]; isKeyword { qu.Kind = kind continue } qu.Tokens = append(qu.Tokens, tok) } } return qu }
go
func ParseQuery(q string) (qu Query) { // All queries are case insensitive. q = strings.ToLower(q) // Split the query into space-delimited fields. for _, field := range strings.Fields(q) { // Check if the field is a filter like `is:exported`. if strings.HasPrefix(field, "dir:") { qu.Filter = FilterDir qu.Dir = strings.TrimPrefix(field, "dir:") continue } if field == "is:exported" { qu.Filter = FilterExported continue } // Each field is split into tokens, delimited by periods or slashes. tokens := strings.FieldsFunc(field, func(c rune) bool { return c == '.' || c == '/' }) for _, tok := range tokens { if kind, isKeyword := keywords[tok]; isKeyword { qu.Kind = kind continue } qu.Tokens = append(qu.Tokens, tok) } } return qu }
[ "func", "ParseQuery", "(", "q", "string", ")", "(", "qu", "Query", ")", "{", "q", "=", "strings", ".", "ToLower", "(", "q", ")", "\n", "for", "_", ",", "field", ":=", "range", "strings", ".", "Fields", "(", "q", ")", "{", "if", "strings", ".", ...
// ParseQuery parses a user's raw query string and returns a // structured representation of the query.
[ "ParseQuery", "parses", "a", "user", "s", "raw", "query", "string", "and", "returns", "a", "structured", "representation", "of", "the", "query", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L73-L103
train
sourcegraph/go-langserver
langserver/symbol.go
Collect
func (s *resultSorter) Collect(si symbolPair) { s.resultsMu.Lock() score := score(s.Query, si) if score > 0 { sc := scoredSymbol{score, si} s.results = append(s.results, sc) } s.resultsMu.Unlock() }
go
func (s *resultSorter) Collect(si symbolPair) { s.resultsMu.Lock() score := score(s.Query, si) if score > 0 { sc := scoredSymbol{score, si} s.results = append(s.results, sc) } s.resultsMu.Unlock() }
[ "func", "(", "s", "*", "resultSorter", ")", "Collect", "(", "si", "symbolPair", ")", "{", "s", ".", "resultsMu", ".", "Lock", "(", ")", "\n", "score", ":=", "score", "(", "s", ".", "Query", ",", "si", ")", "\n", "if", "score", ">", "0", "{", "s...
// Collect is a thread-safe method that will record the passed-in // symbol in the list of results if its score > 0.
[ "Collect", "is", "a", "thread", "-", "safe", "method", "that", "will", "record", "the", "passed", "-", "in", "symbol", "in", "the", "list", "of", "results", "if", "its", "score", ">", "0", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L167-L175
train
sourcegraph/go-langserver
langserver/symbol.go
Results
func (s *resultSorter) Results() []lsp.SymbolInformation { res := make([]lsp.SymbolInformation, len(s.results)) for i, s := range s.results { res[i] = s.SymbolInformation } return res }
go
func (s *resultSorter) Results() []lsp.SymbolInformation { res := make([]lsp.SymbolInformation, len(s.results)) for i, s := range s.results { res[i] = s.SymbolInformation } return res }
[ "func", "(", "s", "*", "resultSorter", ")", "Results", "(", ")", "[", "]", "lsp", ".", "SymbolInformation", "{", "res", ":=", "make", "(", "[", "]", "lsp", ".", "SymbolInformation", ",", "len", "(", "s", ".", "results", ")", ")", "\n", "for", "i", ...
// Results returns the ranked list of SymbolInformation values.
[ "Results", "returns", "the", "ranked", "list", "of", "SymbolInformation", "values", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L178-L184
train
sourcegraph/go-langserver
langserver/symbol.go
score
func score(q Query, s symbolPair) (scor int) { if q.Kind != 0 { if q.Kind != s.Kind { return 0 } } if q.Symbol != nil && !s.desc.Contains(q.Symbol) { return -1 } name, container := strings.ToLower(s.Name), strings.ToLower(s.ContainerName) if !util.IsURI(s.Location.URI) { log.Printf("unexpectedly saw symbol defined at a non-file URI: %q", s.Location.URI) return 0 } filename := util.UriToPath(s.Location.URI) isVendor := strings.HasPrefix(filename, "vendor/") || strings.Contains(filename, "/vendor/") if q.Filter == FilterExported && isVendor { // is:exported excludes vendor symbols always. return 0 } if q.File != "" && filename != q.File { // We're restricting results to a single file, and this isn't it. return 0 } if len(q.Tokens) == 0 { // early return if empty query if isVendor { return 1 // lower score for vendor symbols } else { return 2 } } for i, tok := range q.Tokens { tok := strings.ToLower(tok) if strings.HasPrefix(container, tok) { scor += 2 } if strings.HasPrefix(name, tok) { scor += 3 } if strings.Contains(filename, tok) && len(tok) >= 3 { scor++ } if strings.HasPrefix(path.Base(filename), tok) && len(tok) >= 3 { scor += 2 } if tok == name { if i == len(q.Tokens)-1 { scor += 50 } else { scor += 5 } } if tok == container { scor += 3 } } if scor > 0 && !(strings.HasPrefix(filename, "vendor/") || strings.Contains(filename, "/vendor/")) { // boost for non-vendor symbols scor += 5 } if scor > 0 && ast.IsExported(s.Name) { // boost for exported symbols scor++ } return scor }
go
func score(q Query, s symbolPair) (scor int) { if q.Kind != 0 { if q.Kind != s.Kind { return 0 } } if q.Symbol != nil && !s.desc.Contains(q.Symbol) { return -1 } name, container := strings.ToLower(s.Name), strings.ToLower(s.ContainerName) if !util.IsURI(s.Location.URI) { log.Printf("unexpectedly saw symbol defined at a non-file URI: %q", s.Location.URI) return 0 } filename := util.UriToPath(s.Location.URI) isVendor := strings.HasPrefix(filename, "vendor/") || strings.Contains(filename, "/vendor/") if q.Filter == FilterExported && isVendor { // is:exported excludes vendor symbols always. return 0 } if q.File != "" && filename != q.File { // We're restricting results to a single file, and this isn't it. return 0 } if len(q.Tokens) == 0 { // early return if empty query if isVendor { return 1 // lower score for vendor symbols } else { return 2 } } for i, tok := range q.Tokens { tok := strings.ToLower(tok) if strings.HasPrefix(container, tok) { scor += 2 } if strings.HasPrefix(name, tok) { scor += 3 } if strings.Contains(filename, tok) && len(tok) >= 3 { scor++ } if strings.HasPrefix(path.Base(filename), tok) && len(tok) >= 3 { scor += 2 } if tok == name { if i == len(q.Tokens)-1 { scor += 50 } else { scor += 5 } } if tok == container { scor += 3 } } if scor > 0 && !(strings.HasPrefix(filename, "vendor/") || strings.Contains(filename, "/vendor/")) { // boost for non-vendor symbols scor += 5 } if scor > 0 && ast.IsExported(s.Name) { // boost for exported symbols scor++ } return scor }
[ "func", "score", "(", "q", "Query", ",", "s", "symbolPair", ")", "(", "scor", "int", ")", "{", "if", "q", ".", "Kind", "!=", "0", "{", "if", "q", ".", "Kind", "!=", "s", ".", "Kind", "{", "return", "0", "\n", "}", "\n", "}", "\n", "if", "q"...
// score returns 0 for results that aren't matches. Results that are matches are assigned // a positive score, which should be used for ranking purposes.
[ "score", "returns", "0", "for", "results", "that", "aren", "t", "matches", ".", "Results", "that", "are", "matches", "are", "assigned", "a", "positive", "score", "which", "should", "be", "used", "for", "ranking", "purposes", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L188-L253
train
sourcegraph/go-langserver
langserver/symbol.go
toSym
func toSym(name string, bpkg *build.Package, container string, recv string, kind lsp.SymbolKind, fs *token.FileSet, pos token.Pos) symbolPair { var id string if container == "" { id = fmt.Sprintf("%s/-/%s", path.Clean(bpkg.ImportPath), name) } else { id = fmt.Sprintf("%s/-/%s/%s", path.Clean(bpkg.ImportPath), container, name) } return symbolPair{ SymbolInformation: lsp.SymbolInformation{ Name: name, Kind: kind, Location: goRangeToLSPLocation(fs, pos, pos+token.Pos(len(name))), ContainerName: container, }, // NOTE: fields must be kept in sync with workspace_refs.go:defSymbolDescriptor desc: symbolDescriptor{ Vendor: util.IsVendorDir(bpkg.Dir), Package: path.Clean(bpkg.ImportPath), PackageName: bpkg.Name, Recv: recv, Name: name, ID: id, }, } }
go
func toSym(name string, bpkg *build.Package, container string, recv string, kind lsp.SymbolKind, fs *token.FileSet, pos token.Pos) symbolPair { var id string if container == "" { id = fmt.Sprintf("%s/-/%s", path.Clean(bpkg.ImportPath), name) } else { id = fmt.Sprintf("%s/-/%s/%s", path.Clean(bpkg.ImportPath), container, name) } return symbolPair{ SymbolInformation: lsp.SymbolInformation{ Name: name, Kind: kind, Location: goRangeToLSPLocation(fs, pos, pos+token.Pos(len(name))), ContainerName: container, }, // NOTE: fields must be kept in sync with workspace_refs.go:defSymbolDescriptor desc: symbolDescriptor{ Vendor: util.IsVendorDir(bpkg.Dir), Package: path.Clean(bpkg.ImportPath), PackageName: bpkg.Name, Recv: recv, Name: name, ID: id, }, } }
[ "func", "toSym", "(", "name", "string", ",", "bpkg", "*", "build", ".", "Package", ",", "container", "string", ",", "recv", "string", ",", "kind", "lsp", ".", "SymbolKind", ",", "fs", "*", "token", ".", "FileSet", ",", "pos", "token", ".", "Pos", ")"...
// toSym returns a SymbolInformation value derived from values we get // from visiting the Go ast.
[ "toSym", "returns", "a", "SymbolInformation", "value", "derived", "from", "values", "we", "get", "from", "visiting", "the", "Go", "ast", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L257-L282
train
sourcegraph/go-langserver
langserver/symbol.go
collectFromPkg
func (h *LangHandler) collectFromPkg(ctx context.Context, bctx *build.Context, pkg string, rootPath string, results *resultSorter) { symbols := h.symbolCache.Get(pkg, func() interface{} { findPackage := h.getFindPackageFunc() buildPkg, err := findPackage(ctx, bctx, pkg, rootPath, rootPath, 0) if err != nil { maybeLogImportError(pkg, err) return nil } fs := token.NewFileSet() astPkgs, err := parseDir(fs, bctx, buildPkg.Dir, nil, 0) if err != nil { log.Printf("failed to parse directory %s: %s", buildPkg.Dir, err) return nil } astPkg := astPkgs[buildPkg.Name] if astPkg == nil { return nil } return astPkgToSymbols(fs, astPkg, buildPkg) }) if symbols == nil { return } for _, sym := range symbols.([]symbolPair) { if results.Query.Filter == FilterExported && !isExported(&sym) { continue } results.Collect(sym) } }
go
func (h *LangHandler) collectFromPkg(ctx context.Context, bctx *build.Context, pkg string, rootPath string, results *resultSorter) { symbols := h.symbolCache.Get(pkg, func() interface{} { findPackage := h.getFindPackageFunc() buildPkg, err := findPackage(ctx, bctx, pkg, rootPath, rootPath, 0) if err != nil { maybeLogImportError(pkg, err) return nil } fs := token.NewFileSet() astPkgs, err := parseDir(fs, bctx, buildPkg.Dir, nil, 0) if err != nil { log.Printf("failed to parse directory %s: %s", buildPkg.Dir, err) return nil } astPkg := astPkgs[buildPkg.Name] if astPkg == nil { return nil } return astPkgToSymbols(fs, astPkg, buildPkg) }) if symbols == nil { return } for _, sym := range symbols.([]symbolPair) { if results.Query.Filter == FilterExported && !isExported(&sym) { continue } results.Collect(sym) } }
[ "func", "(", "h", "*", "LangHandler", ")", "collectFromPkg", "(", "ctx", "context", ".", "Context", ",", "bctx", "*", "build", ".", "Context", ",", "pkg", "string", ",", "rootPath", "string", ",", "results", "*", "resultSorter", ")", "{", "symbols", ":="...
// collectFromPkg collects all the symbols from the specified package // into the results. It uses LangHandler's package symbol cache to // speed up repeated calls.
[ "collectFromPkg", "collects", "all", "the", "symbols", "from", "the", "specified", "package", "into", "the", "results", ".", "It", "uses", "LangHandler", "s", "package", "symbol", "cache", "to", "speed", "up", "repeated", "calls", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L403-L436
train
sourcegraph/go-langserver
langserver/symbol.go
Visit
func (c *SymbolCollector) Visit(n ast.Node) (w ast.Visitor) { switch t := n.(type) { case *ast.TypeSpec: if t.Name.Name != "_" { switch term := t.Type.(type) { case *ast.StructType: c.addContainer(t.Name.Name, term.Fields, lsp.SKClass, t.Name.NamePos) case *ast.InterfaceType: c.addContainer(t.Name.Name, term.Methods, lsp.SKInterface, t.Name.NamePos) default: c.addSymbol(t.Name.Name, "", "", lsp.SKClass, t.Name.NamePos) } } case *ast.GenDecl: switch t.Tok { case token.CONST: names := specNames(t.Specs) for _, name := range names { c.addSymbol(name, "", "", lsp.SKConstant, declNamePos(t, name)) } case token.VAR: names := specNames(t.Specs) for _, name := range names { if name != "_" { c.addSymbol(name, "", "", lsp.SKVariable, declNamePos(t, name)) } } } case *ast.FuncDecl: c.addFuncDecl(t) } return c }
go
func (c *SymbolCollector) Visit(n ast.Node) (w ast.Visitor) { switch t := n.(type) { case *ast.TypeSpec: if t.Name.Name != "_" { switch term := t.Type.(type) { case *ast.StructType: c.addContainer(t.Name.Name, term.Fields, lsp.SKClass, t.Name.NamePos) case *ast.InterfaceType: c.addContainer(t.Name.Name, term.Methods, lsp.SKInterface, t.Name.NamePos) default: c.addSymbol(t.Name.Name, "", "", lsp.SKClass, t.Name.NamePos) } } case *ast.GenDecl: switch t.Tok { case token.CONST: names := specNames(t.Specs) for _, name := range names { c.addSymbol(name, "", "", lsp.SKConstant, declNamePos(t, name)) } case token.VAR: names := specNames(t.Specs) for _, name := range names { if name != "_" { c.addSymbol(name, "", "", lsp.SKVariable, declNamePos(t, name)) } } } case *ast.FuncDecl: c.addFuncDecl(t) } return c }
[ "func", "(", "c", "*", "SymbolCollector", ")", "Visit", "(", "n", "ast", ".", "Node", ")", "(", "w", "ast", ".", "Visitor", ")", "{", "switch", "t", ":=", "n", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "TypeSpec", ":", "if", "t", "...
// Visit visits AST nodes and collects symbol information
[ "Visit", "visits", "AST", "nodes", "and", "collects", "symbol", "information" ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/symbol.go#L497-L529
train
sourcegraph/go-langserver
langserver/config.go
Apply
func (c Config) Apply(o *InitializationOptions) Config { if o == nil { return c } if o.FuncSnippetEnabled != nil { c.FuncSnippetEnabled = *o.FuncSnippetEnabled } if o.GocodeCompletionEnabled != nil { c.GocodeCompletionEnabled = *o.GocodeCompletionEnabled } if o.FormatTool != nil { c.FormatTool = *o.FormatTool } if o.LintTool != nil { c.LintTool = *o.LintTool } if o.GoimportsLocalPrefix != nil { c.GoimportsLocalPrefix = *o.GoimportsLocalPrefix } if o.MaxParallelism != nil { c.MaxParallelism = *o.MaxParallelism } if o.UseBinaryPkgCache != nil { c.UseBinaryPkgCache = *o.UseBinaryPkgCache } if o.DiagnosticsEnabled != nil { c.DiagnosticsEnabled = *o.DiagnosticsEnabled } return c }
go
func (c Config) Apply(o *InitializationOptions) Config { if o == nil { return c } if o.FuncSnippetEnabled != nil { c.FuncSnippetEnabled = *o.FuncSnippetEnabled } if o.GocodeCompletionEnabled != nil { c.GocodeCompletionEnabled = *o.GocodeCompletionEnabled } if o.FormatTool != nil { c.FormatTool = *o.FormatTool } if o.LintTool != nil { c.LintTool = *o.LintTool } if o.GoimportsLocalPrefix != nil { c.GoimportsLocalPrefix = *o.GoimportsLocalPrefix } if o.MaxParallelism != nil { c.MaxParallelism = *o.MaxParallelism } if o.UseBinaryPkgCache != nil { c.UseBinaryPkgCache = *o.UseBinaryPkgCache } if o.DiagnosticsEnabled != nil { c.DiagnosticsEnabled = *o.DiagnosticsEnabled } return c }
[ "func", "(", "c", "Config", ")", "Apply", "(", "o", "*", "InitializationOptions", ")", "Config", "{", "if", "o", "==", "nil", "{", "return", "c", "\n", "}", "\n", "if", "o", ".", "FuncSnippetEnabled", "!=", "nil", "{", "c", ".", "FuncSnippetEnabled", ...
// Apply sets the corresponding field in c for each non-nil field in o.
[ "Apply", "sets", "the", "corresponding", "field", "in", "c", "for", "each", "non", "-", "nil", "field", "in", "o", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/config.go#L70-L99
train
sourcegraph/go-langserver
langserver/config.go
NewDefaultConfig
func NewDefaultConfig() Config { // Default max parallelism to half the CPU cores, but at least always one. maxparallelism := runtime.NumCPU() / 2 if maxparallelism <= 0 { maxparallelism = 1 } return Config{ FuncSnippetEnabled: true, GocodeCompletionEnabled: false, FormatTool: formatToolGoimports, LintTool: lintToolNone, DiagnosticsEnabled: false, MaxParallelism: maxparallelism, UseBinaryPkgCache: true, } }
go
func NewDefaultConfig() Config { // Default max parallelism to half the CPU cores, but at least always one. maxparallelism := runtime.NumCPU() / 2 if maxparallelism <= 0 { maxparallelism = 1 } return Config{ FuncSnippetEnabled: true, GocodeCompletionEnabled: false, FormatTool: formatToolGoimports, LintTool: lintToolNone, DiagnosticsEnabled: false, MaxParallelism: maxparallelism, UseBinaryPkgCache: true, } }
[ "func", "NewDefaultConfig", "(", ")", "Config", "{", "maxparallelism", ":=", "runtime", ".", "NumCPU", "(", ")", "/", "2", "\n", "if", "maxparallelism", "<=", "0", "{", "maxparallelism", "=", "1", "\n", "}", "\n", "return", "Config", "{", "FuncSnippetEnabl...
// NewDefaultConfig returns the default config. See the field comments for the // defaults.
[ "NewDefaultConfig", "returns", "the", "default", "config", ".", "See", "the", "field", "comments", "for", "the", "defaults", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/config.go#L103-L119
train
sourcegraph/go-langserver
gosrc/import_path.go
guessImportPath
func guessImportPath(importPath string) (*Directory, error) { if !strings.Contains(importPath, ".git") { // Assume GitHub-like where two path elements is the project // root. parts := strings.SplitN(importPath, "/", 4) if len(parts) < 3 { return nil, fmt.Errorf("invalid GitHub-like import path: %q", importPath) } repo := parts[0] + "/" + parts[1] + "/" + parts[2] return &Directory{ ImportPath: importPath, ProjectRoot: repo, CloneURL: "http://" + repo, VCS: "git", }, nil } // TODO(slimsag): We assume that .git only shows up // once in the import path. Not always true, but generally // should be in 99% of cases. split := strings.Split(importPath, ".git") if len(split) != 2 { return nil, fmt.Errorf("expected one .git in %q", importPath) } return &Directory{ ImportPath: importPath, ProjectRoot: split[0] + ".git", CloneURL: "http://" + split[0] + ".git", VCS: "git", }, nil }
go
func guessImportPath(importPath string) (*Directory, error) { if !strings.Contains(importPath, ".git") { // Assume GitHub-like where two path elements is the project // root. parts := strings.SplitN(importPath, "/", 4) if len(parts) < 3 { return nil, fmt.Errorf("invalid GitHub-like import path: %q", importPath) } repo := parts[0] + "/" + parts[1] + "/" + parts[2] return &Directory{ ImportPath: importPath, ProjectRoot: repo, CloneURL: "http://" + repo, VCS: "git", }, nil } // TODO(slimsag): We assume that .git only shows up // once in the import path. Not always true, but generally // should be in 99% of cases. split := strings.Split(importPath, ".git") if len(split) != 2 { return nil, fmt.Errorf("expected one .git in %q", importPath) } return &Directory{ ImportPath: importPath, ProjectRoot: split[0] + ".git", CloneURL: "http://" + split[0] + ".git", VCS: "git", }, nil }
[ "func", "guessImportPath", "(", "importPath", "string", ")", "(", "*", "Directory", ",", "error", ")", "{", "if", "!", "strings", ".", "Contains", "(", "importPath", ",", "\".git\"", ")", "{", "parts", ":=", "strings", ".", "SplitN", "(", "importPath", "...
// guessImportPath is used by noGoGetDomains since we can't do the usual // go get resolution.
[ "guessImportPath", "is", "used", "by", "noGoGetDomains", "since", "we", "can", "t", "do", "the", "usual", "go", "get", "resolution", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/gosrc/import_path.go#L152-L183
train
sourcegraph/go-langserver
langserver/handler.go
NewHandler
func NewHandler(defaultCfg Config) jsonrpc2.Handler { return lspHandler{jsonrpc2.HandlerWithError((&LangHandler{ DefaultConfig: defaultCfg, HandlerShared: &HandlerShared{}, }).handle)} }
go
func NewHandler(defaultCfg Config) jsonrpc2.Handler { return lspHandler{jsonrpc2.HandlerWithError((&LangHandler{ DefaultConfig: defaultCfg, HandlerShared: &HandlerShared{}, }).handle)} }
[ "func", "NewHandler", "(", "defaultCfg", "Config", ")", "jsonrpc2", ".", "Handler", "{", "return", "lspHandler", "{", "jsonrpc2", ".", "HandlerWithError", "(", "(", "&", "LangHandler", "{", "DefaultConfig", ":", "defaultCfg", ",", "HandlerShared", ":", "&", "H...
// NewHandler creates a Go language server handler.
[ "NewHandler", "creates", "a", "Go", "language", "server", "handler", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler.go#L26-L31
train
sourcegraph/go-langserver
langserver/handler.go
Handle
func (h lspHandler) Handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) { if isFileSystemRequest(req.Method) { h.Handler.Handle(ctx, conn, req) return } go h.Handler.Handle(ctx, conn, req) }
go
func (h lspHandler) Handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) { if isFileSystemRequest(req.Method) { h.Handler.Handle(ctx, conn, req) return } go h.Handler.Handle(ctx, conn, req) }
[ "func", "(", "h", "lspHandler", ")", "Handle", "(", "ctx", "context", ".", "Context", ",", "conn", "*", "jsonrpc2", ".", "Conn", ",", "req", "*", "jsonrpc2", ".", "Request", ")", "{", "if", "isFileSystemRequest", "(", "req", ".", "Method", ")", "{", ...
// Handle implements jsonrpc2.Handler
[ "Handle", "implements", "jsonrpc2", ".", "Handler" ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler.go#L49-L55
train
sourcegraph/go-langserver
langserver/handler.go
handle
func (h *LangHandler) handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) { return h.Handle(ctx, conn, req) }
go
func (h *LangHandler) handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) (result interface{}, err error) { return h.Handle(ctx, conn, req) }
[ "func", "(", "h", "*", "LangHandler", ")", "handle", "(", "ctx", "context", ".", "Context", ",", "conn", "*", "jsonrpc2", ".", "Conn", ",", "req", "*", "jsonrpc2", ".", "Request", ")", "(", "result", "interface", "{", "}", ",", "err", "error", ")", ...
// handle implements jsonrpc2.Handler.
[ "handle", "implements", "jsonrpc2", ".", "Handler", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/handler.go#L153-L155
train
sourcegraph/go-langserver
buildserver/stdlib.go
addSysZversionFile
func addSysZversionFile(fs ctxvfs.FileSystem) ctxvfs.FileSystem { return ctxvfs.SingleFileOverlay(fs, "/src/runtime/internal/sys/zversion.go", []byte(fmt.Sprintf(` package sys const DefaultGoroot = %q const TheVersion = %q const Goexperiment="" const StackGuardMultiplier=1`, goroot, gosrc.RuntimeVersion))) }
go
func addSysZversionFile(fs ctxvfs.FileSystem) ctxvfs.FileSystem { return ctxvfs.SingleFileOverlay(fs, "/src/runtime/internal/sys/zversion.go", []byte(fmt.Sprintf(` package sys const DefaultGoroot = %q const TheVersion = %q const Goexperiment="" const StackGuardMultiplier=1`, goroot, gosrc.RuntimeVersion))) }
[ "func", "addSysZversionFile", "(", "fs", "ctxvfs", ".", "FileSystem", ")", "ctxvfs", ".", "FileSystem", "{", "return", "ctxvfs", ".", "SingleFileOverlay", "(", "fs", ",", "\"/src/runtime/internal/sys/zversion.go\"", ",", "[", "]", "byte", "(", "fmt", ".", "Sprin...
// addSysZversionFile adds the zversion.go file, which is generated // during the Go release process and does not exist in the VCS repo // archive zips. We need to create it here, or else we'll see // typechecker errors like "StackGuardMultiplier not declared by // package sys" when any packages import from the Go stdlib.
[ "addSysZversionFile", "adds", "the", "zversion", ".", "go", "file", "which", "is", "generated", "during", "the", "Go", "release", "process", "and", "does", "not", "exist", "in", "the", "VCS", "repo", "archive", "zips", ".", "We", "need", "to", "create", "i...
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/buildserver/stdlib.go#L15-L26
train
sourcegraph/go-langserver
langserver/internal/godef/go/types/types.go
DefaultImportPathToName
func DefaultImportPathToName(path, srcDir string) (string, error) { if path == "C" { return "C", nil } pkg, err := build.Default.Import(path, srcDir, 0) return pkg.Name, err }
go
func DefaultImportPathToName(path, srcDir string) (string, error) { if path == "C" { return "C", nil } pkg, err := build.Default.Import(path, srcDir, 0) return pkg.Name, err }
[ "func", "DefaultImportPathToName", "(", "path", ",", "srcDir", "string", ")", "(", "string", ",", "error", ")", "{", "if", "path", "==", "\"C\"", "{", "return", "\"C\"", ",", "nil", "\n", "}", "\n", "pkg", ",", "err", ":=", "build", ".", "Default", "...
// DefaultImportPathToName returns the package identifier // for the given import path.
[ "DefaultImportPathToName", "returns", "the", "package", "identifier", "for", "the", "given", "import", "path", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L123-L129
train
sourcegraph/go-langserver
langserver/internal/godef/go/types/types.go
isGoFile
func isGoFile(d os.FileInfo) bool { return strings.HasSuffix(d.Name(), ".go") && !strings.HasSuffix(d.Name(), "_test.go") && !strings.HasPrefix(d.Name(), ".") && goodOSArch(d.Name()) }
go
func isGoFile(d os.FileInfo) bool { return strings.HasSuffix(d.Name(), ".go") && !strings.HasSuffix(d.Name(), "_test.go") && !strings.HasPrefix(d.Name(), ".") && goodOSArch(d.Name()) }
[ "func", "isGoFile", "(", "d", "os", ".", "FileInfo", ")", "bool", "{", "return", "strings", ".", "HasSuffix", "(", "d", ".", "Name", "(", ")", ",", "\".go\"", ")", "&&", "!", "strings", ".", "HasSuffix", "(", "d", ".", "Name", "(", ")", ",", "\"_...
// isGoFile returns true if we will consider the file as a // possible candidate for parsing as part of a package. // Including _test.go here isn't quite right, but what // else can we do? //
[ "isGoFile", "returns", "true", "if", "we", "will", "consider", "the", "file", "as", "a", "possible", "candidate", "for", "parsing", "as", "part", "of", "a", "package", ".", "Including", "_test", ".", "go", "here", "isn", "t", "quite", "right", "but", "wh...
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L136-L141
train
sourcegraph/go-langserver
langserver/internal/godef/go/types/types.go
Member
func (t Type) Member(name string) *ast.Object { debugp("member %v '%s' {", t, name) if t.Pkg != "" && !ast.IsExported(name) { return nil } c := make(chan *ast.Object) go func() { if !Panic { defer func() { if err := recover(); err != nil { log.Printf("panic: %v", err) c <- nil } }() } doMembers(t, name, func(obj *ast.Object) { if obj.Name == name { c <- obj runtime.Goexit() } }) c <- nil }() m := <-c debugp("} -> %v", m) return m }
go
func (t Type) Member(name string) *ast.Object { debugp("member %v '%s' {", t, name) if t.Pkg != "" && !ast.IsExported(name) { return nil } c := make(chan *ast.Object) go func() { if !Panic { defer func() { if err := recover(); err != nil { log.Printf("panic: %v", err) c <- nil } }() } doMembers(t, name, func(obj *ast.Object) { if obj.Name == name { c <- obj runtime.Goexit() } }) c <- nil }() m := <-c debugp("} -> %v", m) return m }
[ "func", "(", "t", "Type", ")", "Member", "(", "name", "string", ")", "*", "ast", ".", "Object", "{", "debugp", "(", "\"member %v '%s' {\"", ",", "t", ",", "name", ")", "\n", "if", "t", ".", "Pkg", "!=", "\"\"", "&&", "!", "ast", ".", "IsExported", ...
// Member looks for a member with the given name inside // the type. For packages, the member can be any exported // top level declaration inside the package.
[ "Member", "looks", "for", "a", "member", "with", "the", "given", "name", "inside", "the", "type", ".", "For", "packages", "the", "member", "can", "be", "any", "exported", "top", "level", "declaration", "inside", "the", "package", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L156-L182
train
sourcegraph/go-langserver
langserver/internal/godef/go/types/types.go
Iter
func (t Type) Iter() <-chan *ast.Object { // TODO avoid sending members with the same name twice. c := make(chan *ast.Object) go func() { internal := t.Pkg == "" doMembers(t, "", func(obj *ast.Object) { if internal || ast.IsExported(obj.Name) { c <- obj } }) close(c) }() return c }
go
func (t Type) Iter() <-chan *ast.Object { // TODO avoid sending members with the same name twice. c := make(chan *ast.Object) go func() { internal := t.Pkg == "" doMembers(t, "", func(obj *ast.Object) { if internal || ast.IsExported(obj.Name) { c <- obj } }) close(c) }() return c }
[ "func", "(", "t", "Type", ")", "Iter", "(", ")", "<-", "chan", "*", "ast", ".", "Object", "{", "c", ":=", "make", "(", "chan", "*", "ast", ".", "Object", ")", "\n", "go", "func", "(", ")", "{", "internal", ":=", "t", ".", "Pkg", "==", "\"\"",...
// Iter returns a channel, sends on it // all the members of the type, then closes it. // Members at a shallower depth will be // sent first. //
[ "Iter", "returns", "a", "channel", "sends", "on", "it", "all", "the", "members", "of", "the", "type", "then", "closes", "it", ".", "Members", "at", "a", "shallower", "depth", "will", "be", "sent", "first", "." ]
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L189-L202
train
sourcegraph/go-langserver
langserver/internal/godef/go/types/types.go
ExprType
func ExprType(e ast.Expr, importer Importer, fs *token.FileSet) (obj *ast.Object, typ Type) { ctxt := &exprTypeContext{ importer: importer, fileSet: fs, } return ctxt.exprType(e, false, "") }
go
func ExprType(e ast.Expr, importer Importer, fs *token.FileSet) (obj *ast.Object, typ Type) { ctxt := &exprTypeContext{ importer: importer, fileSet: fs, } return ctxt.exprType(e, false, "") }
[ "func", "ExprType", "(", "e", "ast", ".", "Expr", ",", "importer", "Importer", ",", "fs", "*", "token", ".", "FileSet", ")", "(", "obj", "*", "ast", ".", "Object", ",", "typ", "Type", ")", "{", "ctxt", ":=", "&", "exprTypeContext", "{", "importer", ...
// ExprType returns the type for the given expression, // and the object that represents it, if there is one. // All variables, methods, top level functions, packages, struct and // interface members, and types have objects. // The returned object can be used with DeclPos to find out // the source location of the definition of the object. //
[ "ExprType", "returns", "the", "type", "for", "the", "given", "expression", "and", "the", "object", "that", "represents", "it", "if", "there", "is", "one", ".", "All", "variables", "methods", "top", "level", "functions", "packages", "struct", "and", "interface"...
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L211-L217
train
sourcegraph/go-langserver
langserver/internal/godef/go/types/types.go
doMembers
func doMembers(typ Type, name string, fn func(*ast.Object)) { switch t := typ.Node.(type) { case nil: return case *ast.ImportSpec: path := litToString(t.Path) pos := typ.ctxt.fileSet.Position(typ.Node.Pos()) if pkg := typ.ctxt.importer(path, filepath.Dir(pos.Filename)); pkg != nil { doScope(pkg.Scope, name, fn, path) } return } q := list.New() q.PushBack(typ) for e := q.Front(); e != nil; e = q.Front() { doTypeMembers(e.Value.(Type), name, fn, q) q.Remove(e) } }
go
func doMembers(typ Type, name string, fn func(*ast.Object)) { switch t := typ.Node.(type) { case nil: return case *ast.ImportSpec: path := litToString(t.Path) pos := typ.ctxt.fileSet.Position(typ.Node.Pos()) if pkg := typ.ctxt.importer(path, filepath.Dir(pos.Filename)); pkg != nil { doScope(pkg.Scope, name, fn, path) } return } q := list.New() q.PushBack(typ) for e := q.Front(); e != nil; e = q.Front() { doTypeMembers(e.Value.(Type), name, fn, q) q.Remove(e) } }
[ "func", "doMembers", "(", "typ", "Type", ",", "name", "string", ",", "fn", "func", "(", "*", "ast", ".", "Object", ")", ")", "{", "switch", "t", ":=", "typ", ".", "Node", ".", "(", "type", ")", "{", "case", "nil", ":", "return", "\n", "case", "...
// doMembers iterates through a type's members, calling // fn for each member. If name is non-empty, it looks // directly for members with that name when possible. // It uses the list q as a queue to perform breadth-first // traversal, as per the Go specification.
[ "doMembers", "iterates", "through", "a", "type", "s", "members", "calling", "fn", "for", "each", "member", ".", "If", "name", "is", "non", "-", "empty", "it", "looks", "directly", "for", "members", "with", "that", "name", "when", "possible", ".", "It", "...
33d2968a49e1131825a0accdd64bdf9901cf144c
https://github.com/sourcegraph/go-langserver/blob/33d2968a49e1131825a0accdd64bdf9901cf144c/langserver/internal/godef/go/types/types.go#L536-L556
train