repository_name
stringlengths 5
54
| func_path_in_repository
stringlengths 4
155
| func_name
stringlengths 1
118
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 1
value | func_code_string
stringlengths 52
3.87M
| func_code_tokens
sequencelengths 21
188k
| func_documentation_string
stringlengths 4
26.3k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|
GoogleContainerTools/container-diff | differs/apt_diff.go | Diff | func (a AptLayerAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
diff, err := singleVersionLayerDiff(image1, image2, a)
return diff, err
} | go | func (a AptLayerAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
diff, err := singleVersionLayerDiff(image1, image2, a)
return diff, err
} | [
"func",
"(",
"a",
"AptLayerAnalyzer",
")",
"Diff",
"(",
"image1",
",",
"image2",
"pkgutil",
".",
"Image",
")",
"(",
"util",
".",
"Result",
",",
"error",
")",
"{",
"diff",
",",
"err",
":=",
"singleVersionLayerDiff",
"(",
"image1",
",",
"image2",
",",
"a",
")",
"\n",
"return",
"diff",
",",
"err",
"\n",
"}"
] | // AptDiff compares the packages installed by apt-get. | [
"AptDiff",
"compares",
"the",
"packages",
"installed",
"by",
"apt",
"-",
"get",
"."
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/apt_diff.go#L138-L141 |
GoogleContainerTools/container-diff | differs/size_diff.go | Diff | func (a SizeAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
diff := []util.SizeDiff{}
size1 := pkgutil.GetSize(image1.FSPath)
size2 := pkgutil.GetSize(image2.FSPath)
if size1 != size2 {
diff = append(diff, util.SizeDiff{
Size1: size1,
Size2: size2,
})
}
return &util.SizeDiffResult{
Image1: image1.Source,
Image2: image2.Source,
DiffType: "Size",
Diff: diff,
}, nil
} | go | func (a SizeAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
diff := []util.SizeDiff{}
size1 := pkgutil.GetSize(image1.FSPath)
size2 := pkgutil.GetSize(image2.FSPath)
if size1 != size2 {
diff = append(diff, util.SizeDiff{
Size1: size1,
Size2: size2,
})
}
return &util.SizeDiffResult{
Image1: image1.Source,
Image2: image2.Source,
DiffType: "Size",
Diff: diff,
}, nil
} | [
"func",
"(",
"a",
"SizeAnalyzer",
")",
"Diff",
"(",
"image1",
",",
"image2",
"pkgutil",
".",
"Image",
")",
"(",
"util",
".",
"Result",
",",
"error",
")",
"{",
"diff",
":=",
"[",
"]",
"util",
".",
"SizeDiff",
"{",
"}",
"\n",
"size1",
":=",
"pkgutil",
".",
"GetSize",
"(",
"image1",
".",
"FSPath",
")",
"\n",
"size2",
":=",
"pkgutil",
".",
"GetSize",
"(",
"image2",
".",
"FSPath",
")",
"\n\n",
"if",
"size1",
"!=",
"size2",
"{",
"diff",
"=",
"append",
"(",
"diff",
",",
"util",
".",
"SizeDiff",
"{",
"Size1",
":",
"size1",
",",
"Size2",
":",
"size2",
",",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"util",
".",
"SizeDiffResult",
"{",
"Image1",
":",
"image1",
".",
"Source",
",",
"Image2",
":",
"image2",
".",
"Source",
",",
"DiffType",
":",
"\"",
"\"",
",",
"Diff",
":",
"diff",
",",
"}",
",",
"nil",
"\n",
"}"
] | // SizeDiff diffs two images and compares their size | [
"SizeDiff",
"diffs",
"two",
"images",
"and",
"compares",
"their",
"size"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/size_diff.go#L34-L52 |
GoogleContainerTools/container-diff | differs/size_diff.go | Diff | func (a SizeLayerAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
var layerDiffs []util.SizeDiff
maxLayer := len(image1.Layers)
if len(image2.Layers) > maxLayer {
maxLayer = len(image2.Layers)
}
for index := 0; index < maxLayer; index++ {
var size1, size2 int64 = -1, -1
if index < len(image1.Layers) {
size1 = pkgutil.GetSize(image1.Layers[index].FSPath)
}
if index < len(image2.Layers) {
size2 = pkgutil.GetSize(image2.Layers[index].FSPath)
}
if size1 != size2 {
diff := util.SizeDiff{
Name: strconv.Itoa(index),
Size1: size1,
Size2: size2,
}
layerDiffs = append(layerDiffs, diff)
}
}
return &util.SizeLayerDiffResult{
Image1: image1.Source,
Image2: image2.Source,
DiffType: "SizeLayer",
Diff: layerDiffs,
}, nil
} | go | func (a SizeLayerAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
var layerDiffs []util.SizeDiff
maxLayer := len(image1.Layers)
if len(image2.Layers) > maxLayer {
maxLayer = len(image2.Layers)
}
for index := 0; index < maxLayer; index++ {
var size1, size2 int64 = -1, -1
if index < len(image1.Layers) {
size1 = pkgutil.GetSize(image1.Layers[index].FSPath)
}
if index < len(image2.Layers) {
size2 = pkgutil.GetSize(image2.Layers[index].FSPath)
}
if size1 != size2 {
diff := util.SizeDiff{
Name: strconv.Itoa(index),
Size1: size1,
Size2: size2,
}
layerDiffs = append(layerDiffs, diff)
}
}
return &util.SizeLayerDiffResult{
Image1: image1.Source,
Image2: image2.Source,
DiffType: "SizeLayer",
Diff: layerDiffs,
}, nil
} | [
"func",
"(",
"a",
"SizeLayerAnalyzer",
")",
"Diff",
"(",
"image1",
",",
"image2",
"pkgutil",
".",
"Image",
")",
"(",
"util",
".",
"Result",
",",
"error",
")",
"{",
"var",
"layerDiffs",
"[",
"]",
"util",
".",
"SizeDiff",
"\n\n",
"maxLayer",
":=",
"len",
"(",
"image1",
".",
"Layers",
")",
"\n",
"if",
"len",
"(",
"image2",
".",
"Layers",
")",
">",
"maxLayer",
"{",
"maxLayer",
"=",
"len",
"(",
"image2",
".",
"Layers",
")",
"\n",
"}",
"\n\n",
"for",
"index",
":=",
"0",
";",
"index",
"<",
"maxLayer",
";",
"index",
"++",
"{",
"var",
"size1",
",",
"size2",
"int64",
"=",
"-",
"1",
",",
"-",
"1",
"\n",
"if",
"index",
"<",
"len",
"(",
"image1",
".",
"Layers",
")",
"{",
"size1",
"=",
"pkgutil",
".",
"GetSize",
"(",
"image1",
".",
"Layers",
"[",
"index",
"]",
".",
"FSPath",
")",
"\n",
"}",
"\n",
"if",
"index",
"<",
"len",
"(",
"image2",
".",
"Layers",
")",
"{",
"size2",
"=",
"pkgutil",
".",
"GetSize",
"(",
"image2",
".",
"Layers",
"[",
"index",
"]",
".",
"FSPath",
")",
"\n",
"}",
"\n\n",
"if",
"size1",
"!=",
"size2",
"{",
"diff",
":=",
"util",
".",
"SizeDiff",
"{",
"Name",
":",
"strconv",
".",
"Itoa",
"(",
"index",
")",
",",
"Size1",
":",
"size1",
",",
"Size2",
":",
"size2",
",",
"}",
"\n",
"layerDiffs",
"=",
"append",
"(",
"layerDiffs",
",",
"diff",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"util",
".",
"SizeLayerDiffResult",
"{",
"Image1",
":",
"image1",
".",
"Source",
",",
"Image2",
":",
"image2",
".",
"Source",
",",
"DiffType",
":",
"\"",
"\"",
",",
"Diff",
":",
"layerDiffs",
",",
"}",
",",
"nil",
"\n",
"}"
] | // SizeLayerDiff diffs the layers of two images and compares their size | [
"SizeLayerDiff",
"diffs",
"the",
"layers",
"of",
"two",
"images",
"and",
"compares",
"their",
"size"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/size_diff.go#L78-L111 |
GoogleContainerTools/container-diff | differs/metadata_diff.go | StructMapToStringMap | func StructMapToStringMap(m map[string]struct{}) map[string]string {
newMap := make(map[string]string)
for k := range m {
newMap[k] = fmt.Sprintf("%s", m[k])
}
return newMap
} | go | func StructMapToStringMap(m map[string]struct{}) map[string]string {
newMap := make(map[string]string)
for k := range m {
newMap[k] = fmt.Sprintf("%s", m[k])
}
return newMap
} | [
"func",
"StructMapToStringMap",
"(",
"m",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"newMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"k",
":=",
"range",
"m",
"{",
"newMap",
"[",
"k",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"m",
"[",
"k",
"]",
")",
"\n",
"}",
"\n",
"return",
"newMap",
"\n",
"}"
] | // StructMapToStringMap converts map[string]struct{} to map[string]string knowing that the
// struct in the value is always empty | [
"StructMapToStringMap",
"converts",
"map",
"[",
"string",
"]",
"struct",
"{}",
"to",
"map",
"[",
"string",
"]",
"string",
"knowing",
"that",
"the",
"struct",
"in",
"the",
"value",
"is",
"always",
"empty"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/metadata_diff.go#L110-L116 |
GoogleContainerTools/container-diff | differs/file_diff.go | Diff | func (a FileAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
diff, err := diffImageFiles(image1.FSPath, image2.FSPath)
return &util.DirDiffResult{
Image1: image1.Source,
Image2: image2.Source,
DiffType: "File",
Diff: diff,
}, err
} | go | func (a FileAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
diff, err := diffImageFiles(image1.FSPath, image2.FSPath)
return &util.DirDiffResult{
Image1: image1.Source,
Image2: image2.Source,
DiffType: "File",
Diff: diff,
}, err
} | [
"func",
"(",
"a",
"FileAnalyzer",
")",
"Diff",
"(",
"image1",
",",
"image2",
"pkgutil",
".",
"Image",
")",
"(",
"util",
".",
"Result",
",",
"error",
")",
"{",
"diff",
",",
"err",
":=",
"diffImageFiles",
"(",
"image1",
".",
"FSPath",
",",
"image2",
".",
"FSPath",
")",
"\n",
"return",
"&",
"util",
".",
"DirDiffResult",
"{",
"Image1",
":",
"image1",
".",
"Source",
",",
"Image2",
":",
"image2",
".",
"Source",
",",
"DiffType",
":",
"\"",
"\"",
",",
"Diff",
":",
"diff",
",",
"}",
",",
"err",
"\n",
"}"
] | // FileDiff diffs two packages and compares their contents | [
"FileDiff",
"diffs",
"two",
"packages",
"and",
"compares",
"their",
"contents"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/file_diff.go#L33-L41 |
GoogleContainerTools/container-diff | differs/file_diff.go | Diff | func (a FileLayerAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
var dirDiffs []util.DirDiff
// Go through each layer of the first image...
for index, layer := range image1.Layers {
if index >= len(image2.Layers) {
continue
}
// ...else, diff as usual
layer2 := image2.Layers[index]
diff, err := diffImageFiles(layer.FSPath, layer2.FSPath)
if err != nil {
return &util.MultipleDirDiffResult{}, err
}
dirDiffs = append(dirDiffs, diff)
}
// check if there are any additional layers in either image
if len(image1.Layers) != len(image2.Layers) {
if len(image1.Layers) > len(image2.Layers) {
logrus.Infof("%s has additional layers, please use container-diff analyze to view the files in these layers", image1.Source)
} else {
logrus.Infof("%s has additional layers, please use container-diff analyze to view the files in these layers", image2.Source)
}
}
return &util.MultipleDirDiffResult{
Image1: image1.Source,
Image2: image2.Source,
DiffType: "FileLayer",
Diff: util.MultipleDirDiff{
DirDiffs: dirDiffs,
},
}, nil
} | go | func (a FileLayerAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
var dirDiffs []util.DirDiff
// Go through each layer of the first image...
for index, layer := range image1.Layers {
if index >= len(image2.Layers) {
continue
}
// ...else, diff as usual
layer2 := image2.Layers[index]
diff, err := diffImageFiles(layer.FSPath, layer2.FSPath)
if err != nil {
return &util.MultipleDirDiffResult{}, err
}
dirDiffs = append(dirDiffs, diff)
}
// check if there are any additional layers in either image
if len(image1.Layers) != len(image2.Layers) {
if len(image1.Layers) > len(image2.Layers) {
logrus.Infof("%s has additional layers, please use container-diff analyze to view the files in these layers", image1.Source)
} else {
logrus.Infof("%s has additional layers, please use container-diff analyze to view the files in these layers", image2.Source)
}
}
return &util.MultipleDirDiffResult{
Image1: image1.Source,
Image2: image2.Source,
DiffType: "FileLayer",
Diff: util.MultipleDirDiff{
DirDiffs: dirDiffs,
},
}, nil
} | [
"func",
"(",
"a",
"FileLayerAnalyzer",
")",
"Diff",
"(",
"image1",
",",
"image2",
"pkgutil",
".",
"Image",
")",
"(",
"util",
".",
"Result",
",",
"error",
")",
"{",
"var",
"dirDiffs",
"[",
"]",
"util",
".",
"DirDiff",
"\n\n",
"// Go through each layer of the first image...",
"for",
"index",
",",
"layer",
":=",
"range",
"image1",
".",
"Layers",
"{",
"if",
"index",
">=",
"len",
"(",
"image2",
".",
"Layers",
")",
"{",
"continue",
"\n",
"}",
"\n",
"// ...else, diff as usual",
"layer2",
":=",
"image2",
".",
"Layers",
"[",
"index",
"]",
"\n",
"diff",
",",
"err",
":=",
"diffImageFiles",
"(",
"layer",
".",
"FSPath",
",",
"layer2",
".",
"FSPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"util",
".",
"MultipleDirDiffResult",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"dirDiffs",
"=",
"append",
"(",
"dirDiffs",
",",
"diff",
")",
"\n",
"}",
"\n\n",
"// check if there are any additional layers in either image",
"if",
"len",
"(",
"image1",
".",
"Layers",
")",
"!=",
"len",
"(",
"image2",
".",
"Layers",
")",
"{",
"if",
"len",
"(",
"image1",
".",
"Layers",
")",
">",
"len",
"(",
"image2",
".",
"Layers",
")",
"{",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"image1",
".",
"Source",
")",
"\n",
"}",
"else",
"{",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"image2",
".",
"Source",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"&",
"util",
".",
"MultipleDirDiffResult",
"{",
"Image1",
":",
"image1",
".",
"Source",
",",
"Image2",
":",
"image2",
".",
"Source",
",",
"DiffType",
":",
"\"",
"\"",
",",
"Diff",
":",
"util",
".",
"MultipleDirDiff",
"{",
"DirDiffs",
":",
"dirDiffs",
",",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // FileDiff diffs two packages and compares their contents | [
"FileDiff",
"diffs",
"two",
"packages",
"and",
"compares",
"their",
"contents"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/file_diff.go#L81-L114 |
GoogleContainerTools/container-diff | differs/package_differs.go | singleVersionLayerDiff | func singleVersionLayerDiff(image1, image2 pkgutil.Image, differ SingleVersionPackageLayerAnalyzer) (*util.SingleVersionPackageLayerDiffResult, error) {
logrus.Warning("'diff' command for packages on layers is not supported, consider using 'analyze' on each image instead")
return &util.SingleVersionPackageLayerDiffResult{}, errors.New("Diff for packages on layers is not supported, only analysis is supported")
} | go | func singleVersionLayerDiff(image1, image2 pkgutil.Image, differ SingleVersionPackageLayerAnalyzer) (*util.SingleVersionPackageLayerDiffResult, error) {
logrus.Warning("'diff' command for packages on layers is not supported, consider using 'analyze' on each image instead")
return &util.SingleVersionPackageLayerDiffResult{}, errors.New("Diff for packages on layers is not supported, only analysis is supported")
} | [
"func",
"singleVersionLayerDiff",
"(",
"image1",
",",
"image2",
"pkgutil",
".",
"Image",
",",
"differ",
"SingleVersionPackageLayerAnalyzer",
")",
"(",
"*",
"util",
".",
"SingleVersionPackageLayerDiffResult",
",",
"error",
")",
"{",
"logrus",
".",
"Warning",
"(",
"\"",
"\"",
")",
"\n",
"return",
"&",
"util",
".",
"SingleVersionPackageLayerDiffResult",
"{",
"}",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // singleVersionLayerDiff returns an error as this diff is not supported as
// it is far from obvious to define it in meaningful way | [
"singleVersionLayerDiff",
"returns",
"an",
"error",
"as",
"this",
"diff",
"is",
"not",
"supported",
"as",
"it",
"is",
"far",
"from",
"obvious",
"to",
"define",
"it",
"in",
"meaningful",
"way"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/package_differs.go#L83-L86 |
GoogleContainerTools/container-diff | differs/package_differs.go | singleVersionLayerAnalysis | func singleVersionLayerAnalysis(image pkgutil.Image, analyzer SingleVersionPackageLayerAnalyzer) (*util.SingleVersionPackageLayerAnalyzeResult, error) {
pack, err := analyzer.getPackages(image)
if err != nil {
return &util.SingleVersionPackageLayerAnalyzeResult{}, err
}
var pkgDiffs []util.PackageDiff
// Each layer with modified packages includes a complete list of packages
// in its package database. Thus we diff the current layer with the
// previous one that contains a package database. Layers that do not
// include a package database are omitted.
preInd := -1
for i := range pack {
var pkgDiff util.PackageDiff
if preInd < 0 && len(pack[i]) > 0 {
pkgDiff = util.GetMapDiff(make(map[string]util.PackageInfo), pack[i])
preInd = i
} else if preInd >= 0 && len(pack[i]) > 0 {
pkgDiff = util.GetMapDiff(pack[preInd], pack[i])
preInd = i
}
pkgDiffs = append(pkgDiffs, pkgDiff)
}
return &util.SingleVersionPackageLayerAnalyzeResult{
Image: image.Source,
AnalyzeType: strings.TrimSuffix(analyzer.Name(), "Analyzer"),
Analysis: util.PackageLayerDiff{
PackageDiffs: pkgDiffs,
},
}, nil
} | go | func singleVersionLayerAnalysis(image pkgutil.Image, analyzer SingleVersionPackageLayerAnalyzer) (*util.SingleVersionPackageLayerAnalyzeResult, error) {
pack, err := analyzer.getPackages(image)
if err != nil {
return &util.SingleVersionPackageLayerAnalyzeResult{}, err
}
var pkgDiffs []util.PackageDiff
// Each layer with modified packages includes a complete list of packages
// in its package database. Thus we diff the current layer with the
// previous one that contains a package database. Layers that do not
// include a package database are omitted.
preInd := -1
for i := range pack {
var pkgDiff util.PackageDiff
if preInd < 0 && len(pack[i]) > 0 {
pkgDiff = util.GetMapDiff(make(map[string]util.PackageInfo), pack[i])
preInd = i
} else if preInd >= 0 && len(pack[i]) > 0 {
pkgDiff = util.GetMapDiff(pack[preInd], pack[i])
preInd = i
}
pkgDiffs = append(pkgDiffs, pkgDiff)
}
return &util.SingleVersionPackageLayerAnalyzeResult{
Image: image.Source,
AnalyzeType: strings.TrimSuffix(analyzer.Name(), "Analyzer"),
Analysis: util.PackageLayerDiff{
PackageDiffs: pkgDiffs,
},
}, nil
} | [
"func",
"singleVersionLayerAnalysis",
"(",
"image",
"pkgutil",
".",
"Image",
",",
"analyzer",
"SingleVersionPackageLayerAnalyzer",
")",
"(",
"*",
"util",
".",
"SingleVersionPackageLayerAnalyzeResult",
",",
"error",
")",
"{",
"pack",
",",
"err",
":=",
"analyzer",
".",
"getPackages",
"(",
"image",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"util",
".",
"SingleVersionPackageLayerAnalyzeResult",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"var",
"pkgDiffs",
"[",
"]",
"util",
".",
"PackageDiff",
"\n\n",
"// Each layer with modified packages includes a complete list of packages",
"// in its package database. Thus we diff the current layer with the",
"// previous one that contains a package database. Layers that do not",
"// include a package database are omitted.",
"preInd",
":=",
"-",
"1",
"\n",
"for",
"i",
":=",
"range",
"pack",
"{",
"var",
"pkgDiff",
"util",
".",
"PackageDiff",
"\n",
"if",
"preInd",
"<",
"0",
"&&",
"len",
"(",
"pack",
"[",
"i",
"]",
")",
">",
"0",
"{",
"pkgDiff",
"=",
"util",
".",
"GetMapDiff",
"(",
"make",
"(",
"map",
"[",
"string",
"]",
"util",
".",
"PackageInfo",
")",
",",
"pack",
"[",
"i",
"]",
")",
"\n",
"preInd",
"=",
"i",
"\n",
"}",
"else",
"if",
"preInd",
">=",
"0",
"&&",
"len",
"(",
"pack",
"[",
"i",
"]",
")",
">",
"0",
"{",
"pkgDiff",
"=",
"util",
".",
"GetMapDiff",
"(",
"pack",
"[",
"preInd",
"]",
",",
"pack",
"[",
"i",
"]",
")",
"\n",
"preInd",
"=",
"i",
"\n",
"}",
"\n\n",
"pkgDiffs",
"=",
"append",
"(",
"pkgDiffs",
",",
"pkgDiff",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"util",
".",
"SingleVersionPackageLayerAnalyzeResult",
"{",
"Image",
":",
"image",
".",
"Source",
",",
"AnalyzeType",
":",
"strings",
".",
"TrimSuffix",
"(",
"analyzer",
".",
"Name",
"(",
")",
",",
"\"",
"\"",
")",
",",
"Analysis",
":",
"util",
".",
"PackageLayerDiff",
"{",
"PackageDiffs",
":",
"pkgDiffs",
",",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // singleVersionLayerAnalysis returns the packages included, deleted or
// updated in each layer | [
"singleVersionLayerAnalysis",
"returns",
"the",
"packages",
"included",
"deleted",
"or",
"updated",
"in",
"each",
"layer"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/differs/package_differs.go#L118-L150 |
GoogleContainerTools/container-diff | pkg/util/image_utils.go | GetImage | func GetImage(imageName string, includeLayers bool, cacheDir string) (Image, error) {
logrus.Infof("retrieving image: %s", imageName)
var img v1.Image
var err error
if IsTar(imageName) {
start := time.Now()
img, err = tarball.ImageFromPath(imageName, nil)
if err != nil {
return Image{}, errors.Wrap(err, "retrieving tar from path")
}
elapsed := time.Now().Sub(start)
logrus.Infof("retrieving image ref from tar took %f seconds", elapsed.Seconds())
} else if strings.HasPrefix(imageName, daemonPrefix) {
// remove the daemon prefix
imageName = strings.Replace(imageName, daemonPrefix, "", -1)
ref, err := name.ParseReference(imageName, name.WeakValidation)
if err != nil {
return Image{}, errors.Wrap(err, "parsing image reference")
}
start := time.Now()
// TODO(nkubala): specify gzip.NoCompression here when functional options are supported
img, err = daemon.Image(ref, daemon.WithBufferedOpener())
if err != nil {
return Image{}, errors.Wrap(err, "retrieving image from daemon")
}
elapsed := time.Now().Sub(start)
logrus.Infof("retrieving local image ref took %f seconds", elapsed.Seconds())
} else {
// either has remote prefix or has no prefix, in which case we force remote
imageName = strings.Replace(imageName, remotePrefix, "", -1)
ref, err := name.ParseReference(imageName, name.WeakValidation)
if err != nil {
return Image{}, errors.Wrap(err, "parsing image reference")
}
auth, err := authn.DefaultKeychain.Resolve(ref.Context().Registry)
if err != nil {
return Image{}, errors.Wrap(err, "resolving auth")
}
start := time.Now()
img, err = remote.Image(ref, remote.WithAuth(auth), remote.WithTransport(http.DefaultTransport))
if err != nil {
return Image{}, errors.Wrap(err, "retrieving remote image")
}
elapsed := time.Now().Sub(start)
logrus.Infof("retrieving remote image ref took %f seconds", elapsed.Seconds())
}
// create tempdir and extract fs into it
var layers []Layer
if includeLayers {
start := time.Now()
imgLayers, err := img.Layers()
if err != nil {
return Image{}, errors.Wrap(err, "getting image layers")
}
for _, layer := range imgLayers {
layerStart := time.Now()
digest, err := layer.Digest()
path, err := getExtractPathForName(digest.String(), cacheDir)
if err != nil {
return Image{
Layers: layers,
}, errors.Wrap(err, "getting extract path for layer")
}
if err := GetFileSystemForLayer(layer, path, nil); err != nil {
return Image{
Layers: layers,
}, errors.Wrap(err, "getting filesystem for layer")
}
layers = append(layers, Layer{
FSPath: path,
Digest: digest,
})
elapsed := time.Now().Sub(layerStart)
logrus.Infof("time elapsed retrieving layer: %fs", elapsed.Seconds())
}
elapsed := time.Now().Sub(start)
logrus.Infof("time elapsed retrieving image layers: %fs", elapsed.Seconds())
}
imageDigest, err := getImageDigest(img)
if err != nil {
return Image{}, err
}
path, err := getExtractPathForName(RemoveTag(imageName)+"@"+imageDigest.String(), cacheDir)
if err != nil {
return Image{}, err
}
// extract fs into provided dir
if err := GetFileSystemForImage(img, path, nil); err != nil {
return Image{
FSPath: path,
Layers: layers,
}, errors.Wrap(err, "getting filesystem for image")
}
return Image{
Image: img,
Source: imageName,
FSPath: path,
Digest: imageDigest,
Layers: layers,
}, nil
} | go | func GetImage(imageName string, includeLayers bool, cacheDir string) (Image, error) {
logrus.Infof("retrieving image: %s", imageName)
var img v1.Image
var err error
if IsTar(imageName) {
start := time.Now()
img, err = tarball.ImageFromPath(imageName, nil)
if err != nil {
return Image{}, errors.Wrap(err, "retrieving tar from path")
}
elapsed := time.Now().Sub(start)
logrus.Infof("retrieving image ref from tar took %f seconds", elapsed.Seconds())
} else if strings.HasPrefix(imageName, daemonPrefix) {
// remove the daemon prefix
imageName = strings.Replace(imageName, daemonPrefix, "", -1)
ref, err := name.ParseReference(imageName, name.WeakValidation)
if err != nil {
return Image{}, errors.Wrap(err, "parsing image reference")
}
start := time.Now()
// TODO(nkubala): specify gzip.NoCompression here when functional options are supported
img, err = daemon.Image(ref, daemon.WithBufferedOpener())
if err != nil {
return Image{}, errors.Wrap(err, "retrieving image from daemon")
}
elapsed := time.Now().Sub(start)
logrus.Infof("retrieving local image ref took %f seconds", elapsed.Seconds())
} else {
// either has remote prefix or has no prefix, in which case we force remote
imageName = strings.Replace(imageName, remotePrefix, "", -1)
ref, err := name.ParseReference(imageName, name.WeakValidation)
if err != nil {
return Image{}, errors.Wrap(err, "parsing image reference")
}
auth, err := authn.DefaultKeychain.Resolve(ref.Context().Registry)
if err != nil {
return Image{}, errors.Wrap(err, "resolving auth")
}
start := time.Now()
img, err = remote.Image(ref, remote.WithAuth(auth), remote.WithTransport(http.DefaultTransport))
if err != nil {
return Image{}, errors.Wrap(err, "retrieving remote image")
}
elapsed := time.Now().Sub(start)
logrus.Infof("retrieving remote image ref took %f seconds", elapsed.Seconds())
}
// create tempdir and extract fs into it
var layers []Layer
if includeLayers {
start := time.Now()
imgLayers, err := img.Layers()
if err != nil {
return Image{}, errors.Wrap(err, "getting image layers")
}
for _, layer := range imgLayers {
layerStart := time.Now()
digest, err := layer.Digest()
path, err := getExtractPathForName(digest.String(), cacheDir)
if err != nil {
return Image{
Layers: layers,
}, errors.Wrap(err, "getting extract path for layer")
}
if err := GetFileSystemForLayer(layer, path, nil); err != nil {
return Image{
Layers: layers,
}, errors.Wrap(err, "getting filesystem for layer")
}
layers = append(layers, Layer{
FSPath: path,
Digest: digest,
})
elapsed := time.Now().Sub(layerStart)
logrus.Infof("time elapsed retrieving layer: %fs", elapsed.Seconds())
}
elapsed := time.Now().Sub(start)
logrus.Infof("time elapsed retrieving image layers: %fs", elapsed.Seconds())
}
imageDigest, err := getImageDigest(img)
if err != nil {
return Image{}, err
}
path, err := getExtractPathForName(RemoveTag(imageName)+"@"+imageDigest.String(), cacheDir)
if err != nil {
return Image{}, err
}
// extract fs into provided dir
if err := GetFileSystemForImage(img, path, nil); err != nil {
return Image{
FSPath: path,
Layers: layers,
}, errors.Wrap(err, "getting filesystem for image")
}
return Image{
Image: img,
Source: imageName,
FSPath: path,
Digest: imageDigest,
Layers: layers,
}, nil
} | [
"func",
"GetImage",
"(",
"imageName",
"string",
",",
"includeLayers",
"bool",
",",
"cacheDir",
"string",
")",
"(",
"Image",
",",
"error",
")",
"{",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"imageName",
")",
"\n",
"var",
"img",
"v1",
".",
"Image",
"\n",
"var",
"err",
"error",
"\n",
"if",
"IsTar",
"(",
"imageName",
")",
"{",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"img",
",",
"err",
"=",
"tarball",
".",
"ImageFromPath",
"(",
"imageName",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Image",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"elapsed",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"start",
")",
"\n",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"elapsed",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"imageName",
",",
"daemonPrefix",
")",
"{",
"// remove the daemon prefix",
"imageName",
"=",
"strings",
".",
"Replace",
"(",
"imageName",
",",
"daemonPrefix",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n\n",
"ref",
",",
"err",
":=",
"name",
".",
"ParseReference",
"(",
"imageName",
",",
"name",
".",
"WeakValidation",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Image",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"// TODO(nkubala): specify gzip.NoCompression here when functional options are supported",
"img",
",",
"err",
"=",
"daemon",
".",
"Image",
"(",
"ref",
",",
"daemon",
".",
"WithBufferedOpener",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Image",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"elapsed",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"start",
")",
"\n",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"elapsed",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"// either has remote prefix or has no prefix, in which case we force remote",
"imageName",
"=",
"strings",
".",
"Replace",
"(",
"imageName",
",",
"remotePrefix",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"ref",
",",
"err",
":=",
"name",
".",
"ParseReference",
"(",
"imageName",
",",
"name",
".",
"WeakValidation",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Image",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"auth",
",",
"err",
":=",
"authn",
".",
"DefaultKeychain",
".",
"Resolve",
"(",
"ref",
".",
"Context",
"(",
")",
".",
"Registry",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Image",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"img",
",",
"err",
"=",
"remote",
".",
"Image",
"(",
"ref",
",",
"remote",
".",
"WithAuth",
"(",
"auth",
")",
",",
"remote",
".",
"WithTransport",
"(",
"http",
".",
"DefaultTransport",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Image",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"elapsed",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"start",
")",
"\n",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"elapsed",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"\n\n",
"// create tempdir and extract fs into it",
"var",
"layers",
"[",
"]",
"Layer",
"\n",
"if",
"includeLayers",
"{",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"imgLayers",
",",
"err",
":=",
"img",
".",
"Layers",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Image",
"{",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"layer",
":=",
"range",
"imgLayers",
"{",
"layerStart",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"digest",
",",
"err",
":=",
"layer",
".",
"Digest",
"(",
")",
"\n",
"path",
",",
"err",
":=",
"getExtractPathForName",
"(",
"digest",
".",
"String",
"(",
")",
",",
"cacheDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Image",
"{",
"Layers",
":",
"layers",
",",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"GetFileSystemForLayer",
"(",
"layer",
",",
"path",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"Image",
"{",
"Layers",
":",
"layers",
",",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"layers",
"=",
"append",
"(",
"layers",
",",
"Layer",
"{",
"FSPath",
":",
"path",
",",
"Digest",
":",
"digest",
",",
"}",
")",
"\n",
"elapsed",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"layerStart",
")",
"\n",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"elapsed",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"\n",
"elapsed",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"start",
")",
"\n",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"elapsed",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"\n\n",
"imageDigest",
",",
"err",
":=",
"getImageDigest",
"(",
"img",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Image",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"path",
",",
"err",
":=",
"getExtractPathForName",
"(",
"RemoveTag",
"(",
"imageName",
")",
"+",
"\"",
"\"",
"+",
"imageDigest",
".",
"String",
"(",
")",
",",
"cacheDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"Image",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"// extract fs into provided dir",
"if",
"err",
":=",
"GetFileSystemForImage",
"(",
"img",
",",
"path",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"Image",
"{",
"FSPath",
":",
"path",
",",
"Layers",
":",
"layers",
",",
"}",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"Image",
"{",
"Image",
":",
"img",
",",
"Source",
":",
"imageName",
",",
"FSPath",
":",
"path",
",",
"Digest",
":",
"imageDigest",
",",
"Layers",
":",
"layers",
",",
"}",
",",
"nil",
"\n",
"}"
] | // GetImage infers the source of an image and retrieves a v1.Image reference to it.
// Once a reference is obtained, it attempts to unpack the v1.Image's reader's contents
// into a temp directory on the local filesystem. | [
"GetImage",
"infers",
"the",
"source",
"of",
"an",
"image",
"and",
"retrieves",
"a",
"v1",
".",
"Image",
"reference",
"to",
"it",
".",
"Once",
"a",
"reference",
"is",
"obtained",
"it",
"attempts",
"to",
"unpack",
"the",
"v1",
".",
"Image",
"s",
"reader",
"s",
"contents",
"into",
"a",
"temp",
"directory",
"on",
"the",
"local",
"filesystem",
"."
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/image_utils.go#L78-L182 |
GoogleContainerTools/container-diff | pkg/util/image_utils.go | GetFileSystemForLayer | func GetFileSystemForLayer(layer v1.Layer, root string, whitelist []string) error {
empty, err := DirIsEmpty(root)
if err != nil {
return err
}
if !empty {
logrus.Infof("using cached filesystem in %s", root)
return nil
}
contents, err := layer.Uncompressed()
if err != nil {
return err
}
return unpackTar(tar.NewReader(contents), root, whitelist)
} | go | func GetFileSystemForLayer(layer v1.Layer, root string, whitelist []string) error {
empty, err := DirIsEmpty(root)
if err != nil {
return err
}
if !empty {
logrus.Infof("using cached filesystem in %s", root)
return nil
}
contents, err := layer.Uncompressed()
if err != nil {
return err
}
return unpackTar(tar.NewReader(contents), root, whitelist)
} | [
"func",
"GetFileSystemForLayer",
"(",
"layer",
"v1",
".",
"Layer",
",",
"root",
"string",
",",
"whitelist",
"[",
"]",
"string",
")",
"error",
"{",
"empty",
",",
"err",
":=",
"DirIsEmpty",
"(",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"empty",
"{",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"root",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"contents",
",",
"err",
":=",
"layer",
".",
"Uncompressed",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"unpackTar",
"(",
"tar",
".",
"NewReader",
"(",
"contents",
")",
",",
"root",
",",
"whitelist",
")",
"\n",
"}"
] | // GetFileSystemForLayer unpacks a layer to local disk | [
"GetFileSystemForLayer",
"unpacks",
"a",
"layer",
"to",
"local",
"disk"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/image_utils.go#L244-L258 |
GoogleContainerTools/container-diff | pkg/util/image_utils.go | GetFileSystemForImage | func GetFileSystemForImage(image v1.Image, root string, whitelist []string) error {
empty, err := DirIsEmpty(root)
if err != nil {
return err
}
if !empty {
logrus.Infof("using cached filesystem in %s", root)
return nil
}
if err := unpackTar(tar.NewReader(mutate.Extract(image)), root, whitelist); err != nil {
return err
}
return nil
} | go | func GetFileSystemForImage(image v1.Image, root string, whitelist []string) error {
empty, err := DirIsEmpty(root)
if err != nil {
return err
}
if !empty {
logrus.Infof("using cached filesystem in %s", root)
return nil
}
if err := unpackTar(tar.NewReader(mutate.Extract(image)), root, whitelist); err != nil {
return err
}
return nil
} | [
"func",
"GetFileSystemForImage",
"(",
"image",
"v1",
".",
"Image",
",",
"root",
"string",
",",
"whitelist",
"[",
"]",
"string",
")",
"error",
"{",
"empty",
",",
"err",
":=",
"DirIsEmpty",
"(",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"empty",
"{",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
",",
"root",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"unpackTar",
"(",
"tar",
".",
"NewReader",
"(",
"mutate",
".",
"Extract",
"(",
"image",
")",
")",
",",
"root",
",",
"whitelist",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // unpack image filesystem to local disk
// if provided directory is not empty, do nothing | [
"unpack",
"image",
"filesystem",
"to",
"local",
"disk",
"if",
"provided",
"directory",
"is",
"not",
"empty",
"do",
"nothing"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/image_utils.go#L262-L275 |
GoogleContainerTools/container-diff | pkg/util/image_utils.go | HasTag | func HasTag(image string) bool {
tagRegex := regexp.MustCompile(tagRegexStr)
return tagRegex.MatchString(image)
} | go | func HasTag(image string) bool {
tagRegex := regexp.MustCompile(tagRegexStr)
return tagRegex.MatchString(image)
} | [
"func",
"HasTag",
"(",
"image",
"string",
")",
"bool",
"{",
"tagRegex",
":=",
"regexp",
".",
"MustCompile",
"(",
"tagRegexStr",
")",
"\n",
"return",
"tagRegex",
".",
"MatchString",
"(",
"image",
")",
"\n",
"}"
] | // checks to see if an image string contains a tag. | [
"checks",
"to",
"see",
"if",
"an",
"image",
"string",
"contains",
"a",
"tag",
"."
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/image_utils.go#L320-L323 |
GoogleContainerTools/container-diff | pkg/util/image_utils.go | RemoveTag | func RemoveTag(image string) string {
if !HasTag(image) {
return image
}
tagRegex := regexp.MustCompile(tagRegexStr)
parts := tagRegex.FindStringSubmatch(image)
tag := parts[len(parts)-1]
return image[0 : len(image)-len(tag)-1]
} | go | func RemoveTag(image string) string {
if !HasTag(image) {
return image
}
tagRegex := regexp.MustCompile(tagRegexStr)
parts := tagRegex.FindStringSubmatch(image)
tag := parts[len(parts)-1]
return image[0 : len(image)-len(tag)-1]
} | [
"func",
"RemoveTag",
"(",
"image",
"string",
")",
"string",
"{",
"if",
"!",
"HasTag",
"(",
"image",
")",
"{",
"return",
"image",
"\n",
"}",
"\n",
"tagRegex",
":=",
"regexp",
".",
"MustCompile",
"(",
"tagRegexStr",
")",
"\n",
"parts",
":=",
"tagRegex",
".",
"FindStringSubmatch",
"(",
"image",
")",
"\n",
"tag",
":=",
"parts",
"[",
"len",
"(",
"parts",
")",
"-",
"1",
"]",
"\n",
"return",
"image",
"[",
"0",
":",
"len",
"(",
"image",
")",
"-",
"len",
"(",
"tag",
")",
"-",
"1",
"]",
"\n",
"}"
] | // returns a raw image name with the tag removed | [
"returns",
"a",
"raw",
"image",
"name",
"with",
"the",
"tag",
"removed"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/image_utils.go#L326-L334 |
GoogleContainerTools/container-diff | cmd/root.go | Set | func (d *diffTypes) Set(value string) error {
// Dedupe repeated elements.
for _, t := range *d {
if t == value {
return nil
}
}
*d = append(*d, value)
return nil
} | go | func (d *diffTypes) Set(value string) error {
// Dedupe repeated elements.
for _, t := range *d {
if t == value {
return nil
}
}
*d = append(*d, value)
return nil
} | [
"func",
"(",
"d",
"*",
"diffTypes",
")",
"Set",
"(",
"value",
"string",
")",
"error",
"{",
"// Dedupe repeated elements.",
"for",
"_",
",",
"t",
":=",
"range",
"*",
"d",
"{",
"if",
"t",
"==",
"value",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"*",
"d",
"=",
"append",
"(",
"*",
"d",
",",
"value",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // The second method is Set(value string) error | [
"The",
"second",
"method",
"is",
"Set",
"(",
"value",
"string",
")",
"error"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/cmd/root.go#L210-L219 |
GoogleContainerTools/container-diff | util/diff_utils.go | GetAdditions | func GetAdditions(a, b []string) []string {
matcher := difflib.NewMatcher(a, b)
differences := matcher.GetGroupedOpCodes(0)
adds := []string{}
for _, group := range differences {
for _, opCode := range group {
j1, j2 := opCode.J1, opCode.J2
if opCode.Tag == 'r' || opCode.Tag == 'i' {
for _, line := range b[j1:j2] {
adds = append(adds, line)
}
}
}
}
return adds
} | go | func GetAdditions(a, b []string) []string {
matcher := difflib.NewMatcher(a, b)
differences := matcher.GetGroupedOpCodes(0)
adds := []string{}
for _, group := range differences {
for _, opCode := range group {
j1, j2 := opCode.J1, opCode.J2
if opCode.Tag == 'r' || opCode.Tag == 'i' {
for _, line := range b[j1:j2] {
adds = append(adds, line)
}
}
}
}
return adds
} | [
"func",
"GetAdditions",
"(",
"a",
",",
"b",
"[",
"]",
"string",
")",
"[",
"]",
"string",
"{",
"matcher",
":=",
"difflib",
".",
"NewMatcher",
"(",
"a",
",",
"b",
")",
"\n",
"differences",
":=",
"matcher",
".",
"GetGroupedOpCodes",
"(",
"0",
")",
"\n\n",
"adds",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"group",
":=",
"range",
"differences",
"{",
"for",
"_",
",",
"opCode",
":=",
"range",
"group",
"{",
"j1",
",",
"j2",
":=",
"opCode",
".",
"J1",
",",
"opCode",
".",
"J2",
"\n",
"if",
"opCode",
".",
"Tag",
"==",
"'r'",
"||",
"opCode",
".",
"Tag",
"==",
"'i'",
"{",
"for",
"_",
",",
"line",
":=",
"range",
"b",
"[",
"j1",
":",
"j2",
"]",
"{",
"adds",
"=",
"append",
"(",
"adds",
",",
"line",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"adds",
"\n",
"}"
] | // Modification of difflib's unified differ | [
"Modification",
"of",
"difflib",
"s",
"unified",
"differ"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/util/diff_utils.go#L54-L70 |
GoogleContainerTools/container-diff | util/diff_utils.go | DiffDirectory | func DiffDirectory(d1, d2 pkgutil.Directory) (DirDiff, bool) {
adds := GetAddedEntries(d1, d2)
sort.Strings(adds)
addedEntries := pkgutil.CreateDirectoryEntries(d2.Root, adds)
dels := GetDeletedEntries(d1, d2)
sort.Strings(dels)
deletedEntries := pkgutil.CreateDirectoryEntries(d1.Root, dels)
mods := GetModifiedEntries(d1, d2)
sort.Strings(mods)
modifiedEntries := createEntryDiffs(d1.Root, d2.Root, mods)
var same bool
if len(adds) == 0 && len(dels) == 0 && len(mods) == 0 {
same = true
} else {
same = false
}
return DirDiff{addedEntries, deletedEntries, modifiedEntries}, same
} | go | func DiffDirectory(d1, d2 pkgutil.Directory) (DirDiff, bool) {
adds := GetAddedEntries(d1, d2)
sort.Strings(adds)
addedEntries := pkgutil.CreateDirectoryEntries(d2.Root, adds)
dels := GetDeletedEntries(d1, d2)
sort.Strings(dels)
deletedEntries := pkgutil.CreateDirectoryEntries(d1.Root, dels)
mods := GetModifiedEntries(d1, d2)
sort.Strings(mods)
modifiedEntries := createEntryDiffs(d1.Root, d2.Root, mods)
var same bool
if len(adds) == 0 && len(dels) == 0 && len(mods) == 0 {
same = true
} else {
same = false
}
return DirDiff{addedEntries, deletedEntries, modifiedEntries}, same
} | [
"func",
"DiffDirectory",
"(",
"d1",
",",
"d2",
"pkgutil",
".",
"Directory",
")",
"(",
"DirDiff",
",",
"bool",
")",
"{",
"adds",
":=",
"GetAddedEntries",
"(",
"d1",
",",
"d2",
")",
"\n",
"sort",
".",
"Strings",
"(",
"adds",
")",
"\n",
"addedEntries",
":=",
"pkgutil",
".",
"CreateDirectoryEntries",
"(",
"d2",
".",
"Root",
",",
"adds",
")",
"\n\n",
"dels",
":=",
"GetDeletedEntries",
"(",
"d1",
",",
"d2",
")",
"\n",
"sort",
".",
"Strings",
"(",
"dels",
")",
"\n",
"deletedEntries",
":=",
"pkgutil",
".",
"CreateDirectoryEntries",
"(",
"d1",
".",
"Root",
",",
"dels",
")",
"\n\n",
"mods",
":=",
"GetModifiedEntries",
"(",
"d1",
",",
"d2",
")",
"\n",
"sort",
".",
"Strings",
"(",
"mods",
")",
"\n",
"modifiedEntries",
":=",
"createEntryDiffs",
"(",
"d1",
".",
"Root",
",",
"d2",
".",
"Root",
",",
"mods",
")",
"\n\n",
"var",
"same",
"bool",
"\n",
"if",
"len",
"(",
"adds",
")",
"==",
"0",
"&&",
"len",
"(",
"dels",
")",
"==",
"0",
"&&",
"len",
"(",
"mods",
")",
"==",
"0",
"{",
"same",
"=",
"true",
"\n",
"}",
"else",
"{",
"same",
"=",
"false",
"\n",
"}",
"\n\n",
"return",
"DirDiff",
"{",
"addedEntries",
",",
"deletedEntries",
",",
"modifiedEntries",
"}",
",",
"same",
"\n",
"}"
] | // DiffDirectory takes the diff of two directories, assuming both are completely unpacked | [
"DiffDirectory",
"takes",
"the",
"diff",
"of",
"two",
"directories",
"assuming",
"both",
"are",
"completely",
"unpacked"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/util/diff_utils.go#L108-L129 |
GoogleContainerTools/container-diff | util/diff_utils.go | GetModifiedEntries | func GetModifiedEntries(d1, d2 pkgutil.Directory) []string {
d1files := d1.Content
d2files := d2.Content
filematches := GetMatches(d1files, d2files)
modified := []string{}
for _, f := range filematches {
f1path := fmt.Sprintf("%s%s", d1.Root, f)
f2path := fmt.Sprintf("%s%s", d2.Root, f)
f1stat, err := os.Lstat(f1path)
if err != nil {
logrus.Errorf("Error checking directory entry %s: %s\n", f, err)
continue
}
f2stat, err := os.Lstat(f2path)
if err != nil {
logrus.Errorf("Error checking directory entry %s: %s\n", f, err)
continue
}
// If the directory entry is a symlink, make sure the symlinks point to the same place
if f1stat.Mode()&os.ModeSymlink != 0 && f2stat.Mode()&os.ModeSymlink != 0 {
same, err := pkgutil.CheckSameSymlink(f1path, f2path)
if err != nil {
logrus.Errorf("Error determining if symlink %s and %s are equivalent: %s\n", f1path, f2path, err)
continue
}
if !same {
modified = append(modified, f)
}
continue
}
// If the directory entry in question is a tar, verify that the two have the same size
if pkgutil.IsTar(f1path) {
if f1stat.Size() != f2stat.Size() {
modified = append(modified, f)
}
continue
}
// If the directory entry is not a tar and not a directory, then it's a file so make sure the file contents are the same
// Note: We skip over directory entries because to compare directories, we compare their contents
if !f1stat.IsDir() {
same, err := pkgutil.CheckSameFile(f1path, f2path)
if err != nil {
logrus.Errorf("Error diffing contents of %s and %s: %s\n", f1path, f2path, err)
continue
}
if !same {
modified = append(modified, f)
}
}
}
return modified
} | go | func GetModifiedEntries(d1, d2 pkgutil.Directory) []string {
d1files := d1.Content
d2files := d2.Content
filematches := GetMatches(d1files, d2files)
modified := []string{}
for _, f := range filematches {
f1path := fmt.Sprintf("%s%s", d1.Root, f)
f2path := fmt.Sprintf("%s%s", d2.Root, f)
f1stat, err := os.Lstat(f1path)
if err != nil {
logrus.Errorf("Error checking directory entry %s: %s\n", f, err)
continue
}
f2stat, err := os.Lstat(f2path)
if err != nil {
logrus.Errorf("Error checking directory entry %s: %s\n", f, err)
continue
}
// If the directory entry is a symlink, make sure the symlinks point to the same place
if f1stat.Mode()&os.ModeSymlink != 0 && f2stat.Mode()&os.ModeSymlink != 0 {
same, err := pkgutil.CheckSameSymlink(f1path, f2path)
if err != nil {
logrus.Errorf("Error determining if symlink %s and %s are equivalent: %s\n", f1path, f2path, err)
continue
}
if !same {
modified = append(modified, f)
}
continue
}
// If the directory entry in question is a tar, verify that the two have the same size
if pkgutil.IsTar(f1path) {
if f1stat.Size() != f2stat.Size() {
modified = append(modified, f)
}
continue
}
// If the directory entry is not a tar and not a directory, then it's a file so make sure the file contents are the same
// Note: We skip over directory entries because to compare directories, we compare their contents
if !f1stat.IsDir() {
same, err := pkgutil.CheckSameFile(f1path, f2path)
if err != nil {
logrus.Errorf("Error diffing contents of %s and %s: %s\n", f1path, f2path, err)
continue
}
if !same {
modified = append(modified, f)
}
}
}
return modified
} | [
"func",
"GetModifiedEntries",
"(",
"d1",
",",
"d2",
"pkgutil",
".",
"Directory",
")",
"[",
"]",
"string",
"{",
"d1files",
":=",
"d1",
".",
"Content",
"\n",
"d2files",
":=",
"d2",
".",
"Content",
"\n\n",
"filematches",
":=",
"GetMatches",
"(",
"d1files",
",",
"d2files",
")",
"\n\n",
"modified",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"filematches",
"{",
"f1path",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"d1",
".",
"Root",
",",
"f",
")",
"\n",
"f2path",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"d2",
".",
"Root",
",",
"f",
")",
"\n\n",
"f1stat",
",",
"err",
":=",
"os",
".",
"Lstat",
"(",
"f1path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"f",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"f2stat",
",",
"err",
":=",
"os",
".",
"Lstat",
"(",
"f2path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"f",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// If the directory entry is a symlink, make sure the symlinks point to the same place",
"if",
"f1stat",
".",
"Mode",
"(",
")",
"&",
"os",
".",
"ModeSymlink",
"!=",
"0",
"&&",
"f2stat",
".",
"Mode",
"(",
")",
"&",
"os",
".",
"ModeSymlink",
"!=",
"0",
"{",
"same",
",",
"err",
":=",
"pkgutil",
".",
"CheckSameSymlink",
"(",
"f1path",
",",
"f2path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"f1path",
",",
"f2path",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"same",
"{",
"modified",
"=",
"append",
"(",
"modified",
",",
"f",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// If the directory entry in question is a tar, verify that the two have the same size",
"if",
"pkgutil",
".",
"IsTar",
"(",
"f1path",
")",
"{",
"if",
"f1stat",
".",
"Size",
"(",
")",
"!=",
"f2stat",
".",
"Size",
"(",
")",
"{",
"modified",
"=",
"append",
"(",
"modified",
",",
"f",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// If the directory entry is not a tar and not a directory, then it's a file so make sure the file contents are the same",
"// Note: We skip over directory entries because to compare directories, we compare their contents",
"if",
"!",
"f1stat",
".",
"IsDir",
"(",
")",
"{",
"same",
",",
"err",
":=",
"pkgutil",
".",
"CheckSameFile",
"(",
"f1path",
",",
"f2path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"f1path",
",",
"f2path",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"same",
"{",
"modified",
"=",
"append",
"(",
"modified",
",",
"f",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"modified",
"\n",
"}"
] | // Checks for content differences between files of the same name from different directories | [
"Checks",
"for",
"content",
"differences",
"between",
"files",
"of",
"the",
"same",
"name",
"from",
"different",
"directories"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/util/diff_utils.go#L190-L247 |
GoogleContainerTools/container-diff | pkg/util/fs_utils.go | GetFileContents | func GetFileContents(path string) (*string, error) {
if _, err := os.Stat(path); os.IsNotExist(err) {
return nil, err
}
contents, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
strContents := string(contents)
//If file is empty, return nil
if strContents == "" {
return nil, nil
}
return &strContents, nil
} | go | func GetFileContents(path string) (*string, error) {
if _, err := os.Stat(path); os.IsNotExist(err) {
return nil, err
}
contents, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
strContents := string(contents)
//If file is empty, return nil
if strContents == "" {
return nil, nil
}
return &strContents, nil
} | [
"func",
"GetFileContents",
"(",
"path",
"string",
")",
"(",
"*",
"string",
",",
"error",
")",
"{",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"path",
")",
";",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"contents",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"strContents",
":=",
"string",
"(",
"contents",
")",
"\n",
"//If file is empty, return nil",
"if",
"strContents",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"strContents",
",",
"nil",
"\n",
"}"
] | //GetFileContents returns the contents of a file at the specified path | [
"GetFileContents",
"returns",
"the",
"contents",
"of",
"a",
"file",
"at",
"the",
"specified",
"path"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/fs_utils.go#L58-L74 |
GoogleContainerTools/container-diff | pkg/util/fs_utils.go | GetDirectory | func GetDirectory(path string, deep bool) (Directory, error) {
var directory Directory
directory.Root = path
var err error
if deep {
walkFn := func(currPath string, info os.FileInfo, err error) error {
newContent := strings.TrimPrefix(currPath, directory.Root)
if newContent != "" {
directory.Content = append(directory.Content, newContent)
}
return nil
}
err = filepath.Walk(path, walkFn)
} else {
contents, err := ioutil.ReadDir(path)
if err != nil {
return directory, err
}
for _, file := range contents {
fileName := "/" + file.Name()
directory.Content = append(directory.Content, fileName)
}
}
return directory, err
} | go | func GetDirectory(path string, deep bool) (Directory, error) {
var directory Directory
directory.Root = path
var err error
if deep {
walkFn := func(currPath string, info os.FileInfo, err error) error {
newContent := strings.TrimPrefix(currPath, directory.Root)
if newContent != "" {
directory.Content = append(directory.Content, newContent)
}
return nil
}
err = filepath.Walk(path, walkFn)
} else {
contents, err := ioutil.ReadDir(path)
if err != nil {
return directory, err
}
for _, file := range contents {
fileName := "/" + file.Name()
directory.Content = append(directory.Content, fileName)
}
}
return directory, err
} | [
"func",
"GetDirectory",
"(",
"path",
"string",
",",
"deep",
"bool",
")",
"(",
"Directory",
",",
"error",
")",
"{",
"var",
"directory",
"Directory",
"\n",
"directory",
".",
"Root",
"=",
"path",
"\n",
"var",
"err",
"error",
"\n",
"if",
"deep",
"{",
"walkFn",
":=",
"func",
"(",
"currPath",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"newContent",
":=",
"strings",
".",
"TrimPrefix",
"(",
"currPath",
",",
"directory",
".",
"Root",
")",
"\n",
"if",
"newContent",
"!=",
"\"",
"\"",
"{",
"directory",
".",
"Content",
"=",
"append",
"(",
"directory",
".",
"Content",
",",
"newContent",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"err",
"=",
"filepath",
".",
"Walk",
"(",
"path",
",",
"walkFn",
")",
"\n",
"}",
"else",
"{",
"contents",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"directory",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"file",
":=",
"range",
"contents",
"{",
"fileName",
":=",
"\"",
"\"",
"+",
"file",
".",
"Name",
"(",
")",
"\n",
"directory",
".",
"Content",
"=",
"append",
"(",
"directory",
".",
"Content",
",",
"fileName",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"directory",
",",
"err",
"\n",
"}"
] | // GetDirectoryContents converts the directory starting at the provided path into a Directory struct. | [
"GetDirectoryContents",
"converts",
"the",
"directory",
"starting",
"at",
"the",
"provided",
"path",
"into",
"a",
"Directory",
"struct",
"."
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/fs_utils.go#L88-L114 |
GoogleContainerTools/container-diff | pkg/util/fs_utils.go | HasFilepathPrefix | func HasFilepathPrefix(path, prefix string) bool {
path = filepath.Clean(path)
prefix = filepath.Clean(prefix)
pathArray := strings.Split(path, "/")
prefixArray := strings.Split(prefix, "/")
if len(pathArray) < len(prefixArray) {
return false
}
for index := range prefixArray {
if prefixArray[index] == pathArray[index] {
continue
}
return false
}
return true
} | go | func HasFilepathPrefix(path, prefix string) bool {
path = filepath.Clean(path)
prefix = filepath.Clean(prefix)
pathArray := strings.Split(path, "/")
prefixArray := strings.Split(prefix, "/")
if len(pathArray) < len(prefixArray) {
return false
}
for index := range prefixArray {
if prefixArray[index] == pathArray[index] {
continue
}
return false
}
return true
} | [
"func",
"HasFilepathPrefix",
"(",
"path",
",",
"prefix",
"string",
")",
"bool",
"{",
"path",
"=",
"filepath",
".",
"Clean",
"(",
"path",
")",
"\n",
"prefix",
"=",
"filepath",
".",
"Clean",
"(",
"prefix",
")",
"\n",
"pathArray",
":=",
"strings",
".",
"Split",
"(",
"path",
",",
"\"",
"\"",
")",
"\n",
"prefixArray",
":=",
"strings",
".",
"Split",
"(",
"prefix",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"len",
"(",
"pathArray",
")",
"<",
"len",
"(",
"prefixArray",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"index",
":=",
"range",
"prefixArray",
"{",
"if",
"prefixArray",
"[",
"index",
"]",
"==",
"pathArray",
"[",
"index",
"]",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // HasFilepathPrefix checks if the given file path begins with prefix | [
"HasFilepathPrefix",
"checks",
"if",
"the",
"given",
"file",
"path",
"begins",
"with",
"prefix"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/fs_utils.go#L178-L194 |
GoogleContainerTools/container-diff | pkg/util/fs_utils.go | CleanFilePath | func CleanFilePath(dirtyPath string) string {
var windowsReplacements = []string{"<", "_", ">", "_", ":", "_", "?", "_", "*", "_", "?", "_", "|", "_"}
replacer := strings.NewReplacer(windowsReplacements...)
return filepath.Clean(replacer.Replace(dirtyPath))
} | go | func CleanFilePath(dirtyPath string) string {
var windowsReplacements = []string{"<", "_", ">", "_", ":", "_", "?", "_", "*", "_", "?", "_", "|", "_"}
replacer := strings.NewReplacer(windowsReplacements...)
return filepath.Clean(replacer.Replace(dirtyPath))
} | [
"func",
"CleanFilePath",
"(",
"dirtyPath",
"string",
")",
"string",
"{",
"var",
"windowsReplacements",
"=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"replacer",
":=",
"strings",
".",
"NewReplacer",
"(",
"windowsReplacements",
"...",
")",
"\n",
"return",
"filepath",
".",
"Clean",
"(",
"replacer",
".",
"Replace",
"(",
"dirtyPath",
")",
")",
"\n",
"}"
] | // CleanFilePath removes characters from a given path that cannot be used
// in paths by the underlying platform (e.g. Windows) | [
"CleanFilePath",
"removes",
"characters",
"from",
"a",
"given",
"path",
"that",
"cannot",
"be",
"used",
"in",
"paths",
"by",
"the",
"underlying",
"platform",
"(",
"e",
".",
"g",
".",
"Windows",
")"
] | train | https://github.com/GoogleContainerTools/container-diff/blob/a62c5163a8a12073631fddd972570e5559476e24/pkg/util/fs_utils.go#L213-L217 |
Unknwon/com | path.go | GetSrcPath | func GetSrcPath(importPath string) (appPath string, err error) {
paths := GetGOPATHs()
for _, p := range paths {
if IsExist(p + "/src/" + importPath + "/") {
appPath = p + "/src/" + importPath + "/"
break
}
}
if len(appPath) == 0 {
return "", errors.New("Unable to locate source folder path")
}
appPath = filepath.Dir(appPath) + "/"
if runtime.GOOS == "windows" {
// Replace all '\' to '/'.
appPath = strings.Replace(appPath, "\\", "/", -1)
}
return appPath, nil
} | go | func GetSrcPath(importPath string) (appPath string, err error) {
paths := GetGOPATHs()
for _, p := range paths {
if IsExist(p + "/src/" + importPath + "/") {
appPath = p + "/src/" + importPath + "/"
break
}
}
if len(appPath) == 0 {
return "", errors.New("Unable to locate source folder path")
}
appPath = filepath.Dir(appPath) + "/"
if runtime.GOOS == "windows" {
// Replace all '\' to '/'.
appPath = strings.Replace(appPath, "\\", "/", -1)
}
return appPath, nil
} | [
"func",
"GetSrcPath",
"(",
"importPath",
"string",
")",
"(",
"appPath",
"string",
",",
"err",
"error",
")",
"{",
"paths",
":=",
"GetGOPATHs",
"(",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"paths",
"{",
"if",
"IsExist",
"(",
"p",
"+",
"\"",
"\"",
"+",
"importPath",
"+",
"\"",
"\"",
")",
"{",
"appPath",
"=",
"p",
"+",
"\"",
"\"",
"+",
"importPath",
"+",
"\"",
"\"",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"appPath",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"appPath",
"=",
"filepath",
".",
"Dir",
"(",
"appPath",
")",
"+",
"\"",
"\"",
"\n",
"if",
"runtime",
".",
"GOOS",
"==",
"\"",
"\"",
"{",
"// Replace all '\\' to '/'.",
"appPath",
"=",
"strings",
".",
"Replace",
"(",
"appPath",
",",
"\"",
"\\\\",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"}",
"\n\n",
"return",
"appPath",
",",
"nil",
"\n",
"}"
] | // GetSrcPath returns app. source code path.
// It only works when you have src. folder in GOPATH,
// it returns error not able to locate source folder path. | [
"GetSrcPath",
"returns",
"app",
".",
"source",
"code",
"path",
".",
"It",
"only",
"works",
"when",
"you",
"have",
"src",
".",
"folder",
"in",
"GOPATH",
"it",
"returns",
"error",
"not",
"able",
"to",
"locate",
"source",
"folder",
"path",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/path.go#L41-L61 |
Unknwon/com | cmd.go | getColorLevel | func getColorLevel(level string) string {
level = strings.ToUpper(level)
switch level {
case "TRAC":
return fmt.Sprintf("\033[%dm%s\033[0m", Blue, level)
case "ERRO":
return fmt.Sprintf("\033[%dm%s\033[0m", Red, level)
case "WARN":
return fmt.Sprintf("\033[%dm%s\033[0m", Magenta, level)
case "SUCC":
return fmt.Sprintf("\033[%dm%s\033[0m", Green, level)
default:
return level
}
} | go | func getColorLevel(level string) string {
level = strings.ToUpper(level)
switch level {
case "TRAC":
return fmt.Sprintf("\033[%dm%s\033[0m", Blue, level)
case "ERRO":
return fmt.Sprintf("\033[%dm%s\033[0m", Red, level)
case "WARN":
return fmt.Sprintf("\033[%dm%s\033[0m", Magenta, level)
case "SUCC":
return fmt.Sprintf("\033[%dm%s\033[0m", Green, level)
default:
return level
}
} | [
"func",
"getColorLevel",
"(",
"level",
"string",
")",
"string",
"{",
"level",
"=",
"strings",
".",
"ToUpper",
"(",
"level",
")",
"\n",
"switch",
"level",
"{",
"case",
"\"",
"\"",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\033",
"\\033",
"\"",
",",
"Blue",
",",
"level",
")",
"\n",
"case",
"\"",
"\"",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\033",
"\\033",
"\"",
",",
"Red",
",",
"level",
")",
"\n",
"case",
"\"",
"\"",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\033",
"\\033",
"\"",
",",
"Magenta",
",",
"level",
")",
"\n",
"case",
"\"",
"\"",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\033",
"\\033",
"\"",
",",
"Green",
",",
"level",
")",
"\n",
"default",
":",
"return",
"level",
"\n",
"}",
"\n",
"}"
] | // getColorLevel returns colored level string by given level. | [
"getColorLevel",
"returns",
"colored",
"level",
"string",
"by",
"given",
"level",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/cmd.go#L82-L96 |
Unknwon/com | cmd.go | ColorLogS | func ColorLogS(format string, a ...interface{}) string {
log := fmt.Sprintf(format, a...)
var clog string
if runtime.GOOS != "windows" {
// Level.
i := strings.Index(log, "]")
if log[0] == '[' && i > -1 {
clog += "[" + getColorLevel(log[1:i]) + "]"
}
log = log[i+1:]
// Error.
log = strings.Replace(log, "[ ", fmt.Sprintf("[\033[%dm", Red), -1)
log = strings.Replace(log, " ]", EndColor+"]", -1)
// Path.
log = strings.Replace(log, "( ", fmt.Sprintf("(\033[%dm", Yellow), -1)
log = strings.Replace(log, " )", EndColor+")", -1)
// Highlights.
log = strings.Replace(log, "# ", fmt.Sprintf("\033[%dm", Gray), -1)
log = strings.Replace(log, " #", EndColor, -1)
} else {
// Level.
i := strings.Index(log, "]")
if log[0] == '[' && i > -1 {
clog += "[" + log[1:i] + "]"
}
log = log[i+1:]
// Error.
log = strings.Replace(log, "[ ", "[", -1)
log = strings.Replace(log, " ]", "]", -1)
// Path.
log = strings.Replace(log, "( ", "(", -1)
log = strings.Replace(log, " )", ")", -1)
// Highlights.
log = strings.Replace(log, "# ", "", -1)
log = strings.Replace(log, " #", "", -1)
}
return clog + log
} | go | func ColorLogS(format string, a ...interface{}) string {
log := fmt.Sprintf(format, a...)
var clog string
if runtime.GOOS != "windows" {
// Level.
i := strings.Index(log, "]")
if log[0] == '[' && i > -1 {
clog += "[" + getColorLevel(log[1:i]) + "]"
}
log = log[i+1:]
// Error.
log = strings.Replace(log, "[ ", fmt.Sprintf("[\033[%dm", Red), -1)
log = strings.Replace(log, " ]", EndColor+"]", -1)
// Path.
log = strings.Replace(log, "( ", fmt.Sprintf("(\033[%dm", Yellow), -1)
log = strings.Replace(log, " )", EndColor+")", -1)
// Highlights.
log = strings.Replace(log, "# ", fmt.Sprintf("\033[%dm", Gray), -1)
log = strings.Replace(log, " #", EndColor, -1)
} else {
// Level.
i := strings.Index(log, "]")
if log[0] == '[' && i > -1 {
clog += "[" + log[1:i] + "]"
}
log = log[i+1:]
// Error.
log = strings.Replace(log, "[ ", "[", -1)
log = strings.Replace(log, " ]", "]", -1)
// Path.
log = strings.Replace(log, "( ", "(", -1)
log = strings.Replace(log, " )", ")", -1)
// Highlights.
log = strings.Replace(log, "# ", "", -1)
log = strings.Replace(log, " #", "", -1)
}
return clog + log
} | [
"func",
"ColorLogS",
"(",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"string",
"{",
"log",
":=",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"a",
"...",
")",
"\n\n",
"var",
"clog",
"string",
"\n\n",
"if",
"runtime",
".",
"GOOS",
"!=",
"\"",
"\"",
"{",
"// Level.",
"i",
":=",
"strings",
".",
"Index",
"(",
"log",
",",
"\"",
"\"",
")",
"\n",
"if",
"log",
"[",
"0",
"]",
"==",
"'['",
"&&",
"i",
">",
"-",
"1",
"{",
"clog",
"+=",
"\"",
"\"",
"+",
"getColorLevel",
"(",
"log",
"[",
"1",
":",
"i",
"]",
")",
"+",
"\"",
"\"",
"\n",
"}",
"\n\n",
"log",
"=",
"log",
"[",
"i",
"+",
"1",
":",
"]",
"\n\n",
"// Error.",
"log",
"=",
"strings",
".",
"Replace",
"(",
"log",
",",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\033",
"\"",
",",
"Red",
")",
",",
"-",
"1",
")",
"\n",
"log",
"=",
"strings",
".",
"Replace",
"(",
"log",
",",
"\"",
"\"",
",",
"EndColor",
"+",
"\"",
"\"",
",",
"-",
"1",
")",
"\n\n",
"// Path.",
"log",
"=",
"strings",
".",
"Replace",
"(",
"log",
",",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\033",
"\"",
",",
"Yellow",
")",
",",
"-",
"1",
")",
"\n",
"log",
"=",
"strings",
".",
"Replace",
"(",
"log",
",",
"\"",
"\"",
",",
"EndColor",
"+",
"\"",
"\"",
",",
"-",
"1",
")",
"\n\n",
"// Highlights.",
"log",
"=",
"strings",
".",
"Replace",
"(",
"log",
",",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\033",
"\"",
",",
"Gray",
")",
",",
"-",
"1",
")",
"\n",
"log",
"=",
"strings",
".",
"Replace",
"(",
"log",
",",
"\"",
"\"",
",",
"EndColor",
",",
"-",
"1",
")",
"\n\n",
"}",
"else",
"{",
"// Level.",
"i",
":=",
"strings",
".",
"Index",
"(",
"log",
",",
"\"",
"\"",
")",
"\n",
"if",
"log",
"[",
"0",
"]",
"==",
"'['",
"&&",
"i",
">",
"-",
"1",
"{",
"clog",
"+=",
"\"",
"\"",
"+",
"log",
"[",
"1",
":",
"i",
"]",
"+",
"\"",
"\"",
"\n",
"}",
"\n\n",
"log",
"=",
"log",
"[",
"i",
"+",
"1",
":",
"]",
"\n\n",
"// Error.",
"log",
"=",
"strings",
".",
"Replace",
"(",
"log",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"log",
"=",
"strings",
".",
"Replace",
"(",
"log",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n\n",
"// Path.",
"log",
"=",
"strings",
".",
"Replace",
"(",
"log",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"log",
"=",
"strings",
".",
"Replace",
"(",
"log",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n\n",
"// Highlights.",
"log",
"=",
"strings",
".",
"Replace",
"(",
"log",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"log",
"=",
"strings",
".",
"Replace",
"(",
"log",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"}",
"\n",
"return",
"clog",
"+",
"log",
"\n",
"}"
] | // ColorLogS colors log and return colored content.
// Log format: <level> <content [highlight][path]> [ error ].
// Level: TRAC -> blue; ERRO -> red; WARN -> Magenta; SUCC -> green; others -> default.
// Content: default; path: yellow; error -> red.
// Level has to be surrounded by "[" and "]".
// Highlights have to be surrounded by "# " and " #"(space), "#" will be deleted.
// Paths have to be surrounded by "( " and " )"(space).
// Errors have to be surrounded by "[ " and " ]"(space).
// Note: it hasn't support windows yet, contribute is welcome. | [
"ColorLogS",
"colors",
"log",
"and",
"return",
"colored",
"content",
".",
"Log",
"format",
":",
"<level",
">",
"<content",
"[",
"highlight",
"]",
"[",
"path",
"]",
">",
"[",
"error",
"]",
".",
"Level",
":",
"TRAC",
"-",
">",
"blue",
";",
"ERRO",
"-",
">",
"red",
";",
"WARN",
"-",
">",
"Magenta",
";",
"SUCC",
"-",
">",
"green",
";",
"others",
"-",
">",
"default",
".",
"Content",
":",
"default",
";",
"path",
":",
"yellow",
";",
"error",
"-",
">",
"red",
".",
"Level",
"has",
"to",
"be",
"surrounded",
"by",
"[",
"and",
"]",
".",
"Highlights",
"have",
"to",
"be",
"surrounded",
"by",
"#",
"and",
"#",
"(",
"space",
")",
"#",
"will",
"be",
"deleted",
".",
"Paths",
"have",
"to",
"be",
"surrounded",
"by",
"(",
"and",
")",
"(",
"space",
")",
".",
"Errors",
"have",
"to",
"be",
"surrounded",
"by",
"[",
"and",
"]",
"(",
"space",
")",
".",
"Note",
":",
"it",
"hasn",
"t",
"support",
"windows",
"yet",
"contribute",
"is",
"welcome",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/cmd.go#L107-L155 |
Unknwon/com | string.go | AESGCMEncrypt | func AESGCMEncrypt(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
ciphertext := gcm.Seal(nil, nonce, plaintext, nil)
return append(nonce, ciphertext...), nil
} | go | func AESGCMEncrypt(key, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
ciphertext := gcm.Seal(nil, nonce, plaintext, nil)
return append(nonce, ciphertext...), nil
} | [
"func",
"AESGCMEncrypt",
"(",
"key",
",",
"plaintext",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"block",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"gcm",
",",
"err",
":=",
"cipher",
".",
"NewGCM",
"(",
"block",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"nonce",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"gcm",
".",
"NonceSize",
"(",
")",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"nonce",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"ciphertext",
":=",
"gcm",
".",
"Seal",
"(",
"nil",
",",
"nonce",
",",
"plaintext",
",",
"nil",
")",
"\n",
"return",
"append",
"(",
"nonce",
",",
"ciphertext",
"...",
")",
",",
"nil",
"\n",
"}"
] | // AESGCMEncrypt encrypts plaintext with the given key using AES in GCM mode. | [
"AESGCMEncrypt",
"encrypts",
"plaintext",
"with",
"the",
"given",
"key",
"using",
"AES",
"in",
"GCM",
"mode",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/string.go#L32-L50 |
Unknwon/com | string.go | AESGCMDecrypt | func AESGCMDecrypt(key, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
size := gcm.NonceSize()
if len(ciphertext)-size <= 0 {
return nil, errors.New("Ciphertext is empty")
}
nonce := ciphertext[:size]
ciphertext = ciphertext[size:]
plainText, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plainText, nil
} | go | func AESGCMDecrypt(key, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
size := gcm.NonceSize()
if len(ciphertext)-size <= 0 {
return nil, errors.New("Ciphertext is empty")
}
nonce := ciphertext[:size]
ciphertext = ciphertext[size:]
plainText, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plainText, nil
} | [
"func",
"AESGCMDecrypt",
"(",
"key",
",",
"ciphertext",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"block",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"gcm",
",",
"err",
":=",
"cipher",
".",
"NewGCM",
"(",
"block",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"size",
":=",
"gcm",
".",
"NonceSize",
"(",
")",
"\n",
"if",
"len",
"(",
"ciphertext",
")",
"-",
"size",
"<=",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"nonce",
":=",
"ciphertext",
"[",
":",
"size",
"]",
"\n",
"ciphertext",
"=",
"ciphertext",
"[",
"size",
":",
"]",
"\n\n",
"plainText",
",",
"err",
":=",
"gcm",
".",
"Open",
"(",
"nil",
",",
"nonce",
",",
"ciphertext",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"plainText",
",",
"nil",
"\n",
"}"
] | // AESGCMDecrypt decrypts ciphertext with the given key using AES in GCM mode. | [
"AESGCMDecrypt",
"decrypts",
"ciphertext",
"with",
"the",
"given",
"key",
"using",
"AES",
"in",
"GCM",
"mode",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/string.go#L53-L78 |
Unknwon/com | string.go | IsLetter | func IsLetter(l uint8) bool {
n := (l | 0x20) - 'a'
if n >= 0 && n < 26 {
return true
}
return false
} | go | func IsLetter(l uint8) bool {
n := (l | 0x20) - 'a'
if n >= 0 && n < 26 {
return true
}
return false
} | [
"func",
"IsLetter",
"(",
"l",
"uint8",
")",
"bool",
"{",
"n",
":=",
"(",
"l",
"|",
"0x20",
")",
"-",
"'a'",
"\n",
"if",
"n",
">=",
"0",
"&&",
"n",
"<",
"26",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsLetter returns true if the 'l' is an English letter. | [
"IsLetter",
"returns",
"true",
"if",
"the",
"l",
"is",
"an",
"English",
"letter",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/string.go#L81-L87 |
Unknwon/com | string.go | Reverse | func Reverse(s string) string {
n := len(s)
runes := make([]rune, n)
for _, rune := range s {
n--
runes[n] = rune
}
return string(runes[n:])
} | go | func Reverse(s string) string {
n := len(s)
runes := make([]rune, n)
for _, rune := range s {
n--
runes[n] = rune
}
return string(runes[n:])
} | [
"func",
"Reverse",
"(",
"s",
"string",
")",
"string",
"{",
"n",
":=",
"len",
"(",
"s",
")",
"\n",
"runes",
":=",
"make",
"(",
"[",
"]",
"rune",
",",
"n",
")",
"\n",
"for",
"_",
",",
"rune",
":=",
"range",
"s",
"{",
"n",
"--",
"\n",
"runes",
"[",
"n",
"]",
"=",
"rune",
"\n",
"}",
"\n",
"return",
"string",
"(",
"runes",
"[",
"n",
":",
"]",
")",
"\n",
"}"
] | // Reverse s string, support unicode | [
"Reverse",
"s",
"string",
"support",
"unicode"
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/string.go#L118-L126 |
Unknwon/com | time.go | Date | func Date(ti int64, format string) string {
t := time.Unix(int64(ti), 0)
return DateT(t, format)
} | go | func Date(ti int64, format string) string {
t := time.Unix(int64(ti), 0)
return DateT(t, format)
} | [
"func",
"Date",
"(",
"ti",
"int64",
",",
"format",
"string",
")",
"string",
"{",
"t",
":=",
"time",
".",
"Unix",
"(",
"int64",
"(",
"ti",
")",
",",
"0",
")",
"\n",
"return",
"DateT",
"(",
"t",
",",
"format",
")",
"\n",
"}"
] | // Format unix time int64 to string | [
"Format",
"unix",
"time",
"int64",
"to",
"string"
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/time.go#L25-L28 |
Unknwon/com | time.go | DateS | func DateS(ts string, format string) string {
i, _ := strconv.ParseInt(ts, 10, 64)
return Date(i, format)
} | go | func DateS(ts string, format string) string {
i, _ := strconv.ParseInt(ts, 10, 64)
return Date(i, format)
} | [
"func",
"DateS",
"(",
"ts",
"string",
",",
"format",
"string",
")",
"string",
"{",
"i",
",",
"_",
":=",
"strconv",
".",
"ParseInt",
"(",
"ts",
",",
"10",
",",
"64",
")",
"\n",
"return",
"Date",
"(",
"i",
",",
"format",
")",
"\n",
"}"
] | // Format unix time string to string | [
"Format",
"unix",
"time",
"string",
"to",
"string"
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/time.go#L31-L34 |
Unknwon/com | time.go | DateT | func DateT(t time.Time, format string) string {
res := strings.Replace(format, "MM", t.Format("01"), -1)
res = strings.Replace(res, "M", t.Format("1"), -1)
res = strings.Replace(res, "DD", t.Format("02"), -1)
res = strings.Replace(res, "D", t.Format("2"), -1)
res = strings.Replace(res, "YYYY", t.Format("2006"), -1)
res = strings.Replace(res, "YY", t.Format("06"), -1)
res = strings.Replace(res, "HH", fmt.Sprintf("%02d", t.Hour()), -1)
res = strings.Replace(res, "H", fmt.Sprintf("%d", t.Hour()), -1)
res = strings.Replace(res, "hh", t.Format("03"), -1)
res = strings.Replace(res, "h", t.Format("3"), -1)
res = strings.Replace(res, "mm", t.Format("04"), -1)
res = strings.Replace(res, "m", t.Format("4"), -1)
res = strings.Replace(res, "ss", t.Format("05"), -1)
res = strings.Replace(res, "s", t.Format("5"), -1)
return res
} | go | func DateT(t time.Time, format string) string {
res := strings.Replace(format, "MM", t.Format("01"), -1)
res = strings.Replace(res, "M", t.Format("1"), -1)
res = strings.Replace(res, "DD", t.Format("02"), -1)
res = strings.Replace(res, "D", t.Format("2"), -1)
res = strings.Replace(res, "YYYY", t.Format("2006"), -1)
res = strings.Replace(res, "YY", t.Format("06"), -1)
res = strings.Replace(res, "HH", fmt.Sprintf("%02d", t.Hour()), -1)
res = strings.Replace(res, "H", fmt.Sprintf("%d", t.Hour()), -1)
res = strings.Replace(res, "hh", t.Format("03"), -1)
res = strings.Replace(res, "h", t.Format("3"), -1)
res = strings.Replace(res, "mm", t.Format("04"), -1)
res = strings.Replace(res, "m", t.Format("4"), -1)
res = strings.Replace(res, "ss", t.Format("05"), -1)
res = strings.Replace(res, "s", t.Format("5"), -1)
return res
} | [
"func",
"DateT",
"(",
"t",
"time",
".",
"Time",
",",
"format",
"string",
")",
"string",
"{",
"res",
":=",
"strings",
".",
"Replace",
"(",
"format",
",",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
"strings",
".",
"Replace",
"(",
"res",
",",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
"strings",
".",
"Replace",
"(",
"res",
",",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
"strings",
".",
"Replace",
"(",
"res",
",",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
"strings",
".",
"Replace",
"(",
"res",
",",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
"strings",
".",
"Replace",
"(",
"res",
",",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
"strings",
".",
"Replace",
"(",
"res",
",",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Hour",
"(",
")",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
"strings",
".",
"Replace",
"(",
"res",
",",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Hour",
"(",
")",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
"strings",
".",
"Replace",
"(",
"res",
",",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
"strings",
".",
"Replace",
"(",
"res",
",",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
"strings",
".",
"Replace",
"(",
"res",
",",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
"strings",
".",
"Replace",
"(",
"res",
",",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
"strings",
".",
"Replace",
"(",
"res",
",",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"-",
"1",
")",
"\n",
"res",
"=",
"strings",
".",
"Replace",
"(",
"res",
",",
"\"",
"\"",
",",
"t",
".",
"Format",
"(",
"\"",
"\"",
")",
",",
"-",
"1",
")",
"\n",
"return",
"res",
"\n",
"}"
] | // Format time.Time struct to string
// MM - month - 01
// M - month - 1, single bit
// DD - day - 02
// D - day 2
// YYYY - year - 2006
// YY - year - 06
// HH - 24 hours - 03
// H - 24 hours - 3
// hh - 12 hours - 03
// h - 12 hours - 3
// mm - minute - 04
// m - minute - 4
// ss - second - 05
// s - second = 5 | [
"Format",
"time",
".",
"Time",
"struct",
"to",
"string",
"MM",
"-",
"month",
"-",
"01",
"M",
"-",
"month",
"-",
"1",
"single",
"bit",
"DD",
"-",
"day",
"-",
"02",
"D",
"-",
"day",
"2",
"YYYY",
"-",
"year",
"-",
"2006",
"YY",
"-",
"year",
"-",
"06",
"HH",
"-",
"24",
"hours",
"-",
"03",
"H",
"-",
"24",
"hours",
"-",
"3",
"hh",
"-",
"12",
"hours",
"-",
"03",
"h",
"-",
"12",
"hours",
"-",
"3",
"mm",
"-",
"minute",
"-",
"04",
"m",
"-",
"minute",
"-",
"4",
"ss",
"-",
"second",
"-",
"05",
"s",
"-",
"second",
"=",
"5"
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/time.go#L51-L67 |
Unknwon/com | time.go | DateParse | func DateParse(dateString, format string) (time.Time, error) {
replacer := strings.NewReplacer(datePatterns...)
format = replacer.Replace(format)
return time.ParseInLocation(format, dateString, time.Local)
} | go | func DateParse(dateString, format string) (time.Time, error) {
replacer := strings.NewReplacer(datePatterns...)
format = replacer.Replace(format)
return time.ParseInLocation(format, dateString, time.Local)
} | [
"func",
"DateParse",
"(",
"dateString",
",",
"format",
"string",
")",
"(",
"time",
".",
"Time",
",",
"error",
")",
"{",
"replacer",
":=",
"strings",
".",
"NewReplacer",
"(",
"datePatterns",
"...",
")",
"\n",
"format",
"=",
"replacer",
".",
"Replace",
"(",
"format",
")",
"\n",
"return",
"time",
".",
"ParseInLocation",
"(",
"format",
",",
"dateString",
",",
"time",
".",
"Local",
")",
"\n",
"}"
] | // Parse Date use PHP time format. | [
"Parse",
"Date",
"use",
"PHP",
"time",
"format",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/time.go#L111-L115 |
Unknwon/com | dir.go | StatDir | func StatDir(rootPath string, includeDir ...bool) ([]string, error) {
if !IsDir(rootPath) {
return nil, errors.New("not a directory or does not exist: " + rootPath)
}
isIncludeDir := false
if len(includeDir) >= 1 {
isIncludeDir = includeDir[0]
}
return statDir(rootPath, "", isIncludeDir, false, false)
} | go | func StatDir(rootPath string, includeDir ...bool) ([]string, error) {
if !IsDir(rootPath) {
return nil, errors.New("not a directory or does not exist: " + rootPath)
}
isIncludeDir := false
if len(includeDir) >= 1 {
isIncludeDir = includeDir[0]
}
return statDir(rootPath, "", isIncludeDir, false, false)
} | [
"func",
"StatDir",
"(",
"rootPath",
"string",
",",
"includeDir",
"...",
"bool",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"!",
"IsDir",
"(",
"rootPath",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"rootPath",
")",
"\n",
"}",
"\n\n",
"isIncludeDir",
":=",
"false",
"\n",
"if",
"len",
"(",
"includeDir",
")",
">=",
"1",
"{",
"isIncludeDir",
"=",
"includeDir",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"statDir",
"(",
"rootPath",
",",
"\"",
"\"",
",",
"isIncludeDir",
",",
"false",
",",
"false",
")",
"\n",
"}"
] | // StatDir gathers information of given directory by depth-first.
// It returns slice of file list and includes subdirectories if enabled;
// it returns error and nil slice when error occurs in underlying functions,
// or given path is not a directory or does not exist.
//
// Slice does not include given path itself.
// If subdirectories is enabled, they will have suffix '/'. | [
"StatDir",
"gathers",
"information",
"of",
"given",
"directory",
"by",
"depth",
"-",
"first",
".",
"It",
"returns",
"slice",
"of",
"file",
"list",
"and",
"includes",
"subdirectories",
"if",
"enabled",
";",
"it",
"returns",
"error",
"and",
"nil",
"slice",
"when",
"error",
"occurs",
"in",
"underlying",
"functions",
"or",
"given",
"path",
"is",
"not",
"a",
"directory",
"or",
"does",
"not",
"exist",
".",
"Slice",
"does",
"not",
"include",
"given",
"path",
"itself",
".",
"If",
"subdirectories",
"is",
"enabled",
"they",
"will",
"have",
"suffix",
"/",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/dir.go#L94-L104 |
Unknwon/com | dir.go | GetAllSubDirs | func GetAllSubDirs(rootPath string) ([]string, error) {
if !IsDir(rootPath) {
return nil, errors.New("not a directory or does not exist: " + rootPath)
}
return statDir(rootPath, "", true, true, false)
} | go | func GetAllSubDirs(rootPath string) ([]string, error) {
if !IsDir(rootPath) {
return nil, errors.New("not a directory or does not exist: " + rootPath)
}
return statDir(rootPath, "", true, true, false)
} | [
"func",
"GetAllSubDirs",
"(",
"rootPath",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"!",
"IsDir",
"(",
"rootPath",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"rootPath",
")",
"\n",
"}",
"\n",
"return",
"statDir",
"(",
"rootPath",
",",
"\"",
"\"",
",",
"true",
",",
"true",
",",
"false",
")",
"\n",
"}"
] | // GetAllSubDirs returns all subdirectories of given root path.
// Slice does not include given path itself. | [
"GetAllSubDirs",
"returns",
"all",
"subdirectories",
"of",
"given",
"root",
"path",
".",
"Slice",
"does",
"not",
"include",
"given",
"path",
"itself",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/dir.go#L127-L132 |
Unknwon/com | dir.go | GetFileListBySuffix | func GetFileListBySuffix(dirPath, suffix string) ([]string, error) {
if !IsExist(dirPath) {
return nil, fmt.Errorf("given path does not exist: %s", dirPath)
} else if IsFile(dirPath) {
return []string{dirPath}, nil
}
// Given path is a directory.
dir, err := os.Open(dirPath)
if err != nil {
return nil, err
}
fis, err := dir.Readdir(0)
if err != nil {
return nil, err
}
files := make([]string, 0, len(fis))
for _, fi := range fis {
if strings.HasSuffix(fi.Name(), suffix) {
files = append(files, path.Join(dirPath, fi.Name()))
}
}
return files, nil
} | go | func GetFileListBySuffix(dirPath, suffix string) ([]string, error) {
if !IsExist(dirPath) {
return nil, fmt.Errorf("given path does not exist: %s", dirPath)
} else if IsFile(dirPath) {
return []string{dirPath}, nil
}
// Given path is a directory.
dir, err := os.Open(dirPath)
if err != nil {
return nil, err
}
fis, err := dir.Readdir(0)
if err != nil {
return nil, err
}
files := make([]string, 0, len(fis))
for _, fi := range fis {
if strings.HasSuffix(fi.Name(), suffix) {
files = append(files, path.Join(dirPath, fi.Name()))
}
}
return files, nil
} | [
"func",
"GetFileListBySuffix",
"(",
"dirPath",
",",
"suffix",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"!",
"IsExist",
"(",
"dirPath",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"dirPath",
")",
"\n",
"}",
"else",
"if",
"IsFile",
"(",
"dirPath",
")",
"{",
"return",
"[",
"]",
"string",
"{",
"dirPath",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"// Given path is a directory.",
"dir",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"dirPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"fis",
",",
"err",
":=",
"dir",
".",
"Readdir",
"(",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"files",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"fis",
")",
")",
"\n",
"for",
"_",
",",
"fi",
":=",
"range",
"fis",
"{",
"if",
"strings",
".",
"HasSuffix",
"(",
"fi",
".",
"Name",
"(",
")",
",",
"suffix",
")",
"{",
"files",
"=",
"append",
"(",
"files",
",",
"path",
".",
"Join",
"(",
"dirPath",
",",
"fi",
".",
"Name",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"files",
",",
"nil",
"\n",
"}"
] | // GetFileListBySuffix returns an ordered list of file paths.
// It recognize if given path is a file, and don't do recursive find. | [
"GetFileListBySuffix",
"returns",
"an",
"ordered",
"list",
"of",
"file",
"paths",
".",
"It",
"recognize",
"if",
"given",
"path",
"is",
"a",
"file",
"and",
"don",
"t",
"do",
"recursive",
"find",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/dir.go#L146-L172 |
Unknwon/com | slice.go | AppendStr | func AppendStr(strs []string, str string) []string {
for _, s := range strs {
if s == str {
return strs
}
}
return append(strs, str)
} | go | func AppendStr(strs []string, str string) []string {
for _, s := range strs {
if s == str {
return strs
}
}
return append(strs, str)
} | [
"func",
"AppendStr",
"(",
"strs",
"[",
"]",
"string",
",",
"str",
"string",
")",
"[",
"]",
"string",
"{",
"for",
"_",
",",
"s",
":=",
"range",
"strs",
"{",
"if",
"s",
"==",
"str",
"{",
"return",
"strs",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"append",
"(",
"strs",
",",
"str",
")",
"\n",
"}"
] | // AppendStr appends string to slice with no duplicates. | [
"AppendStr",
"appends",
"string",
"to",
"slice",
"with",
"no",
"duplicates",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/slice.go#L22-L29 |
Unknwon/com | slice.go | CompareSliceStrU | func CompareSliceStrU(s1, s2 []string) bool {
if len(s1) != len(s2) {
return false
}
for i := range s1 {
for j := len(s2) - 1; j >= 0; j-- {
if s1[i] == s2[j] {
s2 = append(s2[:j], s2[j+1:]...)
break
}
}
}
if len(s2) > 0 {
return false
}
return true
} | go | func CompareSliceStrU(s1, s2 []string) bool {
if len(s1) != len(s2) {
return false
}
for i := range s1 {
for j := len(s2) - 1; j >= 0; j-- {
if s1[i] == s2[j] {
s2 = append(s2[:j], s2[j+1:]...)
break
}
}
}
if len(s2) > 0 {
return false
}
return true
} | [
"func",
"CompareSliceStrU",
"(",
"s1",
",",
"s2",
"[",
"]",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"s1",
")",
"!=",
"len",
"(",
"s2",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"range",
"s1",
"{",
"for",
"j",
":=",
"len",
"(",
"s2",
")",
"-",
"1",
";",
"j",
">=",
"0",
";",
"j",
"--",
"{",
"if",
"s1",
"[",
"i",
"]",
"==",
"s2",
"[",
"j",
"]",
"{",
"s2",
"=",
"append",
"(",
"s2",
"[",
":",
"j",
"]",
",",
"s2",
"[",
"j",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"s2",
")",
">",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // CompareSliceStrU compares two 'string' type slices.
// It returns true if elements are the same, and ignores the order. | [
"CompareSliceStrU",
"compares",
"two",
"string",
"type",
"slices",
".",
"It",
"returns",
"true",
"if",
"elements",
"are",
"the",
"same",
"and",
"ignores",
"the",
"order",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/slice.go#L49-L66 |
Unknwon/com | slice.go | IsSliceContainsInt64 | func IsSliceContainsInt64(sl []int64, i int64) bool {
for _, s := range sl {
if s == i {
return true
}
}
return false
} | go | func IsSliceContainsInt64(sl []int64, i int64) bool {
for _, s := range sl {
if s == i {
return true
}
}
return false
} | [
"func",
"IsSliceContainsInt64",
"(",
"sl",
"[",
"]",
"int64",
",",
"i",
"int64",
")",
"bool",
"{",
"for",
"_",
",",
"s",
":=",
"range",
"sl",
"{",
"if",
"s",
"==",
"i",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // IsSliceContainsInt64 returns true if the int64 exists in given slice. | [
"IsSliceContainsInt64",
"returns",
"true",
"if",
"the",
"int64",
"exists",
"in",
"given",
"slice",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/slice.go#L80-L87 |
Unknwon/com | file.go | FileMTime | func FileMTime(file string) (int64, error) {
f, err := os.Stat(file)
if err != nil {
return 0, err
}
return f.ModTime().Unix(), nil
} | go | func FileMTime(file string) (int64, error) {
f, err := os.Stat(file)
if err != nil {
return 0, err
}
return f.ModTime().Unix(), nil
} | [
"func",
"FileMTime",
"(",
"file",
"string",
")",
"(",
"int64",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"f",
".",
"ModTime",
"(",
")",
".",
"Unix",
"(",
")",
",",
"nil",
"\n",
"}"
] | // FileMTime returns file modified time and possible error. | [
"FileMTime",
"returns",
"file",
"modified",
"time",
"and",
"possible",
"error",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/file.go#L63-L69 |
Unknwon/com | file.go | FileSize | func FileSize(file string) (int64, error) {
f, err := os.Stat(file)
if err != nil {
return 0, err
}
return f.Size(), nil
} | go | func FileSize(file string) (int64, error) {
f, err := os.Stat(file)
if err != nil {
return 0, err
}
return f.Size(), nil
} | [
"func",
"FileSize",
"(",
"file",
"string",
")",
"(",
"int64",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"f",
".",
"Size",
"(",
")",
",",
"nil",
"\n",
"}"
] | // FileSize returns file size in bytes and possible error. | [
"FileSize",
"returns",
"file",
"size",
"in",
"bytes",
"and",
"possible",
"error",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/file.go#L72-L78 |
Unknwon/com | file.go | WriteFile | func WriteFile(filename string, data []byte) error {
os.MkdirAll(path.Dir(filename), os.ModePerm)
return ioutil.WriteFile(filename, data, 0655)
} | go | func WriteFile(filename string, data []byte) error {
os.MkdirAll(path.Dir(filename), os.ModePerm)
return ioutil.WriteFile(filename, data, 0655)
} | [
"func",
"WriteFile",
"(",
"filename",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"os",
".",
"MkdirAll",
"(",
"path",
".",
"Dir",
"(",
"filename",
")",
",",
"os",
".",
"ModePerm",
")",
"\n",
"return",
"ioutil",
".",
"WriteFile",
"(",
"filename",
",",
"data",
",",
"0655",
")",
"\n",
"}"
] | // WriteFile writes data to a file named by filename.
// If the file does not exist, WriteFile creates it
// and its upper level paths. | [
"WriteFile",
"writes",
"data",
"to",
"a",
"file",
"named",
"by",
"filename",
".",
"If",
"the",
"file",
"does",
"not",
"exist",
"WriteFile",
"creates",
"it",
"and",
"its",
"upper",
"level",
"paths",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/file.go#L125-L128 |
Unknwon/com | http.go | HttpGet | func HttpGet(client *http.Client, url string, header http.Header) (io.ReadCloser, error) {
return HttpCall(client, "GET", url, header, nil)
} | go | func HttpGet(client *http.Client, url string, header http.Header) (io.ReadCloser, error) {
return HttpCall(client, "GET", url, header, nil)
} | [
"func",
"HttpGet",
"(",
"client",
"*",
"http",
".",
"Client",
",",
"url",
"string",
",",
"header",
"http",
".",
"Header",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"return",
"HttpCall",
"(",
"client",
",",
"\"",
"\"",
",",
"url",
",",
"header",
",",
"nil",
")",
"\n",
"}"
] | // HttpGet gets the specified resource.
// ErrNotFound is returned if the server responds with status 404. | [
"HttpGet",
"gets",
"the",
"specified",
"resource",
".",
"ErrNotFound",
"is",
"returned",
"if",
"the",
"server",
"responds",
"with",
"status",
"404",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/http.go#L75-L77 |
Unknwon/com | http.go | HttpPost | func HttpPost(client *http.Client, url string, header http.Header, body []byte) (io.ReadCloser, error) {
return HttpCall(client, "POST", url, header, bytes.NewBuffer(body))
} | go | func HttpPost(client *http.Client, url string, header http.Header, body []byte) (io.ReadCloser, error) {
return HttpCall(client, "POST", url, header, bytes.NewBuffer(body))
} | [
"func",
"HttpPost",
"(",
"client",
"*",
"http",
".",
"Client",
",",
"url",
"string",
",",
"header",
"http",
".",
"Header",
",",
"body",
"[",
"]",
"byte",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"return",
"HttpCall",
"(",
"client",
",",
"\"",
"\"",
",",
"url",
",",
"header",
",",
"bytes",
".",
"NewBuffer",
"(",
"body",
")",
")",
"\n",
"}"
] | // HttpPost posts the specified resource.
// ErrNotFound is returned if the server responds with status 404. | [
"HttpPost",
"posts",
"the",
"specified",
"resource",
".",
"ErrNotFound",
"is",
"returned",
"if",
"the",
"server",
"responds",
"with",
"status",
"404",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/http.go#L81-L83 |
Unknwon/com | http.go | HttpGetToFile | func HttpGetToFile(client *http.Client, url string, header http.Header, fileName string) error {
rc, err := HttpGet(client, url, header)
if err != nil {
return err
}
defer rc.Close()
os.MkdirAll(path.Dir(fileName), os.ModePerm)
f, err := os.Create(fileName)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, rc)
return err
} | go | func HttpGetToFile(client *http.Client, url string, header http.Header, fileName string) error {
rc, err := HttpGet(client, url, header)
if err != nil {
return err
}
defer rc.Close()
os.MkdirAll(path.Dir(fileName), os.ModePerm)
f, err := os.Create(fileName)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, rc)
return err
} | [
"func",
"HttpGetToFile",
"(",
"client",
"*",
"http",
".",
"Client",
",",
"url",
"string",
",",
"header",
"http",
".",
"Header",
",",
"fileName",
"string",
")",
"error",
"{",
"rc",
",",
"err",
":=",
"HttpGet",
"(",
"client",
",",
"url",
",",
"header",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"rc",
".",
"Close",
"(",
")",
"\n\n",
"os",
".",
"MkdirAll",
"(",
"path",
".",
"Dir",
"(",
"fileName",
")",
",",
"os",
".",
"ModePerm",
")",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"fileName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"f",
",",
"rc",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // HttpGetToFile gets the specified resource and writes to file.
// ErrNotFound is returned if the server responds with status 404. | [
"HttpGetToFile",
"gets",
"the",
"specified",
"resource",
"and",
"writes",
"to",
"file",
".",
"ErrNotFound",
"is",
"returned",
"if",
"the",
"server",
"responds",
"with",
"status",
"404",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/http.go#L87-L102 |
Unknwon/com | http.go | HttpPostJSON | func HttpPostJSON(client *http.Client, url string, body, v interface{}) error {
data, err := json.Marshal(body)
if err != nil {
return err
}
rc, err := HttpPost(client, url, http.Header{"content-type": []string{"application/json"}}, data)
if err != nil {
return err
}
defer rc.Close()
err = json.NewDecoder(rc).Decode(v)
if _, ok := err.(*json.SyntaxError); ok {
return fmt.Errorf("JSON syntax error at %s", url)
}
return nil
} | go | func HttpPostJSON(client *http.Client, url string, body, v interface{}) error {
data, err := json.Marshal(body)
if err != nil {
return err
}
rc, err := HttpPost(client, url, http.Header{"content-type": []string{"application/json"}}, data)
if err != nil {
return err
}
defer rc.Close()
err = json.NewDecoder(rc).Decode(v)
if _, ok := err.(*json.SyntaxError); ok {
return fmt.Errorf("JSON syntax error at %s", url)
}
return nil
} | [
"func",
"HttpPostJSON",
"(",
"client",
"*",
"http",
".",
"Client",
",",
"url",
"string",
",",
"body",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"data",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"rc",
",",
"err",
":=",
"HttpPost",
"(",
"client",
",",
"url",
",",
"http",
".",
"Header",
"{",
"\"",
"\"",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
"}",
",",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"rc",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"rc",
")",
".",
"Decode",
"(",
"v",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"json",
".",
"SyntaxError",
")",
";",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"url",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // HttpPostJSON posts the specified resource with struct values,
// and maps results to struct.
// ErrNotFound is returned if the server responds with status 404. | [
"HttpPostJSON",
"posts",
"the",
"specified",
"resource",
"with",
"struct",
"values",
"and",
"maps",
"results",
"to",
"struct",
".",
"ErrNotFound",
"is",
"returned",
"if",
"the",
"server",
"responds",
"with",
"status",
"404",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/http.go#L133-L148 |
Unknwon/com | http.go | FetchFiles | func FetchFiles(client *http.Client, files []RawFile, header http.Header) error {
ch := make(chan error, len(files))
for i := range files {
go func(i int) {
p, err := HttpGetBytes(client, files[i].RawUrl(), nil)
if err != nil {
ch <- err
return
}
files[i].SetData(p)
ch <- nil
}(i)
}
for _ = range files {
if err := <-ch; err != nil {
return err
}
}
return nil
} | go | func FetchFiles(client *http.Client, files []RawFile, header http.Header) error {
ch := make(chan error, len(files))
for i := range files {
go func(i int) {
p, err := HttpGetBytes(client, files[i].RawUrl(), nil)
if err != nil {
ch <- err
return
}
files[i].SetData(p)
ch <- nil
}(i)
}
for _ = range files {
if err := <-ch; err != nil {
return err
}
}
return nil
} | [
"func",
"FetchFiles",
"(",
"client",
"*",
"http",
".",
"Client",
",",
"files",
"[",
"]",
"RawFile",
",",
"header",
"http",
".",
"Header",
")",
"error",
"{",
"ch",
":=",
"make",
"(",
"chan",
"error",
",",
"len",
"(",
"files",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"files",
"{",
"go",
"func",
"(",
"i",
"int",
")",
"{",
"p",
",",
"err",
":=",
"HttpGetBytes",
"(",
"client",
",",
"files",
"[",
"i",
"]",
".",
"RawUrl",
"(",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ch",
"<-",
"err",
"\n",
"return",
"\n",
"}",
"\n",
"files",
"[",
"i",
"]",
".",
"SetData",
"(",
"p",
")",
"\n",
"ch",
"<-",
"nil",
"\n",
"}",
"(",
"i",
")",
"\n",
"}",
"\n",
"for",
"_",
"=",
"range",
"files",
"{",
"if",
"err",
":=",
"<-",
"ch",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // FetchFiles fetches files specified by the rawURL field in parallel. | [
"FetchFiles",
"fetches",
"files",
"specified",
"by",
"the",
"rawURL",
"field",
"in",
"parallel",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/http.go#L159-L178 |
Unknwon/com | math.go | PowInt | func PowInt(x int, y int) int {
if y <= 0 {
return 1
} else {
if y%2 == 0 {
sqrt := PowInt(x, y/2)
return sqrt * sqrt
} else {
return PowInt(x, y-1) * x
}
}
} | go | func PowInt(x int, y int) int {
if y <= 0 {
return 1
} else {
if y%2 == 0 {
sqrt := PowInt(x, y/2)
return sqrt * sqrt
} else {
return PowInt(x, y-1) * x
}
}
} | [
"func",
"PowInt",
"(",
"x",
"int",
",",
"y",
"int",
")",
"int",
"{",
"if",
"y",
"<=",
"0",
"{",
"return",
"1",
"\n",
"}",
"else",
"{",
"if",
"y",
"%",
"2",
"==",
"0",
"{",
"sqrt",
":=",
"PowInt",
"(",
"x",
",",
"y",
"/",
"2",
")",
"\n",
"return",
"sqrt",
"*",
"sqrt",
"\n",
"}",
"else",
"{",
"return",
"PowInt",
"(",
"x",
",",
"y",
"-",
"1",
")",
"*",
"x",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // PowInt is int type of math.Pow function. | [
"PowInt",
"is",
"int",
"type",
"of",
"math",
".",
"Pow",
"function",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/math.go#L18-L29 |
Unknwon/com | url.go | Base64Decode | func Base64Decode(str string) (string, error) {
s, e := base64.StdEncoding.DecodeString(str)
return string(s), e
} | go | func Base64Decode(str string) (string, error) {
s, e := base64.StdEncoding.DecodeString(str)
return string(s), e
} | [
"func",
"Base64Decode",
"(",
"str",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"s",
",",
"e",
":=",
"base64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"str",
")",
"\n",
"return",
"string",
"(",
"s",
")",
",",
"e",
"\n",
"}"
] | // base64 decode | [
"base64",
"decode"
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/url.go#L38-L41 |
Unknwon/com | convert.go | HexStr2int | func HexStr2int(hexStr string) (int, error) {
num := 0
length := len(hexStr)
for i := 0; i < length; i++ {
char := hexStr[length-i-1]
factor := -1
switch {
case char >= '0' && char <= '9':
factor = int(char) - '0'
case char >= 'a' && char <= 'f':
factor = int(char) - 'a' + 10
default:
return -1, fmt.Errorf("invalid hex: %s", string(char))
}
num += factor * PowInt(16, i)
}
return num, nil
} | go | func HexStr2int(hexStr string) (int, error) {
num := 0
length := len(hexStr)
for i := 0; i < length; i++ {
char := hexStr[length-i-1]
factor := -1
switch {
case char >= '0' && char <= '9':
factor = int(char) - '0'
case char >= 'a' && char <= 'f':
factor = int(char) - 'a' + 10
default:
return -1, fmt.Errorf("invalid hex: %s", string(char))
}
num += factor * PowInt(16, i)
}
return num, nil
} | [
"func",
"HexStr2int",
"(",
"hexStr",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"num",
":=",
"0",
"\n",
"length",
":=",
"len",
"(",
"hexStr",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
"{",
"char",
":=",
"hexStr",
"[",
"length",
"-",
"i",
"-",
"1",
"]",
"\n",
"factor",
":=",
"-",
"1",
"\n\n",
"switch",
"{",
"case",
"char",
">=",
"'0'",
"&&",
"char",
"<=",
"'9'",
":",
"factor",
"=",
"int",
"(",
"char",
")",
"-",
"'0'",
"\n",
"case",
"char",
">=",
"'a'",
"&&",
"char",
"<=",
"'f'",
":",
"factor",
"=",
"int",
"(",
"char",
")",
"-",
"'a'",
"+",
"10",
"\n",
"default",
":",
"return",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"string",
"(",
"char",
")",
")",
"\n",
"}",
"\n\n",
"num",
"+=",
"factor",
"*",
"PowInt",
"(",
"16",
",",
"i",
")",
"\n",
"}",
"\n",
"return",
"num",
",",
"nil",
"\n",
"}"
] | // HexStr2int converts hex format string to decimal number. | [
"HexStr2int",
"converts",
"hex",
"format",
"string",
"to",
"decimal",
"number",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/convert.go#L127-L146 |
Unknwon/com | html.go | Html2JS | func Html2JS(data []byte) []byte {
s := string(data)
s = strings.Replace(s, `\`, `\\`, -1)
s = strings.Replace(s, "\n", `\n`, -1)
s = strings.Replace(s, "\r", "", -1)
s = strings.Replace(s, "\"", `\"`, -1)
s = strings.Replace(s, "<table>", "<table>", -1)
return []byte(s)
} | go | func Html2JS(data []byte) []byte {
s := string(data)
s = strings.Replace(s, `\`, `\\`, -1)
s = strings.Replace(s, "\n", `\n`, -1)
s = strings.Replace(s, "\r", "", -1)
s = strings.Replace(s, "\"", `\"`, -1)
s = strings.Replace(s, "<table>", "<table>", -1)
return []byte(s)
} | [
"func",
"Html2JS",
"(",
"data",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"s",
":=",
"string",
"(",
"data",
")",
"\n",
"s",
"=",
"strings",
".",
"Replace",
"(",
"s",
",",
"`\\`",
",",
"`\\\\`",
",",
"-",
"1",
")",
"\n",
"s",
"=",
"strings",
".",
"Replace",
"(",
"s",
",",
"\"",
"\\n",
"\"",
",",
"`\\n`",
",",
"-",
"1",
")",
"\n",
"s",
"=",
"strings",
".",
"Replace",
"(",
"s",
",",
"\"",
"\\r",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"s",
"=",
"strings",
".",
"Replace",
"(",
"s",
",",
"\"",
"\\\"",
"\"",
",",
"`\\\"`",
",",
"-",
"1",
")",
"\n",
"s",
"=",
"strings",
".",
"Replace",
"(",
"s",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"return",
"[",
"]",
"byte",
"(",
"s",
")",
"\n",
"}"
] | // Html2JS converts []byte type of HTML content into JS format. | [
"Html2JS",
"converts",
"[]",
"byte",
"type",
"of",
"HTML",
"content",
"into",
"JS",
"format",
"."
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/html.go#L24-L32 |
Unknwon/com | html.go | StripTags | func StripTags(src string) string {
//去除style,script,html tag
re := regexp.MustCompile(`(?s)<(?:style|script)[^<>]*>.*?</(?:style|script)>|</?[a-z][a-z0-9]*[^<>]*>|<!--.*?-->`)
src = re.ReplaceAllString(src, "")
//trim all spaces(2+) into \n
re = regexp.MustCompile(`\s{2,}`)
src = re.ReplaceAllString(src, "\n")
return strings.TrimSpace(src)
} | go | func StripTags(src string) string {
//去除style,script,html tag
re := regexp.MustCompile(`(?s)<(?:style|script)[^<>]*>.*?</(?:style|script)>|</?[a-z][a-z0-9]*[^<>]*>|<!--.*?-->`)
src = re.ReplaceAllString(src, "")
//trim all spaces(2+) into \n
re = regexp.MustCompile(`\s{2,}`)
src = re.ReplaceAllString(src, "\n")
return strings.TrimSpace(src)
} | [
"func",
"StripTags",
"(",
"src",
"string",
")",
"string",
"{",
"//去除style,script,html tag",
"re",
":=",
"regexp",
".",
"MustCompile",
"(",
"`(?s)<(?:style|script)[^<>]*>.*?</(?:style|script)>|</?[a-z][a-z0-9]*[^<>]*>|<!--.*?-->`",
")",
"\n",
"src",
"=",
"re",
".",
"ReplaceAllString",
"(",
"src",
",",
"\"",
"\"",
")",
"\n\n",
"//trim all spaces(2+) into \\n",
"re",
"=",
"regexp",
".",
"MustCompile",
"(",
"`\\s{2,}`",
")",
"\n",
"src",
"=",
"re",
".",
"ReplaceAllString",
"(",
"src",
",",
"\"",
"\\n",
"\"",
")",
"\n\n",
"return",
"strings",
".",
"TrimSpace",
"(",
"src",
")",
"\n",
"}"
] | // strip tags in html string | [
"strip",
"tags",
"in",
"html",
"string"
] | train | https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/html.go#L45-L55 |
HouzuoGuo/tiedot | data/partition.go | OpenPartition | func (conf *Config) OpenPartition(colPath, lookupPath string) (part *Partition, err error) {
part = conf.newPartition()
part.CalculateConfigConstants()
if part.col, err = conf.OpenCollection(colPath); err != nil {
return
} else if part.lookup, err = conf.OpenHashTable(lookupPath); err != nil {
return
}
return
} | go | func (conf *Config) OpenPartition(colPath, lookupPath string) (part *Partition, err error) {
part = conf.newPartition()
part.CalculateConfigConstants()
if part.col, err = conf.OpenCollection(colPath); err != nil {
return
} else if part.lookup, err = conf.OpenHashTable(lookupPath); err != nil {
return
}
return
} | [
"func",
"(",
"conf",
"*",
"Config",
")",
"OpenPartition",
"(",
"colPath",
",",
"lookupPath",
"string",
")",
"(",
"part",
"*",
"Partition",
",",
"err",
"error",
")",
"{",
"part",
"=",
"conf",
".",
"newPartition",
"(",
")",
"\n",
"part",
".",
"CalculateConfigConstants",
"(",
")",
"\n",
"if",
"part",
".",
"col",
",",
"err",
"=",
"conf",
".",
"OpenCollection",
"(",
"colPath",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"else",
"if",
"part",
".",
"lookup",
",",
"err",
"=",
"conf",
".",
"OpenHashTable",
"(",
"lookupPath",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Open a collection partition. | [
"Open",
"a",
"collection",
"partition",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L37-L46 |
HouzuoGuo/tiedot | data/partition.go | Insert | func (part *Partition) Insert(id int, data []byte) (physID int, err error) {
physID, err = part.col.Insert(data)
if err != nil {
return
}
part.lookup.Put(id, physID)
return
} | go | func (part *Partition) Insert(id int, data []byte) (physID int, err error) {
physID, err = part.col.Insert(data)
if err != nil {
return
}
part.lookup.Put(id, physID)
return
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"Insert",
"(",
"id",
"int",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"physID",
"int",
",",
"err",
"error",
")",
"{",
"physID",
",",
"err",
"=",
"part",
".",
"col",
".",
"Insert",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"part",
".",
"lookup",
".",
"Put",
"(",
"id",
",",
"physID",
")",
"\n",
"return",
"\n",
"}"
] | // Insert a document. The ID may be used to retrieve/update/delete the document later on. | [
"Insert",
"a",
"document",
".",
"The",
"ID",
"may",
"be",
"used",
"to",
"retrieve",
"/",
"update",
"/",
"delete",
"the",
"document",
"later",
"on",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L49-L56 |
HouzuoGuo/tiedot | data/partition.go | Read | func (part *Partition) Read(id int) ([]byte, error) {
physID := part.lookup.Get(id, 1)
if len(physID) == 0 {
return nil, dberr.New(dberr.ErrorNoDoc, id)
}
data := part.col.Read(physID[0])
if data == nil {
return nil, dberr.New(dberr.ErrorNoDoc, id)
}
return data, nil
} | go | func (part *Partition) Read(id int) ([]byte, error) {
physID := part.lookup.Get(id, 1)
if len(physID) == 0 {
return nil, dberr.New(dberr.ErrorNoDoc, id)
}
data := part.col.Read(physID[0])
if data == nil {
return nil, dberr.New(dberr.ErrorNoDoc, id)
}
return data, nil
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"Read",
"(",
"id",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"physID",
":=",
"part",
".",
"lookup",
".",
"Get",
"(",
"id",
",",
"1",
")",
"\n\n",
"if",
"len",
"(",
"physID",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorNoDoc",
",",
"id",
")",
"\n",
"}",
"\n\n",
"data",
":=",
"part",
".",
"col",
".",
"Read",
"(",
"physID",
"[",
"0",
"]",
")",
"\n\n",
"if",
"data",
"==",
"nil",
"{",
"return",
"nil",
",",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorNoDoc",
",",
"id",
")",
"\n",
"}",
"\n\n",
"return",
"data",
",",
"nil",
"\n",
"}"
] | // Find and retrieve a document by ID. | [
"Find",
"and",
"retrieve",
"a",
"document",
"by",
"ID",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L59-L73 |
HouzuoGuo/tiedot | data/partition.go | Update | func (part *Partition) Update(id int, data []byte) (err error) {
physID := part.lookup.Get(id, 1)
if len(physID) == 0 {
return dberr.New(dberr.ErrorNoDoc, id)
}
newID, err := part.col.Update(physID[0], data)
if err != nil {
return
}
if newID != physID[0] {
part.lookup.Remove(id, physID[0])
part.lookup.Put(id, newID)
}
return
} | go | func (part *Partition) Update(id int, data []byte) (err error) {
physID := part.lookup.Get(id, 1)
if len(physID) == 0 {
return dberr.New(dberr.ErrorNoDoc, id)
}
newID, err := part.col.Update(physID[0], data)
if err != nil {
return
}
if newID != physID[0] {
part.lookup.Remove(id, physID[0])
part.lookup.Put(id, newID)
}
return
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"Update",
"(",
"id",
"int",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"physID",
":=",
"part",
".",
"lookup",
".",
"Get",
"(",
"id",
",",
"1",
")",
"\n",
"if",
"len",
"(",
"physID",
")",
"==",
"0",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorNoDoc",
",",
"id",
")",
"\n",
"}",
"\n",
"newID",
",",
"err",
":=",
"part",
".",
"col",
".",
"Update",
"(",
"physID",
"[",
"0",
"]",
",",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"newID",
"!=",
"physID",
"[",
"0",
"]",
"{",
"part",
".",
"lookup",
".",
"Remove",
"(",
"id",
",",
"physID",
"[",
"0",
"]",
")",
"\n",
"part",
".",
"lookup",
".",
"Put",
"(",
"id",
",",
"newID",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Update a document. | [
"Update",
"a",
"document",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L76-L90 |
HouzuoGuo/tiedot | data/partition.go | LockUpdate | func (part *Partition) LockUpdate(id int) {
for {
part.exclUpdateLock.Lock()
ch, ok := part.exclUpdate[id]
if !ok {
part.exclUpdate[id] = make(chan struct{})
}
part.exclUpdateLock.Unlock()
if ok {
<-ch
} else {
break
}
}
} | go | func (part *Partition) LockUpdate(id int) {
for {
part.exclUpdateLock.Lock()
ch, ok := part.exclUpdate[id]
if !ok {
part.exclUpdate[id] = make(chan struct{})
}
part.exclUpdateLock.Unlock()
if ok {
<-ch
} else {
break
}
}
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"LockUpdate",
"(",
"id",
"int",
")",
"{",
"for",
"{",
"part",
".",
"exclUpdateLock",
".",
"Lock",
"(",
")",
"\n",
"ch",
",",
"ok",
":=",
"part",
".",
"exclUpdate",
"[",
"id",
"]",
"\n",
"if",
"!",
"ok",
"{",
"part",
".",
"exclUpdate",
"[",
"id",
"]",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"}",
"\n",
"part",
".",
"exclUpdateLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"ok",
"{",
"<-",
"ch",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Lock a document for exclusive update. | [
"Lock",
"a",
"document",
"for",
"exclusive",
"update",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L93-L107 |
HouzuoGuo/tiedot | data/partition.go | UnlockUpdate | func (part *Partition) UnlockUpdate(id int) {
part.exclUpdateLock.Lock()
ch := part.exclUpdate[id]
delete(part.exclUpdate, id)
part.exclUpdateLock.Unlock()
close(ch)
} | go | func (part *Partition) UnlockUpdate(id int) {
part.exclUpdateLock.Lock()
ch := part.exclUpdate[id]
delete(part.exclUpdate, id)
part.exclUpdateLock.Unlock()
close(ch)
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"UnlockUpdate",
"(",
"id",
"int",
")",
"{",
"part",
".",
"exclUpdateLock",
".",
"Lock",
"(",
")",
"\n",
"ch",
":=",
"part",
".",
"exclUpdate",
"[",
"id",
"]",
"\n",
"delete",
"(",
"part",
".",
"exclUpdate",
",",
"id",
")",
"\n",
"part",
".",
"exclUpdateLock",
".",
"Unlock",
"(",
")",
"\n",
"close",
"(",
"ch",
")",
"\n",
"}"
] | // Unlock a document to make it ready for the next update. | [
"Unlock",
"a",
"document",
"to",
"make",
"it",
"ready",
"for",
"the",
"next",
"update",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L110-L116 |
HouzuoGuo/tiedot | data/partition.go | Delete | func (part *Partition) Delete(id int) (err error) {
physID := part.lookup.Get(id, 1)
if len(physID) == 0 {
return dberr.New(dberr.ErrorNoDoc, id)
}
part.col.Delete(physID[0])
part.lookup.Remove(id, physID[0])
return
} | go | func (part *Partition) Delete(id int) (err error) {
physID := part.lookup.Get(id, 1)
if len(physID) == 0 {
return dberr.New(dberr.ErrorNoDoc, id)
}
part.col.Delete(physID[0])
part.lookup.Remove(id, physID[0])
return
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"Delete",
"(",
"id",
"int",
")",
"(",
"err",
"error",
")",
"{",
"physID",
":=",
"part",
".",
"lookup",
".",
"Get",
"(",
"id",
",",
"1",
")",
"\n",
"if",
"len",
"(",
"physID",
")",
"==",
"0",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorNoDoc",
",",
"id",
")",
"\n",
"}",
"\n",
"part",
".",
"col",
".",
"Delete",
"(",
"physID",
"[",
"0",
"]",
")",
"\n",
"part",
".",
"lookup",
".",
"Remove",
"(",
"id",
",",
"physID",
"[",
"0",
"]",
")",
"\n",
"return",
"\n",
"}"
] | // Delete a document. | [
"Delete",
"a",
"document",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L119-L127 |
HouzuoGuo/tiedot | data/partition.go | ForEachDoc | func (part *Partition) ForEachDoc(partNum, totalPart int, fun func(id int, doc []byte) bool) (moveOn bool) {
ids, physIDs := part.lookup.GetPartition(partNum, totalPart)
for i, id := range ids {
data := part.col.Read(physIDs[i])
if data != nil {
if !fun(id, data) {
return false
}
}
}
return true
} | go | func (part *Partition) ForEachDoc(partNum, totalPart int, fun func(id int, doc []byte) bool) (moveOn bool) {
ids, physIDs := part.lookup.GetPartition(partNum, totalPart)
for i, id := range ids {
data := part.col.Read(physIDs[i])
if data != nil {
if !fun(id, data) {
return false
}
}
}
return true
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"ForEachDoc",
"(",
"partNum",
",",
"totalPart",
"int",
",",
"fun",
"func",
"(",
"id",
"int",
",",
"doc",
"[",
"]",
"byte",
")",
"bool",
")",
"(",
"moveOn",
"bool",
")",
"{",
"ids",
",",
"physIDs",
":=",
"part",
".",
"lookup",
".",
"GetPartition",
"(",
"partNum",
",",
"totalPart",
")",
"\n",
"for",
"i",
",",
"id",
":=",
"range",
"ids",
"{",
"data",
":=",
"part",
".",
"col",
".",
"Read",
"(",
"physIDs",
"[",
"i",
"]",
")",
"\n",
"if",
"data",
"!=",
"nil",
"{",
"if",
"!",
"fun",
"(",
"id",
",",
"data",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // Partition documents into roughly equally sized portions, and run the function on every document in the portion. | [
"Partition",
"documents",
"into",
"roughly",
"equally",
"sized",
"portions",
"and",
"run",
"the",
"function",
"on",
"every",
"document",
"in",
"the",
"portion",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L130-L141 |
HouzuoGuo/tiedot | data/partition.go | ApproxDocCount | func (part *Partition) ApproxDocCount() int {
totalPart := 24 // not magic; a larger number makes estimation less accurate, but improves performance
for {
keys, _ := part.lookup.GetPartition(0, totalPart)
if len(keys) == 0 {
if totalPart < 8 {
return 0 // the hash table is really really empty
}
// Try a larger partition size
totalPart = totalPart / 2
} else {
return int(float64(len(keys)) * float64(totalPart))
}
}
} | go | func (part *Partition) ApproxDocCount() int {
totalPart := 24 // not magic; a larger number makes estimation less accurate, but improves performance
for {
keys, _ := part.lookup.GetPartition(0, totalPart)
if len(keys) == 0 {
if totalPart < 8 {
return 0 // the hash table is really really empty
}
// Try a larger partition size
totalPart = totalPart / 2
} else {
return int(float64(len(keys)) * float64(totalPart))
}
}
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"ApproxDocCount",
"(",
")",
"int",
"{",
"totalPart",
":=",
"24",
"// not magic; a larger number makes estimation less accurate, but improves performance",
"\n",
"for",
"{",
"keys",
",",
"_",
":=",
"part",
".",
"lookup",
".",
"GetPartition",
"(",
"0",
",",
"totalPart",
")",
"\n",
"if",
"len",
"(",
"keys",
")",
"==",
"0",
"{",
"if",
"totalPart",
"<",
"8",
"{",
"return",
"0",
"// the hash table is really really empty",
"\n",
"}",
"\n",
"// Try a larger partition size",
"totalPart",
"=",
"totalPart",
"/",
"2",
"\n",
"}",
"else",
"{",
"return",
"int",
"(",
"float64",
"(",
"len",
"(",
"keys",
")",
")",
"*",
"float64",
"(",
"totalPart",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Return approximate number of documents in the partition. | [
"Return",
"approximate",
"number",
"of",
"documents",
"in",
"the",
"partition",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L144-L158 |
HouzuoGuo/tiedot | data/partition.go | Close | func (part *Partition) Close() error {
var err error
if e := part.col.Close(); e != nil {
tdlog.CritNoRepeat("Failed to close %s: %v", part.col.Path, e)
err = dberr.New(dberr.ErrorIO)
}
if e := part.lookup.Close(); e != nil {
tdlog.CritNoRepeat("Failed to close %s: %v", part.lookup.Path, e)
err = dberr.New(dberr.ErrorIO)
}
return err
} | go | func (part *Partition) Close() error {
var err error
if e := part.col.Close(); e != nil {
tdlog.CritNoRepeat("Failed to close %s: %v", part.col.Path, e)
err = dberr.New(dberr.ErrorIO)
}
if e := part.lookup.Close(); e != nil {
tdlog.CritNoRepeat("Failed to close %s: %v", part.lookup.Path, e)
err = dberr.New(dberr.ErrorIO)
}
return err
} | [
"func",
"(",
"part",
"*",
"Partition",
")",
"Close",
"(",
")",
"error",
"{",
"var",
"err",
"error",
"\n\n",
"if",
"e",
":=",
"part",
".",
"col",
".",
"Close",
"(",
")",
";",
"e",
"!=",
"nil",
"{",
"tdlog",
".",
"CritNoRepeat",
"(",
"\"",
"\"",
",",
"part",
".",
"col",
".",
"Path",
",",
"e",
")",
"\n",
"err",
"=",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorIO",
")",
"\n",
"}",
"\n",
"if",
"e",
":=",
"part",
".",
"lookup",
".",
"Close",
"(",
")",
";",
"e",
"!=",
"nil",
"{",
"tdlog",
".",
"CritNoRepeat",
"(",
"\"",
"\"",
",",
"part",
".",
"lookup",
".",
"Path",
",",
"e",
")",
"\n",
"err",
"=",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorIO",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // Close all file handles. | [
"Close",
"all",
"file",
"handles",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/partition.go#L181-L194 |
HouzuoGuo/tiedot | gommap/mmap.go | Map | func Map(f *os.File) (MMap, error) {
fd := uintptr(f.Fd())
fi, err := f.Stat()
if err != nil {
return nil, err
}
length := int(fi.Size())
if int64(length) != fi.Size() {
return nil, errors.New("memory map file length overflow")
}
return mmap(length, fd)
} | go | func Map(f *os.File) (MMap, error) {
fd := uintptr(f.Fd())
fi, err := f.Stat()
if err != nil {
return nil, err
}
length := int(fi.Size())
if int64(length) != fi.Size() {
return nil, errors.New("memory map file length overflow")
}
return mmap(length, fd)
} | [
"func",
"Map",
"(",
"f",
"*",
"os",
".",
"File",
")",
"(",
"MMap",
",",
"error",
")",
"{",
"fd",
":=",
"uintptr",
"(",
"f",
".",
"Fd",
"(",
")",
")",
"\n",
"fi",
",",
"err",
":=",
"f",
".",
"Stat",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"length",
":=",
"int",
"(",
"fi",
".",
"Size",
"(",
")",
")",
"\n",
"if",
"int64",
"(",
"length",
")",
"!=",
"fi",
".",
"Size",
"(",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"mmap",
"(",
"length",
",",
"fd",
")",
"\n",
"}"
] | // Map maps an entire file into memory.
// Note that because of runtime limitations, no file larger than about 2GB can
// be completely mapped into memory. | [
"Map",
"maps",
"an",
"entire",
"file",
"into",
"memory",
".",
"Note",
"that",
"because",
"of",
"runtime",
"limitations",
"no",
"file",
"larger",
"than",
"about",
"2GB",
"can",
"be",
"completely",
"mapped",
"into",
"memory",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/gommap/mmap.go#L30-L41 |
HouzuoGuo/tiedot | gommap/mmap.go | Unmap | func (m *MMap) Unmap() error {
dh := m.header()
err := unmap(dh.Data, uintptr(dh.Len))
*m = nil
return err
} | go | func (m *MMap) Unmap() error {
dh := m.header()
err := unmap(dh.Data, uintptr(dh.Len))
*m = nil
return err
} | [
"func",
"(",
"m",
"*",
"MMap",
")",
"Unmap",
"(",
")",
"error",
"{",
"dh",
":=",
"m",
".",
"header",
"(",
")",
"\n",
"err",
":=",
"unmap",
"(",
"dh",
".",
"Data",
",",
"uintptr",
"(",
"dh",
".",
"Len",
")",
")",
"\n",
"*",
"m",
"=",
"nil",
"\n",
"return",
"err",
"\n",
"}"
] | // Unmap deletes the memory mapped region, flushes any remaining changes, and sets
// m to nil.
// Trying to read or write any remaining references to m after Unmap is called will
// result in undefined behavior.
// Unmap should only be called on the slice value that was originally returned from
// a call to Map. Calling Unmap on a derived slice may cause errors. | [
"Unmap",
"deletes",
"the",
"memory",
"mapped",
"region",
"flushes",
"any",
"remaining",
"changes",
"and",
"sets",
"m",
"to",
"nil",
".",
"Trying",
"to",
"read",
"or",
"write",
"any",
"remaining",
"references",
"to",
"m",
"after",
"Unmap",
"is",
"called",
"will",
"result",
"in",
"undefined",
"behavior",
".",
"Unmap",
"should",
"only",
"be",
"called",
"on",
"the",
"slice",
"value",
"that",
"was",
"originally",
"returned",
"from",
"a",
"call",
"to",
"Map",
".",
"Calling",
"Unmap",
"on",
"a",
"derived",
"slice",
"may",
"cause",
"errors",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/gommap/mmap.go#L53-L58 |
HouzuoGuo/tiedot | httpapi/query.go | Query | func Query(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, q string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "q", &q) {
return
}
var qJson interface{}
if err := json.Unmarshal([]byte(q), &qJson); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON.", q), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
// Evaluate the query
queryResult := make(map[int]struct{})
if err := db.EvalQuery(qJson, dbcol, &queryResult); err != nil {
http.Error(w, fmt.Sprint(err), 400)
return
}
// Construct array of result
resultDocs := make(map[string]interface{}, len(queryResult))
counter := 0
for docID := range queryResult {
doc, _ := dbcol.Read(docID)
if doc != nil {
resultDocs[strconv.Itoa(docID)] = doc
counter++
}
}
// Serialize the array
resp, err := json.Marshal(resultDocs)
if err != nil {
http.Error(w, fmt.Sprintf("Server error: query returned invalid structure"), 500)
return
}
w.Write([]byte(string(resp)))
} | go | func Query(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, q string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "q", &q) {
return
}
var qJson interface{}
if err := json.Unmarshal([]byte(q), &qJson); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON.", q), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
// Evaluate the query
queryResult := make(map[int]struct{})
if err := db.EvalQuery(qJson, dbcol, &queryResult); err != nil {
http.Error(w, fmt.Sprint(err), 400)
return
}
// Construct array of result
resultDocs := make(map[string]interface{}, len(queryResult))
counter := 0
for docID := range queryResult {
doc, _ := dbcol.Read(docID)
if doc != nil {
resultDocs[strconv.Itoa(docID)] = doc
counter++
}
}
// Serialize the array
resp, err := json.Marshal(resultDocs)
if err != nil {
http.Error(w, fmt.Sprintf("Server error: query returned invalid structure"), 500)
return
}
w.Write([]byte(string(resp)))
} | [
"func",
"Query",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"col",
",",
"q",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"col",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"q",
")",
"{",
"return",
"\n",
"}",
"\n",
"var",
"qJson",
"interface",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"q",
")",
",",
"&",
"qJson",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"q",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"dbcol",
":=",
"HttpDB",
".",
"Use",
"(",
"col",
")",
"\n",
"if",
"dbcol",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"col",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// Evaluate the query",
"queryResult",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"\n",
"if",
"err",
":=",
"db",
".",
"EvalQuery",
"(",
"qJson",
",",
"dbcol",
",",
"&",
"queryResult",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// Construct array of result",
"resultDocs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"queryResult",
")",
")",
"\n",
"counter",
":=",
"0",
"\n",
"for",
"docID",
":=",
"range",
"queryResult",
"{",
"doc",
",",
"_",
":=",
"dbcol",
".",
"Read",
"(",
"docID",
")",
"\n",
"if",
"doc",
"!=",
"nil",
"{",
"resultDocs",
"[",
"strconv",
".",
"Itoa",
"(",
"docID",
")",
"]",
"=",
"doc",
"\n",
"counter",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"// Serialize the array",
"resp",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"resultDocs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
")",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"string",
"(",
"resp",
")",
")",
")",
"\n",
"}"
] | // Execute a query and return documents from the result. | [
"Execute",
"a",
"query",
"and",
"return",
"documents",
"from",
"the",
"result",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/query.go#L15-L60 |
HouzuoGuo/tiedot | httpapi/query.go | Count | func Count(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, q string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "q", &q) {
return
}
var qJson interface{}
if err := json.Unmarshal([]byte(q), &qJson); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON.", q), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
queryResult := make(map[int]struct{})
if err := db.EvalQuery(qJson, dbcol, &queryResult); err != nil {
http.Error(w, fmt.Sprint(err), 400)
return
}
w.Write([]byte(strconv.Itoa(len(queryResult))))
} | go | func Count(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, q string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "q", &q) {
return
}
var qJson interface{}
if err := json.Unmarshal([]byte(q), &qJson); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON.", q), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
queryResult := make(map[int]struct{})
if err := db.EvalQuery(qJson, dbcol, &queryResult); err != nil {
http.Error(w, fmt.Sprint(err), 400)
return
}
w.Write([]byte(strconv.Itoa(len(queryResult))))
} | [
"func",
"Count",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"var",
"col",
",",
"q",
"string",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"col",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"!",
"Require",
"(",
"w",
",",
"r",
",",
"\"",
"\"",
",",
"&",
"q",
")",
"{",
"return",
"\n",
"}",
"\n",
"var",
"qJson",
"interface",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"q",
")",
",",
"&",
"qJson",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"q",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"dbcol",
":=",
"HttpDB",
".",
"Use",
"(",
"col",
")",
"\n",
"if",
"dbcol",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"col",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"queryResult",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"\n",
"if",
"err",
":=",
"db",
".",
"EvalQuery",
"(",
"qJson",
",",
"dbcol",
",",
"&",
"queryResult",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprint",
"(",
"err",
")",
",",
"400",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"strconv",
".",
"Itoa",
"(",
"len",
"(",
"queryResult",
")",
")",
")",
")",
"\n",
"}"
] | // Execute a query and return number of documents from the result. | [
"Execute",
"a",
"query",
"and",
"return",
"number",
"of",
"documents",
"from",
"the",
"result",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/httpapi/query.go#L63-L91 |
HouzuoGuo/tiedot | db/col.go | OpenCol | func OpenCol(db *DB, name string) (*Col, error) {
col := &Col{db: db, name: name}
return col, col.load()
} | go | func OpenCol(db *DB, name string) (*Col, error) {
col := &Col{db: db, name: name}
return col, col.load()
} | [
"func",
"OpenCol",
"(",
"db",
"*",
"DB",
",",
"name",
"string",
")",
"(",
"*",
"Col",
",",
"error",
")",
"{",
"col",
":=",
"&",
"Col",
"{",
"db",
":",
"db",
",",
"name",
":",
"name",
"}",
"\n",
"return",
"col",
",",
"col",
".",
"load",
"(",
")",
"\n",
"}"
] | // Open a collection and load all indexes. | [
"Open",
"a",
"collection",
"and",
"load",
"all",
"indexes",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L33-L36 |
HouzuoGuo/tiedot | db/col.go | load | func (col *Col) load() error {
if err := os.MkdirAll(path.Join(col.db.path, col.name), 0700); err != nil {
return err
}
col.parts = make([]*data.Partition, col.db.numParts)
col.hts = make([]map[string]*data.HashTable, col.db.numParts)
for i := 0; i < col.db.numParts; i++ {
col.hts[i] = make(map[string]*data.HashTable)
}
col.indexPaths = make(map[string][]string)
// Open collection document partitions
for i := 0; i < col.db.numParts; i++ {
var err error
if col.parts[i], err = col.db.Config.OpenPartition(
path.Join(col.db.path, col.name, DOC_DATA_FILE+strconv.Itoa(i)),
path.Join(col.db.path, col.name, DOC_LOOKUP_FILE+strconv.Itoa(i))); err != nil {
return err
}
}
// Look for index directories
colDirContent, err := ioutil.ReadDir(path.Join(col.db.path, col.name))
if err != nil {
return err
}
for _, htDir := range colDirContent {
if !htDir.IsDir() {
continue
}
// Open index partitions
idxName := htDir.Name()
idxPath := strings.Split(idxName, INDEX_PATH_SEP)
col.indexPaths[idxName] = idxPath
for i := 0; i < col.db.numParts; i++ {
if col.hts[i][idxName], err = col.db.Config.OpenHashTable(
path.Join(col.db.path, col.name, idxName, strconv.Itoa(i))); err != nil {
return err
}
}
}
return nil
} | go | func (col *Col) load() error {
if err := os.MkdirAll(path.Join(col.db.path, col.name), 0700); err != nil {
return err
}
col.parts = make([]*data.Partition, col.db.numParts)
col.hts = make([]map[string]*data.HashTable, col.db.numParts)
for i := 0; i < col.db.numParts; i++ {
col.hts[i] = make(map[string]*data.HashTable)
}
col.indexPaths = make(map[string][]string)
// Open collection document partitions
for i := 0; i < col.db.numParts; i++ {
var err error
if col.parts[i], err = col.db.Config.OpenPartition(
path.Join(col.db.path, col.name, DOC_DATA_FILE+strconv.Itoa(i)),
path.Join(col.db.path, col.name, DOC_LOOKUP_FILE+strconv.Itoa(i))); err != nil {
return err
}
}
// Look for index directories
colDirContent, err := ioutil.ReadDir(path.Join(col.db.path, col.name))
if err != nil {
return err
}
for _, htDir := range colDirContent {
if !htDir.IsDir() {
continue
}
// Open index partitions
idxName := htDir.Name()
idxPath := strings.Split(idxName, INDEX_PATH_SEP)
col.indexPaths[idxName] = idxPath
for i := 0; i < col.db.numParts; i++ {
if col.hts[i][idxName], err = col.db.Config.OpenHashTable(
path.Join(col.db.path, col.name, idxName, strconv.Itoa(i))); err != nil {
return err
}
}
}
return nil
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"load",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"path",
".",
"Join",
"(",
"col",
".",
"db",
".",
"path",
",",
"col",
".",
"name",
")",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"col",
".",
"parts",
"=",
"make",
"(",
"[",
"]",
"*",
"data",
".",
"Partition",
",",
"col",
".",
"db",
".",
"numParts",
")",
"\n",
"col",
".",
"hts",
"=",
"make",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"*",
"data",
".",
"HashTable",
",",
"col",
".",
"db",
".",
"numParts",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"col",
".",
"db",
".",
"numParts",
";",
"i",
"++",
"{",
"col",
".",
"hts",
"[",
"i",
"]",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"data",
".",
"HashTable",
")",
"\n",
"}",
"\n",
"col",
".",
"indexPaths",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n",
"// Open collection document partitions",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"col",
".",
"db",
".",
"numParts",
";",
"i",
"++",
"{",
"var",
"err",
"error",
"\n",
"if",
"col",
".",
"parts",
"[",
"i",
"]",
",",
"err",
"=",
"col",
".",
"db",
".",
"Config",
".",
"OpenPartition",
"(",
"path",
".",
"Join",
"(",
"col",
".",
"db",
".",
"path",
",",
"col",
".",
"name",
",",
"DOC_DATA_FILE",
"+",
"strconv",
".",
"Itoa",
"(",
"i",
")",
")",
",",
"path",
".",
"Join",
"(",
"col",
".",
"db",
".",
"path",
",",
"col",
".",
"name",
",",
"DOC_LOOKUP_FILE",
"+",
"strconv",
".",
"Itoa",
"(",
"i",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// Look for index directories",
"colDirContent",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"path",
".",
"Join",
"(",
"col",
".",
"db",
".",
"path",
",",
"col",
".",
"name",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"htDir",
":=",
"range",
"colDirContent",
"{",
"if",
"!",
"htDir",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"// Open index partitions",
"idxName",
":=",
"htDir",
".",
"Name",
"(",
")",
"\n",
"idxPath",
":=",
"strings",
".",
"Split",
"(",
"idxName",
",",
"INDEX_PATH_SEP",
")",
"\n",
"col",
".",
"indexPaths",
"[",
"idxName",
"]",
"=",
"idxPath",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"col",
".",
"db",
".",
"numParts",
";",
"i",
"++",
"{",
"if",
"col",
".",
"hts",
"[",
"i",
"]",
"[",
"idxName",
"]",
",",
"err",
"=",
"col",
".",
"db",
".",
"Config",
".",
"OpenHashTable",
"(",
"path",
".",
"Join",
"(",
"col",
".",
"db",
".",
"path",
",",
"col",
".",
"name",
",",
"idxName",
",",
"strconv",
".",
"Itoa",
"(",
"i",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Load collection schema including index schema. | [
"Load",
"collection",
"schema",
"including",
"index",
"schema",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L39-L79 |
HouzuoGuo/tiedot | db/col.go | close | func (col *Col) close() error {
errs := make([]error, 0, 0)
for i := 0; i < col.db.numParts; i++ {
col.parts[i].DataLock.Lock()
if err := col.parts[i].Close(); err != nil {
errs = append(errs, err)
}
for _, ht := range col.hts[i] {
if err := ht.Close(); err != nil {
errs = append(errs, err)
}
}
col.parts[i].DataLock.Unlock()
}
if len(errs) == 0 {
return nil
}
return fmt.Errorf("%v", errs)
} | go | func (col *Col) close() error {
errs := make([]error, 0, 0)
for i := 0; i < col.db.numParts; i++ {
col.parts[i].DataLock.Lock()
if err := col.parts[i].Close(); err != nil {
errs = append(errs, err)
}
for _, ht := range col.hts[i] {
if err := ht.Close(); err != nil {
errs = append(errs, err)
}
}
col.parts[i].DataLock.Unlock()
}
if len(errs) == 0 {
return nil
}
return fmt.Errorf("%v", errs)
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"close",
"(",
")",
"error",
"{",
"errs",
":=",
"make",
"(",
"[",
"]",
"error",
",",
"0",
",",
"0",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"col",
".",
"db",
".",
"numParts",
";",
"i",
"++",
"{",
"col",
".",
"parts",
"[",
"i",
"]",
".",
"DataLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"err",
":=",
"col",
".",
"parts",
"[",
"i",
"]",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"ht",
":=",
"range",
"col",
".",
"hts",
"[",
"i",
"]",
"{",
"if",
"err",
":=",
"ht",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"col",
".",
"parts",
"[",
"i",
"]",
".",
"DataLock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"errs",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"errs",
")",
"\n",
"}"
] | // Close all collection files. Do not use the collection afterwards! | [
"Close",
"all",
"collection",
"files",
".",
"Do",
"not",
"use",
"the",
"collection",
"afterwards!"
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L82-L100 |
HouzuoGuo/tiedot | db/col.go | ForEachDoc | func (col *Col) ForEachDoc(fun func(id int, doc []byte) (moveOn bool)) {
col.forEachDoc(fun, true)
} | go | func (col *Col) ForEachDoc(fun func(id int, doc []byte) (moveOn bool)) {
col.forEachDoc(fun, true)
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"ForEachDoc",
"(",
"fun",
"func",
"(",
"id",
"int",
",",
"doc",
"[",
"]",
"byte",
")",
"(",
"moveOn",
"bool",
")",
")",
"{",
"col",
".",
"forEachDoc",
"(",
"fun",
",",
"true",
")",
"\n",
"}"
] | // Do fun for all documents in the collection. | [
"Do",
"fun",
"for",
"all",
"documents",
"in",
"the",
"collection",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L126-L128 |
HouzuoGuo/tiedot | db/col.go | Index | func (col *Col) Index(idxPath []string) (err error) {
col.db.schemaLock.Lock()
defer col.db.schemaLock.Unlock()
idxName := strings.Join(idxPath, INDEX_PATH_SEP)
if _, exists := col.indexPaths[idxName]; exists {
return fmt.Errorf("Path %v is already indexed", idxPath)
}
col.indexPaths[idxName] = idxPath
idxDir := path.Join(col.db.path, col.name, idxName)
if err = os.MkdirAll(idxDir, 0700); err != nil {
return err
}
for i := 0; i < col.db.numParts; i++ {
if col.hts[i][idxName], err = col.db.Config.OpenHashTable(path.Join(idxDir, strconv.Itoa(i))); err != nil {
return err
}
}
// Put all documents on the new index
col.forEachDoc(func(id int, doc []byte) (moveOn bool) {
var docObj map[string]interface{}
if err := json.Unmarshal(doc, &docObj); err != nil {
// Skip corrupted document
return true
}
for _, idxVal := range GetIn(docObj, idxPath) {
if idxVal != nil {
hashKey := StrHash(fmt.Sprint(idxVal))
col.hts[hashKey%col.db.numParts][idxName].Put(hashKey, id)
}
}
return true
}, false)
return
} | go | func (col *Col) Index(idxPath []string) (err error) {
col.db.schemaLock.Lock()
defer col.db.schemaLock.Unlock()
idxName := strings.Join(idxPath, INDEX_PATH_SEP)
if _, exists := col.indexPaths[idxName]; exists {
return fmt.Errorf("Path %v is already indexed", idxPath)
}
col.indexPaths[idxName] = idxPath
idxDir := path.Join(col.db.path, col.name, idxName)
if err = os.MkdirAll(idxDir, 0700); err != nil {
return err
}
for i := 0; i < col.db.numParts; i++ {
if col.hts[i][idxName], err = col.db.Config.OpenHashTable(path.Join(idxDir, strconv.Itoa(i))); err != nil {
return err
}
}
// Put all documents on the new index
col.forEachDoc(func(id int, doc []byte) (moveOn bool) {
var docObj map[string]interface{}
if err := json.Unmarshal(doc, &docObj); err != nil {
// Skip corrupted document
return true
}
for _, idxVal := range GetIn(docObj, idxPath) {
if idxVal != nil {
hashKey := StrHash(fmt.Sprint(idxVal))
col.hts[hashKey%col.db.numParts][idxName].Put(hashKey, id)
}
}
return true
}, false)
return
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"Index",
"(",
"idxPath",
"[",
"]",
"string",
")",
"(",
"err",
"error",
")",
"{",
"col",
".",
"db",
".",
"schemaLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"col",
".",
"db",
".",
"schemaLock",
".",
"Unlock",
"(",
")",
"\n",
"idxName",
":=",
"strings",
".",
"Join",
"(",
"idxPath",
",",
"INDEX_PATH_SEP",
")",
"\n",
"if",
"_",
",",
"exists",
":=",
"col",
".",
"indexPaths",
"[",
"idxName",
"]",
";",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"idxPath",
")",
"\n",
"}",
"\n",
"col",
".",
"indexPaths",
"[",
"idxName",
"]",
"=",
"idxPath",
"\n",
"idxDir",
":=",
"path",
".",
"Join",
"(",
"col",
".",
"db",
".",
"path",
",",
"col",
".",
"name",
",",
"idxName",
")",
"\n",
"if",
"err",
"=",
"os",
".",
"MkdirAll",
"(",
"idxDir",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"col",
".",
"db",
".",
"numParts",
";",
"i",
"++",
"{",
"if",
"col",
".",
"hts",
"[",
"i",
"]",
"[",
"idxName",
"]",
",",
"err",
"=",
"col",
".",
"db",
".",
"Config",
".",
"OpenHashTable",
"(",
"path",
".",
"Join",
"(",
"idxDir",
",",
"strconv",
".",
"Itoa",
"(",
"i",
")",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// Put all documents on the new index",
"col",
".",
"forEachDoc",
"(",
"func",
"(",
"id",
"int",
",",
"doc",
"[",
"]",
"byte",
")",
"(",
"moveOn",
"bool",
")",
"{",
"var",
"docObj",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"doc",
",",
"&",
"docObj",
")",
";",
"err",
"!=",
"nil",
"{",
"// Skip corrupted document",
"return",
"true",
"\n",
"}",
"\n",
"for",
"_",
",",
"idxVal",
":=",
"range",
"GetIn",
"(",
"docObj",
",",
"idxPath",
")",
"{",
"if",
"idxVal",
"!=",
"nil",
"{",
"hashKey",
":=",
"StrHash",
"(",
"fmt",
".",
"Sprint",
"(",
"idxVal",
")",
")",
"\n",
"col",
".",
"hts",
"[",
"hashKey",
"%",
"col",
".",
"db",
".",
"numParts",
"]",
"[",
"idxName",
"]",
".",
"Put",
"(",
"hashKey",
",",
"id",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
",",
"false",
")",
"\n",
"return",
"\n",
"}"
] | // Create an index on the path. | [
"Create",
"an",
"index",
"on",
"the",
"path",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L131-L164 |
HouzuoGuo/tiedot | db/col.go | AllIndexes | func (col *Col) AllIndexes() (ret [][]string) {
col.db.schemaLock.RLock()
defer col.db.schemaLock.RUnlock()
ret = make([][]string, 0, len(col.indexPaths))
for _, path := range col.indexPaths {
pathCopy := make([]string, len(path))
for i, p := range path {
pathCopy[i] = p
}
ret = append(ret, pathCopy)
}
return ret
} | go | func (col *Col) AllIndexes() (ret [][]string) {
col.db.schemaLock.RLock()
defer col.db.schemaLock.RUnlock()
ret = make([][]string, 0, len(col.indexPaths))
for _, path := range col.indexPaths {
pathCopy := make([]string, len(path))
for i, p := range path {
pathCopy[i] = p
}
ret = append(ret, pathCopy)
}
return ret
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"AllIndexes",
"(",
")",
"(",
"ret",
"[",
"]",
"[",
"]",
"string",
")",
"{",
"col",
".",
"db",
".",
"schemaLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"ret",
"=",
"make",
"(",
"[",
"]",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"col",
".",
"indexPaths",
")",
")",
"\n",
"for",
"_",
",",
"path",
":=",
"range",
"col",
".",
"indexPaths",
"{",
"pathCopy",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"path",
")",
")",
"\n",
"for",
"i",
",",
"p",
":=",
"range",
"path",
"{",
"pathCopy",
"[",
"i",
"]",
"=",
"p",
"\n",
"}",
"\n",
"ret",
"=",
"append",
"(",
"ret",
",",
"pathCopy",
")",
"\n",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] | // Return all indexed paths. | [
"Return",
"all",
"indexed",
"paths",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L167-L179 |
HouzuoGuo/tiedot | db/col.go | Unindex | func (col *Col) Unindex(idxPath []string) error {
col.db.schemaLock.Lock()
defer col.db.schemaLock.Unlock()
idxName := strings.Join(idxPath, INDEX_PATH_SEP)
if _, exists := col.indexPaths[idxName]; !exists {
return fmt.Errorf("Path %v is not indexed", idxPath)
}
delete(col.indexPaths, idxName)
for i := 0; i < col.db.numParts; i++ {
col.hts[i][idxName].Close()
delete(col.hts[i], idxName)
}
if err := os.RemoveAll(path.Join(col.db.path, col.name, idxName)); err != nil {
return err
}
return nil
} | go | func (col *Col) Unindex(idxPath []string) error {
col.db.schemaLock.Lock()
defer col.db.schemaLock.Unlock()
idxName := strings.Join(idxPath, INDEX_PATH_SEP)
if _, exists := col.indexPaths[idxName]; !exists {
return fmt.Errorf("Path %v is not indexed", idxPath)
}
delete(col.indexPaths, idxName)
for i := 0; i < col.db.numParts; i++ {
col.hts[i][idxName].Close()
delete(col.hts[i], idxName)
}
if err := os.RemoveAll(path.Join(col.db.path, col.name, idxName)); err != nil {
return err
}
return nil
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"Unindex",
"(",
"idxPath",
"[",
"]",
"string",
")",
"error",
"{",
"col",
".",
"db",
".",
"schemaLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"col",
".",
"db",
".",
"schemaLock",
".",
"Unlock",
"(",
")",
"\n",
"idxName",
":=",
"strings",
".",
"Join",
"(",
"idxPath",
",",
"INDEX_PATH_SEP",
")",
"\n",
"if",
"_",
",",
"exists",
":=",
"col",
".",
"indexPaths",
"[",
"idxName",
"]",
";",
"!",
"exists",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"idxPath",
")",
"\n",
"}",
"\n",
"delete",
"(",
"col",
".",
"indexPaths",
",",
"idxName",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"col",
".",
"db",
".",
"numParts",
";",
"i",
"++",
"{",
"col",
".",
"hts",
"[",
"i",
"]",
"[",
"idxName",
"]",
".",
"Close",
"(",
")",
"\n",
"delete",
"(",
"col",
".",
"hts",
"[",
"i",
"]",
",",
"idxName",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"os",
".",
"RemoveAll",
"(",
"path",
".",
"Join",
"(",
"col",
".",
"db",
".",
"path",
",",
"col",
".",
"name",
",",
"idxName",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Remove an index. | [
"Remove",
"an",
"index",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L182-L198 |
HouzuoGuo/tiedot | db/col.go | ForEachDocInPage | func (col *Col) ForEachDocInPage(page, total int, fun func(id int, doc []byte) bool) {
col.db.schemaLock.RLock()
defer col.db.schemaLock.RUnlock()
for iteratePart := 0; iteratePart < col.db.numParts; iteratePart++ {
part := col.parts[iteratePart]
part.DataLock.RLock()
if !part.ForEachDoc(page, total, fun) {
part.DataLock.RUnlock()
return
}
part.DataLock.RUnlock()
}
} | go | func (col *Col) ForEachDocInPage(page, total int, fun func(id int, doc []byte) bool) {
col.db.schemaLock.RLock()
defer col.db.schemaLock.RUnlock()
for iteratePart := 0; iteratePart < col.db.numParts; iteratePart++ {
part := col.parts[iteratePart]
part.DataLock.RLock()
if !part.ForEachDoc(page, total, fun) {
part.DataLock.RUnlock()
return
}
part.DataLock.RUnlock()
}
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"ForEachDocInPage",
"(",
"page",
",",
"total",
"int",
",",
"fun",
"func",
"(",
"id",
"int",
",",
"doc",
"[",
"]",
"byte",
")",
"bool",
")",
"{",
"col",
".",
"db",
".",
"schemaLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"for",
"iteratePart",
":=",
"0",
";",
"iteratePart",
"<",
"col",
".",
"db",
".",
"numParts",
";",
"iteratePart",
"++",
"{",
"part",
":=",
"col",
".",
"parts",
"[",
"iteratePart",
"]",
"\n",
"part",
".",
"DataLock",
".",
"RLock",
"(",
")",
"\n",
"if",
"!",
"part",
".",
"ForEachDoc",
"(",
"page",
",",
"total",
",",
"fun",
")",
"{",
"part",
".",
"DataLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"part",
".",
"DataLock",
".",
"RUnlock",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Divide the collection into roughly equally sized pages, and do fun on all documents in the specified page. | [
"Divide",
"the",
"collection",
"into",
"roughly",
"equally",
"sized",
"pages",
"and",
"do",
"fun",
"on",
"all",
"documents",
"in",
"the",
"specified",
"page",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/col.go#L220-L232 |
HouzuoGuo/tiedot | db/doc.go | GetIn | func GetIn(doc interface{}, path []string) (ret []interface{}) {
docMap, ok := doc.(map[string]interface{})
if !ok {
return
}
var thing interface{} = docMap
// Get into each path segment
for i, seg := range path {
if aMap, ok := thing.(map[string]interface{}); ok {
thing = aMap[seg]
} else if anArray, ok := thing.([]interface{}); ok {
for _, element := range anArray {
ret = append(ret, GetIn(element, path[i:])...)
}
return ret
} else {
return nil
}
}
switch thing := thing.(type) {
case []interface{}:
return append(ret, thing...)
default:
return append(ret, thing)
}
} | go | func GetIn(doc interface{}, path []string) (ret []interface{}) {
docMap, ok := doc.(map[string]interface{})
if !ok {
return
}
var thing interface{} = docMap
// Get into each path segment
for i, seg := range path {
if aMap, ok := thing.(map[string]interface{}); ok {
thing = aMap[seg]
} else if anArray, ok := thing.([]interface{}); ok {
for _, element := range anArray {
ret = append(ret, GetIn(element, path[i:])...)
}
return ret
} else {
return nil
}
}
switch thing := thing.(type) {
case []interface{}:
return append(ret, thing...)
default:
return append(ret, thing)
}
} | [
"func",
"GetIn",
"(",
"doc",
"interface",
"{",
"}",
",",
"path",
"[",
"]",
"string",
")",
"(",
"ret",
"[",
"]",
"interface",
"{",
"}",
")",
"{",
"docMap",
",",
"ok",
":=",
"doc",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"var",
"thing",
"interface",
"{",
"}",
"=",
"docMap",
"\n",
"// Get into each path segment",
"for",
"i",
",",
"seg",
":=",
"range",
"path",
"{",
"if",
"aMap",
",",
"ok",
":=",
"thing",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"thing",
"=",
"aMap",
"[",
"seg",
"]",
"\n",
"}",
"else",
"if",
"anArray",
",",
"ok",
":=",
"thing",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"for",
"_",
",",
"element",
":=",
"range",
"anArray",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"GetIn",
"(",
"element",
",",
"path",
"[",
"i",
":",
"]",
")",
"...",
")",
"\n",
"}",
"\n",
"return",
"ret",
"\n",
"}",
"else",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"switch",
"thing",
":=",
"thing",
".",
"(",
"type",
")",
"{",
"case",
"[",
"]",
"interface",
"{",
"}",
":",
"return",
"append",
"(",
"ret",
",",
"thing",
"...",
")",
"\n",
"default",
":",
"return",
"append",
"(",
"ret",
",",
"thing",
")",
"\n",
"}",
"\n",
"}"
] | // Resolve the attribute(s) in the document structure along the given path. | [
"Resolve",
"the",
"attribute",
"(",
"s",
")",
"in",
"the",
"document",
"structure",
"along",
"the",
"given",
"path",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/doc.go#L14-L39 |
HouzuoGuo/tiedot | db/doc.go | StrHash | func StrHash(str string) int {
var hash int
for _, c := range str {
hash = int(c) + (hash << 6) + (hash << 16) - hash
}
if hash < 0 {
return -hash
}
return hash
} | go | func StrHash(str string) int {
var hash int
for _, c := range str {
hash = int(c) + (hash << 6) + (hash << 16) - hash
}
if hash < 0 {
return -hash
}
return hash
} | [
"func",
"StrHash",
"(",
"str",
"string",
")",
"int",
"{",
"var",
"hash",
"int",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"str",
"{",
"hash",
"=",
"int",
"(",
"c",
")",
"+",
"(",
"hash",
"<<",
"6",
")",
"+",
"(",
"hash",
"<<",
"16",
")",
"-",
"hash",
"\n",
"}",
"\n",
"if",
"hash",
"<",
"0",
"{",
"return",
"-",
"hash",
"\n",
"}",
"\n",
"return",
"hash",
"\n",
"}"
] | // Hash a string using sdbm algorithm. | [
"Hash",
"a",
"string",
"using",
"sdbm",
"algorithm",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/doc.go#L42-L51 |
HouzuoGuo/tiedot | db/doc.go | indexDoc | func (col *Col) indexDoc(id int, doc map[string]interface{}) {
for idxName, idxPath := range col.indexPaths {
for _, idxVal := range GetIn(doc, idxPath) {
if idxVal != nil {
hashKey := StrHash(fmt.Sprint(idxVal))
partNum := hashKey % col.db.numParts
ht := col.hts[partNum][idxName]
ht.Lock.Lock()
ht.Put(hashKey, id)
ht.Lock.Unlock()
}
}
}
} | go | func (col *Col) indexDoc(id int, doc map[string]interface{}) {
for idxName, idxPath := range col.indexPaths {
for _, idxVal := range GetIn(doc, idxPath) {
if idxVal != nil {
hashKey := StrHash(fmt.Sprint(idxVal))
partNum := hashKey % col.db.numParts
ht := col.hts[partNum][idxName]
ht.Lock.Lock()
ht.Put(hashKey, id)
ht.Lock.Unlock()
}
}
}
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"indexDoc",
"(",
"id",
"int",
",",
"doc",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"{",
"for",
"idxName",
",",
"idxPath",
":=",
"range",
"col",
".",
"indexPaths",
"{",
"for",
"_",
",",
"idxVal",
":=",
"range",
"GetIn",
"(",
"doc",
",",
"idxPath",
")",
"{",
"if",
"idxVal",
"!=",
"nil",
"{",
"hashKey",
":=",
"StrHash",
"(",
"fmt",
".",
"Sprint",
"(",
"idxVal",
")",
")",
"\n",
"partNum",
":=",
"hashKey",
"%",
"col",
".",
"db",
".",
"numParts",
"\n",
"ht",
":=",
"col",
".",
"hts",
"[",
"partNum",
"]",
"[",
"idxName",
"]",
"\n",
"ht",
".",
"Lock",
".",
"Lock",
"(",
")",
"\n",
"ht",
".",
"Put",
"(",
"hashKey",
",",
"id",
")",
"\n",
"ht",
".",
"Lock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Put a document on all user-created indexes. | [
"Put",
"a",
"document",
"on",
"all",
"user",
"-",
"created",
"indexes",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/doc.go#L54-L67 |
HouzuoGuo/tiedot | db/doc.go | InsertRecovery | func (col *Col) InsertRecovery(id int, doc map[string]interface{}) (err error) {
docJS, err := json.Marshal(doc)
if err != nil {
return
}
partNum := id % col.db.numParts
part := col.parts[partNum]
// Put document data into collection
if _, err = part.Insert(id, []byte(docJS)); err != nil {
return
}
// Index the document
col.indexDoc(id, doc)
return
} | go | func (col *Col) InsertRecovery(id int, doc map[string]interface{}) (err error) {
docJS, err := json.Marshal(doc)
if err != nil {
return
}
partNum := id % col.db.numParts
part := col.parts[partNum]
// Put document data into collection
if _, err = part.Insert(id, []byte(docJS)); err != nil {
return
}
// Index the document
col.indexDoc(id, doc)
return
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"InsertRecovery",
"(",
"id",
"int",
",",
"doc",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"docJS",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"doc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"partNum",
":=",
"id",
"%",
"col",
".",
"db",
".",
"numParts",
"\n",
"part",
":=",
"col",
".",
"parts",
"[",
"partNum",
"]",
"\n",
"// Put document data into collection",
"if",
"_",
",",
"err",
"=",
"part",
".",
"Insert",
"(",
"id",
",",
"[",
"]",
"byte",
"(",
"docJS",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"// Index the document",
"col",
".",
"indexDoc",
"(",
"id",
",",
"doc",
")",
"\n",
"return",
"\n",
"}"
] | // Insert a document with the specified ID into the collection (incl. index). Does not place partition/schema lock. | [
"Insert",
"a",
"document",
"with",
"the",
"specified",
"ID",
"into",
"the",
"collection",
"(",
"incl",
".",
"index",
")",
".",
"Does",
"not",
"place",
"partition",
"/",
"schema",
"lock",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/doc.go#L86-L100 |
HouzuoGuo/tiedot | db/doc.go | Insert | func (col *Col) Insert(doc map[string]interface{}) (id int, err error) {
docJS, err := json.Marshal(doc)
if err != nil {
return
}
id = rand.Int()
partNum := id % col.db.numParts
col.db.schemaLock.RLock()
part := col.parts[partNum]
// Put document data into collection
part.DataLock.Lock()
_, err = part.Insert(id, []byte(docJS))
part.DataLock.Unlock()
if err != nil {
col.db.schemaLock.RUnlock()
return
}
part.LockUpdate(id)
// Index the document
col.indexDoc(id, doc)
part.UnlockUpdate(id)
col.db.schemaLock.RUnlock()
return
} | go | func (col *Col) Insert(doc map[string]interface{}) (id int, err error) {
docJS, err := json.Marshal(doc)
if err != nil {
return
}
id = rand.Int()
partNum := id % col.db.numParts
col.db.schemaLock.RLock()
part := col.parts[partNum]
// Put document data into collection
part.DataLock.Lock()
_, err = part.Insert(id, []byte(docJS))
part.DataLock.Unlock()
if err != nil {
col.db.schemaLock.RUnlock()
return
}
part.LockUpdate(id)
// Index the document
col.indexDoc(id, doc)
part.UnlockUpdate(id)
col.db.schemaLock.RUnlock()
return
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"Insert",
"(",
"doc",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"id",
"int",
",",
"err",
"error",
")",
"{",
"docJS",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"doc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"id",
"=",
"rand",
".",
"Int",
"(",
")",
"\n",
"partNum",
":=",
"id",
"%",
"col",
".",
"db",
".",
"numParts",
"\n",
"col",
".",
"db",
".",
"schemaLock",
".",
"RLock",
"(",
")",
"\n",
"part",
":=",
"col",
".",
"parts",
"[",
"partNum",
"]",
"\n\n",
"// Put document data into collection",
"part",
".",
"DataLock",
".",
"Lock",
"(",
")",
"\n",
"_",
",",
"err",
"=",
"part",
".",
"Insert",
"(",
"id",
",",
"[",
"]",
"byte",
"(",
"docJS",
")",
")",
"\n",
"part",
".",
"DataLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"part",
".",
"LockUpdate",
"(",
"id",
")",
"\n",
"// Index the document",
"col",
".",
"indexDoc",
"(",
"id",
",",
"doc",
")",
"\n",
"part",
".",
"UnlockUpdate",
"(",
"id",
")",
"\n\n",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Insert a document into the collection. | [
"Insert",
"a",
"document",
"into",
"the",
"collection",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/doc.go#L103-L129 |
HouzuoGuo/tiedot | db/doc.go | Read | func (col *Col) Read(id int) (doc map[string]interface{}, err error) {
return col.read(id, true)
} | go | func (col *Col) Read(id int) (doc map[string]interface{}, err error) {
return col.read(id, true)
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"Read",
"(",
"id",
"int",
")",
"(",
"doc",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"return",
"col",
".",
"read",
"(",
"id",
",",
"true",
")",
"\n",
"}"
] | // Find and retrieve a document by ID. | [
"Find",
"and",
"retrieve",
"a",
"document",
"by",
"ID",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/doc.go#L155-L157 |
HouzuoGuo/tiedot | db/doc.go | Update | func (col *Col) Update(id int, doc map[string]interface{}) error {
if doc == nil {
return fmt.Errorf("Updating %d: input doc may not be nil", id)
}
docJS, err := json.Marshal(doc)
if err != nil {
return err
}
col.db.schemaLock.RLock()
part := col.parts[id%col.db.numParts]
// Place lock, read back original document and update
part.DataLock.Lock()
originalB, err := part.Read(id)
if err != nil {
part.DataLock.Unlock()
col.db.schemaLock.RUnlock()
return err
}
err = part.Update(id, []byte(docJS))
part.DataLock.Unlock()
if err != nil {
col.db.schemaLock.RUnlock()
return err
}
// Done with the collection data, next is to maintain indexed values
var original map[string]interface{}
json.Unmarshal(originalB, &original)
part.LockUpdate(id)
if original != nil {
col.unindexDoc(id, original)
} else {
tdlog.Noticef("Will not attempt to unindex document %d during update", id)
}
col.indexDoc(id, doc)
// Done with the index
part.UnlockUpdate(id)
col.db.schemaLock.RUnlock()
return nil
} | go | func (col *Col) Update(id int, doc map[string]interface{}) error {
if doc == nil {
return fmt.Errorf("Updating %d: input doc may not be nil", id)
}
docJS, err := json.Marshal(doc)
if err != nil {
return err
}
col.db.schemaLock.RLock()
part := col.parts[id%col.db.numParts]
// Place lock, read back original document and update
part.DataLock.Lock()
originalB, err := part.Read(id)
if err != nil {
part.DataLock.Unlock()
col.db.schemaLock.RUnlock()
return err
}
err = part.Update(id, []byte(docJS))
part.DataLock.Unlock()
if err != nil {
col.db.schemaLock.RUnlock()
return err
}
// Done with the collection data, next is to maintain indexed values
var original map[string]interface{}
json.Unmarshal(originalB, &original)
part.LockUpdate(id)
if original != nil {
col.unindexDoc(id, original)
} else {
tdlog.Noticef("Will not attempt to unindex document %d during update", id)
}
col.indexDoc(id, doc)
// Done with the index
part.UnlockUpdate(id)
col.db.schemaLock.RUnlock()
return nil
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"Update",
"(",
"id",
"int",
",",
"doc",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"doc",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"}",
"\n",
"docJS",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"doc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"col",
".",
"db",
".",
"schemaLock",
".",
"RLock",
"(",
")",
"\n",
"part",
":=",
"col",
".",
"parts",
"[",
"id",
"%",
"col",
".",
"db",
".",
"numParts",
"]",
"\n\n",
"// Place lock, read back original document and update",
"part",
".",
"DataLock",
".",
"Lock",
"(",
")",
"\n",
"originalB",
",",
"err",
":=",
"part",
".",
"Read",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"part",
".",
"DataLock",
".",
"Unlock",
"(",
")",
"\n",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"part",
".",
"Update",
"(",
"id",
",",
"[",
"]",
"byte",
"(",
"docJS",
")",
")",
"\n",
"part",
".",
"DataLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Done with the collection data, next is to maintain indexed values",
"var",
"original",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"json",
".",
"Unmarshal",
"(",
"originalB",
",",
"&",
"original",
")",
"\n",
"part",
".",
"LockUpdate",
"(",
"id",
")",
"\n",
"if",
"original",
"!=",
"nil",
"{",
"col",
".",
"unindexDoc",
"(",
"id",
",",
"original",
")",
"\n",
"}",
"else",
"{",
"tdlog",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"}",
"\n",
"col",
".",
"indexDoc",
"(",
"id",
",",
"doc",
")",
"\n",
"// Done with the index",
"part",
".",
"UnlockUpdate",
"(",
"id",
")",
"\n\n",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Update a document. | [
"Update",
"a",
"document",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/doc.go#L160-L201 |
HouzuoGuo/tiedot | db/doc.go | UpdateBytesFunc | func (col *Col) UpdateBytesFunc(id int, update func(origDoc []byte) (newDoc []byte, err error)) error {
col.db.schemaLock.RLock()
part := col.parts[id%col.db.numParts]
// Place lock, read back original document and update
part.DataLock.Lock()
originalB, err := part.Read(id)
if err != nil {
part.DataLock.Unlock()
col.db.schemaLock.RUnlock()
return err
}
var original map[string]interface{}
json.Unmarshal(originalB, &original) // Unmarshal originalB before passing it to update
docB, err := update(originalB)
if err != nil {
part.DataLock.Unlock()
col.db.schemaLock.RUnlock()
return err
}
var doc map[string]interface{} // check if docB are valid JSON before Update
if err = json.Unmarshal(docB, &doc); err != nil {
part.DataLock.Unlock()
col.db.schemaLock.RUnlock()
return err
}
err = part.Update(id, docB)
part.DataLock.Unlock()
if err != nil {
col.db.schemaLock.RUnlock()
return err
}
// Done with the collection data, next is to maintain indexed values
part.LockUpdate(id)
if original != nil {
col.unindexDoc(id, original)
} else {
tdlog.Noticef("Will not attempt to unindex document %d during update", id)
}
col.indexDoc(id, doc)
// Done with the index
part.UnlockUpdate(id)
col.db.schemaLock.RUnlock()
return nil
} | go | func (col *Col) UpdateBytesFunc(id int, update func(origDoc []byte) (newDoc []byte, err error)) error {
col.db.schemaLock.RLock()
part := col.parts[id%col.db.numParts]
// Place lock, read back original document and update
part.DataLock.Lock()
originalB, err := part.Read(id)
if err != nil {
part.DataLock.Unlock()
col.db.schemaLock.RUnlock()
return err
}
var original map[string]interface{}
json.Unmarshal(originalB, &original) // Unmarshal originalB before passing it to update
docB, err := update(originalB)
if err != nil {
part.DataLock.Unlock()
col.db.schemaLock.RUnlock()
return err
}
var doc map[string]interface{} // check if docB are valid JSON before Update
if err = json.Unmarshal(docB, &doc); err != nil {
part.DataLock.Unlock()
col.db.schemaLock.RUnlock()
return err
}
err = part.Update(id, docB)
part.DataLock.Unlock()
if err != nil {
col.db.schemaLock.RUnlock()
return err
}
// Done with the collection data, next is to maintain indexed values
part.LockUpdate(id)
if original != nil {
col.unindexDoc(id, original)
} else {
tdlog.Noticef("Will not attempt to unindex document %d during update", id)
}
col.indexDoc(id, doc)
// Done with the index
part.UnlockUpdate(id)
col.db.schemaLock.RUnlock()
return nil
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"UpdateBytesFunc",
"(",
"id",
"int",
",",
"update",
"func",
"(",
"origDoc",
"[",
"]",
"byte",
")",
"(",
"newDoc",
"[",
"]",
"byte",
",",
"err",
"error",
")",
")",
"error",
"{",
"col",
".",
"db",
".",
"schemaLock",
".",
"RLock",
"(",
")",
"\n",
"part",
":=",
"col",
".",
"parts",
"[",
"id",
"%",
"col",
".",
"db",
".",
"numParts",
"]",
"\n\n",
"// Place lock, read back original document and update",
"part",
".",
"DataLock",
".",
"Lock",
"(",
")",
"\n",
"originalB",
",",
"err",
":=",
"part",
".",
"Read",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"part",
".",
"DataLock",
".",
"Unlock",
"(",
")",
"\n",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"var",
"original",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"json",
".",
"Unmarshal",
"(",
"originalB",
",",
"&",
"original",
")",
"// Unmarshal originalB before passing it to update",
"\n",
"docB",
",",
"err",
":=",
"update",
"(",
"originalB",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"part",
".",
"DataLock",
".",
"Unlock",
"(",
")",
"\n",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"var",
"doc",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"// check if docB are valid JSON before Update",
"\n",
"if",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"docB",
",",
"&",
"doc",
")",
";",
"err",
"!=",
"nil",
"{",
"part",
".",
"DataLock",
".",
"Unlock",
"(",
")",
"\n",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"part",
".",
"Update",
"(",
"id",
",",
"docB",
")",
"\n",
"part",
".",
"DataLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Done with the collection data, next is to maintain indexed values",
"part",
".",
"LockUpdate",
"(",
"id",
")",
"\n",
"if",
"original",
"!=",
"nil",
"{",
"col",
".",
"unindexDoc",
"(",
"id",
",",
"original",
")",
"\n",
"}",
"else",
"{",
"tdlog",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"}",
"\n",
"col",
".",
"indexDoc",
"(",
"id",
",",
"doc",
")",
"\n",
"// Done with the index",
"part",
".",
"UnlockUpdate",
"(",
"id",
")",
"\n\n",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // UpdateBytesFunc will update a document bytes.
// update func will get current document bytes and should return bytes of updated document;
// updated document should be valid JSON;
// provided buffer could be modified (reused for returned value);
// non-nil error will be propagated back and returned from UpdateBytesFunc. | [
"UpdateBytesFunc",
"will",
"update",
"a",
"document",
"bytes",
".",
"update",
"func",
"will",
"get",
"current",
"document",
"bytes",
"and",
"should",
"return",
"bytes",
"of",
"updated",
"document",
";",
"updated",
"document",
"should",
"be",
"valid",
"JSON",
";",
"provided",
"buffer",
"could",
"be",
"modified",
"(",
"reused",
"for",
"returned",
"value",
")",
";",
"non",
"-",
"nil",
"error",
"will",
"be",
"propagated",
"back",
"and",
"returned",
"from",
"UpdateBytesFunc",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/doc.go#L208-L254 |
HouzuoGuo/tiedot | db/doc.go | Delete | func (col *Col) Delete(id int) error {
col.db.schemaLock.RLock()
part := col.parts[id%col.db.numParts]
// Place lock, read back original document and delete document
part.DataLock.Lock()
originalB, err := part.Read(id)
if err != nil {
part.DataLock.Unlock()
col.db.schemaLock.RUnlock()
return err
}
err = part.Delete(id)
part.DataLock.Unlock()
if err != nil {
col.db.schemaLock.RUnlock()
return err
}
// Done with the collection data, next is to remove indexed values
var original map[string]interface{}
err = json.Unmarshal(originalB, &original)
if err == nil {
part.LockUpdate(id)
col.unindexDoc(id, original)
part.UnlockUpdate(id)
} else {
tdlog.Noticef("Will not attempt to unindex document %d during delete", id)
}
col.db.schemaLock.RUnlock()
return nil
} | go | func (col *Col) Delete(id int) error {
col.db.schemaLock.RLock()
part := col.parts[id%col.db.numParts]
// Place lock, read back original document and delete document
part.DataLock.Lock()
originalB, err := part.Read(id)
if err != nil {
part.DataLock.Unlock()
col.db.schemaLock.RUnlock()
return err
}
err = part.Delete(id)
part.DataLock.Unlock()
if err != nil {
col.db.schemaLock.RUnlock()
return err
}
// Done with the collection data, next is to remove indexed values
var original map[string]interface{}
err = json.Unmarshal(originalB, &original)
if err == nil {
part.LockUpdate(id)
col.unindexDoc(id, original)
part.UnlockUpdate(id)
} else {
tdlog.Noticef("Will not attempt to unindex document %d during delete", id)
}
col.db.schemaLock.RUnlock()
return nil
} | [
"func",
"(",
"col",
"*",
"Col",
")",
"Delete",
"(",
"id",
"int",
")",
"error",
"{",
"col",
".",
"db",
".",
"schemaLock",
".",
"RLock",
"(",
")",
"\n",
"part",
":=",
"col",
".",
"parts",
"[",
"id",
"%",
"col",
".",
"db",
".",
"numParts",
"]",
"\n\n",
"// Place lock, read back original document and delete document",
"part",
".",
"DataLock",
".",
"Lock",
"(",
")",
"\n",
"originalB",
",",
"err",
":=",
"part",
".",
"Read",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"part",
".",
"DataLock",
".",
"Unlock",
"(",
")",
"\n",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"part",
".",
"Delete",
"(",
"id",
")",
"\n",
"part",
".",
"DataLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Done with the collection data, next is to remove indexed values",
"var",
"original",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"originalB",
",",
"&",
"original",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"part",
".",
"LockUpdate",
"(",
"id",
")",
"\n",
"col",
".",
"unindexDoc",
"(",
"id",
",",
"original",
")",
"\n",
"part",
".",
"UnlockUpdate",
"(",
"id",
")",
"\n",
"}",
"else",
"{",
"tdlog",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"id",
")",
"\n",
"}",
"\n\n",
"col",
".",
"db",
".",
"schemaLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Delete a document. | [
"Delete",
"a",
"document",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/doc.go#L310-L342 |
HouzuoGuo/tiedot | tdlog/tdlog.go | CritNoRepeat | func CritNoRepeat(template string, params ...interface{}) {
msg := fmt.Sprintf(template, params...)
critLock.Lock()
if _, exists := critHistory[msg]; !exists {
log.Print(msg)
critHistory[msg] = struct{}{}
}
if len(critHistory) > limitCritHistory {
critHistory = make(map[string]struct{})
}
critLock.Unlock()
} | go | func CritNoRepeat(template string, params ...interface{}) {
msg := fmt.Sprintf(template, params...)
critLock.Lock()
if _, exists := critHistory[msg]; !exists {
log.Print(msg)
critHistory[msg] = struct{}{}
}
if len(critHistory) > limitCritHistory {
critHistory = make(map[string]struct{})
}
critLock.Unlock()
} | [
"func",
"CritNoRepeat",
"(",
"template",
"string",
",",
"params",
"...",
"interface",
"{",
"}",
")",
"{",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"template",
",",
"params",
"...",
")",
"\n",
"critLock",
".",
"Lock",
"(",
")",
"\n",
"if",
"_",
",",
"exists",
":=",
"critHistory",
"[",
"msg",
"]",
";",
"!",
"exists",
"{",
"log",
".",
"Print",
"(",
"msg",
")",
"\n",
"critHistory",
"[",
"msg",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"critHistory",
")",
">",
"limitCritHistory",
"{",
"critHistory",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"}",
"\n",
"critLock",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // LVL 2 - will not repeat a message twice over the past 100 distinct crit messages | [
"LVL",
"2",
"-",
"will",
"not",
"repeat",
"a",
"message",
"twice",
"over",
"the",
"past",
"100",
"distinct",
"crit",
"messages"
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/tdlog/tdlog.go#L41-L52 |
HouzuoGuo/tiedot | examples/example.go | EmbeddedExample | func EmbeddedExample() {
// ****************** Collection Management ******************
myDBDir := "/tmp/MyDatabase"
os.RemoveAll(myDBDir)
defer os.RemoveAll(myDBDir)
// (Create if not exist) open a database
myDB, err := db.OpenDB(myDBDir)
if err != nil {
panic(err)
}
// Create two collections: Feeds and Votes
if err := myDB.Create("Feeds"); err != nil {
panic(err)
}
if err := myDB.Create("Votes"); err != nil {
panic(err)
}
// What collections do I now have?
for _, name := range myDB.AllCols() {
fmt.Printf("I have a collection called %s\n", name)
}
// Rename collection "Votes" to "Points"
if err := myDB.Rename("Votes", "Points"); err != nil {
panic(err)
}
// Drop (delete) collection "Points"
if err := myDB.Drop("Points"); err != nil {
panic(err)
}
// Scrub (repair and compact) "Feeds"
if err := myDB.Scrub("Feeds"); err != nil {
panic(err)
}
// ****************** Document Management ******************
// Start using a collection (the reference is valid until DB schema changes or Scrub is carried out)
feeds := myDB.Use("Feeds")
// Insert document (afterwards the docID uniquely identifies the document and will never change)
docID, err := feeds.Insert(map[string]interface{}{
"name": "Go 1.2 is released",
"url": "golang.org"})
if err != nil {
panic(err)
}
// Read document
readBack, err := feeds.Read(docID)
if err != nil {
panic(err)
}
fmt.Println("Document", docID, "is", readBack)
// Update document
err = feeds.Update(docID, map[string]interface{}{
"name": "Go is very popular",
"url": "google.com"})
if err != nil {
panic(err)
}
// Process all documents (note that document order is undetermined)
feeds.ForEachDoc(func(id int, docContent []byte) (willMoveOn bool) {
fmt.Println("Document", id, "is", string(docContent))
return true // move on to the next document OR
return false // do not move on to the next document
})
// Delete document
if err := feeds.Delete(docID); err != nil {
panic(err)
}
// More complicated error handing - identify the error Type.
// In this example, the error code tells that the document no longer exists.
if err := feeds.Delete(docID); dberr.Type(err) == dberr.ErrorNoDoc {
fmt.Println("The document was already deleted")
}
// ****************** Index Management ******************
// Indexes assist in many types of queries
// Create index (path leads to document JSON attribute)
if err := feeds.Index([]string{"author", "name", "first_name"}); err != nil {
panic(err)
}
if err := feeds.Index([]string{"Title"}); err != nil {
panic(err)
}
if err := feeds.Index([]string{"Source"}); err != nil {
panic(err)
}
// What indexes do I have on collection A?
for _, path := range feeds.AllIndexes() {
fmt.Printf("I have an index on path %v\n", path)
}
// Remove index
if err := feeds.Unindex([]string{"author", "name", "first_name"}); err != nil {
panic(err)
}
// ****************** Queries ******************
// Prepare some documents for the query
feeds.Insert(map[string]interface{}{"Title": "New Go release", "Source": "golang.org", "Age": 3})
feeds.Insert(map[string]interface{}{"Title": "Kitkat is here", "Source": "google.com", "Age": 2})
feeds.Insert(map[string]interface{}{"Title": "Good Slackware", "Source": "slackware.com", "Age": 1})
var query interface{}
json.Unmarshal([]byte(`[{"eq": "New Go release", "in": ["Title"]}, {"eq": "slackware.com", "in": ["Source"]}]`), &query)
queryResult := make(map[int]struct{}) // query result (document IDs) goes into map keys
if err := db.EvalQuery(query, feeds, &queryResult); err != nil {
panic(err)
}
// Query result are document IDs
for id := range queryResult {
// To get query result document, simply read it
readBack, err := feeds.Read(id)
if err != nil {
panic(err)
}
fmt.Printf("Query returned document %v\n", readBack)
}
// Gracefully close database
if err := myDB.Close(); err != nil {
panic(err)
}
} | go | func EmbeddedExample() {
// ****************** Collection Management ******************
myDBDir := "/tmp/MyDatabase"
os.RemoveAll(myDBDir)
defer os.RemoveAll(myDBDir)
// (Create if not exist) open a database
myDB, err := db.OpenDB(myDBDir)
if err != nil {
panic(err)
}
// Create two collections: Feeds and Votes
if err := myDB.Create("Feeds"); err != nil {
panic(err)
}
if err := myDB.Create("Votes"); err != nil {
panic(err)
}
// What collections do I now have?
for _, name := range myDB.AllCols() {
fmt.Printf("I have a collection called %s\n", name)
}
// Rename collection "Votes" to "Points"
if err := myDB.Rename("Votes", "Points"); err != nil {
panic(err)
}
// Drop (delete) collection "Points"
if err := myDB.Drop("Points"); err != nil {
panic(err)
}
// Scrub (repair and compact) "Feeds"
if err := myDB.Scrub("Feeds"); err != nil {
panic(err)
}
// ****************** Document Management ******************
// Start using a collection (the reference is valid until DB schema changes or Scrub is carried out)
feeds := myDB.Use("Feeds")
// Insert document (afterwards the docID uniquely identifies the document and will never change)
docID, err := feeds.Insert(map[string]interface{}{
"name": "Go 1.2 is released",
"url": "golang.org"})
if err != nil {
panic(err)
}
// Read document
readBack, err := feeds.Read(docID)
if err != nil {
panic(err)
}
fmt.Println("Document", docID, "is", readBack)
// Update document
err = feeds.Update(docID, map[string]interface{}{
"name": "Go is very popular",
"url": "google.com"})
if err != nil {
panic(err)
}
// Process all documents (note that document order is undetermined)
feeds.ForEachDoc(func(id int, docContent []byte) (willMoveOn bool) {
fmt.Println("Document", id, "is", string(docContent))
return true // move on to the next document OR
return false // do not move on to the next document
})
// Delete document
if err := feeds.Delete(docID); err != nil {
panic(err)
}
// More complicated error handing - identify the error Type.
// In this example, the error code tells that the document no longer exists.
if err := feeds.Delete(docID); dberr.Type(err) == dberr.ErrorNoDoc {
fmt.Println("The document was already deleted")
}
// ****************** Index Management ******************
// Indexes assist in many types of queries
// Create index (path leads to document JSON attribute)
if err := feeds.Index([]string{"author", "name", "first_name"}); err != nil {
panic(err)
}
if err := feeds.Index([]string{"Title"}); err != nil {
panic(err)
}
if err := feeds.Index([]string{"Source"}); err != nil {
panic(err)
}
// What indexes do I have on collection A?
for _, path := range feeds.AllIndexes() {
fmt.Printf("I have an index on path %v\n", path)
}
// Remove index
if err := feeds.Unindex([]string{"author", "name", "first_name"}); err != nil {
panic(err)
}
// ****************** Queries ******************
// Prepare some documents for the query
feeds.Insert(map[string]interface{}{"Title": "New Go release", "Source": "golang.org", "Age": 3})
feeds.Insert(map[string]interface{}{"Title": "Kitkat is here", "Source": "google.com", "Age": 2})
feeds.Insert(map[string]interface{}{"Title": "Good Slackware", "Source": "slackware.com", "Age": 1})
var query interface{}
json.Unmarshal([]byte(`[{"eq": "New Go release", "in": ["Title"]}, {"eq": "slackware.com", "in": ["Source"]}]`), &query)
queryResult := make(map[int]struct{}) // query result (document IDs) goes into map keys
if err := db.EvalQuery(query, feeds, &queryResult); err != nil {
panic(err)
}
// Query result are document IDs
for id := range queryResult {
// To get query result document, simply read it
readBack, err := feeds.Read(id)
if err != nil {
panic(err)
}
fmt.Printf("Query returned document %v\n", readBack)
}
// Gracefully close database
if err := myDB.Close(); err != nil {
panic(err)
}
} | [
"func",
"EmbeddedExample",
"(",
")",
"{",
"// ****************** Collection Management ******************",
"myDBDir",
":=",
"\"",
"\"",
"\n",
"os",
".",
"RemoveAll",
"(",
"myDBDir",
")",
"\n",
"defer",
"os",
".",
"RemoveAll",
"(",
"myDBDir",
")",
"\n\n",
"// (Create if not exist) open a database",
"myDB",
",",
"err",
":=",
"db",
".",
"OpenDB",
"(",
"myDBDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Create two collections: Feeds and Votes",
"if",
"err",
":=",
"myDB",
".",
"Create",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"myDB",
".",
"Create",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// What collections do I now have?",
"for",
"_",
",",
"name",
":=",
"range",
"myDB",
".",
"AllCols",
"(",
")",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"// Rename collection \"Votes\" to \"Points\"",
"if",
"err",
":=",
"myDB",
".",
"Rename",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Drop (delete) collection \"Points\"",
"if",
"err",
":=",
"myDB",
".",
"Drop",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Scrub (repair and compact) \"Feeds\"",
"if",
"err",
":=",
"myDB",
".",
"Scrub",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// ****************** Document Management ******************",
"// Start using a collection (the reference is valid until DB schema changes or Scrub is carried out)",
"feeds",
":=",
"myDB",
".",
"Use",
"(",
"\"",
"\"",
")",
"\n\n",
"// Insert document (afterwards the docID uniquely identifies the document and will never change)",
"docID",
",",
"err",
":=",
"feeds",
".",
"Insert",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Read document",
"readBack",
",",
"err",
":=",
"feeds",
".",
"Read",
"(",
"docID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"docID",
",",
"\"",
"\"",
",",
"readBack",
")",
"\n\n",
"// Update document",
"err",
"=",
"feeds",
".",
"Update",
"(",
"docID",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Process all documents (note that document order is undetermined)",
"feeds",
".",
"ForEachDoc",
"(",
"func",
"(",
"id",
"int",
",",
"docContent",
"[",
"]",
"byte",
")",
"(",
"willMoveOn",
"bool",
")",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"id",
",",
"\"",
"\"",
",",
"string",
"(",
"docContent",
")",
")",
"\n",
"return",
"true",
"// move on to the next document OR",
"\n",
"return",
"false",
"// do not move on to the next document",
"\n",
"}",
")",
"\n\n",
"// Delete document",
"if",
"err",
":=",
"feeds",
".",
"Delete",
"(",
"docID",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// More complicated error handing - identify the error Type.",
"// In this example, the error code tells that the document no longer exists.",
"if",
"err",
":=",
"feeds",
".",
"Delete",
"(",
"docID",
")",
";",
"dberr",
".",
"Type",
"(",
"err",
")",
"==",
"dberr",
".",
"ErrorNoDoc",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// ****************** Index Management ******************",
"// Indexes assist in many types of queries",
"// Create index (path leads to document JSON attribute)",
"if",
"err",
":=",
"feeds",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"feeds",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"feeds",
".",
"Index",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// What indexes do I have on collection A?",
"for",
"_",
",",
"path",
":=",
"range",
"feeds",
".",
"AllIndexes",
"(",
")",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"path",
")",
"\n",
"}",
"\n\n",
"// Remove index",
"if",
"err",
":=",
"feeds",
".",
"Unindex",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// ****************** Queries ******************",
"// Prepare some documents for the query",
"feeds",
".",
"Insert",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"3",
"}",
")",
"\n",
"feeds",
".",
"Insert",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"2",
"}",
")",
"\n",
"feeds",
".",
"Insert",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"1",
"}",
")",
"\n\n",
"var",
"query",
"interface",
"{",
"}",
"\n",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"`[{\"eq\": \"New Go release\", \"in\": [\"Title\"]}, {\"eq\": \"slackware.com\", \"in\": [\"Source\"]}]`",
")",
",",
"&",
"query",
")",
"\n\n",
"queryResult",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"// query result (document IDs) goes into map keys",
"\n\n",
"if",
"err",
":=",
"db",
".",
"EvalQuery",
"(",
"query",
",",
"feeds",
",",
"&",
"queryResult",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Query result are document IDs",
"for",
"id",
":=",
"range",
"queryResult",
"{",
"// To get query result document, simply read it",
"readBack",
",",
"err",
":=",
"feeds",
".",
"Read",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"readBack",
")",
"\n",
"}",
"\n\n",
"// Gracefully close database",
"if",
"err",
":=",
"myDB",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] | /*
In embedded usage, you are encouraged to use all public functions concurrently.
However please do not use public functions in "data" package by yourself - you most likely will not need to use them directly.
To compile and run the example:
go build && ./tiedot -mode=example
It may require as much as 1.5GB of free disk space in order to run the example.
*/ | [
"/",
"*",
"In",
"embedded",
"usage",
"you",
"are",
"encouraged",
"to",
"use",
"all",
"public",
"functions",
"concurrently",
".",
"However",
"please",
"do",
"not",
"use",
"public",
"functions",
"in",
"data",
"package",
"by",
"yourself",
"-",
"you",
"most",
"likely",
"will",
"not",
"need",
"to",
"use",
"them",
"directly",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/examples/example.go#L23-L162 |
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",
"{",
"if",
"err",
"=",
"evalQuery",
"(",
"subExpr",
",",
"src",
",",
"result",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Calculate union of sub-query results. | [
"Calculate",
"union",
"of",
"sub",
"-",
"query",
"results",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/query.go#L16-L23 |
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",
"{",
"(",
"*",
"result",
")",
"[",
"id",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"return",
"true",
"\n",
"}",
",",
"false",
")",
"\n",
"return",
"\n",
"}"
] | // Put all document IDs into result. | [
"Put",
"all",
"document",
"IDs",
"into",
"result",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/query.go#L26-L32 |
HouzuoGuo/tiedot | db/query.go | Lookup | func Lookup(lookupValue interface{}, expr map[string]interface{}, src *Col, result *map[int]struct{}) (err error) {
// Figure out lookup path - JSON array "in"
path, hasPath := expr["in"]
if !hasPath {
return errors.New("Missing lookup path `in`")
}
vecPath := make([]string, 0)
if vecPathInterface, ok := path.([]interface{}); ok {
for _, v := range vecPathInterface {
vecPath = append(vecPath, fmt.Sprint(v))
}
} else {
return fmt.Errorf("Expecting vector lookup path `in`, but %v given", path)
}
// Figure out result number limit
intLimit := int(0)
if limit, hasLimit := expr["limit"]; hasLimit {
if floatLimit, ok := limit.(float64); ok {
intLimit = int(floatLimit)
} else if _, ok := limit.(int); ok {
intLimit = limit.(int)
} else {
return dberr.New(dberr.ErrorExpectingInt, "limit", limit)
}
}
lookupStrValue := fmt.Sprint(lookupValue) // the value to look for
lookupValueHash := StrHash(lookupStrValue)
scanPath := strings.Join(vecPath, INDEX_PATH_SEP)
if _, indexed := src.indexPaths[scanPath]; !indexed {
return dberr.New(dberr.ErrorNeedIndex, scanPath, expr)
}
num := lookupValueHash % src.db.numParts
ht := src.hts[num][scanPath]
ht.Lock.RLock()
vals := ht.Get(lookupValueHash, intLimit)
ht.Lock.RUnlock()
for _, match := range vals {
// Filter result to avoid hash collision
if doc, err := src.read(match, false); err == nil {
for _, v := range GetIn(doc, vecPath) {
if fmt.Sprint(v) == lookupStrValue {
(*result)[match] = struct{}{}
}
}
}
}
return
} | go | func Lookup(lookupValue interface{}, expr map[string]interface{}, src *Col, result *map[int]struct{}) (err error) {
// Figure out lookup path - JSON array "in"
path, hasPath := expr["in"]
if !hasPath {
return errors.New("Missing lookup path `in`")
}
vecPath := make([]string, 0)
if vecPathInterface, ok := path.([]interface{}); ok {
for _, v := range vecPathInterface {
vecPath = append(vecPath, fmt.Sprint(v))
}
} else {
return fmt.Errorf("Expecting vector lookup path `in`, but %v given", path)
}
// Figure out result number limit
intLimit := int(0)
if limit, hasLimit := expr["limit"]; hasLimit {
if floatLimit, ok := limit.(float64); ok {
intLimit = int(floatLimit)
} else if _, ok := limit.(int); ok {
intLimit = limit.(int)
} else {
return dberr.New(dberr.ErrorExpectingInt, "limit", limit)
}
}
lookupStrValue := fmt.Sprint(lookupValue) // the value to look for
lookupValueHash := StrHash(lookupStrValue)
scanPath := strings.Join(vecPath, INDEX_PATH_SEP)
if _, indexed := src.indexPaths[scanPath]; !indexed {
return dberr.New(dberr.ErrorNeedIndex, scanPath, expr)
}
num := lookupValueHash % src.db.numParts
ht := src.hts[num][scanPath]
ht.Lock.RLock()
vals := ht.Get(lookupValueHash, intLimit)
ht.Lock.RUnlock()
for _, match := range vals {
// Filter result to avoid hash collision
if doc, err := src.read(match, false); err == nil {
for _, v := range GetIn(doc, vecPath) {
if fmt.Sprint(v) == lookupStrValue {
(*result)[match] = struct{}{}
}
}
}
}
return
} | [
"func",
"Lookup",
"(",
"lookupValue",
"interface",
"{",
"}",
",",
"expr",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"src",
"*",
"Col",
",",
"result",
"*",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"// Figure out lookup path - JSON array \"in\"",
"path",
",",
"hasPath",
":=",
"expr",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"hasPath",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"vecPath",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"if",
"vecPathInterface",
",",
"ok",
":=",
"path",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"vecPathInterface",
"{",
"vecPath",
"=",
"append",
"(",
"vecPath",
",",
"fmt",
".",
"Sprint",
"(",
"v",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n",
"// Figure out result number limit",
"intLimit",
":=",
"int",
"(",
"0",
")",
"\n",
"if",
"limit",
",",
"hasLimit",
":=",
"expr",
"[",
"\"",
"\"",
"]",
";",
"hasLimit",
"{",
"if",
"floatLimit",
",",
"ok",
":=",
"limit",
".",
"(",
"float64",
")",
";",
"ok",
"{",
"intLimit",
"=",
"int",
"(",
"floatLimit",
")",
"\n",
"}",
"else",
"if",
"_",
",",
"ok",
":=",
"limit",
".",
"(",
"int",
")",
";",
"ok",
"{",
"intLimit",
"=",
"limit",
".",
"(",
"int",
")",
"\n",
"}",
"else",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorExpectingInt",
",",
"\"",
"\"",
",",
"limit",
")",
"\n",
"}",
"\n",
"}",
"\n",
"lookupStrValue",
":=",
"fmt",
".",
"Sprint",
"(",
"lookupValue",
")",
"// the value to look for",
"\n",
"lookupValueHash",
":=",
"StrHash",
"(",
"lookupStrValue",
")",
"\n",
"scanPath",
":=",
"strings",
".",
"Join",
"(",
"vecPath",
",",
"INDEX_PATH_SEP",
")",
"\n",
"if",
"_",
",",
"indexed",
":=",
"src",
".",
"indexPaths",
"[",
"scanPath",
"]",
";",
"!",
"indexed",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorNeedIndex",
",",
"scanPath",
",",
"expr",
")",
"\n",
"}",
"\n",
"num",
":=",
"lookupValueHash",
"%",
"src",
".",
"db",
".",
"numParts",
"\n",
"ht",
":=",
"src",
".",
"hts",
"[",
"num",
"]",
"[",
"scanPath",
"]",
"\n",
"ht",
".",
"Lock",
".",
"RLock",
"(",
")",
"\n",
"vals",
":=",
"ht",
".",
"Get",
"(",
"lookupValueHash",
",",
"intLimit",
")",
"\n",
"ht",
".",
"Lock",
".",
"RUnlock",
"(",
")",
"\n",
"for",
"_",
",",
"match",
":=",
"range",
"vals",
"{",
"// Filter result to avoid hash collision",
"if",
"doc",
",",
"err",
":=",
"src",
".",
"read",
"(",
"match",
",",
"false",
")",
";",
"err",
"==",
"nil",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"GetIn",
"(",
"doc",
",",
"vecPath",
")",
"{",
"if",
"fmt",
".",
"Sprint",
"(",
"v",
")",
"==",
"lookupStrValue",
"{",
"(",
"*",
"result",
")",
"[",
"match",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Value equity check ("attribute == value") using hash lookup. | [
"Value",
"equity",
"check",
"(",
"attribute",
"==",
"value",
")",
"using",
"hash",
"lookup",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/query.go#L35-L82 |
HouzuoGuo/tiedot | db/query.go | PathExistence | func PathExistence(hasPath interface{}, expr map[string]interface{}, src *Col, result *map[int]struct{}) (err error) {
// Figure out the path
vecPath := make([]string, 0)
if vecPathInterface, ok := hasPath.([]interface{}); ok {
for _, v := range vecPathInterface {
vecPath = append(vecPath, fmt.Sprint(v))
}
} else {
return errors.New(fmt.Sprintf("Expecting vector path, but %v given", hasPath))
}
// Figure out result number limit
intLimit := 0
if limit, hasLimit := expr["limit"]; hasLimit {
if floatLimit, ok := limit.(float64); ok {
intLimit = int(floatLimit)
} else if _, ok := limit.(int); ok {
intLimit = limit.(int)
} else {
return dberr.New(dberr.ErrorExpectingInt, "limit", limit)
}
}
jointPath := strings.Join(vecPath, INDEX_PATH_SEP)
if _, indexed := src.indexPaths[jointPath]; !indexed {
return dberr.New(dberr.ErrorNeedIndex, vecPath, expr)
}
counter := 0
partDiv := src.approxDocCount(false) / src.db.numParts / 4000 // collect approx. 4k document IDs in each iteration
if partDiv == 0 {
partDiv++
}
for iteratePart := 0; iteratePart < src.db.numParts; iteratePart++ {
ht := src.hts[iteratePart][jointPath]
ht.Lock.RLock()
for i := 0; i < partDiv; i++ {
_, ids := ht.GetPartition(i, partDiv)
for _, id := range ids {
(*result)[id] = struct{}{}
counter++
if counter == intLimit {
ht.Lock.RUnlock()
return nil
}
}
}
ht.Lock.RUnlock()
}
return nil
} | go | func PathExistence(hasPath interface{}, expr map[string]interface{}, src *Col, result *map[int]struct{}) (err error) {
// Figure out the path
vecPath := make([]string, 0)
if vecPathInterface, ok := hasPath.([]interface{}); ok {
for _, v := range vecPathInterface {
vecPath = append(vecPath, fmt.Sprint(v))
}
} else {
return errors.New(fmt.Sprintf("Expecting vector path, but %v given", hasPath))
}
// Figure out result number limit
intLimit := 0
if limit, hasLimit := expr["limit"]; hasLimit {
if floatLimit, ok := limit.(float64); ok {
intLimit = int(floatLimit)
} else if _, ok := limit.(int); ok {
intLimit = limit.(int)
} else {
return dberr.New(dberr.ErrorExpectingInt, "limit", limit)
}
}
jointPath := strings.Join(vecPath, INDEX_PATH_SEP)
if _, indexed := src.indexPaths[jointPath]; !indexed {
return dberr.New(dberr.ErrorNeedIndex, vecPath, expr)
}
counter := 0
partDiv := src.approxDocCount(false) / src.db.numParts / 4000 // collect approx. 4k document IDs in each iteration
if partDiv == 0 {
partDiv++
}
for iteratePart := 0; iteratePart < src.db.numParts; iteratePart++ {
ht := src.hts[iteratePart][jointPath]
ht.Lock.RLock()
for i := 0; i < partDiv; i++ {
_, ids := ht.GetPartition(i, partDiv)
for _, id := range ids {
(*result)[id] = struct{}{}
counter++
if counter == intLimit {
ht.Lock.RUnlock()
return nil
}
}
}
ht.Lock.RUnlock()
}
return nil
} | [
"func",
"PathExistence",
"(",
"hasPath",
"interface",
"{",
"}",
",",
"expr",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"src",
"*",
"Col",
",",
"result",
"*",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"// Figure out the path",
"vecPath",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"if",
"vecPathInterface",
",",
"ok",
":=",
"hasPath",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"vecPathInterface",
"{",
"vecPath",
"=",
"append",
"(",
"vecPath",
",",
"fmt",
".",
"Sprint",
"(",
"v",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"errors",
".",
"New",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"hasPath",
")",
")",
"\n",
"}",
"\n",
"// Figure out result number limit",
"intLimit",
":=",
"0",
"\n",
"if",
"limit",
",",
"hasLimit",
":=",
"expr",
"[",
"\"",
"\"",
"]",
";",
"hasLimit",
"{",
"if",
"floatLimit",
",",
"ok",
":=",
"limit",
".",
"(",
"float64",
")",
";",
"ok",
"{",
"intLimit",
"=",
"int",
"(",
"floatLimit",
")",
"\n",
"}",
"else",
"if",
"_",
",",
"ok",
":=",
"limit",
".",
"(",
"int",
")",
";",
"ok",
"{",
"intLimit",
"=",
"limit",
".",
"(",
"int",
")",
"\n",
"}",
"else",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorExpectingInt",
",",
"\"",
"\"",
",",
"limit",
")",
"\n",
"}",
"\n",
"}",
"\n",
"jointPath",
":=",
"strings",
".",
"Join",
"(",
"vecPath",
",",
"INDEX_PATH_SEP",
")",
"\n",
"if",
"_",
",",
"indexed",
":=",
"src",
".",
"indexPaths",
"[",
"jointPath",
"]",
";",
"!",
"indexed",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorNeedIndex",
",",
"vecPath",
",",
"expr",
")",
"\n",
"}",
"\n",
"counter",
":=",
"0",
"\n",
"partDiv",
":=",
"src",
".",
"approxDocCount",
"(",
"false",
")",
"/",
"src",
".",
"db",
".",
"numParts",
"/",
"4000",
"// collect approx. 4k document IDs in each iteration",
"\n",
"if",
"partDiv",
"==",
"0",
"{",
"partDiv",
"++",
"\n",
"}",
"\n",
"for",
"iteratePart",
":=",
"0",
";",
"iteratePart",
"<",
"src",
".",
"db",
".",
"numParts",
";",
"iteratePart",
"++",
"{",
"ht",
":=",
"src",
".",
"hts",
"[",
"iteratePart",
"]",
"[",
"jointPath",
"]",
"\n",
"ht",
".",
"Lock",
".",
"RLock",
"(",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"partDiv",
";",
"i",
"++",
"{",
"_",
",",
"ids",
":=",
"ht",
".",
"GetPartition",
"(",
"i",
",",
"partDiv",
")",
"\n",
"for",
"_",
",",
"id",
":=",
"range",
"ids",
"{",
"(",
"*",
"result",
")",
"[",
"id",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"counter",
"++",
"\n",
"if",
"counter",
"==",
"intLimit",
"{",
"ht",
".",
"Lock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"ht",
".",
"Lock",
".",
"RUnlock",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Value existence check (value != nil) using hash lookup. | [
"Value",
"existence",
"check",
"(",
"value",
"!",
"=",
"nil",
")",
"using",
"hash",
"lookup",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/query.go#L85-L132 |
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",
"]",
"struct",
"{",
"}",
")",
"\n",
"if",
"subExprVecs",
",",
"ok",
":=",
"subExprs",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"first",
":=",
"true",
"\n",
"for",
"_",
",",
"subExpr",
":=",
"range",
"subExprVecs",
"{",
"subResult",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"\n",
"intersection",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"\n",
"if",
"err",
"=",
"evalQuery",
"(",
"subExpr",
",",
"src",
",",
"&",
"subResult",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"first",
"{",
"myResult",
"=",
"subResult",
"\n",
"first",
"=",
"false",
"\n",
"}",
"else",
"{",
"for",
"k",
":=",
"range",
"subResult",
"{",
"if",
"_",
",",
"inBoth",
":=",
"myResult",
"[",
"k",
"]",
";",
"inBoth",
"{",
"intersection",
"[",
"k",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"myResult",
"=",
"intersection",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"docID",
":=",
"range",
"myResult",
"{",
"(",
"*",
"result",
")",
"[",
"docID",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorExpectingSubQuery",
",",
"subExprs",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Calculate intersection of sub-query results. | [
"Calculate",
"intersection",
"of",
"sub",
"-",
"query",
"results",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/query.go#L135-L164 |
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",
"]",
"struct",
"{",
"}",
")",
"\n",
"if",
"subExprVecs",
",",
"ok",
":=",
"subExprs",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"for",
"_",
",",
"subExpr",
":=",
"range",
"subExprVecs",
"{",
"subResult",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"\n",
"complement",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"\n",
"if",
"err",
"=",
"evalQuery",
"(",
"subExpr",
",",
"src",
",",
"&",
"subResult",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"for",
"k",
":=",
"range",
"subResult",
"{",
"if",
"_",
",",
"inBoth",
":=",
"myResult",
"[",
"k",
"]",
";",
"!",
"inBoth",
"{",
"complement",
"[",
"k",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"k",
":=",
"range",
"myResult",
"{",
"if",
"_",
",",
"inBoth",
":=",
"subResult",
"[",
"k",
"]",
";",
"!",
"inBoth",
"{",
"complement",
"[",
"k",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"myResult",
"=",
"complement",
"\n",
"}",
"\n",
"for",
"docID",
":=",
"range",
"myResult",
"{",
"(",
"*",
"result",
")",
"[",
"docID",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorExpectingSubQuery",
",",
"subExprs",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Calculate complement of sub-query results. | [
"Calculate",
"complement",
"of",
"sub",
"-",
"query",
"results",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/query.go#L167-L195 |
HouzuoGuo/tiedot | db/query.go | IntRange | func IntRange(intFrom interface{}, expr map[string]interface{}, src *Col, result *map[int]struct{}) (err error) {
path, hasPath := expr["in"]
if !hasPath {
return errors.New("Missing path `in`")
}
// Figure out the path
vecPath := make([]string, 0)
if vecPathInterface, ok := path.([]interface{}); ok {
for _, v := range vecPathInterface {
vecPath = append(vecPath, fmt.Sprint(v))
}
} else {
return errors.New(fmt.Sprintf("Expecting vector path `in`, but %v given", path))
}
// Figure out result number limit
intLimit := int(0)
if limit, hasLimit := expr["limit"]; hasLimit {
if floatLimit, ok := limit.(float64); ok {
intLimit = int(floatLimit)
} else if _, ok := limit.(int); ok {
intLimit = limit.(int)
} else {
return dberr.New(dberr.ErrorExpectingInt, limit)
}
}
// Figure out the range ("from" value & "to" value)
from, to := int(0), int(0)
if floatFrom, ok := intFrom.(float64); ok {
from = int(floatFrom)
} else if _, ok := intFrom.(int); ok {
from = intFrom.(int)
} else {
return dberr.New(dberr.ErrorExpectingInt, "int-from", from)
}
if intTo, ok := expr["int-to"]; ok {
if floatTo, ok := intTo.(float64); ok {
to = int(floatTo)
} else if _, ok := intTo.(int); ok {
to = intTo.(int)
} else {
return dberr.New(dberr.ErrorExpectingInt, "int-to", to)
}
} else if intTo, ok := expr["int to"]; ok {
if floatTo, ok := intTo.(float64); ok {
to = int(floatTo)
} else if _, ok := intTo.(int); ok {
to = intTo.(int)
} else {
return dberr.New(dberr.ErrorExpectingInt, "int to", to)
}
} else {
return dberr.New(dberr.ErrorMissing, "int-to")
}
if to > from && to-from > 1000 || from > to && from-to > 1000 {
tdlog.CritNoRepeat("Query %v involves index lookup on more than 1000 values, which can be very inefficient", expr)
}
counter := int(0) // Number of results already collected
htPath := strings.Join(vecPath, ",")
if _, indexScan := src.indexPaths[htPath]; !indexScan {
return dberr.New(dberr.ErrorNeedIndex, vecPath, expr)
}
if from < to {
// Forward scan - from low value to high value
for lookupValue := from; lookupValue <= to; lookupValue++ {
lookupStrValue := fmt.Sprint(float64(lookupValue))
hashValue := StrHash(lookupStrValue)
vals := src.hashScan(htPath, hashValue, int(intLimit))
for _, docID := range vals {
if intLimit > 0 && counter == intLimit {
break
}
counter++
(*result)[docID] = struct{}{}
}
}
} else {
// Backward scan - from high value to low value
for lookupValue := from; lookupValue >= to; lookupValue-- {
lookupStrValue := fmt.Sprint(float64(lookupValue))
hashValue := StrHash(lookupStrValue)
vals := src.hashScan(htPath, hashValue, int(intLimit))
for _, docID := range vals {
if intLimit > 0 && counter == intLimit {
break
}
counter++
(*result)[docID] = struct{}{}
}
}
}
return
} | go | func IntRange(intFrom interface{}, expr map[string]interface{}, src *Col, result *map[int]struct{}) (err error) {
path, hasPath := expr["in"]
if !hasPath {
return errors.New("Missing path `in`")
}
// Figure out the path
vecPath := make([]string, 0)
if vecPathInterface, ok := path.([]interface{}); ok {
for _, v := range vecPathInterface {
vecPath = append(vecPath, fmt.Sprint(v))
}
} else {
return errors.New(fmt.Sprintf("Expecting vector path `in`, but %v given", path))
}
// Figure out result number limit
intLimit := int(0)
if limit, hasLimit := expr["limit"]; hasLimit {
if floatLimit, ok := limit.(float64); ok {
intLimit = int(floatLimit)
} else if _, ok := limit.(int); ok {
intLimit = limit.(int)
} else {
return dberr.New(dberr.ErrorExpectingInt, limit)
}
}
// Figure out the range ("from" value & "to" value)
from, to := int(0), int(0)
if floatFrom, ok := intFrom.(float64); ok {
from = int(floatFrom)
} else if _, ok := intFrom.(int); ok {
from = intFrom.(int)
} else {
return dberr.New(dberr.ErrorExpectingInt, "int-from", from)
}
if intTo, ok := expr["int-to"]; ok {
if floatTo, ok := intTo.(float64); ok {
to = int(floatTo)
} else if _, ok := intTo.(int); ok {
to = intTo.(int)
} else {
return dberr.New(dberr.ErrorExpectingInt, "int-to", to)
}
} else if intTo, ok := expr["int to"]; ok {
if floatTo, ok := intTo.(float64); ok {
to = int(floatTo)
} else if _, ok := intTo.(int); ok {
to = intTo.(int)
} else {
return dberr.New(dberr.ErrorExpectingInt, "int to", to)
}
} else {
return dberr.New(dberr.ErrorMissing, "int-to")
}
if to > from && to-from > 1000 || from > to && from-to > 1000 {
tdlog.CritNoRepeat("Query %v involves index lookup on more than 1000 values, which can be very inefficient", expr)
}
counter := int(0) // Number of results already collected
htPath := strings.Join(vecPath, ",")
if _, indexScan := src.indexPaths[htPath]; !indexScan {
return dberr.New(dberr.ErrorNeedIndex, vecPath, expr)
}
if from < to {
// Forward scan - from low value to high value
for lookupValue := from; lookupValue <= to; lookupValue++ {
lookupStrValue := fmt.Sprint(float64(lookupValue))
hashValue := StrHash(lookupStrValue)
vals := src.hashScan(htPath, hashValue, int(intLimit))
for _, docID := range vals {
if intLimit > 0 && counter == intLimit {
break
}
counter++
(*result)[docID] = struct{}{}
}
}
} else {
// Backward scan - from high value to low value
for lookupValue := from; lookupValue >= to; lookupValue-- {
lookupStrValue := fmt.Sprint(float64(lookupValue))
hashValue := StrHash(lookupStrValue)
vals := src.hashScan(htPath, hashValue, int(intLimit))
for _, docID := range vals {
if intLimit > 0 && counter == intLimit {
break
}
counter++
(*result)[docID] = struct{}{}
}
}
}
return
} | [
"func",
"IntRange",
"(",
"intFrom",
"interface",
"{",
"}",
",",
"expr",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"src",
"*",
"Col",
",",
"result",
"*",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"path",
",",
"hasPath",
":=",
"expr",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"hasPath",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Figure out the path",
"vecPath",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"if",
"vecPathInterface",
",",
"ok",
":=",
"path",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"vecPathInterface",
"{",
"vecPath",
"=",
"append",
"(",
"vecPath",
",",
"fmt",
".",
"Sprint",
"(",
"v",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"errors",
".",
"New",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
")",
")",
"\n",
"}",
"\n",
"// Figure out result number limit",
"intLimit",
":=",
"int",
"(",
"0",
")",
"\n",
"if",
"limit",
",",
"hasLimit",
":=",
"expr",
"[",
"\"",
"\"",
"]",
";",
"hasLimit",
"{",
"if",
"floatLimit",
",",
"ok",
":=",
"limit",
".",
"(",
"float64",
")",
";",
"ok",
"{",
"intLimit",
"=",
"int",
"(",
"floatLimit",
")",
"\n",
"}",
"else",
"if",
"_",
",",
"ok",
":=",
"limit",
".",
"(",
"int",
")",
";",
"ok",
"{",
"intLimit",
"=",
"limit",
".",
"(",
"int",
")",
"\n",
"}",
"else",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorExpectingInt",
",",
"limit",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Figure out the range (\"from\" value & \"to\" value)",
"from",
",",
"to",
":=",
"int",
"(",
"0",
")",
",",
"int",
"(",
"0",
")",
"\n",
"if",
"floatFrom",
",",
"ok",
":=",
"intFrom",
".",
"(",
"float64",
")",
";",
"ok",
"{",
"from",
"=",
"int",
"(",
"floatFrom",
")",
"\n",
"}",
"else",
"if",
"_",
",",
"ok",
":=",
"intFrom",
".",
"(",
"int",
")",
";",
"ok",
"{",
"from",
"=",
"intFrom",
".",
"(",
"int",
")",
"\n",
"}",
"else",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorExpectingInt",
",",
"\"",
"\"",
",",
"from",
")",
"\n",
"}",
"\n",
"if",
"intTo",
",",
"ok",
":=",
"expr",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"floatTo",
",",
"ok",
":=",
"intTo",
".",
"(",
"float64",
")",
";",
"ok",
"{",
"to",
"=",
"int",
"(",
"floatTo",
")",
"\n",
"}",
"else",
"if",
"_",
",",
"ok",
":=",
"intTo",
".",
"(",
"int",
")",
";",
"ok",
"{",
"to",
"=",
"intTo",
".",
"(",
"int",
")",
"\n",
"}",
"else",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorExpectingInt",
",",
"\"",
"\"",
",",
"to",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"intTo",
",",
"ok",
":=",
"expr",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"floatTo",
",",
"ok",
":=",
"intTo",
".",
"(",
"float64",
")",
";",
"ok",
"{",
"to",
"=",
"int",
"(",
"floatTo",
")",
"\n",
"}",
"else",
"if",
"_",
",",
"ok",
":=",
"intTo",
".",
"(",
"int",
")",
";",
"ok",
"{",
"to",
"=",
"intTo",
".",
"(",
"int",
")",
"\n",
"}",
"else",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorExpectingInt",
",",
"\"",
"\"",
",",
"to",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorMissing",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"to",
">",
"from",
"&&",
"to",
"-",
"from",
">",
"1000",
"||",
"from",
">",
"to",
"&&",
"from",
"-",
"to",
">",
"1000",
"{",
"tdlog",
".",
"CritNoRepeat",
"(",
"\"",
"\"",
",",
"expr",
")",
"\n",
"}",
"\n",
"counter",
":=",
"int",
"(",
"0",
")",
"// Number of results already collected",
"\n",
"htPath",
":=",
"strings",
".",
"Join",
"(",
"vecPath",
",",
"\"",
"\"",
")",
"\n",
"if",
"_",
",",
"indexScan",
":=",
"src",
".",
"indexPaths",
"[",
"htPath",
"]",
";",
"!",
"indexScan",
"{",
"return",
"dberr",
".",
"New",
"(",
"dberr",
".",
"ErrorNeedIndex",
",",
"vecPath",
",",
"expr",
")",
"\n",
"}",
"\n",
"if",
"from",
"<",
"to",
"{",
"// Forward scan - from low value to high value",
"for",
"lookupValue",
":=",
"from",
";",
"lookupValue",
"<=",
"to",
";",
"lookupValue",
"++",
"{",
"lookupStrValue",
":=",
"fmt",
".",
"Sprint",
"(",
"float64",
"(",
"lookupValue",
")",
")",
"\n",
"hashValue",
":=",
"StrHash",
"(",
"lookupStrValue",
")",
"\n",
"vals",
":=",
"src",
".",
"hashScan",
"(",
"htPath",
",",
"hashValue",
",",
"int",
"(",
"intLimit",
")",
")",
"\n",
"for",
"_",
",",
"docID",
":=",
"range",
"vals",
"{",
"if",
"intLimit",
">",
"0",
"&&",
"counter",
"==",
"intLimit",
"{",
"break",
"\n",
"}",
"\n",
"counter",
"++",
"\n",
"(",
"*",
"result",
")",
"[",
"docID",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// Backward scan - from high value to low value",
"for",
"lookupValue",
":=",
"from",
";",
"lookupValue",
">=",
"to",
";",
"lookupValue",
"--",
"{",
"lookupStrValue",
":=",
"fmt",
".",
"Sprint",
"(",
"float64",
"(",
"lookupValue",
")",
")",
"\n",
"hashValue",
":=",
"StrHash",
"(",
"lookupStrValue",
")",
"\n",
"vals",
":=",
"src",
".",
"hashScan",
"(",
"htPath",
",",
"hashValue",
",",
"int",
"(",
"intLimit",
")",
")",
"\n",
"for",
"_",
",",
"docID",
":=",
"range",
"vals",
"{",
"if",
"intLimit",
">",
"0",
"&&",
"counter",
"==",
"intLimit",
"{",
"break",
"\n",
"}",
"\n",
"counter",
"++",
"\n",
"(",
"*",
"result",
")",
"[",
"docID",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Look for indexed integer values within the specified integer range. | [
"Look",
"for",
"indexed",
"integer",
"values",
"within",
"the",
"specified",
"integer",
"range",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/query.go#L206-L297 |
HouzuoGuo/tiedot | db/query.go | EvalQuery | func EvalQuery(q interface{}, src *Col, result *map[int]struct{}) (err error) {
return evalQuery(q, src, result, true)
} | go | func EvalQuery(q interface{}, src *Col, result *map[int]struct{}) (err error) {
return evalQuery(q, src, result, true)
} | [
"func",
"EvalQuery",
"(",
"q",
"interface",
"{",
"}",
",",
"src",
"*",
"Col",
",",
"result",
"*",
"map",
"[",
"int",
"]",
"struct",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"return",
"evalQuery",
"(",
"q",
",",
"src",
",",
"result",
",",
"true",
")",
"\n",
"}"
] | // Main entrance to query processor - evaluate a query and put result into result map (as map keys). | [
"Main",
"entrance",
"to",
"query",
"processor",
"-",
"evaluate",
"a",
"query",
"and",
"put",
"result",
"into",
"result",
"map",
"(",
"as",
"map",
"keys",
")",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/db/query.go#L338-L340 |
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",
";",
"i",
"<",
"upTo",
";",
"i",
"++",
"{",
"if",
"buf",
"[",
"i",
"]",
"!=",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // Return true if the buffer begins with 64 consecutive zero bytes. | [
"Return",
"true",
"if",
"the",
"buffer",
"begins",
"with",
"64",
"consecutive",
"zero",
"bytes",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/file.go#L21-L32 |
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",
".",
"Fh",
",",
"err",
"=",
"os",
".",
"OpenFile",
"(",
"file",
".",
"Path",
",",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_RDWR",
",",
"0600",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"var",
"size",
"int64",
"\n",
"if",
"size",
",",
"err",
"=",
"file",
".",
"Fh",
".",
"Seek",
"(",
"0",
",",
"os",
".",
"SEEK_END",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"// 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",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"file",
".",
"Buf",
"==",
"nil",
"{",
"file",
".",
"Buf",
",",
"err",
"=",
"gommap",
".",
"Map",
"(",
"file",
".",
"Fh",
")",
"\n",
"}",
"\n",
"defer",
"tdlog",
".",
"Infof",
"(",
"\"",
"\"",
",",
"file",
".",
"Path",
",",
"file",
".",
"Used",
",",
"file",
".",
"Size",
")",
"\n",
"// 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",
"\n",
"}",
"else",
"{",
"file",
".",
"Used",
"=",
"mid",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"file",
".",
"Used",
"=",
"high",
"\n",
"return",
"\n",
"case",
"LooksEmpty",
"(",
"file",
".",
"Buf",
"[",
"mid",
":",
"]",
")",
":",
"high",
"=",
"mid",
"\n",
"mid",
"=",
"low",
"+",
"(",
"mid",
"-",
"low",
")",
"/",
"2",
"\n",
"default",
":",
"low",
"=",
"mid",
"\n",
"mid",
"=",
"mid",
"+",
"(",
"high",
"-",
"mid",
")",
"/",
"2",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Open a data file that grows by the specified size. | [
"Open",
"a",
"data",
"file",
"that",
"grows",
"by",
"the",
"specified",
"size",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/file.go#L35-L77 |
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",
".",
"SEEK_SET",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"zeroSize",
":=",
"1048576",
"*",
"8",
"// Fill 8 MB at a time",
"\n",
"zero",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"zeroSize",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"+=",
"zeroSize",
"{",
"var",
"zeroSlice",
"[",
"]",
"byte",
"\n",
"if",
"i",
"+",
"zeroSize",
">",
"size",
"{",
"zeroSlice",
"=",
"zero",
"[",
"0",
":",
"size",
"-",
"i",
"]",
"\n",
"}",
"else",
"{",
"zeroSlice",
"=",
"zero",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
"=",
"file",
".",
"Fh",
".",
"Write",
"(",
"zeroSlice",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"file",
".",
"Fh",
".",
"Sync",
"(",
")",
"\n",
"}"
] | // Fill up portion of a file with 0s. | [
"Fill",
"up",
"portion",
"of",
"a",
"file",
"with",
"0s",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/file.go#L80-L98 |
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",
"!=",
"nil",
"{",
"if",
"err",
"=",
"file",
".",
"Buf",
".",
"Unmap",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"=",
"file",
".",
"overwriteWithZero",
"(",
"file",
".",
"Size",
",",
"file",
".",
"Growth",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"else",
"if",
"file",
".",
"Buf",
",",
"err",
"=",
"gommap",
".",
"Map",
"(",
"file",
".",
"Fh",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"file",
".",
"Size",
"+=",
"file",
".",
"Growth",
"\n",
"tdlog",
".",
"Infof",
"(",
"\"",
"\"",
",",
"file",
".",
"Path",
",",
"file",
".",
"Size",
"-",
"file",
".",
"Growth",
",",
"file",
".",
"Size",
",",
"file",
".",
"Used",
")",
"\n",
"return",
"file",
".",
"EnsureSize",
"(",
"more",
")",
"\n",
"}"
] | // Ensure there is enough room for that many bytes of data. | [
"Ensure",
"there",
"is",
"enough",
"room",
"for",
"that",
"many",
"bytes",
"of",
"data",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/file.go#L101-L117 |
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",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Un-map the file buffer and close the file handle. | [
"Un",
"-",
"map",
"the",
"file",
"buffer",
"and",
"close",
"the",
"file",
"handle",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/file.go#L120-L125 |
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",
"(",
"file",
".",
"Path",
",",
"0",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"else",
"if",
"file",
".",
"Fh",
",",
"err",
"=",
"os",
".",
"OpenFile",
"(",
"file",
".",
"Path",
",",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_RDWR",
",",
"0600",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"else",
"if",
"err",
"=",
"file",
".",
"overwriteWithZero",
"(",
"0",
",",
"file",
".",
"Growth",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"else",
"if",
"file",
".",
"Buf",
",",
"err",
"=",
"gommap",
".",
"Map",
"(",
"file",
".",
"Fh",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"file",
".",
"Used",
",",
"file",
".",
"Size",
"=",
"0",
",",
"file",
".",
"Growth",
"\n",
"tdlog",
".",
"Infof",
"(",
"\"",
"\"",
",",
"file",
".",
"Path",
",",
"file",
".",
"Used",
",",
"file",
".",
"Size",
")",
"\n",
"return",
"\n",
"}"
] | // Clear the entire file and resize it to initial size. | [
"Clear",
"the",
"entire",
"file",
"and",
"resize",
"it",
"to",
"initial",
"size",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/file.go#L128-L143 |
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",
"=",
"OpenDataFile",
"(",
"path",
",",
"conf",
".",
"ColFileGrowth",
")",
"\n",
"col",
".",
"Config",
"=",
"conf",
"\n",
"col",
".",
"Config",
".",
"CalculateConfigConstants",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Open a collection file. | [
"Open",
"a",
"collection",
"file",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/collection.go#L30-L36 |
HouzuoGuo/tiedot | data/collection.go | Read | func (col *Collection) Read(id int) []byte {
if id < 0 || id > col.Used-DocHeader || col.Buf[id] != 1 {
return nil
} else if room, _ := binary.Varint(col.Buf[id+1 : id+11]); room > int64(col.DocMaxRoom) {
return nil
} else if docEnd := id + DocHeader + int(room); docEnd >= col.Size {
return nil
} else {
docCopy := make([]byte, room)
copy(docCopy, col.Buf[id+DocHeader:docEnd])
return docCopy
}
} | go | func (col *Collection) Read(id int) []byte {
if id < 0 || id > col.Used-DocHeader || col.Buf[id] != 1 {
return nil
} else if room, _ := binary.Varint(col.Buf[id+1 : id+11]); room > int64(col.DocMaxRoom) {
return nil
} else if docEnd := id + DocHeader + int(room); docEnd >= col.Size {
return nil
} else {
docCopy := make([]byte, room)
copy(docCopy, col.Buf[id+DocHeader:docEnd])
return docCopy
}
} | [
"func",
"(",
"col",
"*",
"Collection",
")",
"Read",
"(",
"id",
"int",
")",
"[",
"]",
"byte",
"{",
"if",
"id",
"<",
"0",
"||",
"id",
">",
"col",
".",
"Used",
"-",
"DocHeader",
"||",
"col",
".",
"Buf",
"[",
"id",
"]",
"!=",
"1",
"{",
"return",
"nil",
"\n",
"}",
"else",
"if",
"room",
",",
"_",
":=",
"binary",
".",
"Varint",
"(",
"col",
".",
"Buf",
"[",
"id",
"+",
"1",
":",
"id",
"+",
"11",
"]",
")",
";",
"room",
">",
"int64",
"(",
"col",
".",
"DocMaxRoom",
")",
"{",
"return",
"nil",
"\n",
"}",
"else",
"if",
"docEnd",
":=",
"id",
"+",
"DocHeader",
"+",
"int",
"(",
"room",
")",
";",
"docEnd",
">=",
"col",
".",
"Size",
"{",
"return",
"nil",
"\n",
"}",
"else",
"{",
"docCopy",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"room",
")",
"\n",
"copy",
"(",
"docCopy",
",",
"col",
".",
"Buf",
"[",
"id",
"+",
"DocHeader",
":",
"docEnd",
"]",
")",
"\n",
"return",
"docCopy",
"\n",
"}",
"\n",
"}"
] | // Find and retrieve a document by ID (physical document location). Return value is a copy of the document. | [
"Find",
"and",
"retrieve",
"a",
"document",
"by",
"ID",
"(",
"physical",
"document",
"location",
")",
".",
"Return",
"value",
"is",
"a",
"copy",
"of",
"the",
"document",
"."
] | train | https://github.com/HouzuoGuo/tiedot/blob/be8ab1f1598ed275ad3857e5d5f23ddc1f8b8b39/data/collection.go#L39-L51 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.