repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
vektra/mockery | mockery/generator.go | generateCalled | func (g *Generator) generateCalled(list *paramList, formattedParamNames string) string {
namesLen := len(list.Names)
if namesLen == 0 {
return "_m.Called()"
}
if !list.Variadic {
return "_m.Called(" + formattedParamNames + ")"
}
var variadicArgsName string
variadicName := list.Names[namesLen-1]
variadicIface := strings.Contains(list.Types[namesLen-1], "interface{}")
if variadicIface {
// Variadic is already of the interface{} type, so we don't need special handling.
variadicArgsName = variadicName
} else {
// Define _va to avoid "cannot use t (type T) as type []interface {} in append" error
// whenever the variadic type is non-interface{}.
g.printf("\t_va := make([]interface{}, len(%s))\n", variadicName)
g.printf("\tfor _i := range %s {\n\t\t_va[_i] = %s[_i]\n\t}\n", variadicName, variadicName)
variadicArgsName = "_va"
}
// _ca will hold all arguments we'll mirror into Called, one argument per distinct value
// passed to the method.
//
// For example, if the second argument is variadic and consists of three values,
// a total of 4 arguments will be passed to Called. The alternative is to
// pass a total of 2 arguments where the second is a slice with those 3 values from
// the variadic argument. But the alternative is less accessible because it requires
// building a []interface{} before calling Mock methods like On and AssertCalled for
// the variadic argument, and creates incompatibility issues with the diff algorithm
// in github.com/stretchr/testify/mock.
//
// This mirroring will allow argument lists for methods like On and AssertCalled to
// always resemble the expected calls they describe and retain compatibility.
//
// It's okay for us to use the interface{} type, regardless of the actual types, because
// Called receives only interface{} anyway.
g.printf("\tvar _ca []interface{}\n")
if namesLen > 1 {
nonVariadicParamNames := formattedParamNames[0:strings.LastIndex(formattedParamNames, ",")]
g.printf("\t_ca = append(_ca, %s)\n", nonVariadicParamNames)
}
g.printf("\t_ca = append(_ca, %s...)\n", variadicArgsName)
return "_m.Called(_ca...)"
} | go | func (g *Generator) generateCalled(list *paramList, formattedParamNames string) string {
namesLen := len(list.Names)
if namesLen == 0 {
return "_m.Called()"
}
if !list.Variadic {
return "_m.Called(" + formattedParamNames + ")"
}
var variadicArgsName string
variadicName := list.Names[namesLen-1]
variadicIface := strings.Contains(list.Types[namesLen-1], "interface{}")
if variadicIface {
// Variadic is already of the interface{} type, so we don't need special handling.
variadicArgsName = variadicName
} else {
// Define _va to avoid "cannot use t (type T) as type []interface {} in append" error
// whenever the variadic type is non-interface{}.
g.printf("\t_va := make([]interface{}, len(%s))\n", variadicName)
g.printf("\tfor _i := range %s {\n\t\t_va[_i] = %s[_i]\n\t}\n", variadicName, variadicName)
variadicArgsName = "_va"
}
// _ca will hold all arguments we'll mirror into Called, one argument per distinct value
// passed to the method.
//
// For example, if the second argument is variadic and consists of three values,
// a total of 4 arguments will be passed to Called. The alternative is to
// pass a total of 2 arguments where the second is a slice with those 3 values from
// the variadic argument. But the alternative is less accessible because it requires
// building a []interface{} before calling Mock methods like On and AssertCalled for
// the variadic argument, and creates incompatibility issues with the diff algorithm
// in github.com/stretchr/testify/mock.
//
// This mirroring will allow argument lists for methods like On and AssertCalled to
// always resemble the expected calls they describe and retain compatibility.
//
// It's okay for us to use the interface{} type, regardless of the actual types, because
// Called receives only interface{} anyway.
g.printf("\tvar _ca []interface{}\n")
if namesLen > 1 {
nonVariadicParamNames := formattedParamNames[0:strings.LastIndex(formattedParamNames, ",")]
g.printf("\t_ca = append(_ca, %s)\n", nonVariadicParamNames)
}
g.printf("\t_ca = append(_ca, %s...)\n", variadicArgsName)
return "_m.Called(_ca...)"
} | [
"func",
"(",
"g",
"*",
"Generator",
")",
"generateCalled",
"(",
"list",
"*",
"paramList",
",",
"formattedParamNames",
"string",
")",
"string",
"{",
"namesLen",
":=",
"len",
"(",
"list",
".",
"Names",
")",
"\n",
"if",
"namesLen",
"==",
"0",
"{",
"return",... | // generateCalled returns the Mock.Called invocation string and, if necessary, prints the
// steps to prepare its argument list.
//
// It is separate from Generate to avoid cyclomatic complexity through early return statements. | [
"generateCalled",
"returns",
"the",
"Mock",
".",
"Called",
"invocation",
"string",
"and",
"if",
"necessary",
"prints",
"the",
"steps",
"to",
"prepare",
"its",
"argument",
"list",
".",
"It",
"is",
"separate",
"from",
"Generate",
"to",
"avoid",
"cyclomatic",
"co... | e78b021dcbb558a8e7ac1fc5bc757ad7c277bb81 | https://github.com/vektra/mockery/blob/e78b021dcbb558a8e7ac1fc5bc757ad7c277bb81/mockery/generator.go#L583-L633 | train |
evanphx/json-patch | cmd/json-patch/file_flag.go | UnmarshalFlag | func (f *FileFlag) UnmarshalFlag(value string) error {
stat, err := os.Stat(value)
if err != nil {
return err
}
if stat.IsDir() {
return fmt.Errorf("path '%s' is a directory, not a file", value)
}
abs, err := filepath.Abs(value)
if err != nil {
return err
}
*f = FileFlag(abs)
return nil
} | go | func (f *FileFlag) UnmarshalFlag(value string) error {
stat, err := os.Stat(value)
if err != nil {
return err
}
if stat.IsDir() {
return fmt.Errorf("path '%s' is a directory, not a file", value)
}
abs, err := filepath.Abs(value)
if err != nil {
return err
}
*f = FileFlag(abs)
return nil
} | [
"func",
"(",
"f",
"*",
"FileFlag",
")",
"UnmarshalFlag",
"(",
"value",
"string",
")",
"error",
"{",
"stat",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"st... | // UnmarshalFlag implements go-flag's Unmarshaler interface | [
"UnmarshalFlag",
"implements",
"go",
"-",
"flag",
"s",
"Unmarshaler",
"interface"
] | 5858425f75500d40c52783dce87d085a483ce135 | https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/cmd/json-patch/file_flag.go#L16-L34 | train |
evanphx/json-patch | patch.go | set | func (d *partialArray) set(key string, val *lazyNode) error {
idx, err := strconv.Atoi(key)
if err != nil {
return err
}
(*d)[idx] = val
return nil
} | go | func (d *partialArray) set(key string, val *lazyNode) error {
idx, err := strconv.Atoi(key)
if err != nil {
return err
}
(*d)[idx] = val
return nil
} | [
"func",
"(",
"d",
"*",
"partialArray",
")",
"set",
"(",
"key",
"string",
",",
"val",
"*",
"lazyNode",
")",
"error",
"{",
"idx",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",... | // set should only be used to implement the "replace" operation, so "key" must
// be an already existing index in "d". | [
"set",
"should",
"only",
"be",
"used",
"to",
"implement",
"the",
"replace",
"operation",
"so",
"key",
"must",
"be",
"an",
"already",
"existing",
"index",
"in",
"d",
"."
] | 5858425f75500d40c52783dce87d085a483ce135 | https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/patch.go#L371-L378 | train |
evanphx/json-patch | patch.go | Equal | func Equal(a, b []byte) bool {
ra := make(json.RawMessage, len(a))
copy(ra, a)
la := newLazyNode(&ra)
rb := make(json.RawMessage, len(b))
copy(rb, b)
lb := newLazyNode(&rb)
return la.equal(lb)
} | go | func Equal(a, b []byte) bool {
ra := make(json.RawMessage, len(a))
copy(ra, a)
la := newLazyNode(&ra)
rb := make(json.RawMessage, len(b))
copy(rb, b)
lb := newLazyNode(&rb)
return la.equal(lb)
} | [
"func",
"Equal",
"(",
"a",
",",
"b",
"[",
"]",
"byte",
")",
"bool",
"{",
"ra",
":=",
"make",
"(",
"json",
".",
"RawMessage",
",",
"len",
"(",
"a",
")",
")",
"\n",
"copy",
"(",
"ra",
",",
"a",
")",
"\n",
"la",
":=",
"newLazyNode",
"(",
"&",
... | // Equal indicates if 2 JSON documents have the same structural equality. | [
"Equal",
"indicates",
"if",
"2",
"JSON",
"documents",
"have",
"the",
"same",
"structural",
"equality",
"."
] | 5858425f75500d40c52783dce87d085a483ce135 | https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/patch.go#L602-L612 | train |
evanphx/json-patch | patch.go | DecodePatch | func DecodePatch(buf []byte) (Patch, error) {
var p Patch
err := json.Unmarshal(buf, &p)
if err != nil {
return nil, err
}
return p, nil
} | go | func DecodePatch(buf []byte) (Patch, error) {
var p Patch
err := json.Unmarshal(buf, &p)
if err != nil {
return nil, err
}
return p, nil
} | [
"func",
"DecodePatch",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"Patch",
",",
"error",
")",
"{",
"var",
"p",
"Patch",
"\n\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"buf",
",",
"&",
"p",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // DecodePatch decodes the passed JSON document as an RFC 6902 patch. | [
"DecodePatch",
"decodes",
"the",
"passed",
"JSON",
"document",
"as",
"an",
"RFC",
"6902",
"patch",
"."
] | 5858425f75500d40c52783dce87d085a483ce135 | https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/patch.go#L615-L625 | train |
evanphx/json-patch | patch.go | Apply | func (p Patch) Apply(doc []byte) ([]byte, error) {
return p.ApplyIndent(doc, "")
} | go | func (p Patch) Apply(doc []byte) ([]byte, error) {
return p.ApplyIndent(doc, "")
} | [
"func",
"(",
"p",
"Patch",
")",
"Apply",
"(",
"doc",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"p",
".",
"ApplyIndent",
"(",
"doc",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // Apply mutates a JSON document according to the patch, and returns the new
// document. | [
"Apply",
"mutates",
"a",
"JSON",
"document",
"according",
"to",
"the",
"patch",
"and",
"returns",
"the",
"new",
"document",
"."
] | 5858425f75500d40c52783dce87d085a483ce135 | https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/patch.go#L629-L631 | train |
evanphx/json-patch | patch.go | ApplyIndent | func (p Patch) ApplyIndent(doc []byte, indent string) ([]byte, error) {
var pd container
if doc[0] == '[' {
pd = &partialArray{}
} else {
pd = &partialDoc{}
}
err := json.Unmarshal(doc, pd)
if err != nil {
return nil, err
}
err = nil
var accumulatedCopySize int64
for _, op := range p {
switch op.kind() {
case "add":
err = p.add(&pd, op)
case "remove":
err = p.remove(&pd, op)
case "replace":
err = p.replace(&pd, op)
case "move":
err = p.move(&pd, op)
case "test":
err = p.test(&pd, op)
case "copy":
err = p.copy(&pd, op, &accumulatedCopySize)
default:
err = fmt.Errorf("Unexpected kind: %s", op.kind())
}
if err != nil {
return nil, err
}
}
if indent != "" {
return json.MarshalIndent(pd, "", indent)
}
return json.Marshal(pd)
} | go | func (p Patch) ApplyIndent(doc []byte, indent string) ([]byte, error) {
var pd container
if doc[0] == '[' {
pd = &partialArray{}
} else {
pd = &partialDoc{}
}
err := json.Unmarshal(doc, pd)
if err != nil {
return nil, err
}
err = nil
var accumulatedCopySize int64
for _, op := range p {
switch op.kind() {
case "add":
err = p.add(&pd, op)
case "remove":
err = p.remove(&pd, op)
case "replace":
err = p.replace(&pd, op)
case "move":
err = p.move(&pd, op)
case "test":
err = p.test(&pd, op)
case "copy":
err = p.copy(&pd, op, &accumulatedCopySize)
default:
err = fmt.Errorf("Unexpected kind: %s", op.kind())
}
if err != nil {
return nil, err
}
}
if indent != "" {
return json.MarshalIndent(pd, "", indent)
}
return json.Marshal(pd)
} | [
"func",
"(",
"p",
"Patch",
")",
"ApplyIndent",
"(",
"doc",
"[",
"]",
"byte",
",",
"indent",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"pd",
"container",
"\n",
"if",
"doc",
"[",
"0",
"]",
"==",
"'['",
"{",
"pd",
"=",
... | // ApplyIndent mutates a JSON document according to the patch, and returns the new
// document indented. | [
"ApplyIndent",
"mutates",
"a",
"JSON",
"document",
"according",
"to",
"the",
"patch",
"and",
"returns",
"the",
"new",
"document",
"indented",
"."
] | 5858425f75500d40c52783dce87d085a483ce135 | https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/patch.go#L635-L681 | train |
evanphx/json-patch | errors.go | NewAccumulatedCopySizeError | func NewAccumulatedCopySizeError(l, a int64) *AccumulatedCopySizeError {
return &AccumulatedCopySizeError{limit: l, accumulated: a}
} | go | func NewAccumulatedCopySizeError(l, a int64) *AccumulatedCopySizeError {
return &AccumulatedCopySizeError{limit: l, accumulated: a}
} | [
"func",
"NewAccumulatedCopySizeError",
"(",
"l",
",",
"a",
"int64",
")",
"*",
"AccumulatedCopySizeError",
"{",
"return",
"&",
"AccumulatedCopySizeError",
"{",
"limit",
":",
"l",
",",
"accumulated",
":",
"a",
"}",
"\n",
"}"
] | // NewAccumulatedCopySizeError returns an AccumulatedCopySizeError. | [
"NewAccumulatedCopySizeError",
"returns",
"an",
"AccumulatedCopySizeError",
"."
] | 5858425f75500d40c52783dce87d085a483ce135 | https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/errors.go#L14-L16 | train |
evanphx/json-patch | errors.go | NewArraySizeError | func NewArraySizeError(l, s int) *ArraySizeError {
return &ArraySizeError{limit: l, size: s}
} | go | func NewArraySizeError(l, s int) *ArraySizeError {
return &ArraySizeError{limit: l, size: s}
} | [
"func",
"NewArraySizeError",
"(",
"l",
",",
"s",
"int",
")",
"*",
"ArraySizeError",
"{",
"return",
"&",
"ArraySizeError",
"{",
"limit",
":",
"l",
",",
"size",
":",
"s",
"}",
"\n",
"}"
] | // NewArraySizeError returns an ArraySizeError. | [
"NewArraySizeError",
"returns",
"an",
"ArraySizeError",
"."
] | 5858425f75500d40c52783dce87d085a483ce135 | https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/errors.go#L31-L33 | train |
evanphx/json-patch | merge.go | MergeMergePatches | func MergeMergePatches(patch1Data, patch2Data []byte) ([]byte, error) {
return doMergePatch(patch1Data, patch2Data, true)
} | go | func MergeMergePatches(patch1Data, patch2Data []byte) ([]byte, error) {
return doMergePatch(patch1Data, patch2Data, true)
} | [
"func",
"MergeMergePatches",
"(",
"patch1Data",
",",
"patch2Data",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"doMergePatch",
"(",
"patch1Data",
",",
"patch2Data",
",",
"true",
")",
"\n",
"}"
] | // MergeMergePatches merges two merge patches together, such that
// applying this resulting merged merge patch to a document yields the same
// as merging each merge patch to the document in succession. | [
"MergeMergePatches",
"merges",
"two",
"merge",
"patches",
"together",
"such",
"that",
"applying",
"this",
"resulting",
"merged",
"merge",
"patch",
"to",
"a",
"document",
"yields",
"the",
"same",
"as",
"merging",
"each",
"merge",
"patch",
"to",
"the",
"document",... | 5858425f75500d40c52783dce87d085a483ce135 | https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/merge.go#L98-L100 | train |
evanphx/json-patch | merge.go | MergePatch | func MergePatch(docData, patchData []byte) ([]byte, error) {
return doMergePatch(docData, patchData, false)
} | go | func MergePatch(docData, patchData []byte) ([]byte, error) {
return doMergePatch(docData, patchData, false)
} | [
"func",
"MergePatch",
"(",
"docData",
",",
"patchData",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"doMergePatch",
"(",
"docData",
",",
"patchData",
",",
"false",
")",
"\n",
"}"
] | // MergePatch merges the patchData into the docData. | [
"MergePatch",
"merges",
"the",
"patchData",
"into",
"the",
"docData",
"."
] | 5858425f75500d40c52783dce87d085a483ce135 | https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/merge.go#L103-L105 | train |
evanphx/json-patch | merge.go | resemblesJSONArray | func resemblesJSONArray(input []byte) bool {
input = bytes.TrimSpace(input)
hasPrefix := bytes.HasPrefix(input, []byte("["))
hasSuffix := bytes.HasSuffix(input, []byte("]"))
return hasPrefix && hasSuffix
} | go | func resemblesJSONArray(input []byte) bool {
input = bytes.TrimSpace(input)
hasPrefix := bytes.HasPrefix(input, []byte("["))
hasSuffix := bytes.HasSuffix(input, []byte("]"))
return hasPrefix && hasSuffix
} | [
"func",
"resemblesJSONArray",
"(",
"input",
"[",
"]",
"byte",
")",
"bool",
"{",
"input",
"=",
"bytes",
".",
"TrimSpace",
"(",
"input",
")",
"\n\n",
"hasPrefix",
":=",
"bytes",
".",
"HasPrefix",
"(",
"input",
",",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")... | // resemblesJSONArray indicates whether the byte-slice "appears" to be
// a JSON array or not.
// False-positives are possible, as this function does not check the internal
// structure of the array. It only checks that the outer syntax is present and
// correct. | [
"resemblesJSONArray",
"indicates",
"whether",
"the",
"byte",
"-",
"slice",
"appears",
"to",
"be",
"a",
"JSON",
"array",
"or",
"not",
".",
"False",
"-",
"positives",
"are",
"possible",
"as",
"this",
"function",
"does",
"not",
"check",
"the",
"internal",
"stru... | 5858425f75500d40c52783dce87d085a483ce135 | https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/merge.go#L170-L177 | train |
evanphx/json-patch | merge.go | createObjectMergePatch | func createObjectMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
originalDoc := map[string]interface{}{}
modifiedDoc := map[string]interface{}{}
err := json.Unmarshal(originalJSON, &originalDoc)
if err != nil {
return nil, errBadJSONDoc
}
err = json.Unmarshal(modifiedJSON, &modifiedDoc)
if err != nil {
return nil, errBadJSONDoc
}
dest, err := getDiff(originalDoc, modifiedDoc)
if err != nil {
return nil, err
}
return json.Marshal(dest)
} | go | func createObjectMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
originalDoc := map[string]interface{}{}
modifiedDoc := map[string]interface{}{}
err := json.Unmarshal(originalJSON, &originalDoc)
if err != nil {
return nil, errBadJSONDoc
}
err = json.Unmarshal(modifiedJSON, &modifiedDoc)
if err != nil {
return nil, errBadJSONDoc
}
dest, err := getDiff(originalDoc, modifiedDoc)
if err != nil {
return nil, err
}
return json.Marshal(dest)
} | [
"func",
"createObjectMergePatch",
"(",
"originalJSON",
",",
"modifiedJSON",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"originalDoc",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"modifiedDoc",
":=",
... | // createObjectMergePatch will return a merge-patch document capable of
// converting the original document to the modified document. | [
"createObjectMergePatch",
"will",
"return",
"a",
"merge",
"-",
"patch",
"document",
"capable",
"of",
"converting",
"the",
"original",
"document",
"to",
"the",
"modified",
"document",
"."
] | 5858425f75500d40c52783dce87d085a483ce135 | https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/merge.go#L204-L224 | train |
evanphx/json-patch | merge.go | createArrayMergePatch | func createArrayMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
originalDocs := []json.RawMessage{}
modifiedDocs := []json.RawMessage{}
err := json.Unmarshal(originalJSON, &originalDocs)
if err != nil {
return nil, errBadJSONDoc
}
err = json.Unmarshal(modifiedJSON, &modifiedDocs)
if err != nil {
return nil, errBadJSONDoc
}
total := len(originalDocs)
if len(modifiedDocs) != total {
return nil, errBadJSONDoc
}
result := []json.RawMessage{}
for i := 0; i < len(originalDocs); i++ {
original := originalDocs[i]
modified := modifiedDocs[i]
patch, err := createObjectMergePatch(original, modified)
if err != nil {
return nil, err
}
result = append(result, json.RawMessage(patch))
}
return json.Marshal(result)
} | go | func createArrayMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
originalDocs := []json.RawMessage{}
modifiedDocs := []json.RawMessage{}
err := json.Unmarshal(originalJSON, &originalDocs)
if err != nil {
return nil, errBadJSONDoc
}
err = json.Unmarshal(modifiedJSON, &modifiedDocs)
if err != nil {
return nil, errBadJSONDoc
}
total := len(originalDocs)
if len(modifiedDocs) != total {
return nil, errBadJSONDoc
}
result := []json.RawMessage{}
for i := 0; i < len(originalDocs); i++ {
original := originalDocs[i]
modified := modifiedDocs[i]
patch, err := createObjectMergePatch(original, modified)
if err != nil {
return nil, err
}
result = append(result, json.RawMessage(patch))
}
return json.Marshal(result)
} | [
"func",
"createArrayMergePatch",
"(",
"originalJSON",
",",
"modifiedJSON",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"originalDocs",
":=",
"[",
"]",
"json",
".",
"RawMessage",
"{",
"}",
"\n",
"modifiedDocs",
":=",
"[",
"]",
... | // createArrayMergePatch will return an array of merge-patch documents capable
// of converting the original document to the modified document for each
// pair of JSON documents provided in the arrays.
// Arrays of mismatched sizes will result in an error. | [
"createArrayMergePatch",
"will",
"return",
"an",
"array",
"of",
"merge",
"-",
"patch",
"documents",
"capable",
"of",
"converting",
"the",
"original",
"document",
"to",
"the",
"modified",
"document",
"for",
"each",
"pair",
"of",
"JSON",
"documents",
"provided",
"... | 5858425f75500d40c52783dce87d085a483ce135 | https://github.com/evanphx/json-patch/blob/5858425f75500d40c52783dce87d085a483ce135/merge.go#L230-L263 | train |
mssola/user_agent | operating_systems.go | normalizeOS | func normalizeOS(name string) string {
sp := strings.SplitN(name, " ", 3)
if len(sp) != 3 || sp[1] != "NT" {
return name
}
switch sp[2] {
case "5.0":
return "Windows 2000"
case "5.01":
return "Windows 2000, Service Pack 1 (SP1)"
case "5.1":
return "Windows XP"
case "5.2":
return "Windows XP x64 Edition"
case "6.0":
return "Windows Vista"
case "6.1":
return "Windows 7"
case "6.2":
return "Windows 8"
case "6.3":
return "Windows 8.1"
case "10.0":
return "Windows 10"
}
return name
} | go | func normalizeOS(name string) string {
sp := strings.SplitN(name, " ", 3)
if len(sp) != 3 || sp[1] != "NT" {
return name
}
switch sp[2] {
case "5.0":
return "Windows 2000"
case "5.01":
return "Windows 2000, Service Pack 1 (SP1)"
case "5.1":
return "Windows XP"
case "5.2":
return "Windows XP x64 Edition"
case "6.0":
return "Windows Vista"
case "6.1":
return "Windows 7"
case "6.2":
return "Windows 8"
case "6.3":
return "Windows 8.1"
case "10.0":
return "Windows 10"
}
return name
} | [
"func",
"normalizeOS",
"(",
"name",
"string",
")",
"string",
"{",
"sp",
":=",
"strings",
".",
"SplitN",
"(",
"name",
",",
"\"",
"\"",
",",
"3",
")",
"\n",
"if",
"len",
"(",
"sp",
")",
"!=",
"3",
"||",
"sp",
"[",
"1",
"]",
"!=",
"\"",
"\"",
"{... | // Normalize the name of the operating system. By now, this just
// affects to Windows NT.
//
// Returns a string containing the normalized name for the Operating System. | [
"Normalize",
"the",
"name",
"of",
"the",
"operating",
"system",
".",
"By",
"now",
"this",
"just",
"affects",
"to",
"Windows",
"NT",
".",
"Returns",
"a",
"string",
"containing",
"the",
"normalized",
"name",
"for",
"the",
"Operating",
"System",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L26-L53 | train |
mssola/user_agent | operating_systems.go | webkit | func webkit(p *UserAgent, comment []string) {
if p.platform == "webOS" {
p.browser.Name = p.platform
p.os = "Palm"
if len(comment) > 2 {
p.localization = comment[2]
}
p.mobile = true
} else if p.platform == "Symbian" {
p.mobile = true
p.browser.Name = p.platform
p.os = comment[0]
} else if p.platform == "Linux" {
p.mobile = true
if p.browser.Name == "Safari" {
p.browser.Name = "Android"
}
if len(comment) > 1 {
if comment[1] == "U" {
if len(comment) > 2 {
p.os = comment[2]
} else {
p.mobile = false
p.os = comment[0]
}
} else {
p.os = comment[1]
}
}
if len(comment) > 3 {
p.localization = comment[3]
} else if len(comment) == 3 {
_ = p.googleBot()
}
} else if len(comment) > 0 {
if len(comment) > 3 {
p.localization = comment[3]
}
if strings.HasPrefix(comment[0], "Windows NT") {
p.os = normalizeOS(comment[0])
} else if len(comment) < 2 {
p.localization = comment[0]
} else if len(comment) < 3 {
if !p.googleBot() {
p.os = normalizeOS(comment[1])
}
} else {
p.os = normalizeOS(comment[2])
}
if p.platform == "BlackBerry" {
p.browser.Name = p.platform
if p.os == "Touch" {
p.os = p.platform
}
}
}
} | go | func webkit(p *UserAgent, comment []string) {
if p.platform == "webOS" {
p.browser.Name = p.platform
p.os = "Palm"
if len(comment) > 2 {
p.localization = comment[2]
}
p.mobile = true
} else if p.platform == "Symbian" {
p.mobile = true
p.browser.Name = p.platform
p.os = comment[0]
} else if p.platform == "Linux" {
p.mobile = true
if p.browser.Name == "Safari" {
p.browser.Name = "Android"
}
if len(comment) > 1 {
if comment[1] == "U" {
if len(comment) > 2 {
p.os = comment[2]
} else {
p.mobile = false
p.os = comment[0]
}
} else {
p.os = comment[1]
}
}
if len(comment) > 3 {
p.localization = comment[3]
} else if len(comment) == 3 {
_ = p.googleBot()
}
} else if len(comment) > 0 {
if len(comment) > 3 {
p.localization = comment[3]
}
if strings.HasPrefix(comment[0], "Windows NT") {
p.os = normalizeOS(comment[0])
} else if len(comment) < 2 {
p.localization = comment[0]
} else if len(comment) < 3 {
if !p.googleBot() {
p.os = normalizeOS(comment[1])
}
} else {
p.os = normalizeOS(comment[2])
}
if p.platform == "BlackBerry" {
p.browser.Name = p.platform
if p.os == "Touch" {
p.os = p.platform
}
}
}
} | [
"func",
"webkit",
"(",
"p",
"*",
"UserAgent",
",",
"comment",
"[",
"]",
"string",
")",
"{",
"if",
"p",
".",
"platform",
"==",
"\"",
"\"",
"{",
"p",
".",
"browser",
".",
"Name",
"=",
"p",
".",
"platform",
"\n",
"p",
".",
"os",
"=",
"\"",
"\"",
... | // Guess the OS, the localization and if this is a mobile device for a
// Webkit-powered browser.
//
// The first argument p is a reference to the current UserAgent and the second
// argument is a slice of strings containing the comment. | [
"Guess",
"the",
"OS",
"the",
"localization",
"and",
"if",
"this",
"is",
"a",
"mobile",
"device",
"for",
"a",
"Webkit",
"-",
"powered",
"browser",
".",
"The",
"first",
"argument",
"p",
"is",
"a",
"reference",
"to",
"the",
"current",
"UserAgent",
"and",
"t... | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L60-L116 | train |
mssola/user_agent | operating_systems.go | gecko | func gecko(p *UserAgent, comment []string) {
if len(comment) > 1 {
if comment[1] == "U" {
if len(comment) > 2 {
p.os = normalizeOS(comment[2])
} else {
p.os = normalizeOS(comment[1])
}
} else {
if strings.Contains(p.platform, "Android") {
p.mobile = true
p.platform, p.os = normalizeOS(comment[1]), p.platform
} else if comment[0] == "Mobile" || comment[0] == "Tablet" {
p.mobile = true
p.os = "FirefoxOS"
} else {
if p.os == "" {
p.os = normalizeOS(comment[1])
}
}
}
// Only parse 4th comment as localization if it doesn't start with rv:.
// For example Firefox on Ubuntu contains "rv:XX.X" in this field.
if len(comment) > 3 && !strings.HasPrefix(comment[3], "rv:") {
p.localization = comment[3]
}
}
} | go | func gecko(p *UserAgent, comment []string) {
if len(comment) > 1 {
if comment[1] == "U" {
if len(comment) > 2 {
p.os = normalizeOS(comment[2])
} else {
p.os = normalizeOS(comment[1])
}
} else {
if strings.Contains(p.platform, "Android") {
p.mobile = true
p.platform, p.os = normalizeOS(comment[1]), p.platform
} else if comment[0] == "Mobile" || comment[0] == "Tablet" {
p.mobile = true
p.os = "FirefoxOS"
} else {
if p.os == "" {
p.os = normalizeOS(comment[1])
}
}
}
// Only parse 4th comment as localization if it doesn't start with rv:.
// For example Firefox on Ubuntu contains "rv:XX.X" in this field.
if len(comment) > 3 && !strings.HasPrefix(comment[3], "rv:") {
p.localization = comment[3]
}
}
} | [
"func",
"gecko",
"(",
"p",
"*",
"UserAgent",
",",
"comment",
"[",
"]",
"string",
")",
"{",
"if",
"len",
"(",
"comment",
")",
">",
"1",
"{",
"if",
"comment",
"[",
"1",
"]",
"==",
"\"",
"\"",
"{",
"if",
"len",
"(",
"comment",
")",
">",
"2",
"{"... | // Guess the OS, the localization and if this is a mobile device
// for a Gecko-powered browser.
//
// The first argument p is a reference to the current UserAgent and the second
// argument is a slice of strings containing the comment. | [
"Guess",
"the",
"OS",
"the",
"localization",
"and",
"if",
"this",
"is",
"a",
"mobile",
"device",
"for",
"a",
"Gecko",
"-",
"powered",
"browser",
".",
"The",
"first",
"argument",
"p",
"is",
"a",
"reference",
"to",
"the",
"current",
"UserAgent",
"and",
"th... | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L123-L150 | train |
mssola/user_agent | operating_systems.go | trident | func trident(p *UserAgent, comment []string) {
// Internet Explorer only runs on Windows.
p.platform = "Windows"
// The OS can be set before to handle a new case in IE11.
if p.os == "" {
if len(comment) > 2 {
p.os = normalizeOS(comment[2])
} else {
p.os = "Windows NT 4.0"
}
}
// Last but not least, let's detect if it comes from a mobile device.
for _, v := range comment {
if strings.HasPrefix(v, "IEMobile") {
p.mobile = true
return
}
}
} | go | func trident(p *UserAgent, comment []string) {
// Internet Explorer only runs on Windows.
p.platform = "Windows"
// The OS can be set before to handle a new case in IE11.
if p.os == "" {
if len(comment) > 2 {
p.os = normalizeOS(comment[2])
} else {
p.os = "Windows NT 4.0"
}
}
// Last but not least, let's detect if it comes from a mobile device.
for _, v := range comment {
if strings.HasPrefix(v, "IEMobile") {
p.mobile = true
return
}
}
} | [
"func",
"trident",
"(",
"p",
"*",
"UserAgent",
",",
"comment",
"[",
"]",
"string",
")",
"{",
"// Internet Explorer only runs on Windows.",
"p",
".",
"platform",
"=",
"\"",
"\"",
"\n\n",
"// The OS can be set before to handle a new case in IE11.",
"if",
"p",
".",
"os... | // Guess the OS, the localization and if this is a mobile device
// for Internet Explorer.
//
// The first argument p is a reference to the current UserAgent and the second
// argument is a slice of strings containing the comment. | [
"Guess",
"the",
"OS",
"the",
"localization",
"and",
"if",
"this",
"is",
"a",
"mobile",
"device",
"for",
"Internet",
"Explorer",
".",
"The",
"first",
"argument",
"p",
"is",
"a",
"reference",
"to",
"the",
"current",
"UserAgent",
"and",
"the",
"second",
"argu... | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L157-L177 | train |
mssola/user_agent | operating_systems.go | opera | func opera(p *UserAgent, comment []string) {
slen := len(comment)
if strings.HasPrefix(comment[0], "Windows") {
p.platform = "Windows"
p.os = normalizeOS(comment[0])
if slen > 2 {
if slen > 3 && strings.HasPrefix(comment[2], "MRA") {
p.localization = comment[3]
} else {
p.localization = comment[2]
}
}
} else {
if strings.HasPrefix(comment[0], "Android") {
p.mobile = true
}
p.platform = comment[0]
if slen > 1 {
p.os = comment[1]
if slen > 3 {
p.localization = comment[3]
}
} else {
p.os = comment[0]
}
}
} | go | func opera(p *UserAgent, comment []string) {
slen := len(comment)
if strings.HasPrefix(comment[0], "Windows") {
p.platform = "Windows"
p.os = normalizeOS(comment[0])
if slen > 2 {
if slen > 3 && strings.HasPrefix(comment[2], "MRA") {
p.localization = comment[3]
} else {
p.localization = comment[2]
}
}
} else {
if strings.HasPrefix(comment[0], "Android") {
p.mobile = true
}
p.platform = comment[0]
if slen > 1 {
p.os = comment[1]
if slen > 3 {
p.localization = comment[3]
}
} else {
p.os = comment[0]
}
}
} | [
"func",
"opera",
"(",
"p",
"*",
"UserAgent",
",",
"comment",
"[",
"]",
"string",
")",
"{",
"slen",
":=",
"len",
"(",
"comment",
")",
"\n\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"comment",
"[",
"0",
"]",
",",
"\"",
"\"",
")",
"{",
"p",
".",
... | // Guess the OS, the localization and if this is a mobile device
// for Opera.
//
// The first argument p is a reference to the current UserAgent and the second
// argument is a slice of strings containing the comment. | [
"Guess",
"the",
"OS",
"the",
"localization",
"and",
"if",
"this",
"is",
"a",
"mobile",
"device",
"for",
"Opera",
".",
"The",
"first",
"argument",
"p",
"is",
"a",
"reference",
"to",
"the",
"current",
"UserAgent",
"and",
"the",
"second",
"argument",
"is",
... | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L184-L211 | train |
mssola/user_agent | operating_systems.go | dalvik | func dalvik(p *UserAgent, comment []string) {
slen := len(comment)
if strings.HasPrefix(comment[0], "Linux") {
p.platform = comment[0]
if slen > 2 {
p.os = comment[2]
}
p.mobile = true
}
} | go | func dalvik(p *UserAgent, comment []string) {
slen := len(comment)
if strings.HasPrefix(comment[0], "Linux") {
p.platform = comment[0]
if slen > 2 {
p.os = comment[2]
}
p.mobile = true
}
} | [
"func",
"dalvik",
"(",
"p",
"*",
"UserAgent",
",",
"comment",
"[",
"]",
"string",
")",
"{",
"slen",
":=",
"len",
"(",
"comment",
")",
"\n\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"comment",
"[",
"0",
"]",
",",
"\"",
"\"",
")",
"{",
"p",
".",
... | // Guess the OS. Android browsers send Dalvik as the user agent in the
// request header.
//
// The first argument p is a reference to the current UserAgent and the second
// argument is a slice of strings containing the comment. | [
"Guess",
"the",
"OS",
".",
"Android",
"browsers",
"send",
"Dalvik",
"as",
"the",
"user",
"agent",
"in",
"the",
"request",
"header",
".",
"The",
"first",
"argument",
"p",
"is",
"a",
"reference",
"to",
"the",
"current",
"UserAgent",
"and",
"the",
"second",
... | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L218-L228 | train |
mssola/user_agent | operating_systems.go | getPlatform | func getPlatform(comment []string) string {
if len(comment) > 0 {
if comment[0] != "compatible" {
if strings.HasPrefix(comment[0], "Windows") {
return "Windows"
} else if strings.HasPrefix(comment[0], "Symbian") {
return "Symbian"
} else if strings.HasPrefix(comment[0], "webOS") {
return "webOS"
} else if comment[0] == "BB10" {
return "BlackBerry"
}
return comment[0]
}
}
return ""
} | go | func getPlatform(comment []string) string {
if len(comment) > 0 {
if comment[0] != "compatible" {
if strings.HasPrefix(comment[0], "Windows") {
return "Windows"
} else if strings.HasPrefix(comment[0], "Symbian") {
return "Symbian"
} else if strings.HasPrefix(comment[0], "webOS") {
return "webOS"
} else if comment[0] == "BB10" {
return "BlackBerry"
}
return comment[0]
}
}
return ""
} | [
"func",
"getPlatform",
"(",
"comment",
"[",
"]",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"comment",
")",
">",
"0",
"{",
"if",
"comment",
"[",
"0",
"]",
"!=",
"\"",
"\"",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"comment",
"[",
"0",
"]... | // Given the comment of the first section of the UserAgent string,
// get the platform. | [
"Given",
"the",
"comment",
"of",
"the",
"first",
"section",
"of",
"the",
"UserAgent",
"string",
"get",
"the",
"platform",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L232-L248 | train |
mssola/user_agent | operating_systems.go | detectOS | func (p *UserAgent) detectOS(s section) {
if s.name == "Mozilla" {
// Get the platform here. Be aware that IE11 provides a new format
// that is not backwards-compatible with previous versions of IE.
p.platform = getPlatform(s.comment)
if p.platform == "Windows" && len(s.comment) > 0 {
p.os = normalizeOS(s.comment[0])
}
// And finally get the OS depending on the engine.
switch p.browser.Engine {
case "":
p.undecided = true
case "Gecko":
gecko(p, s.comment)
case "AppleWebKit":
webkit(p, s.comment)
case "Trident":
trident(p, s.comment)
}
} else if s.name == "Opera" {
if len(s.comment) > 0 {
opera(p, s.comment)
}
} else if s.name == "Dalvik" {
if len(s.comment) > 0 {
dalvik(p, s.comment)
}
} else {
// Check whether this is a bot or just a weird browser.
p.undecided = true
}
} | go | func (p *UserAgent) detectOS(s section) {
if s.name == "Mozilla" {
// Get the platform here. Be aware that IE11 provides a new format
// that is not backwards-compatible with previous versions of IE.
p.platform = getPlatform(s.comment)
if p.platform == "Windows" && len(s.comment) > 0 {
p.os = normalizeOS(s.comment[0])
}
// And finally get the OS depending on the engine.
switch p.browser.Engine {
case "":
p.undecided = true
case "Gecko":
gecko(p, s.comment)
case "AppleWebKit":
webkit(p, s.comment)
case "Trident":
trident(p, s.comment)
}
} else if s.name == "Opera" {
if len(s.comment) > 0 {
opera(p, s.comment)
}
} else if s.name == "Dalvik" {
if len(s.comment) > 0 {
dalvik(p, s.comment)
}
} else {
// Check whether this is a bot or just a weird browser.
p.undecided = true
}
} | [
"func",
"(",
"p",
"*",
"UserAgent",
")",
"detectOS",
"(",
"s",
"section",
")",
"{",
"if",
"s",
".",
"name",
"==",
"\"",
"\"",
"{",
"// Get the platform here. Be aware that IE11 provides a new format",
"// that is not backwards-compatible with previous versions of IE.",
"p... | // Detect some properties of the OS from the given section. | [
"Detect",
"some",
"properties",
"of",
"the",
"OS",
"from",
"the",
"given",
"section",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L251-L283 | train |
mssola/user_agent | operating_systems.go | osName | func osName(osSplit []string) (name, version string) {
if len(osSplit) == 1 {
name = osSplit[0]
version = ""
} else {
// Assume version is stored in the last part of the array.
nameSplit := osSplit[:len(osSplit)-1]
version = osSplit[len(osSplit)-1]
// Nicer looking Mac OS X
if len(nameSplit) >= 2 && nameSplit[0] == "Intel" && nameSplit[1] == "Mac" {
nameSplit = nameSplit[1:]
}
name = strings.Join(nameSplit, " ")
if strings.Contains(version, "x86") || strings.Contains(version, "i686") {
// x86_64 and i868 are not Linux versions but architectures
version = ""
} else if version == "X" && name == "Mac OS" {
// X is not a version for Mac OS.
name = name + " " + version
version = ""
}
}
return name, version
} | go | func osName(osSplit []string) (name, version string) {
if len(osSplit) == 1 {
name = osSplit[0]
version = ""
} else {
// Assume version is stored in the last part of the array.
nameSplit := osSplit[:len(osSplit)-1]
version = osSplit[len(osSplit)-1]
// Nicer looking Mac OS X
if len(nameSplit) >= 2 && nameSplit[0] == "Intel" && nameSplit[1] == "Mac" {
nameSplit = nameSplit[1:]
}
name = strings.Join(nameSplit, " ")
if strings.Contains(version, "x86") || strings.Contains(version, "i686") {
// x86_64 and i868 are not Linux versions but architectures
version = ""
} else if version == "X" && name == "Mac OS" {
// X is not a version for Mac OS.
name = name + " " + version
version = ""
}
}
return name, version
} | [
"func",
"osName",
"(",
"osSplit",
"[",
"]",
"string",
")",
"(",
"name",
",",
"version",
"string",
")",
"{",
"if",
"len",
"(",
"osSplit",
")",
"==",
"1",
"{",
"name",
"=",
"osSplit",
"[",
"0",
"]",
"\n",
"version",
"=",
"\"",
"\"",
"\n",
"}",
"e... | // Return OS name and version from a slice of strings created from the full name of the OS. | [
"Return",
"OS",
"name",
"and",
"version",
"from",
"a",
"slice",
"of",
"strings",
"created",
"from",
"the",
"full",
"name",
"of",
"the",
"OS",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L301-L326 | train |
mssola/user_agent | operating_systems.go | OSInfo | func (p *UserAgent) OSInfo() OSInfo {
// Special case for iPhone weirdness
os := strings.Replace(p.os, "like Mac OS X", "", 1)
os = strings.Replace(os, "CPU", "", 1)
os = strings.Trim(os, " ")
osSplit := strings.Split(os, " ")
// Special case for x64 edition of Windows
if os == "Windows XP x64 Edition" {
osSplit = osSplit[:len(osSplit)-2]
}
name, version := osName(osSplit)
// Special case for names that contain a forward slash version separator.
if strings.Contains(name, "/") {
s := strings.Split(name, "/")
name = s[0]
version = s[1]
}
// Special case for versions that use underscores
version = strings.Replace(version, "_", ".", -1)
return OSInfo{
FullName: p.os,
Name: name,
Version: version,
}
} | go | func (p *UserAgent) OSInfo() OSInfo {
// Special case for iPhone weirdness
os := strings.Replace(p.os, "like Mac OS X", "", 1)
os = strings.Replace(os, "CPU", "", 1)
os = strings.Trim(os, " ")
osSplit := strings.Split(os, " ")
// Special case for x64 edition of Windows
if os == "Windows XP x64 Edition" {
osSplit = osSplit[:len(osSplit)-2]
}
name, version := osName(osSplit)
// Special case for names that contain a forward slash version separator.
if strings.Contains(name, "/") {
s := strings.Split(name, "/")
name = s[0]
version = s[1]
}
// Special case for versions that use underscores
version = strings.Replace(version, "_", ".", -1)
return OSInfo{
FullName: p.os,
Name: name,
Version: version,
}
} | [
"func",
"(",
"p",
"*",
"UserAgent",
")",
"OSInfo",
"(",
")",
"OSInfo",
"{",
"// Special case for iPhone weirdness",
"os",
":=",
"strings",
".",
"Replace",
"(",
"p",
".",
"os",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"1",
")",
"\n",
"os",
"=",
"strings... | // OSInfo returns combined information for the operating system. | [
"OSInfo",
"returns",
"combined",
"information",
"for",
"the",
"operating",
"system",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/operating_systems.go#L329-L359 | train |
mssola/user_agent | browser.go | Engine | func (p *UserAgent) Engine() (string, string) {
return p.browser.Engine, p.browser.EngineVersion
} | go | func (p *UserAgent) Engine() (string, string) {
return p.browser.Engine, p.browser.EngineVersion
} | [
"func",
"(",
"p",
"*",
"UserAgent",
")",
"Engine",
"(",
")",
"(",
"string",
",",
"string",
")",
"{",
"return",
"p",
".",
"browser",
".",
"Engine",
",",
"p",
".",
"browser",
".",
"EngineVersion",
"\n",
"}"
] | // Engine returns two strings. The first string is the name of the engine and the
// second one is the version of the engine. | [
"Engine",
"returns",
"two",
"strings",
".",
"The",
"first",
"string",
"is",
"the",
"name",
"of",
"the",
"engine",
"and",
"the",
"second",
"one",
"is",
"the",
"version",
"of",
"the",
"engine",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/browser.go#L146-L148 | train |
mssola/user_agent | browser.go | Browser | func (p *UserAgent) Browser() (string, string) {
return p.browser.Name, p.browser.Version
} | go | func (p *UserAgent) Browser() (string, string) {
return p.browser.Name, p.browser.Version
} | [
"func",
"(",
"p",
"*",
"UserAgent",
")",
"Browser",
"(",
")",
"(",
"string",
",",
"string",
")",
"{",
"return",
"p",
".",
"browser",
".",
"Name",
",",
"p",
".",
"browser",
".",
"Version",
"\n",
"}"
] | // Browser returns two strings. The first string is the name of the browser and the
// second one is the version of the browser. | [
"Browser",
"returns",
"two",
"strings",
".",
"The",
"first",
"string",
"is",
"the",
"name",
"of",
"the",
"browser",
"and",
"the",
"second",
"one",
"is",
"the",
"version",
"of",
"the",
"browser",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/browser.go#L152-L154 | train |
mssola/user_agent | user_agent.go | readUntil | func readUntil(ua string, index *int, delimiter byte, cat bool) []byte {
var buffer []byte
i := *index
catalan := 0
for ; i < len(ua); i = i + 1 {
if ua[i] == delimiter {
if catalan == 0 {
*index = i + 1
return buffer
}
catalan--
} else if cat && ua[i] == '(' {
catalan++
}
buffer = append(buffer, ua[i])
}
*index = i + 1
return buffer
} | go | func readUntil(ua string, index *int, delimiter byte, cat bool) []byte {
var buffer []byte
i := *index
catalan := 0
for ; i < len(ua); i = i + 1 {
if ua[i] == delimiter {
if catalan == 0 {
*index = i + 1
return buffer
}
catalan--
} else if cat && ua[i] == '(' {
catalan++
}
buffer = append(buffer, ua[i])
}
*index = i + 1
return buffer
} | [
"func",
"readUntil",
"(",
"ua",
"string",
",",
"index",
"*",
"int",
",",
"delimiter",
"byte",
",",
"cat",
"bool",
")",
"[",
"]",
"byte",
"{",
"var",
"buffer",
"[",
"]",
"byte",
"\n\n",
"i",
":=",
"*",
"index",
"\n",
"catalan",
":=",
"0",
"\n",
"f... | // Read from the given string until the given delimiter or the
// end of the string have been reached.
//
// The first argument is the user agent string being parsed. The second
// argument is a reference pointing to the current index of the user agent
// string. The delimiter argument specifies which character is the delimiter
// and the cat argument determines whether nested '(' should be ignored or not.
//
// Returns an array of bytes containing what has been read. | [
"Read",
"from",
"the",
"given",
"string",
"until",
"the",
"given",
"delimiter",
"or",
"the",
"end",
"of",
"the",
"string",
"have",
"been",
"reached",
".",
"The",
"first",
"argument",
"is",
"the",
"user",
"agent",
"string",
"being",
"parsed",
".",
"The",
... | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/user_agent.go#L44-L63 | train |
mssola/user_agent | user_agent.go | initialize | func (p *UserAgent) initialize() {
p.ua = ""
p.mozilla = ""
p.platform = ""
p.os = ""
p.localization = ""
p.browser.Engine = ""
p.browser.EngineVersion = ""
p.browser.Name = ""
p.browser.Version = ""
p.bot = false
p.mobile = false
p.undecided = false
} | go | func (p *UserAgent) initialize() {
p.ua = ""
p.mozilla = ""
p.platform = ""
p.os = ""
p.localization = ""
p.browser.Engine = ""
p.browser.EngineVersion = ""
p.browser.Name = ""
p.browser.Version = ""
p.bot = false
p.mobile = false
p.undecided = false
} | [
"func",
"(",
"p",
"*",
"UserAgent",
")",
"initialize",
"(",
")",
"{",
"p",
".",
"ua",
"=",
"\"",
"\"",
"\n",
"p",
".",
"mozilla",
"=",
"\"",
"\"",
"\n",
"p",
".",
"platform",
"=",
"\"",
"\"",
"\n",
"p",
".",
"os",
"=",
"\"",
"\"",
"\n",
"p"... | // Initialize the parser. | [
"Initialize",
"the",
"parser",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/user_agent.go#L113-L126 | train |
mssola/user_agent | user_agent.go | New | func New(ua string) *UserAgent {
o := &UserAgent{}
o.Parse(ua)
return o
} | go | func New(ua string) *UserAgent {
o := &UserAgent{}
o.Parse(ua)
return o
} | [
"func",
"New",
"(",
"ua",
"string",
")",
"*",
"UserAgent",
"{",
"o",
":=",
"&",
"UserAgent",
"{",
"}",
"\n",
"o",
".",
"Parse",
"(",
"ua",
")",
"\n",
"return",
"o",
"\n",
"}"
] | // Parse the given User-Agent string and get the resulting UserAgent object.
//
// Returns an UserAgent object that has been initialized after parsing
// the given User-Agent string. | [
"Parse",
"the",
"given",
"User",
"-",
"Agent",
"string",
"and",
"get",
"the",
"resulting",
"UserAgent",
"object",
".",
"Returns",
"an",
"UserAgent",
"object",
"that",
"has",
"been",
"initialized",
"after",
"parsing",
"the",
"given",
"User",
"-",
"Agent",
"st... | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/user_agent.go#L132-L136 | train |
mssola/user_agent | user_agent.go | Parse | func (p *UserAgent) Parse(ua string) {
var sections []section
p.initialize()
p.ua = ua
for index, limit := 0, len(ua); index < limit; {
s := parseSection(ua, &index)
if !p.mobile && s.name == "Mobile" {
p.mobile = true
}
sections = append(sections, s)
}
if len(sections) > 0 {
if sections[0].name == "Mozilla" {
p.mozilla = sections[0].version
}
p.detectBrowser(sections)
p.detectOS(sections[0])
if p.undecided {
p.checkBot(sections)
}
}
} | go | func (p *UserAgent) Parse(ua string) {
var sections []section
p.initialize()
p.ua = ua
for index, limit := 0, len(ua); index < limit; {
s := parseSection(ua, &index)
if !p.mobile && s.name == "Mobile" {
p.mobile = true
}
sections = append(sections, s)
}
if len(sections) > 0 {
if sections[0].name == "Mozilla" {
p.mozilla = sections[0].version
}
p.detectBrowser(sections)
p.detectOS(sections[0])
if p.undecided {
p.checkBot(sections)
}
}
} | [
"func",
"(",
"p",
"*",
"UserAgent",
")",
"Parse",
"(",
"ua",
"string",
")",
"{",
"var",
"sections",
"[",
"]",
"section",
"\n\n",
"p",
".",
"initialize",
"(",
")",
"\n",
"p",
".",
"ua",
"=",
"ua",
"\n",
"for",
"index",
",",
"limit",
":=",
"0",
"... | // Parse the given User-Agent string. After calling this function, the
// receiver will be setted up with all the information that we've extracted. | [
"Parse",
"the",
"given",
"User",
"-",
"Agent",
"string",
".",
"After",
"calling",
"this",
"function",
"the",
"receiver",
"will",
"be",
"setted",
"up",
"with",
"all",
"the",
"information",
"that",
"we",
"ve",
"extracted",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/user_agent.go#L140-L165 | train |
mssola/user_agent | bot.go | getFromSite | func getFromSite(comment []string) string {
if len(comment) == 0 {
return ""
}
// Where we should check the website.
idx := 2
if len(comment) < 3 {
idx = 0
} else if len(comment) == 4 {
idx = 3
}
// Pick the site.
results := botFromSiteRegexp.FindStringSubmatch(comment[idx])
if len(results) == 1 {
// If it's a simple comment, just return the name of the site.
if idx == 0 {
return results[0]
}
// This is a large comment, usually the name will be in the previous
// field of the comment.
return strings.TrimSpace(comment[idx-1])
}
return ""
} | go | func getFromSite(comment []string) string {
if len(comment) == 0 {
return ""
}
// Where we should check the website.
idx := 2
if len(comment) < 3 {
idx = 0
} else if len(comment) == 4 {
idx = 3
}
// Pick the site.
results := botFromSiteRegexp.FindStringSubmatch(comment[idx])
if len(results) == 1 {
// If it's a simple comment, just return the name of the site.
if idx == 0 {
return results[0]
}
// This is a large comment, usually the name will be in the previous
// field of the comment.
return strings.TrimSpace(comment[idx-1])
}
return ""
} | [
"func",
"getFromSite",
"(",
"comment",
"[",
"]",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"comment",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"// Where we should check the website.",
"idx",
":=",
"2",
"\n",
"if",
"len",
"(",
... | // Get the name of the bot from the website that may be in the given comment. If
// there is no website in the comment, then an empty string is returned. | [
"Get",
"the",
"name",
"of",
"the",
"bot",
"from",
"the",
"website",
"that",
"may",
"be",
"in",
"the",
"given",
"comment",
".",
"If",
"there",
"is",
"no",
"website",
"in",
"the",
"comment",
"then",
"an",
"empty",
"string",
"is",
"returned",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/bot.go#L16-L42 | train |
mssola/user_agent | bot.go | googleBot | func (p *UserAgent) googleBot() bool {
// This is a hackish way to detect Google's mobile bot (Googlebot, AdsBot-Google-Mobile, etc.).
// See https://support.google.com/webmasters/answer/1061943
if strings.Index(p.ua, "Google") != -1 {
p.platform = ""
p.undecided = true
}
return p.undecided
} | go | func (p *UserAgent) googleBot() bool {
// This is a hackish way to detect Google's mobile bot (Googlebot, AdsBot-Google-Mobile, etc.).
// See https://support.google.com/webmasters/answer/1061943
if strings.Index(p.ua, "Google") != -1 {
p.platform = ""
p.undecided = true
}
return p.undecided
} | [
"func",
"(",
"p",
"*",
"UserAgent",
")",
"googleBot",
"(",
")",
"bool",
"{",
"// This is a hackish way to detect Google's mobile bot (Googlebot, AdsBot-Google-Mobile, etc.).",
"// See https://support.google.com/webmasters/answer/1061943",
"if",
"strings",
".",
"Index",
"(",
"p",
... | // Returns true if the info that we currently have corresponds to the Google
// mobile bot. This function also modifies some attributes in the receiver
// accordingly. | [
"Returns",
"true",
"if",
"the",
"info",
"that",
"we",
"currently",
"have",
"corresponds",
"to",
"the",
"Google",
"mobile",
"bot",
".",
"This",
"function",
"also",
"modifies",
"some",
"attributes",
"in",
"the",
"receiver",
"accordingly",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/bot.go#L47-L55 | train |
mssola/user_agent | bot.go | setSimple | func (p *UserAgent) setSimple(name, version string, bot bool) {
p.bot = bot
if !bot {
p.mozilla = ""
}
p.browser.Name = name
p.browser.Version = version
p.browser.Engine = ""
p.browser.EngineVersion = ""
p.os = ""
p.localization = ""
} | go | func (p *UserAgent) setSimple(name, version string, bot bool) {
p.bot = bot
if !bot {
p.mozilla = ""
}
p.browser.Name = name
p.browser.Version = version
p.browser.Engine = ""
p.browser.EngineVersion = ""
p.os = ""
p.localization = ""
} | [
"func",
"(",
"p",
"*",
"UserAgent",
")",
"setSimple",
"(",
"name",
",",
"version",
"string",
",",
"bot",
"bool",
")",
"{",
"p",
".",
"bot",
"=",
"bot",
"\n",
"if",
"!",
"bot",
"{",
"p",
".",
"mozilla",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"p",
"... | // Set the attributes of the receiver as given by the parameters. All the other
// parameters are set to empty. | [
"Set",
"the",
"attributes",
"of",
"the",
"receiver",
"as",
"given",
"by",
"the",
"parameters",
".",
"All",
"the",
"other",
"parameters",
"are",
"set",
"to",
"empty",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/bot.go#L59-L70 | train |
mssola/user_agent | bot.go | fixOther | func (p *UserAgent) fixOther(sections []section) {
if len(sections) > 0 {
p.browser.Name = sections[0].name
p.browser.Version = sections[0].version
p.mozilla = ""
}
} | go | func (p *UserAgent) fixOther(sections []section) {
if len(sections) > 0 {
p.browser.Name = sections[0].name
p.browser.Version = sections[0].version
p.mozilla = ""
}
} | [
"func",
"(",
"p",
"*",
"UserAgent",
")",
"fixOther",
"(",
"sections",
"[",
"]",
"section",
")",
"{",
"if",
"len",
"(",
"sections",
")",
">",
"0",
"{",
"p",
".",
"browser",
".",
"Name",
"=",
"sections",
"[",
"0",
"]",
".",
"name",
"\n",
"p",
"."... | // Fix some values for some weird browsers. | [
"Fix",
"some",
"values",
"for",
"some",
"weird",
"browsers",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/bot.go#L73-L79 | train |
mssola/user_agent | bot.go | checkBot | func (p *UserAgent) checkBot(sections []section) {
// If there's only one element, and it's doesn't have the Mozilla string,
// check whether this is a bot or not.
if len(sections) == 1 && sections[0].name != "Mozilla" {
p.mozilla = ""
// Check whether the name has some suspicious "bot" or "crawler" in his name.
if botRegex.Match([]byte(sections[0].name)) {
p.setSimple(sections[0].name, "", true)
return
}
// Tough luck, let's try to see if it has a website in his comment.
if name := getFromSite(sections[0].comment); name != "" {
// First of all, this is a bot. Moreover, since it doesn't have the
// Mozilla string, we can assume that the name and the version are
// the ones from the first section.
p.setSimple(sections[0].name, sections[0].version, true)
return
}
// At this point we are sure that this is not a bot, but some weirdo.
p.setSimple(sections[0].name, sections[0].version, false)
} else {
// Let's iterate over the available comments and check for a website.
for _, v := range sections {
if name := getFromSite(v.comment); name != "" {
// Ok, we've got a bot name.
results := strings.SplitN(name, "/", 2)
version := ""
if len(results) == 2 {
version = results[1]
}
p.setSimple(results[0], version, true)
return
}
}
// We will assume that this is some other weird browser.
p.fixOther(sections)
}
} | go | func (p *UserAgent) checkBot(sections []section) {
// If there's only one element, and it's doesn't have the Mozilla string,
// check whether this is a bot or not.
if len(sections) == 1 && sections[0].name != "Mozilla" {
p.mozilla = ""
// Check whether the name has some suspicious "bot" or "crawler" in his name.
if botRegex.Match([]byte(sections[0].name)) {
p.setSimple(sections[0].name, "", true)
return
}
// Tough luck, let's try to see if it has a website in his comment.
if name := getFromSite(sections[0].comment); name != "" {
// First of all, this is a bot. Moreover, since it doesn't have the
// Mozilla string, we can assume that the name and the version are
// the ones from the first section.
p.setSimple(sections[0].name, sections[0].version, true)
return
}
// At this point we are sure that this is not a bot, but some weirdo.
p.setSimple(sections[0].name, sections[0].version, false)
} else {
// Let's iterate over the available comments and check for a website.
for _, v := range sections {
if name := getFromSite(v.comment); name != "" {
// Ok, we've got a bot name.
results := strings.SplitN(name, "/", 2)
version := ""
if len(results) == 2 {
version = results[1]
}
p.setSimple(results[0], version, true)
return
}
}
// We will assume that this is some other weird browser.
p.fixOther(sections)
}
} | [
"func",
"(",
"p",
"*",
"UserAgent",
")",
"checkBot",
"(",
"sections",
"[",
"]",
"section",
")",
"{",
"// If there's only one element, and it's doesn't have the Mozilla string,",
"// check whether this is a bot or not.",
"if",
"len",
"(",
"sections",
")",
"==",
"1",
"&&"... | // Check if we're dealing with a bot or with some weird browser. If that is the
// case, the receiver will be modified accordingly. | [
"Check",
"if",
"we",
"re",
"dealing",
"with",
"a",
"bot",
"or",
"with",
"some",
"weird",
"browser",
".",
"If",
"that",
"is",
"the",
"case",
"the",
"receiver",
"will",
"be",
"modified",
"accordingly",
"."
] | 74451004a1beb37221bccd8a3931c6acf4a2e80e | https://github.com/mssola/user_agent/blob/74451004a1beb37221bccd8a3931c6acf4a2e80e/bot.go#L85-L126 | train |
minio/highwayhash | highwayhash.go | New | func New(key []byte) (hash.Hash, error) {
if len(key) != Size {
return nil, errKeySize
}
h := &digest{size: Size}
copy(h.key[:], key)
h.Reset()
return h, nil
} | go | func New(key []byte) (hash.Hash, error) {
if len(key) != Size {
return nil, errKeySize
}
h := &digest{size: Size}
copy(h.key[:], key)
h.Reset()
return h, nil
} | [
"func",
"New",
"(",
"key",
"[",
"]",
"byte",
")",
"(",
"hash",
".",
"Hash",
",",
"error",
")",
"{",
"if",
"len",
"(",
"key",
")",
"!=",
"Size",
"{",
"return",
"nil",
",",
"errKeySize",
"\n",
"}",
"\n",
"h",
":=",
"&",
"digest",
"{",
"size",
"... | // New returns a hash.Hash computing the HighwayHash-256 checksum.
// It returns a non-nil error if the key is not 32 bytes long. | [
"New",
"returns",
"a",
"hash",
".",
"Hash",
"computing",
"the",
"HighwayHash",
"-",
"256",
"checksum",
".",
"It",
"returns",
"a",
"non",
"-",
"nil",
"error",
"if",
"the",
"key",
"is",
"not",
"32",
"bytes",
"long",
"."
] | 02ca4b43caa3297fbb615700d8800acc7933be98 | https://github.com/minio/highwayhash/blob/02ca4b43caa3297fbb615700d8800acc7933be98/highwayhash.go#L32-L40 | train |
minio/highwayhash | highwayhash.go | New64 | func New64(key []byte) (hash.Hash64, error) {
if len(key) != Size {
return nil, errKeySize
}
h := new(digest64)
h.size = Size64
copy(h.key[:], key)
h.Reset()
return h, nil
} | go | func New64(key []byte) (hash.Hash64, error) {
if len(key) != Size {
return nil, errKeySize
}
h := new(digest64)
h.size = Size64
copy(h.key[:], key)
h.Reset()
return h, nil
} | [
"func",
"New64",
"(",
"key",
"[",
"]",
"byte",
")",
"(",
"hash",
".",
"Hash64",
",",
"error",
")",
"{",
"if",
"len",
"(",
"key",
")",
"!=",
"Size",
"{",
"return",
"nil",
",",
"errKeySize",
"\n",
"}",
"\n",
"h",
":=",
"new",
"(",
"digest64",
")"... | // New64 returns a hash.Hash computing the HighwayHash-64 checksum.
// It returns a non-nil error if the key is not 32 bytes long. | [
"New64",
"returns",
"a",
"hash",
".",
"Hash",
"computing",
"the",
"HighwayHash",
"-",
"64",
"checksum",
".",
"It",
"returns",
"a",
"non",
"-",
"nil",
"error",
"if",
"the",
"key",
"is",
"not",
"32",
"bytes",
"long",
"."
] | 02ca4b43caa3297fbb615700d8800acc7933be98 | https://github.com/minio/highwayhash/blob/02ca4b43caa3297fbb615700d8800acc7933be98/highwayhash.go#L56-L65 | train |
minio/highwayhash | highwayhash.go | Sum | func Sum(data, key []byte) [Size]byte {
if len(key) != Size {
panic(errKeySize)
}
var state [16]uint64
initialize(&state, key)
if n := len(data) & (^(Size - 1)); n > 0 {
update(&state, data[:n])
data = data[n:]
}
if len(data) > 0 {
var block [Size]byte
offset := copy(block[:], data)
hashBuffer(&state, &block, offset)
}
var hash [Size]byte
finalize(hash[:], &state)
return hash
} | go | func Sum(data, key []byte) [Size]byte {
if len(key) != Size {
panic(errKeySize)
}
var state [16]uint64
initialize(&state, key)
if n := len(data) & (^(Size - 1)); n > 0 {
update(&state, data[:n])
data = data[n:]
}
if len(data) > 0 {
var block [Size]byte
offset := copy(block[:], data)
hashBuffer(&state, &block, offset)
}
var hash [Size]byte
finalize(hash[:], &state)
return hash
} | [
"func",
"Sum",
"(",
"data",
",",
"key",
"[",
"]",
"byte",
")",
"[",
"Size",
"]",
"byte",
"{",
"if",
"len",
"(",
"key",
")",
"!=",
"Size",
"{",
"panic",
"(",
"errKeySize",
")",
"\n",
"}",
"\n",
"var",
"state",
"[",
"16",
"]",
"uint64",
"\n",
"... | // Sum computes the HighwayHash-256 checksum of data.
// It panics if the key is not 32 bytes long. | [
"Sum",
"computes",
"the",
"HighwayHash",
"-",
"256",
"checksum",
"of",
"data",
".",
"It",
"panics",
"if",
"the",
"key",
"is",
"not",
"32",
"bytes",
"long",
"."
] | 02ca4b43caa3297fbb615700d8800acc7933be98 | https://github.com/minio/highwayhash/blob/02ca4b43caa3297fbb615700d8800acc7933be98/highwayhash.go#L69-L87 | train |
minio/highwayhash | highwayhash.go | Sum64 | func Sum64(data, key []byte) uint64 {
if len(key) != Size {
panic(errKeySize)
}
var state [16]uint64
initialize(&state, key)
if n := len(data) & (^(Size - 1)); n > 0 {
update(&state, data[:n])
data = data[n:]
}
if len(data) > 0 {
var block [Size]byte
offset := copy(block[:], data)
hashBuffer(&state, &block, offset)
}
var hash [Size64]byte
finalize(hash[:], &state)
return binary.LittleEndian.Uint64(hash[:])
} | go | func Sum64(data, key []byte) uint64 {
if len(key) != Size {
panic(errKeySize)
}
var state [16]uint64
initialize(&state, key)
if n := len(data) & (^(Size - 1)); n > 0 {
update(&state, data[:n])
data = data[n:]
}
if len(data) > 0 {
var block [Size]byte
offset := copy(block[:], data)
hashBuffer(&state, &block, offset)
}
var hash [Size64]byte
finalize(hash[:], &state)
return binary.LittleEndian.Uint64(hash[:])
} | [
"func",
"Sum64",
"(",
"data",
",",
"key",
"[",
"]",
"byte",
")",
"uint64",
"{",
"if",
"len",
"(",
"key",
")",
"!=",
"Size",
"{",
"panic",
"(",
"errKeySize",
")",
"\n",
"}",
"\n",
"var",
"state",
"[",
"16",
"]",
"uint64",
"\n",
"initialize",
"(",
... | // Sum64 computes the HighwayHash-64 checksum of data.
// It panics if the key is not 32 bytes long. | [
"Sum64",
"computes",
"the",
"HighwayHash",
"-",
"64",
"checksum",
"of",
"data",
".",
"It",
"panics",
"if",
"the",
"key",
"is",
"not",
"32",
"bytes",
"long",
"."
] | 02ca4b43caa3297fbb615700d8800acc7933be98 | https://github.com/minio/highwayhash/blob/02ca4b43caa3297fbb615700d8800acc7933be98/highwayhash.go#L113-L131 | train |
chasex/redis-go-cluster | batch.go | NewBatch | func (cluster *Cluster) NewBatch() *Batch {
return &Batch{
cluster: cluster,
batches: make([]nodeBatch, 0),
index: make([]int, 0),
}
} | go | func (cluster *Cluster) NewBatch() *Batch {
return &Batch{
cluster: cluster,
batches: make([]nodeBatch, 0),
index: make([]int, 0),
}
} | [
"func",
"(",
"cluster",
"*",
"Cluster",
")",
"NewBatch",
"(",
")",
"*",
"Batch",
"{",
"return",
"&",
"Batch",
"{",
"cluster",
":",
"cluster",
",",
"batches",
":",
"make",
"(",
"[",
"]",
"nodeBatch",
",",
"0",
")",
",",
"index",
":",
"make",
"(",
... | // NewBatch create a new batch to pack mutiple commands. | [
"NewBatch",
"create",
"a",
"new",
"batch",
"to",
"pack",
"mutiple",
"commands",
"."
] | 222d81891f1d3fa7cf8b5655020352c3e5b4ec0f | https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/batch.go#L44-L50 | train |
chasex/redis-go-cluster | batch.go | RunBatch | func (cluster *Cluster) RunBatch(bat *Batch) ([]interface{}, error) {
for i := range bat.batches {
go doBatch(&bat.batches[i])
}
for i := range bat.batches {
<-bat.batches[i].done
}
var replies []interface{}
for _, i := range bat.index {
if bat.batches[i].err != nil {
return nil, bat.batches[i].err
}
replies = append(replies, bat.batches[i].cmds[0].reply)
bat.batches[i].cmds = bat.batches[i].cmds[1:]
}
return replies, nil
} | go | func (cluster *Cluster) RunBatch(bat *Batch) ([]interface{}, error) {
for i := range bat.batches {
go doBatch(&bat.batches[i])
}
for i := range bat.batches {
<-bat.batches[i].done
}
var replies []interface{}
for _, i := range bat.index {
if bat.batches[i].err != nil {
return nil, bat.batches[i].err
}
replies = append(replies, bat.batches[i].cmds[0].reply)
bat.batches[i].cmds = bat.batches[i].cmds[1:]
}
return replies, nil
} | [
"func",
"(",
"cluster",
"*",
"Cluster",
")",
"RunBatch",
"(",
"bat",
"*",
"Batch",
")",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"for",
"i",
":=",
"range",
"bat",
".",
"batches",
"{",
"go",
"doBatch",
"(",
"&",
"bat",
".",
... | // RunBatch execute commands in batch simutaneously. If multiple commands are
// directed to the same node, they will be merged and sent at once using pipeling. | [
"RunBatch",
"execute",
"commands",
"in",
"batch",
"simutaneously",
".",
"If",
"multiple",
"commands",
"are",
"directed",
"to",
"the",
"same",
"node",
"they",
"will",
"be",
"merged",
"and",
"sent",
"at",
"once",
"using",
"pipeling",
"."
] | 222d81891f1d3fa7cf8b5655020352c3e5b4ec0f | https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/batch.go#L92-L112 | train |
chasex/redis-go-cluster | node.go | readLine | func (conn *redisConn) readLine() ([]byte, error) {
var line []byte
for {
p, err := conn.br.ReadBytes('\n')
if err != nil {
return nil, err
}
n := len(p) - 2
if n < 0 {
return nil, errors.New("invalid response")
}
// bulk string may contain '\n', such as CLUSTER NODES
if p[n] != '\r' {
if line != nil {
line = append(line, p[:]...)
} else {
line = p
}
continue
}
if line != nil {
return append(line, p[:n]...), nil
} else {
return p[:n], nil
}
}
} | go | func (conn *redisConn) readLine() ([]byte, error) {
var line []byte
for {
p, err := conn.br.ReadBytes('\n')
if err != nil {
return nil, err
}
n := len(p) - 2
if n < 0 {
return nil, errors.New("invalid response")
}
// bulk string may contain '\n', such as CLUSTER NODES
if p[n] != '\r' {
if line != nil {
line = append(line, p[:]...)
} else {
line = p
}
continue
}
if line != nil {
return append(line, p[:n]...), nil
} else {
return p[:n], nil
}
}
} | [
"func",
"(",
"conn",
"*",
"redisConn",
")",
"readLine",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"line",
"[",
"]",
"byte",
"\n",
"for",
"{",
"p",
",",
"err",
":=",
"conn",
".",
"br",
".",
"ReadBytes",
"(",
"'\\n'",
")",
... | // readLine read a single line terminated with CRLF. | [
"readLine",
"read",
"a",
"single",
"line",
"terminated",
"with",
"CRLF",
"."
] | 222d81891f1d3fa7cf8b5655020352c3e5b4ec0f | https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/node.go#L297-L326 | train |
chasex/redis-go-cluster | node.go | parseLen | func parseLen(p []byte) (int, error) {
if len(p) == 0 {
return -1, errors.New("invalid response")
}
// null element.
if p[0] == '-' && len(p) == 2 && p[1] == '1' {
return -1, nil
}
var n int
for _, b := range p {
n *= 10
if b < '0' || b > '9' {
return -1, errors.New("invalid response")
}
n += int(b - '0')
}
return n, nil
} | go | func parseLen(p []byte) (int, error) {
if len(p) == 0 {
return -1, errors.New("invalid response")
}
// null element.
if p[0] == '-' && len(p) == 2 && p[1] == '1' {
return -1, nil
}
var n int
for _, b := range p {
n *= 10
if b < '0' || b > '9' {
return -1, errors.New("invalid response")
}
n += int(b - '0')
}
return n, nil
} | [
"func",
"parseLen",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"len",
"(",
"p",
")",
"==",
"0",
"{",
"return",
"-",
"1",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// null element.",
"... | // parseLen parses bulk string and array length. | [
"parseLen",
"parses",
"bulk",
"string",
"and",
"array",
"length",
"."
] | 222d81891f1d3fa7cf8b5655020352c3e5b4ec0f | https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/node.go#L329-L349 | train |
chasex/redis-go-cluster | node.go | parseInt | func parseInt(p []byte) (int64, error) {
if len(p) == 0 {
return 0, errors.New("invalid response")
}
var negate bool
if p[0] == '-' {
negate = true
p = p[1:]
if len(p) == 0 {
return 0, errors.New("invalid response")
}
}
var n int64
for _, b := range p {
n *= 10
if b < '0' || b > '9' {
return 0, errors.New("invalid response")
}
n += int64(b - '0')
}
if negate {
n = -n
}
return n, nil
} | go | func parseInt(p []byte) (int64, error) {
if len(p) == 0 {
return 0, errors.New("invalid response")
}
var negate bool
if p[0] == '-' {
negate = true
p = p[1:]
if len(p) == 0 {
return 0, errors.New("invalid response")
}
}
var n int64
for _, b := range p {
n *= 10
if b < '0' || b > '9' {
return 0, errors.New("invalid response")
}
n += int64(b - '0')
}
if negate {
n = -n
}
return n, nil
} | [
"func",
"parseInt",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int64",
",",
"error",
")",
"{",
"if",
"len",
"(",
"p",
")",
"==",
"0",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"negate",
"bool",... | // parseInt parses an integer reply. | [
"parseInt",
"parses",
"an",
"integer",
"reply",
"."
] | 222d81891f1d3fa7cf8b5655020352c3e5b4ec0f | https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/node.go#L352-L380 | train |
chasex/redis-go-cluster | cluster.go | NewCluster | func NewCluster(options *Options) (*Cluster, error) {
cluster := &Cluster{
nodes: make(map[string]*redisNode),
connTimeout: options.ConnTimeout,
readTimeout: options.ReadTimeout,
writeTimeout: options.WriteTimeout,
keepAlive: options.KeepAlive,
aliveTime: options.AliveTime,
updateList: make(chan updateMesg),
}
for i := range options.StartNodes {
node := &redisNode{
address: options.StartNodes[i],
connTimeout: options.ConnTimeout,
readTimeout: options.ReadTimeout,
writeTimeout: options.WriteTimeout,
keepAlive: options.KeepAlive,
aliveTime: options.AliveTime,
}
err := cluster.update(node)
if err != nil {
continue
} else {
go cluster.handleUpdate()
return cluster, nil
}
}
return nil, fmt.Errorf("NewCluster: no valid node in %v", options.StartNodes)
} | go | func NewCluster(options *Options) (*Cluster, error) {
cluster := &Cluster{
nodes: make(map[string]*redisNode),
connTimeout: options.ConnTimeout,
readTimeout: options.ReadTimeout,
writeTimeout: options.WriteTimeout,
keepAlive: options.KeepAlive,
aliveTime: options.AliveTime,
updateList: make(chan updateMesg),
}
for i := range options.StartNodes {
node := &redisNode{
address: options.StartNodes[i],
connTimeout: options.ConnTimeout,
readTimeout: options.ReadTimeout,
writeTimeout: options.WriteTimeout,
keepAlive: options.KeepAlive,
aliveTime: options.AliveTime,
}
err := cluster.update(node)
if err != nil {
continue
} else {
go cluster.handleUpdate()
return cluster, nil
}
}
return nil, fmt.Errorf("NewCluster: no valid node in %v", options.StartNodes)
} | [
"func",
"NewCluster",
"(",
"options",
"*",
"Options",
")",
"(",
"*",
"Cluster",
",",
"error",
")",
"{",
"cluster",
":=",
"&",
"Cluster",
"{",
"nodes",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"redisNode",
")",
",",
"connTimeout",
":",
"optio... | // NewCluster create a new redis cluster client with specified options. | [
"NewCluster",
"create",
"a",
"new",
"redis",
"cluster",
"client",
"with",
"specified",
"options",
"."
] | 222d81891f1d3fa7cf8b5655020352c3e5b4ec0f | https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/cluster.go#L67-L98 | train |
chasex/redis-go-cluster | cluster.go | Close | func (cluster *Cluster) Close() {
cluster.rwLock.Lock()
defer cluster.rwLock.Unlock()
for addr, node := range cluster.nodes {
node.shutdown()
delete(cluster.nodes, addr)
}
cluster.closed = true
} | go | func (cluster *Cluster) Close() {
cluster.rwLock.Lock()
defer cluster.rwLock.Unlock()
for addr, node := range cluster.nodes {
node.shutdown()
delete(cluster.nodes, addr)
}
cluster.closed = true
} | [
"func",
"(",
"cluster",
"*",
"Cluster",
")",
"Close",
"(",
")",
"{",
"cluster",
".",
"rwLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cluster",
".",
"rwLock",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"addr",
",",
"node",
":=",
"range",
"cluster",
".... | // Close cluster connection, any subsequent method call will fail. | [
"Close",
"cluster",
"connection",
"any",
"subsequent",
"method",
"call",
"will",
"fail",
"."
] | 222d81891f1d3fa7cf8b5655020352c3e5b4ec0f | https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/cluster.go#L153-L163 | train |
hairyhenderson/gomplate | gomplate.go | RunTemplates | func RunTemplates(o *Config) error {
Metrics = newMetrics()
defer runCleanupHooks()
// make sure config is sane
o.defaults()
ds := append(o.DataSources, o.Contexts...)
d, err := data.NewData(ds, o.DataSourceHeaders)
if err != nil {
return err
}
addCleanupHook(d.Cleanup)
nested, err := parseTemplateArgs(o.Templates)
if err != nil {
return err
}
c, err := createContext(o.Contexts, d)
if err != nil {
return err
}
g := newGomplate(d, o.LDelim, o.RDelim, nested, c)
return g.runTemplates(o)
} | go | func RunTemplates(o *Config) error {
Metrics = newMetrics()
defer runCleanupHooks()
// make sure config is sane
o.defaults()
ds := append(o.DataSources, o.Contexts...)
d, err := data.NewData(ds, o.DataSourceHeaders)
if err != nil {
return err
}
addCleanupHook(d.Cleanup)
nested, err := parseTemplateArgs(o.Templates)
if err != nil {
return err
}
c, err := createContext(o.Contexts, d)
if err != nil {
return err
}
g := newGomplate(d, o.LDelim, o.RDelim, nested, c)
return g.runTemplates(o)
} | [
"func",
"RunTemplates",
"(",
"o",
"*",
"Config",
")",
"error",
"{",
"Metrics",
"=",
"newMetrics",
"(",
")",
"\n",
"defer",
"runCleanupHooks",
"(",
")",
"\n",
"// make sure config is sane",
"o",
".",
"defaults",
"(",
")",
"\n",
"ds",
":=",
"append",
"(",
... | // RunTemplates - run all gomplate templates specified by the given configuration | [
"RunTemplates",
"-",
"run",
"all",
"gomplate",
"templates",
"specified",
"by",
"the",
"given",
"configuration"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/gomplate.go#L107-L129 | train |
hairyhenderson/gomplate | funcs/uuid.go | IsValid | func (f *UUIDFuncs) IsValid(in interface{}) (bool, error) {
_, err := f.Parse(in)
return err == nil, nil
} | go | func (f *UUIDFuncs) IsValid(in interface{}) (bool, error) {
_, err := f.Parse(in)
return err == nil, nil
} | [
"func",
"(",
"f",
"*",
"UUIDFuncs",
")",
"IsValid",
"(",
"in",
"interface",
"{",
"}",
")",
"(",
"bool",
",",
"error",
")",
"{",
"_",
",",
"err",
":=",
"f",
".",
"Parse",
"(",
"in",
")",
"\n",
"return",
"err",
"==",
"nil",
",",
"nil",
"\n",
"}... | // IsValid - checks if the given UUID is in the correct format. It does not
// validate whether the version or variant are correct. | [
"IsValid",
"-",
"checks",
"if",
"the",
"given",
"UUID",
"is",
"in",
"the",
"correct",
"format",
".",
"It",
"does",
"not",
"validate",
"whether",
"the",
"version",
"or",
"variant",
"are",
"correct",
"."
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs/uuid.go#L58-L61 | train |
hairyhenderson/gomplate | env/env.go | getenvVFS | func getenvVFS(fs afero.Fs, key string, def ...string) string {
val := getenvFile(fs, key)
if val == "" && len(def) > 0 {
return def[0]
}
return val
} | go | func getenvVFS(fs afero.Fs, key string, def ...string) string {
val := getenvFile(fs, key)
if val == "" && len(def) > 0 {
return def[0]
}
return val
} | [
"func",
"getenvVFS",
"(",
"fs",
"afero",
".",
"Fs",
",",
"key",
"string",
",",
"def",
"...",
"string",
")",
"string",
"{",
"val",
":=",
"getenvFile",
"(",
"fs",
",",
"key",
")",
"\n",
"if",
"val",
"==",
"\"",
"\"",
"&&",
"len",
"(",
"def",
")",
... | // getenvVFS - a convenience function intended for internal use only! | [
"getenvVFS",
"-",
"a",
"convenience",
"function",
"intended",
"for",
"internal",
"use",
"only!"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/env/env.go#L32-L39 | train |
hairyhenderson/gomplate | funcs/crypto.go | WPAPSK | func (f *CryptoFuncs) WPAPSK(ssid, password interface{}) (string, error) {
return f.PBKDF2(password, ssid, 4096, 32)
} | go | func (f *CryptoFuncs) WPAPSK(ssid, password interface{}) (string, error) {
return f.PBKDF2(password, ssid, 4096, 32)
} | [
"func",
"(",
"f",
"*",
"CryptoFuncs",
")",
"WPAPSK",
"(",
"ssid",
",",
"password",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"f",
".",
"PBKDF2",
"(",
"password",
",",
"ssid",
",",
"4096",
",",
"32",
")",
"\n",
"... | // WPAPSK - Convert an ASCII passphrase to WPA PSK for a given SSID | [
"WPAPSK",
"-",
"Convert",
"an",
"ASCII",
"passphrase",
"to",
"WPA",
"PSK",
"for",
"a",
"given",
"SSID"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs/crypto.go#L61-L63 | train |
hairyhenderson/gomplate | crypto/pbkdf2.go | StrToHash | func StrToHash(hash string) (crypto.Hash, error) {
switch hash {
case "SHA1", "SHA-1":
return crypto.SHA1, nil
case "SHA224", "SHA-224":
return crypto.SHA224, nil
case "SHA256", "SHA-256":
return crypto.SHA256, nil
case "SHA384", "SHA-384":
return crypto.SHA384, nil
case "SHA512", "SHA-512":
return crypto.SHA512, nil
case "SHA512_224", "SHA512/224", "SHA-512_224", "SHA-512/224":
return crypto.SHA512_224, nil
case "SHA512_256", "SHA512/256", "SHA-512_256", "SHA-512/256":
return crypto.SHA512_256, nil
}
return 0, errors.Errorf("no such hash %s", hash)
} | go | func StrToHash(hash string) (crypto.Hash, error) {
switch hash {
case "SHA1", "SHA-1":
return crypto.SHA1, nil
case "SHA224", "SHA-224":
return crypto.SHA224, nil
case "SHA256", "SHA-256":
return crypto.SHA256, nil
case "SHA384", "SHA-384":
return crypto.SHA384, nil
case "SHA512", "SHA-512":
return crypto.SHA512, nil
case "SHA512_224", "SHA512/224", "SHA-512_224", "SHA-512/224":
return crypto.SHA512_224, nil
case "SHA512_256", "SHA512/256", "SHA-512_256", "SHA-512/256":
return crypto.SHA512_256, nil
}
return 0, errors.Errorf("no such hash %s", hash)
} | [
"func",
"StrToHash",
"(",
"hash",
"string",
")",
"(",
"crypto",
".",
"Hash",
",",
"error",
")",
"{",
"switch",
"hash",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"return",
"crypto",
".",
"SHA1",
",",
"nil",
"\n",
"case",
"\"",
"\"",
",",
"\""... | // StrToHash - find a hash given a certain string | [
"StrToHash",
"-",
"find",
"a",
"hash",
"given",
"a",
"certain",
"string"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/crypto/pbkdf2.go#L29-L47 | train |
hairyhenderson/gomplate | conv/conv.go | Join | func Join(in interface{}, sep string) (out string, err error) {
s, ok := in.([]string)
if ok {
return strings.Join(s, sep), nil
}
var a []interface{}
a, ok = in.([]interface{})
if !ok {
a, err = interfaceSlice(in)
if err != nil {
return "", errors.Wrap(err, "Input to Join must be an array")
}
ok = true
}
if ok {
b := make([]string, len(a))
for i := range a {
b[i] = ToString(a[i])
}
return strings.Join(b, sep), nil
}
return "", errors.New("Input to Join must be an array")
} | go | func Join(in interface{}, sep string) (out string, err error) {
s, ok := in.([]string)
if ok {
return strings.Join(s, sep), nil
}
var a []interface{}
a, ok = in.([]interface{})
if !ok {
a, err = interfaceSlice(in)
if err != nil {
return "", errors.Wrap(err, "Input to Join must be an array")
}
ok = true
}
if ok {
b := make([]string, len(a))
for i := range a {
b[i] = ToString(a[i])
}
return strings.Join(b, sep), nil
}
return "", errors.New("Input to Join must be an array")
} | [
"func",
"Join",
"(",
"in",
"interface",
"{",
"}",
",",
"sep",
"string",
")",
"(",
"out",
"string",
",",
"err",
"error",
")",
"{",
"s",
",",
"ok",
":=",
"in",
".",
"(",
"[",
"]",
"string",
")",
"\n",
"if",
"ok",
"{",
"return",
"strings",
".",
... | // Join concatenates the elements of a to create a single string.
// The separator string sep is placed between elements in the resulting string.
//
// This is functionally identical to strings.Join, except that each element is
// coerced to a string first | [
"Join",
"concatenates",
"the",
"elements",
"of",
"a",
"to",
"create",
"a",
"single",
"string",
".",
"The",
"separator",
"string",
"sep",
"is",
"placed",
"between",
"elements",
"in",
"the",
"resulting",
"string",
".",
"This",
"is",
"functionally",
"identical",
... | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L75-L99 | train |
hairyhenderson/gomplate | conv/conv.go | Has | func Has(in interface{}, key interface{}) bool {
av := reflect.ValueOf(in)
switch av.Kind() {
case reflect.Map:
kv := reflect.ValueOf(key)
return av.MapIndex(kv).IsValid()
case reflect.Slice, reflect.Array:
l := av.Len()
for i := 0; i < l; i++ {
v := av.Index(i).Interface()
if reflect.DeepEqual(v, key) {
return true
}
}
}
return false
} | go | func Has(in interface{}, key interface{}) bool {
av := reflect.ValueOf(in)
switch av.Kind() {
case reflect.Map:
kv := reflect.ValueOf(key)
return av.MapIndex(kv).IsValid()
case reflect.Slice, reflect.Array:
l := av.Len()
for i := 0; i < l; i++ {
v := av.Index(i).Interface()
if reflect.DeepEqual(v, key) {
return true
}
}
}
return false
} | [
"func",
"Has",
"(",
"in",
"interface",
"{",
"}",
",",
"key",
"interface",
"{",
"}",
")",
"bool",
"{",
"av",
":=",
"reflect",
".",
"ValueOf",
"(",
"in",
")",
"\n\n",
"switch",
"av",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Map",
":",
... | // Has determines whether or not a given object has a property with the given key | [
"Has",
"determines",
"whether",
"or",
"not",
"a",
"given",
"object",
"has",
"a",
"property",
"with",
"the",
"given",
"key"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L117-L135 | train |
hairyhenderson/gomplate | conv/conv.go | MustParseInt | func MustParseInt(s string, base, bitSize int) int64 {
// nolint: gosec
i, _ := strconv.ParseInt(s, base, bitSize)
return i
} | go | func MustParseInt(s string, base, bitSize int) int64 {
// nolint: gosec
i, _ := strconv.ParseInt(s, base, bitSize)
return i
} | [
"func",
"MustParseInt",
"(",
"s",
"string",
",",
"base",
",",
"bitSize",
"int",
")",
"int64",
"{",
"// nolint: gosec",
"i",
",",
"_",
":=",
"strconv",
".",
"ParseInt",
"(",
"s",
",",
"base",
",",
"bitSize",
")",
"\n",
"return",
"i",
"\n",
"}"
] | // MustParseInt - wrapper for strconv.ParseInt that returns 0 in the case of error | [
"MustParseInt",
"-",
"wrapper",
"for",
"strconv",
".",
"ParseInt",
"that",
"returns",
"0",
"in",
"the",
"case",
"of",
"error"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L166-L170 | train |
hairyhenderson/gomplate | conv/conv.go | MustParseFloat | func MustParseFloat(s string, bitSize int) float64 {
// nolint: gosec
i, _ := strconv.ParseFloat(s, bitSize)
return i
} | go | func MustParseFloat(s string, bitSize int) float64 {
// nolint: gosec
i, _ := strconv.ParseFloat(s, bitSize)
return i
} | [
"func",
"MustParseFloat",
"(",
"s",
"string",
",",
"bitSize",
"int",
")",
"float64",
"{",
"// nolint: gosec",
"i",
",",
"_",
":=",
"strconv",
".",
"ParseFloat",
"(",
"s",
",",
"bitSize",
")",
"\n",
"return",
"i",
"\n",
"}"
] | // MustParseFloat - wrapper for strconv.ParseFloat that returns 0 in the case of error | [
"MustParseFloat",
"-",
"wrapper",
"for",
"strconv",
".",
"ParseFloat",
"that",
"returns",
"0",
"in",
"the",
"case",
"of",
"error"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L173-L177 | train |
hairyhenderson/gomplate | conv/conv.go | MustParseUint | func MustParseUint(s string, base, bitSize int) uint64 {
// nolint: gosec
i, _ := strconv.ParseUint(s, base, bitSize)
return i
} | go | func MustParseUint(s string, base, bitSize int) uint64 {
// nolint: gosec
i, _ := strconv.ParseUint(s, base, bitSize)
return i
} | [
"func",
"MustParseUint",
"(",
"s",
"string",
",",
"base",
",",
"bitSize",
"int",
")",
"uint64",
"{",
"// nolint: gosec",
"i",
",",
"_",
":=",
"strconv",
".",
"ParseUint",
"(",
"s",
",",
"base",
",",
"bitSize",
")",
"\n",
"return",
"i",
"\n",
"}"
] | // MustParseUint - wrapper for strconv.ParseUint that returns 0 in the case of error | [
"MustParseUint",
"-",
"wrapper",
"for",
"strconv",
".",
"ParseUint",
"that",
"returns",
"0",
"in",
"the",
"case",
"of",
"error"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L180-L184 | train |
hairyhenderson/gomplate | conv/conv.go | MustAtoi | func MustAtoi(s string) int {
// nolint: gosec
i, _ := strconv.Atoi(s)
return i
} | go | func MustAtoi(s string) int {
// nolint: gosec
i, _ := strconv.Atoi(s)
return i
} | [
"func",
"MustAtoi",
"(",
"s",
"string",
")",
"int",
"{",
"// nolint: gosec",
"i",
",",
"_",
":=",
"strconv",
".",
"Atoi",
"(",
"s",
")",
"\n",
"return",
"i",
"\n",
"}"
] | // MustAtoi - wrapper for strconv.Atoi that returns 0 in the case of error | [
"MustAtoi",
"-",
"wrapper",
"for",
"strconv",
".",
"Atoi",
"that",
"returns",
"0",
"in",
"the",
"case",
"of",
"error"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L187-L191 | train |
hairyhenderson/gomplate | conv/conv.go | ToInt64 | func ToInt64(v interface{}) int64 {
if str, ok := v.(string); ok {
return strToInt64(str)
}
val := reflect.Indirect(reflect.ValueOf(v))
switch val.Kind() {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
return val.Int()
case reflect.Uint8, reflect.Uint16, reflect.Uint32:
return int64(val.Uint())
case reflect.Uint, reflect.Uint64:
tv := val.Uint()
// this can overflow and give -1, but IMO this is better than
// returning maxint64
return int64(tv)
case reflect.Float32, reflect.Float64:
return int64(val.Float())
case reflect.Bool:
if val.Bool() {
return 1
}
return 0
default:
return 0
}
} | go | func ToInt64(v interface{}) int64 {
if str, ok := v.(string); ok {
return strToInt64(str)
}
val := reflect.Indirect(reflect.ValueOf(v))
switch val.Kind() {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
return val.Int()
case reflect.Uint8, reflect.Uint16, reflect.Uint32:
return int64(val.Uint())
case reflect.Uint, reflect.Uint64:
tv := val.Uint()
// this can overflow and give -1, but IMO this is better than
// returning maxint64
return int64(tv)
case reflect.Float32, reflect.Float64:
return int64(val.Float())
case reflect.Bool:
if val.Bool() {
return 1
}
return 0
default:
return 0
}
} | [
"func",
"ToInt64",
"(",
"v",
"interface",
"{",
"}",
")",
"int64",
"{",
"if",
"str",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
";",
"ok",
"{",
"return",
"strToInt64",
"(",
"str",
")",
"\n",
"}",
"\n\n",
"val",
":=",
"reflect",
".",
"Indirect"... | // ToInt64 - convert input to an int64, if convertible. Otherwise, returns 0. | [
"ToInt64",
"-",
"convert",
"input",
"to",
"an",
"int64",
"if",
"convertible",
".",
"Otherwise",
"returns",
"0",
"."
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L194-L220 | train |
hairyhenderson/gomplate | conv/conv.go | ToFloat64 | func ToFloat64(v interface{}) float64 {
if str, ok := v.(string); ok {
return strToFloat64(str)
}
val := reflect.Indirect(reflect.ValueOf(v))
switch val.Kind() {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
return float64(val.Int())
case reflect.Uint8, reflect.Uint16, reflect.Uint32:
return float64(val.Uint())
case reflect.Uint, reflect.Uint64:
return float64(val.Uint())
case reflect.Float32, reflect.Float64:
return val.Float()
case reflect.Bool:
if val.Bool() {
return 1
}
return 0
default:
return 0
}
} | go | func ToFloat64(v interface{}) float64 {
if str, ok := v.(string); ok {
return strToFloat64(str)
}
val := reflect.Indirect(reflect.ValueOf(v))
switch val.Kind() {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
return float64(val.Int())
case reflect.Uint8, reflect.Uint16, reflect.Uint32:
return float64(val.Uint())
case reflect.Uint, reflect.Uint64:
return float64(val.Uint())
case reflect.Float32, reflect.Float64:
return val.Float()
case reflect.Bool:
if val.Bool() {
return 1
}
return 0
default:
return 0
}
} | [
"func",
"ToFloat64",
"(",
"v",
"interface",
"{",
"}",
")",
"float64",
"{",
"if",
"str",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
";",
"ok",
"{",
"return",
"strToFloat64",
"(",
"str",
")",
"\n",
"}",
"\n\n",
"val",
":=",
"reflect",
".",
"Ind... | // ToFloat64 - convert input to a float64, if convertible. Otherwise, returns 0. | [
"ToFloat64",
"-",
"convert",
"input",
"to",
"a",
"float64",
"if",
"convertible",
".",
"Otherwise",
"returns",
"0",
"."
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/conv/conv.go#L246-L269 | train |
hairyhenderson/gomplate | libkv/boltdb.go | NewBoltDB | func NewBoltDB(u *url.URL) (*LibKV, error) {
boltdb.Register()
config, err := setupBoltDB(u.Fragment)
if err != nil {
return nil, err
}
kv, err := libkv.NewStore(store.BOLTDB, []string{u.Path}, config)
if err != nil {
return nil, errors.Wrapf(err, "BoltDB store creation failed")
}
return &LibKV{kv}, nil
} | go | func NewBoltDB(u *url.URL) (*LibKV, error) {
boltdb.Register()
config, err := setupBoltDB(u.Fragment)
if err != nil {
return nil, err
}
kv, err := libkv.NewStore(store.BOLTDB, []string{u.Path}, config)
if err != nil {
return nil, errors.Wrapf(err, "BoltDB store creation failed")
}
return &LibKV{kv}, nil
} | [
"func",
"NewBoltDB",
"(",
"u",
"*",
"url",
".",
"URL",
")",
"(",
"*",
"LibKV",
",",
"error",
")",
"{",
"boltdb",
".",
"Register",
"(",
")",
"\n\n",
"config",
",",
"err",
":=",
"setupBoltDB",
"(",
"u",
".",
"Fragment",
")",
"\n",
"if",
"err",
"!="... | // NewBoltDB - initialize a new BoltDB datasource handler | [
"NewBoltDB",
"-",
"initialize",
"a",
"new",
"BoltDB",
"datasource",
"handler"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/libkv/boltdb.go#L16-L28 | train |
hairyhenderson/gomplate | funcs/aws.go | AWSNS | func AWSNS() *Funcs {
afInit.Do(func() {
af = &Funcs{
awsopts: aws.GetClientOptions(),
}
})
return af
} | go | func AWSNS() *Funcs {
afInit.Do(func() {
af = &Funcs{
awsopts: aws.GetClientOptions(),
}
})
return af
} | [
"func",
"AWSNS",
"(",
")",
"*",
"Funcs",
"{",
"afInit",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"af",
"=",
"&",
"Funcs",
"{",
"awsopts",
":",
"aws",
".",
"GetClientOptions",
"(",
")",
",",
"}",
"\n",
"}",
")",
"\n",
"return",
"af",
"\n",
"}"
] | // AWSNS - the aws namespace | [
"AWSNS",
"-",
"the",
"aws",
"namespace"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs/aws.go#L16-L23 | train |
hairyhenderson/gomplate | funcs/aws.go | ARN | func (a *Funcs) ARN() (string, error) {
a.stsInit.Do(a.initSTS)
return a.sts.Arn()
} | go | func (a *Funcs) ARN() (string, error) {
a.stsInit.Do(a.initSTS)
return a.sts.Arn()
} | [
"func",
"(",
"a",
"*",
"Funcs",
")",
"ARN",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"a",
".",
"stsInit",
".",
"Do",
"(",
"a",
".",
"initSTS",
")",
"\n",
"return",
"a",
".",
"sts",
".",
"Arn",
"(",
")",
"\n",
"}"
] | // ARN - Gets the AWS ARN associated with the calling entity | [
"ARN",
"-",
"Gets",
"the",
"AWS",
"ARN",
"associated",
"with",
"the",
"calling",
"entity"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs/aws.go#L103-L106 | train |
hairyhenderson/gomplate | base64/base64.go | Encode | func Encode(in []byte) (string, error) {
return b64.StdEncoding.EncodeToString(in), nil
} | go | func Encode(in []byte) (string, error) {
return b64.StdEncoding.EncodeToString(in), nil
} | [
"func",
"Encode",
"(",
"in",
"[",
"]",
"byte",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"b64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"in",
")",
",",
"nil",
"\n",
"}"
] | // Encode - Encode data in base64 format | [
"Encode",
"-",
"Encode",
"data",
"in",
"base64",
"format"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/base64/base64.go#L8-L10 | train |
hairyhenderson/gomplate | base64/base64.go | Decode | func Decode(in string) ([]byte, error) {
o, err := b64.StdEncoding.DecodeString(in)
if err != nil {
// maybe it's in the URL variant?
o, err = b64.URLEncoding.DecodeString(in)
if err != nil {
// ok, just give up...
return nil, err
}
}
return o, nil
} | go | func Decode(in string) ([]byte, error) {
o, err := b64.StdEncoding.DecodeString(in)
if err != nil {
// maybe it's in the URL variant?
o, err = b64.URLEncoding.DecodeString(in)
if err != nil {
// ok, just give up...
return nil, err
}
}
return o, nil
} | [
"func",
"Decode",
"(",
"in",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"o",
",",
"err",
":=",
"b64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"in",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// maybe it's in the URL variant?",
... | // Decode - Decode a base64-encoded string | [
"Decode",
"-",
"Decode",
"a",
"base64",
"-",
"encoded",
"string"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/base64/base64.go#L13-L24 | train |
hairyhenderson/gomplate | vault/auth.go | AppIDLogin | func (v *Vault) AppIDLogin() (string, error) {
appID := env.Getenv("VAULT_APP_ID")
userID := env.Getenv("VAULT_USER_ID")
if appID == "" || userID == "" {
return "", nil
}
mount := env.Getenv("VAULT_AUTH_APP_ID_MOUNT", "app-id")
vars := map[string]interface{}{
"user_id": userID,
}
path := fmt.Sprintf("auth/%s/login/%s", mount, appID)
secret, err := v.client.Logical().Write(path, vars)
if err != nil {
return "", errors.Wrapf(err, "AppID logon failed")
}
if secret == nil {
return "", errors.New("Empty response from AppID logon")
}
return secret.Auth.ClientToken, nil
} | go | func (v *Vault) AppIDLogin() (string, error) {
appID := env.Getenv("VAULT_APP_ID")
userID := env.Getenv("VAULT_USER_ID")
if appID == "" || userID == "" {
return "", nil
}
mount := env.Getenv("VAULT_AUTH_APP_ID_MOUNT", "app-id")
vars := map[string]interface{}{
"user_id": userID,
}
path := fmt.Sprintf("auth/%s/login/%s", mount, appID)
secret, err := v.client.Logical().Write(path, vars)
if err != nil {
return "", errors.Wrapf(err, "AppID logon failed")
}
if secret == nil {
return "", errors.New("Empty response from AppID logon")
}
return secret.Auth.ClientToken, nil
} | [
"func",
"(",
"v",
"*",
"Vault",
")",
"AppIDLogin",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"appID",
":=",
"env",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"userID",
":=",
"env",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"appI... | // AppIDLogin - app-id auth backend | [
"AppIDLogin",
"-",
"app",
"-",
"id",
"auth",
"backend"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/vault/auth.go#L37-L61 | train |
hairyhenderson/gomplate | vault/auth.go | GitHubLogin | func (v *Vault) GitHubLogin() (string, error) {
githubToken := env.Getenv("VAULT_AUTH_GITHUB_TOKEN")
if githubToken == "" {
return "", nil
}
mount := env.Getenv("VAULT_AUTH_GITHUB_MOUNT", "github")
vars := map[string]interface{}{
"token": githubToken,
}
path := fmt.Sprintf("auth/%s/login", mount)
secret, err := v.client.Logical().Write(path, vars)
if err != nil {
return "", errors.Wrap(err, "AppRole logon failed")
}
if secret == nil {
return "", errors.New("Empty response from AppRole logon")
}
return secret.Auth.ClientToken, nil
} | go | func (v *Vault) GitHubLogin() (string, error) {
githubToken := env.Getenv("VAULT_AUTH_GITHUB_TOKEN")
if githubToken == "" {
return "", nil
}
mount := env.Getenv("VAULT_AUTH_GITHUB_MOUNT", "github")
vars := map[string]interface{}{
"token": githubToken,
}
path := fmt.Sprintf("auth/%s/login", mount)
secret, err := v.client.Logical().Write(path, vars)
if err != nil {
return "", errors.Wrap(err, "AppRole logon failed")
}
if secret == nil {
return "", errors.New("Empty response from AppRole logon")
}
return secret.Auth.ClientToken, nil
} | [
"func",
"(",
"v",
"*",
"Vault",
")",
"GitHubLogin",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"githubToken",
":=",
"env",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"githubToken",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"... | // GitHubLogin - github auth backend | [
"GitHubLogin",
"-",
"github",
"auth",
"backend"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/vault/auth.go#L92-L115 | train |
hairyhenderson/gomplate | vault/auth.go | EC2Login | func (v *Vault) EC2Login() (string, error) {
mount := env.Getenv("VAULT_AUTH_AWS_MOUNT", "aws")
output := env.Getenv("VAULT_AUTH_AWS_NONCE_OUTPUT")
nonce := env.Getenv("VAULT_AUTH_AWS_NONCE")
vars, err := createEc2LoginVars(nonce)
if err != nil {
return "", err
}
if vars["pkcs7"] == "" {
return "", nil
}
path := fmt.Sprintf("auth/%s/login", mount)
secret, err := v.client.Logical().Write(path, vars)
if err != nil {
return "", errors.Wrapf(err, "AWS EC2 logon failed")
}
if secret == nil {
return "", errors.New("Empty response from AWS EC2 logon")
}
if output != "" {
if val, ok := secret.Auth.Metadata["nonce"]; ok {
nonce = val
}
f, err := os.OpenFile(output, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(0600))
if err != nil {
return "", errors.Wrapf(err, "Error opening nonce output file")
}
n, err := f.Write([]byte(nonce + "\n"))
if err != nil {
return "", errors.Wrapf(err, "Error writing nonce output file")
}
if n == 0 {
return "", errors.Wrapf(err, "No bytes written to nonce output file")
}
}
return secret.Auth.ClientToken, nil
} | go | func (v *Vault) EC2Login() (string, error) {
mount := env.Getenv("VAULT_AUTH_AWS_MOUNT", "aws")
output := env.Getenv("VAULT_AUTH_AWS_NONCE_OUTPUT")
nonce := env.Getenv("VAULT_AUTH_AWS_NONCE")
vars, err := createEc2LoginVars(nonce)
if err != nil {
return "", err
}
if vars["pkcs7"] == "" {
return "", nil
}
path := fmt.Sprintf("auth/%s/login", mount)
secret, err := v.client.Logical().Write(path, vars)
if err != nil {
return "", errors.Wrapf(err, "AWS EC2 logon failed")
}
if secret == nil {
return "", errors.New("Empty response from AWS EC2 logon")
}
if output != "" {
if val, ok := secret.Auth.Metadata["nonce"]; ok {
nonce = val
}
f, err := os.OpenFile(output, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(0600))
if err != nil {
return "", errors.Wrapf(err, "Error opening nonce output file")
}
n, err := f.Write([]byte(nonce + "\n"))
if err != nil {
return "", errors.Wrapf(err, "Error writing nonce output file")
}
if n == 0 {
return "", errors.Wrapf(err, "No bytes written to nonce output file")
}
}
return secret.Auth.ClientToken, nil
} | [
"func",
"(",
"v",
"*",
"Vault",
")",
"EC2Login",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"mount",
":=",
"env",
".",
"Getenv",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"output",
":=",
"env",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\... | // EC2Login - AWS EC2 auth backend | [
"EC2Login",
"-",
"AWS",
"EC2",
"auth",
"backend"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/vault/auth.go#L145-L186 | train |
hairyhenderson/gomplate | strings/strings.go | Indent | func Indent(width int, indent, s string) string {
if width == 0 {
return s
}
if width > 1 {
indent = strings.Repeat(indent, width)
}
var res []byte
bol := true
for i := 0; i < len(s); i++ {
c := s[i]
if bol && c != '\n' {
res = append(res, indent...)
}
res = append(res, c)
bol = c == '\n'
}
return string(res)
} | go | func Indent(width int, indent, s string) string {
if width == 0 {
return s
}
if width > 1 {
indent = strings.Repeat(indent, width)
}
var res []byte
bol := true
for i := 0; i < len(s); i++ {
c := s[i]
if bol && c != '\n' {
res = append(res, indent...)
}
res = append(res, c)
bol = c == '\n'
}
return string(res)
} | [
"func",
"Indent",
"(",
"width",
"int",
",",
"indent",
",",
"s",
"string",
")",
"string",
"{",
"if",
"width",
"==",
"0",
"{",
"return",
"s",
"\n",
"}",
"\n",
"if",
"width",
">",
"1",
"{",
"indent",
"=",
"strings",
".",
"Repeat",
"(",
"indent",
","... | // Indent - indent each line of the string with the given indent string | [
"Indent",
"-",
"indent",
"each",
"line",
"of",
"the",
"string",
"with",
"the",
"given",
"indent",
"string"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/strings/strings.go#L12-L30 | train |
hairyhenderson/gomplate | strings/strings.go | Trunc | func Trunc(length int, s string) string {
if length < 0 {
return s
}
if len(s) <= length {
return s
}
return s[0:length]
} | go | func Trunc(length int, s string) string {
if length < 0 {
return s
}
if len(s) <= length {
return s
}
return s[0:length]
} | [
"func",
"Trunc",
"(",
"length",
"int",
",",
"s",
"string",
")",
"string",
"{",
"if",
"length",
"<",
"0",
"{",
"return",
"s",
"\n",
"}",
"\n",
"if",
"len",
"(",
"s",
")",
"<=",
"length",
"{",
"return",
"s",
"\n",
"}",
"\n",
"return",
"s",
"[",
... | // Trunc - truncate a string to the given length | [
"Trunc",
"-",
"truncate",
"a",
"string",
"to",
"the",
"given",
"length"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/strings/strings.go#L33-L41 | train |
hairyhenderson/gomplate | strings/strings.go | wwDefaults | func wwDefaults(opts WordWrapOpts) WordWrapOpts {
if opts.Width == 0 {
opts.Width = 80
}
if opts.LBSeq == "" {
opts.LBSeq = "\n"
}
return opts
} | go | func wwDefaults(opts WordWrapOpts) WordWrapOpts {
if opts.Width == 0 {
opts.Width = 80
}
if opts.LBSeq == "" {
opts.LBSeq = "\n"
}
return opts
} | [
"func",
"wwDefaults",
"(",
"opts",
"WordWrapOpts",
")",
"WordWrapOpts",
"{",
"if",
"opts",
".",
"Width",
"==",
"0",
"{",
"opts",
".",
"Width",
"=",
"80",
"\n",
"}",
"\n",
"if",
"opts",
".",
"LBSeq",
"==",
"\"",
"\"",
"{",
"opts",
".",
"LBSeq",
"=",... | // applies default options | [
"applies",
"default",
"options"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/strings/strings.go#L97-L105 | train |
hairyhenderson/gomplate | strings/strings.go | WordWrap | func WordWrap(in string, opts WordWrapOpts) string {
opts = wwDefaults(opts)
return goutils.WrapCustom(in, int(opts.Width), opts.LBSeq, false)
} | go | func WordWrap(in string, opts WordWrapOpts) string {
opts = wwDefaults(opts)
return goutils.WrapCustom(in, int(opts.Width), opts.LBSeq, false)
} | [
"func",
"WordWrap",
"(",
"in",
"string",
",",
"opts",
"WordWrapOpts",
")",
"string",
"{",
"opts",
"=",
"wwDefaults",
"(",
"opts",
")",
"\n",
"return",
"goutils",
".",
"WrapCustom",
"(",
"in",
",",
"int",
"(",
"opts",
".",
"Width",
")",
",",
"opts",
"... | // WordWrap - insert line-breaks into the string, before it reaches the given
// width. | [
"WordWrap",
"-",
"insert",
"line",
"-",
"breaks",
"into",
"the",
"string",
"before",
"it",
"reaches",
"the",
"given",
"width",
"."
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/strings/strings.go#L109-L112 | train |
hairyhenderson/gomplate | aws/kms.go | NewKMS | func NewKMS(option ClientOptions) *KMS {
client := kms.New(SDKSession())
return &KMS{
Client: client,
}
} | go | func NewKMS(option ClientOptions) *KMS {
client := kms.New(SDKSession())
return &KMS{
Client: client,
}
} | [
"func",
"NewKMS",
"(",
"option",
"ClientOptions",
")",
"*",
"KMS",
"{",
"client",
":=",
"kms",
".",
"New",
"(",
"SDKSession",
"(",
")",
")",
"\n",
"return",
"&",
"KMS",
"{",
"Client",
":",
"client",
",",
"}",
"\n",
"}"
] | // NewKMS - Create new AWS KMS client using an SDKSession | [
"NewKMS",
"-",
"Create",
"new",
"AWS",
"KMS",
"client",
"using",
"an",
"SDKSession"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/aws/kms.go#L21-L26 | train |
hairyhenderson/gomplate | aws/kms.go | Encrypt | func (k *KMS) Encrypt(keyID, plaintext string) (string, error) {
input := &kms.EncryptInput{
KeyId: &keyID,
Plaintext: []byte(plaintext),
}
output, err := k.Client.Encrypt(input)
if err != nil {
return "", err
}
ciphertext, err := b64.Encode(output.CiphertextBlob)
if err != nil {
return "", err
}
return ciphertext, nil
} | go | func (k *KMS) Encrypt(keyID, plaintext string) (string, error) {
input := &kms.EncryptInput{
KeyId: &keyID,
Plaintext: []byte(plaintext),
}
output, err := k.Client.Encrypt(input)
if err != nil {
return "", err
}
ciphertext, err := b64.Encode(output.CiphertextBlob)
if err != nil {
return "", err
}
return ciphertext, nil
} | [
"func",
"(",
"k",
"*",
"KMS",
")",
"Encrypt",
"(",
"keyID",
",",
"plaintext",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"input",
":=",
"&",
"kms",
".",
"EncryptInput",
"{",
"KeyId",
":",
"&",
"keyID",
",",
"Plaintext",
":",
"[",
"]",
... | // Encrypt plaintext using the specified key.
// Returns a base64 encoded ciphertext | [
"Encrypt",
"plaintext",
"using",
"the",
"specified",
"key",
".",
"Returns",
"a",
"base64",
"encoded",
"ciphertext"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/aws/kms.go#L30-L44 | train |
hairyhenderson/gomplate | aws/kms.go | Decrypt | func (k *KMS) Decrypt(ciphertext string) (string, error) {
ciphertextBlob, err := b64.Decode(ciphertext)
if err != nil {
return "", err
}
input := &kms.DecryptInput{
CiphertextBlob: []byte(ciphertextBlob),
}
output, err := k.Client.Decrypt(input)
if err != nil {
return "", err
}
return string(output.Plaintext), nil
} | go | func (k *KMS) Decrypt(ciphertext string) (string, error) {
ciphertextBlob, err := b64.Decode(ciphertext)
if err != nil {
return "", err
}
input := &kms.DecryptInput{
CiphertextBlob: []byte(ciphertextBlob),
}
output, err := k.Client.Decrypt(input)
if err != nil {
return "", err
}
return string(output.Plaintext), nil
} | [
"func",
"(",
"k",
"*",
"KMS",
")",
"Decrypt",
"(",
"ciphertext",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"ciphertextBlob",
",",
"err",
":=",
"b64",
".",
"Decode",
"(",
"ciphertext",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // Decrypt a base64 encoded ciphertext | [
"Decrypt",
"a",
"base64",
"encoded",
"ciphertext"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/aws/kms.go#L47-L60 | train |
hairyhenderson/gomplate | template.go | loadContents | func (t *tplate) loadContents() (err error) {
if t.contents == "" {
t.contents, err = readInput(t.name)
}
return err
} | go | func (t *tplate) loadContents() (err error) {
if t.contents == "" {
t.contents, err = readInput(t.name)
}
return err
} | [
"func",
"(",
"t",
"*",
"tplate",
")",
"loadContents",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"t",
".",
"contents",
"==",
"\"",
"\"",
"{",
"t",
".",
"contents",
",",
"err",
"=",
"readInput",
"(",
"t",
".",
"name",
")",
"\n",
"}",
"\n",
... | // loadContents - reads the template in _once_ if it hasn't yet been read. Uses the name! | [
"loadContents",
"-",
"reads",
"the",
"template",
"in",
"_once_",
"if",
"it",
"hasn",
"t",
"yet",
"been",
"read",
".",
"Uses",
"the",
"name!"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/template.go#L80-L85 | train |
hairyhenderson/gomplate | funcs/math.go | Seq | func (f *MathFuncs) Seq(n ...interface{}) ([]int64, error) {
start := int64(1)
end := int64(0)
step := int64(1)
if len(n) == 0 {
return nil, fmt.Errorf("math.Seq must be given at least an 'end' value")
}
if len(n) == 1 {
end = conv.ToInt64(n[0])
}
if len(n) == 2 {
start = conv.ToInt64(n[0])
end = conv.ToInt64(n[1])
}
if len(n) == 3 {
start = conv.ToInt64(n[0])
end = conv.ToInt64(n[1])
step = conv.ToInt64(n[2])
}
return math.Seq(conv.ToInt64(start), conv.ToInt64(end), conv.ToInt64(step)), nil
} | go | func (f *MathFuncs) Seq(n ...interface{}) ([]int64, error) {
start := int64(1)
end := int64(0)
step := int64(1)
if len(n) == 0 {
return nil, fmt.Errorf("math.Seq must be given at least an 'end' value")
}
if len(n) == 1 {
end = conv.ToInt64(n[0])
}
if len(n) == 2 {
start = conv.ToInt64(n[0])
end = conv.ToInt64(n[1])
}
if len(n) == 3 {
start = conv.ToInt64(n[0])
end = conv.ToInt64(n[1])
step = conv.ToInt64(n[2])
}
return math.Seq(conv.ToInt64(start), conv.ToInt64(end), conv.ToInt64(step)), nil
} | [
"func",
"(",
"f",
"*",
"MathFuncs",
")",
"Seq",
"(",
"n",
"...",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"int64",
",",
"error",
")",
"{",
"start",
":=",
"int64",
"(",
"1",
")",
"\n",
"end",
":=",
"int64",
"(",
"0",
")",
"\n",
"step",
":=",... | // Seq - return a sequence from `start` to `end`, in steps of `step`
// start and step are optional, and default to 1. | [
"Seq",
"-",
"return",
"a",
"sequence",
"from",
"start",
"to",
"end",
"in",
"steps",
"of",
"step",
"start",
"and",
"step",
"are",
"optional",
"and",
"default",
"to",
"1",
"."
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs/math.go#L165-L185 | train |
hairyhenderson/gomplate | data/datasource.go | registerReaders | func (d *Data) registerReaders() {
d.sourceReaders = make(map[string]func(*Source, ...string) ([]byte, error))
d.sourceReaders["aws+smp"] = readAWSSMP
d.sourceReaders["boltdb"] = readBoltDB
d.sourceReaders["consul"] = readConsul
d.sourceReaders["consul+http"] = readConsul
d.sourceReaders["consul+https"] = readConsul
d.sourceReaders["env"] = readEnv
d.sourceReaders["file"] = readFile
d.sourceReaders["http"] = readHTTP
d.sourceReaders["https"] = readHTTP
d.sourceReaders["merge"] = d.readMerge
d.sourceReaders["stdin"] = readStdin
d.sourceReaders["vault"] = readVault
d.sourceReaders["vault+http"] = readVault
d.sourceReaders["vault+https"] = readVault
} | go | func (d *Data) registerReaders() {
d.sourceReaders = make(map[string]func(*Source, ...string) ([]byte, error))
d.sourceReaders["aws+smp"] = readAWSSMP
d.sourceReaders["boltdb"] = readBoltDB
d.sourceReaders["consul"] = readConsul
d.sourceReaders["consul+http"] = readConsul
d.sourceReaders["consul+https"] = readConsul
d.sourceReaders["env"] = readEnv
d.sourceReaders["file"] = readFile
d.sourceReaders["http"] = readHTTP
d.sourceReaders["https"] = readHTTP
d.sourceReaders["merge"] = d.readMerge
d.sourceReaders["stdin"] = readStdin
d.sourceReaders["vault"] = readVault
d.sourceReaders["vault+http"] = readVault
d.sourceReaders["vault+https"] = readVault
} | [
"func",
"(",
"d",
"*",
"Data",
")",
"registerReaders",
"(",
")",
"{",
"d",
".",
"sourceReaders",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"func",
"(",
"*",
"Source",
",",
"...",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
")",
... | // registerReaders registers the source-reader functions | [
"registerReaders",
"registers",
"the",
"source",
"-",
"reader",
"functions"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/datasource.go#L44-L61 | train |
hairyhenderson/gomplate | data/datasource.go | lookupReader | func (d *Data) lookupReader(scheme string) (func(*Source, ...string) ([]byte, error), error) {
if d.sourceReaders == nil {
d.registerReaders()
}
r, ok := d.sourceReaders[scheme]
if !ok {
return nil, errors.Errorf("scheme %s not registered", scheme)
}
return r, nil
} | go | func (d *Data) lookupReader(scheme string) (func(*Source, ...string) ([]byte, error), error) {
if d.sourceReaders == nil {
d.registerReaders()
}
r, ok := d.sourceReaders[scheme]
if !ok {
return nil, errors.Errorf("scheme %s not registered", scheme)
}
return r, nil
} | [
"func",
"(",
"d",
"*",
"Data",
")",
"lookupReader",
"(",
"scheme",
"string",
")",
"(",
"func",
"(",
"*",
"Source",
",",
"...",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
",",
"error",
")",
"{",
"if",
"d",
".",
"sourceReaders",
"==",... | // lookupReader - return the reader function for the given scheme | [
"lookupReader",
"-",
"return",
"the",
"reader",
"function",
"for",
"the",
"given",
"scheme"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/datasource.go#L64-L73 | train |
hairyhenderson/gomplate | data/datasource.go | NewData | func NewData(datasourceArgs, headerArgs []string) (*Data, error) {
headers, err := parseHeaderArgs(headerArgs)
if err != nil {
return nil, err
}
data := &Data{
Sources: make(map[string]*Source),
extraHeaders: headers,
}
for _, v := range datasourceArgs {
s, err := parseSource(v)
if err != nil {
return nil, errors.Wrapf(err, "error parsing datasource")
}
s.header = headers[s.Alias]
// pop the header out of the map, so we end up with only the unreferenced ones
delete(headers, s.Alias)
data.Sources[s.Alias] = s
}
return data, nil
} | go | func NewData(datasourceArgs, headerArgs []string) (*Data, error) {
headers, err := parseHeaderArgs(headerArgs)
if err != nil {
return nil, err
}
data := &Data{
Sources: make(map[string]*Source),
extraHeaders: headers,
}
for _, v := range datasourceArgs {
s, err := parseSource(v)
if err != nil {
return nil, errors.Wrapf(err, "error parsing datasource")
}
s.header = headers[s.Alias]
// pop the header out of the map, so we end up with only the unreferenced ones
delete(headers, s.Alias)
data.Sources[s.Alias] = s
}
return data, nil
} | [
"func",
"NewData",
"(",
"datasourceArgs",
",",
"headerArgs",
"[",
"]",
"string",
")",
"(",
"*",
"Data",
",",
"error",
")",
"{",
"headers",
",",
"err",
":=",
"parseHeaderArgs",
"(",
"headerArgs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil"... | // NewData - constructor for Data | [
"NewData",
"-",
"constructor",
"for",
"Data"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/datasource.go#L95-L118 | train |
hairyhenderson/gomplate | data/datasource.go | DatasourceReachable | func (d *Data) DatasourceReachable(alias string, args ...string) bool {
source, ok := d.Sources[alias]
if !ok {
return false
}
_, err := d.readSource(source, args...)
return err == nil
} | go | func (d *Data) DatasourceReachable(alias string, args ...string) bool {
source, ok := d.Sources[alias]
if !ok {
return false
}
_, err := d.readSource(source, args...)
return err == nil
} | [
"func",
"(",
"d",
"*",
"Data",
")",
"DatasourceReachable",
"(",
"alias",
"string",
",",
"args",
"...",
"string",
")",
"bool",
"{",
"source",
",",
"ok",
":=",
"d",
".",
"Sources",
"[",
"alias",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n... | // DatasourceReachable - Determines if the named datasource is reachable with
// the given arguments. Reads from the datasource, and discards the returned data. | [
"DatasourceReachable",
"-",
"Determines",
"if",
"the",
"named",
"datasource",
"is",
"reachable",
"with",
"the",
"given",
"arguments",
".",
"Reads",
"from",
"the",
"datasource",
"and",
"discards",
"the",
"returned",
"data",
"."
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/datasource.go#L377-L384 | train |
hairyhenderson/gomplate | vault/vault.go | Read | func (v *Vault) Read(path string) ([]byte, error) {
secret, err := v.client.Logical().Read(path)
if err != nil {
return nil, err
}
if secret == nil {
return []byte{}, nil
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
if err := enc.Encode(secret.Data); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | go | func (v *Vault) Read(path string) ([]byte, error) {
secret, err := v.client.Logical().Read(path)
if err != nil {
return nil, err
}
if secret == nil {
return []byte{}, nil
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
if err := enc.Encode(secret.Data); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | [
"func",
"(",
"v",
"*",
"Vault",
")",
"Read",
"(",
"path",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"secret",
",",
"err",
":=",
"v",
".",
"client",
".",
"Logical",
"(",
")",
".",
"Read",
"(",
"path",
")",
"\n",
"if",
"err"... | // Read - returns the value of a given path. If no value is found at the given
// path, returns empty slice. | [
"Read",
"-",
"returns",
"the",
"value",
"of",
"a",
"given",
"path",
".",
"If",
"no",
"value",
"is",
"found",
"at",
"the",
"given",
"path",
"returns",
"empty",
"slice",
"."
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/vault/vault.go#L64-L79 | train |
hairyhenderson/gomplate | math/math.go | Seq | func Seq(start, end, step int64) []int64 {
// a step of 0 just returns an empty sequence
if step == 0 {
return []int64{}
}
// handle cases where step has wrong sign
if end < start && step > 0 {
step = -step
}
if end > start && step < 0 {
step = -step
}
// adjust the end so it aligns exactly (avoids infinite loop!)
end = end - (end-start)%step
seq := []int64{start}
last := start
for last != end {
last = seq[len(seq)-1] + step
seq = append(seq, last)
}
return seq
} | go | func Seq(start, end, step int64) []int64 {
// a step of 0 just returns an empty sequence
if step == 0 {
return []int64{}
}
// handle cases where step has wrong sign
if end < start && step > 0 {
step = -step
}
if end > start && step < 0 {
step = -step
}
// adjust the end so it aligns exactly (avoids infinite loop!)
end = end - (end-start)%step
seq := []int64{start}
last := start
for last != end {
last = seq[len(seq)-1] + step
seq = append(seq, last)
}
return seq
} | [
"func",
"Seq",
"(",
"start",
",",
"end",
",",
"step",
"int64",
")",
"[",
"]",
"int64",
"{",
"// a step of 0 just returns an empty sequence",
"if",
"step",
"==",
"0",
"{",
"return",
"[",
"]",
"int64",
"{",
"}",
"\n",
"}",
"\n\n",
"// handle cases where step h... | // Seq - return a sequence from `start` to `end`, in steps of `step`. | [
"Seq",
"-",
"return",
"a",
"sequence",
"from",
"start",
"to",
"end",
"in",
"steps",
"of",
"step",
"."
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/math/math.go#L22-L46 | train |
hairyhenderson/gomplate | funcs/time.go | padRight | func padRight(in, pad string, length int) string {
for {
in += pad
if len(in) > length {
return in[0:length]
}
}
} | go | func padRight(in, pad string, length int) string {
for {
in += pad
if len(in) > length {
return in[0:length]
}
}
} | [
"func",
"padRight",
"(",
"in",
",",
"pad",
"string",
",",
"length",
"int",
")",
"string",
"{",
"for",
"{",
"in",
"+=",
"pad",
"\n",
"if",
"len",
"(",
"in",
")",
">",
"length",
"{",
"return",
"in",
"[",
"0",
":",
"length",
"]",
"\n",
"}",
"\n",
... | // pads a number with zeroes | [
"pads",
"a",
"number",
"with",
"zeroes"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs/time.go#L195-L202 | train |
hairyhenderson/gomplate | funcs.go | Funcs | func Funcs(d *data.Data) template.FuncMap {
f := template.FuncMap{}
funcs.AddDataFuncs(f, d)
funcs.AWSFuncs(f)
funcs.AddBase64Funcs(f)
funcs.AddNetFuncs(f)
funcs.AddReFuncs(f)
funcs.AddStringFuncs(f)
funcs.AddEnvFuncs(f)
funcs.AddConvFuncs(f)
funcs.AddTimeFuncs(f)
funcs.AddMathFuncs(f)
funcs.AddCryptoFuncs(f)
funcs.AddFileFuncs(f)
funcs.AddFilePathFuncs(f)
funcs.AddPathFuncs(f)
funcs.AddSockaddrFuncs(f)
funcs.AddTestFuncs(f)
funcs.AddCollFuncs(f)
funcs.AddUUIDFuncs(f)
funcs.AddRandomFuncs(f)
return f
} | go | func Funcs(d *data.Data) template.FuncMap {
f := template.FuncMap{}
funcs.AddDataFuncs(f, d)
funcs.AWSFuncs(f)
funcs.AddBase64Funcs(f)
funcs.AddNetFuncs(f)
funcs.AddReFuncs(f)
funcs.AddStringFuncs(f)
funcs.AddEnvFuncs(f)
funcs.AddConvFuncs(f)
funcs.AddTimeFuncs(f)
funcs.AddMathFuncs(f)
funcs.AddCryptoFuncs(f)
funcs.AddFileFuncs(f)
funcs.AddFilePathFuncs(f)
funcs.AddPathFuncs(f)
funcs.AddSockaddrFuncs(f)
funcs.AddTestFuncs(f)
funcs.AddCollFuncs(f)
funcs.AddUUIDFuncs(f)
funcs.AddRandomFuncs(f)
return f
} | [
"func",
"Funcs",
"(",
"d",
"*",
"data",
".",
"Data",
")",
"template",
".",
"FuncMap",
"{",
"f",
":=",
"template",
".",
"FuncMap",
"{",
"}",
"\n",
"funcs",
".",
"AddDataFuncs",
"(",
"f",
",",
"d",
")",
"\n",
"funcs",
".",
"AWSFuncs",
"(",
"f",
")"... | // Funcs - The function mappings are defined here! | [
"Funcs",
"-",
"The",
"function",
"mappings",
"are",
"defined",
"here!"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/funcs.go#L11-L33 | train |
hairyhenderson/gomplate | data/data.go | JSON | func JSON(in string) (map[string]interface{}, error) {
obj := make(map[string]interface{})
out, err := unmarshalObj(obj, in, yaml.Unmarshal)
if err != nil {
return out, err
}
_, ok := out[ejsonJson.PublicKeyField]
if ok {
out, err = decryptEJSON(in)
}
return out, err
} | go | func JSON(in string) (map[string]interface{}, error) {
obj := make(map[string]interface{})
out, err := unmarshalObj(obj, in, yaml.Unmarshal)
if err != nil {
return out, err
}
_, ok := out[ejsonJson.PublicKeyField]
if ok {
out, err = decryptEJSON(in)
}
return out, err
} | [
"func",
"JSON",
"(",
"in",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"obj",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"out",
",",
"err",
":=",
"unmarshalObj... | // JSON - Unmarshal a JSON Object. Can be ejson-encrypted. | [
"JSON",
"-",
"Unmarshal",
"a",
"JSON",
"Object",
".",
"Can",
"be",
"ejson",
"-",
"encrypted",
"."
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L47-L59 | train |
hairyhenderson/gomplate | data/data.go | decryptEJSON | func decryptEJSON(in string) (map[string]interface{}, error) {
keyDir := env.Getenv("EJSON_KEYDIR", "/opt/ejson/keys")
key := env.Getenv("EJSON_KEY")
rIn := bytes.NewBufferString(in)
rOut := &bytes.Buffer{}
err := ejson.Decrypt(rIn, rOut, keyDir, key)
if err != nil {
return nil, errors.WithStack(err)
}
obj := make(map[string]interface{})
out, err := unmarshalObj(obj, rOut.String(), yaml.Unmarshal)
if err != nil {
return nil, errors.WithStack(err)
}
delete(out, ejsonJson.PublicKeyField)
return out, nil
} | go | func decryptEJSON(in string) (map[string]interface{}, error) {
keyDir := env.Getenv("EJSON_KEYDIR", "/opt/ejson/keys")
key := env.Getenv("EJSON_KEY")
rIn := bytes.NewBufferString(in)
rOut := &bytes.Buffer{}
err := ejson.Decrypt(rIn, rOut, keyDir, key)
if err != nil {
return nil, errors.WithStack(err)
}
obj := make(map[string]interface{})
out, err := unmarshalObj(obj, rOut.String(), yaml.Unmarshal)
if err != nil {
return nil, errors.WithStack(err)
}
delete(out, ejsonJson.PublicKeyField)
return out, nil
} | [
"func",
"decryptEJSON",
"(",
"in",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"keyDir",
":=",
"env",
".",
"Getenv",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"key",
":=",
"env",
".",
"Getenv",... | // decryptEJSON - decrypts an ejson input, and unmarshals it, stripping the _public_key field. | [
"decryptEJSON",
"-",
"decrypts",
"an",
"ejson",
"input",
"and",
"unmarshals",
"it",
"stripping",
"the",
"_public_key",
"field",
"."
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L62-L79 | train |
hairyhenderson/gomplate | data/data.go | JSONArray | func JSONArray(in string) ([]interface{}, error) {
obj := make([]interface{}, 1)
return unmarshalArray(obj, in, yaml.Unmarshal)
} | go | func JSONArray(in string) ([]interface{}, error) {
obj := make([]interface{}, 1)
return unmarshalArray(obj, in, yaml.Unmarshal)
} | [
"func",
"JSONArray",
"(",
"in",
"string",
")",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"obj",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"1",
")",
"\n",
"return",
"unmarshalArray",
"(",
"obj",
",",
"in",
",",
... | // JSONArray - Unmarshal a JSON Array | [
"JSONArray",
"-",
"Unmarshal",
"a",
"JSON",
"Array"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L82-L85 | train |
hairyhenderson/gomplate | data/data.go | YAML | func YAML(in string) (map[string]interface{}, error) {
obj := make(map[string]interface{})
return unmarshalObj(obj, in, yaml.Unmarshal)
} | go | func YAML(in string) (map[string]interface{}, error) {
obj := make(map[string]interface{})
return unmarshalObj(obj, in, yaml.Unmarshal)
} | [
"func",
"YAML",
"(",
"in",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"obj",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"return",
"unmarshalObj",
"(",
"obj",
... | // YAML - Unmarshal a YAML Object | [
"YAML",
"-",
"Unmarshal",
"a",
"YAML",
"Object"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L88-L91 | train |
hairyhenderson/gomplate | data/data.go | TOML | func TOML(in string) (interface{}, error) {
obj := make(map[string]interface{})
return unmarshalObj(obj, in, toml.Unmarshal)
} | go | func TOML(in string) (interface{}, error) {
obj := make(map[string]interface{})
return unmarshalObj(obj, in, toml.Unmarshal)
} | [
"func",
"TOML",
"(",
"in",
"string",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"obj",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"return",
"unmarshalObj",
"(",
"obj",
",",
"in",
",",
"toml",
"."... | // TOML - Unmarshal a TOML Object | [
"TOML",
"-",
"Unmarshal",
"a",
"TOML",
"Object"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L100-L103 | train |
hairyhenderson/gomplate | data/data.go | dotEnv | func dotEnv(in string) (interface{}, error) {
env, err := godotenv.Unmarshal(in)
if err != nil {
return nil, err
}
out := make(map[string]interface{})
for k, v := range env {
out[k] = v
}
return out, nil
} | go | func dotEnv(in string) (interface{}, error) {
env, err := godotenv.Unmarshal(in)
if err != nil {
return nil, err
}
out := make(map[string]interface{})
for k, v := range env {
out[k] = v
}
return out, nil
} | [
"func",
"dotEnv",
"(",
"in",
"string",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"env",
",",
"err",
":=",
"godotenv",
".",
"Unmarshal",
"(",
"in",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
... | // dotEnv - Unmarshal a dotenv file | [
"dotEnv",
"-",
"Unmarshal",
"a",
"dotenv",
"file"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L106-L116 | train |
hairyhenderson/gomplate | data/data.go | autoIndex | func autoIndex(i int) string {
s := ""
for n := 0; n <= i/26; n++ {
s += string('A' + i%26)
}
return s
} | go | func autoIndex(i int) string {
s := ""
for n := 0; n <= i/26; n++ {
s += string('A' + i%26)
}
return s
} | [
"func",
"autoIndex",
"(",
"i",
"int",
")",
"string",
"{",
"s",
":=",
"\"",
"\"",
"\n",
"for",
"n",
":=",
"0",
";",
"n",
"<=",
"i",
"/",
"26",
";",
"n",
"++",
"{",
"s",
"+=",
"string",
"(",
"'A'",
"+",
"i",
"%",
"26",
")",
"\n",
"}",
"\n",... | // autoIndex - calculates a default string column name given a numeric value | [
"autoIndex",
"-",
"calculates",
"a",
"default",
"string",
"column",
"name",
"given",
"a",
"numeric",
"value"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L164-L170 | train |
hairyhenderson/gomplate | data/data.go | ToJSON | func ToJSON(in interface{}) (string, error) {
s, err := toJSONBytes(in)
if err != nil {
return "", err
}
return string(s), nil
} | go | func ToJSON(in interface{}) (string, error) {
s, err := toJSONBytes(in)
if err != nil {
return "", err
}
return string(s), nil
} | [
"func",
"ToJSON",
"(",
"in",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"s",
",",
"err",
":=",
"toJSONBytes",
"(",
"in",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"retur... | // ToJSON - Stringify a struct as JSON | [
"ToJSON",
"-",
"Stringify",
"a",
"struct",
"as",
"JSON"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L288-L294 | train |
hairyhenderson/gomplate | data/data.go | ToTOML | func ToTOML(in interface{}) (string, error) {
buf := new(bytes.Buffer)
err := toml.NewEncoder(buf).Encode(in)
if err != nil {
return "", errors.Wrapf(err, "Unable to marshal %s", in)
}
return buf.String(), nil
} | go | func ToTOML(in interface{}) (string, error) {
buf := new(bytes.Buffer)
err := toml.NewEncoder(buf).Encode(in)
if err != nil {
return "", errors.Wrapf(err, "Unable to marshal %s", in)
}
return buf.String(), nil
} | [
"func",
"ToTOML",
"(",
"in",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"error",
")",
"{",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"err",
":=",
"toml",
".",
"NewEncoder",
"(",
"buf",
")",
".",
"Encode",
"(",
"in",
")",
... | // ToTOML - Stringify a struct as TOML | [
"ToTOML",
"-",
"Stringify",
"a",
"struct",
"as",
"TOML"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/data/data.go#L317-L324 | train |
hairyhenderson/gomplate | libkv/consul.go | NewConsul | func NewConsul(u *url.URL) (*LibKV, error) {
consul.Register()
c, err := consulURL(u)
if err != nil {
return nil, err
}
config, err := consulConfig(c.Scheme == https)
if err != nil {
return nil, err
}
if role := env.Getenv("CONSUL_VAULT_ROLE", ""); role != "" {
mount := env.Getenv("CONSUL_VAULT_MOUNT", "consul")
var client *vault.Vault
client, err = vault.New(nil)
if err != nil {
return nil, err
}
err = client.Login()
defer client.Logout()
if err != nil {
return nil, err
}
path := fmt.Sprintf("%s/creds/%s", mount, role)
var data []byte
data, err = client.Read(path)
if err != nil {
return nil, errors.Wrapf(err, "vault consul auth failed")
}
decoded := make(map[string]interface{})
err = yaml.Unmarshal(data, &decoded)
if err != nil {
return nil, errors.Wrapf(err, "Unable to unmarshal object")
}
token := decoded["token"].(string)
// nolint: gosec
_ = os.Setenv("CONSUL_HTTP_TOKEN", token)
}
var kv store.Store
kv, err = libkv.NewStore(store.CONSUL, []string{c.String()}, config)
if err != nil {
return nil, errors.Wrapf(err, "Consul setup failed")
}
return &LibKV{kv}, nil
} | go | func NewConsul(u *url.URL) (*LibKV, error) {
consul.Register()
c, err := consulURL(u)
if err != nil {
return nil, err
}
config, err := consulConfig(c.Scheme == https)
if err != nil {
return nil, err
}
if role := env.Getenv("CONSUL_VAULT_ROLE", ""); role != "" {
mount := env.Getenv("CONSUL_VAULT_MOUNT", "consul")
var client *vault.Vault
client, err = vault.New(nil)
if err != nil {
return nil, err
}
err = client.Login()
defer client.Logout()
if err != nil {
return nil, err
}
path := fmt.Sprintf("%s/creds/%s", mount, role)
var data []byte
data, err = client.Read(path)
if err != nil {
return nil, errors.Wrapf(err, "vault consul auth failed")
}
decoded := make(map[string]interface{})
err = yaml.Unmarshal(data, &decoded)
if err != nil {
return nil, errors.Wrapf(err, "Unable to unmarshal object")
}
token := decoded["token"].(string)
// nolint: gosec
_ = os.Setenv("CONSUL_HTTP_TOKEN", token)
}
var kv store.Store
kv, err = libkv.NewStore(store.CONSUL, []string{c.String()}, config)
if err != nil {
return nil, errors.Wrapf(err, "Consul setup failed")
}
return &LibKV{kv}, nil
} | [
"func",
"NewConsul",
"(",
"u",
"*",
"url",
".",
"URL",
")",
"(",
"*",
"LibKV",
",",
"error",
")",
"{",
"consul",
".",
"Register",
"(",
")",
"\n",
"c",
",",
"err",
":=",
"consulURL",
"(",
"u",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // NewConsul - instantiate a new Consul datasource handler | [
"NewConsul",
"-",
"instantiate",
"a",
"new",
"Consul",
"datasource",
"handler"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/libkv/consul.go#L29-L78 | train |
hairyhenderson/gomplate | coll/coll.go | Keys | func Keys(in ...map[string]interface{}) ([]string, error) {
if len(in) == 0 {
return nil, fmt.Errorf("need at least one argument")
}
keys := []string{}
for _, m := range in {
k, _ := splitMap(m)
keys = append(keys, k...)
}
return keys, nil
} | go | func Keys(in ...map[string]interface{}) ([]string, error) {
if len(in) == 0 {
return nil, fmt.Errorf("need at least one argument")
}
keys := []string{}
for _, m := range in {
k, _ := splitMap(m)
keys = append(keys, k...)
}
return keys, nil
} | [
"func",
"Keys",
"(",
"in",
"...",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"len",
"(",
"in",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\""... | // Keys returns the list of keys in one or more maps. The returned list of keys
// is ordered by map, each in sorted key order. | [
"Keys",
"returns",
"the",
"list",
"of",
"keys",
"in",
"one",
"or",
"more",
"maps",
".",
"The",
"returned",
"list",
"of",
"keys",
"is",
"ordered",
"by",
"map",
"each",
"in",
"sorted",
"key",
"order",
"."
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/coll/coll.go#L74-L84 | train |
hairyhenderson/gomplate | coll/coll.go | mergeValues | func mergeValues(d map[string]interface{}, o map[string]interface{}) map[string]interface{} {
def := copyMap(d)
over := copyMap(o)
for k, v := range over {
// If the key doesn't exist already, then just set the key to that value
if _, exists := def[k]; !exists {
def[k] = v
continue
}
nextMap, ok := v.(map[string]interface{})
// If it isn't another map, overwrite the value
if !ok {
def[k] = v
continue
}
// Edge case: If the key exists in the default, but isn't a map
defMap, isMap := def[k].(map[string]interface{})
// If the override map has a map for this key, prefer it
if !isMap {
def[k] = v
continue
}
// If we got to this point, it is a map in both, so merge them
def[k] = mergeValues(defMap, nextMap)
}
return def
} | go | func mergeValues(d map[string]interface{}, o map[string]interface{}) map[string]interface{} {
def := copyMap(d)
over := copyMap(o)
for k, v := range over {
// If the key doesn't exist already, then just set the key to that value
if _, exists := def[k]; !exists {
def[k] = v
continue
}
nextMap, ok := v.(map[string]interface{})
// If it isn't another map, overwrite the value
if !ok {
def[k] = v
continue
}
// Edge case: If the key exists in the default, but isn't a map
defMap, isMap := def[k].(map[string]interface{})
// If the override map has a map for this key, prefer it
if !isMap {
def[k] = v
continue
}
// If we got to this point, it is a map in both, so merge them
def[k] = mergeValues(defMap, nextMap)
}
return def
} | [
"func",
"mergeValues",
"(",
"d",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"o",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"def",
":=",
"copyMap",
"(",
"d",
")",
"\n"... | // Merges a default and override map | [
"Merges",
"a",
"default",
"and",
"override",
"map"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/coll/coll.go#L184-L210 | train |
hairyhenderson/gomplate | coll/coll.go | Sort | func Sort(key string, list interface{}) (out []interface{}, err error) {
if list == nil {
return nil, nil
}
ia, err := interfaceSlice(list)
if err != nil {
return nil, err
}
// if the types are all the same, we can sort the slice
if sameTypes(ia) {
s := make([]interface{}, len(ia))
// make a copy so the original is unmodified
copy(s, ia)
sort.SliceStable(s, func(i, j int) bool {
return lessThan(key)(s[i], s[j])
})
return s, nil
}
return ia, nil
} | go | func Sort(key string, list interface{}) (out []interface{}, err error) {
if list == nil {
return nil, nil
}
ia, err := interfaceSlice(list)
if err != nil {
return nil, err
}
// if the types are all the same, we can sort the slice
if sameTypes(ia) {
s := make([]interface{}, len(ia))
// make a copy so the original is unmodified
copy(s, ia)
sort.SliceStable(s, func(i, j int) bool {
return lessThan(key)(s[i], s[j])
})
return s, nil
}
return ia, nil
} | [
"func",
"Sort",
"(",
"key",
"string",
",",
"list",
"interface",
"{",
"}",
")",
"(",
"out",
"[",
"]",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"if",
"list",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"ia",
","... | // Sort a given array or slice. Uses natural sort order if possible. If a
// non-empty key is given and the list elements are maps, this will attempt to
// sort by the values of those entries.
//
// Does not modify the input list. | [
"Sort",
"a",
"given",
"array",
"or",
"slice",
".",
"Uses",
"natural",
"sort",
"order",
"if",
"possible",
".",
"If",
"a",
"non",
"-",
"empty",
"key",
"is",
"given",
"and",
"the",
"list",
"elements",
"are",
"maps",
"this",
"will",
"attempt",
"to",
"sort"... | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/coll/coll.go#L217-L237 | train |
hairyhenderson/gomplate | coll/coll.go | lessThan | func lessThan(key string) func(left, right interface{}) bool {
return func(left, right interface{}) bool {
val := reflect.Indirect(reflect.ValueOf(left))
rval := reflect.Indirect(reflect.ValueOf(right))
switch val.Kind() {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
return val.Int() < rval.Int()
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64:
return val.Uint() < rval.Uint()
case reflect.Float32, reflect.Float64:
return val.Float() < rval.Float()
case reflect.String:
return val.String() < rval.String()
case reflect.MapOf(
reflect.TypeOf(reflect.String),
reflect.TypeOf(reflect.Interface),
).Kind():
kval := reflect.ValueOf(key)
if !val.MapIndex(kval).IsValid() {
return false
}
newleft := val.MapIndex(kval).Interface()
newright := rval.MapIndex(kval).Interface()
return lessThan("")(newleft, newright)
case reflect.Struct:
if !val.FieldByName(key).IsValid() {
return false
}
newleft := val.FieldByName(key).Interface()
newright := rval.FieldByName(key).Interface()
return lessThan("")(newleft, newright)
default:
// it's not really comparable, so...
return false
}
}
} | go | func lessThan(key string) func(left, right interface{}) bool {
return func(left, right interface{}) bool {
val := reflect.Indirect(reflect.ValueOf(left))
rval := reflect.Indirect(reflect.ValueOf(right))
switch val.Kind() {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
return val.Int() < rval.Int()
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64:
return val.Uint() < rval.Uint()
case reflect.Float32, reflect.Float64:
return val.Float() < rval.Float()
case reflect.String:
return val.String() < rval.String()
case reflect.MapOf(
reflect.TypeOf(reflect.String),
reflect.TypeOf(reflect.Interface),
).Kind():
kval := reflect.ValueOf(key)
if !val.MapIndex(kval).IsValid() {
return false
}
newleft := val.MapIndex(kval).Interface()
newright := rval.MapIndex(kval).Interface()
return lessThan("")(newleft, newright)
case reflect.Struct:
if !val.FieldByName(key).IsValid() {
return false
}
newleft := val.FieldByName(key).Interface()
newright := rval.FieldByName(key).Interface()
return lessThan("")(newleft, newright)
default:
// it's not really comparable, so...
return false
}
}
} | [
"func",
"lessThan",
"(",
"key",
"string",
")",
"func",
"(",
"left",
",",
"right",
"interface",
"{",
"}",
")",
"bool",
"{",
"return",
"func",
"(",
"left",
",",
"right",
"interface",
"{",
"}",
")",
"bool",
"{",
"val",
":=",
"reflect",
".",
"Indirect",
... | // lessThan - compare two values of the same type | [
"lessThan",
"-",
"compare",
"two",
"values",
"of",
"the",
"same",
"type"
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/coll/coll.go#L240-L276 | train |
hairyhenderson/gomplate | config.go | getMode | func (o *Config) getMode() (os.FileMode, bool, error) {
modeOverride := o.OutMode != ""
m, err := strconv.ParseUint("0"+o.OutMode, 8, 32)
if err != nil {
return 0, false, err
}
mode := os.FileMode(m)
if mode == 0 && o.Input != "" {
mode = 0644
}
return mode, modeOverride, nil
} | go | func (o *Config) getMode() (os.FileMode, bool, error) {
modeOverride := o.OutMode != ""
m, err := strconv.ParseUint("0"+o.OutMode, 8, 32)
if err != nil {
return 0, false, err
}
mode := os.FileMode(m)
if mode == 0 && o.Input != "" {
mode = 0644
}
return mode, modeOverride, nil
} | [
"func",
"(",
"o",
"*",
"Config",
")",
"getMode",
"(",
")",
"(",
"os",
".",
"FileMode",
",",
"bool",
",",
"error",
")",
"{",
"modeOverride",
":=",
"o",
".",
"OutMode",
"!=",
"\"",
"\"",
"\n",
"m",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"("... | // parse an os.FileMode out of the string, and let us know if it's an override or not... | [
"parse",
"an",
"os",
".",
"FileMode",
"out",
"of",
"the",
"string",
"and",
"let",
"us",
"know",
"if",
"it",
"s",
"an",
"override",
"or",
"not",
"..."
] | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/config.go#L52-L63 | train |
hairyhenderson/gomplate | random/random.go | StringBounds | func StringBounds(count int, lower, upper rune) (r string, err error) {
chars := filterRange(lower, upper)
if len(chars) == 0 {
return "", errors.Errorf("No printable codepoints found between U%#q and U%#q.", lower, upper)
}
return rndString(count, chars)
} | go | func StringBounds(count int, lower, upper rune) (r string, err error) {
chars := filterRange(lower, upper)
if len(chars) == 0 {
return "", errors.Errorf("No printable codepoints found between U%#q and U%#q.", lower, upper)
}
return rndString(count, chars)
} | [
"func",
"StringBounds",
"(",
"count",
"int",
",",
"lower",
",",
"upper",
"rune",
")",
"(",
"r",
"string",
",",
"err",
"error",
")",
"{",
"chars",
":=",
"filterRange",
"(",
"lower",
",",
"upper",
")",
"\n",
"if",
"len",
"(",
"chars",
")",
"==",
"0",... | // StringBounds returns a random string of characters with a codepoint
// between the lower and upper bounds. Only valid characters are returned
// and if a range is given where no valid characters can be found, an error
// will be returned. | [
"StringBounds",
"returns",
"a",
"random",
"string",
"of",
"characters",
"with",
"a",
"codepoint",
"between",
"the",
"lower",
"and",
"upper",
"bounds",
".",
"Only",
"valid",
"characters",
"are",
"returned",
"and",
"if",
"a",
"range",
"is",
"given",
"where",
"... | 20937becaa32cdec93e77a84ad04c73e9155b8e7 | https://github.com/hairyhenderson/gomplate/blob/20937becaa32cdec93e77a84ad04c73e9155b8e7/random/random.go#L38-L44 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.