id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
153,200
ReconfigureIO/sdaccel
axi/arbitrate/axiarbitrate.go
ReadArbitrateX2
func ReadArbitrateX2( clientAddr chan<- protocol.Addr, clientData <-chan protocol.ReadData, serverAddr0 <-chan protocol.Addr, serverData0 chan<- protocol.ReadData, serverAddr1 <-chan protocol.Addr, serverData1 chan<- protocol.ReadData) { // Specify the input selection channel. dataChanSelect := make(chan byte) // Run read data channel handler. go func() { for { chanSelect := <-dataChanSelect // Terminate transfers on write data channel 'last' flag. isLast := false for !isLast { readData := <-clientData switch chanSelect { case 0: serverData0 <- readData isLast = readData.Last default: serverData1 <- readData isLast = readData.Last } } } }() // Use intermediate variables for efficient implementation. var readAddr protocol.Addr var dataChanId byte for { select { case readAddr = <-serverAddr0: dataChanId = 0 case readAddr = <-serverAddr1: dataChanId = 1 } clientAddr <- readAddr dataChanSelect <- dataChanId } }
go
func ReadArbitrateX2( clientAddr chan<- protocol.Addr, clientData <-chan protocol.ReadData, serverAddr0 <-chan protocol.Addr, serverData0 chan<- protocol.ReadData, serverAddr1 <-chan protocol.Addr, serverData1 chan<- protocol.ReadData) { // Specify the input selection channel. dataChanSelect := make(chan byte) // Run read data channel handler. go func() { for { chanSelect := <-dataChanSelect // Terminate transfers on write data channel 'last' flag. isLast := false for !isLast { readData := <-clientData switch chanSelect { case 0: serverData0 <- readData isLast = readData.Last default: serverData1 <- readData isLast = readData.Last } } } }() // Use intermediate variables for efficient implementation. var readAddr protocol.Addr var dataChanId byte for { select { case readAddr = <-serverAddr0: dataChanId = 0 case readAddr = <-serverAddr1: dataChanId = 1 } clientAddr <- readAddr dataChanSelect <- dataChanId } }
[ "func", "ReadArbitrateX2", "(", "clientAddr", "chan", "<-", "protocol", ".", "Addr", ",", "clientData", "<-", "chan", "protocol", ".", "ReadData", ",", "serverAddr0", "<-", "chan", "protocol", ".", "Addr", ",", "serverData0", "chan", "<-", "protocol", ".", "...
// // Goroutine which implements AXI arbitration between two AXI read interfaces. //
[ "Goroutine", "which", "implements", "AXI", "arbitration", "between", "two", "AXI", "read", "interfaces", "." ]
26602ba933e27e55e04d18f65b3bb16a12950350
https://github.com/ReconfigureIO/sdaccel/blob/26602ba933e27e55e04d18f65b3bb16a12950350/axi/arbitrate/axiarbitrate.go#L262-L307
153,201
ReconfigureIO/sdaccel
control/control.go
DisableWrites
func DisableWrites( controlWriteAddr <-chan Addr, controlWriteData <-chan WriteData, controlWriteResp chan<- WriteResp) { for { <-controlWriteAddr <-controlWriteData controlWriteResp <- WriteResp{} } }
go
func DisableWrites( controlWriteAddr <-chan Addr, controlWriteData <-chan WriteData, controlWriteResp chan<- WriteResp) { for { <-controlWriteAddr <-controlWriteData controlWriteResp <- WriteResp{} } }
[ "func", "DisableWrites", "(", "controlWriteAddr", "<-", "chan", "Addr", ",", "controlWriteData", "<-", "chan", "WriteData", ",", "controlWriteResp", "chan", "<-", "WriteResp", ")", "{", "for", "{", "<-", "controlWriteAddr", "\n", "<-", "controlWriteData", "\n", ...
// Goroutine to disable control bus write transactions. Should only be run once // for each control interface.
[ "Goroutine", "to", "disable", "control", "bus", "write", "transactions", ".", "Should", "only", "be", "run", "once", "for", "each", "control", "interface", "." ]
26602ba933e27e55e04d18f65b3bb16a12950350
https://github.com/ReconfigureIO/sdaccel/blob/26602ba933e27e55e04d18f65b3bb16a12950350/control/control.go#L49-L59
153,202
kyokomi/slackbot
slackbot.go
WebSocketRTM
func (ctx *Context) WebSocketRTM() { ctx.webSocketRTM(func(event plugins.BotEvent) { log.Println("connected ", event.Channel()) }) }
go
func (ctx *Context) WebSocketRTM() { ctx.webSocketRTM(func(event plugins.BotEvent) { log.Println("connected ", event.Channel()) }) }
[ "func", "(", "ctx", "*", "Context", ")", "WebSocketRTM", "(", ")", "{", "ctx", ".", "webSocketRTM", "(", "func", "(", "event", "plugins", ".", "BotEvent", ")", "{", "log", ".", "Println", "(", "\"", "\"", ",", "event", ".", "Channel", "(", ")", ")"...
// WebSocketRTM is Deprecated
[ "WebSocketRTM", "is", "Deprecated" ]
892540d8979144609b1c749693086bc781c78d43
https://github.com/kyokomi/slackbot/blob/892540d8979144609b1c749693086bc781c78d43/slackbot.go#L77-L79
153,203
favclip/ds2bq
gcs_watcher_handler.go
DecodeGCSObject
func DecodeGCSObject(r io.Reader) (*GCSObject, error) { decoder := json.NewDecoder(r) var obj *GCSObject err := decoder.Decode(&obj) if err != nil { return nil, err } return obj, nil }
go
func DecodeGCSObject(r io.Reader) (*GCSObject, error) { decoder := json.NewDecoder(r) var obj *GCSObject err := decoder.Decode(&obj) if err != nil { return nil, err } return obj, nil }
[ "func", "DecodeGCSObject", "(", "r", "io", ".", "Reader", ")", "(", "*", "GCSObject", ",", "error", ")", "{", "decoder", ":=", "json", ".", "NewDecoder", "(", "r", ")", "\n", "var", "obj", "*", "GCSObject", "\n", "err", ":=", "decoder", ".", "Decode"...
// DecodeGCSObject decodes a GCSObject from r.
[ "DecodeGCSObject", "decodes", "a", "GCSObject", "from", "r", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/gcs_watcher_handler.go#L13-L21
153,204
favclip/ds2bq
gcs_watcher_handler.go
DecodeGCSObjectToBQJobReq
func DecodeGCSObjectToBQJobReq(r io.Reader) (*GCSObjectToBQJobReq, error) { decoder := json.NewDecoder(r) var req *GCSObjectToBQJobReq err := decoder.Decode(&req) if err != nil { return nil, err } return req, nil }
go
func DecodeGCSObjectToBQJobReq(r io.Reader) (*GCSObjectToBQJobReq, error) { decoder := json.NewDecoder(r) var req *GCSObjectToBQJobReq err := decoder.Decode(&req) if err != nil { return nil, err } return req, nil }
[ "func", "DecodeGCSObjectToBQJobReq", "(", "r", "io", ".", "Reader", ")", "(", "*", "GCSObjectToBQJobReq", ",", "error", ")", "{", "decoder", ":=", "json", ".", "NewDecoder", "(", "r", ")", "\n", "var", "req", "*", "GCSObjectToBQJobReq", "\n", "err", ":=", ...
// DecodeGCSObjectToBQJobReq decodes a GCSObjectToBQJobReq from r.
[ "DecodeGCSObjectToBQJobReq", "decodes", "a", "GCSObjectToBQJobReq", "from", "r", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/gcs_watcher_handler.go#L24-L32
153,205
favclip/ds2bq
gcs_watcher_handler.go
ReceiveOCNHandleFunc
func ReceiveOCNHandleFunc(bucketName, queueName, path string, kindNames []string) http.HandlerFunc { // TODO: processWithContext return func(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) obj, err := DecodeGCSObject(r.Body) if err != nil { log.Errorf(c, "ds2bq: failed to decode request: %s", err) return } defer r.Body.Close() if !obj.IsImportTarget(c, r, bucketName, kindNames) { return } err = ReceiveOCN(c, obj, queueName, path) if err != nil { log.Errorf(c, "ds2bq: failed to receive OCN: %s", err) return } } }
go
func ReceiveOCNHandleFunc(bucketName, queueName, path string, kindNames []string) http.HandlerFunc { // TODO: processWithContext return func(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) obj, err := DecodeGCSObject(r.Body) if err != nil { log.Errorf(c, "ds2bq: failed to decode request: %s", err) return } defer r.Body.Close() if !obj.IsImportTarget(c, r, bucketName, kindNames) { return } err = ReceiveOCN(c, obj, queueName, path) if err != nil { log.Errorf(c, "ds2bq: failed to receive OCN: %s", err) return } } }
[ "func", "ReceiveOCNHandleFunc", "(", "bucketName", ",", "queueName", ",", "path", "string", ",", "kindNames", "[", "]", "string", ")", "http", ".", "HandlerFunc", "{", "// TODO: processWithContext", "return", "func", "(", "w", "http", ".", "ResponseWriter", ",",...
// ReceiveOCNHandleFunc returns a http.HandlerFunc that receives OCN. // The path is for
[ "ReceiveOCNHandleFunc", "returns", "a", "http", ".", "HandlerFunc", "that", "receives", "OCN", ".", "The", "path", "is", "for" ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/gcs_watcher_handler.go#L36-L58
153,206
favclip/ds2bq
gcs_watcher_handler.go
ImportBigQueryHandleFunc
func ImportBigQueryHandleFunc(datasetID string) http.HandlerFunc { // TODO: processWithContext return func(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) req, err := DecodeGCSObjectToBQJobReq(r.Body) if err != nil { log.Errorf(c, "ds2bq: failed to decode request: %s", err) return } defer r.Body.Close() err = insertImportJob(c, req, datasetID) if err != nil { log.Errorf(c, "ds2bq: failed to import BigQuery: %s", err) return } } }
go
func ImportBigQueryHandleFunc(datasetID string) http.HandlerFunc { // TODO: processWithContext return func(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) req, err := DecodeGCSObjectToBQJobReq(r.Body) if err != nil { log.Errorf(c, "ds2bq: failed to decode request: %s", err) return } defer r.Body.Close() err = insertImportJob(c, req, datasetID) if err != nil { log.Errorf(c, "ds2bq: failed to import BigQuery: %s", err) return } } }
[ "func", "ImportBigQueryHandleFunc", "(", "datasetID", "string", ")", "http", ".", "HandlerFunc", "{", "// TODO: processWithContext", "return", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "c", ":=", "appengi...
// ImportBigQueryHandleFunc returns a http.HandlerFunc that imports GCSObject to BigQuery.
[ "ImportBigQueryHandleFunc", "returns", "a", "http", ".", "HandlerFunc", "that", "imports", "GCSObject", "to", "BigQuery", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/gcs_watcher_handler.go#L61-L79
153,207
favclip/ds2bq
model_query.go
newAEDatastoreAdminOperationQueryBuilderWithKind
func newAEDatastoreAdminOperationQueryBuilderWithKind(kind string) *aeDatastoreAdminOperationQueryBuilder { q := datastore.NewQuery(kind) bldr := &aeDatastoreAdminOperationQueryBuilder{q: q} bldr.Kind = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "Kind", } bldr.ID = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "__key__", } bldr.ActiveJobIDs = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "active_job_ids", } bldr.ActiveJobs = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "active_jobs", } bldr.CompletedJobs = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "completed_jobs", } bldr.Description = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "description", } bldr.LastUpdated = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "last_updated", } bldr.ServiceJobID = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "service_job_id", } bldr.Status = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "status", } bldr.StatusInfo = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "status_info", } if plugger, ok := interface{}(bldr).(Plugger); ok { bldr.plugin = plugger.Plugin() bldr.plugin.Init("AEDatastoreAdminOperation") } return bldr }
go
func newAEDatastoreAdminOperationQueryBuilderWithKind(kind string) *aeDatastoreAdminOperationQueryBuilder { q := datastore.NewQuery(kind) bldr := &aeDatastoreAdminOperationQueryBuilder{q: q} bldr.Kind = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "Kind", } bldr.ID = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "__key__", } bldr.ActiveJobIDs = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "active_job_ids", } bldr.ActiveJobs = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "active_jobs", } bldr.CompletedJobs = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "completed_jobs", } bldr.Description = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "description", } bldr.LastUpdated = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "last_updated", } bldr.ServiceJobID = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "service_job_id", } bldr.Status = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "status", } bldr.StatusInfo = &aeDatastoreAdminOperationQueryProperty{ bldr: bldr, name: "status_info", } if plugger, ok := interface{}(bldr).(Plugger); ok { bldr.plugin = plugger.Plugin() bldr.plugin.Init("AEDatastoreAdminOperation") } return bldr }
[ "func", "newAEDatastoreAdminOperationQueryBuilderWithKind", "(", "kind", "string", ")", "*", "aeDatastoreAdminOperationQueryBuilder", "{", "q", ":=", "datastore", ".", "NewQuery", "(", "kind", ")", "\n", "bldr", ":=", "&", "aeDatastoreAdminOperationQueryBuilder", "{", "...
// newAEDatastoreAdminOperationQueryBuilderWithKind create new AEDatastoreAdminOperationQueryBuilder with specific kind.
[ "newAEDatastoreAdminOperationQueryBuilderWithKind", "create", "new", "AEDatastoreAdminOperationQueryBuilder", "with", "specific", "kind", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/model_query.go#L55-L105
153,208
favclip/ds2bq
model_query.go
newAEBackupInformationQueryBuilderWithKind
func newAEBackupInformationQueryBuilderWithKind(kind string) *aeBackupInformationQueryBuilder { q := datastore.NewQuery(kind) bldr := &aeBackupInformationQueryBuilder{q: q} bldr.Kind = &aeBackupInformationQueryProperty{ bldr: bldr, name: "Kind", } bldr.ID = &aeBackupInformationQueryProperty{ bldr: bldr, name: "__key__", } bldr.ActiveJobs = &aeBackupInformationQueryProperty{ bldr: bldr, name: "active_jobs", } bldr.CompleteTime = &aeBackupInformationQueryProperty{ bldr: bldr, name: "complete_time", } bldr.CompletedJobs = &aeBackupInformationQueryProperty{ bldr: bldr, name: "completed_jobs", } bldr.Destination = &aeBackupInformationQueryProperty{ bldr: bldr, name: "destination", } bldr.Filesystem = &aeBackupInformationQueryProperty{ bldr: bldr, name: "filesystem", } bldr.GSHandle = &aeBackupInformationQueryProperty{ bldr: bldr, name: "gs_handle", } bldr.Kinds = &aeBackupInformationQueryProperty{ bldr: bldr, name: "kinds", } bldr.Name = &aeBackupInformationQueryProperty{ bldr: bldr, name: "name", } bldr.OriginalApp = &aeBackupInformationQueryProperty{ bldr: bldr, name: "original_app", } bldr.StartTime = &aeBackupInformationQueryProperty{ bldr: bldr, name: "start_time", } if plugger, ok := interface{}(bldr).(Plugger); ok { bldr.plugin = plugger.Plugin() bldr.plugin.Init("AEBackupInformation") } return bldr }
go
func newAEBackupInformationQueryBuilderWithKind(kind string) *aeBackupInformationQueryBuilder { q := datastore.NewQuery(kind) bldr := &aeBackupInformationQueryBuilder{q: q} bldr.Kind = &aeBackupInformationQueryProperty{ bldr: bldr, name: "Kind", } bldr.ID = &aeBackupInformationQueryProperty{ bldr: bldr, name: "__key__", } bldr.ActiveJobs = &aeBackupInformationQueryProperty{ bldr: bldr, name: "active_jobs", } bldr.CompleteTime = &aeBackupInformationQueryProperty{ bldr: bldr, name: "complete_time", } bldr.CompletedJobs = &aeBackupInformationQueryProperty{ bldr: bldr, name: "completed_jobs", } bldr.Destination = &aeBackupInformationQueryProperty{ bldr: bldr, name: "destination", } bldr.Filesystem = &aeBackupInformationQueryProperty{ bldr: bldr, name: "filesystem", } bldr.GSHandle = &aeBackupInformationQueryProperty{ bldr: bldr, name: "gs_handle", } bldr.Kinds = &aeBackupInformationQueryProperty{ bldr: bldr, name: "kinds", } bldr.Name = &aeBackupInformationQueryProperty{ bldr: bldr, name: "name", } bldr.OriginalApp = &aeBackupInformationQueryProperty{ bldr: bldr, name: "original_app", } bldr.StartTime = &aeBackupInformationQueryProperty{ bldr: bldr, name: "start_time", } if plugger, ok := interface{}(bldr).(Plugger); ok { bldr.plugin = plugger.Plugin() bldr.plugin.Init("AEBackupInformation") } return bldr }
[ "func", "newAEBackupInformationQueryBuilderWithKind", "(", "kind", "string", ")", "*", "aeBackupInformationQueryBuilder", "{", "q", ":=", "datastore", ".", "NewQuery", "(", "kind", ")", "\n", "bldr", ":=", "&", "aeBackupInformationQueryBuilder", "{", "q", ":", "q", ...
// newAEBackupInformationQueryBuilderWithKind create new AEBackupInformationQueryBuilder with specific kind.
[ "newAEBackupInformationQueryBuilderWithKind", "create", "new", "AEBackupInformationQueryBuilder", "with", "specific", "kind", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/model_query.go#L272-L330
153,209
favclip/ds2bq
model_query.go
newAEBackupInformationKindFilesQueryBuilderWithKind
func newAEBackupInformationKindFilesQueryBuilderWithKind(kind string) *aeBackupInformationKindFilesQueryBuilder { q := datastore.NewQuery(kind) bldr := &aeBackupInformationKindFilesQueryBuilder{q: q} bldr.Kind = &aeBackupInformationKindFilesQueryProperty{ bldr: bldr, name: "Kind", } bldr.ID = &aeBackupInformationKindFilesQueryProperty{ bldr: bldr, name: "__key__", } bldr.Files = &aeBackupInformationKindFilesQueryProperty{ bldr: bldr, name: "files", } if plugger, ok := interface{}(bldr).(Plugger); ok { bldr.plugin = plugger.Plugin() bldr.plugin.Init("AEBackupInformationKindFiles") } return bldr }
go
func newAEBackupInformationKindFilesQueryBuilderWithKind(kind string) *aeBackupInformationKindFilesQueryBuilder { q := datastore.NewQuery(kind) bldr := &aeBackupInformationKindFilesQueryBuilder{q: q} bldr.Kind = &aeBackupInformationKindFilesQueryProperty{ bldr: bldr, name: "Kind", } bldr.ID = &aeBackupInformationKindFilesQueryProperty{ bldr: bldr, name: "__key__", } bldr.Files = &aeBackupInformationKindFilesQueryProperty{ bldr: bldr, name: "files", } if plugger, ok := interface{}(bldr).(Plugger); ok { bldr.plugin = plugger.Plugin() bldr.plugin.Init("AEBackupInformationKindFiles") } return bldr }
[ "func", "newAEBackupInformationKindFilesQueryBuilderWithKind", "(", "kind", "string", ")", "*", "aeBackupInformationKindFilesQueryBuilder", "{", "q", ":=", "datastore", ".", "NewQuery", "(", "kind", ")", "\n", "bldr", ":=", "&", "aeBackupInformationKindFilesQueryBuilder", ...
// newAEBackupInformationKindFilesQueryBuilderWithKind create new AEBackupInformationKindFilesQueryBuilder with specific kind.
[ "newAEBackupInformationKindFilesQueryBuilderWithKind", "create", "new", "AEBackupInformationKindFilesQueryBuilder", "with", "specific", "kind", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/model_query.go#L488-L510
153,210
favclip/ds2bq
model_query.go
newAEBackupKindQueryBuilderWithKind
func newAEBackupKindQueryBuilderWithKind(kind string) *aeBackupKindQueryBuilder { q := datastore.NewQuery(kind) bldr := &aeBackupKindQueryBuilder{q: q} bldr.Kind = &aeBackupKindQueryProperty{ bldr: bldr, name: "Kind", } bldr.ID = &aeBackupKindQueryProperty{ bldr: bldr, name: "__key__", } if plugger, ok := interface{}(bldr).(Plugger); ok { bldr.plugin = plugger.Plugin() bldr.plugin.Init("AEBackupKind") } return bldr }
go
func newAEBackupKindQueryBuilderWithKind(kind string) *aeBackupKindQueryBuilder { q := datastore.NewQuery(kind) bldr := &aeBackupKindQueryBuilder{q: q} bldr.Kind = &aeBackupKindQueryProperty{ bldr: bldr, name: "Kind", } bldr.ID = &aeBackupKindQueryProperty{ bldr: bldr, name: "__key__", } if plugger, ok := interface{}(bldr).(Plugger); ok { bldr.plugin = plugger.Plugin() bldr.plugin.Init("AEBackupKind") } return bldr }
[ "func", "newAEBackupKindQueryBuilderWithKind", "(", "kind", "string", ")", "*", "aeBackupKindQueryBuilder", "{", "q", ":=", "datastore", ".", "NewQuery", "(", "kind", ")", "\n", "bldr", ":=", "&", "aeBackupKindQueryBuilder", "{", "q", ":", "q", "}", "\n", "bld...
// newAEBackupKindQueryBuilderWithKind create new AEBackupKindQueryBuilder with specific kind.
[ "newAEBackupKindQueryBuilderWithKind", "create", "new", "AEBackupKindQueryBuilder", "with", "specific", "kind", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/model_query.go#L667-L685
153,211
favclip/ds2bq
model_query.go
newAEBackupInformationKindTypeInfoQueryBuilderWithKind
func newAEBackupInformationKindTypeInfoQueryBuilderWithKind(kind string) *aeBackupInformationKindTypeInfoQueryBuilder { q := datastore.NewQuery(kind) bldr := &aeBackupInformationKindTypeInfoQueryBuilder{q: q} bldr.Kind = &aeBackupInformationKindTypeInfoQueryProperty{ bldr: bldr, name: "Kind", } bldr.ID = &aeBackupInformationKindTypeInfoQueryProperty{ bldr: bldr, name: "__key__", } bldr.EntityTypeInfo = &aeBackupInformationKindTypeInfoQueryProperty{ bldr: bldr, name: "entity_type_info", } bldr.IsPartial = &aeBackupInformationKindTypeInfoQueryProperty{ bldr: bldr, name: "is_partial", } if plugger, ok := interface{}(bldr).(Plugger); ok { bldr.plugin = plugger.Plugin() bldr.plugin.Init("AEBackupInformationKindTypeInfo") } return bldr }
go
func newAEBackupInformationKindTypeInfoQueryBuilderWithKind(kind string) *aeBackupInformationKindTypeInfoQueryBuilder { q := datastore.NewQuery(kind) bldr := &aeBackupInformationKindTypeInfoQueryBuilder{q: q} bldr.Kind = &aeBackupInformationKindTypeInfoQueryProperty{ bldr: bldr, name: "Kind", } bldr.ID = &aeBackupInformationKindTypeInfoQueryProperty{ bldr: bldr, name: "__key__", } bldr.EntityTypeInfo = &aeBackupInformationKindTypeInfoQueryProperty{ bldr: bldr, name: "entity_type_info", } bldr.IsPartial = &aeBackupInformationKindTypeInfoQueryProperty{ bldr: bldr, name: "is_partial", } if plugger, ok := interface{}(bldr).(Plugger); ok { bldr.plugin = plugger.Plugin() bldr.plugin.Init("AEBackupInformationKindTypeInfo") } return bldr }
[ "func", "newAEBackupInformationKindTypeInfoQueryBuilderWithKind", "(", "kind", "string", ")", "*", "aeBackupInformationKindTypeInfoQueryBuilder", "{", "q", ":=", "datastore", ".", "NewQuery", "(", "kind", ")", "\n", "bldr", ":=", "&", "aeBackupInformationKindTypeInfoQueryBu...
// newAEBackupInformationKindTypeInfoQueryBuilderWithKind create new AEBackupInformationKindTypeInfoQueryBuilder with specific kind.
[ "newAEBackupInformationKindTypeInfoQueryBuilderWithKind", "create", "new", "AEBackupInformationKindTypeInfoQueryBuilder", "with", "specific", "kind", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/model_query.go#L844-L870
153,212
favclip/ds2bq
gcs_watcher.go
ExtractKindName
func (obj *GCSObject) ExtractKindName() string { if id := obj.extractKindNameForDatastoreAdmin(obj.Name); len(id) > 0 { return id } if id := obj.extractKindNameForDatastoreExport(obj.Name); len(id) > 0 { return id } return "" }
go
func (obj *GCSObject) ExtractKindName() string { if id := obj.extractKindNameForDatastoreAdmin(obj.Name); len(id) > 0 { return id } if id := obj.extractKindNameForDatastoreExport(obj.Name); len(id) > 0 { return id } return "" }
[ "func", "(", "obj", "*", "GCSObject", ")", "ExtractKindName", "(", ")", "string", "{", "if", "id", ":=", "obj", ".", "extractKindNameForDatastoreAdmin", "(", "obj", ".", "Name", ")", ";", "len", "(", "id", ")", ">", "0", "{", "return", "id", "\n", "}...
// ExtractKindName extracts kind name from the object name.
[ "ExtractKindName", "extracts", "kind", "name", "from", "the", "object", "name", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/gcs_watcher.go#L20-L28
153,213
favclip/ds2bq
gcs_watcher.go
extractKindNameForDatastoreAdmin
func (obj *GCSObject) extractKindNameForDatastoreAdmin(name string) string { if v := strings.LastIndex(name, "/"); v != -1 { name = name[v:] } vs := strings.Split(name, ".") if len(vs) != 3 { return "" } if vs[2] != "backup_info" { return "" } return vs[1] }
go
func (obj *GCSObject) extractKindNameForDatastoreAdmin(name string) string { if v := strings.LastIndex(name, "/"); v != -1 { name = name[v:] } vs := strings.Split(name, ".") if len(vs) != 3 { return "" } if vs[2] != "backup_info" { return "" } return vs[1] }
[ "func", "(", "obj", "*", "GCSObject", ")", "extractKindNameForDatastoreAdmin", "(", "name", "string", ")", "string", "{", "if", "v", ":=", "strings", ".", "LastIndex", "(", "name", ",", "\"", "\"", ")", ";", "v", "!=", "-", "1", "{", "name", "=", "na...
// extractKindName from agtzfnN0Zy1jaGFvc3JACxIcX0FFX0RhdGFzdG9yZUFkbWluX09wZXJhdGlvbhjx52oMCxIWX0FFX0JhY2t1cF9JbmZvcm1hdGlvbhgBDA.Article.backup_info like ID value.
[ "extractKindName", "from", "agtzfnN0Zy1jaGFvc3JACxIcX0FFX0RhdGFzdG9yZUFkbWluX09wZXJhdGlvbhjx52oMCxIWX0FFX0JhY2t1cF9JbmZvcm1hdGlvbhgBDA", ".", "Article", ".", "backup_info", "like", "ID", "value", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/gcs_watcher.go#L31-L43
153,214
favclip/ds2bq
gcs_watcher.go
IsRequiredKind
func (obj *GCSObject) IsRequiredKind(requires []string) bool { kindName := obj.ExtractKindName() for _, k := range requires { if k == kindName { return true } } return false }
go
func (obj *GCSObject) IsRequiredKind(requires []string) bool { kindName := obj.ExtractKindName() for _, k := range requires { if k == kindName { return true } } return false }
[ "func", "(", "obj", "*", "GCSObject", ")", "IsRequiredKind", "(", "requires", "[", "]", "string", ")", "bool", "{", "kindName", ":=", "obj", ".", "ExtractKindName", "(", ")", "\n", "for", "_", ",", "k", ":=", "range", "requires", "{", "if", "k", "=="...
// IsRequiredKind reports whether the GCSObject is related required kind.
[ "IsRequiredKind", "reports", "whether", "the", "GCSObject", "is", "related", "required", "kind", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/gcs_watcher.go#L67-L75
153,215
favclip/ds2bq
gcs_watcher.go
IsImportTarget
func (obj *GCSObject) IsImportTarget(c context.Context, r *http.Request, bucketName string, kindNames []string) bool { if bucketName != "" && obj.Bucket != bucketName { log.Infof(c, "ds2bq: %s is unexpected bucket", obj.Bucket) return false } gcsHeader := NewGCSHeader(r) if gcsHeader.ResourceState != "exists" { log.Infof(c, "ds2bq: %s is unexpected state", gcsHeader.ResourceState) return false } if obj.ExtractKindName() == "" { log.Infof(c, "ds2bq: this is not backup file: %s", obj.Name) return false } if !obj.IsRequiredKind(kindNames) { log.Infof(c, "ds2bq: %s is not required kind", obj.ExtractKindName()) return false } log.Infof(c, "ds2bq: %s should imports", obj.Name) return true }
go
func (obj *GCSObject) IsImportTarget(c context.Context, r *http.Request, bucketName string, kindNames []string) bool { if bucketName != "" && obj.Bucket != bucketName { log.Infof(c, "ds2bq: %s is unexpected bucket", obj.Bucket) return false } gcsHeader := NewGCSHeader(r) if gcsHeader.ResourceState != "exists" { log.Infof(c, "ds2bq: %s is unexpected state", gcsHeader.ResourceState) return false } if obj.ExtractKindName() == "" { log.Infof(c, "ds2bq: this is not backup file: %s", obj.Name) return false } if !obj.IsRequiredKind(kindNames) { log.Infof(c, "ds2bq: %s is not required kind", obj.ExtractKindName()) return false } log.Infof(c, "ds2bq: %s should imports", obj.Name) return true }
[ "func", "(", "obj", "*", "GCSObject", ")", "IsImportTarget", "(", "c", "context", ".", "Context", ",", "r", "*", "http", ".", "Request", ",", "bucketName", "string", ",", "kindNames", "[", "]", "string", ")", "bool", "{", "if", "bucketName", "!=", "\""...
// IsImportTarget reports whether the GCSObject is an import target.
[ "IsImportTarget", "reports", "whether", "the", "GCSObject", "is", "an", "import", "target", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/gcs_watcher.go#L78-L98
153,216
favclip/ds2bq
gcs_watcher.go
ToBQJobReq
func (obj *GCSObject) ToBQJobReq() *GCSObjectToBQJobReq { return &GCSObjectToBQJobReq{ Bucket: obj.Bucket, FilePath: obj.Name, KindName: obj.ExtractKindName(), TimeCreated: obj.TimeCreated, } }
go
func (obj *GCSObject) ToBQJobReq() *GCSObjectToBQJobReq { return &GCSObjectToBQJobReq{ Bucket: obj.Bucket, FilePath: obj.Name, KindName: obj.ExtractKindName(), TimeCreated: obj.TimeCreated, } }
[ "func", "(", "obj", "*", "GCSObject", ")", "ToBQJobReq", "(", ")", "*", "GCSObjectToBQJobReq", "{", "return", "&", "GCSObjectToBQJobReq", "{", "Bucket", ":", "obj", ".", "Bucket", ",", "FilePath", ":", "obj", ".", "Name", ",", "KindName", ":", "obj", "."...
// ToBQJobReq creates a new GCSObjectToBQJobReq from the object.
[ "ToBQJobReq", "creates", "a", "new", "GCSObjectToBQJobReq", "from", "the", "object", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/gcs_watcher.go#L101-L108
153,217
favclip/ds2bq
gcs_watcher.go
NewGCSHeader
func NewGCSHeader(r *http.Request) *GCSHeader { return &GCSHeader{ ChannelID: r.Header.Get("X-Goog-Channel-Id"), ClientToken: r.Header.Get("X-Goog-Channel-Token"), ResourceID: r.Header.Get("X-Goog-Resource-Id"), ResourceState: r.Header.Get("X-Goog-Resource-State"), ResourceURI: r.Header.Get("X-Goog-Resource-Uri"), } }
go
func NewGCSHeader(r *http.Request) *GCSHeader { return &GCSHeader{ ChannelID: r.Header.Get("X-Goog-Channel-Id"), ClientToken: r.Header.Get("X-Goog-Channel-Token"), ResourceID: r.Header.Get("X-Goog-Resource-Id"), ResourceState: r.Header.Get("X-Goog-Resource-State"), ResourceURI: r.Header.Get("X-Goog-Resource-Uri"), } }
[ "func", "NewGCSHeader", "(", "r", "*", "http", ".", "Request", ")", "*", "GCSHeader", "{", "return", "&", "GCSHeader", "{", "ChannelID", ":", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "ClientToken", ":", "r", ".", "Header", ".", "G...
// NewGCSHeader returns the header from r.
[ "NewGCSHeader", "returns", "the", "header", "from", "r", "." ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/gcs_watcher.go#L121-L129
153,218
favclip/ds2bq
gcs_watcher.go
ReceiveOCN
func ReceiveOCN(c context.Context, obj *GCSObject, queueName, path string) error { req := obj.ToBQJobReq() b, err := json.MarshalIndent(req, "", " ") if err != nil { return err } h := make(http.Header) h.Set("Content-Type", "application/json") t := &taskqueue.Task{ Path: path, Payload: b, Header: h, Method: "POST", } _, err = taskqueue.Add(c, t, queueName) return err }
go
func ReceiveOCN(c context.Context, obj *GCSObject, queueName, path string) error { req := obj.ToBQJobReq() b, err := json.MarshalIndent(req, "", " ") if err != nil { return err } h := make(http.Header) h.Set("Content-Type", "application/json") t := &taskqueue.Task{ Path: path, Payload: b, Header: h, Method: "POST", } _, err = taskqueue.Add(c, t, queueName) return err }
[ "func", "ReceiveOCN", "(", "c", "context", ".", "Context", ",", "obj", "*", "GCSObject", ",", "queueName", ",", "path", "string", ")", "error", "{", "req", ":=", "obj", ".", "ToBQJobReq", "(", ")", "\n", "b", ",", "err", ":=", "json", ".", "MarshalIn...
// ReceiveOCN is Process payload of Object Change Notification
[ "ReceiveOCN", "is", "Process", "payload", "of", "Object", "Change", "Notification" ]
73bc787eb607dae80eb1dd085a37e3a4123a77bb
https://github.com/favclip/ds2bq/blob/73bc787eb607dae80eb1dd085a37e3a4123a77bb/gcs_watcher.go#L132-L150
153,219
cloudfoundry-community/gogobosh
client.go
DefaultConfig
func DefaultConfig() *Config { return &Config{ BOSHAddress: "https://192.168.50.4:25555", Username: "admin", Password: "admin", HttpClient: http.DefaultClient, SkipSslValidation: true, } }
go
func DefaultConfig() *Config { return &Config{ BOSHAddress: "https://192.168.50.4:25555", Username: "admin", Password: "admin", HttpClient: http.DefaultClient, SkipSslValidation: true, } }
[ "func", "DefaultConfig", "(", ")", "*", "Config", "{", "return", "&", "Config", "{", "BOSHAddress", ":", "\"", "\"", ",", "Username", ":", "\"", "\"", ",", "Password", ":", "\"", "\"", ",", "HttpClient", ":", "http", ".", "DefaultClient", ",", "SkipSsl...
//DefaultConfig configuration for client
[ "DefaultConfig", "configuration", "for", "client" ]
8c9e0d747e480a6373564c51f14d62252c0ef4e5
https://github.com/cloudfoundry-community/gogobosh/blob/8c9e0d747e480a6373564c51f14d62252c0ef4e5/client.go#L56-L64
153,220
cloudfoundry-community/gogobosh
client.go
NewRequest
func (c *Client) NewRequest(method, path string) *request { r := &request{ method: method, url: c.config.BOSHAddress + path, params: make(map[string][]string), header: make(map[string]string), } return r }
go
func (c *Client) NewRequest(method, path string) *request { r := &request{ method: method, url: c.config.BOSHAddress + path, params: make(map[string][]string), header: make(map[string]string), } return r }
[ "func", "(", "c", "*", "Client", ")", "NewRequest", "(", "method", ",", "path", "string", ")", "*", "request", "{", "r", ":=", "&", "request", "{", "method", ":", "method", ",", "url", ":", "c", ".", "config", ".", "BOSHAddress", "+", "path", ",", ...
// NewRequest is used to create a new request
[ "NewRequest", "is", "used", "to", "create", "a", "new", "request" ]
8c9e0d747e480a6373564c51f14d62252c0ef4e5
https://github.com/cloudfoundry-community/gogobosh/blob/8c9e0d747e480a6373564c51f14d62252c0ef4e5/client.go#L212-L220
153,221
cloudfoundry-community/gogobosh
client.go
UUID
func (c *Client) UUID() string { info, _ := c.GetInfo() return info.UUID }
go
func (c *Client) UUID() string { info, _ := c.GetInfo() return info.UUID }
[ "func", "(", "c", "*", "Client", ")", "UUID", "(", ")", "string", "{", "info", ",", "_", ":=", "c", ".", "GetInfo", "(", ")", "\n", "return", "info", ".", "UUID", "\n", "}" ]
// UUID return uuid
[ "UUID", "return", "uuid" ]
8c9e0d747e480a6373564c51f14d62252c0ef4e5
https://github.com/cloudfoundry-community/gogobosh/blob/8c9e0d747e480a6373564c51f14d62252c0ef4e5/client.go#L244-L247
153,222
cloudfoundry-community/gogobosh
client.go
GetInfo
func (c *Client) GetInfo() (info Info, err error) { r := c.NewRequest("GET", "/info") resp, err := c.DoRequest(r) if err != nil { log.Printf("Error requesting info %v", err) return } defer resp.Body.Close() resBody, err := ioutil.ReadAll(resp.Body) if err != nil { log.Printf("Error reading info request %v", resBody) return } err = json.Unmarshal(resBody, &info) if err != nil { log.Printf("Error unmarshaling info %v", err) return } return }
go
func (c *Client) GetInfo() (info Info, err error) { r := c.NewRequest("GET", "/info") resp, err := c.DoRequest(r) if err != nil { log.Printf("Error requesting info %v", err) return } defer resp.Body.Close() resBody, err := ioutil.ReadAll(resp.Body) if err != nil { log.Printf("Error reading info request %v", resBody) return } err = json.Unmarshal(resBody, &info) if err != nil { log.Printf("Error unmarshaling info %v", err) return } return }
[ "func", "(", "c", "*", "Client", ")", "GetInfo", "(", ")", "(", "info", "Info", ",", "err", "error", ")", "{", "r", ":=", "c", ".", "NewRequest", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(...
// GetInfo returns BOSH Info
[ "GetInfo", "returns", "BOSH", "Info" ]
8c9e0d747e480a6373564c51f14d62252c0ef4e5
https://github.com/cloudfoundry-community/gogobosh/blob/8c9e0d747e480a6373564c51f14d62252c0ef4e5/client.go#L250-L271
153,223
cloudfoundry-community/gogobosh
client.go
GetToken
func (c *Client) GetToken() (string, error) { token, err := c.config.TokenSource.Token() if err != nil { return "", fmt.Errorf("Error getting bearer token: %v", err) } return "bearer " + token.AccessToken, nil }
go
func (c *Client) GetToken() (string, error) { token, err := c.config.TokenSource.Token() if err != nil { return "", fmt.Errorf("Error getting bearer token: %v", err) } return "bearer " + token.AccessToken, nil }
[ "func", "(", "c", "*", "Client", ")", "GetToken", "(", ")", "(", "string", ",", "error", ")", "{", "token", ",", "err", ":=", "c", ".", "config", ".", "TokenSource", ".", "Token", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "...
// GetToken - returns the current token bearer
[ "GetToken", "-", "returns", "the", "current", "token", "bearer" ]
8c9e0d747e480a6373564c51f14d62252c0ef4e5
https://github.com/cloudfoundry-community/gogobosh/blob/8c9e0d747e480a6373564c51f14d62252c0ef4e5/client.go#L330-L336
153,224
ONSdigital/go-ns
clients/dataset/dataset.go
NewAPIClient
func NewAPIClient(datasetAPIURL, serviceToken, xDownloadServiceToken string) *Client { return &Client{ cli: rchttp.ClientWithDownloadServiceToken( rchttp.ClientWithServiceToken(nil, serviceToken), xDownloadServiceToken, ), url: datasetAPIURL, } }
go
func NewAPIClient(datasetAPIURL, serviceToken, xDownloadServiceToken string) *Client { return &Client{ cli: rchttp.ClientWithDownloadServiceToken( rchttp.ClientWithServiceToken(nil, serviceToken), xDownloadServiceToken, ), url: datasetAPIURL, } }
[ "func", "NewAPIClient", "(", "datasetAPIURL", ",", "serviceToken", ",", "xDownloadServiceToken", "string", ")", "*", "Client", "{", "return", "&", "Client", "{", "cli", ":", "rchttp", ".", "ClientWithDownloadServiceToken", "(", "rchttp", ".", "ClientWithServiceToken...
// NewAPIClient creates a new instance of Client with a given dataset api url and the relevant tokens
[ "NewAPIClient", "creates", "a", "new", "instance", "of", "Client", "with", "a", "given", "dataset", "api", "url", "and", "the", "relevant", "tokens" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/dataset/dataset.go#L51-L59
153,225
ONSdigital/go-ns
clients/dataset/dataset.go
Get
func (c *Client) Get(ctx context.Context, id string) (m Model, err error) { uri := fmt.Sprintf("%s/datasets/%s", c.url, id) clientlog.Do(ctx, "retrieving dataset", service, uri) req, err := http.NewRequest("GET", uri, nil) if err != nil { return } resp, err := c.cli.Do(ctx, req) if err != nil { return } if resp.StatusCode != http.StatusOK { err = NewDatasetAPIResponse(resp, uri) return } b, err := ioutil.ReadAll(resp.Body) if err != nil { return } defer resp.Body.Close() var body map[string]interface{} if err = json.Unmarshal(b, &body); err != nil { return } // TODO: Authentication will sort this problem out for us. Currently // the shape of the response body is different if you are authenticated // so return the "next" item only if next, ok := body["next"]; ok && (common.IsCallerPresent(ctx) || common.IsFlorenceIdentityPresent(ctx)) { b, err = json.Marshal(next) if err != nil { return } } err = json.Unmarshal(b, &m) return }
go
func (c *Client) Get(ctx context.Context, id string) (m Model, err error) { uri := fmt.Sprintf("%s/datasets/%s", c.url, id) clientlog.Do(ctx, "retrieving dataset", service, uri) req, err := http.NewRequest("GET", uri, nil) if err != nil { return } resp, err := c.cli.Do(ctx, req) if err != nil { return } if resp.StatusCode != http.StatusOK { err = NewDatasetAPIResponse(resp, uri) return } b, err := ioutil.ReadAll(resp.Body) if err != nil { return } defer resp.Body.Close() var body map[string]interface{} if err = json.Unmarshal(b, &body); err != nil { return } // TODO: Authentication will sort this problem out for us. Currently // the shape of the response body is different if you are authenticated // so return the "next" item only if next, ok := body["next"]; ok && (common.IsCallerPresent(ctx) || common.IsFlorenceIdentityPresent(ctx)) { b, err = json.Marshal(next) if err != nil { return } } err = json.Unmarshal(b, &m) return }
[ "func", "(", "c", "*", "Client", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "(", "m", "Model", ",", "err", "error", ")", "{", "uri", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "url", ",", "i...
// Get returns dataset level information for a given dataset id
[ "Get", "returns", "dataset", "level", "information", "for", "a", "given", "dataset", "id" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/dataset/dataset.go#L78-L121
153,226
ONSdigital/go-ns
clients/dataset/dataset.go
GetDatasets
func (c *Client) GetDatasets(ctx context.Context) (m ModelCollection, err error) { uri := fmt.Sprintf("%s/datasets", c.url) clientlog.Do(ctx, "retrieving datasets", service, uri) req, err := http.NewRequest("GET", uri, nil) if err != nil { return } resp, err := c.cli.Do(ctx, req) if err != nil { return } if resp.StatusCode != http.StatusOK { err = NewDatasetAPIResponse(resp, uri) return } b, err := ioutil.ReadAll(resp.Body) if err != nil { return } defer resp.Body.Close() var body map[string]interface{} if err = json.Unmarshal(b, &body); err != nil { return } return }
go
func (c *Client) GetDatasets(ctx context.Context) (m ModelCollection, err error) { uri := fmt.Sprintf("%s/datasets", c.url) clientlog.Do(ctx, "retrieving datasets", service, uri) req, err := http.NewRequest("GET", uri, nil) if err != nil { return } resp, err := c.cli.Do(ctx, req) if err != nil { return } if resp.StatusCode != http.StatusOK { err = NewDatasetAPIResponse(resp, uri) return } b, err := ioutil.ReadAll(resp.Body) if err != nil { return } defer resp.Body.Close() var body map[string]interface{} if err = json.Unmarshal(b, &body); err != nil { return } return }
[ "func", "(", "c", "*", "Client", ")", "GetDatasets", "(", "ctx", "context", ".", "Context", ")", "(", "m", "ModelCollection", ",", "err", "error", ")", "{", "uri", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "url", ")", "\n\n", "...
// GetDatasets returns the list of datasets
[ "GetDatasets", "returns", "the", "list", "of", "datasets" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/dataset/dataset.go#L124-L156
153,227
ONSdigital/go-ns
clients/dataset/dataset.go
GetEditions
func (c *Client) GetEditions(ctx context.Context, id string) (m []Edition, err error) { uri := fmt.Sprintf("%s/datasets/%s/editions", c.url, id) clientlog.Do(ctx, "retrieving dataset editions", service, uri) req, err := http.NewRequest("GET", uri, nil) if err != nil { return } resp, err := c.cli.Do(ctx, req) if err != nil { return } if resp.StatusCode != http.StatusOK { err = NewDatasetAPIResponse(resp, uri) return } b, err := ioutil.ReadAll(resp.Body) if err != nil { return } defer resp.Body.Close() var body map[string]interface{} if err = json.Unmarshal(b, &body); err != nil { return nil, nil } if _, ok := body["items"].([]interface{})[0].(map[string]interface{})["next"]; ok && common.IsCallerPresent(ctx) { var items []map[string]interface{} for _, item := range body["items"].([]interface{}) { items = append(items, item.(map[string]interface{})["next"].(map[string]interface{})) } parentItems := make(map[string]interface{}) parentItems["items"] = items b, err = json.Marshal(parentItems) if err != nil { return } } editions := struct { Items []Edition `json:"items"` }{} err = json.Unmarshal(b, &editions) m = editions.Items return }
go
func (c *Client) GetEditions(ctx context.Context, id string) (m []Edition, err error) { uri := fmt.Sprintf("%s/datasets/%s/editions", c.url, id) clientlog.Do(ctx, "retrieving dataset editions", service, uri) req, err := http.NewRequest("GET", uri, nil) if err != nil { return } resp, err := c.cli.Do(ctx, req) if err != nil { return } if resp.StatusCode != http.StatusOK { err = NewDatasetAPIResponse(resp, uri) return } b, err := ioutil.ReadAll(resp.Body) if err != nil { return } defer resp.Body.Close() var body map[string]interface{} if err = json.Unmarshal(b, &body); err != nil { return nil, nil } if _, ok := body["items"].([]interface{})[0].(map[string]interface{})["next"]; ok && common.IsCallerPresent(ctx) { var items []map[string]interface{} for _, item := range body["items"].([]interface{}) { items = append(items, item.(map[string]interface{})["next"].(map[string]interface{})) } parentItems := make(map[string]interface{}) parentItems["items"] = items b, err = json.Marshal(parentItems) if err != nil { return } } editions := struct { Items []Edition `json:"items"` }{} err = json.Unmarshal(b, &editions) m = editions.Items return }
[ "func", "(", "c", "*", "Client", ")", "GetEditions", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "(", "m", "[", "]", "Edition", ",", "err", "error", ")", "{", "uri", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", "...
// GetEditions returns all editions for a dataset
[ "GetEditions", "returns", "all", "editions", "for", "a", "dataset" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/dataset/dataset.go#L202-L252
153,228
ONSdigital/go-ns
clients/dataset/dataset.go
PutVersion
func (c *Client) PutVersion(ctx context.Context, datasetID, edition, version string, v Version) error { uri := fmt.Sprintf("%s/datasets/%s/editions/%s/versions/%s", c.url, datasetID, edition, version) clientlog.Do(ctx, "updating version", service, uri) b, err := json.Marshal(v) if err != nil { return errors.Wrap(err, "error while attempting to marshall version") } req, err := http.NewRequest(http.MethodPut, uri, bytes.NewBuffer(b)) if err != nil { return errors.Wrap(err, "error while attempting to create http request") } resp, err := c.cli.Do(ctx, req) if err != nil { return errors.Wrap(err, "http client returned error while attempting to make request") } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return errors.Errorf("incorrect http status, expected: 200, actual: %d, uri: %s", resp.StatusCode, uri) } return nil }
go
func (c *Client) PutVersion(ctx context.Context, datasetID, edition, version string, v Version) error { uri := fmt.Sprintf("%s/datasets/%s/editions/%s/versions/%s", c.url, datasetID, edition, version) clientlog.Do(ctx, "updating version", service, uri) b, err := json.Marshal(v) if err != nil { return errors.Wrap(err, "error while attempting to marshall version") } req, err := http.NewRequest(http.MethodPut, uri, bytes.NewBuffer(b)) if err != nil { return errors.Wrap(err, "error while attempting to create http request") } resp, err := c.cli.Do(ctx, req) if err != nil { return errors.Wrap(err, "http client returned error while attempting to make request") } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return errors.Errorf("incorrect http status, expected: 200, actual: %d, uri: %s", resp.StatusCode, uri) } return nil }
[ "func", "(", "c", "*", "Client", ")", "PutVersion", "(", "ctx", "context", ".", "Context", ",", "datasetID", ",", "edition", ",", "version", "string", ",", "v", "Version", ")", "error", "{", "uri", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", ...
// PutVersion update the version
[ "PutVersion", "update", "the", "version" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/dataset/dataset.go#L353-L378
153,229
ONSdigital/go-ns
clients/dataset/dataset.go
GetMetadataURL
func (c *Client) GetMetadataURL(id, edition, version string) string { return fmt.Sprintf("%s/datasets/%s/editions/%s/versions/%s/metadata", c.url, id, edition, version) }
go
func (c *Client) GetMetadataURL(id, edition, version string) string { return fmt.Sprintf("%s/datasets/%s/editions/%s/versions/%s/metadata", c.url, id, edition, version) }
[ "func", "(", "c", "*", "Client", ")", "GetMetadataURL", "(", "id", ",", "edition", ",", "version", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "url", ",", "id", ",", "edition", ",", "version", ")",...
// GetMetadataURL returns the URL for the metadata of a given dataset id, edition and version
[ "GetMetadataURL", "returns", "the", "URL", "for", "the", "metadata", "of", "a", "given", "dataset", "id", "edition", "and", "version" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/dataset/dataset.go#L381-L383
153,230
ONSdigital/go-ns
clients/dataset/dataset.go
NewDatasetAPIResponse
func NewDatasetAPIResponse(resp *http.Response, uri string) (e *ErrInvalidDatasetAPIResponse) { e = &ErrInvalidDatasetAPIResponse{ actualCode: resp.StatusCode, uri: uri, } if resp.StatusCode == http.StatusNotFound { b, err := ioutil.ReadAll(resp.Body) if err != nil { e.body = "Client failed to read DatasetAPI body" return } defer resp.Body.Close() e.body = string(b) } return }
go
func NewDatasetAPIResponse(resp *http.Response, uri string) (e *ErrInvalidDatasetAPIResponse) { e = &ErrInvalidDatasetAPIResponse{ actualCode: resp.StatusCode, uri: uri, } if resp.StatusCode == http.StatusNotFound { b, err := ioutil.ReadAll(resp.Body) if err != nil { e.body = "Client failed to read DatasetAPI body" return } defer resp.Body.Close() e.body = string(b) } return }
[ "func", "NewDatasetAPIResponse", "(", "resp", "*", "http", ".", "Response", ",", "uri", "string", ")", "(", "e", "*", "ErrInvalidDatasetAPIResponse", ")", "{", "e", "=", "&", "ErrInvalidDatasetAPIResponse", "{", "actualCode", ":", "resp", ".", "StatusCode", ",...
// NewDatasetAPIResponse creates an error response, optionally adding body to e when status is 404
[ "NewDatasetAPIResponse", "creates", "an", "error", "response", "optionally", "adding", "body", "to", "e", "when", "status", "is", "404" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/dataset/dataset.go#L484-L499
153,231
op/go-libspotify
examples/portaudio/portaudio.go
newAudioWriter
func newAudioWriter() (*audioWriter, error) { w := &audioWriter{ input: make(chan audio, audioInputBufferSize), quit: make(chan bool, 1), } stream, err := newPortAudioStream() if err != nil { return w, err } w.wg.Add(1) go w.streamWriter(stream) return w, nil }
go
func newAudioWriter() (*audioWriter, error) { w := &audioWriter{ input: make(chan audio, audioInputBufferSize), quit: make(chan bool, 1), } stream, err := newPortAudioStream() if err != nil { return w, err } w.wg.Add(1) go w.streamWriter(stream) return w, nil }
[ "func", "newAudioWriter", "(", ")", "(", "*", "audioWriter", ",", "error", ")", "{", "w", ":=", "&", "audioWriter", "{", "input", ":", "make", "(", "chan", "audio", ",", "audioInputBufferSize", ")", ",", "quit", ":", "make", "(", "chan", "bool", ",", ...
// newAudioWriter creates a new audioWriter handler.
[ "newAudioWriter", "creates", "a", "new", "audioWriter", "handler", "." ]
12dd11fb33ecf760c356b65dc1116bc92589dea4
https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/examples/portaudio/portaudio.go#L66-L80
153,232
op/go-libspotify
examples/portaudio/portaudio.go
Close
func (w *audioWriter) Close() error { select { case w.quit <- true: default: } w.wg.Wait() return nil }
go
func (w *audioWriter) Close() error { select { case w.quit <- true: default: } w.wg.Wait() return nil }
[ "func", "(", "w", "*", "audioWriter", ")", "Close", "(", ")", "error", "{", "select", "{", "case", "w", ".", "quit", "<-", "true", ":", "default", ":", "}", "\n", "w", ".", "wg", ".", "Wait", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Close stops and closes the audio stream and terminates PortAudio.
[ "Close", "stops", "and", "closes", "the", "audio", "stream", "and", "terminates", "PortAudio", "." ]
12dd11fb33ecf760c356b65dc1116bc92589dea4
https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/examples/portaudio/portaudio.go#L83-L90
153,233
op/go-libspotify
examples/portaudio/portaudio.go
WriteAudio
func (w *audioWriter) WriteAudio(format spotify.AudioFormat, frames []byte) int { select { case w.input <- audio{format, frames}: return len(frames) default: return 0 } }
go
func (w *audioWriter) WriteAudio(format spotify.AudioFormat, frames []byte) int { select { case w.input <- audio{format, frames}: return len(frames) default: return 0 } }
[ "func", "(", "w", "*", "audioWriter", ")", "WriteAudio", "(", "format", "spotify", ".", "AudioFormat", ",", "frames", "[", "]", "byte", ")", "int", "{", "select", "{", "case", "w", ".", "input", "<-", "audio", "{", "format", ",", "frames", "}", ":", ...
// WriteAudio implements the spotify.AudioWriter interface.
[ "WriteAudio", "implements", "the", "spotify", ".", "AudioWriter", "interface", "." ]
12dd11fb33ecf760c356b65dc1116bc92589dea4
https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/examples/portaudio/portaudio.go#L93-L100
153,234
op/go-libspotify
examples/portaudio/portaudio.go
streamWriter
func (w *audioWriter) streamWriter(stream *portAudioStream) { defer w.wg.Done() defer stream.Close() buffer := make([]int16, audioOutputBufferSize) output := buffer[:] for { // Wait for input data or signal to quit. var input audio select { case input = <-w.input: case <-w.quit: return } // Initialize the audio stream based on the specification of the input format. err := stream.Stream(&output, input.format.Channels, input.format.SampleRate) if err != nil { panic(err) } // Decode the incoming data which is expected to be 2 channels and // delivered as int16 in []byte, hence we need to convert it. i := 0 for i < len(input.frames) { j := 0 for j < len(buffer) && i < len(input.frames) { buffer[j] = int16(input.frames[i]) | int16(input.frames[i+1])<<8 j += 1 i += 2 } output = buffer[:j] stream.Write() } } }
go
func (w *audioWriter) streamWriter(stream *portAudioStream) { defer w.wg.Done() defer stream.Close() buffer := make([]int16, audioOutputBufferSize) output := buffer[:] for { // Wait for input data or signal to quit. var input audio select { case input = <-w.input: case <-w.quit: return } // Initialize the audio stream based on the specification of the input format. err := stream.Stream(&output, input.format.Channels, input.format.SampleRate) if err != nil { panic(err) } // Decode the incoming data which is expected to be 2 channels and // delivered as int16 in []byte, hence we need to convert it. i := 0 for i < len(input.frames) { j := 0 for j < len(buffer) && i < len(input.frames) { buffer[j] = int16(input.frames[i]) | int16(input.frames[i+1])<<8 j += 1 i += 2 } output = buffer[:j] stream.Write() } } }
[ "func", "(", "w", "*", "audioWriter", ")", "streamWriter", "(", "stream", "*", "portAudioStream", ")", "{", "defer", "w", ".", "wg", ".", "Done", "(", ")", "\n", "defer", "stream", ".", "Close", "(", ")", "\n\n", "buffer", ":=", "make", "(", "[", "...
// streamWriter reads data from the input buffer and writes it to the output // portaudio buffer.
[ "streamWriter", "reads", "data", "from", "the", "input", "buffer", "and", "writes", "it", "to", "the", "output", "portaudio", "buffer", "." ]
12dd11fb33ecf760c356b65dc1116bc92589dea4
https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/examples/portaudio/portaudio.go#L104-L141
153,235
op/go-libspotify
examples/portaudio/portaudio.go
newPortAudioStream
func newPortAudioStream() (*portAudioStream, error) { if err := portaudio.Initialize(); err != nil { return nil, err } out, err := portaudio.DefaultHostApi() if err != nil { portaudio.Terminate() return nil, err } return &portAudioStream{device: out.DefaultOutputDevice}, nil }
go
func newPortAudioStream() (*portAudioStream, error) { if err := portaudio.Initialize(); err != nil { return nil, err } out, err := portaudio.DefaultHostApi() if err != nil { portaudio.Terminate() return nil, err } return &portAudioStream{device: out.DefaultOutputDevice}, nil }
[ "func", "newPortAudioStream", "(", ")", "(", "*", "portAudioStream", ",", "error", ")", "{", "if", "err", ":=", "portaudio", ".", "Initialize", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "out", ",", "err", ...
// newPortAudioStream creates a new portAudioStream using the default output // device found on the system. It will also take care of automatically // initialise the PortAudio API.
[ "newPortAudioStream", "creates", "a", "new", "portAudioStream", "using", "the", "default", "output", "device", "found", "on", "the", "system", ".", "It", "will", "also", "take", "care", "of", "automatically", "initialise", "the", "PortAudio", "API", "." ]
12dd11fb33ecf760c356b65dc1116bc92589dea4
https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/examples/portaudio/portaudio.go#L156-L166
153,236
op/go-libspotify
examples/portaudio/portaudio.go
Close
func (s *portAudioStream) Close() error { if err := s.reset(); err != nil { portaudio.Terminate() return err } return portaudio.Terminate() }
go
func (s *portAudioStream) Close() error { if err := s.reset(); err != nil { portaudio.Terminate() return err } return portaudio.Terminate() }
[ "func", "(", "s", "*", "portAudioStream", ")", "Close", "(", ")", "error", "{", "if", "err", ":=", "s", ".", "reset", "(", ")", ";", "err", "!=", "nil", "{", "portaudio", ".", "Terminate", "(", ")", "\n", "return", "err", "\n", "}", "\n", "return...
// Close closes any open audio stream and terminates the PortAudio API.
[ "Close", "closes", "any", "open", "audio", "stream", "and", "terminates", "the", "PortAudio", "API", "." ]
12dd11fb33ecf760c356b65dc1116bc92589dea4
https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/examples/portaudio/portaudio.go#L169-L175
153,237
op/go-libspotify
examples/portaudio/portaudio.go
Stream
func (s *portAudioStream) Stream(buffer *[]int16, channels int, sampleRate int) error { if s.stream == nil || s.channels != channels || s.sampleRate != sampleRate { if err := s.reset(); err != nil { return err } params := portaudio.HighLatencyParameters(nil, s.device) params.Output.Channels = channels params.SampleRate = float64(sampleRate) params.FramesPerBuffer = len(*buffer) stream, err := portaudio.OpenStream(params, buffer) if err != nil { return err } if err := stream.Start(); err != nil { stream.Close() return err } s.stream = stream s.channels = channels s.sampleRate = sampleRate } return nil }
go
func (s *portAudioStream) Stream(buffer *[]int16, channels int, sampleRate int) error { if s.stream == nil || s.channels != channels || s.sampleRate != sampleRate { if err := s.reset(); err != nil { return err } params := portaudio.HighLatencyParameters(nil, s.device) params.Output.Channels = channels params.SampleRate = float64(sampleRate) params.FramesPerBuffer = len(*buffer) stream, err := portaudio.OpenStream(params, buffer) if err != nil { return err } if err := stream.Start(); err != nil { stream.Close() return err } s.stream = stream s.channels = channels s.sampleRate = sampleRate } return nil }
[ "func", "(", "s", "*", "portAudioStream", ")", "Stream", "(", "buffer", "*", "[", "]", "int16", ",", "channels", "int", ",", "sampleRate", "int", ")", "error", "{", "if", "s", ".", "stream", "==", "nil", "||", "s", ".", "channels", "!=", "channels", ...
// Stream prepares the stream to go through the specified buffer, channels and // sample rate, re-using any previously defined stream or setting up a new one.
[ "Stream", "prepares", "the", "stream", "to", "go", "through", "the", "specified", "buffer", "channels", "and", "sample", "rate", "re", "-", "using", "any", "previously", "defined", "stream", "or", "setting", "up", "a", "new", "one", "." ]
12dd11fb33ecf760c356b65dc1116bc92589dea4
https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/examples/portaudio/portaudio.go#L191-L216
153,238
ONSdigital/go-ns
healthcheck/healthcheck.go
MonitorExternal
func MonitorExternal(clients ...Client) { hs := make(HealthState) type externalError struct { name string err error } errs := make(chan externalError) done := make(chan bool) go func() { for extErr := range errs { hs[extErr.name] = extErr.err } close(done) }() var wg sync.WaitGroup wg.Add(len(clients)) for _, client := range clients { go func(client Client) { if name, err := client.Healthcheck(); err != nil { log.ErrorC("unsuccessful healthcheck", err, log.Data{"external_service": name}) errs <- externalError{name, err} } wg.Done() }(client) } wg.Wait() close(errs) <-done mutex.Lock() healthState = hs healthLastChecked = time.Now() if len(hs) == 0 { healthLastSuccess = healthLastChecked } mutex.Unlock() }
go
func MonitorExternal(clients ...Client) { hs := make(HealthState) type externalError struct { name string err error } errs := make(chan externalError) done := make(chan bool) go func() { for extErr := range errs { hs[extErr.name] = extErr.err } close(done) }() var wg sync.WaitGroup wg.Add(len(clients)) for _, client := range clients { go func(client Client) { if name, err := client.Healthcheck(); err != nil { log.ErrorC("unsuccessful healthcheck", err, log.Data{"external_service": name}) errs <- externalError{name, err} } wg.Done() }(client) } wg.Wait() close(errs) <-done mutex.Lock() healthState = hs healthLastChecked = time.Now() if len(hs) == 0 { healthLastSuccess = healthLastChecked } mutex.Unlock() }
[ "func", "MonitorExternal", "(", "clients", "...", "Client", ")", "{", "hs", ":=", "make", "(", "HealthState", ")", "\n\n", "type", "externalError", "struct", "{", "name", "string", "\n", "err", "error", "\n", "}", "\n", "errs", ":=", "make", "(", "chan",...
// MonitorExternal concurrently monitors external service health and if they are unhealthy, // records the status in a map
[ "MonitorExternal", "concurrently", "monitors", "external", "service", "health", "and", "if", "they", "are", "unhealthy", "records", "the", "status", "in", "a", "map" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/healthcheck/healthcheck.go#L39-L79
153,239
ONSdigital/go-ns
healthcheck/healthcheck.go
Do
func Do(w http.ResponseWriter, req *http.Request) { state, lastTry, lastSuccess := GetState() w.Header().Set("Content-Type", "application/json") var healthStateInfo healthResponse if len(state) > 0 { w.WriteHeader(http.StatusInternalServerError) healthStateInfo = healthResponse{Status: "error", Errors: &[]healthError{}} // add errors to healthStateInfo and set its Status to "error" for stateKey := range state { *(healthStateInfo.Errors) = append(*(healthStateInfo.Errors), healthError{Namespace: stateKey, ErrorMessage: state[stateKey].Error()}) } } else if lastTry.IsZero() { w.WriteHeader(http.StatusTooManyRequests) return } else { w.WriteHeader(http.StatusOK) healthStateInfo.Status = "OK" } healthStateInfo.LastChecked = lastTry healthStateInfo.LastSuccess = lastSuccess healthStateJSON, err := json.Marshal(healthStateInfo) if err != nil { log.ErrorC("marshal json", err, log.Data{"struct": healthStateInfo}) return } if _, err = w.Write(healthStateJSON); err != nil { log.ErrorC("writing json body", err, log.Data{"json": string(healthStateJSON)}) } }
go
func Do(w http.ResponseWriter, req *http.Request) { state, lastTry, lastSuccess := GetState() w.Header().Set("Content-Type", "application/json") var healthStateInfo healthResponse if len(state) > 0 { w.WriteHeader(http.StatusInternalServerError) healthStateInfo = healthResponse{Status: "error", Errors: &[]healthError{}} // add errors to healthStateInfo and set its Status to "error" for stateKey := range state { *(healthStateInfo.Errors) = append(*(healthStateInfo.Errors), healthError{Namespace: stateKey, ErrorMessage: state[stateKey].Error()}) } } else if lastTry.IsZero() { w.WriteHeader(http.StatusTooManyRequests) return } else { w.WriteHeader(http.StatusOK) healthStateInfo.Status = "OK" } healthStateInfo.LastChecked = lastTry healthStateInfo.LastSuccess = lastSuccess healthStateJSON, err := json.Marshal(healthStateInfo) if err != nil { log.ErrorC("marshal json", err, log.Data{"struct": healthStateInfo}) return } if _, err = w.Write(healthStateJSON); err != nil { log.ErrorC("writing json body", err, log.Data{"json": string(healthStateJSON)}) } }
[ "func", "Do", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "state", ",", "lastTry", ",", "lastSuccess", ":=", "GetState", "(", ")", "\n\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ...
// Do is responsible for returning the healthcheck status to the user
[ "Do", "is", "responsible", "for", "returning", "the", "healthcheck", "status", "to", "the", "user" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/healthcheck/healthcheck.go#L82-L113
153,240
ONSdigital/go-ns
healthcheck/healthcheck.go
GetState
func GetState() (HealthState, time.Time, time.Time) { mutex.RLock() defer mutex.RUnlock() hs := make(HealthState) for key := range healthState { hs[key] = healthState[key] } return hs, healthLastChecked, healthLastSuccess }
go
func GetState() (HealthState, time.Time, time.Time) { mutex.RLock() defer mutex.RUnlock() hs := make(HealthState) for key := range healthState { hs[key] = healthState[key] } return hs, healthLastChecked, healthLastSuccess }
[ "func", "GetState", "(", ")", "(", "HealthState", ",", "time", ".", "Time", ",", "time", ".", "Time", ")", "{", "mutex", ".", "RLock", "(", ")", "\n", "defer", "mutex", ".", "RUnlock", "(", ")", "\n\n", "hs", ":=", "make", "(", "HealthState", ")", ...
// GetState returns current map of errors and times of last check, last success
[ "GetState", "returns", "current", "map", "of", "errors", "and", "times", "of", "last", "check", "last", "success" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/healthcheck/healthcheck.go#L116-L126
153,241
peter-edge/pkg-go
app/pkgapp.go
GetAppEnv
func GetAppEnv() (AppEnv, error) { appEnv := AppEnv{} if err := env.Populate(&appEnv); err != nil { return AppEnv{}, err } return appEnv, nil }
go
func GetAppEnv() (AppEnv, error) { appEnv := AppEnv{} if err := env.Populate(&appEnv); err != nil { return AppEnv{}, err } return appEnv, nil }
[ "func", "GetAppEnv", "(", ")", "(", "AppEnv", ",", "error", ")", "{", "appEnv", ":=", "AppEnv", "{", "}", "\n", "if", "err", ":=", "env", ".", "Populate", "(", "&", "appEnv", ")", ";", "err", "!=", "nil", "{", "return", "AppEnv", "{", "}", ",", ...
// GetAppEnv gets the AppEnv from the environment.
[ "GetAppEnv", "gets", "the", "AppEnv", "from", "the", "environment", "." ]
318cf31141c87eaa4348bd8a54886ba3aaf2a427
https://github.com/peter-edge/pkg-go/blob/318cf31141c87eaa4348bd8a54886ba3aaf2a427/app/pkgapp.go#L19-L25
153,242
peter-edge/pkg-go
app/pkgapp.go
SetupAppEnv
func SetupAppEnv(appEnv AppEnv) (AppOptions, error) { if err := envlion.SetupEnv(appEnv.LionEnv); err != nil { return AppOptions{}, err } registry, err := pkgmetrics.SetupMetrics(appEnv.LionEnv.LogAppName, appEnv.MetricsEnv) if err != nil { return AppOptions{}, err } return AppOptions{ MetricsRegistry: registry, }, nil }
go
func SetupAppEnv(appEnv AppEnv) (AppOptions, error) { if err := envlion.SetupEnv(appEnv.LionEnv); err != nil { return AppOptions{}, err } registry, err := pkgmetrics.SetupMetrics(appEnv.LionEnv.LogAppName, appEnv.MetricsEnv) if err != nil { return AppOptions{}, err } return AppOptions{ MetricsRegistry: registry, }, nil }
[ "func", "SetupAppEnv", "(", "appEnv", "AppEnv", ")", "(", "AppOptions", ",", "error", ")", "{", "if", "err", ":=", "envlion", ".", "SetupEnv", "(", "appEnv", ".", "LionEnv", ")", ";", "err", "!=", "nil", "{", "return", "AppOptions", "{", "}", ",", "e...
// SetupAppEnv does the setup for AppEnv.
[ "SetupAppEnv", "does", "the", "setup", "for", "AppEnv", "." ]
318cf31141c87eaa4348bd8a54886ba3aaf2a427
https://github.com/peter-edge/pkg-go/blob/318cf31141c87eaa4348bd8a54886ba3aaf2a427/app/pkgapp.go#L35-L46
153,243
peter-edge/pkg-go
app/pkgapp.go
GetAndSetupAppEnv
func GetAndSetupAppEnv() (AppOptions, error) { appEnv, err := GetAppEnv() if err != nil { return AppOptions{}, err } return SetupAppEnv(appEnv) }
go
func GetAndSetupAppEnv() (AppOptions, error) { appEnv, err := GetAppEnv() if err != nil { return AppOptions{}, err } return SetupAppEnv(appEnv) }
[ "func", "GetAndSetupAppEnv", "(", ")", "(", "AppOptions", ",", "error", ")", "{", "appEnv", ",", "err", ":=", "GetAppEnv", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "AppOptions", "{", "}", ",", "err", "\n", "}", "\n", "return", "SetupA...
// GetAndSetupAppEnv does GetAppEnv then SetupAppEnv.
[ "GetAndSetupAppEnv", "does", "GetAppEnv", "then", "SetupAppEnv", "." ]
318cf31141c87eaa4348bd8a54886ba3aaf2a427
https://github.com/peter-edge/pkg-go/blob/318cf31141c87eaa4348bd8a54886ba3aaf2a427/app/pkgapp.go#L49-L55
153,244
ONSdigital/go-ns
clients/search/search_mocks/mocks.go
NewMockHTTPClient
func NewMockHTTPClient(ctrl *gomock.Controller) *MockHTTPClient { mock := &MockHTTPClient{ctrl: ctrl} mock.recorder = &MockHTTPClientMockRecorder{mock} return mock }
go
func NewMockHTTPClient(ctrl *gomock.Controller) *MockHTTPClient { mock := &MockHTTPClient{ctrl: ctrl} mock.recorder = &MockHTTPClientMockRecorder{mock} return mock }
[ "func", "NewMockHTTPClient", "(", "ctrl", "*", "gomock", ".", "Controller", ")", "*", "MockHTTPClient", "{", "mock", ":=", "&", "MockHTTPClient", "{", "ctrl", ":", "ctrl", "}", "\n", "mock", ".", "recorder", "=", "&", "MockHTTPClientMockRecorder", "{", "mock...
// NewMockHTTPClient creates a new mock instance
[ "NewMockHTTPClient", "creates", "a", "new", "mock", "instance" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/search/search_mocks/mocks.go#L28-L32
153,245
ONSdigital/go-ns
clients/search/search_mocks/mocks.go
Post
func (m *MockHTTPClient) Post(arg0, arg1 string, arg2 io.Reader) (*http.Response, error) { ret := m.ctrl.Call(m, "Post", arg0, arg1, arg2) ret0, _ := ret[0].(*http.Response) ret1, _ := ret[1].(error) return ret0, ret1 }
go
func (m *MockHTTPClient) Post(arg0, arg1 string, arg2 io.Reader) (*http.Response, error) { ret := m.ctrl.Call(m, "Post", arg0, arg1, arg2) ret0, _ := ret[0].(*http.Response) ret1, _ := ret[1].(error) return ret0, ret1 }
[ "func", "(", "m", "*", "MockHTTPClient", ")", "Post", "(", "arg0", ",", "arg1", "string", ",", "arg2", "io", ".", "Reader", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "ret", ":=", "m", ".", "ctrl", ".", "Call", "(", "m", ",...
// Post mocks base method
[ "Post", "mocks", "base", "method" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/search/search_mocks/mocks.go#L79-L84
153,246
ONSdigital/go-ns
vault/client.go
CreateVaultClient
func CreateVaultClient(token, vaultAddress string, retries int) (*VaultClient, error) { config := vaultapi.Config{Address: vaultAddress, MaxRetries: retries} client, err := vaultapi.NewClient(&config) if err != nil { return nil, err } client.SetToken(token) return &VaultClient{client}, nil }
go
func CreateVaultClient(token, vaultAddress string, retries int) (*VaultClient, error) { config := vaultapi.Config{Address: vaultAddress, MaxRetries: retries} client, err := vaultapi.NewClient(&config) if err != nil { return nil, err } client.SetToken(token) return &VaultClient{client}, nil }
[ "func", "CreateVaultClient", "(", "token", ",", "vaultAddress", "string", ",", "retries", "int", ")", "(", "*", "VaultClient", ",", "error", ")", "{", "config", ":=", "vaultapi", ".", "Config", "{", "Address", ":", "vaultAddress", ",", "MaxRetries", ":", "...
// CreateVaultClient by providing an auth token, vault address and the maximum number of retries for a request
[ "CreateVaultClient", "by", "providing", "an", "auth", "token", "vault", "address", "and", "the", "maximum", "number", "of", "retries", "for", "a", "request" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/vault/client.go#L24-L32
153,247
ONSdigital/go-ns
vault/client.go
CreateVaultClientTLS
func CreateVaultClientTLS(token, vaultAddress string, retries int, cacert, cert, key string) (*VaultClient, error) { config := vaultapi.Config{Address: vaultAddress, MaxRetries: retries} config.ConfigureTLS(&vaultapi.TLSConfig{CACert: cacert, ClientCert: cert, ClientKey: key}) client, err := vaultapi.NewClient(&config) if err != nil { return nil, err } client.SetToken(token) return &VaultClient{client}, nil }
go
func CreateVaultClientTLS(token, vaultAddress string, retries int, cacert, cert, key string) (*VaultClient, error) { config := vaultapi.Config{Address: vaultAddress, MaxRetries: retries} config.ConfigureTLS(&vaultapi.TLSConfig{CACert: cacert, ClientCert: cert, ClientKey: key}) client, err := vaultapi.NewClient(&config) if err != nil { return nil, err } client.SetToken(token) return &VaultClient{client}, nil }
[ "func", "CreateVaultClientTLS", "(", "token", ",", "vaultAddress", "string", ",", "retries", "int", ",", "cacert", ",", "cert", ",", "key", "string", ")", "(", "*", "VaultClient", ",", "error", ")", "{", "config", ":=", "vaultapi", ".", "Config", "{", "A...
// CreateVaultClientTLS is like the CreateVaultClient function but wraps the HTTP client with TLS
[ "CreateVaultClientTLS", "is", "like", "the", "CreateVaultClient", "function", "but", "wraps", "the", "HTTP", "client", "with", "TLS" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/vault/client.go#L35-L45
153,248
ONSdigital/go-ns
vault/client.go
Healthcheck
func (c *VaultClient) Healthcheck() (string, error) { resp, err := c.client.Sys().Health() if err != nil { return "vault", err } if !resp.Initialized { return "vault", errors.New("vault not initialised") } return "", nil }
go
func (c *VaultClient) Healthcheck() (string, error) { resp, err := c.client.Sys().Health() if err != nil { return "vault", err } if !resp.Initialized { return "vault", errors.New("vault not initialised") } return "", nil }
[ "func", "(", "c", "*", "VaultClient", ")", "Healthcheck", "(", ")", "(", "string", ",", "error", ")", "{", "resp", ",", "err", ":=", "c", ".", "client", ".", "Sys", "(", ")", ".", "Health", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return...
// Healthcheck determines the state of vault
[ "Healthcheck", "determines", "the", "state", "of", "vault" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/vault/client.go#L48-L59
153,249
ONSdigital/go-ns
vault/client.go
Read
func (c *VaultClient) Read(path string) (map[string]interface{}, error) { secret, err := c.client.Logical().Read(path) if err != nil { return nil, err } if secret == nil { // If there is no secret and no error return a empty map. return make(map[string]interface{}), nil } return secret.Data, err }
go
func (c *VaultClient) Read(path string) (map[string]interface{}, error) { secret, err := c.client.Logical().Read(path) if err != nil { return nil, err } if secret == nil { // If there is no secret and no error return a empty map. return make(map[string]interface{}), nil } return secret.Data, err }
[ "func", "(", "c", "*", "VaultClient", ")", "Read", "(", "path", "string", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "secret", ",", "err", ":=", "c", ".", "client", ".", "Logical", "(", ")", ".", "Read", ...
// Read reads a secret from vault. If the token does not have the correct policy this returns an error; // if the vault server is not reachable, return all the information stored about the secret.
[ "Read", "reads", "a", "secret", "from", "vault", ".", "If", "the", "token", "does", "not", "have", "the", "correct", "policy", "this", "returns", "an", "error", ";", "if", "the", "vault", "server", "is", "not", "reachable", "return", "all", "the", "infor...
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/vault/client.go#L63-L73
153,250
ONSdigital/go-ns
vault/client.go
ReadKey
func (c *VaultClient) ReadKey(path, key string) (string, error) { data, err := c.Read(path) if err != nil { return "", err } val, ok := data[key] if !ok { return "", errors.New("key not found") } return val.(string), nil }
go
func (c *VaultClient) ReadKey(path, key string) (string, error) { data, err := c.Read(path) if err != nil { return "", err } val, ok := data[key] if !ok { return "", errors.New("key not found") } return val.(string), nil }
[ "func", "(", "c", "*", "VaultClient", ")", "ReadKey", "(", "path", ",", "key", "string", ")", "(", "string", ",", "error", ")", "{", "data", ",", "err", ":=", "c", ".", "Read", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\...
// ReadKey from vault. Like read but only return a single value from the secret
[ "ReadKey", "from", "vault", ".", "Like", "read", "but", "only", "return", "a", "single", "value", "from", "the", "secret" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/vault/client.go#L76-L86
153,251
ONSdigital/go-ns
vault/client.go
Write
func (c *VaultClient) Write(path string, data map[string]interface{}) error { _, err := c.client.Logical().Write(path, data) return err }
go
func (c *VaultClient) Write(path string, data map[string]interface{}) error { _, err := c.client.Logical().Write(path, data) return err }
[ "func", "(", "c", "*", "VaultClient", ")", "Write", "(", "path", "string", ",", "data", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "_", ",", "err", ":=", "c", ".", "client", ".", "Logical", "(", ")", ".", "Write", "(", ...
// Write writes a secret to vault. Returns an error if the token does not have the correct policy or the // vault server is not reachable. Returns nil when the operation was successful.
[ "Write", "writes", "a", "secret", "to", "vault", ".", "Returns", "an", "error", "if", "the", "token", "does", "not", "have", "the", "correct", "policy", "or", "the", "vault", "server", "is", "not", "reachable", ".", "Returns", "nil", "when", "the", "oper...
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/vault/client.go#L90-L93
153,252
ONSdigital/go-ns
vault/client.go
VReadKey
func (c *VaultClient) VReadKey(path, key string) (string, int64, error) { data, ver, err := c.VRead(path) if err != nil { return "", -1, err } val, ok := data[key] if !ok { return "", -1, ErrKeyNotFound } return val.(string), ver, nil }
go
func (c *VaultClient) VReadKey(path, key string) (string, int64, error) { data, ver, err := c.VRead(path) if err != nil { return "", -1, err } val, ok := data[key] if !ok { return "", -1, ErrKeyNotFound } return val.(string), ver, nil }
[ "func", "(", "c", "*", "VaultClient", ")", "VReadKey", "(", "path", ",", "key", "string", ")", "(", "string", ",", "int64", ",", "error", ")", "{", "data", ",", "ver", ",", "err", ":=", "c", ".", "VRead", "(", "path", ")", "\n", "if", "err", "!...
// VReadKey - cf Read but for versioned secret - return the value of the key and the version
[ "VReadKey", "-", "cf", "Read", "but", "for", "versioned", "secret", "-", "return", "the", "value", "of", "the", "key", "and", "the", "version" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/vault/client.go#L132-L142
153,253
peter-edge/pkg-go
exec/pkgexec.go
SetDebug
func SetDebug(debug bool) { // sort of unnecessary but hey, standards lock.Lock() defer lock.Unlock() globalDebug = debug if debug { lion.SetLogger(lion.GlobalLogger().AtLevel(lion.LevelDebug)) } }
go
func SetDebug(debug bool) { // sort of unnecessary but hey, standards lock.Lock() defer lock.Unlock() globalDebug = debug if debug { lion.SetLogger(lion.GlobalLogger().AtLevel(lion.LevelDebug)) } }
[ "func", "SetDebug", "(", "debug", "bool", ")", "{", "// sort of unnecessary but hey, standards", "lock", ".", "Lock", "(", ")", "\n", "defer", "lock", ".", "Unlock", "(", ")", "\n", "globalDebug", "=", "debug", "\n", "if", "debug", "{", "lion", ".", "SetLo...
// SetDebug sets debug mode for This will log commands at the debug level, and // include the output of a command in the resulting error if the command fails.
[ "SetDebug", "sets", "debug", "mode", "for", "This", "will", "log", "commands", "at", "the", "debug", "level", "and", "include", "the", "output", "of", "a", "command", "in", "the", "resulting", "error", "if", "the", "command", "fails", "." ]
318cf31141c87eaa4348bd8a54886ba3aaf2a427
https://github.com/peter-edge/pkg-go/blob/318cf31141c87eaa4348bd8a54886ba3aaf2a427/exec/pkgexec.go#L28-L36
153,254
peter-edge/pkg-go
exec/pkgexec.go
RunDirPath
func RunDirPath(dirPath string, args ...string) error { return RunIODirPath(IO{}, dirPath, args...) }
go
func RunDirPath(dirPath string, args ...string) error { return RunIODirPath(IO{}, dirPath, args...) }
[ "func", "RunDirPath", "(", "dirPath", "string", ",", "args", "...", "string", ")", "error", "{", "return", "RunIODirPath", "(", "IO", "{", "}", ",", "dirPath", ",", "args", "...", ")", "\n", "}" ]
// RunDirPath runs the command with the given arguments in the given directory specified by dirPath.
[ "RunDirPath", "runs", "the", "command", "with", "the", "given", "arguments", "in", "the", "given", "directory", "specified", "by", "dirPath", "." ]
318cf31141c87eaa4348bd8a54886ba3aaf2a427
https://github.com/peter-edge/pkg-go/blob/318cf31141c87eaa4348bd8a54886ba3aaf2a427/exec/pkgexec.go#L51-L53
153,255
peter-edge/pkg-go
exec/pkgexec.go
RunStdout
func RunStdout(stdout io.Writer, args ...string) error { return RunIO(IO{Stdout: stdout}, args...) }
go
func RunStdout(stdout io.Writer, args ...string) error { return RunIO(IO{Stdout: stdout}, args...) }
[ "func", "RunStdout", "(", "stdout", "io", ".", "Writer", ",", "args", "...", "string", ")", "error", "{", "return", "RunIO", "(", "IO", "{", "Stdout", ":", "stdout", "}", ",", "args", "...", ")", "\n", "}" ]
// RunStdout runs the command with the given stdout and arguments.
[ "RunStdout", "runs", "the", "command", "with", "the", "given", "stdout", "and", "arguments", "." ]
318cf31141c87eaa4348bd8a54886ba3aaf2a427
https://github.com/peter-edge/pkg-go/blob/318cf31141c87eaa4348bd8a54886ba3aaf2a427/exec/pkgexec.go#L61-L63
153,256
peter-edge/pkg-go
exec/pkgexec.go
RunStderr
func RunStderr(stderr io.Writer, args ...string) error { return RunIO(IO{Stderr: stderr}, args...) }
go
func RunStderr(stderr io.Writer, args ...string) error { return RunIO(IO{Stderr: stderr}, args...) }
[ "func", "RunStderr", "(", "stderr", "io", ".", "Writer", ",", "args", "...", "string", ")", "error", "{", "return", "RunIO", "(", "IO", "{", "Stderr", ":", "stderr", "}", ",", "args", "...", ")", "\n", "}" ]
// RunStderr runs the command with the given stderr and arguments.
[ "RunStderr", "runs", "the", "command", "with", "the", "given", "stderr", "and", "arguments", "." ]
318cf31141c87eaa4348bd8a54886ba3aaf2a427
https://github.com/peter-edge/pkg-go/blob/318cf31141c87eaa4348bd8a54886ba3aaf2a427/exec/pkgexec.go#L66-L68
153,257
peter-edge/pkg-go
exec/pkgexec.go
RunOutput
func RunOutput(args ...string) ([]byte, error) { stdout := bytes.NewBuffer(nil) err := RunStdout(stdout, args...) return stdout.Bytes(), err }
go
func RunOutput(args ...string) ([]byte, error) { stdout := bytes.NewBuffer(nil) err := RunStdout(stdout, args...) return stdout.Bytes(), err }
[ "func", "RunOutput", "(", "args", "...", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "stdout", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "err", ":=", "RunStdout", "(", "stdout", ",", "args", "...", ")", "\n", "return...
// RunOutput runs the command with the given arguments and returns the output of stdout.
[ "RunOutput", "runs", "the", "command", "with", "the", "given", "arguments", "and", "returns", "the", "output", "of", "stdout", "." ]
318cf31141c87eaa4348bd8a54886ba3aaf2a427
https://github.com/peter-edge/pkg-go/blob/318cf31141c87eaa4348bd8a54886ba3aaf2a427/exec/pkgexec.go#L71-L75
153,258
peter-edge/pkg-go
exec/pkgexec.go
RunOutputDirPath
func RunOutputDirPath(dirPath string, args ...string) ([]byte, error) { stdout := bytes.NewBuffer(nil) err := RunIODirPath(IO{Stdout: stdout}, dirPath, args...) return stdout.Bytes(), err }
go
func RunOutputDirPath(dirPath string, args ...string) ([]byte, error) { stdout := bytes.NewBuffer(nil) err := RunIODirPath(IO{Stdout: stdout}, dirPath, args...) return stdout.Bytes(), err }
[ "func", "RunOutputDirPath", "(", "dirPath", "string", ",", "args", "...", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "stdout", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "err", ":=", "RunIODirPath", "(", "IO", "{", "St...
// RunOutputDirPath runs the command with the given arguments in the given directory and returns the output of stdout.
[ "RunOutputDirPath", "runs", "the", "command", "with", "the", "given", "arguments", "in", "the", "given", "directory", "and", "returns", "the", "output", "of", "stdout", "." ]
318cf31141c87eaa4348bd8a54886ba3aaf2a427
https://github.com/peter-edge/pkg-go/blob/318cf31141c87eaa4348bd8a54886ba3aaf2a427/exec/pkgexec.go#L78-L82
153,259
ONSdigital/go-ns
mongo/healthcheck.go
Healthcheck
func (m *HealthCheckClient) Healthcheck() (res string, err error) { s := m.mongo.Copy() defer s.Close() res = m.serviceName err = s.Ping() if err != nil { log.ErrorC("Ping mongo", err, nil) } return }
go
func (m *HealthCheckClient) Healthcheck() (res string, err error) { s := m.mongo.Copy() defer s.Close() res = m.serviceName err = s.Ping() if err != nil { log.ErrorC("Ping mongo", err, nil) } return }
[ "func", "(", "m", "*", "HealthCheckClient", ")", "Healthcheck", "(", ")", "(", "res", "string", ",", "err", "error", ")", "{", "s", ":=", "m", ".", "mongo", ".", "Copy", "(", ")", "\n", "defer", "s", ".", "Close", "(", ")", "\n", "res", "=", "m...
// Healthcheck calls service to check its health status
[ "Healthcheck", "calls", "service", "to", "check", "its", "health", "status" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/mongo/healthcheck.go#L23-L33
153,260
ONSdigital/go-ns
healthcheck/client.go
Healthcheck
func (c *healthcheckClient) Healthcheck() (string, error) { resp, err := c.client.Get(context.Background(), c.url) if err != nil { return c.service, err } if resp.StatusCode != http.StatusOK { return c.service, &errorResponse{c.service, http.StatusOK, resp.StatusCode, c.url} } return c.service, nil }
go
func (c *healthcheckClient) Healthcheck() (string, error) { resp, err := c.client.Get(context.Background(), c.url) if err != nil { return c.service, err } if resp.StatusCode != http.StatusOK { return c.service, &errorResponse{c.service, http.StatusOK, resp.StatusCode, c.url} } return c.service, nil }
[ "func", "(", "c", "*", "healthcheckClient", ")", "Healthcheck", "(", ")", "(", "string", ",", "error", ")", "{", "resp", ",", "err", ":=", "c", ".", "client", ".", "Get", "(", "context", ".", "Background", "(", ")", ",", "c", ".", "url", ")", "\n...
// Healthcheck calls the endpoint url and alerts the caller of any errors
[ "Healthcheck", "calls", "the", "endpoint", "url", "and", "alerts", "the", "caller", "of", "any", "errors" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/healthcheck/client.go#L51-L62
153,261
keegancsmith/shell
command.go
Commandf
func Commandf(format string, a ...interface{}) *exec.Cmd { shellCmd := Sprintf(format, a...) return exec.Command("/bin/sh", "-c", shellCmd) }
go
func Commandf(format string, a ...interface{}) *exec.Cmd { shellCmd := Sprintf(format, a...) return exec.Command("/bin/sh", "-c", shellCmd) }
[ "func", "Commandf", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "*", "exec", ".", "Cmd", "{", "shellCmd", ":=", "Sprintf", "(", "format", ",", "a", "...", ")", "\n", "return", "exec", ".", "Command", "(", "\"", "\"", ",", ...
// Commandf runs a shell command based on the format string
[ "Commandf", "runs", "a", "shell", "command", "based", "on", "the", "format", "string" ]
ccb53e0c7c5c3deb421db041b1c4a7737d33ff44
https://github.com/keegancsmith/shell/blob/ccb53e0c7c5c3deb421db041b1c4a7737d33ff44/command.go#L13-L16
153,262
keegancsmith/shell
command.go
Sprintf
func Sprintf(format string, a ...interface{}) string { wrapped := make([]interface{}, len(a)) for i, v := range a { wrapped[i] = escapable{v} } return fmt.Sprintf(format, wrapped...) }
go
func Sprintf(format string, a ...interface{}) string { wrapped := make([]interface{}, len(a)) for i, v := range a { wrapped[i] = escapable{v} } return fmt.Sprintf(format, wrapped...) }
[ "func", "Sprintf", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "string", "{", "wrapped", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "a", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "a...
// Sprintf generates a shell command with the format arguments escaped.
[ "Sprintf", "generates", "a", "shell", "command", "with", "the", "format", "arguments", "escaped", "." ]
ccb53e0c7c5c3deb421db041b1c4a7737d33ff44
https://github.com/keegancsmith/shell/blob/ccb53e0c7c5c3deb421db041b1c4a7737d33ff44/command.go#L19-L25
153,263
op/go-libspotify
examples/gospshell/gospshell.go
cmdHelp
func cmdHelp(session *sp.Session, args []string, abort <-chan bool) error { println("use <command> -h for more information") for command := range commands { println(" - ", command) } return nil }
go
func cmdHelp(session *sp.Session, args []string, abort <-chan bool) error { println("use <command> -h for more information") for command := range commands { println(" - ", command) } return nil }
[ "func", "cmdHelp", "(", "session", "*", "sp", ".", "Session", ",", "args", "[", "]", "string", ",", "abort", "<-", "chan", "bool", ")", "error", "{", "println", "(", "\"", "\"", ")", "\n", "for", "command", ":=", "range", "commands", "{", "println", ...
// cmdHelp displays available commands.
[ "cmdHelp", "displays", "available", "commands", "." ]
12dd11fb33ecf760c356b65dc1116bc92589dea4
https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/examples/gospshell/gospshell.go#L230-L236
153,264
op/go-libspotify
examples/gospshell/gospshell.go
cmdSearch
func cmdSearch(session *sp.Session, args []string, abort <-chan bool) error { var f = flag.NewFlagSet(args[0], flag.ContinueOnError) opts := struct { track, album, artist, playlist *bool offset, limit *int }{ track: f.Bool("track", false, "include tracks"), album: f.Bool("album", false, "include albums"), artist: f.Bool("artist", false, "include artists"), playlist: f.Bool("playlist", false, "include playlists"), offset: f.Int("offset", 0, "result offset"), limit: f.Int("limit", 10, "result count limitation"), } if err := f.Parse(args[1:]); err != nil { return err } else if f.NArg() == 0 { return errors.New("expected query string") } // Set all values to true if none are request. if !*opts.track && !*opts.album && !*opts.artist && !*opts.playlist { *opts.track = true *opts.album = true *opts.artist = true *opts.playlist = true } query := strings.Join(f.Args(), " ") var sOpts sp.SearchOptions spec := sp.SearchSpec{*opts.offset, *opts.limit} if *opts.track { sOpts.Tracks = spec } if *opts.album { sOpts.Albums = spec } if *opts.artist { sOpts.Artists = spec } if *opts.playlist { sOpts.Playlists = spec } // TODO cancel wait when abort<-true search, err := session.Search(query, &sOpts) if err != nil { return err } search.Wait() println("###done searching", search.Tracks(), search.TotalTracks(), search.Query(), search.Link().String()) for i := 0; i < search.Tracks(); i++ { println(trackStr(search.Track(i))) } for i := 0; i < search.Albums(); i++ { println(albumStr(search.Album(i))) } for i := 0; i < search.Artists(); i++ { println(artistStr(search.Artist(i))) } // TODO playlist return nil }
go
func cmdSearch(session *sp.Session, args []string, abort <-chan bool) error { var f = flag.NewFlagSet(args[0], flag.ContinueOnError) opts := struct { track, album, artist, playlist *bool offset, limit *int }{ track: f.Bool("track", false, "include tracks"), album: f.Bool("album", false, "include albums"), artist: f.Bool("artist", false, "include artists"), playlist: f.Bool("playlist", false, "include playlists"), offset: f.Int("offset", 0, "result offset"), limit: f.Int("limit", 10, "result count limitation"), } if err := f.Parse(args[1:]); err != nil { return err } else if f.NArg() == 0 { return errors.New("expected query string") } // Set all values to true if none are request. if !*opts.track && !*opts.album && !*opts.artist && !*opts.playlist { *opts.track = true *opts.album = true *opts.artist = true *opts.playlist = true } query := strings.Join(f.Args(), " ") var sOpts sp.SearchOptions spec := sp.SearchSpec{*opts.offset, *opts.limit} if *opts.track { sOpts.Tracks = spec } if *opts.album { sOpts.Albums = spec } if *opts.artist { sOpts.Artists = spec } if *opts.playlist { sOpts.Playlists = spec } // TODO cancel wait when abort<-true search, err := session.Search(query, &sOpts) if err != nil { return err } search.Wait() println("###done searching", search.Tracks(), search.TotalTracks(), search.Query(), search.Link().String()) for i := 0; i < search.Tracks(); i++ { println(trackStr(search.Track(i))) } for i := 0; i < search.Albums(); i++ { println(albumStr(search.Album(i))) } for i := 0; i < search.Artists(); i++ { println(artistStr(search.Artist(i))) } // TODO playlist return nil }
[ "func", "cmdSearch", "(", "session", "*", "sp", ".", "Session", ",", "args", "[", "]", "string", ",", "abort", "<-", "chan", "bool", ")", "error", "{", "var", "f", "=", "flag", ".", "NewFlagSet", "(", "args", "[", "0", "]", ",", "flag", ".", "Con...
// cmdSearch searches for music.
[ "cmdSearch", "searches", "for", "music", "." ]
12dd11fb33ecf760c356b65dc1116bc92589dea4
https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/examples/gospshell/gospshell.go#L239-L307
153,265
op/go-libspotify
examples/gospshell/gospshell.go
cmdPlaylist
func cmdPlaylist(session *sp.Session, args []string, abort <-chan bool) error { var f = flag.NewFlagSet(args[0], flag.ContinueOnError) opts := struct { offset, limit *int }{ offset: f.Int("offset", 0, "result offset"), limit: f.Int("limit", 10, "result count limitation"), } if err := f.Parse(args[1:]); err != nil { return err } else if f.NArg() >= 2 { return errors.New("too many arguments") } // TODO cancel wait when abort<-true if f.NArg() == 0 { playlists, err := session.Playlists() if err != nil { return err } playlists.Wait() println("###done playlisting") indent := 0 for i := *opts.offset; i < playlists.Playlists() && i < *opts.limit; i++ { switch playlists.PlaylistType(i) { case sp.PlaylistTypeStartFolder: if folder, err := playlists.Folder(i); err == nil { print(strings.Repeat(" ", indent)) println(folder.Name()) } indent += 2 case sp.PlaylistTypeEndFolder: indent -= 2 case sp.PlaylistTypePlaylist: print(strings.Repeat(" ", indent)) println(playlistStr(playlists.Playlist(i))) } } } else { var playlist *sp.Playlist // Argument is either uri or a playlist index if n, err := strconv.Atoi(f.Arg(0)); err == nil { playlists, err := session.Playlists() if err != nil { return err } playlists.Wait() // TODO do not panic on invalid index playlist = playlists.Playlist(n) } else { link, err := session.ParseLink(f.Arg(0)) if err != nil { return err } if link.Type() != sp.LinkTypePlaylist { return errors.New("invalid link type") } playlist, err = link.Playlist() if err != nil { return err } } playlist.Wait() println(playlistStr(playlist)) for i := *opts.offset; i < playlist.Tracks() && i < *opts.limit; i++ { pt := playlist.Track(i) println(trackStr(pt.Track())) } } return nil }
go
func cmdPlaylist(session *sp.Session, args []string, abort <-chan bool) error { var f = flag.NewFlagSet(args[0], flag.ContinueOnError) opts := struct { offset, limit *int }{ offset: f.Int("offset", 0, "result offset"), limit: f.Int("limit", 10, "result count limitation"), } if err := f.Parse(args[1:]); err != nil { return err } else if f.NArg() >= 2 { return errors.New("too many arguments") } // TODO cancel wait when abort<-true if f.NArg() == 0 { playlists, err := session.Playlists() if err != nil { return err } playlists.Wait() println("###done playlisting") indent := 0 for i := *opts.offset; i < playlists.Playlists() && i < *opts.limit; i++ { switch playlists.PlaylistType(i) { case sp.PlaylistTypeStartFolder: if folder, err := playlists.Folder(i); err == nil { print(strings.Repeat(" ", indent)) println(folder.Name()) } indent += 2 case sp.PlaylistTypeEndFolder: indent -= 2 case sp.PlaylistTypePlaylist: print(strings.Repeat(" ", indent)) println(playlistStr(playlists.Playlist(i))) } } } else { var playlist *sp.Playlist // Argument is either uri or a playlist index if n, err := strconv.Atoi(f.Arg(0)); err == nil { playlists, err := session.Playlists() if err != nil { return err } playlists.Wait() // TODO do not panic on invalid index playlist = playlists.Playlist(n) } else { link, err := session.ParseLink(f.Arg(0)) if err != nil { return err } if link.Type() != sp.LinkTypePlaylist { return errors.New("invalid link type") } playlist, err = link.Playlist() if err != nil { return err } } playlist.Wait() println(playlistStr(playlist)) for i := *opts.offset; i < playlist.Tracks() && i < *opts.limit; i++ { pt := playlist.Track(i) println(trackStr(pt.Track())) } } return nil }
[ "func", "cmdPlaylist", "(", "session", "*", "sp", ".", "Session", ",", "args", "[", "]", "string", ",", "abort", "<-", "chan", "bool", ")", "error", "{", "var", "f", "=", "flag", ".", "NewFlagSet", "(", "args", "[", "0", "]", ",", "flag", ".", "C...
// cmdPlaylist lists all playlists or contents of one playlist.
[ "cmdPlaylist", "lists", "all", "playlists", "or", "contents", "of", "one", "playlist", "." ]
12dd11fb33ecf760c356b65dc1116bc92589dea4
https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/examples/gospshell/gospshell.go#L407-L483
153,266
op/go-libspotify
examples/gospshell/gospshell.go
cmdStar
func cmdStar(session *sp.Session, args []string, abort <-chan bool) error { var f = flag.NewFlagSet(args[0], flag.ContinueOnError) opts := struct { offset, limit *int user *string }{ offset: f.Int("offset", 0, "result offset"), limit: f.Int("limit", 10, "result count limitation"), user: f.String("user", "", "query for username instead of logged in user"), } if err := f.Parse(args[1:]); err != nil { return err } else if f.NArg() >= 2 { return errors.New("too many arguments") } // TODO cancel wait when abort<-true if f.NArg() == 0 { var starred *sp.Playlist if *opts.user == "" { starred = session.Starred() } else { user, err := session.GetUser(*opts.user) if err != nil { return err } user.Wait() starred = user.Starred() } starred.Wait() println("###done starred") for i := *opts.offset; i < starred.Tracks() && i < *opts.limit; i++ { pt := starred.Track(i) println(trackStr(pt.Track())) } } else { link, err := session.ParseLink(f.Arg(0)) if err != nil { return err } track, err := link.Track() if err != nil { return err } _ = track // TODO fix method return errors.New("not implemented") // session.SetStarred( // []*Track{track}, // track.IsStarred() == false // ) } return nil }
go
func cmdStar(session *sp.Session, args []string, abort <-chan bool) error { var f = flag.NewFlagSet(args[0], flag.ContinueOnError) opts := struct { offset, limit *int user *string }{ offset: f.Int("offset", 0, "result offset"), limit: f.Int("limit", 10, "result count limitation"), user: f.String("user", "", "query for username instead of logged in user"), } if err := f.Parse(args[1:]); err != nil { return err } else if f.NArg() >= 2 { return errors.New("too many arguments") } // TODO cancel wait when abort<-true if f.NArg() == 0 { var starred *sp.Playlist if *opts.user == "" { starred = session.Starred() } else { user, err := session.GetUser(*opts.user) if err != nil { return err } user.Wait() starred = user.Starred() } starred.Wait() println("###done starred") for i := *opts.offset; i < starred.Tracks() && i < *opts.limit; i++ { pt := starred.Track(i) println(trackStr(pt.Track())) } } else { link, err := session.ParseLink(f.Arg(0)) if err != nil { return err } track, err := link.Track() if err != nil { return err } _ = track // TODO fix method return errors.New("not implemented") // session.SetStarred( // []*Track{track}, // track.IsStarred() == false // ) } return nil }
[ "func", "cmdStar", "(", "session", "*", "sp", ".", "Session", ",", "args", "[", "]", "string", ",", "abort", "<-", "chan", "bool", ")", "error", "{", "var", "f", "=", "flag", ".", "NewFlagSet", "(", "args", "[", "0", "]", ",", "flag", ".", "Conti...
// cmdStar lists all starred tracks.
[ "cmdStar", "lists", "all", "starred", "tracks", "." ]
12dd11fb33ecf760c356b65dc1116bc92589dea4
https://github.com/op/go-libspotify/blob/12dd11fb33ecf760c356b65dc1116bc92589dea4/examples/gospshell/gospshell.go#L486-L544
153,267
peter-edge/pkg-go
yaml/pkgyaml.go
ParseYAMLOrJSON
func ParseYAMLOrJSON(filePath string, v interface{}) (retErr error) { data, err := ioutil.ReadFile(filePath) if err != nil { return err } switch ext := filepath.Ext(filePath); ext { case ".yml", ".yaml": data, err = ToJSON(data, ToJSONOptions{}) if err != nil { return err } case ".json": default: return fmt.Errorf("pkgyaml: %s is not a valid extension yml, yaml, or json", ext) } return json.Unmarshal(data, v) }
go
func ParseYAMLOrJSON(filePath string, v interface{}) (retErr error) { data, err := ioutil.ReadFile(filePath) if err != nil { return err } switch ext := filepath.Ext(filePath); ext { case ".yml", ".yaml": data, err = ToJSON(data, ToJSONOptions{}) if err != nil { return err } case ".json": default: return fmt.Errorf("pkgyaml: %s is not a valid extension yml, yaml, or json", ext) } return json.Unmarshal(data, v) }
[ "func", "ParseYAMLOrJSON", "(", "filePath", "string", ",", "v", "interface", "{", "}", ")", "(", "retErr", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "e...
// ParseYAMLOrJSON unmarshals the given file at filePath, switching based on the file extension. // // This uses the json tags on any fields, as json.Unmarshal is the unmarshalling function used.
[ "ParseYAMLOrJSON", "unmarshals", "the", "given", "file", "at", "filePath", "switching", "based", "on", "the", "file", "extension", ".", "This", "uses", "the", "json", "tags", "on", "any", "fields", "as", "json", ".", "Unmarshal", "is", "the", "unmarshalling", ...
318cf31141c87eaa4348bd8a54886ba3aaf2a427
https://github.com/peter-edge/pkg-go/blob/318cf31141c87eaa4348bd8a54886ba3aaf2a427/yaml/pkgyaml.go#L55-L71
153,268
peter-edge/pkg-go
bytes/pkgbytes.go
NewSizedBufferPool
func NewSizedBufferPool(size int, alloc int) BufferPool { return bpool.NewSizedBufferPool(size, alloc) }
go
func NewSizedBufferPool(size int, alloc int) BufferPool { return bpool.NewSizedBufferPool(size, alloc) }
[ "func", "NewSizedBufferPool", "(", "size", "int", ",", "alloc", "int", ")", "BufferPool", "{", "return", "bpool", ".", "NewSizedBufferPool", "(", "size", ",", "alloc", ")", "\n", "}" ]
// NewSizedBufferPool creates a new sized buffer pool.
[ "NewSizedBufferPool", "creates", "a", "new", "sized", "buffer", "pool", "." ]
318cf31141c87eaa4348bd8a54886ba3aaf2a427
https://github.com/peter-edge/pkg-go/blob/318cf31141c87eaa4348bd8a54886ba3aaf2a427/bytes/pkgbytes.go#L16-L18
153,269
ONSdigital/go-ns
elasticsearch/healthcheck.go
NewHealthCheckClient
func NewHealthCheckClient(url string, signRequests bool) *HealthCheckClient { return &HealthCheckClient{ cli: rhttp.DefaultClient, path: url + "/_cluster/health", serviceName: "elasticsearch", signRequests: signRequests, } }
go
func NewHealthCheckClient(url string, signRequests bool) *HealthCheckClient { return &HealthCheckClient{ cli: rhttp.DefaultClient, path: url + "/_cluster/health", serviceName: "elasticsearch", signRequests: signRequests, } }
[ "func", "NewHealthCheckClient", "(", "url", "string", ",", "signRequests", "bool", ")", "*", "HealthCheckClient", "{", "return", "&", "HealthCheckClient", "{", "cli", ":", "rhttp", ".", "DefaultClient", ",", "path", ":", "url", "+", "\"", "\"", ",", "service...
// NewHealthCheckClient returns a new elasticsearch health check client.
[ "NewHealthCheckClient", "returns", "a", "new", "elasticsearch", "health", "check", "client", "." ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/elasticsearch/healthcheck.go#L44-L52
153,270
ONSdigital/go-ns
elasticsearch/healthcheck.go
Healthcheck
func (elasticsearch *HealthCheckClient) Healthcheck() (string, error) { logData := log.Data{"url": elasticsearch.path} URL, err := url.Parse(elasticsearch.path) if err != nil { log.ErrorC("failed to create url for elasticsearch healthcheck", err, logData) return elasticsearch.serviceName, err } path := URL.String() logData["url"] = path req, err := http.NewRequest("GET", path, nil) if err != nil { log.ErrorC("failed to create request for healthcheck call to elasticsearch", err, logData) return elasticsearch.serviceName, err } if elasticsearch.signRequests { awsauth.Sign(req) } resp, err := elasticsearch.cli.Do(req) if err != nil { log.ErrorC("failed to call elasticsearch", err, logData) return elasticsearch.serviceName, err } defer resp.Body.Close() logData["http_code"] = resp.StatusCode if resp.StatusCode < http.StatusOK || resp.StatusCode >= 300 { log.Error(ErrorUnexpectedStatusCode, logData) return elasticsearch.serviceName, ErrorUnexpectedStatusCode } jsonBody, err := ioutil.ReadAll(resp.Body) if err != nil { log.ErrorC("failed to read response body from call to elastic", err, logData) return elasticsearch.serviceName, ErrorUnexpectedStatusCode } var clusterHealth ClusterHealth err = json.Unmarshal(jsonBody, &clusterHealth) if err != nil { log.Error(ErrorParsingBody, logData) return elasticsearch.serviceName, ErrorParsingBody } logData["cluster_health"] = clusterHealth.Status if clusterHealth.Status == unhealthy { log.Error(ErrorUnhealthyClusterStatus, logData) return elasticsearch.serviceName, ErrorUnhealthyClusterStatus } return elasticsearch.serviceName, nil }
go
func (elasticsearch *HealthCheckClient) Healthcheck() (string, error) { logData := log.Data{"url": elasticsearch.path} URL, err := url.Parse(elasticsearch.path) if err != nil { log.ErrorC("failed to create url for elasticsearch healthcheck", err, logData) return elasticsearch.serviceName, err } path := URL.String() logData["url"] = path req, err := http.NewRequest("GET", path, nil) if err != nil { log.ErrorC("failed to create request for healthcheck call to elasticsearch", err, logData) return elasticsearch.serviceName, err } if elasticsearch.signRequests { awsauth.Sign(req) } resp, err := elasticsearch.cli.Do(req) if err != nil { log.ErrorC("failed to call elasticsearch", err, logData) return elasticsearch.serviceName, err } defer resp.Body.Close() logData["http_code"] = resp.StatusCode if resp.StatusCode < http.StatusOK || resp.StatusCode >= 300 { log.Error(ErrorUnexpectedStatusCode, logData) return elasticsearch.serviceName, ErrorUnexpectedStatusCode } jsonBody, err := ioutil.ReadAll(resp.Body) if err != nil { log.ErrorC("failed to read response body from call to elastic", err, logData) return elasticsearch.serviceName, ErrorUnexpectedStatusCode } var clusterHealth ClusterHealth err = json.Unmarshal(jsonBody, &clusterHealth) if err != nil { log.Error(ErrorParsingBody, logData) return elasticsearch.serviceName, ErrorParsingBody } logData["cluster_health"] = clusterHealth.Status if clusterHealth.Status == unhealthy { log.Error(ErrorUnhealthyClusterStatus, logData) return elasticsearch.serviceName, ErrorUnhealthyClusterStatus } return elasticsearch.serviceName, nil }
[ "func", "(", "elasticsearch", "*", "HealthCheckClient", ")", "Healthcheck", "(", ")", "(", "string", ",", "error", ")", "{", "logData", ":=", "log", ".", "Data", "{", "\"", "\"", ":", "elasticsearch", ".", "path", "}", "\n\n", "URL", ",", "err", ":=", ...
// Healthcheck calls elasticsearch to check its health status.
[ "Healthcheck", "calls", "elasticsearch", "to", "check", "its", "health", "status", "." ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/elasticsearch/healthcheck.go#L55-L111
153,271
alexkappa/mustache
lex.go
emit
func (l *lexer) emit(t tokenType) { l.tokens <- token{ t, l.input[l.start:l.pos], l.lineNum(), l.columnNum(), } l.start = l.pos }
go
func (l *lexer) emit(t tokenType) { l.tokens <- token{ t, l.input[l.start:l.pos], l.lineNum(), l.columnNum(), } l.start = l.pos }
[ "func", "(", "l", "*", "lexer", ")", "emit", "(", "t", "tokenType", ")", "{", "l", ".", "tokens", "<-", "token", "{", "t", ",", "l", ".", "input", "[", "l", ".", "start", ":", "l", ".", "pos", "]", ",", "l", ".", "lineNum", "(", ")", ",", ...
// emit passes an token back to the client.
[ "emit", "passes", "an", "token", "back", "to", "the", "client", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L128-L136
153,272
alexkappa/mustache
lex.go
lineNum
func (l *lexer) lineNum() int { return 1 + strings.Count(l.input[:l.pos], "\n") }
go
func (l *lexer) lineNum() int { return 1 + strings.Count(l.input[:l.pos], "\n") }
[ "func", "(", "l", "*", "lexer", ")", "lineNum", "(", ")", "int", "{", "return", "1", "+", "strings", ".", "Count", "(", "l", ".", "input", "[", ":", "l", ".", "pos", "]", ",", "\"", "\\n", "\"", ")", "\n", "}" ]
// lineNum reports which line we're on. Doing it this way // means we don't have to worry about peek double counting.
[ "lineNum", "reports", "which", "line", "we", "re", "on", ".", "Doing", "it", "this", "way", "means", "we", "don", "t", "have", "to", "worry", "about", "peek", "double", "counting", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L145-L147
153,273
alexkappa/mustache
lex.go
columnNum
func (l *lexer) columnNum() int { if lf := strings.LastIndex(l.input[:l.pos], "\n"); lf != -1 { return len(l.input[lf+1 : l.pos]) } return len(l.input[:l.pos]) }
go
func (l *lexer) columnNum() int { if lf := strings.LastIndex(l.input[:l.pos], "\n"); lf != -1 { return len(l.input[lf+1 : l.pos]) } return len(l.input[:l.pos]) }
[ "func", "(", "l", "*", "lexer", ")", "columnNum", "(", ")", "int", "{", "if", "lf", ":=", "strings", ".", "LastIndex", "(", "l", ".", "input", "[", ":", "l", ".", "pos", "]", ",", "\"", "\\n", "\"", ")", ";", "lf", "!=", "-", "1", "{", "ret...
// columnNum reports the character of the current line we're on.
[ "columnNum", "reports", "the", "character", "of", "the", "current", "line", "we", "re", "on", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L150-L155
153,274
alexkappa/mustache
lex.go
errorf
func (l *lexer) errorf(format string, args ...interface{}) stateFn { l.tokens <- token{ tokenError, fmt.Sprintf(format, args...), l.lineNum(), l.columnNum(), } return nil }
go
func (l *lexer) errorf(format string, args ...interface{}) stateFn { l.tokens <- token{ tokenError, fmt.Sprintf(format, args...), l.lineNum(), l.columnNum(), } return nil }
[ "func", "(", "l", "*", "lexer", ")", "errorf", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "stateFn", "{", "l", ".", "tokens", "<-", "token", "{", "tokenError", ",", "fmt", ".", "Sprintf", "(", "format", ",", "args", "....
// error returns an error token and terminates the scan by passing // back a nil pointer that will be the next state, terminating l.token.
[ "error", "returns", "an", "error", "token", "and", "terminates", "the", "scan", "by", "passing", "back", "a", "nil", "pointer", "that", "will", "be", "the", "next", "state", "terminating", "l", ".", "token", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L159-L167
153,275
alexkappa/mustache
lex.go
token
func (l *lexer) token() token { for { select { case token := <-l.tokens: return token default: l.state = l.state(l) } } }
go
func (l *lexer) token() token { for { select { case token := <-l.tokens: return token default: l.state = l.state(l) } } }
[ "func", "(", "l", "*", "lexer", ")", "token", "(", ")", "token", "{", "for", "{", "select", "{", "case", "token", ":=", "<-", "l", ".", "tokens", ":", "return", "token", "\n", "default", ":", "l", ".", "state", "=", "l", ".", "state", "(", "l",...
// token returns the next token from the input.
[ "token", "returns", "the", "next", "token", "from", "the", "input", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L170-L179
153,276
alexkappa/mustache
lex.go
newLexer
func newLexer(input, left, right string) *lexer { l := &lexer{ input: input, leftDelim: left, rightDelim: right, tokens: make(chan token, 2), } l.state = stateText // initial state return l }
go
func newLexer(input, left, right string) *lexer { l := &lexer{ input: input, leftDelim: left, rightDelim: right, tokens: make(chan token, 2), } l.state = stateText // initial state return l }
[ "func", "newLexer", "(", "input", ",", "left", ",", "right", "string", ")", "*", "lexer", "{", "l", ":=", "&", "lexer", "{", "input", ":", "input", ",", "leftDelim", ":", "left", ",", "rightDelim", ":", "right", ",", "tokens", ":", "make", "(", "ch...
// newLexer creates a new scanner for the input string.
[ "newLexer", "creates", "a", "new", "scanner", "for", "the", "input", "string", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L191-L200
153,277
alexkappa/mustache
lex.go
stateText
func stateText(l *lexer) stateFn { for { // Lookahead for {{ which should switch to lexing an open tag instead of // regular text tokens. if strings.HasPrefix(l.input[l.pos:], l.leftDelim) { if l.pos > l.start { l.emit(tokenText) } return stateLeftDelim } // Produce a token and exit the loop if we have reached the end of file. if l.next() == eof { break } } // Emit whatever we gathered so far as text. if l.pos > l.start { l.emit(tokenText) } // Always end with EOF token. The parser will keep asking for tokens until // an tokenEOF or tokenError token are encountered. l.emit(tokenEOF) // The text state doesn't have a default next state. return nil }
go
func stateText(l *lexer) stateFn { for { // Lookahead for {{ which should switch to lexing an open tag instead of // regular text tokens. if strings.HasPrefix(l.input[l.pos:], l.leftDelim) { if l.pos > l.start { l.emit(tokenText) } return stateLeftDelim } // Produce a token and exit the loop if we have reached the end of file. if l.next() == eof { break } } // Emit whatever we gathered so far as text. if l.pos > l.start { l.emit(tokenText) } // Always end with EOF token. The parser will keep asking for tokens until // an tokenEOF or tokenError token are encountered. l.emit(tokenEOF) // The text state doesn't have a default next state. return nil }
[ "func", "stateText", "(", "l", "*", "lexer", ")", "stateFn", "{", "for", "{", "// Lookahead for {{ which should switch to lexing an open tag instead of", "// regular text tokens.", "if", "strings", ".", "HasPrefix", "(", "l", ".", "input", "[", "l", ".", "pos", ":",...
// state functions. // stateText scans until an opening action delimiter, "{{".
[ "state", "functions", ".", "stateText", "scans", "until", "an", "opening", "action", "delimiter", "{{", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L205-L229
153,278
alexkappa/mustache
lex.go
stateLeftDelim
func stateLeftDelim(l *lexer) stateFn { l.seek(len(l.leftDelim)) if l.peek() == '=' { // When the lexer encounters "{{=" it proceeds to the set delimiter // state which alters the left and right delimiters. This operation is // hidden from the parser and no tokens are emited. l.next() return stateSetDelim } l.emit(tokenLeftDelim) return stateTag }
go
func stateLeftDelim(l *lexer) stateFn { l.seek(len(l.leftDelim)) if l.peek() == '=' { // When the lexer encounters "{{=" it proceeds to the set delimiter // state which alters the left and right delimiters. This operation is // hidden from the parser and no tokens are emited. l.next() return stateSetDelim } l.emit(tokenLeftDelim) return stateTag }
[ "func", "stateLeftDelim", "(", "l", "*", "lexer", ")", "stateFn", "{", "l", ".", "seek", "(", "len", "(", "l", ".", "leftDelim", ")", ")", "\n", "if", "l", ".", "peek", "(", ")", "==", "'='", "{", "// When the lexer encounters \"{{=\" it proceeds to the se...
// stateLeftDelim scans the left delimiter, which is known to be present.
[ "stateLeftDelim", "scans", "the", "left", "delimiter", "which", "is", "known", "to", "be", "present", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L232-L243
153,279
alexkappa/mustache
lex.go
stateRightDelim
func stateRightDelim(l *lexer) stateFn { l.seek(len(l.rightDelim)) l.emit(tokenRightDelim) return stateText }
go
func stateRightDelim(l *lexer) stateFn { l.seek(len(l.rightDelim)) l.emit(tokenRightDelim) return stateText }
[ "func", "stateRightDelim", "(", "l", "*", "lexer", ")", "stateFn", "{", "l", ".", "seek", "(", "len", "(", "l", ".", "rightDelim", ")", ")", "\n", "l", ".", "emit", "(", "tokenRightDelim", ")", "\n", "return", "stateText", "\n", "}" ]
// stateRightDelim scans the right delimiter, which is known to be present.
[ "stateRightDelim", "scans", "the", "right", "delimiter", "which", "is", "known", "to", "be", "present", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L246-L250
153,280
alexkappa/mustache
lex.go
stateTag
func stateTag(l *lexer) stateFn { if strings.HasPrefix(l.input[l.pos:], "}"+l.rightDelim) { l.seek(1) l.emit(tokenRawEnd) return stateRightDelim } if strings.HasPrefix(l.input[l.pos:], l.rightDelim) { return stateRightDelim } switch r := l.next(); { case r == eof || r == '\n': return l.errorf("unclosed action") case whitespace(r): l.ignore() case r == '!': l.emit(tokenComment) return stateComment case r == '#': l.emit(tokenSectionStart) case r == '^': l.emit(tokenSectionInverse) case r == '/': l.emit(tokenSectionEnd) case r == '&': l.emit(tokenRawAlt) case r == '>': l.emit(tokenPartial) case r == '{': l.emit(tokenRawStart) case alphanum(r): l.backup() return stateIdent default: return l.errorf("unrecognized character in action: %#U", r) } return stateTag }
go
func stateTag(l *lexer) stateFn { if strings.HasPrefix(l.input[l.pos:], "}"+l.rightDelim) { l.seek(1) l.emit(tokenRawEnd) return stateRightDelim } if strings.HasPrefix(l.input[l.pos:], l.rightDelim) { return stateRightDelim } switch r := l.next(); { case r == eof || r == '\n': return l.errorf("unclosed action") case whitespace(r): l.ignore() case r == '!': l.emit(tokenComment) return stateComment case r == '#': l.emit(tokenSectionStart) case r == '^': l.emit(tokenSectionInverse) case r == '/': l.emit(tokenSectionEnd) case r == '&': l.emit(tokenRawAlt) case r == '>': l.emit(tokenPartial) case r == '{': l.emit(tokenRawStart) case alphanum(r): l.backup() return stateIdent default: return l.errorf("unrecognized character in action: %#U", r) } return stateTag }
[ "func", "stateTag", "(", "l", "*", "lexer", ")", "stateFn", "{", "if", "strings", ".", "HasPrefix", "(", "l", ".", "input", "[", "l", ".", "pos", ":", "]", ",", "\"", "\"", "+", "l", ".", "rightDelim", ")", "{", "l", ".", "seek", "(", "1", ")...
// stateTag scans the elements inside action delimiters.
[ "stateTag", "scans", "the", "elements", "inside", "action", "delimiters", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L253-L289
153,281
alexkappa/mustache
lex.go
stateIdent
func stateIdent(l *lexer) stateFn { Loop: for { switch r := l.next(); { case alphanum(r): // absorb. default: l.backup() l.emit(tokenIdentifier) break Loop } } return stateTag }
go
func stateIdent(l *lexer) stateFn { Loop: for { switch r := l.next(); { case alphanum(r): // absorb. default: l.backup() l.emit(tokenIdentifier) break Loop } } return stateTag }
[ "func", "stateIdent", "(", "l", "*", "lexer", ")", "stateFn", "{", "Loop", ":", "for", "{", "switch", "r", ":=", "l", ".", "next", "(", ")", ";", "{", "case", "alphanum", "(", "r", ")", ":", "// absorb.", "default", ":", "l", ".", "backup", "(", ...
// stateIdent scans an alphanumeric or field.
[ "stateIdent", "scans", "an", "alphanumeric", "or", "field", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L292-L305
153,282
alexkappa/mustache
lex.go
stateComment
func stateComment(l *lexer) stateFn { i := strings.Index(l.input[l.pos:], l.rightDelim) if i < 0 { return l.errorf("unclosed tag") } l.seek(i) l.emit(tokenText) return stateRightDelim }
go
func stateComment(l *lexer) stateFn { i := strings.Index(l.input[l.pos:], l.rightDelim) if i < 0 { return l.errorf("unclosed tag") } l.seek(i) l.emit(tokenText) return stateRightDelim }
[ "func", "stateComment", "(", "l", "*", "lexer", ")", "stateFn", "{", "i", ":=", "strings", ".", "Index", "(", "l", ".", "input", "[", "l", ".", "pos", ":", "]", ",", "l", ".", "rightDelim", ")", "\n", "if", "i", "<", "0", "{", "return", "l", ...
// stateComment scans a comment. The left comment marker is known to be present.
[ "stateComment", "scans", "a", "comment", ".", "The", "left", "comment", "marker", "is", "known", "to", "be", "present", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L308-L316
153,283
alexkappa/mustache
lex.go
stateSetDelim
func stateSetDelim(l *lexer) stateFn { end := "=" + l.rightDelim i := strings.Index(l.input[l.pos:], end) if i < 0 { return l.errorf("unclosed tag") } delims := strings.Split(l.input[l.pos:l.pos+i], " ") // " | | " if len(delims) < 2 { l.errorf("set delimiters should be separated by a space") } delimFn := leftFn for _, delim := range delims { if delim != "" { if delimFn != nil { delimFn = delimFn(l, delim) } } } l.seek(i + len(end)) l.ignore() l.emit(tokenSetDelim) return stateText }
go
func stateSetDelim(l *lexer) stateFn { end := "=" + l.rightDelim i := strings.Index(l.input[l.pos:], end) if i < 0 { return l.errorf("unclosed tag") } delims := strings.Split(l.input[l.pos:l.pos+i], " ") // " | | " if len(delims) < 2 { l.errorf("set delimiters should be separated by a space") } delimFn := leftFn for _, delim := range delims { if delim != "" { if delimFn != nil { delimFn = delimFn(l, delim) } } } l.seek(i + len(end)) l.ignore() l.emit(tokenSetDelim) return stateText }
[ "func", "stateSetDelim", "(", "l", "*", "lexer", ")", "stateFn", "{", "end", ":=", "\"", "\"", "+", "l", ".", "rightDelim", "\n", "i", ":=", "strings", ".", "Index", "(", "l", ".", "input", "[", "l", ".", "pos", ":", "]", ",", "end", ")", "\n",...
// stateSetDelim scans a set of set delimiter tags and replaces the lexers left // and right delimiters to new values.
[ "stateSetDelim", "scans", "a", "set", "of", "set", "delimiter", "tags", "and", "replaces", "the", "lexers", "left", "and", "right", "delimiters", "to", "new", "values", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L320-L342
153,284
alexkappa/mustache
lex.go
leftFn
func leftFn(l *lexer, s string) delimFn { l.leftDelim = s return rightFn }
go
func leftFn(l *lexer, s string) delimFn { l.leftDelim = s return rightFn }
[ "func", "leftFn", "(", "l", "*", "lexer", ",", "s", "string", ")", "delimFn", "{", "l", ".", "leftDelim", "=", "s", "\n", "return", "rightFn", "\n", "}" ]
// leftFn sets the left delimiter to s and returns a rightFn.
[ "leftFn", "sets", "the", "left", "delimiter", "to", "s", "and", "returns", "a", "rightFn", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L349-L352
153,285
alexkappa/mustache
lex.go
rightFn
func rightFn(l *lexer, s string) delimFn { l.rightDelim = s return nil }
go
func rightFn(l *lexer, s string) delimFn { l.rightDelim = s return nil }
[ "func", "rightFn", "(", "l", "*", "lexer", ",", "s", "string", ")", "delimFn", "{", "l", ".", "rightDelim", "=", "s", "\n", "return", "nil", "\n", "}" ]
// rightFn sets the right delimiter to s.
[ "rightFn", "sets", "the", "right", "delimiter", "to", "s", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L355-L358
153,286
alexkappa/mustache
lex.go
alphanum
func alphanum(r rune) bool { return r == '_' || r == '.' || unicode.IsLetter(r) || unicode.IsDigit(r) }
go
func alphanum(r rune) bool { return r == '_' || r == '.' || unicode.IsLetter(r) || unicode.IsDigit(r) }
[ "func", "alphanum", "(", "r", "rune", ")", "bool", "{", "return", "r", "==", "'_'", "||", "r", "==", "'.'", "||", "unicode", ".", "IsLetter", "(", "r", ")", "||", "unicode", ".", "IsDigit", "(", "r", ")", "\n", "}" ]
// alphanum reports whether r is an alphabetic, digit, or underscore.
[ "alphanum", "reports", "whether", "r", "is", "an", "alphabetic", "digit", "or", "underscore", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/lex.go#L370-L372
153,287
ONSdigital/go-ns
handlers/response/writer.go
WriteJSON
func WriteJSON(w http.ResponseWriter, value interface{}, status int) error { return jsonResponseEncoder.writeResponseJSON(w, value, status) }
go
func WriteJSON(w http.ResponseWriter, value interface{}, status int) error { return jsonResponseEncoder.writeResponseJSON(w, value, status) }
[ "func", "WriteJSON", "(", "w", "http", ".", "ResponseWriter", ",", "value", "interface", "{", "}", ",", "status", "int", ")", "error", "{", "return", "jsonResponseEncoder", ".", "writeResponseJSON", "(", "w", ",", "value", ",", "status", ")", "\n", "}" ]
// WriteJSON set the content type header to JSON, writes the response object as json and sets the http status code.
[ "WriteJSON", "set", "the", "content", "type", "header", "to", "JSON", "writes", "the", "response", "object", "as", "json", "and", "sets", "the", "http", "status", "code", "." ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/handlers/response/writer.go#L21-L23
153,288
ONSdigital/go-ns
clients/identity/authentication.go
NewAPIClient
func NewAPIClient(cli common.RCHTTPClienter, url string) (api *Client) { return &Client{ HTTPClient: cli, BaseURL: url, } }
go
func NewAPIClient(cli common.RCHTTPClienter, url string) (api *Client) { return &Client{ HTTPClient: cli, BaseURL: url, } }
[ "func", "NewAPIClient", "(", "cli", "common", ".", "RCHTTPClienter", ",", "url", "string", ")", "(", "api", "*", "Client", ")", "{", "return", "&", "Client", "{", "HTTPClient", ":", "cli", ",", "BaseURL", ":", "url", ",", "}", "\n", "}" ]
// NewAPIClient returns a Client
[ "NewAPIClient", "returns", "a", "Client" ]
81b393bfc6e80674df603b7fde2f31a35e81b9dd
https://github.com/ONSdigital/go-ns/blob/81b393bfc6e80674df603b7fde2f31a35e81b9dd/clients/identity/authentication.go#L33-L38
153,289
alexkappa/mustache
mustache.go
print
func print(w io.Writer, v interface{}) { if s, ok := v.(fmt.Stringer); ok { fmt.Fprint(w, s.String()) } else { switch v.(type) { case string: fmt.Fprintf(w, "%s", v) case int, uint, int8, uint8, int16, uint16, int32, uint32, int64, uint64: fmt.Fprintf(w, "%d", v) case float32, float64: fmt.Fprintf(w, "%g", v) default: fmt.Fprintf(w, "%v", v) } } }
go
func print(w io.Writer, v interface{}) { if s, ok := v.(fmt.Stringer); ok { fmt.Fprint(w, s.String()) } else { switch v.(type) { case string: fmt.Fprintf(w, "%s", v) case int, uint, int8, uint8, int16, uint16, int32, uint32, int64, uint64: fmt.Fprintf(w, "%d", v) case float32, float64: fmt.Fprintf(w, "%g", v) default: fmt.Fprintf(w, "%v", v) } } }
[ "func", "print", "(", "w", "io", ".", "Writer", ",", "v", "interface", "{", "}", ")", "{", "if", "s", ",", "ok", ":=", "v", ".", "(", "fmt", ".", "Stringer", ")", ";", "ok", "{", "fmt", ".", "Fprint", "(", "w", ",", "s", ".", "String", "(",...
// The print function is able to format the interface v and write it to w using // the best possible formatting flags.
[ "The", "print", "function", "is", "able", "to", "format", "the", "interface", "v", "and", "write", "it", "to", "w", "using", "the", "best", "possible", "formatting", "flags", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/mustache.go#L153-L168
153,290
alexkappa/mustache
mustache.go
Delimiters
func Delimiters(start, end string) Option { return func(t *Template) { t.startDelim = start t.endDelim = end } }
go
func Delimiters(start, end string) Option { return func(t *Template) { t.startDelim = start t.endDelim = end } }
[ "func", "Delimiters", "(", "start", ",", "end", "string", ")", "Option", "{", "return", "func", "(", "t", "*", "Template", ")", "{", "t", ".", "startDelim", "=", "start", "\n", "t", ".", "endDelim", "=", "end", "\n", "}", "\n", "}" ]
// Delimiters sets the start and end delimiters of the template.
[ "Delimiters", "sets", "the", "start", "and", "end", "delimiters", "of", "the", "template", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/mustache.go#L208-L213
153,291
alexkappa/mustache
mustache.go
Partial
func Partial(p *Template) Option { return func(t *Template) { t.partials[p.name] = p } }
go
func Partial(p *Template) Option { return func(t *Template) { t.partials[p.name] = p } }
[ "func", "Partial", "(", "p", "*", "Template", ")", "Option", "{", "return", "func", "(", "t", "*", "Template", ")", "{", "t", ".", "partials", "[", "p", ".", "name", "]", "=", "p", "\n", "}", "\n", "}" ]
// Partial sets p as a partial to the template. It is important to set the name // of p so that it may be looked up by the parent template.
[ "Partial", "sets", "p", "as", "a", "partial", "to", "the", "template", ".", "It", "is", "important", "to", "set", "the", "name", "of", "p", "so", "that", "it", "may", "be", "looked", "up", "by", "the", "parent", "template", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/mustache.go#L217-L221
153,292
alexkappa/mustache
mustache.go
New
func New(options ...Option) *Template { t := &Template{ elems: make([]node, 0), partials: make(map[string]*Template), startDelim: "{{", endDelim: "}}", silentMiss: true, } t.Option(options...) return t }
go
func New(options ...Option) *Template { t := &Template{ elems: make([]node, 0), partials: make(map[string]*Template), startDelim: "{{", endDelim: "}}", silentMiss: true, } t.Option(options...) return t }
[ "func", "New", "(", "options", "...", "Option", ")", "*", "Template", "{", "t", ":=", "&", "Template", "{", "elems", ":", "make", "(", "[", "]", "node", ",", "0", ")", ",", "partials", ":", "make", "(", "map", "[", "string", "]", "*", "Template",...
// New returns a new Template instance.
[ "New", "returns", "a", "new", "Template", "instance", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/mustache.go#L251-L261
153,293
alexkappa/mustache
mustache.go
Option
func (t *Template) Option(options ...Option) { for _, optionFn := range options { optionFn(t) } }
go
func (t *Template) Option(options ...Option) { for _, optionFn := range options { optionFn(t) } }
[ "func", "(", "t", "*", "Template", ")", "Option", "(", "options", "...", "Option", ")", "{", "for", "_", ",", "optionFn", ":=", "range", "options", "{", "optionFn", "(", "t", ")", "\n", "}", "\n", "}" ]
// Option applies options to the currrent template t.
[ "Option", "applies", "options", "to", "the", "currrent", "template", "t", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/mustache.go#L264-L268
153,294
alexkappa/mustache
mustache.go
Parse
func (t *Template) Parse(r io.Reader) error { b, err := ioutil.ReadAll(r) if err != nil { return err } l := newLexer(string(b), t.startDelim, t.endDelim) p := newParser(l) elems, err := p.parse() if err != nil { return err } t.elems = elems return nil }
go
func (t *Template) Parse(r io.Reader) error { b, err := ioutil.ReadAll(r) if err != nil { return err } l := newLexer(string(b), t.startDelim, t.endDelim) p := newParser(l) elems, err := p.parse() if err != nil { return err } t.elems = elems return nil }
[ "func", "(", "t", "*", "Template", ")", "Parse", "(", "r", "io", ".", "Reader", ")", "error", "{", "b", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "l", ":=...
// Parse parses a stream of bytes read from r and creates a parse tree that // represents the template.
[ "Parse", "parses", "a", "stream", "of", "bytes", "read", "from", "r", "and", "creates", "a", "parse", "tree", "that", "represents", "the", "template", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/mustache.go#L272-L285
153,295
alexkappa/mustache
mustache.go
ParseString
func (t *Template) ParseString(s string) error { return t.Parse(strings.NewReader(s)) }
go
func (t *Template) ParseString(s string) error { return t.Parse(strings.NewReader(s)) }
[ "func", "(", "t", "*", "Template", ")", "ParseString", "(", "s", "string", ")", "error", "{", "return", "t", ".", "Parse", "(", "strings", ".", "NewReader", "(", "s", ")", ")", "\n", "}" ]
// ParseString is a helper function that uses a string as input.
[ "ParseString", "is", "a", "helper", "function", "that", "uses", "a", "string", "as", "input", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/mustache.go#L288-L290
153,296
alexkappa/mustache
mustache.go
ParseBytes
func (t *Template) ParseBytes(b []byte) error { return t.Parse(bytes.NewReader(b)) }
go
func (t *Template) ParseBytes(b []byte) error { return t.Parse(bytes.NewReader(b)) }
[ "func", "(", "t", "*", "Template", ")", "ParseBytes", "(", "b", "[", "]", "byte", ")", "error", "{", "return", "t", ".", "Parse", "(", "bytes", ".", "NewReader", "(", "b", ")", ")", "\n", "}" ]
// ParseBytes is a helper function that uses a byte array as input.
[ "ParseBytes", "is", "a", "helper", "function", "that", "uses", "a", "byte", "array", "as", "input", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/mustache.go#L293-L295
153,297
alexkappa/mustache
mustache.go
Render
func (t *Template) Render(w io.Writer, context ...interface{}) error { return t.render(newWriter(w), context...) }
go
func (t *Template) Render(w io.Writer, context ...interface{}) error { return t.render(newWriter(w), context...) }
[ "func", "(", "t", "*", "Template", ")", "Render", "(", "w", "io", ".", "Writer", ",", "context", "...", "interface", "{", "}", ")", "error", "{", "return", "t", ".", "render", "(", "newWriter", "(", "w", ")", ",", "context", "...", ")", "\n", "}"...
// Render walks through the template's parse tree and writes the output to w // replacing the values found in context.
[ "Render", "walks", "through", "the", "template", "s", "parse", "tree", "and", "writes", "the", "output", "to", "w", "replacing", "the", "values", "found", "in", "context", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/mustache.go#L311-L313
153,298
alexkappa/mustache
mustache.go
RenderString
func (t *Template) RenderString(context ...interface{}) (string, error) { b := &bytes.Buffer{} err := t.Render(b, context...) return b.String(), err }
go
func (t *Template) RenderString(context ...interface{}) (string, error) { b := &bytes.Buffer{} err := t.Render(b, context...) return b.String(), err }
[ "func", "(", "t", "*", "Template", ")", "RenderString", "(", "context", "...", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "b", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "err", ":=", "t", ".", "Render", "(", "b", ...
// RenderString is a helper function that renders the template as a string.
[ "RenderString", "is", "a", "helper", "function", "that", "renders", "the", "template", "as", "a", "string", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/mustache.go#L316-L320
153,299
alexkappa/mustache
mustache.go
RenderBytes
func (t *Template) RenderBytes(context ...interface{}) ([]byte, error) { var b *bytes.Buffer err := t.Render(b, context...) return b.Bytes(), err }
go
func (t *Template) RenderBytes(context ...interface{}) ([]byte, error) { var b *bytes.Buffer err := t.Render(b, context...) return b.Bytes(), err }
[ "func", "(", "t", "*", "Template", ")", "RenderBytes", "(", "context", "...", "interface", "{", "}", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "b", "*", "bytes", ".", "Buffer", "\n", "err", ":=", "t", ".", "Render", "(", "b", "...
// RenderBytes is a helper function that renders the template as a byte slice.
[ "RenderBytes", "is", "a", "helper", "function", "that", "renders", "the", "template", "as", "a", "byte", "slice", "." ]
d29845f60a879542625ba65812ddfb99fd9b12b9
https://github.com/alexkappa/mustache/blob/d29845f60a879542625ba65812ddfb99fd9b12b9/mustache.go#L323-L327