nwo
stringlengths 7
28
| sha
stringlengths 40
40
| path
stringlengths 6
81
| language
stringclasses 1
value | identifier
stringlengths 1
29
| parameters
stringlengths 2
104
| argument_list
stringclasses 1
value | return_statement
stringclasses 1
value | docstring
stringlengths 0
765
| docstring_summary
stringlengths 0
735
| docstring_tokens
list | function
stringlengths 66
9.83k
| function_tokens
list | url
stringlengths 90
185
| score
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kubernetes/kubernetes
|
6a8a3682919652ae668c389ed2f60efb770eed03
|
pkg/volume/azure_dd/azure_mounter.go
|
go
|
GetAttributes
|
(m *azureDiskMounter) ()
|
[] |
func (m *azureDiskMounter) GetAttributes() volume.Attributes {
readOnly := false
volumeSource, _, err := getVolumeSource(m.spec)
if err != nil {
klog.Infof("azureDisk - mounter failed to get volume source for spec %s %v", m.spec.Name(), err)
} else if volumeSource.ReadOnly != nil {
readOnly = *volumeSource.ReadOnly
}
return volume.Attributes{
ReadOnly: readOnly,
Managed: !readOnly,
SupportsSELinux: true,
}
}
|
[
"func",
"(",
"m",
"*",
"azureDiskMounter",
")",
"GetAttributes",
"(",
")",
"volume",
".",
"Attributes",
"{",
"readOnly",
":=",
"false",
"\n",
"volumeSource",
",",
"_",
",",
"err",
":=",
"getVolumeSource",
"(",
"m",
".",
"spec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"klog",
".",
"Infof",
"(",
"\"",
"\"",
",",
"m",
".",
"spec",
".",
"Name",
"(",
")",
",",
"err",
")",
"\n",
"}",
"else",
"if",
"volumeSource",
".",
"ReadOnly",
"!=",
"nil",
"{",
"readOnly",
"=",
"*",
"volumeSource",
".",
"ReadOnly",
"\n",
"}",
"\n",
"return",
"volume",
".",
"Attributes",
"{",
"ReadOnly",
":",
"readOnly",
",",
"Managed",
":",
"!",
"readOnly",
",",
"SupportsSELinux",
":",
"true",
",",
"}",
"\n",
"}"
] |
https://github.com/kubernetes/kubernetes/blob/6a8a3682919652ae668c389ed2f60efb770eed03/pkg/volume/azure_dd/azure_mounter.go#L46-L59
| 0.999957
|
||||
moby/moby
|
e516af6e5636023e85335ed8d9d0d824349dd6ff
|
errdefs/http_helpers.go
|
go
|
GetHTTPErrorStatusCode
|
(err error)
|
// GetHTTPErrorStatusCode retrieves status code from error message.
|
GetHTTPErrorStatusCode retrieves status code from error message.
|
[
"GetHTTPErrorStatusCode",
"retrieves",
"status",
"code",
"from",
"error",
"message",
"."
] |
func GetHTTPErrorStatusCode(err error) int {
if err == nil {
logrus.WithFields(logrus.Fields{"error": err}).Error("unexpected HTTP error handling")
return http.StatusInternalServerError
}
var statusCode int
// Stop right there
// Are you sure you should be adding a new error class here? Do one of the existing ones work?
// Note that the below functions are already checking the error causal chain for matches.
switch {
case IsNotFound(err):
statusCode = http.StatusNotFound
case IsInvalidParameter(err):
statusCode = http.StatusBadRequest
case IsConflict(err):
statusCode = http.StatusConflict
case IsUnauthorized(err):
statusCode = http.StatusUnauthorized
case IsUnavailable(err):
statusCode = http.StatusServiceUnavailable
case IsForbidden(err):
statusCode = http.StatusForbidden
case IsNotModified(err):
statusCode = http.StatusNotModified
case IsNotImplemented(err):
statusCode = http.StatusNotImplemented
case IsSystem(err) || IsUnknown(err) || IsDataLoss(err) || IsDeadline(err) || IsCancelled(err):
statusCode = http.StatusInternalServerError
default:
statusCode = statusCodeFromGRPCError(err)
if statusCode != http.StatusInternalServerError {
return statusCode
}
statusCode = statusCodeFromDistributionError(err)
if statusCode != http.StatusInternalServerError {
return statusCode
}
if e, ok := err.(causer); ok {
return GetHTTPErrorStatusCode(e.Cause())
}
logrus.WithFields(logrus.Fields{
"module": "api",
"error_type": fmt.Sprintf("%T", err),
}).Debugf("FIXME: Got an API for which error does not match any expected type!!!: %+v", err)
}
if statusCode == 0 {
statusCode = http.StatusInternalServerError
}
return statusCode
}
|
[
"func",
"GetHTTPErrorStatusCode",
"(",
"err",
"error",
")",
"int",
"{",
"if",
"err",
"==",
"nil",
"{",
"logrus",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"err",
"}",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"http",
".",
"StatusInternalServerError",
"\n",
"}",
"\n\n",
"var",
"statusCode",
"int",
"\n\n",
"// Stop right there",
"// Are you sure you should be adding a new error class here? Do one of the existing ones work?",
"// Note that the below functions are already checking the error causal chain for matches.",
"switch",
"{",
"case",
"IsNotFound",
"(",
"err",
")",
":",
"statusCode",
"=",
"http",
".",
"StatusNotFound",
"\n",
"case",
"IsInvalidParameter",
"(",
"err",
")",
":",
"statusCode",
"=",
"http",
".",
"StatusBadRequest",
"\n",
"case",
"IsConflict",
"(",
"err",
")",
":",
"statusCode",
"=",
"http",
".",
"StatusConflict",
"\n",
"case",
"IsUnauthorized",
"(",
"err",
")",
":",
"statusCode",
"=",
"http",
".",
"StatusUnauthorized",
"\n",
"case",
"IsUnavailable",
"(",
"err",
")",
":",
"statusCode",
"=",
"http",
".",
"StatusServiceUnavailable",
"\n",
"case",
"IsForbidden",
"(",
"err",
")",
":",
"statusCode",
"=",
"http",
".",
"StatusForbidden",
"\n",
"case",
"IsNotModified",
"(",
"err",
")",
":",
"statusCode",
"=",
"http",
".",
"StatusNotModified",
"\n",
"case",
"IsNotImplemented",
"(",
"err",
")",
":",
"statusCode",
"=",
"http",
".",
"StatusNotImplemented",
"\n",
"case",
"IsSystem",
"(",
"err",
")",
"||",
"IsUnknown",
"(",
"err",
")",
"||",
"IsDataLoss",
"(",
"err",
")",
"||",
"IsDeadline",
"(",
"err",
")",
"||",
"IsCancelled",
"(",
"err",
")",
":",
"statusCode",
"=",
"http",
".",
"StatusInternalServerError",
"\n",
"default",
":",
"statusCode",
"=",
"statusCodeFromGRPCError",
"(",
"err",
")",
"\n",
"if",
"statusCode",
"!=",
"http",
".",
"StatusInternalServerError",
"{",
"return",
"statusCode",
"\n",
"}",
"\n",
"statusCode",
"=",
"statusCodeFromDistributionError",
"(",
"err",
")",
"\n",
"if",
"statusCode",
"!=",
"http",
".",
"StatusInternalServerError",
"{",
"return",
"statusCode",
"\n",
"}",
"\n",
"if",
"e",
",",
"ok",
":=",
"err",
".",
"(",
"causer",
")",
";",
"ok",
"{",
"return",
"GetHTTPErrorStatusCode",
"(",
"e",
".",
"Cause",
"(",
")",
")",
"\n",
"}",
"\n\n",
"logrus",
".",
"WithFields",
"(",
"logrus",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
",",
"}",
")",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"statusCode",
"==",
"0",
"{",
"statusCode",
"=",
"http",
".",
"StatusInternalServerError",
"\n",
"}",
"\n\n",
"return",
"statusCode",
"\n",
"}"
] |
https://github.com/moby/moby/blob/e516af6e5636023e85335ed8d9d0d824349dd6ff/errdefs/http_helpers.go#L14-L69
| 0.999672
|
||
ethereum/go-ethereum
|
b6c0234e0b5c9d459d1ed784c910f6348890d56b
|
consensus/ethash/algorithm.go
|
go
|
generateDatasetItem
|
(cache []uint32, index uint32, keccak512 hasher)
|
// generateDatasetItem combines data from 256 pseudorandomly selected cache nodes,
// and hashes that to compute a single dataset node.
|
generateDatasetItem combines data from 256 pseudorandomly selected cache nodes,
and hashes that to compute a single dataset node.
|
[
"generateDatasetItem",
"combines",
"data",
"from",
"256",
"pseudorandomly",
"selected",
"cache",
"nodes",
"and",
"hashes",
"that",
"to",
"compute",
"a",
"single",
"dataset",
"node",
"."
] |
func generateDatasetItem(cache []uint32, index uint32, keccak512 hasher) []byte {
// Calculate the number of theoretical rows (we use one buffer nonetheless)
rows := uint32(len(cache) / hashWords)
// Initialize the mix
mix := make([]byte, hashBytes)
binary.LittleEndian.PutUint32(mix, cache[(index%rows)*hashWords]^index)
for i := 1; i < hashWords; i++ {
binary.LittleEndian.PutUint32(mix[i*4:], cache[(index%rows)*hashWords+uint32(i)])
}
keccak512(mix, mix)
// Convert the mix to uint32s to avoid constant bit shifting
intMix := make([]uint32, hashWords)
for i := 0; i < len(intMix); i++ {
intMix[i] = binary.LittleEndian.Uint32(mix[i*4:])
}
// fnv it with a lot of random cache nodes based on index
for i := uint32(0); i < datasetParents; i++ {
parent := fnv(index^i, intMix[i%16]) % rows
fnvHash(intMix, cache[parent*hashWords:])
}
// Flatten the uint32 mix into a binary one and return
for i, val := range intMix {
binary.LittleEndian.PutUint32(mix[i*4:], val)
}
keccak512(mix, mix)
return mix
}
|
[
"func",
"generateDatasetItem",
"(",
"cache",
"[",
"]",
"uint32",
",",
"index",
"uint32",
",",
"keccak512",
"hasher",
")",
"[",
"]",
"byte",
"{",
"// Calculate the number of theoretical rows (we use one buffer nonetheless)",
"rows",
":=",
"uint32",
"(",
"len",
"(",
"cache",
")",
"/",
"hashWords",
")",
"\n\n",
"// Initialize the mix",
"mix",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"hashBytes",
")",
"\n\n",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"mix",
",",
"cache",
"[",
"(",
"index",
"%",
"rows",
")",
"*",
"hashWords",
"]",
"^",
"index",
")",
"\n",
"for",
"i",
":=",
"1",
";",
"i",
"<",
"hashWords",
";",
"i",
"++",
"{",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"mix",
"[",
"i",
"*",
"4",
":",
"]",
",",
"cache",
"[",
"(",
"index",
"%",
"rows",
")",
"*",
"hashWords",
"+",
"uint32",
"(",
"i",
")",
"]",
")",
"\n",
"}",
"\n",
"keccak512",
"(",
"mix",
",",
"mix",
")",
"\n\n",
"// Convert the mix to uint32s to avoid constant bit shifting",
"intMix",
":=",
"make",
"(",
"[",
"]",
"uint32",
",",
"hashWords",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"intMix",
")",
";",
"i",
"++",
"{",
"intMix",
"[",
"i",
"]",
"=",
"binary",
".",
"LittleEndian",
".",
"Uint32",
"(",
"mix",
"[",
"i",
"*",
"4",
":",
"]",
")",
"\n",
"}",
"\n",
"// fnv it with a lot of random cache nodes based on index",
"for",
"i",
":=",
"uint32",
"(",
"0",
")",
";",
"i",
"<",
"datasetParents",
";",
"i",
"++",
"{",
"parent",
":=",
"fnv",
"(",
"index",
"^",
"i",
",",
"intMix",
"[",
"i",
"%",
"16",
"]",
")",
"%",
"rows",
"\n",
"fnvHash",
"(",
"intMix",
",",
"cache",
"[",
"parent",
"*",
"hashWords",
":",
"]",
")",
"\n",
"}",
"\n",
"// Flatten the uint32 mix into a binary one and return",
"for",
"i",
",",
"val",
":=",
"range",
"intMix",
"{",
"binary",
".",
"LittleEndian",
".",
"PutUint32",
"(",
"mix",
"[",
"i",
"*",
"4",
":",
"]",
",",
"val",
")",
"\n",
"}",
"\n",
"keccak512",
"(",
"mix",
",",
"mix",
")",
"\n",
"return",
"mix",
"\n",
"}"
] |
https://github.com/ethereum/go-ethereum/blob/b6c0234e0b5c9d459d1ed784c910f6348890d56b/consensus/ethash/algorithm.go#L234-L263
| 0.999608
|
||
gohugoio/hugo
|
f94a388ad319eaa6b2d9b32658c1257e9ca8ce4c
|
releaser/releaser.go
|
go
|
replaceInFile
|
(r *ReleaseHandler) (filename string, oldNew ...string)
|
[] |
func (r *ReleaseHandler) replaceInFile(filename string, oldNew ...string) error {
fullFilename := hugoFilepath(filename)
fi, err := os.Stat(fullFilename)
if err != nil {
return err
}
if r.try {
fmt.Printf("Replace in %q: %q\n", filename, oldNew)
return nil
}
b, err := ioutil.ReadFile(fullFilename)
if err != nil {
return err
}
newContent := string(b)
for i := 0; i < len(oldNew); i += 2 {
re := regexp.MustCompile(oldNew[i])
newContent = re.ReplaceAllString(newContent, oldNew[i+1])
}
return ioutil.WriteFile(fullFilename, []byte(newContent), fi.Mode())
}
|
[
"func",
"(",
"r",
"*",
"ReleaseHandler",
")",
"replaceInFile",
"(",
"filename",
"string",
",",
"oldNew",
"...",
"string",
")",
"error",
"{",
"fullFilename",
":=",
"hugoFilepath",
"(",
"filename",
")",
"\n",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"fullFilename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"r",
".",
"try",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"filename",
",",
"oldNew",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"fullFilename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"newContent",
":=",
"string",
"(",
"b",
")",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"oldNew",
")",
";",
"i",
"+=",
"2",
"{",
"re",
":=",
"regexp",
".",
"MustCompile",
"(",
"oldNew",
"[",
"i",
"]",
")",
"\n",
"newContent",
"=",
"re",
".",
"ReplaceAllString",
"(",
"newContent",
",",
"oldNew",
"[",
"i",
"+",
"1",
"]",
")",
"\n",
"}",
"\n\n",
"return",
"ioutil",
".",
"WriteFile",
"(",
"fullFilename",
",",
"[",
"]",
"byte",
"(",
"newContent",
")",
",",
"fi",
".",
"Mode",
"(",
")",
")",
"\n",
"}"
] |
https://github.com/gohugoio/hugo/blob/f94a388ad319eaa6b2d9b32658c1257e9ca8ce4c/releaser/releaser.go#L304-L328
| 0.999584
|
||||
hyperledger/fabric
|
49f496925df1e66198d7ec794849536c9f8b104b
|
bccsp/sw/aes.go
|
go
|
aesCBCEncryptWithRand
|
(prng io.Reader, key, s []byte)
|
[] |
func aesCBCEncryptWithRand(prng io.Reader, key, s []byte) ([]byte, error) {
if len(s)%aes.BlockSize != 0 {
return nil, errors.New("Invalid plaintext. It must be a multiple of the block size")
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, aes.BlockSize+len(s))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(prng, iv); err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], s)
return ciphertext, nil
}
|
[
"func",
"aesCBCEncryptWithRand",
"(",
"prng",
"io",
".",
"Reader",
",",
"key",
",",
"s",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"s",
")",
"%",
"aes",
".",
"BlockSize",
"!=",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"block",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"ciphertext",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"aes",
".",
"BlockSize",
"+",
"len",
"(",
"s",
")",
")",
"\n",
"iv",
":=",
"ciphertext",
"[",
":",
"aes",
".",
"BlockSize",
"]",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"prng",
",",
"iv",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"mode",
":=",
"cipher",
".",
"NewCBCEncrypter",
"(",
"block",
",",
"iv",
")",
"\n",
"mode",
".",
"CryptBlocks",
"(",
"ciphertext",
"[",
"aes",
".",
"BlockSize",
":",
"]",
",",
"s",
")",
"\n\n",
"return",
"ciphertext",
",",
"nil",
"\n",
"}"
] |
https://github.com/hyperledger/fabric/blob/49f496925df1e66198d7ec794849536c9f8b104b/bccsp/sw/aes.go#L78-L98
| 0.999299
|
||||
hyperledger/fabric
|
49f496925df1e66198d7ec794849536c9f8b104b
|
gossip/privdata/reconcile.go
|
go
|
groupRwsetByBlock
|
(r *Reconciler) (elements []*gossip2.PvtDataElement)
|
// return a mapping from block num to rwsetByKeys
|
return a mapping from block num to rwsetByKeys
|
[
"return",
"a",
"mapping",
"from",
"block",
"num",
"to",
"rwsetByKeys"
] |
func (r *Reconciler) groupRwsetByBlock(elements []*gossip2.PvtDataElement) map[uint64]rwsetByKeys {
rwSetByBlockByKeys := make(map[uint64]rwsetByKeys) // map from block num to rwsetByKeys
// Iterate over data fetched from peers
for _, element := range elements {
dig := element.Digest
if _, exists := rwSetByBlockByKeys[dig.BlockSeq]; !exists {
rwSetByBlockByKeys[dig.BlockSeq] = make(map[rwSetKey][]byte)
}
for _, rws := range element.Payload {
hash := hex.EncodeToString(util2.ComputeSHA256(rws))
key := rwSetKey{
txID: dig.TxId,
namespace: dig.Namespace,
collection: dig.Collection,
seqInBlock: dig.SeqInBlock,
hash: hash,
}
rwSetByBlockByKeys[dig.BlockSeq][key] = rws
}
}
return rwSetByBlockByKeys
}
|
[
"func",
"(",
"r",
"*",
"Reconciler",
")",
"groupRwsetByBlock",
"(",
"elements",
"[",
"]",
"*",
"gossip2",
".",
"PvtDataElement",
")",
"map",
"[",
"uint64",
"]",
"rwsetByKeys",
"{",
"rwSetByBlockByKeys",
":=",
"make",
"(",
"map",
"[",
"uint64",
"]",
"rwsetByKeys",
")",
"// map from block num to rwsetByKeys",
"\n\n",
"// Iterate over data fetched from peers",
"for",
"_",
",",
"element",
":=",
"range",
"elements",
"{",
"dig",
":=",
"element",
".",
"Digest",
"\n",
"if",
"_",
",",
"exists",
":=",
"rwSetByBlockByKeys",
"[",
"dig",
".",
"BlockSeq",
"]",
";",
"!",
"exists",
"{",
"rwSetByBlockByKeys",
"[",
"dig",
".",
"BlockSeq",
"]",
"=",
"make",
"(",
"map",
"[",
"rwSetKey",
"]",
"[",
"]",
"byte",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"rws",
":=",
"range",
"element",
".",
"Payload",
"{",
"hash",
":=",
"hex",
".",
"EncodeToString",
"(",
"util2",
".",
"ComputeSHA256",
"(",
"rws",
")",
")",
"\n",
"key",
":=",
"rwSetKey",
"{",
"txID",
":",
"dig",
".",
"TxId",
",",
"namespace",
":",
"dig",
".",
"Namespace",
",",
"collection",
":",
"dig",
".",
"Collection",
",",
"seqInBlock",
":",
"dig",
".",
"SeqInBlock",
",",
"hash",
":",
"hash",
",",
"}",
"\n",
"rwSetByBlockByKeys",
"[",
"dig",
".",
"BlockSeq",
"]",
"[",
"key",
"]",
"=",
"rws",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"rwSetByBlockByKeys",
"\n",
"}"
] |
https://github.com/hyperledger/fabric/blob/49f496925df1e66198d7ec794849536c9f8b104b/gossip/privdata/reconcile.go#L289-L311
| 0.999299
|
||
gogs/gogs
|
4f9c5b60c56606e709c4da2d1587aa7096ae24da
|
pkg/template/template.go
|
go
|
Str2HTML
|
(raw string)
|
[] |
func Str2HTML(raw string) template.HTML {
return template.HTML(markup.Sanitize(raw))
}
|
[
"func",
"Str2HTML",
"(",
"raw",
"string",
")",
"template",
".",
"HTML",
"{",
"return",
"template",
".",
"HTML",
"(",
"markup",
".",
"Sanitize",
"(",
"raw",
")",
")",
"\n",
"}"
] |
https://github.com/gogs/gogs/blob/4f9c5b60c56606e709c4da2d1587aa7096ae24da/pkg/template/template.go#L130-L132
| 0.999194
|
||||
hashicorp/vault
|
7e96d5c2b53ee9e22439f3bc0cb366d7e92f949b
|
sdk/physical/file/file.go
|
go
|
expandPath
|
(b *FileBackend) (k string)
|
[] |
func (b *FileBackend) expandPath(k string) (string, string) {
path := filepath.Join(b.path, k)
key := filepath.Base(path)
path = filepath.Dir(path)
return path, "_" + key
}
|
[
"func",
"(",
"b",
"*",
"FileBackend",
")",
"expandPath",
"(",
"k",
"string",
")",
"(",
"string",
",",
"string",
")",
"{",
"path",
":=",
"filepath",
".",
"Join",
"(",
"b",
".",
"path",
",",
"k",
")",
"\n",
"key",
":=",
"filepath",
".",
"Base",
"(",
"path",
")",
"\n",
"path",
"=",
"filepath",
".",
"Dir",
"(",
"path",
")",
"\n",
"return",
"path",
",",
"\"",
"\"",
"+",
"key",
"\n",
"}"
] |
https://github.com/hashicorp/vault/blob/7e96d5c2b53ee9e22439f3bc0cb366d7e92f949b/sdk/physical/file/file.go#L350-L355
| 0.997655
|
||||
openshift/origin
|
00a7323a2f454c2ca26ab58e1f487dc81e30e19c
|
pkg/oauthserver/oauth/external/handler.go
|
go
|
encodeState
|
(values url.Values)
|
// URL-encode, then base-64 encode for OAuth providers that don't do a good job of treating the state param like an opaque value
|
URL-encode, then base-64 encode for OAuth providers that don't do a good job of treating the state param like an opaque value
|
[
"URL",
"-",
"encode",
"then",
"base",
"-",
"64",
"encode",
"for",
"OAuth",
"providers",
"that",
"don",
"t",
"do",
"a",
"good",
"job",
"of",
"treating",
"the",
"state",
"param",
"like",
"an",
"opaque",
"value"
] |
func encodeState(values url.Values) string {
return base64.URLEncoding.EncodeToString([]byte(values.Encode()))
}
|
[
"func",
"encodeState",
"(",
"values",
"url",
".",
"Values",
")",
"string",
"{",
"return",
"base64",
".",
"URLEncoding",
".",
"EncodeToString",
"(",
"[",
"]",
"byte",
"(",
"values",
".",
"Encode",
"(",
")",
")",
")",
"\n",
"}"
] |
https://github.com/openshift/origin/blob/00a7323a2f454c2ca26ab58e1f487dc81e30e19c/pkg/oauthserver/oauth/external/handler.go#L339-L341
| 0.997079
|
||
openshift/origin
|
00a7323a2f454c2ca26ab58e1f487dc81e30e19c
|
pkg/security/mcs/label.go
|
go
|
Size
|
(r *Range) ()
|
[] |
func (r *Range) Size() uint64 {
return binomial(r.n, uint(r.k))
}
|
[
"func",
"(",
"r",
"*",
"Range",
")",
"Size",
"(",
")",
"uint64",
"{",
"return",
"binomial",
"(",
"r",
".",
"n",
",",
"uint",
"(",
"r",
".",
"k",
")",
")",
"\n",
"}"
] |
https://github.com/openshift/origin/blob/00a7323a2f454c2ca26ab58e1f487dc81e30e19c/pkg/security/mcs/label.go#L202-L204
| 0.997079
|
||||
kataras/iris
|
6aafc0b9d5e97d0c52e325d8c4b4d23d61eb3f9d
|
_examples/tutorial/caddy/server1/main.go
|
go
|
Get
|
(c *Controller) ()
|
// Get handles GET http://localhost:9091
|
Get handles GET http://localhost:9091
|
[
"Get",
"handles",
"GET",
"http",
":",
"//",
"localhost",
":",
"9091"
] |
func (c *Controller) Get() mvc.View {
return mvc.View{
Name: "index.html",
Data: iris.Map{
"Layout": c.Layout,
"Message": "Welcome to my website!",
},
}
}
|
[
"func",
"(",
"c",
"*",
"Controller",
")",
"Get",
"(",
")",
"mvc",
".",
"View",
"{",
"return",
"mvc",
".",
"View",
"{",
"Name",
":",
"\"",
"\"",
",",
"Data",
":",
"iris",
".",
"Map",
"{",
"\"",
"\"",
":",
"c",
".",
"Layout",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"}",
",",
"}",
"\n",
"}"
] |
https://github.com/kataras/iris/blob/6aafc0b9d5e97d0c52e325d8c4b4d23d61eb3f9d/_examples/tutorial/caddy/server1/main.go#L41-L49
| 0.995945
|
||
kataras/iris
|
6aafc0b9d5e97d0c52e325d8c4b4d23d61eb3f9d
|
context/context.go
|
go
|
HTML
|
(ctx *context) (htmlContents string)
|
// HTML writes out a string as text/html.
|
HTML writes out a string as text/html.
|
[
"HTML",
"writes",
"out",
"a",
"string",
"as",
"text",
"/",
"html",
"."
] |
func (ctx *context) HTML(htmlContents string) (int, error) {
ctx.ContentType(ContentHTMLHeaderValue)
return ctx.writer.WriteString(htmlContents)
}
|
[
"func",
"(",
"ctx",
"*",
"context",
")",
"HTML",
"(",
"htmlContents",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"ctx",
".",
"ContentType",
"(",
"ContentHTMLHeaderValue",
")",
"\n",
"return",
"ctx",
".",
"writer",
".",
"WriteString",
"(",
"htmlContents",
")",
"\n",
"}"
] |
https://github.com/kataras/iris/blob/6aafc0b9d5e97d0c52e325d8c4b4d23d61eb3f9d/context/context.go#L2767-L2770
| 0.995945
|
||
minio/minio
|
4b858b562a0887e10bfd0414dc87e68f1af31c3a
|
cmd/healthcheck-handler.go
|
go
|
goroutineCountCheck
|
(threshold int)
|
// checks threshold against total number of go-routines in the system and throws error if
// more than threshold go-routines are running.
|
checks threshold against total number of go-routines in the system and throws error if
more than threshold go-routines are running.
|
[
"checks",
"threshold",
"against",
"total",
"number",
"of",
"go",
"-",
"routines",
"in",
"the",
"system",
"and",
"throws",
"error",
"if",
"more",
"than",
"threshold",
"go",
"-",
"routines",
"are",
"running",
"."
] |
func goroutineCountCheck(threshold int) error {
count := runtime.NumGoroutine()
if count > threshold {
return fmt.Errorf("too many goroutines (%d > %d)", count, threshold)
}
return nil
}
|
[
"func",
"goroutineCountCheck",
"(",
"threshold",
"int",
")",
"error",
"{",
"count",
":=",
"runtime",
".",
"NumGoroutine",
"(",
")",
"\n",
"if",
"count",
">",
"threshold",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"count",
",",
"threshold",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
https://github.com/minio/minio/blob/4b858b562a0887e10bfd0414dc87e68f1af31c3a/cmd/healthcheck-handler.go#L102-L108
| 0.994907
|
||
labstack/echo
|
5d2c33ad5dbb78540a56dd08d09d91f991bc3156
|
context.go
|
go
|
HTML
|
(c *context) (code int, html string)
|
[] |
func (c *context) HTML(code int, html string) (err error) {
return c.HTMLBlob(code, []byte(html))
}
|
[
"func",
"(",
"c",
"*",
"context",
")",
"HTML",
"(",
"code",
"int",
",",
"html",
"string",
")",
"(",
"err",
"error",
")",
"{",
"return",
"c",
".",
"HTMLBlob",
"(",
"code",
",",
"[",
"]",
"byte",
"(",
"html",
")",
")",
"\n",
"}"
] |
https://github.com/labstack/echo/blob/5d2c33ad5dbb78540a56dd08d09d91f991bc3156/context.go#L402-L404
| 0.993985
|
||||
containerd/containerd
|
a17c8095716415cebb1157a27db5fccace56b0fc
|
windows/task.go
|
go
|
getProcess
|
(t *task) (id string)
|
[] |
func (t *task) getProcess(id string) *process {
t.Lock()
p := t.processes[id]
t.Unlock()
return p
}
|
[
"func",
"(",
"t",
"*",
"task",
")",
"getProcess",
"(",
"id",
"string",
")",
"*",
"process",
"{",
"t",
".",
"Lock",
"(",
")",
"\n",
"p",
":=",
"t",
".",
"processes",
"[",
"id",
"]",
"\n",
"t",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"p",
"\n",
"}"
] |
https://github.com/containerd/containerd/blob/a17c8095716415cebb1157a27db5fccace56b0fc/windows/task.go#L404-L410
| 0.993772
|
||||
containerd/containerd
|
a17c8095716415cebb1157a27db5fccace56b0fc
|
runtime/v2/runhcs/service.go
|
go
|
getProcess
|
(s *service) (id, execID string)
|
// getProcess attempts to get a process by id.
// The caller MUST NOT have locked s.mu previous to calling this function.
|
getProcess attempts to get a process by id.
The caller MUST NOT have locked s.mu previous to calling this function.
|
[
"getProcess",
"attempts",
"to",
"get",
"a",
"process",
"by",
"id",
".",
"The",
"caller",
"MUST",
"NOT",
"have",
"locked",
"s",
".",
"mu",
"previous",
"to",
"calling",
"this",
"function",
"."
] |
func (s *service) getProcess(id, execID string) (*process, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.getProcessLocked(id, execID)
}
|
[
"func",
"(",
"s",
"*",
"service",
")",
"getProcess",
"(",
"id",
",",
"execID",
"string",
")",
"(",
"*",
"process",
",",
"error",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"s",
".",
"getProcessLocked",
"(",
"id",
",",
"execID",
")",
"\n",
"}"
] |
https://github.com/containerd/containerd/blob/a17c8095716415cebb1157a27db5fccace56b0fc/runtime/v2/runhcs/service.go#L178-L183
| 0.993772
|
||
ory/hydra
|
67c246c177446daab64be00ba82b3aea1a546570
|
sdk/go/hydra/client/admin/get_json_web_key_parameters.go
|
go
|
WithHTTPClient
|
(o *GetJSONWebKeyParams) (client *http.Client)
|
// WithHTTPClient adds the HTTPClient to the get Json web key params
|
WithHTTPClient adds the HTTPClient to the get Json web key params
|
[
"WithHTTPClient",
"adds",
"the",
"HTTPClient",
"to",
"the",
"get",
"Json",
"web",
"key",
"params"
] |
func (o *GetJSONWebKeyParams) WithHTTPClient(client *http.Client) *GetJSONWebKeyParams {
o.SetHTTPClient(client)
return o
}
|
[
"func",
"(",
"o",
"*",
"GetJSONWebKeyParams",
")",
"WithHTTPClient",
"(",
"client",
"*",
"http",
".",
"Client",
")",
"*",
"GetJSONWebKeyParams",
"{",
"o",
".",
"SetHTTPClient",
"(",
"client",
")",
"\n",
"return",
"o",
"\n",
"}"
] |
https://github.com/ory/hydra/blob/67c246c177446daab64be00ba82b3aea1a546570/sdk/go/hydra/client/admin/get_json_web_key_parameters.go#L103-L106
| 0.992936
|
||
keybase/client
|
b352622cd8cc94798cfacbcb56ada203c18e519e
|
go/kbfs/libhttpserver/content_type_utils.go
|
go
|
calculateOverride
|
(w *contentTypeOverridingResponseWriter) (
mimeType string)
|
[] |
func (w *contentTypeOverridingResponseWriter) calculateOverride(
mimeType string) (newMimeType, disposition string) {
// Send text/plain for all HTML and JS files to avoid them being executed
// by the frontend WebView.
ty := strings.ToLower(mimeType)
switch {
// First anything textual as text/plain.
// Javascript is set to plain text by additionalMimeTypes map.
// If text/something-dangerous would get here, we set it to plaintext.
// If application/javascript somehow gets here it would be handled safely
// by the default handler below.
case strings.HasPrefix(ty, "text/"):
return textPlainUtf8, "inline"
// Pass multimedia types through, and pdf too.
// Some types get special handling here and are not shown inline (e.g. SVG).
case strings.HasPrefix(ty, "audio/") ||
strings.HasPrefix(ty, "image/") ||
strings.HasPrefix(ty, "video/") ||
ty == "application/pdf":
return ty, getDisposition(true, ty)
// Otherwise default to text + attachment.
// This is safe for all files.
default:
return textPlainUtf8, "attachment"
}
}
|
[
"func",
"(",
"w",
"*",
"contentTypeOverridingResponseWriter",
")",
"calculateOverride",
"(",
"mimeType",
"string",
")",
"(",
"newMimeType",
",",
"disposition",
"string",
")",
"{",
"// Send text/plain for all HTML and JS files to avoid them being executed",
"// by the frontend WebView.",
"ty",
":=",
"strings",
".",
"ToLower",
"(",
"mimeType",
")",
"\n",
"switch",
"{",
"// First anything textual as text/plain.",
"// Javascript is set to plain text by additionalMimeTypes map.",
"// If text/something-dangerous would get here, we set it to plaintext.",
"// If application/javascript somehow gets here it would be handled safely",
"// by the default handler below.",
"case",
"strings",
".",
"HasPrefix",
"(",
"ty",
",",
"\"",
"\"",
")",
":",
"return",
"textPlainUtf8",
",",
"\"",
"\"",
"\n",
"// Pass multimedia types through, and pdf too.",
"// Some types get special handling here and are not shown inline (e.g. SVG).",
"case",
"strings",
".",
"HasPrefix",
"(",
"ty",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"HasPrefix",
"(",
"ty",
",",
"\"",
"\"",
")",
"||",
"strings",
".",
"HasPrefix",
"(",
"ty",
",",
"\"",
"\"",
")",
"||",
"ty",
"==",
"\"",
"\"",
":",
"return",
"ty",
",",
"getDisposition",
"(",
"true",
",",
"ty",
")",
"\n",
"// Otherwise default to text + attachment.",
"// This is safe for all files.",
"default",
":",
"return",
"textPlainUtf8",
",",
"\"",
"\"",
"\n",
"}",
"\n",
"}"
] |
https://github.com/keybase/client/blob/b352622cd8cc94798cfacbcb56ada203c18e519e/go/kbfs/libhttpserver/content_type_utils.go#L54-L79
| 0.992098
|
||||
keybase/client
|
b352622cd8cc94798cfacbcb56ada203c18e519e
|
go/protocol/keybase1/home.go
|
go
|
T
|
(o *HomeScreenItemData) ()
|
[] |
func (o *HomeScreenItemData) T() (ret HomeScreenItemType, err error) {
switch o.T__ {
case HomeScreenItemType_TODO:
if o.Todo__ == nil {
err = errors.New("unexpected nil value for Todo__")
return ret, err
}
case HomeScreenItemType_PEOPLE:
if o.People__ == nil {
err = errors.New("unexpected nil value for People__")
return ret, err
}
case HomeScreenItemType_ANNOUNCEMENT:
if o.Announcement__ == nil {
err = errors.New("unexpected nil value for Announcement__")
return ret, err
}
}
return o.T__, nil
}
|
[
"func",
"(",
"o",
"*",
"HomeScreenItemData",
")",
"T",
"(",
")",
"(",
"ret",
"HomeScreenItemType",
",",
"err",
"error",
")",
"{",
"switch",
"o",
".",
"T__",
"{",
"case",
"HomeScreenItemType_TODO",
":",
"if",
"o",
".",
"Todo__",
"==",
"nil",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"ret",
",",
"err",
"\n",
"}",
"\n",
"case",
"HomeScreenItemType_PEOPLE",
":",
"if",
"o",
".",
"People__",
"==",
"nil",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"ret",
",",
"err",
"\n",
"}",
"\n",
"case",
"HomeScreenItemType_ANNOUNCEMENT",
":",
"if",
"o",
".",
"Announcement__",
"==",
"nil",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"ret",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"o",
".",
"T__",
",",
"nil",
"\n",
"}"
] |
https://github.com/keybase/client/blob/b352622cd8cc94798cfacbcb56ada203c18e519e/go/protocol/keybase1/home.go#L54-L73
| 0.992098
|
||||
sjwhitworth/golearn
|
82e59c89f5020c45292c68472908f2150a87422e
|
examples/trees/trees.go
|
go
|
main
|
()
|
[] |
func main() {
var tree base.Classifier
rand.Seed(44111342)
// Load in the iris dataset
iris, err := base.ParseCSVToInstances("../datasets/iris_headers.csv", true)
if err != nil {
panic(err)
}
// Discretise the iris dataset with Chi-Merge
filt := filters.NewChiMergeFilter(iris, 0.999)
for _, a := range base.NonClassFloatAttributes(iris) {
filt.AddAttribute(a)
}
filt.Train()
irisf := base.NewLazilyFilteredInstances(iris, filt)
// Create a 60-40 training-test split
trainData, testData := base.InstancesTrainTestSplit(irisf, 0.60)
//
// First up, use ID3
//
tree = trees.NewID3DecisionTree(0.6)
// (Parameter controls train-prune split.)
// Train the ID3 tree
err = tree.Fit(trainData)
if err != nil {
panic(err)
}
// Generate predictions
predictions, err := tree.Predict(testData)
if err != nil {
panic(err)
}
// Evaluate
fmt.Println("ID3 Performance (information gain)")
cf, err := evaluation.GetConfusionMatrix(testData, predictions)
if err != nil {
panic(fmt.Sprintf("Unable to get confusion matrix: %s", err.Error()))
}
fmt.Println(evaluation.GetSummary(cf))
tree = trees.NewID3DecisionTreeFromRule(0.6, new(trees.InformationGainRatioRuleGenerator))
// (Parameter controls train-prune split.)
// Train the ID3 tree
err = tree.Fit(trainData)
if err != nil {
panic(err)
}
// Generate predictions
predictions, err = tree.Predict(testData)
if err != nil {
panic(err)
}
// Evaluate
fmt.Println("ID3 Performance (information gain ratio)")
cf, err = evaluation.GetConfusionMatrix(testData, predictions)
if err != nil {
panic(fmt.Sprintf("Unable to get confusion matrix: %s", err.Error()))
}
fmt.Println(evaluation.GetSummary(cf))
tree = trees.NewID3DecisionTreeFromRule(0.6, new(trees.GiniCoefficientRuleGenerator))
// (Parameter controls train-prune split.)
// Train the ID3 tree
err = tree.Fit(trainData)
if err != nil {
panic(err)
}
// Generate predictions
predictions, err = tree.Predict(testData)
if err != nil {
panic(err)
}
// Evaluate
fmt.Println("ID3 Performance (gini index generator)")
cf, err = evaluation.GetConfusionMatrix(testData, predictions)
if err != nil {
panic(fmt.Sprintf("Unable to get confusion matrix: %s", err.Error()))
}
fmt.Println(evaluation.GetSummary(cf))
//
// Next up, Random Trees
//
// Consider two randomly-chosen attributes
tree = trees.NewRandomTree(2)
err = tree.Fit(trainData)
if err != nil {
panic(err)
}
predictions, err = tree.Predict(testData)
if err != nil {
panic(err)
}
fmt.Println("RandomTree Performance")
cf, err = evaluation.GetConfusionMatrix(testData, predictions)
if err != nil {
panic(fmt.Sprintf("Unable to get confusion matrix: %s", err.Error()))
}
fmt.Println(evaluation.GetSummary(cf))
//
// Finally, Random Forests
//
tree = ensemble.NewRandomForest(70, 3)
err = tree.Fit(trainData)
if err != nil {
panic(err)
}
predictions, err = tree.Predict(testData)
if err != nil {
panic(err)
}
fmt.Println("RandomForest Performance")
cf, err = evaluation.GetConfusionMatrix(testData, predictions)
if err != nil {
panic(fmt.Sprintf("Unable to get confusion matrix: %s", err.Error()))
}
fmt.Println(evaluation.GetSummary(cf))
}
|
[
"func",
"main",
"(",
")",
"{",
"var",
"tree",
"base",
".",
"Classifier",
"\n\n",
"rand",
".",
"Seed",
"(",
"44111342",
")",
"\n\n",
"// Load in the iris dataset",
"iris",
",",
"err",
":=",
"base",
".",
"ParseCSVToInstances",
"(",
"\"",
"\"",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Discretise the iris dataset with Chi-Merge",
"filt",
":=",
"filters",
".",
"NewChiMergeFilter",
"(",
"iris",
",",
"0.999",
")",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"base",
".",
"NonClassFloatAttributes",
"(",
"iris",
")",
"{",
"filt",
".",
"AddAttribute",
"(",
"a",
")",
"\n",
"}",
"\n",
"filt",
".",
"Train",
"(",
")",
"\n",
"irisf",
":=",
"base",
".",
"NewLazilyFilteredInstances",
"(",
"iris",
",",
"filt",
")",
"\n\n",
"// Create a 60-40 training-test split",
"trainData",
",",
"testData",
":=",
"base",
".",
"InstancesTrainTestSplit",
"(",
"irisf",
",",
"0.60",
")",
"\n\n",
"//",
"// First up, use ID3",
"//",
"tree",
"=",
"trees",
".",
"NewID3DecisionTree",
"(",
"0.6",
")",
"\n",
"// (Parameter controls train-prune split.)",
"// Train the ID3 tree",
"err",
"=",
"tree",
".",
"Fit",
"(",
"trainData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Generate predictions",
"predictions",
",",
"err",
":=",
"tree",
".",
"Predict",
"(",
"testData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Evaluate",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"cf",
",",
"err",
":=",
"evaluation",
".",
"GetConfusionMatrix",
"(",
"testData",
",",
"predictions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"evaluation",
".",
"GetSummary",
"(",
"cf",
")",
")",
"\n\n",
"tree",
"=",
"trees",
".",
"NewID3DecisionTreeFromRule",
"(",
"0.6",
",",
"new",
"(",
"trees",
".",
"InformationGainRatioRuleGenerator",
")",
")",
"\n",
"// (Parameter controls train-prune split.)",
"// Train the ID3 tree",
"err",
"=",
"tree",
".",
"Fit",
"(",
"trainData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Generate predictions",
"predictions",
",",
"err",
"=",
"tree",
".",
"Predict",
"(",
"testData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Evaluate",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"cf",
",",
"err",
"=",
"evaluation",
".",
"GetConfusionMatrix",
"(",
"testData",
",",
"predictions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"evaluation",
".",
"GetSummary",
"(",
"cf",
")",
")",
"\n\n",
"tree",
"=",
"trees",
".",
"NewID3DecisionTreeFromRule",
"(",
"0.6",
",",
"new",
"(",
"trees",
".",
"GiniCoefficientRuleGenerator",
")",
")",
"\n",
"// (Parameter controls train-prune split.)",
"// Train the ID3 tree",
"err",
"=",
"tree",
".",
"Fit",
"(",
"trainData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Generate predictions",
"predictions",
",",
"err",
"=",
"tree",
".",
"Predict",
"(",
"testData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"// Evaluate",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"cf",
",",
"err",
"=",
"evaluation",
".",
"GetConfusionMatrix",
"(",
"testData",
",",
"predictions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"evaluation",
".",
"GetSummary",
"(",
"cf",
")",
")",
"\n",
"//",
"// Next up, Random Trees",
"//",
"// Consider two randomly-chosen attributes",
"tree",
"=",
"trees",
".",
"NewRandomTree",
"(",
"2",
")",
"\n",
"err",
"=",
"tree",
".",
"Fit",
"(",
"trainData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"predictions",
",",
"err",
"=",
"tree",
".",
"Predict",
"(",
"testData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"cf",
",",
"err",
"=",
"evaluation",
".",
"GetConfusionMatrix",
"(",
"testData",
",",
"predictions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"evaluation",
".",
"GetSummary",
"(",
"cf",
")",
")",
"\n\n",
"//",
"// Finally, Random Forests",
"//",
"tree",
"=",
"ensemble",
".",
"NewRandomForest",
"(",
"70",
",",
"3",
")",
"\n",
"err",
"=",
"tree",
".",
"Fit",
"(",
"trainData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"predictions",
",",
"err",
"=",
"tree",
".",
"Predict",
"(",
"testData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"cf",
",",
"err",
"=",
"evaluation",
".",
"GetConfusionMatrix",
"(",
"testData",
",",
"predictions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"evaluation",
".",
"GetSummary",
"(",
"cf",
")",
")",
"\n",
"}"
] |
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/examples/trees/trees.go#L15-L148
| 0.991265
|
||||
aws/aws-sdk-go
|
6c4060605190fc6f00d63cd4e5572faa9f07345d
|
service/cloudfront/api.go
|
go
|
SetResponseCode
|
(s *CustomErrorResponse) (v string)
|
// SetResponseCode sets the ResponseCode field's value.
|
SetResponseCode sets the ResponseCode field's value.
|
[
"SetResponseCode",
"sets",
"the",
"ResponseCode",
"field",
"s",
"value",
"."
] |
func (s *CustomErrorResponse) SetResponseCode(v string) *CustomErrorResponse {
s.ResponseCode = &v
return s
}
|
[
"func",
"(",
"s",
"*",
"CustomErrorResponse",
")",
"SetResponseCode",
"(",
"v",
"string",
")",
"*",
"CustomErrorResponse",
"{",
"s",
".",
"ResponseCode",
"=",
"&",
"v",
"\n",
"return",
"s",
"\n",
"}"
] |
https://github.com/aws/aws-sdk-go/blob/6c4060605190fc6f00d63cd4e5572faa9f07345d/service/cloudfront/api.go#L6650-L6653
| 0.991152
|
||
aws/aws-sdk-go
|
6c4060605190fc6f00d63cd4e5572faa9f07345d
|
service/cloudfront/api.go
|
go
|
SetItems
|
(s *CustomErrorResponses) (v []*CustomErrorResponse)
|
// SetItems sets the Items field's value.
|
SetItems sets the Items field's value.
|
[
"SetItems",
"sets",
"the",
"Items",
"field",
"s",
"value",
"."
] |
func (s *CustomErrorResponses) SetItems(v []*CustomErrorResponse) *CustomErrorResponses {
s.Items = v
return s
}
|
[
"func",
"(",
"s",
"*",
"CustomErrorResponses",
")",
"SetItems",
"(",
"v",
"[",
"]",
"*",
"CustomErrorResponse",
")",
"*",
"CustomErrorResponses",
"{",
"s",
".",
"Items",
"=",
"v",
"\n",
"return",
"s",
"\n",
"}"
] |
https://github.com/aws/aws-sdk-go/blob/6c4060605190fc6f00d63cd4e5572faa9f07345d/service/cloudfront/api.go#L6720-L6723
| 0.991152
|
||
go-vgo/robotgo
|
d643b9ffe5a44c524740136edc428be68ddbecae
|
examples/window/main.go
|
go
|
get
|
()
|
[] |
func get() {
// get the current process id
pid := robotgo.GetPID()
fmt.Println("pid----", pid)
// get current Window Active
mdata := robotgo.GetActive()
// get current Window Handle
hwnd := robotgo.GetHandle()
fmt.Println("hwnd---", hwnd)
// get current Window Handle
bhwnd := robotgo.GetBHandle()
fmt.Println("bhwnd---", bhwnd)
// get current Window title
title := robotgo.GetTitle()
fmt.Println("title-----", title)
// set Window Active
robotgo.SetActive(mdata)
}
|
[
"func",
"get",
"(",
")",
"{",
"// get the current process id",
"pid",
":=",
"robotgo",
".",
"GetPID",
"(",
")",
"\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"pid",
")",
"\n\n",
"// get current Window Active",
"mdata",
":=",
"robotgo",
".",
"GetActive",
"(",
")",
"\n\n",
"// get current Window Handle",
"hwnd",
":=",
"robotgo",
".",
"GetHandle",
"(",
")",
"\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"hwnd",
")",
"\n\n",
"// get current Window Handle",
"bhwnd",
":=",
"robotgo",
".",
"GetBHandle",
"(",
")",
"\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"bhwnd",
")",
"\n\n",
"// get current Window title",
"title",
":=",
"robotgo",
".",
"GetTitle",
"(",
")",
"\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"title",
")",
"\n\n",
"// set Window Active",
"robotgo",
".",
"SetActive",
"(",
"mdata",
")",
"\n",
"}"
] |
https://github.com/go-vgo/robotgo/blob/d643b9ffe5a44c524740136edc428be68ddbecae/examples/window/main.go#L30-L52
| 0.990885
|
||||
gobuffalo/buffalo
|
7f360181f4ccd79dcc9dcea2c904a4801f194f04
|
mail/internal/mail/message.go
|
go
|
FormatDate
|
(m *Message) (date time.Time)
|
// FormatDate formats a date as a valid RFC 5322 date.
|
FormatDate formats a date as a valid RFC 5322 date.
|
[
"FormatDate",
"formats",
"a",
"date",
"as",
"a",
"valid",
"RFC",
"5322",
"date",
"."
] |
func (m *Message) FormatDate(date time.Time) string {
return date.Format(time.RFC1123Z)
}
|
[
"func",
"(",
"m",
"*",
"Message",
")",
"FormatDate",
"(",
"date",
"time",
".",
"Time",
")",
"string",
"{",
"return",
"date",
".",
"Format",
"(",
"time",
".",
"RFC1123Z",
")",
"\n",
"}"
] |
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L182-L184
| 0.990162
|
||
olivere/elastic
|
0534a7b1bf47b1ccf57e905491a641709f8a623d
|
geo_point.go
|
go
|
GeoPointFromLatLon
|
(lat, lon float64)
|
// GeoPointFromLatLon initializes a new GeoPoint by latitude and longitude.
|
GeoPointFromLatLon initializes a new GeoPoint by latitude and longitude.
|
[
"GeoPointFromLatLon",
"initializes",
"a",
"new",
"GeoPoint",
"by",
"latitude",
"and",
"longitude",
"."
] |
func GeoPointFromLatLon(lat, lon float64) *GeoPoint {
return &GeoPoint{Lat: lat, Lon: lon}
}
|
[
"func",
"GeoPointFromLatLon",
"(",
"lat",
",",
"lon",
"float64",
")",
"*",
"GeoPoint",
"{",
"return",
"&",
"GeoPoint",
"{",
"Lat",
":",
"lat",
",",
"Lon",
":",
"lon",
"}",
"\n",
"}"
] |
https://github.com/olivere/elastic/blob/0534a7b1bf47b1ccf57e905491a641709f8a623d/geo_point.go#L34-L36
| 0.989981
|
||
json-iterator/go
|
0ff49de124c6f76f8494e194af75bde0f1a49a29
|
config.go
|
go
|
Encode
|
(encoder *htmlEscapedStringEncoder) (ptr unsafe.Pointer, stream *Stream)
|
[] |
func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) {
str := *((*string)(ptr))
stream.WriteStringWithHTMLEscaped(str)
}
|
[
"func",
"(",
"encoder",
"*",
"htmlEscapedStringEncoder",
")",
"Encode",
"(",
"ptr",
"unsafe",
".",
"Pointer",
",",
"stream",
"*",
"Stream",
")",
"{",
"str",
":=",
"*",
"(",
"(",
"*",
"string",
")",
"(",
"ptr",
")",
")",
"\n",
"stream",
".",
"WriteStringWithHTMLEscaped",
"(",
"str",
")",
"\n",
"}"
] |
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/config.go#L261-L264
| 0.989762
|
||||
json-iterator/go
|
0ff49de124c6f76f8494e194af75bde0f1a49a29
|
reflect.go
|
go
|
caseSensitive
|
(b *ctx) ()
|
[] |
func (b *ctx) caseSensitive() bool {
if b.frozenConfig == nil {
// default is case-insensitive
return false
}
return b.frozenConfig.caseSensitive
}
|
[
"func",
"(",
"b",
"*",
"ctx",
")",
"caseSensitive",
"(",
")",
"bool",
"{",
"if",
"b",
".",
"frozenConfig",
"==",
"nil",
"{",
"// default is case-insensitive",
"return",
"false",
"\n",
"}",
"\n",
"return",
"b",
".",
"frozenConfig",
".",
"caseSensitive",
"\n",
"}"
] |
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/reflect.go#L44-L50
| 0.989762
|
||||
go-xorm/xorm
|
ce804aee6c5118ed9a6bc04754aea4ea65232fe5
|
session_cols.go
|
go
|
Distinct
|
(session *Session) (columns ...string)
|
// Distinct use for distinct columns. Caution: when you are using cache,
// distinct will not be cached because cache system need id,
// but distinct will not provide id
|
Distinct use for distinct columns. Caution: when you are using cache,
distinct will not be cached because cache system need id,
but distinct will not provide id
|
[
"Distinct",
"use",
"for",
"distinct",
"columns",
".",
"Caution",
":",
"when",
"you",
"are",
"using",
"cache",
"distinct",
"will",
"not",
"be",
"cached",
"because",
"cache",
"system",
"need",
"id",
"but",
"distinct",
"will",
"not",
"provide",
"id"
] |
func (session *Session) Distinct(columns ...string) *Session {
session.statement.Distinct(columns...)
return session
}
|
[
"func",
"(",
"session",
"*",
"Session",
")",
"Distinct",
"(",
"columns",
"...",
"string",
")",
"*",
"Session",
"{",
"session",
".",
"statement",
".",
"Distinct",
"(",
"columns",
"...",
")",
"\n",
"return",
"session",
"\n",
"}"
] |
https://github.com/go-xorm/xorm/blob/ce804aee6c5118ed9a6bc04754aea4ea65232fe5/session_cols.go#L177-L180
| 0.989384
|
||
rivo/tview
|
90b4da1bd64ceee13d2e7d782b315b819190f7bf
|
checkbox.go
|
go
|
SetChecked
|
(c *Checkbox) (checked bool)
|
// SetChecked sets the state of the checkbox.
|
SetChecked sets the state of the checkbox.
|
[
"SetChecked",
"sets",
"the",
"state",
"of",
"the",
"checkbox",
"."
] |
func (c *Checkbox) SetChecked(checked bool) *Checkbox {
c.checked = checked
return c
}
|
[
"func",
"(",
"c",
"*",
"Checkbox",
")",
"SetChecked",
"(",
"checked",
"bool",
")",
"*",
"Checkbox",
"{",
"c",
".",
"checked",
"=",
"checked",
"\n",
"return",
"c",
"\n",
"}"
] |
https://github.com/rivo/tview/blob/90b4da1bd64ceee13d2e7d782b315b819190f7bf/checkbox.go#L58-L61
| 0.986897
|
||
kubernetes-retired/contrib
|
89f6948e24578fed2a90a87871b2263729f90ac3
|
scale-demo/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/deep_copy_generated.go
|
go
|
deepCopy_sets_Empty
|
(in sets.Empty, out *sets.Empty, c *conversion.Cloner)
|
[] |
func deepCopy_sets_Empty(in sets.Empty, out *sets.Empty, c *conversion.Cloner) error {
return nil
}
|
[
"func",
"deepCopy_sets_Empty",
"(",
"in",
"sets",
".",
"Empty",
",",
"out",
"*",
"sets",
".",
"Empty",
",",
"c",
"*",
"conversion",
".",
"Cloner",
")",
"error",
"{",
"return",
"nil",
"\n",
"}"
] |
https://github.com/kubernetes-retired/contrib/blob/89f6948e24578fed2a90a87871b2263729f90ac3/scale-demo/Godeps/_workspace/src/k8s.io/kubernetes/pkg/api/deep_copy_generated.go#L2724-L2726
| 0.985341
|
||||
nlopes/slack
|
65ea2b979a7ffe628676bdb6b924e2498d66c1bf
|
misc.go
|
go
|
postJSON
|
(ctx context.Context, client httpClient, endpoint, token string, json []byte, intf interface{}, d debug)
|
// post JSON.
|
post JSON.
|
[
"post",
"JSON",
"."
] |
func postJSON(ctx context.Context, client httpClient, endpoint, token string, json []byte, intf interface{}, d debug) error {
reqBody := bytes.NewBuffer(json)
req, err := http.NewRequest("POST", endpoint, reqBody)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
return doPost(ctx, client, req, intf, d)
}
|
[
"func",
"postJSON",
"(",
"ctx",
"context",
".",
"Context",
",",
"client",
"httpClient",
",",
"endpoint",
",",
"token",
"string",
",",
"json",
"[",
"]",
"byte",
",",
"intf",
"interface",
"{",
"}",
",",
"d",
"debug",
")",
"error",
"{",
"reqBody",
":=",
"bytes",
".",
"NewBuffer",
"(",
"json",
")",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"endpoint",
",",
"reqBody",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"token",
")",
")",
"\n",
"return",
"doPost",
"(",
"ctx",
",",
"client",
",",
"req",
",",
"intf",
",",
"d",
")",
"\n",
"}"
] |
https://github.com/nlopes/slack/blob/65ea2b979a7ffe628676bdb6b924e2498d66c1bf/misc.go#L210-L219
| 0.984911
|
||
lxc/lxd
|
7a41d14e4c1a6bc25918aca91004d594774dcdd3
|
lxd/networks_utils.go
|
go
|
networkSysctlSet
|
(path string, value string)
|
[] |
func networkSysctlSet(path string, value string) error {
// Get current value
current, err := networkSysctlGet(path)
if err == nil && current == value {
// Nothing to update
return nil
}
return ioutil.WriteFile(fmt.Sprintf("/proc/sys/net/%s", path), []byte(value), 0)
}
|
[
"func",
"networkSysctlSet",
"(",
"path",
"string",
",",
"value",
"string",
")",
"error",
"{",
"// Get current value",
"current",
",",
"err",
":=",
"networkSysctlGet",
"(",
"path",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"current",
"==",
"value",
"{",
"// Nothing to update",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"ioutil",
".",
"WriteFile",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
")",
",",
"[",
"]",
"byte",
"(",
"value",
")",
",",
"0",
")",
"\n",
"}"
] |
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/networks_utils.go#L1016-L1025
| 0.984168
|
||||
vmware/govmomi
|
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
|
vim25/xml/typeinfo.go
|
go
|
structFieldInfo
|
(typ reflect.Type, f *reflect.StructField)
|
// structFieldInfo builds and returns a fieldInfo for f.
|
structFieldInfo builds and returns a fieldInfo for f.
|
[
"structFieldInfo",
"builds",
"and",
"returns",
"a",
"fieldInfo",
"for",
"f",
"."
] |
func structFieldInfo(typ reflect.Type, f *reflect.StructField) (*fieldInfo, error) {
finfo := &fieldInfo{idx: f.Index}
// Split the tag from the xml namespace if necessary.
tag := f.Tag.Get("xml")
if i := strings.Index(tag, " "); i >= 0 {
finfo.xmlns, tag = tag[:i], tag[i+1:]
}
// Parse flags.
tokens := strings.Split(tag, ",")
if len(tokens) == 1 {
finfo.flags = fElement
} else {
tag = tokens[0]
for _, flag := range tokens[1:] {
switch flag {
case "attr":
finfo.flags |= fAttr
case "chardata":
finfo.flags |= fCharData
case "innerxml":
finfo.flags |= fInnerXml
case "comment":
finfo.flags |= fComment
case "any":
finfo.flags |= fAny
case "omitempty":
finfo.flags |= fOmitEmpty
case "typeattr":
finfo.flags |= fTypeAttr
}
}
// Validate the flags used.
valid := true
switch mode := finfo.flags & fMode; mode {
case 0:
finfo.flags |= fElement
case fAttr, fCharData, fInnerXml, fComment, fAny:
if f.Name == "XMLName" || tag != "" && mode != fAttr {
valid = false
}
default:
// This will also catch multiple modes in a single field.
valid = false
}
if finfo.flags&fMode == fAny {
finfo.flags |= fElement
}
if finfo.flags&fOmitEmpty != 0 && finfo.flags&(fElement|fAttr) == 0 {
valid = false
}
if !valid {
return nil, fmt.Errorf("xml: invalid tag in field %s of type %s: %q",
f.Name, typ, f.Tag.Get("xml"))
}
}
// Use of xmlns without a name is not allowed.
if finfo.xmlns != "" && tag == "" {
return nil, fmt.Errorf("xml: namespace without name in field %s of type %s: %q",
f.Name, typ, f.Tag.Get("xml"))
}
if f.Name == "XMLName" {
// The XMLName field records the XML element name. Don't
// process it as usual because its name should default to
// empty rather than to the field name.
finfo.name = tag
return finfo, nil
}
if tag == "" {
// If the name part of the tag is completely empty, get
// default from XMLName of underlying struct if feasible,
// or field name otherwise.
if xmlname := lookupXMLName(f.Type); xmlname != nil {
finfo.xmlns, finfo.name = xmlname.xmlns, xmlname.name
} else {
finfo.name = f.Name
}
return finfo, nil
}
// Prepare field name and parents.
parents := strings.Split(tag, ">")
if parents[0] == "" {
parents[0] = f.Name
}
if parents[len(parents)-1] == "" {
return nil, fmt.Errorf("xml: trailing '>' in field %s of type %s", f.Name, typ)
}
finfo.name = parents[len(parents)-1]
if len(parents) > 1 {
if (finfo.flags & fElement) == 0 {
return nil, fmt.Errorf("xml: %s chain not valid with %s flag", tag, strings.Join(tokens[1:], ","))
}
finfo.parents = parents[:len(parents)-1]
}
// If the field type has an XMLName field, the names must match
// so that the behavior of both marshalling and unmarshalling
// is straightforward and unambiguous.
if finfo.flags&fElement != 0 {
ftyp := f.Type
xmlname := lookupXMLName(ftyp)
if xmlname != nil && xmlname.name != finfo.name {
return nil, fmt.Errorf("xml: name %q in tag of %s.%s conflicts with name %q in %s.XMLName",
finfo.name, typ, f.Name, xmlname.name, ftyp)
}
}
return finfo, nil
}
|
[
"func",
"structFieldInfo",
"(",
"typ",
"reflect",
".",
"Type",
",",
"f",
"*",
"reflect",
".",
"StructField",
")",
"(",
"*",
"fieldInfo",
",",
"error",
")",
"{",
"finfo",
":=",
"&",
"fieldInfo",
"{",
"idx",
":",
"f",
".",
"Index",
"}",
"\n\n",
"// Split the tag from the xml namespace if necessary.",
"tag",
":=",
"f",
".",
"Tag",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"i",
":=",
"strings",
".",
"Index",
"(",
"tag",
",",
"\"",
"\"",
")",
";",
"i",
">=",
"0",
"{",
"finfo",
".",
"xmlns",
",",
"tag",
"=",
"tag",
"[",
":",
"i",
"]",
",",
"tag",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"}",
"\n\n",
"// Parse flags.",
"tokens",
":=",
"strings",
".",
"Split",
"(",
"tag",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"tokens",
")",
"==",
"1",
"{",
"finfo",
".",
"flags",
"=",
"fElement",
"\n",
"}",
"else",
"{",
"tag",
"=",
"tokens",
"[",
"0",
"]",
"\n",
"for",
"_",
",",
"flag",
":=",
"range",
"tokens",
"[",
"1",
":",
"]",
"{",
"switch",
"flag",
"{",
"case",
"\"",
"\"",
":",
"finfo",
".",
"flags",
"|=",
"fAttr",
"\n",
"case",
"\"",
"\"",
":",
"finfo",
".",
"flags",
"|=",
"fCharData",
"\n",
"case",
"\"",
"\"",
":",
"finfo",
".",
"flags",
"|=",
"fInnerXml",
"\n",
"case",
"\"",
"\"",
":",
"finfo",
".",
"flags",
"|=",
"fComment",
"\n",
"case",
"\"",
"\"",
":",
"finfo",
".",
"flags",
"|=",
"fAny",
"\n",
"case",
"\"",
"\"",
":",
"finfo",
".",
"flags",
"|=",
"fOmitEmpty",
"\n",
"case",
"\"",
"\"",
":",
"finfo",
".",
"flags",
"|=",
"fTypeAttr",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Validate the flags used.",
"valid",
":=",
"true",
"\n",
"switch",
"mode",
":=",
"finfo",
".",
"flags",
"&",
"fMode",
";",
"mode",
"{",
"case",
"0",
":",
"finfo",
".",
"flags",
"|=",
"fElement",
"\n",
"case",
"fAttr",
",",
"fCharData",
",",
"fInnerXml",
",",
"fComment",
",",
"fAny",
":",
"if",
"f",
".",
"Name",
"==",
"\"",
"\"",
"||",
"tag",
"!=",
"\"",
"\"",
"&&",
"mode",
"!=",
"fAttr",
"{",
"valid",
"=",
"false",
"\n",
"}",
"\n",
"default",
":",
"// This will also catch multiple modes in a single field.",
"valid",
"=",
"false",
"\n",
"}",
"\n",
"if",
"finfo",
".",
"flags",
"&",
"fMode",
"==",
"fAny",
"{",
"finfo",
".",
"flags",
"|=",
"fElement",
"\n",
"}",
"\n",
"if",
"finfo",
".",
"flags",
"&",
"fOmitEmpty",
"!=",
"0",
"&&",
"finfo",
".",
"flags",
"&",
"(",
"fElement",
"|",
"fAttr",
")",
"==",
"0",
"{",
"valid",
"=",
"false",
"\n",
"}",
"\n",
"if",
"!",
"valid",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"f",
".",
"Name",
",",
"typ",
",",
"f",
".",
"Tag",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Use of xmlns without a name is not allowed.",
"if",
"finfo",
".",
"xmlns",
"!=",
"\"",
"\"",
"&&",
"tag",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"f",
".",
"Name",
",",
"typ",
",",
"f",
".",
"Tag",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"if",
"f",
".",
"Name",
"==",
"\"",
"\"",
"{",
"// The XMLName field records the XML element name. Don't",
"// process it as usual because its name should default to",
"// empty rather than to the field name.",
"finfo",
".",
"name",
"=",
"tag",
"\n",
"return",
"finfo",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"tag",
"==",
"\"",
"\"",
"{",
"// If the name part of the tag is completely empty, get",
"// default from XMLName of underlying struct if feasible,",
"// or field name otherwise.",
"if",
"xmlname",
":=",
"lookupXMLName",
"(",
"f",
".",
"Type",
")",
";",
"xmlname",
"!=",
"nil",
"{",
"finfo",
".",
"xmlns",
",",
"finfo",
".",
"name",
"=",
"xmlname",
".",
"xmlns",
",",
"xmlname",
".",
"name",
"\n",
"}",
"else",
"{",
"finfo",
".",
"name",
"=",
"f",
".",
"Name",
"\n",
"}",
"\n",
"return",
"finfo",
",",
"nil",
"\n",
"}",
"\n\n",
"// Prepare field name and parents.",
"parents",
":=",
"strings",
".",
"Split",
"(",
"tag",
",",
"\"",
"\"",
")",
"\n",
"if",
"parents",
"[",
"0",
"]",
"==",
"\"",
"\"",
"{",
"parents",
"[",
"0",
"]",
"=",
"f",
".",
"Name",
"\n",
"}",
"\n",
"if",
"parents",
"[",
"len",
"(",
"parents",
")",
"-",
"1",
"]",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"f",
".",
"Name",
",",
"typ",
")",
"\n",
"}",
"\n",
"finfo",
".",
"name",
"=",
"parents",
"[",
"len",
"(",
"parents",
")",
"-",
"1",
"]",
"\n",
"if",
"len",
"(",
"parents",
")",
">",
"1",
"{",
"if",
"(",
"finfo",
".",
"flags",
"&",
"fElement",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tag",
",",
"strings",
".",
"Join",
"(",
"tokens",
"[",
"1",
":",
"]",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"finfo",
".",
"parents",
"=",
"parents",
"[",
":",
"len",
"(",
"parents",
")",
"-",
"1",
"]",
"\n",
"}",
"\n\n",
"// If the field type has an XMLName field, the names must match",
"// so that the behavior of both marshalling and unmarshalling",
"// is straightforward and unambiguous.",
"if",
"finfo",
".",
"flags",
"&",
"fElement",
"!=",
"0",
"{",
"ftyp",
":=",
"f",
".",
"Type",
"\n",
"xmlname",
":=",
"lookupXMLName",
"(",
"ftyp",
")",
"\n",
"if",
"xmlname",
"!=",
"nil",
"&&",
"xmlname",
".",
"name",
"!=",
"finfo",
".",
"name",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"finfo",
".",
"name",
",",
"typ",
",",
"f",
".",
"Name",
",",
"xmlname",
".",
"name",
",",
"ftyp",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"finfo",
",",
"nil",
"\n",
"}"
] |
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/xml/typeinfo.go#L115-L228
| 0.982617
|
||
asaskevich/govalidator
|
f61b66f89f4a311bef65f13e575bcf1a2ffadda6
|
arrays.go
|
go
|
Filter
|
(array []interface{}, iterator ConditionIterator)
|
// Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice.
|
Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice.
|
[
"Filter",
"iterates",
"over",
"the",
"slice",
"and",
"apply",
"ConditionIterator",
"to",
"every",
"item",
".",
"Returns",
"new",
"slice",
"."
] |
func Filter(array []interface{}, iterator ConditionIterator) []interface{} {
var result = make([]interface{}, 0)
for index, data := range array {
if iterator(data, index) {
result = append(result, data)
}
}
return result
}
|
[
"func",
"Filter",
"(",
"array",
"[",
"]",
"interface",
"{",
"}",
",",
"iterator",
"ConditionIterator",
")",
"[",
"]",
"interface",
"{",
"}",
"{",
"var",
"result",
"=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"0",
")",
"\n",
"for",
"index",
",",
"data",
":=",
"range",
"array",
"{",
"if",
"iterator",
"(",
"data",
",",
"index",
")",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"data",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] |
https://github.com/asaskevich/govalidator/blob/f61b66f89f4a311bef65f13e575bcf1a2ffadda6/arrays.go#L39-L47
| 0.976611
|
||
cloudfoundry/cli
|
5010c000047f246b870475e2c299556078cdad30
|
cf/util/json/json_parser.go
|
go
|
ParseJSONFromFileOrString
|
(fileOrJSON string)
|
[] |
func ParseJSONFromFileOrString(fileOrJSON string) (map[string]interface{}, error) {
var jsonMap map[string]interface{}
var err error
var bytes []byte
if fileOrJSON == "" {
return nil, nil
}
if fileExists(fileOrJSON) {
bytes, err = readJSONFile(fileOrJSON)
if err != nil {
return nil, err
}
} else {
bytes = []byte(fileOrJSON)
}
jsonMap, err = parseJSON(bytes)
if err != nil {
return nil, err
}
return jsonMap, nil
}
|
[
"func",
"ParseJSONFromFileOrString",
"(",
"fileOrJSON",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"var",
"jsonMap",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"var",
"err",
"error",
"\n",
"var",
"bytes",
"[",
"]",
"byte",
"\n\n",
"if",
"fileOrJSON",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"fileExists",
"(",
"fileOrJSON",
")",
"{",
"bytes",
",",
"err",
"=",
"readJSONFile",
"(",
"fileOrJSON",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"bytes",
"=",
"[",
"]",
"byte",
"(",
"fileOrJSON",
")",
"\n",
"}",
"\n\n",
"jsonMap",
",",
"err",
"=",
"parseJSON",
"(",
"bytes",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"jsonMap",
",",
"nil",
"\n",
"}"
] |
https://github.com/cloudfoundry/cli/blob/5010c000047f246b870475e2c299556078cdad30/cf/util/json/json_parser.go#L29-L54
| 0.976193
|
||||
hyperledger/burrow
|
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
|
vent/sqldb/adapters/postgres_adapter.go
|
go
|
Open
|
(adapter *PostgresAdapter) (dbURL string)
|
// Open connects to a PostgreSQL database, opens it & create default schema if provided
|
Open connects to a PostgreSQL database, opens it & create default schema if provided
|
[
"Open",
"connects",
"to",
"a",
"PostgreSQL",
"database",
"opens",
"it",
"&",
"create",
"default",
"schema",
"if",
"provided"
] |
func (adapter *PostgresAdapter) Open(dbURL string) (*sql.DB, error) {
db, err := sql.Open("postgres", dbURL)
if err != nil {
adapter.Log.Info("msg", "Error creating database connection", "err", err)
return nil, err
}
// if there is a supplied Schema
if adapter.Schema != "" {
if err = db.Ping(); err != nil {
adapter.Log.Info("msg", "Error opening database connection", "err", err)
return nil, err
}
var found bool
query := Cleanf(`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n WHERE n.nspname = '%s');`, adapter.Schema)
adapter.Log.Info("msg", "FIND SCHEMA", "query", query)
if err := db.QueryRow(query).Scan(&found); err == nil {
if !found {
adapter.Log.Warn("msg", "Schema not found")
}
adapter.Log.Info("msg", "Creating schema")
query = Cleanf("CREATE SCHEMA %s;", adapter.Schema)
adapter.Log.Info("msg", "CREATE SCHEMA", "query", query)
if _, err = db.Exec(query); err != nil {
if adapter.ErrorEquals(err, types.SQLErrorTypeDuplicatedSchema) {
adapter.Log.Warn("msg", "Duplicated schema")
return db, nil
}
}
} else {
adapter.Log.Info("msg", "Error searching schema", "err", err)
return nil, err
}
} else {
return nil, fmt.Errorf("no schema supplied")
}
return db, err
}
|
[
"func",
"(",
"adapter",
"*",
"PostgresAdapter",
")",
"Open",
"(",
"dbURL",
"string",
")",
"(",
"*",
"sql",
".",
"DB",
",",
"error",
")",
"{",
"db",
",",
"err",
":=",
"sql",
".",
"Open",
"(",
"\"",
"\"",
",",
"dbURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"adapter",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// if there is a supplied Schema",
"if",
"adapter",
".",
"Schema",
"!=",
"\"",
"\"",
"{",
"if",
"err",
"=",
"db",
".",
"Ping",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"adapter",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"found",
"bool",
"\n\n",
"query",
":=",
"Cleanf",
"(",
"`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n WHERE n.nspname = '%s');`",
",",
"adapter",
".",
"Schema",
")",
"\n",
"adapter",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"query",
")",
"\n\n",
"if",
"err",
":=",
"db",
".",
"QueryRow",
"(",
"query",
")",
".",
"Scan",
"(",
"&",
"found",
")",
";",
"err",
"==",
"nil",
"{",
"if",
"!",
"found",
"{",
"adapter",
".",
"Log",
".",
"Warn",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"adapter",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"query",
"=",
"Cleanf",
"(",
"\"",
"\"",
",",
"adapter",
".",
"Schema",
")",
"\n",
"adapter",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"query",
")",
"\n\n",
"if",
"_",
",",
"err",
"=",
"db",
".",
"Exec",
"(",
"query",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"adapter",
".",
"ErrorEquals",
"(",
"err",
",",
"types",
".",
"SQLErrorTypeDuplicatedSchema",
")",
"{",
"adapter",
".",
"Log",
".",
"Warn",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"db",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"adapter",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"db",
",",
"err",
"\n",
"}"
] |
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqldb/adapters/postgres_adapter.go#L41-L84
| 0.975815
|
||
robertkrimen/otto
|
15f95af6e78dcd2030d8195a138bd88d4f403546
|
builtin_array.go
|
go
|
builtinArray_push
|
(call FunctionCall)
|
[] |
func builtinArray_push(call FunctionCall) Value {
thisObject := call.thisObject()
itemList := call.ArgumentList
index := int64(toUint32(thisObject.get("length")))
for len(itemList) > 0 {
thisObject.put(arrayIndexToString(index), itemList[0], true)
itemList = itemList[1:]
index += 1
}
length := toValue_int64(index)
thisObject.put("length", length, true)
return length
}
|
[
"func",
"builtinArray_push",
"(",
"call",
"FunctionCall",
")",
"Value",
"{",
"thisObject",
":=",
"call",
".",
"thisObject",
"(",
")",
"\n",
"itemList",
":=",
"call",
".",
"ArgumentList",
"\n",
"index",
":=",
"int64",
"(",
"toUint32",
"(",
"thisObject",
".",
"get",
"(",
"\"",
"\"",
")",
")",
")",
"\n",
"for",
"len",
"(",
"itemList",
")",
">",
"0",
"{",
"thisObject",
".",
"put",
"(",
"arrayIndexToString",
"(",
"index",
")",
",",
"itemList",
"[",
"0",
"]",
",",
"true",
")",
"\n",
"itemList",
"=",
"itemList",
"[",
"1",
":",
"]",
"\n",
"index",
"+=",
"1",
"\n",
"}",
"\n",
"length",
":=",
"toValue_int64",
"(",
"index",
")",
"\n",
"thisObject",
".",
"put",
"(",
"\"",
"\"",
",",
"length",
",",
"true",
")",
"\n",
"return",
"length",
"\n",
"}"
] |
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/builtin_array.go#L114-L126
| 0.97548
|
||||
robertkrimen/otto
|
15f95af6e78dcd2030d8195a138bd88d4f403546
|
type_regexp.go
|
go
|
execResultToArray
|
(runtime *_runtime, target string, result []int)
|
[] |
func execResultToArray(runtime *_runtime, target string, result []int) *_object {
captureCount := len(result) / 2
valueArray := make([]Value, captureCount)
for index := 0; index < captureCount; index++ {
offset := 2 * index
if result[offset] != -1 {
valueArray[index] = toValue_string(target[result[offset]:result[offset+1]])
} else {
valueArray[index] = Value{}
}
}
matchIndex := result[0]
if matchIndex != 0 {
matchIndex = 0
// Find the rune index in the string, not the byte index
for index := 0; index < result[0]; {
_, size := utf8.DecodeRuneInString(target[index:])
matchIndex += 1
index += size
}
}
match := runtime.newArrayOf(valueArray)
match.defineProperty("input", toValue_string(target), 0111, false)
match.defineProperty("index", toValue_int(matchIndex), 0111, false)
return match
}
|
[
"func",
"execResultToArray",
"(",
"runtime",
"*",
"_runtime",
",",
"target",
"string",
",",
"result",
"[",
"]",
"int",
")",
"*",
"_object",
"{",
"captureCount",
":=",
"len",
"(",
"result",
")",
"/",
"2",
"\n",
"valueArray",
":=",
"make",
"(",
"[",
"]",
"Value",
",",
"captureCount",
")",
"\n",
"for",
"index",
":=",
"0",
";",
"index",
"<",
"captureCount",
";",
"index",
"++",
"{",
"offset",
":=",
"2",
"*",
"index",
"\n",
"if",
"result",
"[",
"offset",
"]",
"!=",
"-",
"1",
"{",
"valueArray",
"[",
"index",
"]",
"=",
"toValue_string",
"(",
"target",
"[",
"result",
"[",
"offset",
"]",
":",
"result",
"[",
"offset",
"+",
"1",
"]",
"]",
")",
"\n",
"}",
"else",
"{",
"valueArray",
"[",
"index",
"]",
"=",
"Value",
"{",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"matchIndex",
":=",
"result",
"[",
"0",
"]",
"\n",
"if",
"matchIndex",
"!=",
"0",
"{",
"matchIndex",
"=",
"0",
"\n",
"// Find the rune index in the string, not the byte index",
"for",
"index",
":=",
"0",
";",
"index",
"<",
"result",
"[",
"0",
"]",
";",
"{",
"_",
",",
"size",
":=",
"utf8",
".",
"DecodeRuneInString",
"(",
"target",
"[",
"index",
":",
"]",
")",
"\n",
"matchIndex",
"+=",
"1",
"\n",
"index",
"+=",
"size",
"\n",
"}",
"\n",
"}",
"\n",
"match",
":=",
"runtime",
".",
"newArrayOf",
"(",
"valueArray",
")",
"\n",
"match",
".",
"defineProperty",
"(",
"\"",
"\"",
",",
"toValue_string",
"(",
"target",
")",
",",
"0111",
",",
"false",
")",
"\n",
"match",
".",
"defineProperty",
"(",
"\"",
"\"",
",",
"toValue_int",
"(",
"matchIndex",
")",
",",
"0111",
",",
"false",
")",
"\n",
"return",
"match",
"\n",
"}"
] |
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/type_regexp.go#L121-L146
| 0.97548
|
||||
chrislusf/gleam
|
a7aa467b545f5e5e452aaf818299a5f6e6b23760
|
sql/parser/yy_parser.go
|
go
|
toDecimal
|
(l yyLexer, lval *yySymType, str string)
|
[] |
func toDecimal(l yyLexer, lval *yySymType, str string) int {
dec := new(types.MyDecimal)
err := dec.FromString(hack.Slice(str))
if err != nil {
l.Errorf("decimal literal: %v", err)
}
lval.item = dec
return decLit
}
|
[
"func",
"toDecimal",
"(",
"l",
"yyLexer",
",",
"lval",
"*",
"yySymType",
",",
"str",
"string",
")",
"int",
"{",
"dec",
":=",
"new",
"(",
"types",
".",
"MyDecimal",
")",
"\n",
"err",
":=",
"dec",
".",
"FromString",
"(",
"hack",
".",
"Slice",
"(",
"str",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"l",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"lval",
".",
"item",
"=",
"dec",
"\n",
"return",
"decLit",
"\n",
"}"
] |
https://github.com/chrislusf/gleam/blob/a7aa467b545f5e5e452aaf818299a5f6e6b23760/sql/parser/yy_parser.go#L156-L164
| 0.974252
|
||||
gotk3/gotk3
|
c89a2934a82722863fb6782d9245c4e7c3cf25f1
|
gtk/label.go
|
go
|
WidgetToLabel
|
(widget *Widget)
|
[] |
func WidgetToLabel(widget *Widget) (interface{}, error) {
obj := glib.Take(unsafe.Pointer(widget.GObject))
return wrapLabel(obj), nil
}
|
[
"func",
"WidgetToLabel",
"(",
"widget",
"*",
"Widget",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"obj",
":=",
"glib",
".",
"Take",
"(",
"unsafe",
".",
"Pointer",
"(",
"widget",
".",
"GObject",
")",
")",
"\n",
"return",
"wrapLabel",
"(",
"obj",
")",
",",
"nil",
"\n",
"}"
] |
https://github.com/gotk3/gotk3/blob/c89a2934a82722863fb6782d9245c4e7c3cf25f1/gtk/label.go#L45-L48
| 0.97407
|
||||
gopasspw/gopass
|
fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4
|
pkg/clipboard/unclip.go
|
go
|
Clear
|
(ctx context.Context, checksum string, force bool)
|
// Clear will attempt to erase the clipboard
|
Clear will attempt to erase the clipboard
|
[
"Clear",
"will",
"attempt",
"to",
"erase",
"the",
"clipboard"
] |
func Clear(ctx context.Context, checksum string, force bool) error {
if clipboard.Unsupported {
return ErrNotSupported
}
cur, err := clipboard.ReadAll()
if err != nil {
return errors.Wrapf(err, "failed to read clipboard: %s", err)
}
hash := fmt.Sprintf("%x", sha256.Sum256([]byte(cur)))
if hash != checksum && !force {
return nil
}
if err := clipboard.WriteAll(""); err != nil {
_ = notify.Notify(ctx, "gopass - clipboard", "Failed to clear clipboard")
return errors.Wrapf(err, "failed to write clipboard: %s", err)
}
if err := clearClipboardHistory(ctx); err != nil {
_ = notify.Notify(ctx, "gopass - clipboard", "Failed to clear clipboard history")
return errors.Wrapf(err, "failed to clear clipboard history: %s", err)
}
if err := notify.Notify(ctx, "gopass -clipboard", "Clipboard has been cleared"); err != nil {
return errors.Wrapf(err, "failed to send unclip notification: %s", err)
}
return nil
}
|
[
"func",
"Clear",
"(",
"ctx",
"context",
".",
"Context",
",",
"checksum",
"string",
",",
"force",
"bool",
")",
"error",
"{",
"if",
"clipboard",
".",
"Unsupported",
"{",
"return",
"ErrNotSupported",
"\n",
"}",
"\n\n",
"cur",
",",
"err",
":=",
"clipboard",
".",
"ReadAll",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"hash",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sha256",
".",
"Sum256",
"(",
"[",
"]",
"byte",
"(",
"cur",
")",
")",
")",
"\n",
"if",
"hash",
"!=",
"checksum",
"&&",
"!",
"force",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"clipboard",
".",
"WriteAll",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"_",
"=",
"notify",
".",
"Notify",
"(",
"ctx",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"clearClipboardHistory",
"(",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"_",
"=",
"notify",
".",
"Notify",
"(",
"ctx",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"notify",
".",
"Notify",
"(",
"ctx",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
https://github.com/gopasspw/gopass/blob/fe4e21d62182f0f2e4ef9a0ca8168d849dc52bd4/pkg/clipboard/unclip.go#L15-L45
| 0.973739
|
||
inverse-inc/packetfence
|
f29912bde7974931d699aba60aa8fde1c5d9a826
|
go/dhcp/utils.go
|
go
|
Shuffle
|
(addresses string)
|
[] |
func Shuffle(addresses string) (r []byte) {
var array []net.IP
for _, adresse := range strings.Split(addresses, ",") {
array = append(array, net.ParseIP(adresse).To4())
}
slice := make([]byte, 0, len(array))
random := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := len(array) - 1; i > 0; i-- {
j := random.Intn(i + 1)
array[i], array[j] = array[j], array[i]
}
for _, element := range array {
elem := []byte(element)
slice = append(slice, elem...)
}
return slice
}
|
[
"func",
"Shuffle",
"(",
"addresses",
"string",
")",
"(",
"r",
"[",
"]",
"byte",
")",
"{",
"var",
"array",
"[",
"]",
"net",
".",
"IP",
"\n",
"for",
"_",
",",
"adresse",
":=",
"range",
"strings",
".",
"Split",
"(",
"addresses",
",",
"\"",
"\"",
")",
"{",
"array",
"=",
"append",
"(",
"array",
",",
"net",
".",
"ParseIP",
"(",
"adresse",
")",
".",
"To4",
"(",
")",
")",
"\n",
"}",
"\n\n",
"slice",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"len",
"(",
"array",
")",
")",
"\n\n",
"random",
":=",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
")",
"\n",
"for",
"i",
":=",
"len",
"(",
"array",
")",
"-",
"1",
";",
"i",
">",
"0",
";",
"i",
"--",
"{",
"j",
":=",
"random",
".",
"Intn",
"(",
"i",
"+",
"1",
")",
"\n",
"array",
"[",
"i",
"]",
",",
"array",
"[",
"j",
"]",
"=",
"array",
"[",
"j",
"]",
",",
"array",
"[",
"i",
"]",
"\n",
"}",
"\n",
"for",
"_",
",",
"element",
":=",
"range",
"array",
"{",
"elem",
":=",
"[",
"]",
"byte",
"(",
"element",
")",
"\n",
"slice",
"=",
"append",
"(",
"slice",
",",
"elem",
"...",
")",
"\n",
"}",
"\n",
"return",
"slice",
"\n",
"}"
] |
https://github.com/inverse-inc/packetfence/blob/f29912bde7974931d699aba60aa8fde1c5d9a826/go/dhcp/utils.go#L218-L236
| 0.972572
|
||||
fogleman/gg
|
72436a171bf31757dc87fb8fa9f7485307350307
|
matrix.go
|
go
|
Rotate
|
(a Matrix) (angle float64)
|
[] |
func (a Matrix) Rotate(angle float64) Matrix {
return Rotate(angle).Multiply(a)
}
|
[
"func",
"(",
"a",
"Matrix",
")",
"Rotate",
"(",
"angle",
"float64",
")",
"Matrix",
"{",
"return",
"Rotate",
"(",
"angle",
")",
".",
"Multiply",
"(",
"a",
")",
"\n",
"}"
] |
https://github.com/fogleman/gg/blob/72436a171bf31757dc87fb8fa9f7485307350307/matrix.go#L82-L84
| 0.971275
|
||||
hajimehoshi/ebiten
|
3ce8babd9bd0470bd5683158cc320277cc04d5ed
|
internal/graphicsdriver/opengl/context_js.go
|
go
|
setViewportImpl
|
(c *context) (width, height int)
|
[] |
func (c *context) setViewportImpl(width, height int) {
c.ensureGL()
gl := c.gl
gl.Call("viewport", 0, 0, width, height)
}
|
[
"func",
"(",
"c",
"*",
"context",
")",
"setViewportImpl",
"(",
"width",
",",
"height",
"int",
")",
"{",
"c",
".",
"ensureGL",
"(",
")",
"\n",
"gl",
":=",
"c",
".",
"gl",
"\n",
"gl",
".",
"Call",
"(",
"\"",
"\"",
",",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
"\n",
"}"
] |
https://github.com/hajimehoshi/ebiten/blob/3ce8babd9bd0470bd5683158cc320277cc04d5ed/internal/graphicsdriver/opengl/context_js.go#L248-L252
| 0.969041
|
||||
rakyll/statik
|
3bac566d30cdbeddef402a80f3d6305860e59f12
|
fs/fs.go
|
go
|
New
|
()
|
// New creates a new file system with the registered zip contents data.
// It unzips all files and stores them in an in-memory map.
|
New creates a new file system with the registered zip contents data.
It unzips all files and stores them in an in-memory map.
|
[
"New",
"creates",
"a",
"new",
"file",
"system",
"with",
"the",
"registered",
"zip",
"contents",
"data",
".",
"It",
"unzips",
"all",
"files",
"and",
"stores",
"them",
"in",
"an",
"in",
"-",
"memory",
"map",
"."
] |
func New() (http.FileSystem, error) {
if zipData == "" {
return nil, errors.New("statik/fs: no zip data registered")
}
zipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))
if err != nil {
return nil, err
}
files := make(map[string]file, len(zipReader.File))
dirs := make(map[string][]string)
fs := &statikFS{files: files, dirs: dirs}
for _, zipFile := range zipReader.File {
fi := zipFile.FileInfo()
f := file{FileInfo: fi, fs: fs}
f.data, err = unzip(zipFile)
if err != nil {
return nil, fmt.Errorf("statik/fs: error unzipping file %q: %s", zipFile.Name, err)
}
files["/"+zipFile.Name] = f
}
for fn := range files {
// go up directories recursively in order to care deep directory
for dn := path.Dir(fn); dn != fn; {
if _, ok := files[dn]; !ok {
files[dn] = file{FileInfo: dirInfo{dn}, fs: fs}
} else {
break
}
fn, dn = dn, path.Dir(dn)
}
}
for fn := range files {
dn := path.Dir(fn)
if fn != dn {
fs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))
}
}
for _, s := range fs.dirs {
sort.Strings(s)
}
return fs, nil
}
|
[
"func",
"New",
"(",
")",
"(",
"http",
".",
"FileSystem",
",",
"error",
")",
"{",
"if",
"zipData",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"zipReader",
",",
"err",
":=",
"zip",
".",
"NewReader",
"(",
"strings",
".",
"NewReader",
"(",
"zipData",
")",
",",
"int64",
"(",
"len",
"(",
"zipData",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"files",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"file",
",",
"len",
"(",
"zipReader",
".",
"File",
")",
")",
"\n",
"dirs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n",
"fs",
":=",
"&",
"statikFS",
"{",
"files",
":",
"files",
",",
"dirs",
":",
"dirs",
"}",
"\n",
"for",
"_",
",",
"zipFile",
":=",
"range",
"zipReader",
".",
"File",
"{",
"fi",
":=",
"zipFile",
".",
"FileInfo",
"(",
")",
"\n",
"f",
":=",
"file",
"{",
"FileInfo",
":",
"fi",
",",
"fs",
":",
"fs",
"}",
"\n",
"f",
".",
"data",
",",
"err",
"=",
"unzip",
"(",
"zipFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"zipFile",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n",
"files",
"[",
"\"",
"\"",
"+",
"zipFile",
".",
"Name",
"]",
"=",
"f",
"\n",
"}",
"\n",
"for",
"fn",
":=",
"range",
"files",
"{",
"// go up directories recursively in order to care deep directory",
"for",
"dn",
":=",
"path",
".",
"Dir",
"(",
"fn",
")",
";",
"dn",
"!=",
"fn",
";",
"{",
"if",
"_",
",",
"ok",
":=",
"files",
"[",
"dn",
"]",
";",
"!",
"ok",
"{",
"files",
"[",
"dn",
"]",
"=",
"file",
"{",
"FileInfo",
":",
"dirInfo",
"{",
"dn",
"}",
",",
"fs",
":",
"fs",
"}",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"fn",
",",
"dn",
"=",
"dn",
",",
"path",
".",
"Dir",
"(",
"dn",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"fn",
":=",
"range",
"files",
"{",
"dn",
":=",
"path",
".",
"Dir",
"(",
"fn",
")",
"\n",
"if",
"fn",
"!=",
"dn",
"{",
"fs",
".",
"dirs",
"[",
"dn",
"]",
"=",
"append",
"(",
"fs",
".",
"dirs",
"[",
"dn",
"]",
",",
"path",
".",
"Base",
"(",
"fn",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"fs",
".",
"dirs",
"{",
"sort",
".",
"Strings",
"(",
"s",
")",
"\n",
"}",
"\n",
"return",
"fs",
",",
"nil",
"\n",
"}"
] |
https://github.com/rakyll/statik/blob/3bac566d30cdbeddef402a80f3d6305860e59f12/fs/fs.go#L55-L96
| 0.967647
|
||
aarzilli/nucular
|
64ec1eba91814ebb417978927206070dd1fc44e1
|
nucular.go
|
go
|
buttonWidth
|
(lbl label.Label, style *nstyle.Button, font font.Face)
|
[] |
func buttonWidth(lbl label.Label, style *nstyle.Button, font font.Face) int {
w := 2*style.Padding.X + 2*style.TouchPadding.X + 2*style.Border
switch lbl.Kind {
case label.TextLabel:
w += FontWidth(font, lbl.Text)
case label.SymbolLabel:
w += symbolWidth(lbl.Symbol, font)
case label.ImageLabel:
w += lbl.Img.Bounds().Dx() + 2*style.ImagePadding.X
case label.SymbolTextLabel:
w += FontWidth(font, lbl.Text) + symbolWidth(lbl.Symbol, font) + 2*style.Padding.X
case label.ImageTextLabel:
}
return w
}
|
[
"func",
"buttonWidth",
"(",
"lbl",
"label",
".",
"Label",
",",
"style",
"*",
"nstyle",
".",
"Button",
",",
"font",
"font",
".",
"Face",
")",
"int",
"{",
"w",
":=",
"2",
"*",
"style",
".",
"Padding",
".",
"X",
"+",
"2",
"*",
"style",
".",
"TouchPadding",
".",
"X",
"+",
"2",
"*",
"style",
".",
"Border",
"\n",
"switch",
"lbl",
".",
"Kind",
"{",
"case",
"label",
".",
"TextLabel",
":",
"w",
"+=",
"FontWidth",
"(",
"font",
",",
"lbl",
".",
"Text",
")",
"\n",
"case",
"label",
".",
"SymbolLabel",
":",
"w",
"+=",
"symbolWidth",
"(",
"lbl",
".",
"Symbol",
",",
"font",
")",
"\n",
"case",
"label",
".",
"ImageLabel",
":",
"w",
"+=",
"lbl",
".",
"Img",
".",
"Bounds",
"(",
")",
".",
"Dx",
"(",
")",
"+",
"2",
"*",
"style",
".",
"ImagePadding",
".",
"X",
"\n",
"case",
"label",
".",
"SymbolTextLabel",
":",
"w",
"+=",
"FontWidth",
"(",
"font",
",",
"lbl",
".",
"Text",
")",
"+",
"symbolWidth",
"(",
"lbl",
".",
"Symbol",
",",
"font",
")",
"+",
"2",
"*",
"style",
".",
"Padding",
".",
"X",
"\n",
"case",
"label",
".",
"ImageTextLabel",
":",
"}",
"\n",
"return",
"w",
"\n",
"}"
] |
https://github.com/aarzilli/nucular/blob/64ec1eba91814ebb417978927206070dd1fc44e1/nucular.go#L1658-L1672
| 0.96435
|
||||
pilosa/pilosa
|
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
fragment.go
|
go
|
readStorageFromArchive
|
(f *fragment) (r io.Reader)
|
[] |
func (f *fragment) readStorageFromArchive(r io.Reader) error {
// Create a temporary file to copy into.
path := f.path + copyExt
file, err := os.Create(path)
if err != nil {
return errors.Wrap(err, "creating directory")
}
defer file.Close()
// Copy reader into temporary path.
if _, err = io.Copy(file, r); err != nil {
return errors.Wrap(err, "copying")
}
// Close current storage.
if err := f.closeStorage(); err != nil {
return errors.Wrap(err, "closing")
}
// Move snapshot to data file location.
if err := os.Rename(path, f.path); err != nil {
return errors.Wrap(err, "renaming")
}
// Reopen storage.
if err := f.openStorage(); err != nil {
return errors.Wrap(err, "opening")
}
return nil
}
|
[
"func",
"(",
"f",
"*",
"fragment",
")",
"readStorageFromArchive",
"(",
"r",
"io",
".",
"Reader",
")",
"error",
"{",
"// Create a temporary file to copy into.",
"path",
":=",
"f",
".",
"path",
"+",
"copyExt",
"\n",
"file",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n\n",
"// Copy reader into temporary path.",
"if",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"file",
",",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Close current storage.",
"if",
"err",
":=",
"f",
".",
"closeStorage",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Move snapshot to data file location.",
"if",
"err",
":=",
"os",
".",
"Rename",
"(",
"path",
",",
"f",
".",
"path",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Reopen storage.",
"if",
"err",
":=",
"f",
".",
"openStorage",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/fragment.go#L2136-L2166
| 0.963801
|
||||
pilosa/pilosa
|
67d53f6b48a43f7fe090f48e35518ca8d024747c
|
encoding/proto/proto.go
|
go
|
decodeGroupCounts
|
(a []*internal.GroupCount)
|
[] |
func decodeGroupCounts(a []*internal.GroupCount) []pilosa.GroupCount {
other := make([]pilosa.GroupCount, len(a))
for i := range a {
other[i] = pilosa.GroupCount{
Group: decodeFieldRows(a[i].Group),
Count: a[i].Count,
}
}
return other
}
|
[
"func",
"decodeGroupCounts",
"(",
"a",
"[",
"]",
"*",
"internal",
".",
"GroupCount",
")",
"[",
"]",
"pilosa",
".",
"GroupCount",
"{",
"other",
":=",
"make",
"(",
"[",
"]",
"pilosa",
".",
"GroupCount",
",",
"len",
"(",
"a",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"a",
"{",
"other",
"[",
"i",
"]",
"=",
"pilosa",
".",
"GroupCount",
"{",
"Group",
":",
"decodeFieldRows",
"(",
"a",
"[",
"i",
"]",
".",
"Group",
")",
",",
"Count",
":",
"a",
"[",
"i",
"]",
".",
"Count",
",",
"}",
"\n",
"}",
"\n",
"return",
"other",
"\n",
"}"
] |
https://github.com/pilosa/pilosa/blob/67d53f6b48a43f7fe090f48e35518ca8d024747c/encoding/proto/proto.go#L1136-L1145
| 0.963801
|
||||
Workiva/go-datastructures
|
f07cbe3f82ca2fd6e5ab94afce65fe43319f675f
|
numerics/optimization/nelder_mead.go
|
go
|
NelderMead
|
(config NelderMeadConfiguration)
|
// NelderMead takes a configuration and returns a list
// of floats that can be plugged into the provided function
// to converge at the target value.
|
NelderMead takes a configuration and returns a list
of floats that can be plugged into the provided function
to converge at the target value.
|
[
"NelderMead",
"takes",
"a",
"configuration",
"and",
"returns",
"a",
"list",
"of",
"floats",
"that",
"can",
"be",
"plugged",
"into",
"the",
"provided",
"function",
"to",
"converge",
"at",
"the",
"target",
"value",
"."
] |
func NelderMead(config NelderMeadConfiguration) []float64 {
nm := newNelderMead(config)
nm.evaluate()
return nm.results.vertices[0].vars
}
|
[
"func",
"NelderMead",
"(",
"config",
"NelderMeadConfiguration",
")",
"[",
"]",
"float64",
"{",
"nm",
":=",
"newNelderMead",
"(",
"config",
")",
"\n",
"nm",
".",
"evaluate",
"(",
")",
"\n",
"return",
"nm",
".",
"results",
".",
"vertices",
"[",
"0",
"]",
".",
"vars",
"\n",
"}"
] |
https://github.com/Workiva/go-datastructures/blob/f07cbe3f82ca2fd6e5ab94afce65fe43319f675f/numerics/optimization/nelder_mead.go#L555-L559
| 0.957229
|
||
minio/mc
|
f0f156aca82e451c80b05d5be8eb01a04fee29dd
|
pkg/colorjson/encode.go
|
go
|
stringEncoder
|
(e *encodeState, v reflect.Value, opts encOpts)
|
[] |
func stringEncoder(e *encodeState, v reflect.Value, opts encOpts) {
if v.Type() == numberType {
numStr := v.String()
// In Go1.5 the empty string encodes to "0", while this is not a valid number literal
// we keep compatibility so check validity after this.
if numStr == "" {
numStr = "0" // Number's zero-val
}
if !isValidNumber(numStr) {
e.error(fmt.Errorf("json: invalid number literal %q", numStr))
}
e.WriteString(console.Colorize(jsonString, numStr))
return
}
if opts.quoted {
sb, err := Marshal(v.String())
if err != nil {
e.error(err)
}
e.string(console.Colorize(jsonString, string(sb)), opts.escapeHTML)
} else {
e.string(console.Colorize(jsonString, v.String()), opts.escapeHTML)
}
}
|
[
"func",
"stringEncoder",
"(",
"e",
"*",
"encodeState",
",",
"v",
"reflect",
".",
"Value",
",",
"opts",
"encOpts",
")",
"{",
"if",
"v",
".",
"Type",
"(",
")",
"==",
"numberType",
"{",
"numStr",
":=",
"v",
".",
"String",
"(",
")",
"\n",
"// In Go1.5 the empty string encodes to \"0\", while this is not a valid number literal",
"// we keep compatibility so check validity after this.",
"if",
"numStr",
"==",
"\"",
"\"",
"{",
"numStr",
"=",
"\"",
"\"",
"// Number's zero-val",
"\n",
"}",
"\n",
"if",
"!",
"isValidNumber",
"(",
"numStr",
")",
"{",
"e",
".",
"error",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"numStr",
")",
")",
"\n",
"}",
"\n",
"e",
".",
"WriteString",
"(",
"console",
".",
"Colorize",
"(",
"jsonString",
",",
"numStr",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"opts",
".",
"quoted",
"{",
"sb",
",",
"err",
":=",
"Marshal",
"(",
"v",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"e",
".",
"error",
"(",
"err",
")",
"\n",
"}",
"\n",
"e",
".",
"string",
"(",
"console",
".",
"Colorize",
"(",
"jsonString",
",",
"string",
"(",
"sb",
")",
")",
",",
"opts",
".",
"escapeHTML",
")",
"\n",
"}",
"else",
"{",
"e",
".",
"string",
"(",
"console",
".",
"Colorize",
"(",
"jsonString",
",",
"v",
".",
"String",
"(",
")",
")",
",",
"opts",
".",
"escapeHTML",
")",
"\n",
"}",
"\n",
"}"
] |
https://github.com/minio/mc/blob/f0f156aca82e451c80b05d5be8eb01a04fee29dd/pkg/colorjson/encode.go#L615-L638
| 0.949367
|
||||
Unknwon/com
|
0fed4efef7553eed2cd04624befccacda78bb8e2
|
time.go
|
go
|
DateS
|
(ts string, format string)
|
// Format unix time string to string
|
Format unix time string to string
|
[
"Format",
"unix",
"time",
"string",
"to",
"string"
] |
func DateS(ts string, format string) string {
i, _ := strconv.ParseInt(ts, 10, 64)
return Date(i, format)
}
|
[
"func",
"DateS",
"(",
"ts",
"string",
",",
"format",
"string",
")",
"string",
"{",
"i",
",",
"_",
":=",
"strconv",
".",
"ParseInt",
"(",
"ts",
",",
"10",
",",
"64",
")",
"\n",
"return",
"Date",
"(",
"i",
",",
"format",
")",
"\n",
"}"
] |
https://github.com/Unknwon/com/blob/0fed4efef7553eed2cd04624befccacda78bb8e2/time.go#L31-L34
| 0.943836
|
||
dop251/goja
|
8d6ee3d1661108ff8433016620abb64dfa6d9937
|
string_unicode.go
|
go
|
substring
|
(s unicodeString) (start, end int64)
|
[] |
func (s unicodeString) substring(start, end int64) valueString {
ss := s[start:end]
for _, c := range ss {
if c >= utf8.RuneSelf {
return unicodeString(ss)
}
}
as := make([]byte, end-start)
for i, c := range ss {
as[i] = byte(c)
}
return asciiString(as)
}
|
[
"func",
"(",
"s",
"unicodeString",
")",
"substring",
"(",
"start",
",",
"end",
"int64",
")",
"valueString",
"{",
"ss",
":=",
"s",
"[",
"start",
":",
"end",
"]",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"ss",
"{",
"if",
"c",
">=",
"utf8",
".",
"RuneSelf",
"{",
"return",
"unicodeString",
"(",
"ss",
")",
"\n",
"}",
"\n",
"}",
"\n",
"as",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"end",
"-",
"start",
")",
"\n",
"for",
"i",
",",
"c",
":=",
"range",
"ss",
"{",
"as",
"[",
"i",
"]",
"=",
"byte",
"(",
"c",
")",
"\n",
"}",
"\n",
"return",
"asciiString",
"(",
"as",
")",
"\n",
"}"
] |
https://github.com/dop251/goja/blob/8d6ee3d1661108ff8433016620abb64dfa6d9937/string_unicode.go#L201-L213
| 0.940897
|
||||
dop251/goja
|
8d6ee3d1661108ff8433016620abb64dfa6d9937
|
string_ascii.go
|
go
|
substring
|
(s asciiString) (start, end int64)
|
[] |
func (s asciiString) substring(start, end int64) valueString {
return asciiString(s[start:end])
}
|
[
"func",
"(",
"s",
"asciiString",
")",
"substring",
"(",
"start",
",",
"end",
"int64",
")",
"valueString",
"{",
"return",
"asciiString",
"(",
"s",
"[",
"start",
":",
"end",
"]",
")",
"\n",
"}"
] |
https://github.com/dop251/goja/blob/8d6ee3d1661108ff8433016620abb64dfa6d9937/string_ascii.go#L256-L258
| 0.940897
|
||||
tylertreat/BoomFilters
|
611b3dbe80e85df3a0a10a43997d4d5784e86245
|
topk.go
|
go
|
Elements
|
(t *TopK) ()
|
// Elements returns the top-k elements from lowest to highest frequency.
|
Elements returns the top-k elements from lowest to highest frequency.
|
[
"Elements",
"returns",
"the",
"top",
"-",
"k",
"elements",
"from",
"lowest",
"to",
"highest",
"frequency",
"."
] |
func (t *TopK) Elements() []*Element {
if t.elements.Len() == 0 {
return make([]*Element, 0)
}
elements := make(elementHeap, t.elements.Len())
copy(elements, *t.elements)
heap.Init(&elements)
topK := make([]*Element, 0, t.k)
for elements.Len() > 0 {
topK = append(topK, heap.Pop(&elements).(*Element))
}
return topK
}
|
[
"func",
"(",
"t",
"*",
"TopK",
")",
"Elements",
"(",
")",
"[",
"]",
"*",
"Element",
"{",
"if",
"t",
".",
"elements",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"return",
"make",
"(",
"[",
"]",
"*",
"Element",
",",
"0",
")",
"\n",
"}",
"\n\n",
"elements",
":=",
"make",
"(",
"elementHeap",
",",
"t",
".",
"elements",
".",
"Len",
"(",
")",
")",
"\n",
"copy",
"(",
"elements",
",",
"*",
"t",
".",
"elements",
")",
"\n",
"heap",
".",
"Init",
"(",
"&",
"elements",
")",
"\n",
"topK",
":=",
"make",
"(",
"[",
"]",
"*",
"Element",
",",
"0",
",",
"t",
".",
"k",
")",
"\n\n",
"for",
"elements",
".",
"Len",
"(",
")",
">",
"0",
"{",
"topK",
"=",
"append",
"(",
"topK",
",",
"heap",
".",
"Pop",
"(",
"&",
"elements",
")",
".",
"(",
"*",
"Element",
")",
")",
"\n",
"}",
"\n\n",
"return",
"topK",
"\n",
"}"
] |
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/topk.go#L70-L85
| 0.938857
|
||
zorkian/go-datadog-api
|
fcf4c3b6edfd28f3bf01965725f290489b10d1ec
|
datadog-accessors.go
|
go
|
GetHTML
|
(w *Widget) ()
|
// GetHTML returns the HTML field if non-nil, zero value otherwise.
|
GetHTML returns the HTML field if non-nil, zero value otherwise.
|
[
"GetHTML",
"returns",
"the",
"HTML",
"field",
"if",
"non",
"-",
"nil",
"zero",
"value",
"otherwise",
"."
] |
func (w *Widget) GetHTML() string {
if w == nil || w.HTML == nil {
return ""
}
return *w.HTML
}
|
[
"func",
"(",
"w",
"*",
"Widget",
")",
"GetHTML",
"(",
")",
"string",
"{",
"if",
"w",
"==",
"nil",
"||",
"w",
".",
"HTML",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"*",
"w",
".",
"HTML",
"\n",
"}"
] |
https://github.com/zorkian/go-datadog-api/blob/fcf4c3b6edfd28f3bf01965725f290489b10d1ec/datadog-accessors.go#L18618-L18623
| 0.931526
|
||
nanomsg/mangos-v1
|
b213a8e043f6541ad45f946a2e1c5d3617987985
|
compat/compat.go
|
go
|
SetRecvTimeout
|
(s *Socket) (d time.Duration)
|
// SetRecvTimeout sets a timeout for receive operations. The Recv()
// function will return an error if no message is received within this time.
|
SetRecvTimeout sets a timeout for receive operations. The Recv()
function will return an error if no message is received within this time.
|
[
"SetRecvTimeout",
"sets",
"a",
"timeout",
"for",
"receive",
"operations",
".",
"The",
"Recv",
"()",
"function",
"will",
"return",
"an",
"error",
"if",
"no",
"message",
"is",
"received",
"within",
"this",
"time",
"."
] |
func (s *Socket) SetRecvTimeout(d time.Duration) error {
s.rto = d
return nil
}
|
[
"func",
"(",
"s",
"*",
"Socket",
")",
"SetRecvTimeout",
"(",
"d",
"time",
".",
"Duration",
")",
"error",
"{",
"s",
".",
"rto",
"=",
"d",
"\n",
"return",
"nil",
"\n",
"}"
] |
https://github.com/nanomsg/mangos-v1/blob/b213a8e043f6541ad45f946a2e1c5d3617987985/compat/compat.go#L335-L338
| 0.931247
|
||
ugorji/go
|
1d7ab5c50b36701116070c4c612259f93c262367
|
codec/json.go
|
go
|
ReadArrayElem
|
(d *jsonDecDriver) ()
|
// For the ReadXXX methods below, we could just delegate to helper functions
// readContainerState(c containerState, xc uint8, check bool)
// - ReadArrayElem would become:
// readContainerState(containerArrayElem, ',', d.c != containerArrayStart)
//
// However, until mid-stack inlining comes in go1.11 which supports inlining of
// one-liners, we explicitly write them all 5 out to elide the extra func call.
//
// TODO: For Go 1.11, if inlined, consider consolidating these.
|
For the ReadXXX methods below, we could just delegate to helper functions
readContainerState(c containerState, xc uint8, check bool)
- ReadArrayElem would become:
readContainerState(containerArrayElem, ',', d.c != containerArrayStart)
However, until mid-stack inlining comes in go1.11 which supports inlining of
one-liners, we explicitly write them all 5 out to elide the extra func call.
TODO: For Go 1.11, if inlined, consider consolidating these.
|
[
"For",
"the",
"ReadXXX",
"methods",
"below",
"we",
"could",
"just",
"delegate",
"to",
"helper",
"functions",
"readContainerState",
"(",
"c",
"containerState",
"xc",
"uint8",
"check",
"bool",
")",
"-",
"ReadArrayElem",
"would",
"become",
":",
"readContainerState",
"(",
"containerArrayElem",
"d",
".",
"c",
"!",
"=",
"containerArrayStart",
")",
"However",
"until",
"mid",
"-",
"stack",
"inlining",
"comes",
"in",
"go1",
".",
"11",
"which",
"supports",
"inlining",
"of",
"one",
"-",
"liners",
"we",
"explicitly",
"write",
"them",
"all",
"5",
"out",
"to",
"elide",
"the",
"extra",
"func",
"call",
".",
"TODO",
":",
"For",
"Go",
"1",
".",
"11",
"if",
"inlined",
"consider",
"consolidating",
"these",
"."
] |
func (d *jsonDecDriver) ReadArrayElem() {
const xc uint8 = ','
if d.tok == 0 {
d.tok = d.r.skip(&jsonCharWhitespaceSet)
}
if d.c != containerArrayStart {
if d.tok != xc {
d.d.errorf("read array element - expect char '%c' but got char '%c'", xc, d.tok)
}
d.tok = 0
}
d.c = containerArrayElem
}
|
[
"func",
"(",
"d",
"*",
"jsonDecDriver",
")",
"ReadArrayElem",
"(",
")",
"{",
"const",
"xc",
"uint8",
"=",
"','",
"\n",
"if",
"d",
".",
"tok",
"==",
"0",
"{",
"d",
".",
"tok",
"=",
"d",
".",
"r",
".",
"skip",
"(",
"&",
"jsonCharWhitespaceSet",
")",
"\n",
"}",
"\n",
"if",
"d",
".",
"c",
"!=",
"containerArrayStart",
"{",
"if",
"d",
".",
"tok",
"!=",
"xc",
"{",
"d",
".",
"d",
".",
"errorf",
"(",
"\"",
"\"",
",",
"xc",
",",
"d",
".",
"tok",
")",
"\n",
"}",
"\n",
"d",
".",
"tok",
"=",
"0",
"\n",
"}",
"\n",
"d",
".",
"c",
"=",
"containerArrayElem",
"\n",
"}"
] |
https://github.com/ugorji/go/blob/1d7ab5c50b36701116070c4c612259f93c262367/codec/json.go#L678-L690
| 0.929632
|
||
vdobler/chart
|
6627804132c7c237061d1c8fd2554e3206daecb6
|
example/samplecharts.go
|
go
|
scatterTics
|
()
|
//
// Scatter plots with different tic/grid settings
//
|
Scatter plots with different tic/grid settings
|
[
"Scatter",
"plots",
"with",
"different",
"tic",
"/",
"grid",
"settings"
] |
func scatterTics() {
dumper := NewDumper("xstrip1", 3, 3, 400, 300)
defer dumper.Close()
p := chart.ScatterChart{Title: "Sample Scatter Chart"}
p.AddDataPair("Sample A", data10, data1, chart.PlotStylePoints, chart.Style{})
p.XRange.TicSetting.Delta = 5000
p.XRange.Label = "X - Value"
p.YRange.Label = "Y - Value"
dumper.Plot(&p)
p.XRange.TicSetting.Hide, p.YRange.TicSetting.Hide = true, true
dumper.Plot(&p)
p.YRange.TicSetting.Hide = false
p.XRange.TicSetting.Grid, p.YRange.TicSetting.Grid = chart.GridLines, chart.GridLines
dumper.Plot(&p)
p.XRange.TicSetting.Hide, p.YRange.TicSetting.Hide = false, false
p.XRange.TicSetting.Mirror, p.YRange.TicSetting.Mirror = 1, 2
dumper.Plot(&p)
c := chart.ScatterChart{Title: "Own tics"}
c.XRange.Fixed(0, 4*math.Pi, math.Pi)
c.YRange.Fixed(-1.25, 1.25, 0.5)
c.XRange.TicSetting.Format = func(f float64) string {
w := int(180*f/math.Pi + 0.5)
return fmt.Sprintf("%d°", w)
}
c.AddFunc("Sin(x)", func(x float64) float64 { return math.Sin(x) }, chart.PlotStyleLines,
chart.Style{Symbol: '@', LineWidth: 2, LineColor: color.NRGBA{0x00, 0x00, 0xcc, 0xff}, LineStyle: 0})
c.AddFunc("Cos(x)", func(x float64) float64 { return math.Cos(x) }, chart.PlotStyleLines,
chart.Style{Symbol: '%', LineWidth: 2, LineColor: color.NRGBA{0x00, 0xcc, 0x00, 0xff}, LineStyle: 0})
dumper.Plot(&c)
c.Title = "Tic Variants"
c.XRange.TicSetting.Tics = 1
c.YRange.TicSetting.Tics = 2
dumper.Plot(&c)
c.Title = "Blocked Grid"
c.XRange.TicSetting.Tics = 1
c.YRange.TicSetting.Tics = 1
c.XRange.TicSetting.Mirror, c.YRange.TicSetting.Mirror = 1, 1
c.XRange.TicSetting.Grid = chart.GridBlocks
c.YRange.TicSetting.Grid = chart.GridBlocks
dumper.Plot(&c)
}
|
[
"func",
"scatterTics",
"(",
")",
"{",
"dumper",
":=",
"NewDumper",
"(",
"\"",
"\"",
",",
"3",
",",
"3",
",",
"400",
",",
"300",
")",
"\n",
"defer",
"dumper",
".",
"Close",
"(",
")",
"\n\n",
"p",
":=",
"chart",
".",
"ScatterChart",
"{",
"Title",
":",
"\"",
"\"",
"}",
"\n",
"p",
".",
"AddDataPair",
"(",
"\"",
"\"",
",",
"data10",
",",
"data1",
",",
"chart",
".",
"PlotStylePoints",
",",
"chart",
".",
"Style",
"{",
"}",
")",
"\n",
"p",
".",
"XRange",
".",
"TicSetting",
".",
"Delta",
"=",
"5000",
"\n",
"p",
".",
"XRange",
".",
"Label",
"=",
"\"",
"\"",
"\n",
"p",
".",
"YRange",
".",
"Label",
"=",
"\"",
"\"",
"\n",
"dumper",
".",
"Plot",
"(",
"&",
"p",
")",
"\n\n",
"p",
".",
"XRange",
".",
"TicSetting",
".",
"Hide",
",",
"p",
".",
"YRange",
".",
"TicSetting",
".",
"Hide",
"=",
"true",
",",
"true",
"\n",
"dumper",
".",
"Plot",
"(",
"&",
"p",
")",
"\n\n",
"p",
".",
"YRange",
".",
"TicSetting",
".",
"Hide",
"=",
"false",
"\n",
"p",
".",
"XRange",
".",
"TicSetting",
".",
"Grid",
",",
"p",
".",
"YRange",
".",
"TicSetting",
".",
"Grid",
"=",
"chart",
".",
"GridLines",
",",
"chart",
".",
"GridLines",
"\n",
"dumper",
".",
"Plot",
"(",
"&",
"p",
")",
"\n\n",
"p",
".",
"XRange",
".",
"TicSetting",
".",
"Hide",
",",
"p",
".",
"YRange",
".",
"TicSetting",
".",
"Hide",
"=",
"false",
",",
"false",
"\n",
"p",
".",
"XRange",
".",
"TicSetting",
".",
"Mirror",
",",
"p",
".",
"YRange",
".",
"TicSetting",
".",
"Mirror",
"=",
"1",
",",
"2",
"\n",
"dumper",
".",
"Plot",
"(",
"&",
"p",
")",
"\n\n",
"c",
":=",
"chart",
".",
"ScatterChart",
"{",
"Title",
":",
"\"",
"\"",
"}",
"\n",
"c",
".",
"XRange",
".",
"Fixed",
"(",
"0",
",",
"4",
"*",
"math",
".",
"Pi",
",",
"math",
".",
"Pi",
")",
"\n",
"c",
".",
"YRange",
".",
"Fixed",
"(",
"-",
"1.25",
",",
"1.25",
",",
"0.5",
")",
"\n",
"c",
".",
"XRange",
".",
"TicSetting",
".",
"Format",
"=",
"func",
"(",
"f",
"float64",
")",
"string",
"{",
"w",
":=",
"int",
"(",
"180",
"*",
"f",
"/",
"math",
".",
"Pi",
"+",
"0.5",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
",",
" ",
")",
"",
"\n",
"}",
"\n",
"c",
".",
"AddFunc",
"(",
"\"",
"\"",
",",
"func",
"(",
"x",
"float64",
")",
"float64",
"{",
"return",
"math",
".",
"Sin",
"(",
"x",
")",
"}",
",",
"chart",
".",
"PlotStyleLines",
",",
"chart",
".",
"Style",
"{",
"Symbol",
":",
"'@'",
",",
"LineWidth",
":",
"2",
",",
"LineColor",
":",
"color",
".",
"NRGBA",
"{",
"0x00",
",",
"0x00",
",",
"0xcc",
",",
"0xff",
"}",
",",
"LineStyle",
":",
"0",
"}",
")",
"\n",
"c",
".",
"AddFunc",
"(",
"\"",
"\"",
",",
"func",
"(",
"x",
"float64",
")",
"float64",
"{",
"return",
"math",
".",
"Cos",
"(",
"x",
")",
"}",
",",
"chart",
".",
"PlotStyleLines",
",",
"chart",
".",
"Style",
"{",
"Symbol",
":",
"'%'",
",",
"LineWidth",
":",
"2",
",",
"LineColor",
":",
"color",
".",
"NRGBA",
"{",
"0x00",
",",
"0xcc",
",",
"0x00",
",",
"0xff",
"}",
",",
"LineStyle",
":",
"0",
"}",
")",
"\n",
"dumper",
".",
"Plot",
"(",
"&",
"c",
")",
"\n\n",
"c",
".",
"Title",
"=",
"\"",
"\"",
"\n",
"c",
".",
"XRange",
".",
"TicSetting",
".",
"Tics",
"=",
"1",
"\n",
"c",
".",
"YRange",
".",
"TicSetting",
".",
"Tics",
"=",
"2",
"\n",
"dumper",
".",
"Plot",
"(",
"&",
"c",
")",
"\n\n",
"c",
".",
"Title",
"=",
"\"",
"\"",
"\n",
"c",
".",
"XRange",
".",
"TicSetting",
".",
"Tics",
"=",
"1",
"\n",
"c",
".",
"YRange",
".",
"TicSetting",
".",
"Tics",
"=",
"1",
"\n",
"c",
".",
"XRange",
".",
"TicSetting",
".",
"Mirror",
",",
"c",
".",
"YRange",
".",
"TicSetting",
".",
"Mirror",
"=",
"1",
",",
"1",
"\n",
"c",
".",
"XRange",
".",
"TicSetting",
".",
"Grid",
"=",
"chart",
".",
"GridBlocks",
"\n",
"c",
".",
"YRange",
".",
"TicSetting",
".",
"Grid",
"=",
"chart",
".",
"GridBlocks",
"\n",
"dumper",
".",
"Plot",
"(",
"&",
"c",
")",
"\n",
"}"
] |
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/example/samplecharts.go#L186-L233
| 0.882156
|
||
iron-io/functions
|
d59d7d1c40b2ff26b1afee31bde64df444e96525
|
fn/app/app.go
|
go
|
parseArgs
|
(c *cli.Context)
|
[] |
func parseArgs(c *cli.Context) ([]string, []string) {
args := strings.Split(c.Command.ArgsUsage, " ")
var reqArgs []string
var optArgs []string
for _, arg := range args {
if strings.HasPrefix(arg, "[") {
optArgs = append(optArgs, arg)
} else if strings.Trim(arg, " ") != "" {
reqArgs = append(reqArgs, arg)
}
}
return reqArgs, optArgs
}
|
[
"func",
"parseArgs",
"(",
"c",
"*",
"cli",
".",
"Context",
")",
"(",
"[",
"]",
"string",
",",
"[",
"]",
"string",
")",
"{",
"args",
":=",
"strings",
".",
"Split",
"(",
"c",
".",
"Command",
".",
"ArgsUsage",
",",
"\"",
"\"",
")",
"\n",
"var",
"reqArgs",
"[",
"]",
"string",
"\n",
"var",
"optArgs",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"arg",
":=",
"range",
"args",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"arg",
",",
"\"",
"\"",
")",
"{",
"optArgs",
"=",
"append",
"(",
"optArgs",
",",
"arg",
")",
"\n",
"}",
"else",
"if",
"strings",
".",
"Trim",
"(",
"arg",
",",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"reqArgs",
"=",
"append",
"(",
"reqArgs",
",",
"arg",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"reqArgs",
",",
"optArgs",
"\n",
"}"
] |
https://github.com/iron-io/functions/blob/d59d7d1c40b2ff26b1afee31bde64df444e96525/fn/app/app.go#L89-L101
| 0.84655
|
||||
yuin/gopher-lua
|
8bfc7677f583b35a5663a9dd934c08f3b5774bbb
|
iolib.go
|
go
|
AbandonReadBuffer
|
(file *lFile) ()
|
[] |
func (file *lFile) AbandonReadBuffer() error {
if file.Type() == lFileFile && file.reader != nil {
_, err := file.fp.Seek(-int64(file.reader.Buffered()), 1)
if err != nil {
return err
}
file.reader = bufio.NewReaderSize(file.fp, fileDefaultReadBuffer)
}
return nil
}
|
[
"func",
"(",
"file",
"*",
"lFile",
")",
"AbandonReadBuffer",
"(",
")",
"error",
"{",
"if",
"file",
".",
"Type",
"(",
")",
"==",
"lFileFile",
"&&",
"file",
".",
"reader",
"!=",
"nil",
"{",
"_",
",",
"err",
":=",
"file",
".",
"fp",
".",
"Seek",
"(",
"-",
"int64",
"(",
"file",
".",
"reader",
".",
"Buffered",
"(",
")",
")",
",",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"file",
".",
"reader",
"=",
"bufio",
".",
"NewReaderSize",
"(",
"file",
".",
"fp",
",",
"fileDefaultReadBuffer",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
https://github.com/yuin/gopher-lua/blob/8bfc7677f583b35a5663a9dd934c08f3b5774bbb/iolib.go#L131-L140
| 0.790371
|
||||
wcharczuk/go-chart
|
9852fce5a172598e72d16f4306f0f17a53d94eb4
|
matrix/matrix.go
|
go
|
Multiply
|
(m *Matrix) (m2 *Matrix)
|
// math operations
// Multiply multiplies two matrices.
|
math operations
Multiply multiplies two matrices.
|
[
"math",
"operations",
"Multiply",
"multiplies",
"two",
"matrices",
"."
] |
func (m *Matrix) Multiply(m2 *Matrix) (m3 *Matrix, err error) {
if m.stride*m2.stride != len(m2.elements) {
return nil, ErrDimensionMismatch
}
m3 = &Matrix{epsilon: m.epsilon, stride: m2.stride, elements: make([]float64, (len(m.elements)/m.stride)*m2.stride)}
for m1c0, m3x := 0, 0; m1c0 < len(m.elements); m1c0 += m.stride {
for m2r0 := 0; m2r0 < m2.stride; m2r0++ {
for m1x, m2x := m1c0, m2r0; m2x < len(m2.elements); m2x += m2.stride {
m3.elements[m3x] += m.elements[m1x] * m2.elements[m2x]
m1x++
}
m3x++
}
}
return
}
|
[
"func",
"(",
"m",
"*",
"Matrix",
")",
"Multiply",
"(",
"m2",
"*",
"Matrix",
")",
"(",
"m3",
"*",
"Matrix",
",",
"err",
"error",
")",
"{",
"if",
"m",
".",
"stride",
"*",
"m2",
".",
"stride",
"!=",
"len",
"(",
"m2",
".",
"elements",
")",
"{",
"return",
"nil",
",",
"ErrDimensionMismatch",
"\n",
"}",
"\n\n",
"m3",
"=",
"&",
"Matrix",
"{",
"epsilon",
":",
"m",
".",
"epsilon",
",",
"stride",
":",
"m2",
".",
"stride",
",",
"elements",
":",
"make",
"(",
"[",
"]",
"float64",
",",
"(",
"len",
"(",
"m",
".",
"elements",
")",
"/",
"m",
".",
"stride",
")",
"*",
"m2",
".",
"stride",
")",
"}",
"\n",
"for",
"m1c0",
",",
"m3x",
":=",
"0",
",",
"0",
";",
"m1c0",
"<",
"len",
"(",
"m",
".",
"elements",
")",
";",
"m1c0",
"+=",
"m",
".",
"stride",
"{",
"for",
"m2r0",
":=",
"0",
";",
"m2r0",
"<",
"m2",
".",
"stride",
";",
"m2r0",
"++",
"{",
"for",
"m1x",
",",
"m2x",
":=",
"m1c0",
",",
"m2r0",
";",
"m2x",
"<",
"len",
"(",
"m2",
".",
"elements",
")",
";",
"m2x",
"+=",
"m2",
".",
"stride",
"{",
"m3",
".",
"elements",
"[",
"m3x",
"]",
"+=",
"m",
".",
"elements",
"[",
"m1x",
"]",
"*",
"m2",
".",
"elements",
"[",
"m2x",
"]",
"\n",
"m1x",
"++",
"\n",
"}",
"\n",
"m3x",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
https://github.com/wcharczuk/go-chart/blob/9852fce5a172598e72d16f4306f0f17a53d94eb4/matrix/matrix.go#L371-L387
| 0.788856
|
||
wcharczuk/go-chart
|
9852fce5a172598e72d16f4306f0f17a53d94eb4
|
util/file_util.go
|
go
|
ReadByLines
|
(fu fileUtil) (filePath string, handler func(line string) error)
|
// ReadByLines reads a file and calls the handler for each line.
|
ReadByLines reads a file and calls the handler for each line.
|
[
"ReadByLines",
"reads",
"a",
"file",
"and",
"calls",
"the",
"handler",
"for",
"each",
"line",
"."
] |
func (fu fileUtil) ReadByLines(filePath string, handler func(line string) error) error {
var f *os.File
var err error
if f, err = os.Open(filePath); err == nil {
defer f.Close()
var line string
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line = scanner.Text()
err = handler(line)
if err != nil {
return err
}
}
}
return err
}
|
[
"func",
"(",
"fu",
"fileUtil",
")",
"ReadByLines",
"(",
"filePath",
"string",
",",
"handler",
"func",
"(",
"line",
"string",
")",
"error",
")",
"error",
"{",
"var",
"f",
"*",
"os",
".",
"File",
"\n",
"var",
"err",
"error",
"\n",
"if",
"f",
",",
"err",
"=",
"os",
".",
"Open",
"(",
"filePath",
")",
";",
"err",
"==",
"nil",
"{",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"var",
"line",
"string",
"\n",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"f",
")",
"\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"{",
"line",
"=",
"scanner",
".",
"Text",
"(",
")",
"\n",
"err",
"=",
"handler",
"(",
"line",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n\n",
"}"
] |
https://github.com/wcharczuk/go-chart/blob/9852fce5a172598e72d16f4306f0f17a53d94eb4/util/file_util.go#L17-L34
| 0.788856
|
||
hoisie/web
|
a498c022b2c0babab2bf9c0400754190b24c8c39
|
helpers.go
|
go
|
Urlencode
|
(data map[string]string)
|
// Urlencode is a helper method that converts a map into URL-encoded form data.
// It is a useful when constructing HTTP POST requests.
|
Urlencode is a helper method that converts a map into URL-encoded form data.
It is a useful when constructing HTTP POST requests.
|
[
"Urlencode",
"is",
"a",
"helper",
"method",
"that",
"converts",
"a",
"map",
"into",
"URL",
"-",
"encoded",
"form",
"data",
".",
"It",
"is",
"a",
"useful",
"when",
"constructing",
"HTTP",
"POST",
"requests",
"."
] |
func Urlencode(data map[string]string) string {
var buf bytes.Buffer
for k, v := range data {
buf.WriteString(url.QueryEscape(k))
buf.WriteByte('=')
buf.WriteString(url.QueryEscape(v))
buf.WriteByte('&')
}
s := buf.String()
return s[0 : len(s)-1]
}
|
[
"func",
"Urlencode",
"(",
"data",
"map",
"[",
"string",
"]",
"string",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"data",
"{",
"buf",
".",
"WriteString",
"(",
"url",
".",
"QueryEscape",
"(",
"k",
")",
")",
"\n",
"buf",
".",
"WriteByte",
"(",
"'='",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"url",
".",
"QueryEscape",
"(",
"v",
")",
")",
"\n",
"buf",
".",
"WriteByte",
"(",
"'&'",
")",
"\n",
"}",
"\n",
"s",
":=",
"buf",
".",
"String",
"(",
")",
"\n",
"return",
"s",
"[",
"0",
":",
"len",
"(",
"s",
")",
"-",
"1",
"]",
"\n",
"}"
] |
https://github.com/hoisie/web/blob/a498c022b2c0babab2bf9c0400754190b24c8c39/helpers.go#L47-L57
| 0.785138
|
||
mmcdole/gofeed
|
0e68beaf6fdf215bd1fe42a09f6de292c7032359
|
internal/shared/xmlbase.go
|
go
|
ResolveHTML
|
(b *XMLBase) (relHTML string)
|
// Transforms html by resolving any relative URIs in attributes
// if an error occurs during parsing or serialization, then the original string
// is returned along with the error.
|
Transforms html by resolving any relative URIs in attributes
if an error occurs during parsing or serialization, then the original string
is returned along with the error.
|
[
"Transforms",
"html",
"by",
"resolving",
"any",
"relative",
"URIs",
"in",
"attributes",
"if",
"an",
"error",
"occurs",
"during",
"parsing",
"or",
"serialization",
"then",
"the",
"original",
"string",
"is",
"returned",
"along",
"with",
"the",
"error",
"."
] |
func (b *XMLBase) ResolveHTML(relHTML string) (string, error) {
if b.CurrentBase() == "" {
return relHTML, nil
}
htmlReader := strings.NewReader(relHTML)
doc, err := html.Parse(htmlReader)
if err != nil {
return relHTML, err
}
var visit func(*html.Node)
// recursively traverse HTML resolving any relative URIs in attributes
visit = func(n *html.Node) {
if n.Type == html.ElementNode {
for i, a := range n.Attr {
if htmlURIAttrs[a.Key] {
absVal, err := b.ResolveURL(a.Val)
if err == nil {
n.Attr[i].Val = absVal
}
break
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
visit(c)
}
}
visit(doc)
var w bytes.Buffer
err = html.Render(&w, doc)
if err != nil {
return relHTML, err
}
// html.Render() always writes a complete html5 document, so strip the html
// and body tags
absHTML := w.String()
absHTML = strings.TrimPrefix(absHTML, "<html><head></head><body>")
absHTML = strings.TrimSuffix(absHTML, "</body></html>")
return absHTML, err
}
|
[
"func",
"(",
"b",
"*",
"XMLBase",
")",
"ResolveHTML",
"(",
"relHTML",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"b",
".",
"CurrentBase",
"(",
")",
"==",
"\"",
"\"",
"{",
"return",
"relHTML",
",",
"nil",
"\n",
"}",
"\n\n",
"htmlReader",
":=",
"strings",
".",
"NewReader",
"(",
"relHTML",
")",
"\n\n",
"doc",
",",
"err",
":=",
"html",
".",
"Parse",
"(",
"htmlReader",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"relHTML",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"visit",
"func",
"(",
"*",
"html",
".",
"Node",
")",
"\n\n",
"// recursively traverse HTML resolving any relative URIs in attributes",
"visit",
"=",
"func",
"(",
"n",
"*",
"html",
".",
"Node",
")",
"{",
"if",
"n",
".",
"Type",
"==",
"html",
".",
"ElementNode",
"{",
"for",
"i",
",",
"a",
":=",
"range",
"n",
".",
"Attr",
"{",
"if",
"htmlURIAttrs",
"[",
"a",
".",
"Key",
"]",
"{",
"absVal",
",",
"err",
":=",
"b",
".",
"ResolveURL",
"(",
"a",
".",
"Val",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"n",
".",
"Attr",
"[",
"i",
"]",
".",
"Val",
"=",
"absVal",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"c",
":=",
"n",
".",
"FirstChild",
";",
"c",
"!=",
"nil",
";",
"c",
"=",
"c",
".",
"NextSibling",
"{",
"visit",
"(",
"c",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"visit",
"(",
"doc",
")",
"\n",
"var",
"w",
"bytes",
".",
"Buffer",
"\n",
"err",
"=",
"html",
".",
"Render",
"(",
"&",
"w",
",",
"doc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"relHTML",
",",
"err",
"\n",
"}",
"\n\n",
"// html.Render() always writes a complete html5 document, so strip the html",
"// and body tags",
"absHTML",
":=",
"w",
".",
"String",
"(",
")",
"\n",
"absHTML",
"=",
"strings",
".",
"TrimPrefix",
"(",
"absHTML",
",",
"\"",
"\"",
")",
"\n",
"absHTML",
"=",
"strings",
".",
"TrimSuffix",
"(",
"absHTML",
",",
"\"",
"\"",
")",
"\n\n",
"return",
"absHTML",
",",
"err",
"\n",
"}"
] |
https://github.com/mmcdole/gofeed/blob/0e68beaf6fdf215bd1fe42a09f6de292c7032359/internal/shared/xmlbase.go#L212-L258
| 0.782623
|
||
google/go-genproto
|
54afdca5d873f7b529e2ce3def1a99df16feda90
|
googleapis/cloud/automl/v1beta1/classification.pb.go
|
go
|
XXX_Unmarshal
|
(m *ClassificationEvaluationMetrics_ConfusionMatrix) (b []byte)
|
[] |
func (m *ClassificationEvaluationMetrics_ConfusionMatrix) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_ClassificationEvaluationMetrics_ConfusionMatrix.Unmarshal(m, b)
}
|
[
"func",
"(",
"m",
"*",
"ClassificationEvaluationMetrics_ConfusionMatrix",
")",
"XXX_Unmarshal",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"return",
"xxx_messageInfo_ClassificationEvaluationMetrics_ConfusionMatrix",
".",
"Unmarshal",
"(",
"m",
",",
"b",
")",
"\n",
"}"
] |
https://github.com/google/go-genproto/blob/54afdca5d873f7b529e2ce3def1a99df16feda90/googleapis/cloud/automl/v1beta1/classification.pb.go#L486-L488
| 0.780798
|
||||
google/go-genproto
|
54afdca5d873f7b529e2ce3def1a99df16feda90
|
googleapis/ads/googleads/v1/common/policy.pb.go
|
go
|
GetWebsites
|
(m *PolicyTopicEvidence_WebsiteList) ()
|
[] |
func (m *PolicyTopicEvidence_WebsiteList) GetWebsites() []*wrappers.StringValue {
if m != nil {
return m.Websites
}
return nil
}
|
[
"func",
"(",
"m",
"*",
"PolicyTopicEvidence_WebsiteList",
")",
"GetWebsites",
"(",
")",
"[",
"]",
"*",
"wrappers",
".",
"StringValue",
"{",
"if",
"m",
"!=",
"nil",
"{",
"return",
"m",
".",
"Websites",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
https://github.com/google/go-genproto/blob/54afdca5d873f7b529e2ce3def1a99df16feda90/googleapis/ads/googleads/v1/common/policy.pb.go#L587-L592
| 0.780798
|
||||
google/go-genproto
|
54afdca5d873f7b529e2ce3def1a99df16feda90
|
googleapis/cloud/talent/v4beta1/filters.pb.go
|
go
|
GetEndDate
|
(m *ApplicationDateFilter) ()
|
[] |
func (m *ApplicationDateFilter) GetEndDate() *date.Date {
if m != nil {
return m.EndDate
}
return nil
}
|
[
"func",
"(",
"m",
"*",
"ApplicationDateFilter",
")",
"GetEndDate",
"(",
")",
"*",
"date",
".",
"Date",
"{",
"if",
"m",
"!=",
"nil",
"{",
"return",
"m",
".",
"EndDate",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
https://github.com/google/go-genproto/blob/54afdca5d873f7b529e2ce3def1a99df16feda90/googleapis/cloud/talent/v4beta1/filters.pb.go#L1527-L1532
| 0.780798
|
||||
logrusorgru/aurora
|
cea283e61946ad8227cc02a24201407a2c9e5182
|
wrap.go
|
go
|
Reverse
|
(arg interface{})
|
// Reverse video, swap foreground and
// background colors (7).
|
Reverse video, swap foreground and
background colors (7).
|
[
"Reverse",
"video",
"swap",
"foreground",
"and",
"background",
"colors",
"(",
"7",
")",
"."
] |
func Reverse(arg interface{}) Value {
if val, ok := arg.(Value); ok {
return val.Reverse()
}
return value{value: arg, color: ReverseFm}
}
|
[
"func",
"Reverse",
"(",
"arg",
"interface",
"{",
"}",
")",
"Value",
"{",
"if",
"val",
",",
"ok",
":=",
"arg",
".",
"(",
"Value",
")",
";",
"ok",
"{",
"return",
"val",
".",
"Reverse",
"(",
")",
"\n",
"}",
"\n",
"return",
"value",
"{",
"value",
":",
"arg",
",",
"color",
":",
"ReverseFm",
"}",
"\n",
"}"
] |
https://github.com/logrusorgru/aurora/blob/cea283e61946ad8227cc02a24201407a2c9e5182/wrap.go#L138-L143
| 0.780096
|
||
kubicorn/kubicorn
|
c4a4b80994b4333709c0f8164faabd801866b986
|
cloud/amazon/public/resources/securitygroup.go
|
go
|
strToInt
|
(s string)
|
[] |
func strToInt(s string) (int, error) {
i, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("failed to convert string to int err: %#v", err)
}
return i, nil
}
|
[
"func",
"strToInt",
"(",
"s",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"i",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"i",
",",
"nil",
"\n",
"}"
] |
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/amazon/public/resources/securitygroup.go#L375-L381
| 0.779709
|
||||
Microsoft/go-winio
|
3fe4fa31662f6ede2353d913e93907b8e096e0b6
|
pkg/etw/fieldopt.go
|
go
|
Uint8Array
|
(name string, values []uint8)
|
// Uint8Array adds an array of uint8 to the event.
|
Uint8Array adds an array of uint8 to the event.
|
[
"Uint8Array",
"adds",
"an",
"array",
"of",
"uint8",
"to",
"the",
"event",
"."
] |
func Uint8Array(name string, values []uint8) FieldOpt {
return func(em *eventMetadata, ed *eventData) {
em.writeArray(name, inTypeUint8, outTypeDefault, 0)
ed.writeUint16(uint16(len(values)))
for _, v := range values {
ed.writeUint8(v)
}
}
}
|
[
"func",
"Uint8Array",
"(",
"name",
"string",
",",
"values",
"[",
"]",
"uint8",
")",
"FieldOpt",
"{",
"return",
"func",
"(",
"em",
"*",
"eventMetadata",
",",
"ed",
"*",
"eventData",
")",
"{",
"em",
".",
"writeArray",
"(",
"name",
",",
"inTypeUint8",
",",
"outTypeDefault",
",",
"0",
")",
"\n",
"ed",
".",
"writeUint16",
"(",
"uint16",
"(",
"len",
"(",
"values",
")",
")",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"values",
"{",
"ed",
".",
"writeUint8",
"(",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
https://github.com/Microsoft/go-winio/blob/3fe4fa31662f6ede2353d913e93907b8e096e0b6/pkg/etw/fieldopt.go#L222-L230
| 0.776828
|
||
Microsoft/go-winio
|
3fe4fa31662f6ede2353d913e93907b8e096e0b6
|
wim/wim.go
|
go
|
Time
|
(ft *Filetime) ()
|
// Time returns the time as time.Time.
|
Time returns the time as time.Time.
|
[
"Time",
"returns",
"the",
"time",
"as",
"time",
".",
"Time",
"."
] |
func (ft *Filetime) Time() time.Time {
// 100-nanosecond intervals since January 1, 1601
nsec := int64(ft.HighDateTime)<<32 + int64(ft.LowDateTime)
// change starting time to the Epoch (00:00:00 UTC, January 1, 1970)
nsec -= 116444736000000000
// convert into nanoseconds
nsec *= 100
return time.Unix(0, nsec)
}
|
[
"func",
"(",
"ft",
"*",
"Filetime",
")",
"Time",
"(",
")",
"time",
".",
"Time",
"{",
"// 100-nanosecond intervals since January 1, 1601",
"nsec",
":=",
"int64",
"(",
"ft",
".",
"HighDateTime",
")",
"<<",
"32",
"+",
"int64",
"(",
"ft",
".",
"LowDateTime",
")",
"\n",
"// change starting time to the Epoch (00:00:00 UTC, January 1, 1970)",
"nsec",
"-=",
"116444736000000000",
"\n",
"// convert into nanoseconds",
"nsec",
"*=",
"100",
"\n",
"return",
"time",
".",
"Unix",
"(",
"0",
",",
"nsec",
")",
"\n",
"}"
] |
https://github.com/Microsoft/go-winio/blob/3fe4fa31662f6ede2353d913e93907b8e096e0b6/wim/wim.go#L199-L207
| 0.776828
|
||
twpayne/go-geom
|
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
|
xy/cga.go
|
go
|
DistanceFromPointToLineString
|
(layout geom.Layout, p geom.Coord, line []float64)
|
// DistanceFromPointToLineString computes the distance from a point to a sequence of line segments.
//
// Param p - a point
// Param line - a sequence of contiguous line segments defined by their vertices
|
DistanceFromPointToLineString computes the distance from a point to a sequence of line segments.
Param p - a point
Param line - a sequence of contiguous line segments defined by their vertices
|
[
"DistanceFromPointToLineString",
"computes",
"the",
"distance",
"from",
"a",
"point",
"to",
"a",
"sequence",
"of",
"line",
"segments",
".",
"Param",
"p",
"-",
"a",
"point",
"Param",
"line",
"-",
"a",
"sequence",
"of",
"contiguous",
"line",
"segments",
"defined",
"by",
"their",
"vertices"
] |
func DistanceFromPointToLineString(layout geom.Layout, p geom.Coord, line []float64) float64 {
if len(line) < 2 {
panic(fmt.Sprintf("Line array must contain at least one vertex: %v", line))
}
// this handles the case of length = 1
firstPoint := line[0:2]
minDistance := internal.Distance2D(p, firstPoint)
stride := layout.Stride()
for i := 0; i < len(line)-stride; i += stride {
point1 := geom.Coord(line[i : i+2])
point2 := geom.Coord(line[i+stride : i+stride+2])
dist := DistanceFromPointToLine(p, point1, point2)
if dist < minDistance {
minDistance = dist
}
}
return minDistance
}
|
[
"func",
"DistanceFromPointToLineString",
"(",
"layout",
"geom",
".",
"Layout",
",",
"p",
"geom",
".",
"Coord",
",",
"line",
"[",
"]",
"float64",
")",
"float64",
"{",
"if",
"len",
"(",
"line",
")",
"<",
"2",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"line",
")",
")",
"\n",
"}",
"\n",
"// this handles the case of length = 1",
"firstPoint",
":=",
"line",
"[",
"0",
":",
"2",
"]",
"\n",
"minDistance",
":=",
"internal",
".",
"Distance2D",
"(",
"p",
",",
"firstPoint",
")",
"\n",
"stride",
":=",
"layout",
".",
"Stride",
"(",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"line",
")",
"-",
"stride",
";",
"i",
"+=",
"stride",
"{",
"point1",
":=",
"geom",
".",
"Coord",
"(",
"line",
"[",
"i",
":",
"i",
"+",
"2",
"]",
")",
"\n",
"point2",
":=",
"geom",
".",
"Coord",
"(",
"line",
"[",
"i",
"+",
"stride",
":",
"i",
"+",
"stride",
"+",
"2",
"]",
")",
"\n",
"dist",
":=",
"DistanceFromPointToLine",
"(",
"p",
",",
"point1",
",",
"point2",
")",
"\n",
"if",
"dist",
"<",
"minDistance",
"{",
"minDistance",
"=",
"dist",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"minDistance",
"\n",
"}"
] |
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/cga.go#L231-L248
| 0.77303
|
||
denverdino/aliyungo
|
611ead8a6fedf409d6512b6e4f44f3f1cbc65755
|
util/util.go
|
go
|
PrettyJson
|
(object interface{})
|
[] |
func PrettyJson(object interface{}) string {
b, err := json.MarshalIndent(object, "", " ")
if err != nil {
fmt.Printf("ERROR: PrettyJson, %v\n %s\n", err, b)
}
return string(b)
}
|
[
"func",
"PrettyJson",
"(",
"object",
"interface",
"{",
"}",
")",
"string",
"{",
"b",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"object",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\\n",
"\"",
",",
"err",
",",
"b",
")",
"\n",
"}",
"\n",
"return",
"string",
"(",
"b",
")",
"\n",
"}"
] |
https://github.com/denverdino/aliyungo/blob/611ead8a6fedf409d6512b6e4f44f3f1cbc65755/util/util.go#L179-L185
| 0.771841
|
||||
JamesClonk/vultr
|
fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91
|
cmd/commands.go
|
go
|
RegisterCommands
|
(c *CLI) ()
|
// RegisterCommands registers all CLI commands
|
RegisterCommands registers all CLI commands
|
[
"RegisterCommands",
"registers",
"all",
"CLI",
"commands"
] |
func (c *CLI) RegisterCommands() {
// backup
c.Command("backup", "see most recent backups", func(cmd *cli.Cmd) {
cmd.Command("list", "lists backups", backupsList)
})
// dns
c.Command("dns", "modify DNS", func(cmd *cli.Cmd) {
cmd.Command("domain", "show and change DNS domains", func(cmd *cli.Cmd) {
cmd.Command("create", "create a DNS domain", dnsDomainCreate)
cmd.Command("delete", "delete a DNS domain", dnsDomainDelete)
cmd.Command("list", "list all DNS domains", dnsDomainList)
})
cmd.Command("record", "show and change DNS records", func(cmd *cli.Cmd) {
cmd.Command("create", "create a DNS record", dnsRecordCreate)
cmd.Command("update", "update a DNS record", dnsRecordUpdate)
cmd.Command("delete", "delete a DNS record", dnsRecordDelete)
cmd.Command("list", "list all DNS records", dnsRecordList)
})
})
// firewall
c.Command("firewall", "modify firewall groups and rules", func(cmd *cli.Cmd) {
cmd.Command("group", "show and change firewall groups", func(cmd *cli.Cmd) {
cmd.Command("create", "create a firewall group", firewallGroupCreate)
cmd.Command("delete", "delete a firewall group", firewallGroupDelete)
cmd.Command("set-description", "set firewall group description", firewallGroupSetDescription)
cmd.Command("list", "list all firewall groups", firewallGroupList)
})
cmd.Command("rule", "show and change firewall rules", func(cmd *cli.Cmd) {
cmd.Command("create", "create a firewall rule", firewallRuleCreate)
cmd.Command("delete", "delete a firewall rule", firewallRuleDelete)
cmd.Command("list", "list all firewall rules in a group", firewallRuleList)
})
})
// info
c.Command("info", "display account information", accountInfo)
// iso
c.Command("iso", "list all ISOs currently available on account", isoList)
// os
c.Command("os", "list all available operating systems", osList)
// applications
c.Command("apps", "list all available applications", appList)
// plans
c.Command("plans", "list all active plans", planList)
// regions
c.Command("regions", "list all active regions", regionList)
// sshkeys
c.Command("sshkey", "modify SSH public keys", func(cmd *cli.Cmd) {
cmd.Command("create", "upload and add new SSH public key", sshKeysCreate)
cmd.Command("update", "update an existing SSH public key", sshKeysUpdate)
cmd.Command("delete", "remove an existing SSH public key", sshKeysDelete)
cmd.Command("list", "list all existing SSH public keys", sshKeysList)
})
c.Command("sshkeys", "list all existing SSH public keys", sshKeysList)
// ssh
c.Command("ssh", "ssh into a virtual machine", sshServer)
// servers
c.Command("server", "modify virtual machines", func(cmd *cli.Cmd) {
cmd.Command("backup", "get and set backup schedules", func(cmd *cli.Cmd) {
cmd.Command("get", "get a backup schedule", serversBackupGetSchedule)
cmd.Command("set", "set a backup schedule", serversBackupSetSchedule)
})
cmd.Command("create", "create a new virtual machine", serversCreate)
cmd.Command("rename", "rename a virtual machine", serversRename)
cmd.Command("tag", "tag a virtual machine", serversTag)
cmd.Command("start", "start a virtual machine (restart if already running)", serversStart)
cmd.Command("halt", "halt a virtual machine (hard power off)", serversHalt)
cmd.Command("reboot", "reboot a virtual machine (hard reboot)", serversReboot)
cmd.Command("reinstall", "reinstall OS on a virtual machine (all data will be lost)", serversReinstall)
cmd.Command("os", "show and change OS on a virtual machine", func(cmd *cli.Cmd) {
cmd.Command("change", "change operating system of virtual machine (all data will be lost)", serversChangeOS)
cmd.Command("list", "show a list of operating systems to which can be changed to", serversListOS)
})
cmd.Command("app", "show and change application on a virtual machine", func(cmd *cli.Cmd) {
cmd.Command("change", "change application of virtual machine (all data will be lost)", serversChangeApplication)
cmd.Command("list", "show a list of available applications to which can be changed to", serversListApplications)
cmd.Command("info", "retrieves application information of virtual machine", serversAppInfo)
})
cmd.Command("iso", "attach/detach ISO of a virtual machine", func(cmd *cli.Cmd) {
cmd.Command("attach", "attach ISO to a virtual machine (server will hard reboot)", serversAttachISO)
cmd.Command("detach", "detach ISO from a virtual machine (server will hard reboot)", serversDetachISO)
cmd.Command("status", "show status of ISO attached to a virtual machine", serversStatusISO)
})
cmd.Command("restore", "restore from backup/snapshot", func(cmd *cli.Cmd) {
cmd.Command("backup", "restore from backup (any data already on the server will be lost)", serversRestoreBackup)
cmd.Command("snapshot", "restore from snapshot (any data already on the server will be lost)", serversRestoreSnapshot)
})
cmd.Command("delete", "delete a virtual machine", serversDelete)
cmd.Command("bandwidth", "list bandwidth used by a virtual machine", serversBandwidth)
cmd.Command("list", "list all active or pending virtual machines on current account", serversList)
cmd.Command("show", "show detailed information of a virtual machine", serversShow)
// ip information
cmd.Command("list-ipv4", "list IPv4 information of a virtual machine", ipv4List)
cmd.Command("create-ipv4", "add a new IPv4 address to a virtual machine", ipv4Create)
cmd.Command("delete-ipv4", "remove IPv4 address from a virtual machine", ipv4Delete)
cmd.Command("list-ipv6", "list IPv6 information of a virtual machine", ipv6List)
// reverse dns
cmd.Command("reverse-dns", "modify reverse DNS entries", func(cmd *cli.Cmd) {
cmd.Command("default-ipv4", "reset IPv4 reverse DNS entry back to original setting", reverseIpv4Default)
cmd.Command("set-ipv4", "set IPv4 reverse DNS entry", reverseIpv4Set)
cmd.Command("set-ipv6", "set IPv6 reverse DNS entry", reverseIpv6Set)
cmd.Command("delete-ipv6", "delete IPv6 reverse DNS entry", reverseIpv6Delete)
cmd.Command("list-ipv6", "list IPv6 reverse DNS entries of a virtual machine", reverseIpv6List)
})
// firewall groups
cmd.Command("set-firewall-group", "set firewall group of a virtual machine", serversSetFirewallGroup)
cmd.Command("unset-firewall-group", "remove virtual machine from firewall group", serversUnsetFirewallGroup)
// upgrade plans
cmd.Command("upgrade-plan", "upgrade plan of a virtual machine", func(cmd *cli.Cmd) {
cmd.Command("change", "upgrade plan of virtual machine (Note: Downgrading is currently not supported. Shrinking the hard disk is not possible without risking data loss.)", serversChangePlan)
cmd.Command("list", "show a list of VPSPLANIDs to which a virtual machine can be upgraded to", serversListUpgradePlans)
})
})
c.Command("servers", "list all active or pending virtual machines on current account", serversList)
// block storage
c.Command("storage", "modify block storage", func(cmd *cli.Cmd) {
cmd.Command("create", "create new block storage", blockStorageCreate)
cmd.Command("resize", "resize existing block storage", blockStorageResize)
cmd.Command("label", "rename existing block storage", blockStorageLabel)
cmd.Command("attach", "attach block storage to virtual machine", blockStorageAttach)
cmd.Command("detach", "detach block storage from virtual machine", blockStorageDetach)
cmd.Command("delete", "remove block storage", blockStorageDelete)
cmd.Command("list", "list all block storage", blockStorageList)
})
c.Command("storages", "list all block storage", blockStorageList)
// snapshots
c.Command("snapshot", "modify snapshots", func(cmd *cli.Cmd) {
cmd.Command("create", "create a snapshot from an existing virtual machine", snapshotsCreate)
cmd.Command("delete", "delete a snapshot", snapshotsDelete)
cmd.Command("list", "list all snapshots on current account", snapshotsList)
})
c.Command("snapshots", "list all snapshots on current account", snapshotsList)
// startup scripts
c.Command("script", "modify startup scripts", func(cmd *cli.Cmd) {
cmd.Command("create", "create a new startup script", scriptsCreate)
cmd.Command("update", "update an existing startup script", scriptsUpdate)
cmd.Command("delete", "remove an existing startup script", scriptsDelete)
cmd.Command("list", "list all startup scripts on current account", scriptsList)
cmd.Command("show", "show complete startup script", scriptsShow)
})
c.Command("scripts", "list all startup scripts on current account", scriptsList)
// reserved ips
c.Command("reservedip", "modify reserved IPs", func(cmd *cli.Cmd) {
cmd.Command("attach", "attach reserved IP to an existing virtual machine", reservedIPAttach)
cmd.Command("convert", "convert existing IP on a virtual machine to a reserved IP", reservedIPConvert)
cmd.Command("create", "create new reserved IP", reservedIPCreate)
cmd.Command("delete", "delete reserved IP from your account", reservedIPDestroy)
cmd.Command("detach", "detach reserved IP from an existing virtual machine", reservedIPDetach)
cmd.Command("list", "list all active reserved IPs on current account", reservedIPList)
})
c.Command("reservedips", "list all active reserved IPs on current account", reservedIPList)
// version
c.Command("version", "vultr CLI version", func(cmd *cli.Cmd) {
cmd.Action = func() {
lengths := []int{24, 48}
tabsPrint(columns{"Client version:", vultr.Version}, lengths)
tabsPrint(columns{"Vultr API endpoint:", vultr.DefaultEndpoint}, lengths)
tabsPrint(columns{"Vultr API version:", vultr.APIVersion}, lengths)
tabsPrint(columns{"OS/Arch (client):", fmt.Sprintf("%v/%v", runtime.GOOS, runtime.GOARCH)}, lengths)
tabsPrint(columns{"Go version:", runtime.Version()}, lengths)
tabsFlush()
}
})
}
|
[
"func",
"(",
"c",
"*",
"CLI",
")",
"RegisterCommands",
"(",
")",
"{",
"// backup",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"backupsList",
")",
"\n",
"}",
")",
"\n\n",
"// dns",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"dnsDomainCreate",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"dnsDomainDelete",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"dnsDomainList",
")",
"\n",
"}",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"dnsRecordCreate",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"dnsRecordUpdate",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"dnsRecordDelete",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"dnsRecordList",
")",
"\n",
"}",
")",
"\n",
"}",
")",
"\n\n",
"// firewall",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"firewallGroupCreate",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"firewallGroupDelete",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"firewallGroupSetDescription",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"firewallGroupList",
")",
"\n",
"}",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"firewallRuleCreate",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"firewallRuleDelete",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"firewallRuleList",
")",
"\n",
"}",
")",
"\n",
"}",
")",
"\n\n",
"// info",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"accountInfo",
")",
"\n\n",
"// iso",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"isoList",
")",
"\n\n",
"// os",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"osList",
")",
"\n\n",
"// applications",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"appList",
")",
"\n\n",
"// plans",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"planList",
")",
"\n\n",
"// regions",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"regionList",
")",
"\n\n",
"// sshkeys",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"sshKeysCreate",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"sshKeysUpdate",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"sshKeysDelete",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"sshKeysList",
")",
"\n",
"}",
")",
"\n",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"sshKeysList",
")",
"\n\n",
"// ssh",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"sshServer",
")",
"\n\n",
"// servers",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversBackupGetSchedule",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversBackupSetSchedule",
")",
"\n",
"}",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversCreate",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversRename",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversTag",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversStart",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversHalt",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversReboot",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversReinstall",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversChangeOS",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversListOS",
")",
"\n",
"}",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversChangeApplication",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversListApplications",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversAppInfo",
")",
"\n",
"}",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversAttachISO",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversDetachISO",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversStatusISO",
")",
"\n",
"}",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversRestoreBackup",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversRestoreSnapshot",
")",
"\n",
"}",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversDelete",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversBandwidth",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversList",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversShow",
")",
"\n",
"// ip information",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"ipv4List",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"ipv4Create",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"ipv4Delete",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"ipv6List",
")",
"\n",
"// reverse dns",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"reverseIpv4Default",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"reverseIpv4Set",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"reverseIpv6Set",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"reverseIpv6Delete",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"reverseIpv6List",
")",
"\n",
"}",
")",
"\n",
"// firewall groups",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversSetFirewallGroup",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversUnsetFirewallGroup",
")",
"\n",
"// upgrade plans",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversChangePlan",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversListUpgradePlans",
")",
"\n",
"}",
")",
"\n",
"}",
")",
"\n",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"serversList",
")",
"\n\n",
"// block storage",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"blockStorageCreate",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"blockStorageResize",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"blockStorageLabel",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"blockStorageAttach",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"blockStorageDetach",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"blockStorageDelete",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"blockStorageList",
")",
"\n",
"}",
")",
"\n",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"blockStorageList",
")",
"\n\n",
"// snapshots",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"snapshotsCreate",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"snapshotsDelete",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"snapshotsList",
")",
"\n",
"}",
")",
"\n",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"snapshotsList",
")",
"\n\n",
"// startup scripts",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"scriptsCreate",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"scriptsUpdate",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"scriptsDelete",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"scriptsList",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"scriptsShow",
")",
"\n",
"}",
")",
"\n",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"scriptsList",
")",
"\n\n",
"// reserved ips",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"reservedIPAttach",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"reservedIPConvert",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"reservedIPCreate",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"reservedIPDestroy",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"reservedIPDetach",
")",
"\n",
"cmd",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"reservedIPList",
")",
"\n",
"}",
")",
"\n",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"reservedIPList",
")",
"\n\n",
"// version",
"c",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"func",
"(",
"cmd",
"*",
"cli",
".",
"Cmd",
")",
"{",
"cmd",
".",
"Action",
"=",
"func",
"(",
")",
"{",
"lengths",
":=",
"[",
"]",
"int",
"{",
"24",
",",
"48",
"}",
"\n",
"tabsPrint",
"(",
"columns",
"{",
"\"",
"\"",
",",
"vultr",
".",
"Version",
"}",
",",
"lengths",
")",
"\n",
"tabsPrint",
"(",
"columns",
"{",
"\"",
"\"",
",",
"vultr",
".",
"DefaultEndpoint",
"}",
",",
"lengths",
")",
"\n",
"tabsPrint",
"(",
"columns",
"{",
"\"",
"\"",
",",
"vultr",
".",
"APIVersion",
"}",
",",
"lengths",
")",
"\n",
"tabsPrint",
"(",
"columns",
"{",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"runtime",
".",
"GOOS",
",",
"runtime",
".",
"GOARCH",
")",
"}",
",",
"lengths",
")",
"\n",
"tabsPrint",
"(",
"columns",
"{",
"\"",
"\"",
",",
"runtime",
".",
"Version",
"(",
")",
"}",
",",
"lengths",
")",
"\n",
"tabsFlush",
"(",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"}"
] |
https://github.com/JamesClonk/vultr/blob/fed59ad207c9bda0a5dfe4d18de53ccbb3d80c91/cmd/commands.go#L12-L190
| 0.76961
|
||
chasex/redis-go-cluster
|
222d81891f1d3fa7cf8b5655020352c3e5b4ec0f
|
cluster.go
|
go
|
handleAsk
|
(cluster *Cluster) (node *redisNode, replyMsg, cmd string, args []interface{})
|
[] |
func (cluster *Cluster) handleAsk(node *redisNode, replyMsg, cmd string, args []interface{}) (interface{}, error) {
fields := strings.Split(replyMsg, " ")
if len(fields) != 3 {
return nil, fmt.Errorf("handleAsk: invalid response \"%s\"", replyMsg)
}
newNode, err := cluster.getNodeByAddr(fields[2])
if err != nil {
return nil, fmt.Errorf("handleAsk: %v", err)
}
conn, err := newNode.getConn()
if err != nil {
return nil, fmt.Errorf("handleAsk: %v", err)
}
conn.send("ASKING")
conn.send(cmd, args...)
err = conn.flush()
if err != nil {
conn.shutdown()
return nil, fmt.Errorf("handleAsk: %v", err)
}
re, err := String(conn.receive())
if err != nil || re != "OK" {
conn.shutdown()
return nil, fmt.Errorf("handleAsk: %v", err)
}
reply, err := conn.receive()
if err != nil {
conn.shutdown()
return nil, fmt.Errorf("handleAsk: %v", err)
}
newNode.releaseConn(conn)
return reply, nil
}
|
[
"func",
"(",
"cluster",
"*",
"Cluster",
")",
"handleAsk",
"(",
"node",
"*",
"redisNode",
",",
"replyMsg",
",",
"cmd",
"string",
",",
"args",
"[",
"]",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"fields",
":=",
"strings",
".",
"Split",
"(",
"replyMsg",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"fields",
")",
"!=",
"3",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"replyMsg",
")",
"\n",
"}",
"\n\n",
"newNode",
",",
"err",
":=",
"cluster",
".",
"getNodeByAddr",
"(",
"fields",
"[",
"2",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"conn",
",",
"err",
":=",
"newNode",
".",
"getConn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"conn",
".",
"send",
"(",
"\"",
"\"",
")",
"\n",
"conn",
".",
"send",
"(",
"cmd",
",",
"args",
"...",
")",
"\n\n",
"err",
"=",
"conn",
".",
"flush",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"conn",
".",
"shutdown",
"(",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"re",
",",
"err",
":=",
"String",
"(",
"conn",
".",
"receive",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"re",
"!=",
"\"",
"\"",
"{",
"conn",
".",
"shutdown",
"(",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"reply",
",",
"err",
":=",
"conn",
".",
"receive",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"conn",
".",
"shutdown",
"(",
")",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"newNode",
".",
"releaseConn",
"(",
"conn",
")",
"\n\n",
"return",
"reply",
",",
"nil",
"\n",
"}"
] |
https://github.com/chasex/redis-go-cluster/blob/222d81891f1d3fa7cf8b5655020352c3e5b4ec0f/cluster.go#L182-L222
| 0.768823
|
||||
sclevine/agouti
|
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
selection_actions.go
|
go
|
setChecked
|
(s *Selection) (checked bool)
|
[] |
func (s *Selection) setChecked(checked bool) error {
return s.forEachElement(func(selectedElement element.Element) error {
elementType, err := selectedElement.GetAttribute("type")
if err != nil {
return fmt.Errorf("failed to retrieve type attribute of %s: %s", s, err)
}
if elementType != "checkbox" {
return fmt.Errorf("%s does not refer to a checkbox", s)
}
elementChecked, err := selectedElement.IsSelected()
if err != nil {
return fmt.Errorf("failed to retrieve state of %s: %s", s, err)
}
if elementChecked != checked {
if err := selectedElement.Click(); err != nil {
return fmt.Errorf("failed to click on %s: %s", s, err)
}
}
return nil
})
}
|
[
"func",
"(",
"s",
"*",
"Selection",
")",
"setChecked",
"(",
"checked",
"bool",
")",
"error",
"{",
"return",
"s",
".",
"forEachElement",
"(",
"func",
"(",
"selectedElement",
"element",
".",
"Element",
")",
"error",
"{",
"elementType",
",",
"err",
":=",
"selectedElement",
".",
"GetAttribute",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"elementType",
"!=",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
")",
"\n",
"}",
"\n\n",
"elementChecked",
",",
"err",
":=",
"selectedElement",
".",
"IsSelected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"elementChecked",
"!=",
"checked",
"{",
"if",
"err",
":=",
"selectedElement",
".",
"Click",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] |
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_actions.go#L114-L137
| 0.768442
|
||||
sclevine/agouti
|
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
api/session.go
|
go
|
SetCookie
|
(s *Session) (cookie *Cookie)
|
[] |
func (s *Session) SetCookie(cookie *Cookie) error {
if cookie == nil {
return errors.New("nil cookie is invalid")
}
request := struct {
Cookie *Cookie `json:"cookie"`
}{cookie}
return s.Send("POST", "cookie", request, nil)
}
|
[
"func",
"(",
"s",
"*",
"Session",
")",
"SetCookie",
"(",
"cookie",
"*",
"Cookie",
")",
"error",
"{",
"if",
"cookie",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"request",
":=",
"struct",
"{",
"Cookie",
"*",
"Cookie",
"`json:\"cookie\"`",
"\n",
"}",
"{",
"cookie",
"}",
"\n\n",
"return",
"s",
".",
"Send",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"request",
",",
"nil",
")",
"\n",
"}"
] |
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/api/session.go#L139-L148
| 0.768442
|
||||
beeker1121/goque
|
4044bc29b28064db4f08e947c4972d5ca3e0f3c8
|
priority_queue.go
|
go
|
Enqueue
|
(pq *PriorityQueue) (priority uint8, value []byte)
|
// Enqueue adds an item to the priority queue.
|
Enqueue adds an item to the priority queue.
|
[
"Enqueue",
"adds",
"an",
"item",
"to",
"the",
"priority",
"queue",
"."
] |
func (pq *PriorityQueue) Enqueue(priority uint8, value []byte) (*PriorityItem, error) {
pq.Lock()
defer pq.Unlock()
// Check if queue is closed.
if !pq.isOpen {
return nil, ErrDBClosed
}
// Get the priorityLevel.
level := pq.levels[priority]
// Create new PriorityItem.
item := &PriorityItem{
ID: level.tail + 1,
Priority: priority,
Key: pq.generateKey(priority, level.tail+1),
Value: value,
}
// Add it to the priority queue.
if err := pq.db.Put(item.Key, item.Value, nil); err != nil {
return nil, err
}
// Increment tail position.
level.tail++
// If this priority level is more important than the curLevel.
if pq.cmpAsc(priority) || pq.cmpDesc(priority) {
pq.curLevel = priority
}
return item, nil
}
|
[
"func",
"(",
"pq",
"*",
"PriorityQueue",
")",
"Enqueue",
"(",
"priority",
"uint8",
",",
"value",
"[",
"]",
"byte",
")",
"(",
"*",
"PriorityItem",
",",
"error",
")",
"{",
"pq",
".",
"Lock",
"(",
")",
"\n",
"defer",
"pq",
".",
"Unlock",
"(",
")",
"\n\n",
"// Check if queue is closed.",
"if",
"!",
"pq",
".",
"isOpen",
"{",
"return",
"nil",
",",
"ErrDBClosed",
"\n",
"}",
"\n\n",
"// Get the priorityLevel.",
"level",
":=",
"pq",
".",
"levels",
"[",
"priority",
"]",
"\n\n",
"// Create new PriorityItem.",
"item",
":=",
"&",
"PriorityItem",
"{",
"ID",
":",
"level",
".",
"tail",
"+",
"1",
",",
"Priority",
":",
"priority",
",",
"Key",
":",
"pq",
".",
"generateKey",
"(",
"priority",
",",
"level",
".",
"tail",
"+",
"1",
")",
",",
"Value",
":",
"value",
",",
"}",
"\n\n",
"// Add it to the priority queue.",
"if",
"err",
":=",
"pq",
".",
"db",
".",
"Put",
"(",
"item",
".",
"Key",
",",
"item",
".",
"Value",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Increment tail position.",
"level",
".",
"tail",
"++",
"\n\n",
"// If this priority level is more important than the curLevel.",
"if",
"pq",
".",
"cmpAsc",
"(",
"priority",
")",
"||",
"pq",
".",
"cmpDesc",
"(",
"priority",
")",
"{",
"pq",
".",
"curLevel",
"=",
"priority",
"\n",
"}",
"\n\n",
"return",
"item",
",",
"nil",
"\n",
"}"
] |
https://github.com/beeker1121/goque/blob/4044bc29b28064db4f08e947c4972d5ca3e0f3c8/priority_queue.go#L84-L118
| 0.762264
|
||
beeker1121/goque
|
4044bc29b28064db4f08e947c4972d5ca3e0f3c8
|
priority_queue.go
|
go
|
EnqueueString
|
(pq *PriorityQueue) (priority uint8, value string)
|
// EnqueueString is a helper function for Enqueue that accepts a
// value as a string rather than a byte slice.
|
EnqueueString is a helper function for Enqueue that accepts a
value as a string rather than a byte slice.
|
[
"EnqueueString",
"is",
"a",
"helper",
"function",
"for",
"Enqueue",
"that",
"accepts",
"a",
"value",
"as",
"a",
"string",
"rather",
"than",
"a",
"byte",
"slice",
"."
] |
func (pq *PriorityQueue) EnqueueString(priority uint8, value string) (*PriorityItem, error) {
return pq.Enqueue(priority, []byte(value))
}
|
[
"func",
"(",
"pq",
"*",
"PriorityQueue",
")",
"EnqueueString",
"(",
"priority",
"uint8",
",",
"value",
"string",
")",
"(",
"*",
"PriorityItem",
",",
"error",
")",
"{",
"return",
"pq",
".",
"Enqueue",
"(",
"priority",
",",
"[",
"]",
"byte",
"(",
"value",
")",
")",
"\n",
"}"
] |
https://github.com/beeker1121/goque/blob/4044bc29b28064db4f08e947c4972d5ca3e0f3c8/priority_queue.go#L122-L124
| 0.762264
|
||
uber-go/ratelimit
|
c15da02342779cb6dc027fc95ee2277787698f36
|
internal/clock/clock.go
|
go
|
Timer
|
(m *Mock) (d time.Duration)
|
// Timer produces a timer that will emit a time some duration after now.
|
Timer produces a timer that will emit a time some duration after now.
|
[
"Timer",
"produces",
"a",
"timer",
"that",
"will",
"emit",
"a",
"time",
"some",
"duration",
"after",
"now",
"."
] |
func (m *Mock) Timer(d time.Duration) *Timer {
ch := make(chan time.Time)
t := &Timer{
C: ch,
c: ch,
mock: m,
next: m.now.Add(d),
}
m.addTimer(t)
return t
}
|
[
"func",
"(",
"m",
"*",
"Mock",
")",
"Timer",
"(",
"d",
"time",
".",
"Duration",
")",
"*",
"Timer",
"{",
"ch",
":=",
"make",
"(",
"chan",
"time",
".",
"Time",
")",
"\n",
"t",
":=",
"&",
"Timer",
"{",
"C",
":",
"ch",
",",
"c",
":",
"ch",
",",
"mock",
":",
"m",
",",
"next",
":",
"m",
".",
"now",
".",
"Add",
"(",
"d",
")",
",",
"}",
"\n",
"m",
".",
"addTimer",
"(",
"t",
")",
"\n",
"return",
"t",
"\n",
"}"
] |
https://github.com/uber-go/ratelimit/blob/c15da02342779cb6dc027fc95ee2277787698f36/internal/clock/clock.go#L66-L76
| 0.755498
|
||
montanaflynn/stats
|
38304a2645bb6bd10153d518e10a9b69190ff730
|
regression.go
|
go
|
LinearRegression
|
(s Series)
|
// LinearRegression finds the least squares linear regression on data series
|
LinearRegression finds the least squares linear regression on data series
|
[
"LinearRegression",
"finds",
"the",
"least",
"squares",
"linear",
"regression",
"on",
"data",
"series"
] |
func LinearRegression(s Series) (regressions Series, err error) {
if len(s) == 0 {
return nil, EmptyInputErr
}
// Placeholder for the math to be done
var sum [5]float64
// Loop over data keeping index in place
i := 0
for ; i < len(s); i++ {
sum[0] += s[i].X
sum[1] += s[i].Y
sum[2] += s[i].X * s[i].X
sum[3] += s[i].X * s[i].Y
sum[4] += s[i].Y * s[i].Y
}
// Find gradient and intercept
f := float64(i)
gradient := (f*sum[3] - sum[0]*sum[1]) / (f*sum[2] - sum[0]*sum[0])
intercept := (sum[1] / f) - (gradient * sum[0] / f)
// Create the new regression series
for j := 0; j < len(s); j++ {
regressions = append(regressions, Coordinate{
X: s[j].X,
Y: s[j].X*gradient + intercept,
})
}
return regressions, nil
}
|
[
"func",
"LinearRegression",
"(",
"s",
"Series",
")",
"(",
"regressions",
"Series",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"s",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"EmptyInputErr",
"\n",
"}",
"\n\n",
"// Placeholder for the math to be done",
"var",
"sum",
"[",
"5",
"]",
"float64",
"\n\n",
"// Loop over data keeping index in place",
"i",
":=",
"0",
"\n",
"for",
";",
"i",
"<",
"len",
"(",
"s",
")",
";",
"i",
"++",
"{",
"sum",
"[",
"0",
"]",
"+=",
"s",
"[",
"i",
"]",
".",
"X",
"\n",
"sum",
"[",
"1",
"]",
"+=",
"s",
"[",
"i",
"]",
".",
"Y",
"\n",
"sum",
"[",
"2",
"]",
"+=",
"s",
"[",
"i",
"]",
".",
"X",
"*",
"s",
"[",
"i",
"]",
".",
"X",
"\n",
"sum",
"[",
"3",
"]",
"+=",
"s",
"[",
"i",
"]",
".",
"X",
"*",
"s",
"[",
"i",
"]",
".",
"Y",
"\n",
"sum",
"[",
"4",
"]",
"+=",
"s",
"[",
"i",
"]",
".",
"Y",
"*",
"s",
"[",
"i",
"]",
".",
"Y",
"\n",
"}",
"\n\n",
"// Find gradient and intercept",
"f",
":=",
"float64",
"(",
"i",
")",
"\n",
"gradient",
":=",
"(",
"f",
"*",
"sum",
"[",
"3",
"]",
"-",
"sum",
"[",
"0",
"]",
"*",
"sum",
"[",
"1",
"]",
")",
"/",
"(",
"f",
"*",
"sum",
"[",
"2",
"]",
"-",
"sum",
"[",
"0",
"]",
"*",
"sum",
"[",
"0",
"]",
")",
"\n",
"intercept",
":=",
"(",
"sum",
"[",
"1",
"]",
"/",
"f",
")",
"-",
"(",
"gradient",
"*",
"sum",
"[",
"0",
"]",
"/",
"f",
")",
"\n\n",
"// Create the new regression series",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"len",
"(",
"s",
")",
";",
"j",
"++",
"{",
"regressions",
"=",
"append",
"(",
"regressions",
",",
"Coordinate",
"{",
"X",
":",
"s",
"[",
"j",
"]",
".",
"X",
",",
"Y",
":",
"s",
"[",
"j",
"]",
".",
"X",
"*",
"gradient",
"+",
"intercept",
",",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"regressions",
",",
"nil",
"\n",
"}"
] |
https://github.com/montanaflynn/stats/blob/38304a2645bb6bd10153d518e10a9b69190ff730/regression.go#L14-L47
| 0.755305
|
||
contiv/netplugin
|
965773066d2b8ebed3514979949061a03d46fd20
|
netplugin/plugin/netplugin.go
|
go
|
Reinit
|
(p *NetPlugin) (cfg Config)
|
//Reinit reinitialize the network driver
|
Reinit reinitialize the network driver
|
[
"Reinit",
"reinitialize",
"the",
"network",
"driver"
] |
func (p *NetPlugin) Reinit(cfg Config) {
var err error
p.Lock()
defer p.Unlock()
if p.NetworkDriver != nil {
logrus.Infof("Reinit de-initializing NetworkDriver")
p.NetworkDriver.Deinit()
p.NetworkDriver = nil
}
cfg.Instance.StateDriver, _ = utils.GetStateDriver()
p.NetworkDriver, err = utils.NewNetworkDriver(cfg.Drivers.Network, &cfg.Instance)
logrus.Infof("Reinit Initializing NetworkDriver")
if err != nil {
logrus.Errorf("Reinit De-initializing due to error: %v", err)
p.NetworkDriver.Deinit()
}
}
|
[
"func",
"(",
"p",
"*",
"NetPlugin",
")",
"Reinit",
"(",
"cfg",
"Config",
")",
"{",
"var",
"err",
"error",
"\n\n",
"p",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"Unlock",
"(",
")",
"\n",
"if",
"p",
".",
"NetworkDriver",
"!=",
"nil",
"{",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n",
"p",
".",
"NetworkDriver",
".",
"Deinit",
"(",
")",
"\n",
"p",
".",
"NetworkDriver",
"=",
"nil",
"\n",
"}",
"\n\n",
"cfg",
".",
"Instance",
".",
"StateDriver",
",",
"_",
"=",
"utils",
".",
"GetStateDriver",
"(",
")",
"\n",
"p",
".",
"NetworkDriver",
",",
"err",
"=",
"utils",
".",
"NewNetworkDriver",
"(",
"cfg",
".",
"Drivers",
".",
"Network",
",",
"&",
"cfg",
".",
"Instance",
")",
"\n",
"logrus",
".",
"Infof",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"p",
".",
"NetworkDriver",
".",
"Deinit",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
https://github.com/contiv/netplugin/blob/965773066d2b8ebed3514979949061a03d46fd20/netplugin/plugin/netplugin.go#L286-L305
| 0.755117
|
||
go-gl/gl
|
bf2b1f2f34d7f6a60a99a830f65dcd6afb0c6587
|
v3.1/gles2/package.go
|
go
|
ViewportArrayvNV
|
(first uint32, count int32, v *float32)
|
[] |
func ViewportArrayvNV(first uint32, count int32, v *float32) {
C.glowViewportArrayvNV(gpViewportArrayvNV, (C.GLuint)(first), (C.GLsizei)(count), (*C.GLfloat)(unsafe.Pointer(v)))
}
|
[
"func",
"ViewportArrayvNV",
"(",
"first",
"uint32",
",",
"count",
"int32",
",",
"v",
"*",
"float32",
")",
"{",
"C",
".",
"glowViewportArrayvNV",
"(",
"gpViewportArrayvNV",
",",
"(",
"C",
".",
"GLuint",
")",
"(",
"first",
")",
",",
"(",
"C",
".",
"GLsizei",
")",
"(",
"count",
")",
",",
"(",
"*",
"C",
".",
"GLfloat",
")",
"(",
"unsafe",
".",
"Pointer",
"(",
"v",
")",
")",
")",
"\n",
"}"
] |
https://github.com/go-gl/gl/blob/bf2b1f2f34d7f6a60a99a830f65dcd6afb0c6587/v3.1/gles2/package.go#L9402-L9404
| 0.754829
|
||||
ericchiang/k8s
|
68fb2168bedf77759577a56e44f2ccfaf7229673
|
apis/extensions/v1beta1/generated.pb.go
|
go
|
GetReadOnly
|
(m *AllowedHostPath) ()
|
[] |
func (m *AllowedHostPath) GetReadOnly() bool {
if m != nil && m.ReadOnly != nil {
return *m.ReadOnly
}
return false
}
|
[
"func",
"(",
"m",
"*",
"AllowedHostPath",
")",
"GetReadOnly",
"(",
")",
"bool",
"{",
"if",
"m",
"!=",
"nil",
"&&",
"m",
".",
"ReadOnly",
"!=",
"nil",
"{",
"return",
"*",
"m",
".",
"ReadOnly",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
https://github.com/ericchiang/k8s/blob/68fb2168bedf77759577a56e44f2ccfaf7229673/apis/extensions/v1beta1/generated.pb.go#L141-L146
| 0.753014
|
||||
glycerine/zygomys
|
36f1c7120ff2d831cebbb6f059ddc948273a8b56
|
zygo/functions.go
|
go
|
MakeArrayFunction
|
(env *Zlisp, name string, args []Sexp)
|
[] |
func MakeArrayFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
if len(args) < 1 {
return SexpNull, WrongNargs
}
var size int
switch e := args[0].(type) {
case *SexpInt:
size = int(e.Val)
default:
return SexpNull, fmt.Errorf("first argument must be integer")
}
var fill Sexp
if len(args) == 2 {
fill = args[1]
} else {
fill = SexpNull
}
arr := make([]Sexp, size)
for i := range arr {
arr[i] = fill
}
return env.NewSexpArray(arr), nil
}
|
[
"func",
"MakeArrayFunction",
"(",
"env",
"*",
"Zlisp",
",",
"name",
"string",
",",
"args",
"[",
"]",
"Sexp",
")",
"(",
"Sexp",
",",
"error",
")",
"{",
"if",
"len",
"(",
"args",
")",
"<",
"1",
"{",
"return",
"SexpNull",
",",
"WrongNargs",
"\n",
"}",
"\n\n",
"var",
"size",
"int",
"\n",
"switch",
"e",
":=",
"args",
"[",
"0",
"]",
".",
"(",
"type",
")",
"{",
"case",
"*",
"SexpInt",
":",
"size",
"=",
"int",
"(",
"e",
".",
"Val",
")",
"\n",
"default",
":",
"return",
"SexpNull",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"fill",
"Sexp",
"\n",
"if",
"len",
"(",
"args",
")",
"==",
"2",
"{",
"fill",
"=",
"args",
"[",
"1",
"]",
"\n",
"}",
"else",
"{",
"fill",
"=",
"SexpNull",
"\n",
"}",
"\n\n",
"arr",
":=",
"make",
"(",
"[",
"]",
"Sexp",
",",
"size",
")",
"\n",
"for",
"i",
":=",
"range",
"arr",
"{",
"arr",
"[",
"i",
"]",
"=",
"fill",
"\n",
"}",
"\n\n",
"return",
"env",
".",
"NewSexpArray",
"(",
"arr",
")",
",",
"nil",
"\n",
"}"
] |
https://github.com/glycerine/zygomys/blob/36f1c7120ff2d831cebbb6f059ddc948273a8b56/zygo/functions.go#L783-L809
| 0.752772
|
||||
markcheno/go-talib
|
cd53a9264d70bedcff891f59bf153275f524c100
|
talib.go
|
go
|
LinearReg
|
(inReal []float64, inTimePeriod int)
|
// LinearReg - Linear Regression
|
LinearReg - Linear Regression
|
[
"LinearReg",
"-",
"Linear",
"Regression"
] |
func LinearReg(inReal []float64, inTimePeriod int) []float64 {
outReal := make([]float64, len(inReal))
inTimePeriodF := float64(inTimePeriod)
lookbackTotal := inTimePeriod
startIdx := lookbackTotal
outIdx := startIdx - 1
today := startIdx - 1
sumX := inTimePeriodF * (inTimePeriodF - 1) * 0.5
sumXSqr := inTimePeriodF * (inTimePeriodF - 1) * (2*inTimePeriodF - 1) / 6
divisor := sumX*sumX - inTimePeriodF*sumXSqr
//initialize values of sumY and sumXY over first (inTimePeriod) input values
sumXY := 0.0
sumY := 0.0
i := inTimePeriod
for i != 0 {
i--
tempValue1 := inReal[today-i]
sumY += tempValue1
sumXY += float64(i) * tempValue1
}
for today < len(inReal) {
//sumX and sumXY are already available for first output value
if today > startIdx-1 {
tempValue2 := inReal[today-inTimePeriod]
sumXY += sumY - inTimePeriodF*tempValue2
sumY += inReal[today] - tempValue2
}
m := (inTimePeriodF*sumXY - sumX*sumY) / divisor
b := (sumY - m*sumX) / inTimePeriodF
outReal[outIdx] = b + m*(inTimePeriodF-1)
outIdx++
today++
}
return outReal
}
|
[
"func",
"LinearReg",
"(",
"inReal",
"[",
"]",
"float64",
",",
"inTimePeriod",
"int",
")",
"[",
"]",
"float64",
"{",
"outReal",
":=",
"make",
"(",
"[",
"]",
"float64",
",",
"len",
"(",
"inReal",
")",
")",
"\n\n",
"inTimePeriodF",
":=",
"float64",
"(",
"inTimePeriod",
")",
"\n",
"lookbackTotal",
":=",
"inTimePeriod",
"\n",
"startIdx",
":=",
"lookbackTotal",
"\n",
"outIdx",
":=",
"startIdx",
"-",
"1",
"\n",
"today",
":=",
"startIdx",
"-",
"1",
"\n",
"sumX",
":=",
"inTimePeriodF",
"*",
"(",
"inTimePeriodF",
"-",
"1",
")",
"*",
"0.5",
"\n",
"sumXSqr",
":=",
"inTimePeriodF",
"*",
"(",
"inTimePeriodF",
"-",
"1",
")",
"*",
"(",
"2",
"*",
"inTimePeriodF",
"-",
"1",
")",
"/",
"6",
"\n",
"divisor",
":=",
"sumX",
"*",
"sumX",
"-",
"inTimePeriodF",
"*",
"sumXSqr",
"\n",
"//initialize values of sumY and sumXY over first (inTimePeriod) input values",
"sumXY",
":=",
"0.0",
"\n",
"sumY",
":=",
"0.0",
"\n",
"i",
":=",
"inTimePeriod",
"\n",
"for",
"i",
"!=",
"0",
"{",
"i",
"--",
"\n",
"tempValue1",
":=",
"inReal",
"[",
"today",
"-",
"i",
"]",
"\n",
"sumY",
"+=",
"tempValue1",
"\n",
"sumXY",
"+=",
"float64",
"(",
"i",
")",
"*",
"tempValue1",
"\n",
"}",
"\n",
"for",
"today",
"<",
"len",
"(",
"inReal",
")",
"{",
"//sumX and sumXY are already available for first output value",
"if",
"today",
">",
"startIdx",
"-",
"1",
"{",
"tempValue2",
":=",
"inReal",
"[",
"today",
"-",
"inTimePeriod",
"]",
"\n",
"sumXY",
"+=",
"sumY",
"-",
"inTimePeriodF",
"*",
"tempValue2",
"\n",
"sumY",
"+=",
"inReal",
"[",
"today",
"]",
"-",
"tempValue2",
"\n",
"}",
"\n",
"m",
":=",
"(",
"inTimePeriodF",
"*",
"sumXY",
"-",
"sumX",
"*",
"sumY",
")",
"/",
"divisor",
"\n",
"b",
":=",
"(",
"sumY",
"-",
"m",
"*",
"sumX",
")",
"/",
"inTimePeriodF",
"\n",
"outReal",
"[",
"outIdx",
"]",
"=",
"b",
"+",
"m",
"*",
"(",
"inTimePeriodF",
"-",
"1",
")",
"\n",
"outIdx",
"++",
"\n",
"today",
"++",
"\n",
"}",
"\n",
"return",
"outReal",
"\n",
"}"
] |
https://github.com/markcheno/go-talib/blob/cd53a9264d70bedcff891f59bf153275f524c100/talib.go#L5108-L5144
| 0.746057
|
||
mesos/mesos-go
|
ee67238bbd943c751ec0a5dffb09af2b0182d361
|
api/v0/mesosproto/mesos.pb.go
|
go
|
GetIpAddress
|
(m *NetworkInfo_IPAddress) ()
|
[] |
func (m *NetworkInfo_IPAddress) GetIpAddress() string {
if m != nil && m.IpAddress != nil {
return *m.IpAddress
}
return ""
}
|
[
"func",
"(",
"m",
"*",
"NetworkInfo_IPAddress",
")",
"GetIpAddress",
"(",
")",
"string",
"{",
"if",
"m",
"!=",
"nil",
"&&",
"m",
".",
"IpAddress",
"!=",
"nil",
"{",
"return",
"*",
"m",
".",
"IpAddress",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] |
https://github.com/mesos/mesos-go/blob/ee67238bbd943c751ec0a5dffb09af2b0182d361/api/v0/mesosproto/mesos.pb.go#L4142-L4147
| 0.729613
|
||||
moovweb/gokogiri
|
a1a828153468a7518b184e698f6265904108d957
|
xml/node.go
|
go
|
Parent
|
(xmlNode *XmlNode) ()
|
/*
Parent returns the parent of the current node (or nil if there isn't one).
This will always be an element or document node, as those are the only node types
that can have children.
*/
|
/*
Parent returns the parent of the current node (or nil if there isn't one).
This will always be an element or document node, as those are the only node types
that can have children.
|
[
"/",
"*",
"Parent",
"returns",
"the",
"parent",
"of",
"the",
"current",
"node",
"(",
"or",
"nil",
"if",
"there",
"isn",
"t",
"one",
")",
".",
"This",
"will",
"always",
"be",
"an",
"element",
"or",
"document",
"node",
"as",
"those",
"are",
"the",
"only",
"node",
"types",
"that",
"can",
"have",
"children",
"."
] |
func (xmlNode *XmlNode) Parent() Node {
if C.xmlNodePtrCheck(unsafe.Pointer(xmlNode.Ptr.parent)) == C.int(0) {
return nil
}
return NewNode(unsafe.Pointer(xmlNode.Ptr.parent), xmlNode.Document)
}
|
[
"func",
"(",
"xmlNode",
"*",
"XmlNode",
")",
"Parent",
"(",
")",
"Node",
"{",
"if",
"C",
".",
"xmlNodePtrCheck",
"(",
"unsafe",
".",
"Pointer",
"(",
"xmlNode",
".",
"Ptr",
".",
"parent",
")",
")",
"==",
"C",
".",
"int",
"(",
"0",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"NewNode",
"(",
"unsafe",
".",
"Pointer",
"(",
"xmlNode",
".",
"Ptr",
".",
"parent",
")",
",",
"xmlNode",
".",
"Document",
")",
"\n",
"}"
] |
https://github.com/moovweb/gokogiri/blob/a1a828153468a7518b184e698f6265904108d957/xml/node.go#L379-L384
| 0.727373
|
||
ForceCLI/force
|
dcf4021894573897981e05f26e1282dd209519e2
|
command/query.go
|
go
|
init
|
()
|
[] |
func init() {
defaultOutputFormat := "console"
if !terminal.IsTerminal(int(os.Stdout.Fd())) {
defaultOutputFormat = "csv"
}
cmdQuery.Flag.BoolVar(&queryAll, "all", false, "use queryAll to include deleted and archived records in query results")
cmdQuery.Flag.BoolVar(&queryAll, "a", false, "use queryAll to include deleted and archived records in query results")
cmdQuery.Flag.BoolVar(&useTooling, "tooling", false, "use Tooling API")
cmdQuery.Flag.BoolVar(&useTooling, "t", false, "use Tooling API")
cmdQuery.Flag.StringVar(&queryOutputFormat, "format", defaultOutputFormat, "output format: csv, json, json-pretty, console")
cmdQuery.Flag.StringVar(&queryOutputFormat, "f", defaultOutputFormat, "output format: csv, json, json-pretty, console")
}
|
[
"func",
"init",
"(",
")",
"{",
"defaultOutputFormat",
":=",
"\"",
"\"",
"\n",
"if",
"!",
"terminal",
".",
"IsTerminal",
"(",
"int",
"(",
"os",
".",
"Stdout",
".",
"Fd",
"(",
")",
")",
")",
"{",
"defaultOutputFormat",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"cmdQuery",
".",
"Flag",
".",
"BoolVar",
"(",
"&",
"queryAll",
",",
"\"",
"\"",
",",
"false",
",",
"\"",
"\"",
")",
"\n",
"cmdQuery",
".",
"Flag",
".",
"BoolVar",
"(",
"&",
"queryAll",
",",
"\"",
"\"",
",",
"false",
",",
"\"",
"\"",
")",
"\n",
"cmdQuery",
".",
"Flag",
".",
"BoolVar",
"(",
"&",
"useTooling",
",",
"\"",
"\"",
",",
"false",
",",
"\"",
"\"",
")",
"\n",
"cmdQuery",
".",
"Flag",
".",
"BoolVar",
"(",
"&",
"useTooling",
",",
"\"",
"\"",
",",
"false",
",",
"\"",
"\"",
")",
"\n",
"cmdQuery",
".",
"Flag",
".",
"StringVar",
"(",
"&",
"queryOutputFormat",
",",
"\"",
"\"",
",",
"defaultOutputFormat",
",",
"\"",
"\"",
")",
"\n",
"cmdQuery",
".",
"Flag",
".",
"StringVar",
"(",
"&",
"queryOutputFormat",
",",
"\"",
"\"",
",",
"defaultOutputFormat",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
https://github.com/ForceCLI/force/blob/dcf4021894573897981e05f26e1282dd209519e2/command/query.go#L40-L51
| 0.707731
|
||||
thriftrw/thriftrw-go
|
a9a6ad793beab07cc3385954d2e8af8abfaa83e2
|
gen/string.go
|
go
|
goCase
|
(s string)
|
// goCase converts strings into PascalCase.
|
goCase converts strings into PascalCase.
|
[
"goCase",
"converts",
"strings",
"into",
"PascalCase",
"."
] |
func goCase(s string) string {
if len(s) == 0 {
panic(fmt.Sprintf("%q is not a valid identifier", s))
}
words := strings.Split(s, "_")
return pascalCase(len(words) == 1 /* all caps */, words...)
// goCase allows all caps only if the string is a single all caps word.
// That is, "FOO" is allowed but "FOO_BAR" is changed to "FooBar".
}
|
[
"func",
"goCase",
"(",
"s",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"s",
")",
"==",
"0",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"s",
")",
")",
"\n",
"}",
"\n\n",
"words",
":=",
"strings",
".",
"Split",
"(",
"s",
",",
"\"",
"\"",
")",
"\n",
"return",
"pascalCase",
"(",
"len",
"(",
"words",
")",
"==",
"1",
"/* all caps */",
",",
"words",
"...",
")",
"\n",
"// goCase allows all caps only if the string is a single all caps word.",
"// That is, \"FOO\" is allowed but \"FOO_BAR\" is changed to \"FooBar\".",
"}"
] |
https://github.com/thriftrw/thriftrw-go/blob/a9a6ad793beab07cc3385954d2e8af8abfaa83e2/gen/string.go#L84-L93
| 0.68041
|
||
go-ole/go-ole
|
97b6244175ae18ea6eef668034fd6565847501c9
|
_example/excel2/excel.go
|
go
|
main
|
()
|
[] |
func main() {
log.SetFlags(log.Flags() | log.Lshortfile)
ole.CoInitialize(0)
unknown, _ := oleutil.CreateObject("Excel.Application")
excel, _ := unknown.QueryInterface(ole.IID_IDispatch)
oleutil.PutProperty(excel, "Visible", true)
workbooks := oleutil.MustGetProperty(excel, "Workbooks").ToIDispatch()
cwd, _ := os.Getwd()
writeExample(excel, workbooks, cwd+"\\write.xls")
readExample(cwd+"\\excel97-2003.xls", excel, workbooks)
showMethodsAndProperties(workbooks)
workbooks.Release()
// oleutil.CallMethod(excel, "Quit")
excel.Release()
ole.CoUninitialize()
}
|
[
"func",
"main",
"(",
")",
"{",
"log",
".",
"SetFlags",
"(",
"log",
".",
"Flags",
"(",
")",
"|",
"log",
".",
"Lshortfile",
")",
"\n",
"ole",
".",
"CoInitialize",
"(",
"0",
")",
"\n",
"unknown",
",",
"_",
":=",
"oleutil",
".",
"CreateObject",
"(",
"\"",
"\"",
")",
"\n",
"excel",
",",
"_",
":=",
"unknown",
".",
"QueryInterface",
"(",
"ole",
".",
"IID_IDispatch",
")",
"\n",
"oleutil",
".",
"PutProperty",
"(",
"excel",
",",
"\"",
"\"",
",",
"true",
")",
"\n\n",
"workbooks",
":=",
"oleutil",
".",
"MustGetProperty",
"(",
"excel",
",",
"\"",
"\"",
")",
".",
"ToIDispatch",
"(",
")",
"\n",
"cwd",
",",
"_",
":=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"writeExample",
"(",
"excel",
",",
"workbooks",
",",
"cwd",
"+",
"\"",
"\\\\",
"\"",
")",
"\n",
"readExample",
"(",
"cwd",
"+",
"\"",
"\\\\",
"\"",
",",
"excel",
",",
"workbooks",
")",
"\n",
"showMethodsAndProperties",
"(",
"workbooks",
")",
"\n",
"workbooks",
".",
"Release",
"(",
")",
"\n",
"// oleutil.CallMethod(excel, \"Quit\")",
"excel",
".",
"Release",
"(",
")",
"\n",
"ole",
".",
"CoUninitialize",
"(",
")",
"\n",
"}"
] |
https://github.com/go-ole/go-ole/blob/97b6244175ae18ea6eef668034fd6565847501c9/_example/excel2/excel.go#L80-L96
| 0.593039
|
||||
huandu/xstrings
|
8bbcf2f9ccb55755e748b7644164cd4bdce94c1d
|
manipulate.go
|
go
|
WordSplit
|
(str string)
|
// WordSplit splits a string into words. Returns a slice of words.
// If there is no word in a string, return nil.
//
// Word is defined as a locale dependent string containing alphabetic characters,
// which may also contain but not start with `'` and `-` characters.
|
WordSplit splits a string into words. Returns a slice of words.
If there is no word in a string, return nil.
Word is defined as a locale dependent string containing alphabetic characters,
which may also contain but not start with `'` and `-` characters.
|
[
"WordSplit",
"splits",
"a",
"string",
"into",
"words",
".",
"Returns",
"a",
"slice",
"of",
"words",
".",
"If",
"there",
"is",
"no",
"word",
"in",
"a",
"string",
"return",
"nil",
".",
"Word",
"is",
"defined",
"as",
"a",
"locale",
"dependent",
"string",
"containing",
"alphabetic",
"characters",
"which",
"may",
"also",
"contain",
"but",
"not",
"start",
"with",
"and",
"-",
"characters",
"."
] |
func WordSplit(str string) []string {
var word string
var words []string
var r rune
var size, pos int
inWord := false
for len(str) > 0 {
r, size = utf8.DecodeRuneInString(str)
switch {
case isAlphabet(r):
if !inWord {
inWord = true
word = str
pos = 0
}
case inWord && (r == '\'' || r == '-'):
// Still in word.
default:
if inWord {
inWord = false
words = append(words, word[:pos])
}
}
pos += size
str = str[size:]
}
if inWord {
words = append(words, word[:pos])
}
return words
}
|
[
"func",
"WordSplit",
"(",
"str",
"string",
")",
"[",
"]",
"string",
"{",
"var",
"word",
"string",
"\n",
"var",
"words",
"[",
"]",
"string",
"\n",
"var",
"r",
"rune",
"\n",
"var",
"size",
",",
"pos",
"int",
"\n\n",
"inWord",
":=",
"false",
"\n\n",
"for",
"len",
"(",
"str",
")",
">",
"0",
"{",
"r",
",",
"size",
"=",
"utf8",
".",
"DecodeRuneInString",
"(",
"str",
")",
"\n\n",
"switch",
"{",
"case",
"isAlphabet",
"(",
"r",
")",
":",
"if",
"!",
"inWord",
"{",
"inWord",
"=",
"true",
"\n",
"word",
"=",
"str",
"\n",
"pos",
"=",
"0",
"\n",
"}",
"\n\n",
"case",
"inWord",
"&&",
"(",
"r",
"==",
"'\\''",
"||",
"r",
"==",
"'-'",
")",
":",
"// Still in word.",
"default",
":",
"if",
"inWord",
"{",
"inWord",
"=",
"false",
"\n",
"words",
"=",
"append",
"(",
"words",
",",
"word",
"[",
":",
"pos",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"pos",
"+=",
"size",
"\n",
"str",
"=",
"str",
"[",
"size",
":",
"]",
"\n",
"}",
"\n\n",
"if",
"inWord",
"{",
"words",
"=",
"append",
"(",
"words",
",",
"word",
"[",
":",
"pos",
"]",
")",
"\n",
"}",
"\n\n",
"return",
"words",
"\n",
"}"
] |
https://github.com/huandu/xstrings/blob/8bbcf2f9ccb55755e748b7644164cd4bdce94c1d/manipulate.go#L179-L217
| 0.591859
|
||
lileio/lile
|
becf404ea65c4dd7cbe6e8c6dd2a313d07359b4e
|
protoc-gen-lile-server/main.go
|
go
|
DedupImports
|
(imports ...string)
|
[] |
func DedupImports(imports ...string) string {
data := sort.StringSlice(imports)
sort.Sort(data)
n := set.Uniq(data)
imports = data[:n]
return fmt.Sprintf("\t\"%s\"", strings.Join(imports, "\"\n\t\""))
}
|
[
"func",
"DedupImports",
"(",
"imports",
"...",
"string",
")",
"string",
"{",
"data",
":=",
"sort",
".",
"StringSlice",
"(",
"imports",
")",
"\n",
"sort",
".",
"Sort",
"(",
"data",
")",
"\n",
"n",
":=",
"set",
".",
"Uniq",
"(",
"data",
")",
"\n",
"imports",
"=",
"data",
"[",
":",
"n",
"]",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\t",
"\\\"",
"\\\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"imports",
",",
"\"",
"\\\"",
"\\n",
"\\t",
"\\\"",
"\"",
")",
")",
"\n",
"}"
] |
https://github.com/lileio/lile/blob/becf404ea65c4dd7cbe6e8c6dd2a313d07359b4e/protoc-gen-lile-server/main.go#L159-L166
| 0.59144
|
||||
rsc/pdf
|
c47d69cf462f804ff58ca63c61a8fb2aed76587e
|
read.go
|
go
|
Reader
|
(v Value) ()
|
// Reader returns the data contained in the stream v.
// If v.Kind() != Stream, Reader returns a ReadCloser that
// responds to all reads with a ``stream not present'' error.
|
Reader returns the data contained in the stream v.
If v.Kind() != Stream, Reader returns a ReadCloser that
responds to all reads with a ``stream not present'' error.
|
[
"Reader",
"returns",
"the",
"data",
"contained",
"in",
"the",
"stream",
"v",
".",
"If",
"v",
".",
"Kind",
"()",
"!",
"=",
"Stream",
"Reader",
"returns",
"a",
"ReadCloser",
"that",
"responds",
"to",
"all",
"reads",
"with",
"a",
"stream",
"not",
"present",
"error",
"."
] |
func (v Value) Reader() io.ReadCloser {
x, ok := v.data.(stream)
if !ok {
return &errorReadCloser{fmt.Errorf("stream not present")}
}
var rd io.Reader
rd = io.NewSectionReader(v.r.f, x.offset, v.Key("Length").Int64())
if v.r.key != nil {
rd = decryptStream(v.r.key, v.r.useAES, x.ptr, rd)
}
filter := v.Key("Filter")
param := v.Key("DecodeParms")
switch filter.Kind() {
default:
panic(fmt.Errorf("unsupported filter %v", filter))
case Null:
// ok
case Name:
rd = applyFilter(rd, filter.Name(), param)
case Array:
for i := 0; i < filter.Len(); i++ {
rd = applyFilter(rd, filter.Index(i).Name(), param.Index(i))
}
}
return ioutil.NopCloser(rd)
}
|
[
"func",
"(",
"v",
"Value",
")",
"Reader",
"(",
")",
"io",
".",
"ReadCloser",
"{",
"x",
",",
"ok",
":=",
"v",
".",
"data",
".",
"(",
"stream",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"&",
"errorReadCloser",
"{",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"}",
"\n",
"}",
"\n",
"var",
"rd",
"io",
".",
"Reader",
"\n",
"rd",
"=",
"io",
".",
"NewSectionReader",
"(",
"v",
".",
"r",
".",
"f",
",",
"x",
".",
"offset",
",",
"v",
".",
"Key",
"(",
"\"",
"\"",
")",
".",
"Int64",
"(",
")",
")",
"\n",
"if",
"v",
".",
"r",
".",
"key",
"!=",
"nil",
"{",
"rd",
"=",
"decryptStream",
"(",
"v",
".",
"r",
".",
"key",
",",
"v",
".",
"r",
".",
"useAES",
",",
"x",
".",
"ptr",
",",
"rd",
")",
"\n",
"}",
"\n",
"filter",
":=",
"v",
".",
"Key",
"(",
"\"",
"\"",
")",
"\n",
"param",
":=",
"v",
".",
"Key",
"(",
"\"",
"\"",
")",
"\n",
"switch",
"filter",
".",
"Kind",
"(",
")",
"{",
"default",
":",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"filter",
")",
")",
"\n",
"case",
"Null",
":",
"// ok",
"case",
"Name",
":",
"rd",
"=",
"applyFilter",
"(",
"rd",
",",
"filter",
".",
"Name",
"(",
")",
",",
"param",
")",
"\n",
"case",
"Array",
":",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"filter",
".",
"Len",
"(",
")",
";",
"i",
"++",
"{",
"rd",
"=",
"applyFilter",
"(",
"rd",
",",
"filter",
".",
"Index",
"(",
"i",
")",
".",
"Name",
"(",
")",
",",
"param",
".",
"Index",
"(",
"i",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"ioutil",
".",
"NopCloser",
"(",
"rd",
")",
"\n",
"}"
] |
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L793-L819
| 0.589614
|
||
aymerick/douceur
|
f9e29746e1161076eae141dd235f5d98b546ec3e
|
inliner/inliner.go
|
go
|
parseHTML
|
(inliner *Inliner) ()
|
// Parses raw html
|
Parses raw html
|
[
"Parses",
"raw",
"html"
] |
func (inliner *Inliner) parseHTML() error {
doc, err := goquery.NewDocumentFromReader(strings.NewReader(inliner.html))
if err != nil {
return err
}
inliner.doc = doc
return nil
}
|
[
"func",
"(",
"inliner",
"*",
"Inliner",
")",
"parseHTML",
"(",
")",
"error",
"{",
"doc",
",",
"err",
":=",
"goquery",
".",
"NewDocumentFromReader",
"(",
"strings",
".",
"NewReader",
"(",
"inliner",
".",
"html",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"inliner",
".",
"doc",
"=",
"doc",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
https://github.com/aymerick/douceur/blob/f9e29746e1161076eae141dd235f5d98b546ec3e/inliner/inliner.go#L93-L102
| 0.586404
|
||
yosssi/ace
|
2b21b56204aee785bf8d500c3f9dcbe3ed7d4515
|
helper_method_content.go
|
go
|
WriteTo
|
(e *helperMethodContent) (w io.Writer)
|
// WriteTo writes data to w.
|
WriteTo writes data to w.
|
[
"WriteTo",
"writes",
"data",
"to",
"w",
"."
] |
func (e *helperMethodContent) WriteTo(w io.Writer) (int64, error) {
var bf bytes.Buffer
inner := e.src.inner
if inner == nil {
return 0, fmt.Errorf("inner is not specified [file: %s][line: %d]", e.ln.fileName(), e.ln.no)
}
// Write a define action.
bf.WriteString(fmt.Sprintf(actionDefine, e.opts.DelimLeft, inner.path+doubleColon+e.name, e.opts.DelimRight))
// Write the children's HTML.
if i, err := e.writeChildren(&bf); err != nil {
return i, err
}
// Write an end action.
bf.WriteString(fmt.Sprintf(actionEnd, e.opts.DelimLeft, e.opts.DelimRight))
// Write the buffer.
i, err := w.Write(bf.Bytes())
return int64(i), err
}
|
[
"func",
"(",
"e",
"*",
"helperMethodContent",
")",
"WriteTo",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"int64",
",",
"error",
")",
"{",
"var",
"bf",
"bytes",
".",
"Buffer",
"\n\n",
"inner",
":=",
"e",
".",
"src",
".",
"inner",
"\n",
"if",
"inner",
"==",
"nil",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"e",
".",
"ln",
".",
"fileName",
"(",
")",
",",
"e",
".",
"ln",
".",
"no",
")",
"\n",
"}",
"\n\n",
"// Write a define action.",
"bf",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"actionDefine",
",",
"e",
".",
"opts",
".",
"DelimLeft",
",",
"inner",
".",
"path",
"+",
"doubleColon",
"+",
"e",
".",
"name",
",",
"e",
".",
"opts",
".",
"DelimRight",
")",
")",
"\n\n",
"// Write the children's HTML.",
"if",
"i",
",",
"err",
":=",
"e",
".",
"writeChildren",
"(",
"&",
"bf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"i",
",",
"err",
"\n",
"}",
"\n\n",
"// Write an end action.",
"bf",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"actionEnd",
",",
"e",
".",
"opts",
".",
"DelimLeft",
",",
"e",
".",
"opts",
".",
"DelimRight",
")",
")",
"\n\n",
"// Write the buffer.",
"i",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"bf",
".",
"Bytes",
"(",
")",
")",
"\n\n",
"return",
"int64",
"(",
"i",
")",
",",
"err",
"\n",
"}"
] |
https://github.com/yosssi/ace/blob/2b21b56204aee785bf8d500c3f9dcbe3ed7d4515/helper_method_content.go#L16-L39
| 0.578847
|
||
franela/goreq
|
bcd34c9993f899273c74baaa95e15386cd97b6e7
|
goreq.go
|
go
|
Gzip
|
()
|
[] |
func Gzip() *compression {
reader := func(buffer io.Reader) (io.ReadCloser, error) {
return gzip.NewReader(buffer)
}
writer := func(buffer io.Writer) (io.WriteCloser, error) {
return gzip.NewWriter(buffer), nil
}
return &compression{writer: writer, reader: reader, ContentEncoding: "gzip"}
}
|
[
"func",
"Gzip",
"(",
")",
"*",
"compression",
"{",
"reader",
":=",
"func",
"(",
"buffer",
"io",
".",
"Reader",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"return",
"gzip",
".",
"NewReader",
"(",
"buffer",
")",
"\n",
"}",
"\n",
"writer",
":=",
"func",
"(",
"buffer",
"io",
".",
"Writer",
")",
"(",
"io",
".",
"WriteCloser",
",",
"error",
")",
"{",
"return",
"gzip",
".",
"NewWriter",
"(",
"buffer",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"compression",
"{",
"writer",
":",
"writer",
",",
"reader",
":",
"reader",
",",
"ContentEncoding",
":",
"\"",
"\"",
"}",
"\n",
"}"
] |
https://github.com/franela/goreq/blob/bcd34c9993f899273c74baaa95e15386cd97b6e7/goreq.go#L130-L138
| 0.576669
|
||||
advancedlogic/GoOse
|
6cd46faf50eb2105cd5de7328ee8eb62557895c9
|
cleaner.go
|
go
|
cleanBadTags
|
(c *Cleaner) (doc *goquery.Document, pattern *regexp.Regexp, selectors *[]string)
|
[] |
func (c *Cleaner) cleanBadTags(doc *goquery.Document, pattern *regexp.Regexp, selectors *[]string) *goquery.Document {
body := doc.Find("html")
children := body.Children()
children.Each(func(i int, s *goquery.Selection) {
for _, selector := range *selectors {
naughtyList := s.Find("*[" + selector + "]")
count := 0
naughtyList.Each(func(j int, node *goquery.Selection) {
attribute, _ := node.Attr(selector)
if pattern.MatchString(attribute) {
if c.config.debug {
log.Printf("Cleaning: Removing node with %s: %s\n", selector, c.config.parser.name(selector, node))
}
c.config.parser.removeNode(node)
count++
}
})
if c.config.debug && count > 0 {
log.Printf("%d naughty %s elements found", count, selector)
}
}
})
return doc
}
|
[
"func",
"(",
"c",
"*",
"Cleaner",
")",
"cleanBadTags",
"(",
"doc",
"*",
"goquery",
".",
"Document",
",",
"pattern",
"*",
"regexp",
".",
"Regexp",
",",
"selectors",
"*",
"[",
"]",
"string",
")",
"*",
"goquery",
".",
"Document",
"{",
"body",
":=",
"doc",
".",
"Find",
"(",
"\"",
"\"",
")",
"\n",
"children",
":=",
"body",
".",
"Children",
"(",
")",
"\n",
"children",
".",
"Each",
"(",
"func",
"(",
"i",
"int",
",",
"s",
"*",
"goquery",
".",
"Selection",
")",
"{",
"for",
"_",
",",
"selector",
":=",
"range",
"*",
"selectors",
"{",
"naughtyList",
":=",
"s",
".",
"Find",
"(",
"\"",
"\"",
"+",
"selector",
"+",
"\"",
"\"",
")",
"\n",
"count",
":=",
"0",
"\n",
"naughtyList",
".",
"Each",
"(",
"func",
"(",
"j",
"int",
",",
"node",
"*",
"goquery",
".",
"Selection",
")",
"{",
"attribute",
",",
"_",
":=",
"node",
".",
"Attr",
"(",
"selector",
")",
"\n",
"if",
"pattern",
".",
"MatchString",
"(",
"attribute",
")",
"{",
"if",
"c",
".",
"config",
".",
"debug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"selector",
",",
"c",
".",
"config",
".",
"parser",
".",
"name",
"(",
"selector",
",",
"node",
")",
")",
"\n",
"}",
"\n",
"c",
".",
"config",
".",
"parser",
".",
"removeNode",
"(",
"node",
")",
"\n",
"count",
"++",
"\n",
"}",
"\n",
"}",
")",
"\n",
"if",
"c",
".",
"config",
".",
"debug",
"&&",
"count",
">",
"0",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"count",
",",
"selector",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"return",
"doc",
"\n",
"}"
] |
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/cleaner.go#L418-L441
| 0.576433
|
||||
advancedlogic/GoOse
|
6cd46faf50eb2105cd5de7328ee8eb62557895c9
|
cleaner.go
|
go
|
convertDivsToParagraphs
|
(c *Cleaner) (doc *goquery.Document, domType string)
|
[] |
func (c *Cleaner) convertDivsToParagraphs(doc *goquery.Document, domType string) *goquery.Document {
if c.config.debug {
log.Println("Starting to replace bad divs...")
}
badDivs := 0
convertedTextNodes := 0
divs := doc.Find(domType)
divs.Each(func(i int, div *goquery.Selection) {
divHTML, _ := div.Html()
if divToPElementsPattern.Match([]byte(divHTML)) {
c.replaceWithPara(div)
badDivs++
} else {
var replacementText []string
nodesToRemove := list.New()
children := div.Contents()
if c.config.debug {
log.Printf("Found %d children of div\n", children.Size())
}
children.EachWithBreak(func(i int, kid *goquery.Selection) bool {
text := kid.Text()
kidNode := kid.Get(0)
tag := kidNode.Data
if tag == text {
tag = "#text"
}
if tag == "#text" {
text = strings.Replace(text, "\n", "", -1)
text = tabsRegEx.ReplaceAllString(text, "")
if text == "" {
return true
}
if len(text) > 1 {
prev := kidNode.PrevSibling
if c.config.debug {
log.Printf("PARENT CLASS: %s NODENAME: %s\n", c.config.parser.name("class", div), tag)
log.Printf("TEXTREPLACE: %s\n", strings.Replace(text, "\n", "", -1))
}
if prev != nil && prev.DataAtom == atom.A {
nodeSelection := kid.HasNodes(prev)
html, _ := nodeSelection.Html()
replacementText = append(replacementText, html)
if c.config.debug {
log.Printf("SIBLING NODENAME ADDITION: %s TEXT: %s\n", prev.Data, html)
}
}
replacementText = append(replacementText, text)
nodesToRemove.PushBack(kidNode)
convertedTextNodes++
}
}
return true
})
/*
newNode := new(html.Node)
newNode.Type = html.ElementNode
newNode.Data = strings.Join(replacementText, "")
newNode.DataAtom = atom.P
*/
/*
replacementText = strings.Replace(replacementText, "=C3=A8", "è")
replacementText = strings.Replace(replacementText, "=C3=A9", "é")
*/
div.First().BeforeHtml("<p>" + strings.Join(replacementText, "") + "</p>")
for s := nodesToRemove.Front(); s != nil; s = s.Next() {
node := s.Value.(*html.Node)
if node != nil && node.Parent != nil {
node.Parent.RemoveChild(node)
}
}
}
})
if c.config.debug {
log.Printf("Found %d total divs with %d bad divs replaced and %d textnodes converted inside divs", divs.Size(), badDivs, convertedTextNodes)
}
return doc
}
|
[
"func",
"(",
"c",
"*",
"Cleaner",
")",
"convertDivsToParagraphs",
"(",
"doc",
"*",
"goquery",
".",
"Document",
",",
"domType",
"string",
")",
"*",
"goquery",
".",
"Document",
"{",
"if",
"c",
".",
"config",
".",
"debug",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"badDivs",
":=",
"0",
"\n",
"convertedTextNodes",
":=",
"0",
"\n",
"divs",
":=",
"doc",
".",
"Find",
"(",
"domType",
")",
"\n\n",
"divs",
".",
"Each",
"(",
"func",
"(",
"i",
"int",
",",
"div",
"*",
"goquery",
".",
"Selection",
")",
"{",
"divHTML",
",",
"_",
":=",
"div",
".",
"Html",
"(",
")",
"\n",
"if",
"divToPElementsPattern",
".",
"Match",
"(",
"[",
"]",
"byte",
"(",
"divHTML",
")",
")",
"{",
"c",
".",
"replaceWithPara",
"(",
"div",
")",
"\n",
"badDivs",
"++",
"\n",
"}",
"else",
"{",
"var",
"replacementText",
"[",
"]",
"string",
"\n",
"nodesToRemove",
":=",
"list",
".",
"New",
"(",
")",
"\n",
"children",
":=",
"div",
".",
"Contents",
"(",
")",
"\n",
"if",
"c",
".",
"config",
".",
"debug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"children",
".",
"Size",
"(",
")",
")",
"\n",
"}",
"\n",
"children",
".",
"EachWithBreak",
"(",
"func",
"(",
"i",
"int",
",",
"kid",
"*",
"goquery",
".",
"Selection",
")",
"bool",
"{",
"text",
":=",
"kid",
".",
"Text",
"(",
")",
"\n",
"kidNode",
":=",
"kid",
".",
"Get",
"(",
"0",
")",
"\n",
"tag",
":=",
"kidNode",
".",
"Data",
"\n",
"if",
"tag",
"==",
"text",
"{",
"tag",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"tag",
"==",
"\"",
"\"",
"{",
"text",
"=",
"strings",
".",
"Replace",
"(",
"text",
",",
"\"",
"\\n",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"text",
"=",
"tabsRegEx",
".",
"ReplaceAllString",
"(",
"text",
",",
"\"",
"\"",
")",
"\n",
"if",
"text",
"==",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"len",
"(",
"text",
")",
">",
"1",
"{",
"prev",
":=",
"kidNode",
".",
"PrevSibling",
"\n",
"if",
"c",
".",
"config",
".",
"debug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"c",
".",
"config",
".",
"parser",
".",
"name",
"(",
"\"",
"\"",
",",
"div",
")",
",",
"tag",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"strings",
".",
"Replace",
"(",
"text",
",",
"\"",
"\\n",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
")",
"\n",
"}",
"\n",
"if",
"prev",
"!=",
"nil",
"&&",
"prev",
".",
"DataAtom",
"==",
"atom",
".",
"A",
"{",
"nodeSelection",
":=",
"kid",
".",
"HasNodes",
"(",
"prev",
")",
"\n",
"html",
",",
"_",
":=",
"nodeSelection",
".",
"Html",
"(",
")",
"\n",
"replacementText",
"=",
"append",
"(",
"replacementText",
",",
"html",
")",
"\n",
"if",
"c",
".",
"config",
".",
"debug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"prev",
".",
"Data",
",",
"html",
")",
"\n",
"}",
"\n",
"}",
"\n",
"replacementText",
"=",
"append",
"(",
"replacementText",
",",
"text",
")",
"\n",
"nodesToRemove",
".",
"PushBack",
"(",
"kidNode",
")",
"\n",
"convertedTextNodes",
"++",
"\n",
"}",
"\n\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n\n",
"/*\n\t\t\tnewNode := new(html.Node)\n\t\t\tnewNode.Type = html.ElementNode\n\t\t\tnewNode.Data = strings.Join(replacementText, \"\")\n\t\t\tnewNode.DataAtom = atom.P\n\t\t\t*/",
"/*\n\t\t\treplacementText = strings.Replace(replacementText, \"=C3=A8\", \"è\")\n\t\t\treplacementText = strings.Replace(replacementText, \"=C3=A9\", \"é\")\n*/",
"div",
".",
"First",
"(",
")",
".",
"BeforeHtml",
"(",
"\"",
"\"",
"+",
"strings",
".",
"Join",
"(",
"replacementText",
",",
"\"",
"\"",
")",
"+",
"\"",
"\"",
")",
"\n\n",
"for",
"s",
":=",
"nodesToRemove",
".",
"Front",
"(",
")",
";",
"s",
"!=",
"nil",
";",
"s",
"=",
"s",
".",
"Next",
"(",
")",
"{",
"node",
":=",
"s",
".",
"Value",
".",
"(",
"*",
"html",
".",
"Node",
")",
"\n",
"if",
"node",
"!=",
"nil",
"&&",
"node",
".",
"Parent",
"!=",
"nil",
"{",
"node",
".",
"Parent",
".",
"RemoveChild",
"(",
"node",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"if",
"c",
".",
"config",
".",
"debug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"divs",
".",
"Size",
"(",
")",
",",
"badDivs",
",",
"convertedTextNodes",
")",
"\n",
"}",
"\n",
"return",
"doc",
"\n\n",
"}"
] |
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/cleaner.go#L487-L568
| 0.576433
|
||||
cloudflare/golibs
|
4efefffc6d5c2168e1c209e44dad549e0674e7a3
|
bytepool/bytepool.go
|
go
|
log2Ceil
|
(v uint32)
|
// Equivalent to: uint(math.Ceil(math.Log2(float64(n))))
|
Equivalent to: uint(math.Ceil(math.Log2(float64(n))))
|
[
"Equivalent",
"to",
":",
"uint",
"(",
"math",
".",
"Ceil",
"(",
"math",
".",
"Log2",
"(",
"float64",
"(",
"n",
"))))"
] |
func log2Ceil(v uint32) uint {
var isNotPowerOfTwo uint = 1
// Golang doesn't know how to convert bool to int - branch required
if (v & (v - 1)) == 0 {
isNotPowerOfTwo = 0
}
return log2Floor(v) + isNotPowerOfTwo
}
|
[
"func",
"log2Ceil",
"(",
"v",
"uint32",
")",
"uint",
"{",
"var",
"isNotPowerOfTwo",
"uint",
"=",
"1",
"\n",
"// Golang doesn't know how to convert bool to int - branch required",
"if",
"(",
"v",
"&",
"(",
"v",
"-",
"1",
")",
")",
"==",
"0",
"{",
"isNotPowerOfTwo",
"=",
"0",
"\n",
"}",
"\n",
"return",
"log2Floor",
"(",
"v",
")",
"+",
"isNotPowerOfTwo",
"\n",
"}"
] |
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/bytepool/bytepool.go#L128-L135
| 0.576196
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.