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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
10,500 | cloudfoundry/dropsonde | metricbatcher/metricbatcher.go | New | func New(metricSender MetricSender, batchDuration time.Duration) *MetricBatcher {
mb := &MetricBatcher{
batchTicker: time.NewTicker(batchDuration),
metricSender: metricSender,
closed: false,
closedChan: make(chan struct{}),
}
go func() {
for {
select {
case <-mb.batchTicker.C:
mb.flush(mb.resetAndReturnMetrics())
case <-mb.closedChan:
mb.batchTicker.Stop()
return
}
}
}()
return mb
} | go | func New(metricSender MetricSender, batchDuration time.Duration) *MetricBatcher {
mb := &MetricBatcher{
batchTicker: time.NewTicker(batchDuration),
metricSender: metricSender,
closed: false,
closedChan: make(chan struct{}),
}
go func() {
for {
select {
case <-mb.batchTicker.C:
mb.flush(mb.resetAndReturnMetrics())
case <-mb.closedChan:
mb.batchTicker.Stop()
return
}
}
}()
return mb
} | [
"func",
"New",
"(",
"metricSender",
"MetricSender",
",",
"batchDuration",
"time",
".",
"Duration",
")",
"*",
"MetricBatcher",
"{",
"mb",
":=",
"&",
"MetricBatcher",
"{",
"batchTicker",
":",
"time",
".",
"NewTicker",
"(",
"batchDuration",
")",
",",
"metricSender",
":",
"metricSender",
",",
"closed",
":",
"false",
",",
"closedChan",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"mb",
".",
"batchTicker",
".",
"C",
":",
"mb",
".",
"flush",
"(",
"mb",
".",
"resetAndReturnMetrics",
"(",
")",
")",
"\n",
"case",
"<-",
"mb",
".",
"closedChan",
":",
"mb",
".",
"batchTicker",
".",
"Stop",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"mb",
"\n",
"}"
] | // New instantiates a running MetricBatcher. Eventswill be emitted once per batchDuration. All
// updates to a given counter name will be combined into a single event and sent to metricSender. | [
"New",
"instantiates",
"a",
"running",
"MetricBatcher",
".",
"Eventswill",
"be",
"emitted",
"once",
"per",
"batchDuration",
".",
"All",
"updates",
"to",
"a",
"given",
"counter",
"name",
"will",
"be",
"combined",
"into",
"a",
"single",
"event",
"and",
"sent",
"to",
"metricSender",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/metricbatcher/metricbatcher.go#L36-L57 |
10,501 | cloudfoundry/dropsonde | metricbatcher/metricbatcher.go | BatchAddCounter | func (mb *MetricBatcher) BatchAddCounter(name string, delta uint64) {
mb.lock.Lock()
defer mb.lock.Unlock()
if mb.closed {
panic("Attempting to send metrics after closed")
}
mb.add(batch{name: name, value: delta})
} | go | func (mb *MetricBatcher) BatchAddCounter(name string, delta uint64) {
mb.lock.Lock()
defer mb.lock.Unlock()
if mb.closed {
panic("Attempting to send metrics after closed")
}
mb.add(batch{name: name, value: delta})
} | [
"func",
"(",
"mb",
"*",
"MetricBatcher",
")",
"BatchAddCounter",
"(",
"name",
"string",
",",
"delta",
"uint64",
")",
"{",
"mb",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mb",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"mb",
".",
"closed",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"mb",
".",
"add",
"(",
"batch",
"{",
"name",
":",
"name",
",",
"value",
":",
"delta",
"}",
")",
"\n",
"}"
] | // BatchAddCounter increments the named counter by the provided delta, but does not
// immediately send a CounterEvent. | [
"BatchAddCounter",
"increments",
"the",
"named",
"counter",
"by",
"the",
"provided",
"delta",
"but",
"does",
"not",
"immediately",
"send",
"a",
"CounterEvent",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/metricbatcher/metricbatcher.go#L67-L76 |
10,502 | cloudfoundry/dropsonde | metricbatcher/metricbatcher.go | BatchCounter | func (mb *MetricBatcher) BatchCounter(name string) BatchCounterChainer {
return batchCounterChainer{
batcher: mb,
name: name,
tags: make(map[string]string),
}
} | go | func (mb *MetricBatcher) BatchCounter(name string) BatchCounterChainer {
return batchCounterChainer{
batcher: mb,
name: name,
tags: make(map[string]string),
}
} | [
"func",
"(",
"mb",
"*",
"MetricBatcher",
")",
"BatchCounter",
"(",
"name",
"string",
")",
"BatchCounterChainer",
"{",
"return",
"batchCounterChainer",
"{",
"batcher",
":",
"mb",
",",
"name",
":",
"name",
",",
"tags",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
",",
"}",
"\n",
"}"
] | // BatchCounter returns a BatchCounterChainer which can be used to prepare
// a counter event before batching it up. | [
"BatchCounter",
"returns",
"a",
"BatchCounterChainer",
"which",
"can",
"be",
"used",
"to",
"prepare",
"a",
"counter",
"event",
"before",
"batching",
"it",
"up",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/metricbatcher/metricbatcher.go#L104-L110 |
10,503 | cloudfoundry/dropsonde | metricbatcher/metricbatcher.go | Close | func (mb *MetricBatcher) Close() {
mb.lock.Lock()
defer mb.lock.Unlock()
mb.closed = true
close(mb.closedChan)
mb.flush(mb.unsafeResetAndReturnMetrics())
} | go | func (mb *MetricBatcher) Close() {
mb.lock.Lock()
defer mb.lock.Unlock()
mb.closed = true
close(mb.closedChan)
mb.flush(mb.unsafeResetAndReturnMetrics())
} | [
"func",
"(",
"mb",
"*",
"MetricBatcher",
")",
"Close",
"(",
")",
"{",
"mb",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mb",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"mb",
".",
"closed",
"=",
"true",
"\n",
"close",
"(",
"mb",
".",
"closedChan",
")",
"\n\n",
"mb",
".",
"flush",
"(",
"mb",
".",
"unsafeResetAndReturnMetrics",
"(",
")",
")",
"\n",
"}"
] | // Closes the metrics batcher. Using the batcher after closing, will cause a panic. | [
"Closes",
"the",
"metrics",
"batcher",
".",
"Using",
"the",
"batcher",
"after",
"closing",
"will",
"cause",
"a",
"panic",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/metricbatcher/metricbatcher.go#L118-L126 |
10,504 | cloudfoundry/dropsonde | metric_sender/metric_sender.go | Send | func (ms *MetricSender) Send(ev events.Event) error {
return ms.eventEmitter.Emit(ev)
} | go | func (ms *MetricSender) Send(ev events.Event) error {
return ms.eventEmitter.Emit(ev)
} | [
"func",
"(",
"ms",
"*",
"MetricSender",
")",
"Send",
"(",
"ev",
"events",
".",
"Event",
")",
"error",
"{",
"return",
"ms",
".",
"eventEmitter",
".",
"Emit",
"(",
"ev",
")",
"\n",
"}"
] | // Send sends an events.Event. | [
"Send",
"sends",
"an",
"events",
".",
"Event",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/metric_sender/metric_sender.go#L50-L52 |
10,505 | cloudfoundry/dropsonde | logs/logs.go | SendAppLog | func SendAppLog(appID, message, sourceType, sourceInstance string) error {
if logSender == nil {
return nil
}
return logSender.SendAppLog(appID, message, sourceType, sourceInstance)
} | go | func SendAppLog(appID, message, sourceType, sourceInstance string) error {
if logSender == nil {
return nil
}
return logSender.SendAppLog(appID, message, sourceType, sourceInstance)
} | [
"func",
"SendAppLog",
"(",
"appID",
",",
"message",
",",
"sourceType",
",",
"sourceInstance",
"string",
")",
"error",
"{",
"if",
"logSender",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"logSender",
".",
"SendAppLog",
"(",
"appID",
",",
"message",
",",
"sourceType",
",",
"sourceInstance",
")",
"\n",
"}"
] | // SendAppLog sends a log message with the given appid, log message, source type
// and source instance, with a message type of std out.
// Returns an error if one occurs while sending the event. | [
"SendAppLog",
"sends",
"a",
"log",
"message",
"with",
"the",
"given",
"appid",
"log",
"message",
"source",
"type",
"and",
"source",
"instance",
"with",
"a",
"message",
"type",
"of",
"std",
"out",
".",
"Returns",
"an",
"error",
"if",
"one",
"occurs",
"while",
"sending",
"the",
"event",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/logs/logs.go#L44-L49 |
10,506 | cloudfoundry/dropsonde | dropsonde_unmarshaller/dropsonde_unmarshaller.go | Run | func (u *DropsondeUnmarshaller) Run(inputChan <-chan []byte, outputChan chan<- *events.Envelope) {
for message := range inputChan {
envelope, err := u.UnmarshallMessage(message)
if err != nil {
continue
}
outputChan <- envelope
}
} | go | func (u *DropsondeUnmarshaller) Run(inputChan <-chan []byte, outputChan chan<- *events.Envelope) {
for message := range inputChan {
envelope, err := u.UnmarshallMessage(message)
if err != nil {
continue
}
outputChan <- envelope
}
} | [
"func",
"(",
"u",
"*",
"DropsondeUnmarshaller",
")",
"Run",
"(",
"inputChan",
"<-",
"chan",
"[",
"]",
"byte",
",",
"outputChan",
"chan",
"<-",
"*",
"events",
".",
"Envelope",
")",
"{",
"for",
"message",
":=",
"range",
"inputChan",
"{",
"envelope",
",",
"err",
":=",
"u",
".",
"UnmarshallMessage",
"(",
"message",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"outputChan",
"<-",
"envelope",
"\n",
"}",
"\n",
"}"
] | // Run reads byte slices from inputChan, unmarshalls them to Envelopes, and
// emits the Envelopes onto outputChan. It operates one message at a time, and
// will block if outputChan is not read. | [
"Run",
"reads",
"byte",
"slices",
"from",
"inputChan",
"unmarshalls",
"them",
"to",
"Envelopes",
"and",
"emits",
"the",
"Envelopes",
"onto",
"outputChan",
".",
"It",
"operates",
"one",
"message",
"at",
"a",
"time",
"and",
"will",
"block",
"if",
"outputChan",
"is",
"not",
"read",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/dropsonde_unmarshaller/dropsonde_unmarshaller.go#L53-L61 |
10,507 | cloudfoundry/dropsonde | instrumented_handler/instrumented_handler.go | InstrumentedHandler | func InstrumentedHandler(handler http.Handler, emitter EventEmitter) http.Handler {
return &instrumentedHandler{handler, emitter}
} | go | func InstrumentedHandler(handler http.Handler, emitter EventEmitter) http.Handler {
return &instrumentedHandler{handler, emitter}
} | [
"func",
"InstrumentedHandler",
"(",
"handler",
"http",
".",
"Handler",
",",
"emitter",
"EventEmitter",
")",
"http",
".",
"Handler",
"{",
"return",
"&",
"instrumentedHandler",
"{",
"handler",
",",
"emitter",
"}",
"\n",
"}"
] | // InstrumentedHandler is a helper for creating an instrumented http.Handler
// which will delegate to the given http.Handler. | [
"InstrumentedHandler",
"is",
"a",
"helper",
"for",
"creating",
"an",
"instrumented",
"http",
".",
"Handler",
"which",
"will",
"delegate",
"to",
"the",
"given",
"http",
".",
"Handler",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/instrumented_handler/instrumented_handler.go#L27-L29 |
10,508 | cloudfoundry/dropsonde | dropsonde.go | Initialize | func Initialize(destination string, origin ...string) error {
emitter, err := createDefaultEmitter(strings.Join(origin, originDelimiter), destination)
if err != nil {
DefaultEmitter = &NullEventEmitter{}
return err
}
DefaultEmitter = emitter
initialize()
return nil
} | go | func Initialize(destination string, origin ...string) error {
emitter, err := createDefaultEmitter(strings.Join(origin, originDelimiter), destination)
if err != nil {
DefaultEmitter = &NullEventEmitter{}
return err
}
DefaultEmitter = emitter
initialize()
return nil
} | [
"func",
"Initialize",
"(",
"destination",
"string",
",",
"origin",
"...",
"string",
")",
"error",
"{",
"emitter",
",",
"err",
":=",
"createDefaultEmitter",
"(",
"strings",
".",
"Join",
"(",
"origin",
",",
"originDelimiter",
")",
",",
"destination",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"DefaultEmitter",
"=",
"&",
"NullEventEmitter",
"{",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"DefaultEmitter",
"=",
"emitter",
"\n",
"initialize",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Initialize creates default emitters and instruments the default HTTP
// transport.
//
// The origin variable is required and specifies the
// source name for all metrics emitted by this process. If it is not set, the
// program will run normally but will not emit metrics.
//
// The destination variable sets the host and port to
// which metrics are sent. It is optional, and defaults to DefaultDestination. | [
"Initialize",
"creates",
"default",
"emitters",
"and",
"instruments",
"the",
"default",
"HTTP",
"transport",
".",
"The",
"origin",
"variable",
"is",
"required",
"and",
"specifies",
"the",
"source",
"name",
"for",
"all",
"metrics",
"emitted",
"by",
"this",
"process",
".",
"If",
"it",
"is",
"not",
"set",
"the",
"program",
"will",
"run",
"normally",
"but",
"will",
"not",
"emit",
"metrics",
".",
"The",
"destination",
"variable",
"sets",
"the",
"host",
"and",
"port",
"to",
"which",
"metrics",
"are",
"sent",
".",
"It",
"is",
"optional",
"and",
"defaults",
"to",
"DefaultDestination",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/dropsonde.go#L59-L70 |
10,509 | cloudfoundry/dropsonde | dropsonde.go | InstrumentedHandler | func InstrumentedHandler(handler http.Handler) http.Handler {
return instrumented_handler.InstrumentedHandler(handler, DefaultEmitter)
} | go | func InstrumentedHandler(handler http.Handler) http.Handler {
return instrumented_handler.InstrumentedHandler(handler, DefaultEmitter)
} | [
"func",
"InstrumentedHandler",
"(",
"handler",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"instrumented_handler",
".",
"InstrumentedHandler",
"(",
"handler",
",",
"DefaultEmitter",
")",
"\n",
"}"
] | // InstrumentedHandler returns a Handler pre-configured to emit HTTP server
// request metrics to AutowiredEmitter. | [
"InstrumentedHandler",
"returns",
"a",
"Handler",
"pre",
"-",
"configured",
"to",
"emit",
"HTTP",
"server",
"request",
"metrics",
"to",
"AutowiredEmitter",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/dropsonde.go#L86-L88 |
10,510 | cloudfoundry/dropsonde | dropsonde.go | InstrumentedRoundTripper | func InstrumentedRoundTripper(roundTripper http.RoundTripper) http.RoundTripper {
return instrumented_round_tripper.InstrumentedRoundTripper(roundTripper, DefaultEmitter)
} | go | func InstrumentedRoundTripper(roundTripper http.RoundTripper) http.RoundTripper {
return instrumented_round_tripper.InstrumentedRoundTripper(roundTripper, DefaultEmitter)
} | [
"func",
"InstrumentedRoundTripper",
"(",
"roundTripper",
"http",
".",
"RoundTripper",
")",
"http",
".",
"RoundTripper",
"{",
"return",
"instrumented_round_tripper",
".",
"InstrumentedRoundTripper",
"(",
"roundTripper",
",",
"DefaultEmitter",
")",
"\n",
"}"
] | // InstrumentedRoundTripper returns a RoundTripper pre-configured to emit
// HTTP client request metrics to AutowiredEmitter. | [
"InstrumentedRoundTripper",
"returns",
"a",
"RoundTripper",
"pre",
"-",
"configured",
"to",
"emit",
"HTTP",
"client",
"request",
"metrics",
"to",
"AutowiredEmitter",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/dropsonde.go#L92-L94 |
10,511 | cloudfoundry/dropsonde | envelopes/envelopes.go | SendEnvelope | func SendEnvelope(envelope *events.Envelope) error {
if envelopeSender == nil {
return nil
}
return envelopeSender.SendEnvelope(envelope)
} | go | func SendEnvelope(envelope *events.Envelope) error {
if envelopeSender == nil {
return nil
}
return envelopeSender.SendEnvelope(envelope)
} | [
"func",
"SendEnvelope",
"(",
"envelope",
"*",
"events",
".",
"Envelope",
")",
"error",
"{",
"if",
"envelopeSender",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"envelopeSender",
".",
"SendEnvelope",
"(",
"envelope",
")",
"\n",
"}"
] | // SendEnvelope sends the given Envelope. | [
"SendEnvelope",
"sends",
"the",
"given",
"Envelope",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/envelopes/envelopes.go#L29-L34 |
10,512 | cloudfoundry/dropsonde | log_sender/log_sender.go | SendAppLog | func (l *LogSender) SendAppLog(appID, message, sourceType, sourceInstance string) error {
metrics.BatchIncrementCounter("logSenderTotalMessagesRead")
return l.eventEmitter.Emit(makeLogMessage(appID, message, sourceType, sourceInstance, events.LogMessage_OUT))
} | go | func (l *LogSender) SendAppLog(appID, message, sourceType, sourceInstance string) error {
metrics.BatchIncrementCounter("logSenderTotalMessagesRead")
return l.eventEmitter.Emit(makeLogMessage(appID, message, sourceType, sourceInstance, events.LogMessage_OUT))
} | [
"func",
"(",
"l",
"*",
"LogSender",
")",
"SendAppLog",
"(",
"appID",
",",
"message",
",",
"sourceType",
",",
"sourceInstance",
"string",
")",
"error",
"{",
"metrics",
".",
"BatchIncrementCounter",
"(",
"\"",
"\"",
")",
"\n",
"return",
"l",
".",
"eventEmitter",
".",
"Emit",
"(",
"makeLogMessage",
"(",
"appID",
",",
"message",
",",
"sourceType",
",",
"sourceInstance",
",",
"events",
".",
"LogMessage_OUT",
")",
")",
"\n",
"}"
] | // SendAppLog sends a log message with the given appid and log message
// with a message type of std out.
// Returns an error if one occurs while sending the event. | [
"SendAppLog",
"sends",
"a",
"log",
"message",
"with",
"the",
"given",
"appid",
"and",
"log",
"message",
"with",
"a",
"message",
"type",
"of",
"std",
"out",
".",
"Returns",
"an",
"error",
"if",
"one",
"occurs",
"while",
"sending",
"the",
"event",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/log_sender/log_sender.go#L53-L56 |
10,513 | cloudfoundry/dropsonde | log_sender/log_sender.go | SendAppErrorLog | func (l *LogSender) SendAppErrorLog(appID, message, sourceType, sourceInstance string) error {
metrics.BatchIncrementCounter("logSenderTotalMessagesRead")
return l.eventEmitter.Emit(makeLogMessage(appID, message, sourceType, sourceInstance, events.LogMessage_ERR))
} | go | func (l *LogSender) SendAppErrorLog(appID, message, sourceType, sourceInstance string) error {
metrics.BatchIncrementCounter("logSenderTotalMessagesRead")
return l.eventEmitter.Emit(makeLogMessage(appID, message, sourceType, sourceInstance, events.LogMessage_ERR))
} | [
"func",
"(",
"l",
"*",
"LogSender",
")",
"SendAppErrorLog",
"(",
"appID",
",",
"message",
",",
"sourceType",
",",
"sourceInstance",
"string",
")",
"error",
"{",
"metrics",
".",
"BatchIncrementCounter",
"(",
"\"",
"\"",
")",
"\n",
"return",
"l",
".",
"eventEmitter",
".",
"Emit",
"(",
"makeLogMessage",
"(",
"appID",
",",
"message",
",",
"sourceType",
",",
"sourceInstance",
",",
"events",
".",
"LogMessage_ERR",
")",
")",
"\n",
"}"
] | // SendAppErrorLog sends a log error message with the given appid and log message
// with a message type of std err.
// Returns an error if one occurs while sending the event. | [
"SendAppErrorLog",
"sends",
"a",
"log",
"error",
"message",
"with",
"the",
"given",
"appid",
"and",
"log",
"message",
"with",
"a",
"message",
"type",
"of",
"std",
"err",
".",
"Returns",
"an",
"error",
"if",
"one",
"occurs",
"while",
"sending",
"the",
"event",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/log_sender/log_sender.go#L61-L64 |
10,514 | cloudfoundry/dropsonde | log_sender/log_sender.go | ScanErrorLogStream | func (l *LogSender) ScanErrorLogStream(appID, sourceType, sourceInstance string, reader io.Reader) {
l.scanLogStream(appID, sourceType, sourceInstance, l.SendAppErrorLog, reader)
} | go | func (l *LogSender) ScanErrorLogStream(appID, sourceType, sourceInstance string, reader io.Reader) {
l.scanLogStream(appID, sourceType, sourceInstance, l.SendAppErrorLog, reader)
} | [
"func",
"(",
"l",
"*",
"LogSender",
")",
"ScanErrorLogStream",
"(",
"appID",
",",
"sourceType",
",",
"sourceInstance",
"string",
",",
"reader",
"io",
".",
"Reader",
")",
"{",
"l",
".",
"scanLogStream",
"(",
"appID",
",",
"sourceType",
",",
"sourceInstance",
",",
"l",
".",
"SendAppErrorLog",
",",
"reader",
")",
"\n",
"}"
] | // ScanErrorLogStream sends a log error message with the given meta-data for each line from reader.
// Restarts on read errors and continues until EOF. | [
"ScanErrorLogStream",
"sends",
"a",
"log",
"error",
"message",
"with",
"the",
"given",
"meta",
"-",
"data",
"for",
"each",
"line",
"from",
"reader",
".",
"Restarts",
"on",
"read",
"errors",
"and",
"continues",
"until",
"EOF",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/log_sender/log_sender.go#L74-L76 |
10,515 | cloudfoundry/dropsonde | log_sender/log_sender.go | Send | func (c logChainer) Send() error {
if c.err != nil {
return c.err
}
metrics.BatchIncrementCounter("logSenderTotalMessagesRead")
c.envelope.Timestamp = proto.Int64(time.Now().UnixNano())
if c.envelope.LogMessage.Timestamp == nil {
c.envelope.LogMessage.Timestamp = proto.Int64(time.Now().UnixNano())
}
return c.emitter.EmitEnvelope(c.envelope)
} | go | func (c logChainer) Send() error {
if c.err != nil {
return c.err
}
metrics.BatchIncrementCounter("logSenderTotalMessagesRead")
c.envelope.Timestamp = proto.Int64(time.Now().UnixNano())
if c.envelope.LogMessage.Timestamp == nil {
c.envelope.LogMessage.Timestamp = proto.Int64(time.Now().UnixNano())
}
return c.emitter.EmitEnvelope(c.envelope)
} | [
"func",
"(",
"c",
"logChainer",
")",
"Send",
"(",
")",
"error",
"{",
"if",
"c",
".",
"err",
"!=",
"nil",
"{",
"return",
"c",
".",
"err",
"\n",
"}",
"\n\n",
"metrics",
".",
"BatchIncrementCounter",
"(",
"\"",
"\"",
")",
"\n\n",
"c",
".",
"envelope",
".",
"Timestamp",
"=",
"proto",
".",
"Int64",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n\n",
"if",
"c",
".",
"envelope",
".",
"LogMessage",
".",
"Timestamp",
"==",
"nil",
"{",
"c",
".",
"envelope",
".",
"LogMessage",
".",
"Timestamp",
"=",
"proto",
".",
"Int64",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"c",
".",
"emitter",
".",
"EmitEnvelope",
"(",
"c",
".",
"envelope",
")",
"\n",
"}"
] | // Send sends the log message with the envelope timestamp set to now and the
// log message timestamp set to now if none was provided by SetTimestamp. | [
"Send",
"sends",
"the",
"log",
"message",
"with",
"the",
"envelope",
"timestamp",
"set",
"to",
"now",
"and",
"the",
"log",
"message",
"timestamp",
"set",
"to",
"now",
"if",
"none",
"was",
"provided",
"by",
"SetTimestamp",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/log_sender/log_sender.go#L201-L214 |
10,516 | cloudfoundry/dropsonde | dropsonde_unmarshaller/dropsonde_unmarshaller_collection.go | NewDropsondeUnmarshallerCollection | func NewDropsondeUnmarshallerCollection(size int) *DropsondeUnmarshallerCollection {
var unmarshallers []*DropsondeUnmarshaller
for i := 0; i < size; i++ {
unmarshallers = append(unmarshallers, NewDropsondeUnmarshaller())
}
log.Printf("dropsondeUnmarshallerCollection: created %v unmarshallers", size)
return &DropsondeUnmarshallerCollection{
unmarshallers: unmarshallers,
}
} | go | func NewDropsondeUnmarshallerCollection(size int) *DropsondeUnmarshallerCollection {
var unmarshallers []*DropsondeUnmarshaller
for i := 0; i < size; i++ {
unmarshallers = append(unmarshallers, NewDropsondeUnmarshaller())
}
log.Printf("dropsondeUnmarshallerCollection: created %v unmarshallers", size)
return &DropsondeUnmarshallerCollection{
unmarshallers: unmarshallers,
}
} | [
"func",
"NewDropsondeUnmarshallerCollection",
"(",
"size",
"int",
")",
"*",
"DropsondeUnmarshallerCollection",
"{",
"var",
"unmarshallers",
"[",
"]",
"*",
"DropsondeUnmarshaller",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
"{",
"unmarshallers",
"=",
"append",
"(",
"unmarshallers",
",",
"NewDropsondeUnmarshaller",
"(",
")",
")",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"size",
")",
"\n\n",
"return",
"&",
"DropsondeUnmarshallerCollection",
"{",
"unmarshallers",
":",
"unmarshallers",
",",
"}",
"\n",
"}"
] | // NewDropsondeUnmarshallerCollection instantiates a DropsondeUnmarshallerCollection,
// creates the specified number of DropsondeUnmarshaller instances. | [
"NewDropsondeUnmarshallerCollection",
"instantiates",
"a",
"DropsondeUnmarshallerCollection",
"creates",
"the",
"specified",
"number",
"of",
"DropsondeUnmarshaller",
"instances",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/dropsonde_unmarshaller/dropsonde_unmarshaller_collection.go#L17-L28 |
10,517 | cloudfoundry/dropsonde | dropsonde_unmarshaller/dropsonde_unmarshaller_collection.go | Run | func (u *DropsondeUnmarshallerCollection) Run(inputChan <-chan []byte, outputChan chan<- *events.Envelope, waitGroup *sync.WaitGroup) {
for _, unmarshaller := range u.unmarshallers {
go func(um *DropsondeUnmarshaller) {
defer waitGroup.Done()
um.Run(inputChan, outputChan)
}(unmarshaller)
}
} | go | func (u *DropsondeUnmarshallerCollection) Run(inputChan <-chan []byte, outputChan chan<- *events.Envelope, waitGroup *sync.WaitGroup) {
for _, unmarshaller := range u.unmarshallers {
go func(um *DropsondeUnmarshaller) {
defer waitGroup.Done()
um.Run(inputChan, outputChan)
}(unmarshaller)
}
} | [
"func",
"(",
"u",
"*",
"DropsondeUnmarshallerCollection",
")",
"Run",
"(",
"inputChan",
"<-",
"chan",
"[",
"]",
"byte",
",",
"outputChan",
"chan",
"<-",
"*",
"events",
".",
"Envelope",
",",
"waitGroup",
"*",
"sync",
".",
"WaitGroup",
")",
"{",
"for",
"_",
",",
"unmarshaller",
":=",
"range",
"u",
".",
"unmarshallers",
"{",
"go",
"func",
"(",
"um",
"*",
"DropsondeUnmarshaller",
")",
"{",
"defer",
"waitGroup",
".",
"Done",
"(",
")",
"\n",
"um",
".",
"Run",
"(",
"inputChan",
",",
"outputChan",
")",
"\n",
"}",
"(",
"unmarshaller",
")",
"\n",
"}",
"\n",
"}"
] | // Run calls Run on each marshaller in its collection.
// This is done in separate go routines. | [
"Run",
"calls",
"Run",
"on",
"each",
"marshaller",
"in",
"its",
"collection",
".",
"This",
"is",
"done",
"in",
"separate",
"go",
"routines",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/dropsonde_unmarshaller/dropsonde_unmarshaller_collection.go#L37-L44 |
10,518 | cloudfoundry/dropsonde | envelope_sender/envelope_sender.go | SendEnvelope | func (ms *EnvelopeSender) SendEnvelope(envelope *events.Envelope) error {
return ms.emitter.EmitEnvelope(envelope)
} | go | func (ms *EnvelopeSender) SendEnvelope(envelope *events.Envelope) error {
return ms.emitter.EmitEnvelope(envelope)
} | [
"func",
"(",
"ms",
"*",
"EnvelopeSender",
")",
"SendEnvelope",
"(",
"envelope",
"*",
"events",
".",
"Envelope",
")",
"error",
"{",
"return",
"ms",
".",
"emitter",
".",
"EmitEnvelope",
"(",
"envelope",
")",
"\n",
"}"
] | // SendEnvelope sends the given envelope.
// Returns an error if one occurs while sending the envelope. | [
"SendEnvelope",
"sends",
"the",
"given",
"envelope",
".",
"Returns",
"an",
"error",
"if",
"one",
"occurs",
"while",
"sending",
"the",
"envelope",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/envelope_sender/envelope_sender.go#L21-L23 |
10,519 | cloudfoundry/dropsonde | metrics/metrics.go | Initialize | func Initialize(ms MetricSender, mb MetricBatcher) {
if metricBatcher != nil {
metricBatcher.Close()
}
metricSender = ms
metricBatcher = mb
} | go | func Initialize(ms MetricSender, mb MetricBatcher) {
if metricBatcher != nil {
metricBatcher.Close()
}
metricSender = ms
metricBatcher = mb
} | [
"func",
"Initialize",
"(",
"ms",
"MetricSender",
",",
"mb",
"MetricBatcher",
")",
"{",
"if",
"metricBatcher",
"!=",
"nil",
"{",
"metricBatcher",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"metricSender",
"=",
"ms",
"\n",
"metricBatcher",
"=",
"mb",
"\n",
"}"
] | // Initialize prepares the metrics package for use with the automatic Emitter. | [
"Initialize",
"prepares",
"the",
"metrics",
"package",
"for",
"use",
"with",
"the",
"automatic",
"Emitter",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/metrics/metrics.go#L58-L64 |
10,520 | cloudfoundry/dropsonde | metrics/metrics.go | IncrementCounter | func IncrementCounter(name string) error {
if metricSender == nil {
return nil
}
return metricSender.IncrementCounter(name)
} | go | func IncrementCounter(name string) error {
if metricSender == nil {
return nil
}
return metricSender.IncrementCounter(name)
} | [
"func",
"IncrementCounter",
"(",
"name",
"string",
")",
"error",
"{",
"if",
"metricSender",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"metricSender",
".",
"IncrementCounter",
"(",
"name",
")",
"\n",
"}"
] | // IncrementCounter sends an event to increment the named counter by one.
// Maintaining the value of the counter is the responsibility of the receiver of
// the event, not the process that includes this package. | [
"IncrementCounter",
"sends",
"an",
"event",
"to",
"increment",
"the",
"named",
"counter",
"by",
"one",
".",
"Maintaining",
"the",
"value",
"of",
"the",
"counter",
"is",
"the",
"responsibility",
"of",
"the",
"receiver",
"of",
"the",
"event",
"not",
"the",
"process",
"that",
"includes",
"this",
"package",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/metrics/metrics.go#L88-L93 |
10,521 | cloudfoundry/dropsonde | metrics/metrics.go | BatchAddCounter | func BatchAddCounter(name string, delta uint64) {
if metricBatcher == nil {
return
}
metricBatcher.BatchAddCounter(name, delta)
} | go | func BatchAddCounter(name string, delta uint64) {
if metricBatcher == nil {
return
}
metricBatcher.BatchAddCounter(name, delta)
} | [
"func",
"BatchAddCounter",
"(",
"name",
"string",
",",
"delta",
"uint64",
")",
"{",
"if",
"metricBatcher",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"metricBatcher",
".",
"BatchAddCounter",
"(",
"name",
",",
"delta",
")",
"\n",
"}"
] | // BatchAddCounter adds delta to a counter but, unlike AddCounter, does not emit a
// CounterEvent for each add; instead, the adds are batched and a single CounterEvent
// is sent after the timeout. | [
"BatchAddCounter",
"adds",
"delta",
"to",
"a",
"counter",
"but",
"unlike",
"AddCounter",
"does",
"not",
"emit",
"a",
"CounterEvent",
"for",
"each",
"add",
";",
"instead",
"the",
"adds",
"are",
"batched",
"and",
"a",
"single",
"CounterEvent",
"is",
"sent",
"after",
"the",
"timeout",
"."
] | a5c24343b09d7b811567b68cf18c7aa2a34a798a | https://github.com/cloudfoundry/dropsonde/blob/a5c24343b09d7b811567b68cf18c7aa2a34a798a/metrics/metrics.go#L118-L123 |
10,522 | leesper/go_rng | cauchy.go | Cauchy | func (crng CauchyGenerator) Cauchy(x0, gamma float64) float64 {
if !(gamma > 0.0) {
panic(fmt.Sprintf("Invalid parameter gamma: %.2f", gamma))
}
return crng.cauchy(x0, gamma)
} | go | func (crng CauchyGenerator) Cauchy(x0, gamma float64) float64 {
if !(gamma > 0.0) {
panic(fmt.Sprintf("Invalid parameter gamma: %.2f", gamma))
}
return crng.cauchy(x0, gamma)
} | [
"func",
"(",
"crng",
"CauchyGenerator",
")",
"Cauchy",
"(",
"x0",
",",
"gamma",
"float64",
")",
"float64",
"{",
"if",
"!",
"(",
"gamma",
">",
"0.0",
")",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"gamma",
")",
")",
"\n",
"}",
"\n",
"return",
"crng",
".",
"cauchy",
"(",
"x0",
",",
"gamma",
")",
"\n",
"}"
] | // Cauchy returns a random number of cauchy distribution | [
"Cauchy",
"returns",
"a",
"random",
"number",
"of",
"cauchy",
"distribution"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/cauchy.go#L23-L28 |
10,523 | leesper/go_rng | uniform.go | Int32 | func (ung UniformGenerator) Int32() int32 {
ung.mu.Lock()
defer ung.mu.Unlock()
return ung.rd.Int31()
} | go | func (ung UniformGenerator) Int32() int32 {
ung.mu.Lock()
defer ung.mu.Unlock()
return ung.rd.Int31()
} | [
"func",
"(",
"ung",
"UniformGenerator",
")",
"Int32",
"(",
")",
"int32",
"{",
"ung",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ung",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ung",
".",
"rd",
".",
"Int31",
"(",
")",
"\n",
"}"
] | // Int32 returns a random uint32 | [
"Int32",
"returns",
"a",
"random",
"uint32"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/uniform.go#L25-L29 |
10,524 | leesper/go_rng | uniform.go | Int64 | func (ung UniformGenerator) Int64() int64 {
ung.mu.Lock()
defer ung.mu.Unlock()
return ung.rd.Int63()
} | go | func (ung UniformGenerator) Int64() int64 {
ung.mu.Lock()
defer ung.mu.Unlock()
return ung.rd.Int63()
} | [
"func",
"(",
"ung",
"UniformGenerator",
")",
"Int64",
"(",
")",
"int64",
"{",
"ung",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ung",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ung",
".",
"rd",
".",
"Int63",
"(",
")",
"\n",
"}"
] | // Int64 returns a random uint64 | [
"Int64",
"returns",
"a",
"random",
"uint64"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/uniform.go#L32-L36 |
10,525 | leesper/go_rng | uniform.go | Int32n | func (ung UniformGenerator) Int32n(n int32) int32 {
if n <= 0 {
panic(fmt.Sprintf("Illegal parameter n: %d", n))
}
ung.mu.Lock()
defer ung.mu.Unlock()
return ung.rd.Int31n(n)
} | go | func (ung UniformGenerator) Int32n(n int32) int32 {
if n <= 0 {
panic(fmt.Sprintf("Illegal parameter n: %d", n))
}
ung.mu.Lock()
defer ung.mu.Unlock()
return ung.rd.Int31n(n)
} | [
"func",
"(",
"ung",
"UniformGenerator",
")",
"Int32n",
"(",
"n",
"int32",
")",
"int32",
"{",
"if",
"n",
"<=",
"0",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"n",
")",
")",
"\n",
"}",
"\n",
"ung",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ung",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ung",
".",
"rd",
".",
"Int31n",
"(",
"n",
")",
"\n",
"}"
] | // Int32n returns a random uint32 in [0, n) | [
"Int32n",
"returns",
"a",
"random",
"uint32",
"in",
"[",
"0",
"n",
")"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/uniform.go#L39-L46 |
10,526 | leesper/go_rng | uniform.go | Int64n | func (ung UniformGenerator) Int64n(n int64) int64 {
if n <= 0 {
panic(fmt.Sprintf("Illegal parameter n: %d", n))
}
ung.mu.Lock()
defer ung.mu.Unlock()
return ung.rd.Int63n(n)
} | go | func (ung UniformGenerator) Int64n(n int64) int64 {
if n <= 0 {
panic(fmt.Sprintf("Illegal parameter n: %d", n))
}
ung.mu.Lock()
defer ung.mu.Unlock()
return ung.rd.Int63n(n)
} | [
"func",
"(",
"ung",
"UniformGenerator",
")",
"Int64n",
"(",
"n",
"int64",
")",
"int64",
"{",
"if",
"n",
"<=",
"0",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"n",
")",
")",
"\n",
"}",
"\n",
"ung",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ung",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ung",
".",
"rd",
".",
"Int63n",
"(",
"n",
")",
"\n",
"}"
] | // Int64n returns a random uint64 in [0, n) | [
"Int64n",
"returns",
"a",
"random",
"uint64",
"in",
"[",
"0",
"n",
")"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/uniform.go#L49-L56 |
10,527 | leesper/go_rng | uniform.go | Int32Range | func (ung UniformGenerator) Int32Range(a, b int32) int32 {
if b <= a {
panic(fmt.Sprintf("Illegal parameter a, b: %d, %d", a, b))
}
if b-a > math.MaxInt32 {
panic(fmt.Sprintf("Illegal parameter a, b: %d, %d", a, b))
}
return a + ung.Int32n(b-a)
} | go | func (ung UniformGenerator) Int32Range(a, b int32) int32 {
if b <= a {
panic(fmt.Sprintf("Illegal parameter a, b: %d, %d", a, b))
}
if b-a > math.MaxInt32 {
panic(fmt.Sprintf("Illegal parameter a, b: %d, %d", a, b))
}
return a + ung.Int32n(b-a)
} | [
"func",
"(",
"ung",
"UniformGenerator",
")",
"Int32Range",
"(",
"a",
",",
"b",
"int32",
")",
"int32",
"{",
"if",
"b",
"<=",
"a",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"a",
",",
"b",
")",
")",
"\n",
"}",
"\n",
"if",
"b",
"-",
"a",
">",
"math",
".",
"MaxInt32",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"a",
",",
"b",
")",
")",
"\n",
"}",
"\n",
"return",
"a",
"+",
"ung",
".",
"Int32n",
"(",
"b",
"-",
"a",
")",
"\n",
"}"
] | // Int32Range returns a random uint32 in [a, b) | [
"Int32Range",
"returns",
"a",
"random",
"uint32",
"in",
"[",
"a",
"b",
")"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/uniform.go#L59-L67 |
10,528 | leesper/go_rng | uniform.go | Int64Range | func (ung UniformGenerator) Int64Range(a, b int64) int64 {
if b <= a {
panic(fmt.Sprintf("Illegal parameter a, b: %d, %d", a, b))
}
if b-a > math.MaxInt32 {
panic(fmt.Sprintf("Illegal parameter a, b: %d, %d", a, b))
}
return a + ung.Int64n(b-a)
} | go | func (ung UniformGenerator) Int64Range(a, b int64) int64 {
if b <= a {
panic(fmt.Sprintf("Illegal parameter a, b: %d, %d", a, b))
}
if b-a > math.MaxInt32 {
panic(fmt.Sprintf("Illegal parameter a, b: %d, %d", a, b))
}
return a + ung.Int64n(b-a)
} | [
"func",
"(",
"ung",
"UniformGenerator",
")",
"Int64Range",
"(",
"a",
",",
"b",
"int64",
")",
"int64",
"{",
"if",
"b",
"<=",
"a",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"a",
",",
"b",
")",
")",
"\n",
"}",
"\n",
"if",
"b",
"-",
"a",
">",
"math",
".",
"MaxInt32",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"a",
",",
"b",
")",
")",
"\n",
"}",
"\n",
"return",
"a",
"+",
"ung",
".",
"Int64n",
"(",
"b",
"-",
"a",
")",
"\n",
"}"
] | // Int64Range returns a random uint64 in [a, b) | [
"Int64Range",
"returns",
"a",
"random",
"uint64",
"in",
"[",
"a",
"b",
")"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/uniform.go#L70-L78 |
10,529 | leesper/go_rng | uniform.go | Float32 | func (ung UniformGenerator) Float32() float32 {
ung.mu.Lock()
defer ung.mu.Unlock()
return ung.rd.Float32()
} | go | func (ung UniformGenerator) Float32() float32 {
ung.mu.Lock()
defer ung.mu.Unlock()
return ung.rd.Float32()
} | [
"func",
"(",
"ung",
"UniformGenerator",
")",
"Float32",
"(",
")",
"float32",
"{",
"ung",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ung",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ung",
".",
"rd",
".",
"Float32",
"(",
")",
"\n",
"}"
] | // Float32 returns a random float32 in [0.0, 1.0) | [
"Float32",
"returns",
"a",
"random",
"float32",
"in",
"[",
"0",
".",
"0",
"1",
".",
"0",
")"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/uniform.go#L81-L85 |
10,530 | leesper/go_rng | uniform.go | Float64 | func (ung UniformGenerator) Float64() float64 {
ung.mu.Lock()
defer ung.mu.Unlock()
return ung.rd.Float64()
} | go | func (ung UniformGenerator) Float64() float64 {
ung.mu.Lock()
defer ung.mu.Unlock()
return ung.rd.Float64()
} | [
"func",
"(",
"ung",
"UniformGenerator",
")",
"Float64",
"(",
")",
"float64",
"{",
"ung",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"ung",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ung",
".",
"rd",
".",
"Float64",
"(",
")",
"\n",
"}"
] | // Float64 returns a random float64 in [0.0, 1.0) | [
"Float64",
"returns",
"a",
"random",
"float64",
"in",
"[",
"0",
".",
"0",
"1",
".",
"0",
")"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/uniform.go#L88-L92 |
10,531 | leesper/go_rng | uniform.go | Shuffle | func (ung UniformGenerator) Shuffle(arr []interface{}) {
N := len(arr)
for i := range arr {
r := int32(i) + ung.Int32n(int32(N-i))
arr[i], arr[r] = arr[r], arr[i]
}
} | go | func (ung UniformGenerator) Shuffle(arr []interface{}) {
N := len(arr)
for i := range arr {
r := int32(i) + ung.Int32n(int32(N-i))
arr[i], arr[r] = arr[r], arr[i]
}
} | [
"func",
"(",
"ung",
"UniformGenerator",
")",
"Shuffle",
"(",
"arr",
"[",
"]",
"interface",
"{",
"}",
")",
"{",
"N",
":=",
"len",
"(",
"arr",
")",
"\n",
"for",
"i",
":=",
"range",
"arr",
"{",
"r",
":=",
"int32",
"(",
"i",
")",
"+",
"ung",
".",
"Int32n",
"(",
"int32",
"(",
"N",
"-",
"i",
")",
")",
"\n",
"arr",
"[",
"i",
"]",
",",
"arr",
"[",
"r",
"]",
"=",
"arr",
"[",
"r",
"]",
",",
"arr",
"[",
"i",
"]",
"\n",
"}",
"\n",
"}"
] | // Shuffle rearrange the elements of an array in random order | [
"Shuffle",
"rearrange",
"the",
"elements",
"of",
"an",
"array",
"in",
"random",
"order"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/uniform.go#L121-L127 |
10,532 | leesper/go_rng | lognormal.go | Lognormal | func (lnng LognormalGenerator) Lognormal(mean, stddev float64) float64 {
return math.Exp(mean + stddev*lnng.gauss.StdGaussian())
} | go | func (lnng LognormalGenerator) Lognormal(mean, stddev float64) float64 {
return math.Exp(mean + stddev*lnng.gauss.StdGaussian())
} | [
"func",
"(",
"lnng",
"LognormalGenerator",
")",
"Lognormal",
"(",
"mean",
",",
"stddev",
"float64",
")",
"float64",
"{",
"return",
"math",
".",
"Exp",
"(",
"mean",
"+",
"stddev",
"*",
"lnng",
".",
"gauss",
".",
"StdGaussian",
"(",
")",
")",
"\n",
"}"
] | // Lognormal return a random number of lognormal distribution | [
"Lognormal",
"return",
"a",
"random",
"number",
"of",
"lognormal",
"distribution"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/lognormal.go#L22-L24 |
10,533 | leesper/go_rng | logistic.go | Logistic | func (lrng LogisticGenerator) Logistic(mu, s float64) float64 {
if !(s > 0.0) {
panic(fmt.Sprintf("Invalid parameter s: %.2f", s))
}
return lrng.logistic(mu, s)
} | go | func (lrng LogisticGenerator) Logistic(mu, s float64) float64 {
if !(s > 0.0) {
panic(fmt.Sprintf("Invalid parameter s: %.2f", s))
}
return lrng.logistic(mu, s)
} | [
"func",
"(",
"lrng",
"LogisticGenerator",
")",
"Logistic",
"(",
"mu",
",",
"s",
"float64",
")",
"float64",
"{",
"if",
"!",
"(",
"s",
">",
"0.0",
")",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"s",
")",
")",
"\n",
"}",
"\n",
"return",
"lrng",
".",
"logistic",
"(",
"mu",
",",
"s",
")",
"\n",
"}"
] | // Logistic returns a random number of logistic distribution | [
"Logistic",
"returns",
"a",
"random",
"number",
"of",
"logistic",
"distribution"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/logistic.go#L23-L28 |
10,534 | leesper/go_rng | bernoulli.go | Bernoulli_P | func (beng BernoulliGenerator) Bernoulli_P(p float64) bool {
if !(0.0 <= p && p <= 1.0) {
panic(fmt.Sprintf("Invalid probability: %.2f", p))
}
return beng.uniform.Float64() < p
} | go | func (beng BernoulliGenerator) Bernoulli_P(p float64) bool {
if !(0.0 <= p && p <= 1.0) {
panic(fmt.Sprintf("Invalid probability: %.2f", p))
}
return beng.uniform.Float64() < p
} | [
"func",
"(",
"beng",
"BernoulliGenerator",
")",
"Bernoulli_P",
"(",
"p",
"float64",
")",
"bool",
"{",
"if",
"!",
"(",
"0.0",
"<=",
"p",
"&&",
"p",
"<=",
"1.0",
")",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"p",
")",
")",
"\n",
"}",
"\n",
"return",
"beng",
".",
"uniform",
".",
"Float64",
"(",
")",
"<",
"p",
"\n",
"}"
] | // Bernoulli_P returns a bool, which is true with probablity p | [
"Bernoulli_P",
"returns",
"a",
"bool",
"which",
"is",
"true",
"with",
"probablity",
"p"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/bernoulli.go#L27-L32 |
10,535 | leesper/go_rng | poisson.go | Poisson | func (prng PoissonGenerator) Poisson(lambda float64) int64 {
if !(lambda > 0.0) {
panic(fmt.Sprintf("Invalid lambda: %.2f", lambda))
}
return prng.poisson(lambda)
} | go | func (prng PoissonGenerator) Poisson(lambda float64) int64 {
if !(lambda > 0.0) {
panic(fmt.Sprintf("Invalid lambda: %.2f", lambda))
}
return prng.poisson(lambda)
} | [
"func",
"(",
"prng",
"PoissonGenerator",
")",
"Poisson",
"(",
"lambda",
"float64",
")",
"int64",
"{",
"if",
"!",
"(",
"lambda",
">",
"0.0",
")",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"lambda",
")",
")",
"\n",
"}",
"\n",
"return",
"prng",
".",
"poisson",
"(",
"lambda",
")",
"\n",
"}"
] | // Poisson returns a random number of possion distribution | [
"Poisson",
"returns",
"a",
"random",
"number",
"of",
"possion",
"distribution"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/poisson.go#L23-L28 |
10,536 | leesper/go_rng | exponential.go | Exp | func (erng ExpGenerator) Exp(lambda float64) float64 {
if !(lambda > 0.0) {
panic(fmt.Sprintf("Invalid lambda: %.2f", lambda))
}
return erng.exp(lambda)
} | go | func (erng ExpGenerator) Exp(lambda float64) float64 {
if !(lambda > 0.0) {
panic(fmt.Sprintf("Invalid lambda: %.2f", lambda))
}
return erng.exp(lambda)
} | [
"func",
"(",
"erng",
"ExpGenerator",
")",
"Exp",
"(",
"lambda",
"float64",
")",
"float64",
"{",
"if",
"!",
"(",
"lambda",
">",
"0.0",
")",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"lambda",
")",
")",
"\n",
"}",
"\n",
"return",
"erng",
".",
"exp",
"(",
"lambda",
")",
"\n",
"}"
] | // Exp returns a random number of exponential distribution | [
"Exp",
"returns",
"a",
"random",
"number",
"of",
"exponential",
"distribution"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/exponential.go#L23-L28 |
10,537 | leesper/go_rng | gamma.go | gamma | func (grng GammaGenerator) gamma(alpha, beta float64) float64 {
var MAGIC_CONST float64 = 4 * math.Exp(-0.5) / math.Sqrt(2.0)
if alpha > 1.0 {
// Use R.C.H Cheng "The generation of Gamma variables with
// non-integral shape parameters", Applied Statistics, (1977), 26, No. 1, p71-74
ainv := math.Sqrt(2.0*alpha - 1.0)
bbb := alpha - math.Log(4.0)
ccc := alpha + ainv
for {
u1 := grng.uniform.Float64()
if !(1e-7 < u1 && u1 < .9999999) {
continue
}
u2 := 1.0 - grng.uniform.Float64()
v := math.Log(u1/(1.0-u1)) / ainv
x := alpha * math.Exp(v)
z := u1 * u1 * u2
r := bbb + ccc*v - x
if r+MAGIC_CONST-4.5*z >= 0.0 || r >= math.Log(z) {
return x * beta
}
}
} else if alpha == 1.0 {
u := grng.uniform.Float64()
for u <= 1e-7 {
u = grng.uniform.Float64()
}
return -math.Log(u) * beta
} else { // alpha between 0.0 and 1.0 (exclusive)
// Uses Algorithm of Statistical Computing - kennedy & Gentle
var x float64
for {
u := grng.uniform.Float64()
b := (math.E + alpha) / math.E
p := b * u
if p <= 1.0 {
x = math.Pow(p, 1.0/alpha)
} else {
x = -math.Log((b - p) / alpha)
}
u1 := grng.uniform.Float64()
if p > 1.0 {
if u1 <= math.Pow(x, alpha-1.0) {
break
}
} else if u1 <= math.Exp(-x) {
break
}
}
return x * beta
}
} | go | func (grng GammaGenerator) gamma(alpha, beta float64) float64 {
var MAGIC_CONST float64 = 4 * math.Exp(-0.5) / math.Sqrt(2.0)
if alpha > 1.0 {
// Use R.C.H Cheng "The generation of Gamma variables with
// non-integral shape parameters", Applied Statistics, (1977), 26, No. 1, p71-74
ainv := math.Sqrt(2.0*alpha - 1.0)
bbb := alpha - math.Log(4.0)
ccc := alpha + ainv
for {
u1 := grng.uniform.Float64()
if !(1e-7 < u1 && u1 < .9999999) {
continue
}
u2 := 1.0 - grng.uniform.Float64()
v := math.Log(u1/(1.0-u1)) / ainv
x := alpha * math.Exp(v)
z := u1 * u1 * u2
r := bbb + ccc*v - x
if r+MAGIC_CONST-4.5*z >= 0.0 || r >= math.Log(z) {
return x * beta
}
}
} else if alpha == 1.0 {
u := grng.uniform.Float64()
for u <= 1e-7 {
u = grng.uniform.Float64()
}
return -math.Log(u) * beta
} else { // alpha between 0.0 and 1.0 (exclusive)
// Uses Algorithm of Statistical Computing - kennedy & Gentle
var x float64
for {
u := grng.uniform.Float64()
b := (math.E + alpha) / math.E
p := b * u
if p <= 1.0 {
x = math.Pow(p, 1.0/alpha)
} else {
x = -math.Log((b - p) / alpha)
}
u1 := grng.uniform.Float64()
if p > 1.0 {
if u1 <= math.Pow(x, alpha-1.0) {
break
}
} else if u1 <= math.Exp(-x) {
break
}
}
return x * beta
}
} | [
"func",
"(",
"grng",
"GammaGenerator",
")",
"gamma",
"(",
"alpha",
",",
"beta",
"float64",
")",
"float64",
"{",
"var",
"MAGIC_CONST",
"float64",
"=",
"4",
"*",
"math",
".",
"Exp",
"(",
"-",
"0.5",
")",
"/",
"math",
".",
"Sqrt",
"(",
"2.0",
")",
"\n",
"if",
"alpha",
">",
"1.0",
"{",
"// Use R.C.H Cheng \"The generation of Gamma variables with",
"// non-integral shape parameters\", Applied Statistics, (1977), 26, No. 1, p71-74",
"ainv",
":=",
"math",
".",
"Sqrt",
"(",
"2.0",
"*",
"alpha",
"-",
"1.0",
")",
"\n",
"bbb",
":=",
"alpha",
"-",
"math",
".",
"Log",
"(",
"4.0",
")",
"\n",
"ccc",
":=",
"alpha",
"+",
"ainv",
"\n\n",
"for",
"{",
"u1",
":=",
"grng",
".",
"uniform",
".",
"Float64",
"(",
")",
"\n",
"if",
"!",
"(",
"1e-7",
"<",
"u1",
"&&",
"u1",
"<",
".9999999",
")",
"{",
"continue",
"\n",
"}",
"\n",
"u2",
":=",
"1.0",
"-",
"grng",
".",
"uniform",
".",
"Float64",
"(",
")",
"\n",
"v",
":=",
"math",
".",
"Log",
"(",
"u1",
"/",
"(",
"1.0",
"-",
"u1",
")",
")",
"/",
"ainv",
"\n",
"x",
":=",
"alpha",
"*",
"math",
".",
"Exp",
"(",
"v",
")",
"\n",
"z",
":=",
"u1",
"*",
"u1",
"*",
"u2",
"\n",
"r",
":=",
"bbb",
"+",
"ccc",
"*",
"v",
"-",
"x",
"\n",
"if",
"r",
"+",
"MAGIC_CONST",
"-",
"4.5",
"*",
"z",
">=",
"0.0",
"||",
"r",
">=",
"math",
".",
"Log",
"(",
"z",
")",
"{",
"return",
"x",
"*",
"beta",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"if",
"alpha",
"==",
"1.0",
"{",
"u",
":=",
"grng",
".",
"uniform",
".",
"Float64",
"(",
")",
"\n",
"for",
"u",
"<=",
"1e-7",
"{",
"u",
"=",
"grng",
".",
"uniform",
".",
"Float64",
"(",
")",
"\n",
"}",
"\n",
"return",
"-",
"math",
".",
"Log",
"(",
"u",
")",
"*",
"beta",
"\n",
"}",
"else",
"{",
"// alpha between 0.0 and 1.0 (exclusive)",
"// Uses Algorithm of Statistical Computing - kennedy & Gentle",
"var",
"x",
"float64",
"\n",
"for",
"{",
"u",
":=",
"grng",
".",
"uniform",
".",
"Float64",
"(",
")",
"\n",
"b",
":=",
"(",
"math",
".",
"E",
"+",
"alpha",
")",
"/",
"math",
".",
"E",
"\n",
"p",
":=",
"b",
"*",
"u",
"\n",
"if",
"p",
"<=",
"1.0",
"{",
"x",
"=",
"math",
".",
"Pow",
"(",
"p",
",",
"1.0",
"/",
"alpha",
")",
"\n",
"}",
"else",
"{",
"x",
"=",
"-",
"math",
".",
"Log",
"(",
"(",
"b",
"-",
"p",
")",
"/",
"alpha",
")",
"\n",
"}",
"\n",
"u1",
":=",
"grng",
".",
"uniform",
".",
"Float64",
"(",
")",
"\n",
"if",
"p",
">",
"1.0",
"{",
"if",
"u1",
"<=",
"math",
".",
"Pow",
"(",
"x",
",",
"alpha",
"-",
"1.0",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"else",
"if",
"u1",
"<=",
"math",
".",
"Exp",
"(",
"-",
"x",
")",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"x",
"*",
"beta",
"\n",
"}",
"\n",
"}"
] | // inspired by random.py | [
"inspired",
"by",
"random",
".",
"py"
] | 5344a9259b21627d94279721ab1f27eb029194e7 | https://github.com/leesper/go_rng/blob/5344a9259b21627d94279721ab1f27eb029194e7/gamma.go#L32-L85 |
10,538 | jaffee/commandeer | com.go | RunArgs | func RunArgs(flags Flagger, main interface{}, args []string) error {
err := Flags(flags, main)
if err != nil {
return fmt.Errorf("calling Flags: %v", err)
}
err = flags.Parse(args)
if err != nil {
return fmt.Errorf("parsing flags: %v", err)
}
if main, ok := main.(Runner); ok {
return main.Run()
}
return fmt.Errorf("called 'Run' with something which doesn't implement the 'Run() error' method.")
} | go | func RunArgs(flags Flagger, main interface{}, args []string) error {
err := Flags(flags, main)
if err != nil {
return fmt.Errorf("calling Flags: %v", err)
}
err = flags.Parse(args)
if err != nil {
return fmt.Errorf("parsing flags: %v", err)
}
if main, ok := main.(Runner); ok {
return main.Run()
}
return fmt.Errorf("called 'Run' with something which doesn't implement the 'Run() error' method.")
} | [
"func",
"RunArgs",
"(",
"flags",
"Flagger",
",",
"main",
"interface",
"{",
"}",
",",
"args",
"[",
"]",
"string",
")",
"error",
"{",
"err",
":=",
"Flags",
"(",
"flags",
",",
"main",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"flags",
".",
"Parse",
"(",
"args",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"main",
",",
"ok",
":=",
"main",
".",
"(",
"Runner",
")",
";",
"ok",
"{",
"return",
"main",
".",
"Run",
"(",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // RunArgs is similar to Run, but the caller must specify their own flag set and
// args to be parsed by that flag set. | [
"RunArgs",
"is",
"similar",
"to",
"Run",
"but",
"the",
"caller",
"must",
"specify",
"their",
"own",
"flag",
"set",
"and",
"args",
"to",
"be",
"parsed",
"by",
"that",
"flag",
"set",
"."
] | 3bd317f80cbd12c38e6591dc67fa4623adc4741b | https://github.com/jaffee/commandeer/blob/3bd317f80cbd12c38e6591dc67fa4623adc4741b/com.go#L68-L82 |
10,539 | jaffee/commandeer | com.go | flagName | func flagName(field reflect.StructField) (flagname string) {
var ok bool
if flagname, ok = field.Tag.Lookup("flag"); ok {
return flagname
}
if flagname, ok = field.Tag.Lookup("json"); ok {
return flagname
}
flagname = field.Name
return downcaseAndDash(flagname)
} | go | func flagName(field reflect.StructField) (flagname string) {
var ok bool
if flagname, ok = field.Tag.Lookup("flag"); ok {
return flagname
}
if flagname, ok = field.Tag.Lookup("json"); ok {
return flagname
}
flagname = field.Name
return downcaseAndDash(flagname)
} | [
"func",
"flagName",
"(",
"field",
"reflect",
".",
"StructField",
")",
"(",
"flagname",
"string",
")",
"{",
"var",
"ok",
"bool",
"\n",
"if",
"flagname",
",",
"ok",
"=",
"field",
".",
"Tag",
".",
"Lookup",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"return",
"flagname",
"\n",
"}",
"\n\n",
"if",
"flagname",
",",
"ok",
"=",
"field",
".",
"Tag",
".",
"Lookup",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"return",
"flagname",
"\n",
"}",
"\n",
"flagname",
"=",
"field",
".",
"Name",
"\n\n",
"return",
"downcaseAndDash",
"(",
"flagname",
")",
"\n",
"}"
] | // flagName finds a field's flag name. It first looks for a "flag" tag, then
// tries to use the "json" tag, and final falls back to using the name of the
// field after running it through "downcaseAndDash". | [
"flagName",
"finds",
"a",
"field",
"s",
"flag",
"name",
".",
"It",
"first",
"looks",
"for",
"a",
"flag",
"tag",
"then",
"tries",
"to",
"use",
"the",
"json",
"tag",
"and",
"final",
"falls",
"back",
"to",
"using",
"the",
"name",
"of",
"the",
"field",
"after",
"running",
"it",
"through",
"downcaseAndDash",
"."
] | 3bd317f80cbd12c38e6591dc67fa4623adc4741b | https://github.com/jaffee/commandeer/blob/3bd317f80cbd12c38e6591dc67fa4623adc4741b/com.go#L251-L263 |
10,540 | jaffee/commandeer | com.go | flagHelp | func flagHelp(field reflect.StructField) (flaghelp string) {
if flaghelp, ok := field.Tag.Lookup("help"); ok {
return flaghelp
}
return ""
} | go | func flagHelp(field reflect.StructField) (flaghelp string) {
if flaghelp, ok := field.Tag.Lookup("help"); ok {
return flaghelp
}
return ""
} | [
"func",
"flagHelp",
"(",
"field",
"reflect",
".",
"StructField",
")",
"(",
"flaghelp",
"string",
")",
"{",
"if",
"flaghelp",
",",
"ok",
":=",
"field",
".",
"Tag",
".",
"Lookup",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"return",
"flaghelp",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // flagHelp gets the help text from a field's tag or returns an empty string. | [
"flagHelp",
"gets",
"the",
"help",
"text",
"from",
"a",
"field",
"s",
"tag",
"or",
"returns",
"an",
"empty",
"string",
"."
] | 3bd317f80cbd12c38e6591dc67fa4623adc4741b | https://github.com/jaffee/commandeer/blob/3bd317f80cbd12c38e6591dc67fa4623adc4741b/com.go#L292-L297 |
10,541 | jaffee/commandeer | com.go | newFlagTracker | func newFlagTracker(flagger Flagger) *flagTracker {
fTr := &flagTracker{
flagger: flagger,
shorts: map[rune]struct{}{
'h': {}, // "h" is always used for help, so we can't set it.
},
}
fTr.pflagger, fTr.pflag = flagger.(PFlagger)
return fTr
} | go | func newFlagTracker(flagger Flagger) *flagTracker {
fTr := &flagTracker{
flagger: flagger,
shorts: map[rune]struct{}{
'h': {}, // "h" is always used for help, so we can't set it.
},
}
fTr.pflagger, fTr.pflag = flagger.(PFlagger)
return fTr
} | [
"func",
"newFlagTracker",
"(",
"flagger",
"Flagger",
")",
"*",
"flagTracker",
"{",
"fTr",
":=",
"&",
"flagTracker",
"{",
"flagger",
":",
"flagger",
",",
"shorts",
":",
"map",
"[",
"rune",
"]",
"struct",
"{",
"}",
"{",
"'h'",
":",
"{",
"}",
",",
"// \"h\" is always used for help, so we can't set it.",
"}",
",",
"}",
"\n",
"fTr",
".",
"pflagger",
",",
"fTr",
".",
"pflag",
"=",
"flagger",
".",
"(",
"PFlagger",
")",
"\n",
"return",
"fTr",
"\n",
"}"
] | // newFlagTracker sets up a flagTracker based on a flagger. | [
"newFlagTracker",
"sets",
"up",
"a",
"flagTracker",
"based",
"on",
"a",
"flagger",
"."
] | 3bd317f80cbd12c38e6591dc67fa4623adc4741b | https://github.com/jaffee/commandeer/blob/3bd317f80cbd12c38e6591dc67fa4623adc4741b/com.go#L309-L318 |
10,542 | jaffee/commandeer | com.go | short | func (fTr *flagTracker) short(field reflect.StructField, flagName string) (letter string, err error) {
if short, ok := field.Tag.Lookup("short"); ok {
if short == "" {
return "", nil // explicitly set to no shorthand
}
runeVal, width := utf8.DecodeRuneInString(short)
if runeVal == utf8.RuneError || width > 1 {
return "", fmt.Errorf("'%s' is not a valid single ascii character.", short)
}
if _, ok := fTr.shorts[runeVal]; ok {
return "", fmt.Errorf("'%s' has already been used.", short)
}
fTr.shorts[runeVal] = struct{}{}
return short, nil
}
for _, chr := range flagName {
if _, ok := fTr.shorts[chr]; ok {
continue
}
// TODO if the lowercase version of first letter is taken, try upper case and vice versa
if unicode.IsLetter(chr) {
fTr.shorts[chr] = struct{}{}
return string(chr), nil
}
}
return "", nil // no shorthand char available, but that's ok
} | go | func (fTr *flagTracker) short(field reflect.StructField, flagName string) (letter string, err error) {
if short, ok := field.Tag.Lookup("short"); ok {
if short == "" {
return "", nil // explicitly set to no shorthand
}
runeVal, width := utf8.DecodeRuneInString(short)
if runeVal == utf8.RuneError || width > 1 {
return "", fmt.Errorf("'%s' is not a valid single ascii character.", short)
}
if _, ok := fTr.shorts[runeVal]; ok {
return "", fmt.Errorf("'%s' has already been used.", short)
}
fTr.shorts[runeVal] = struct{}{}
return short, nil
}
for _, chr := range flagName {
if _, ok := fTr.shorts[chr]; ok {
continue
}
// TODO if the lowercase version of first letter is taken, try upper case and vice versa
if unicode.IsLetter(chr) {
fTr.shorts[chr] = struct{}{}
return string(chr), nil
}
}
return "", nil // no shorthand char available, but that's ok
} | [
"func",
"(",
"fTr",
"*",
"flagTracker",
")",
"short",
"(",
"field",
"reflect",
".",
"StructField",
",",
"flagName",
"string",
")",
"(",
"letter",
"string",
",",
"err",
"error",
")",
"{",
"if",
"short",
",",
"ok",
":=",
"field",
".",
"Tag",
".",
"Lookup",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"if",
"short",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"nil",
"// explicitly set to no shorthand",
"\n",
"}",
"\n",
"runeVal",
",",
"width",
":=",
"utf8",
".",
"DecodeRuneInString",
"(",
"short",
")",
"\n",
"if",
"runeVal",
"==",
"utf8",
".",
"RuneError",
"||",
"width",
">",
"1",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"short",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"fTr",
".",
"shorts",
"[",
"runeVal",
"]",
";",
"ok",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"short",
")",
"\n",
"}",
"\n",
"fTr",
".",
"shorts",
"[",
"runeVal",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"return",
"short",
",",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"chr",
":=",
"range",
"flagName",
"{",
"if",
"_",
",",
"ok",
":=",
"fTr",
".",
"shorts",
"[",
"chr",
"]",
";",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"// TODO if the lowercase version of first letter is taken, try upper case and vice versa",
"if",
"unicode",
".",
"IsLetter",
"(",
"chr",
")",
"{",
"fTr",
".",
"shorts",
"[",
"chr",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"return",
"string",
"(",
"chr",
")",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"nil",
"// no shorthand char available, but that's ok",
"\n",
"}"
] | // short gets the shorthand for a flag. flagName is the non-prefixed name
// returned by flagName. | [
"short",
"gets",
"the",
"shorthand",
"for",
"a",
"flag",
".",
"flagName",
"is",
"the",
"non",
"-",
"prefixed",
"name",
"returned",
"by",
"flagName",
"."
] | 3bd317f80cbd12c38e6591dc67fa4623adc4741b | https://github.com/jaffee/commandeer/blob/3bd317f80cbd12c38e6591dc67fa4623adc4741b/com.go#L322-L348 |
10,543 | jaffee/commandeer | examples/myapp/myapp.go | Run | func (m *Main) Run() error {
if m.Num < 2 || m.Vehicle == "" {
return fmt.Errorf("Need more gophers and/or vehicles.")
}
fmt.Printf("%d gophers stole my %s!\n", m.Num, m.Vehicle)
return nil
} | go | func (m *Main) Run() error {
if m.Num < 2 || m.Vehicle == "" {
return fmt.Errorf("Need more gophers and/or vehicles.")
}
fmt.Printf("%d gophers stole my %s!\n", m.Num, m.Vehicle)
return nil
} | [
"func",
"(",
"m",
"*",
"Main",
")",
"Run",
"(",
")",
"error",
"{",
"if",
"m",
".",
"Num",
"<",
"2",
"||",
"m",
".",
"Vehicle",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"m",
".",
"Num",
",",
"m",
".",
"Vehicle",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Run implements the Runner interface so that commandeer.Run can be used with
// Main. | [
"Run",
"implements",
"the",
"Runner",
"interface",
"so",
"that",
"commandeer",
".",
"Run",
"can",
"be",
"used",
"with",
"Main",
"."
] | 3bd317f80cbd12c38e6591dc67fa4623adc4741b | https://github.com/jaffee/commandeer/blob/3bd317f80cbd12c38e6591dc67fa4623adc4741b/examples/myapp/myapp.go#L18-L24 |
10,544 | Azure/azure-amqp-common-go | persist/file.go | NewFilePersister | func NewFilePersister(directory string) (*FilePersister, error) {
err := os.MkdirAll(directory, 0777)
return &FilePersister{
directory: directory,
}, err
} | go | func NewFilePersister(directory string) (*FilePersister, error) {
err := os.MkdirAll(directory, 0777)
return &FilePersister{
directory: directory,
}, err
} | [
"func",
"NewFilePersister",
"(",
"directory",
"string",
")",
"(",
"*",
"FilePersister",
",",
"error",
")",
"{",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"directory",
",",
"0777",
")",
"\n",
"return",
"&",
"FilePersister",
"{",
"directory",
":",
"directory",
",",
"}",
",",
"err",
"\n",
"}"
] | // NewFilePersister creates a FilePersister for saving to a given directory | [
"NewFilePersister",
"creates",
"a",
"FilePersister",
"for",
"saving",
"to",
"a",
"given",
"directory"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/persist/file.go#L44-L49 |
10,545 | Azure/azure-amqp-common-go | persist/checkpoint.go | NewCheckpoint | func NewCheckpoint(offset string, sequence int64, enqueueTime time.Time) Checkpoint {
return Checkpoint{
Offset: offset,
SequenceNumber: sequence,
EnqueueTime: enqueueTime,
}
} | go | func NewCheckpoint(offset string, sequence int64, enqueueTime time.Time) Checkpoint {
return Checkpoint{
Offset: offset,
SequenceNumber: sequence,
EnqueueTime: enqueueTime,
}
} | [
"func",
"NewCheckpoint",
"(",
"offset",
"string",
",",
"sequence",
"int64",
",",
"enqueueTime",
"time",
".",
"Time",
")",
"Checkpoint",
"{",
"return",
"Checkpoint",
"{",
"Offset",
":",
"offset",
",",
"SequenceNumber",
":",
"sequence",
",",
"EnqueueTime",
":",
"enqueueTime",
",",
"}",
"\n",
"}"
] | // NewCheckpoint contains the information needed to checkpoint Event Hub progress | [
"NewCheckpoint",
"contains",
"the",
"information",
"needed",
"to",
"checkpoint",
"Event",
"Hub",
"progress"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/persist/checkpoint.go#L63-L69 |
10,546 | Azure/azure-amqp-common-go | internal/tracing/tracing.go | StartSpanFromContext | func StartSpanFromContext(ctx context.Context, operationName string, opts ...trace.StartOption) (*trace.Span, context.Context) {
ctx, span := trace.StartSpan(ctx, operationName, opts...)
ApplyComponentInfo(span)
return span, ctx
} | go | func StartSpanFromContext(ctx context.Context, operationName string, opts ...trace.StartOption) (*trace.Span, context.Context) {
ctx, span := trace.StartSpan(ctx, operationName, opts...)
ApplyComponentInfo(span)
return span, ctx
} | [
"func",
"StartSpanFromContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"operationName",
"string",
",",
"opts",
"...",
"trace",
".",
"StartOption",
")",
"(",
"*",
"trace",
".",
"Span",
",",
"context",
".",
"Context",
")",
"{",
"ctx",
",",
"span",
":=",
"trace",
".",
"StartSpan",
"(",
"ctx",
",",
"operationName",
",",
"opts",
"...",
")",
"\n",
"ApplyComponentInfo",
"(",
"span",
")",
"\n",
"return",
"span",
",",
"ctx",
"\n",
"}"
] | // StartSpanFromContext starts a span given a context and applies common library information | [
"StartSpanFromContext",
"starts",
"a",
"span",
"given",
"a",
"context",
"and",
"applies",
"common",
"library",
"information"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/internal/tracing/tracing.go#L12-L16 |
10,547 | Azure/azure-amqp-common-go | internal/tracing/tracing.go | ApplyComponentInfo | func ApplyComponentInfo(span *trace.Span) {
span.AddAttributes(
trace.StringAttribute("component", "github.com/Azure/azure-amqp-common-go"),
trace.StringAttribute("version", common.Version))
applyNetworkInfo(span)
} | go | func ApplyComponentInfo(span *trace.Span) {
span.AddAttributes(
trace.StringAttribute("component", "github.com/Azure/azure-amqp-common-go"),
trace.StringAttribute("version", common.Version))
applyNetworkInfo(span)
} | [
"func",
"ApplyComponentInfo",
"(",
"span",
"*",
"trace",
".",
"Span",
")",
"{",
"span",
".",
"AddAttributes",
"(",
"trace",
".",
"StringAttribute",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"trace",
".",
"StringAttribute",
"(",
"\"",
"\"",
",",
"common",
".",
"Version",
")",
")",
"\n",
"applyNetworkInfo",
"(",
"span",
")",
"\n",
"}"
] | // ApplyComponentInfo applies eventhub library and network info to the span | [
"ApplyComponentInfo",
"applies",
"eventhub",
"library",
"and",
"network",
"info",
"to",
"the",
"span"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/internal/tracing/tracing.go#L19-L24 |
10,548 | Azure/azure-amqp-common-go | sas/sas.go | NewTokenProvider | func NewTokenProvider(opts ...TokenProviderOption) (*TokenProvider, error) {
provider := new(TokenProvider)
for _, opt := range opts {
err := opt(provider)
if err != nil {
return nil, err
}
}
return provider, nil
} | go | func NewTokenProvider(opts ...TokenProviderOption) (*TokenProvider, error) {
provider := new(TokenProvider)
for _, opt := range opts {
err := opt(provider)
if err != nil {
return nil, err
}
}
return provider, nil
} | [
"func",
"NewTokenProvider",
"(",
"opts",
"...",
"TokenProviderOption",
")",
"(",
"*",
"TokenProvider",
",",
"error",
")",
"{",
"provider",
":=",
"new",
"(",
"TokenProvider",
")",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"err",
":=",
"opt",
"(",
"provider",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"provider",
",",
"nil",
"\n",
"}"
] | // NewTokenProvider builds a SAS claims-based security token provider | [
"NewTokenProvider",
"builds",
"a",
"SAS",
"claims",
"-",
"based",
"security",
"token",
"provider"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/sas/sas.go#L105-L114 |
10,549 | Azure/azure-amqp-common-go | sas/sas.go | GetToken | func (t *TokenProvider) GetToken(audience string) (*auth.Token, error) {
signature, expiry := t.signer.SignWithDuration(audience, 2*time.Hour)
return auth.NewToken(auth.CBSTokenTypeSAS, signature, expiry), nil
} | go | func (t *TokenProvider) GetToken(audience string) (*auth.Token, error) {
signature, expiry := t.signer.SignWithDuration(audience, 2*time.Hour)
return auth.NewToken(auth.CBSTokenTypeSAS, signature, expiry), nil
} | [
"func",
"(",
"t",
"*",
"TokenProvider",
")",
"GetToken",
"(",
"audience",
"string",
")",
"(",
"*",
"auth",
".",
"Token",
",",
"error",
")",
"{",
"signature",
",",
"expiry",
":=",
"t",
".",
"signer",
".",
"SignWithDuration",
"(",
"audience",
",",
"2",
"*",
"time",
".",
"Hour",
")",
"\n",
"return",
"auth",
".",
"NewToken",
"(",
"auth",
".",
"CBSTokenTypeSAS",
",",
"signature",
",",
"expiry",
")",
",",
"nil",
"\n",
"}"
] | // GetToken gets a CBS SAS token | [
"GetToken",
"gets",
"a",
"CBS",
"SAS",
"token"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/sas/sas.go#L117-L120 |
10,550 | Azure/azure-amqp-common-go | sas/sas.go | NewSigner | func NewSigner(keyName, key string) *Signer {
return &Signer{
KeyName: keyName,
Key: key,
}
} | go | func NewSigner(keyName, key string) *Signer {
return &Signer{
KeyName: keyName,
Key: key,
}
} | [
"func",
"NewSigner",
"(",
"keyName",
",",
"key",
"string",
")",
"*",
"Signer",
"{",
"return",
"&",
"Signer",
"{",
"KeyName",
":",
"keyName",
",",
"Key",
":",
"key",
",",
"}",
"\n",
"}"
] | // NewSigner builds a new SAS signer for use in generation Service Bus and Event Hub SAS tokens | [
"NewSigner",
"builds",
"a",
"new",
"SAS",
"signer",
"for",
"use",
"in",
"generation",
"Service",
"Bus",
"and",
"Event",
"Hub",
"SAS",
"tokens"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/sas/sas.go#L123-L128 |
10,551 | Azure/azure-amqp-common-go | sas/sas.go | SignWithDuration | func (s *Signer) SignWithDuration(uri string, interval time.Duration) (signature, expiry string) {
expiry = signatureExpiry(time.Now().UTC(), interval)
return s.SignWithExpiry(uri, expiry), expiry
} | go | func (s *Signer) SignWithDuration(uri string, interval time.Duration) (signature, expiry string) {
expiry = signatureExpiry(time.Now().UTC(), interval)
return s.SignWithExpiry(uri, expiry), expiry
} | [
"func",
"(",
"s",
"*",
"Signer",
")",
"SignWithDuration",
"(",
"uri",
"string",
",",
"interval",
"time",
".",
"Duration",
")",
"(",
"signature",
",",
"expiry",
"string",
")",
"{",
"expiry",
"=",
"signatureExpiry",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
",",
"interval",
")",
"\n",
"return",
"s",
".",
"SignWithExpiry",
"(",
"uri",
",",
"expiry",
")",
",",
"expiry",
"\n",
"}"
] | // SignWithDuration signs a given for a period of time from now | [
"SignWithDuration",
"signs",
"a",
"given",
"for",
"a",
"period",
"of",
"time",
"from",
"now"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/sas/sas.go#L131-L134 |
10,552 | Azure/azure-amqp-common-go | sas/sas.go | SignWithExpiry | func (s *Signer) SignWithExpiry(uri, expiry string) string {
audience := strings.ToLower(url.QueryEscape(uri))
sts := stringToSign(audience, expiry)
sig := s.signString(sts)
return fmt.Sprintf("SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s", audience, sig, expiry, s.KeyName)
} | go | func (s *Signer) SignWithExpiry(uri, expiry string) string {
audience := strings.ToLower(url.QueryEscape(uri))
sts := stringToSign(audience, expiry)
sig := s.signString(sts)
return fmt.Sprintf("SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s", audience, sig, expiry, s.KeyName)
} | [
"func",
"(",
"s",
"*",
"Signer",
")",
"SignWithExpiry",
"(",
"uri",
",",
"expiry",
"string",
")",
"string",
"{",
"audience",
":=",
"strings",
".",
"ToLower",
"(",
"url",
".",
"QueryEscape",
"(",
"uri",
")",
")",
"\n",
"sts",
":=",
"stringToSign",
"(",
"audience",
",",
"expiry",
")",
"\n",
"sig",
":=",
"s",
".",
"signString",
"(",
"sts",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"audience",
",",
"sig",
",",
"expiry",
",",
"s",
".",
"KeyName",
")",
"\n",
"}"
] | // SignWithExpiry signs a given uri with a given expiry string | [
"SignWithExpiry",
"signs",
"a",
"given",
"uri",
"with",
"a",
"given",
"expiry",
"string"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/sas/sas.go#L137-L142 |
10,553 | Azure/azure-amqp-common-go | log/logger.go | For | func For(ctx context.Context) Logger {
if span := trace.FromContext(ctx); span != nil {
return &spanLogger{
span: span,
}
}
return new(nopLogger)
} | go | func For(ctx context.Context) Logger {
if span := trace.FromContext(ctx); span != nil {
return &spanLogger{
span: span,
}
}
return new(nopLogger)
} | [
"func",
"For",
"(",
"ctx",
"context",
".",
"Context",
")",
"Logger",
"{",
"if",
"span",
":=",
"trace",
".",
"FromContext",
"(",
"ctx",
")",
";",
"span",
"!=",
"nil",
"{",
"return",
"&",
"spanLogger",
"{",
"span",
":",
"span",
",",
"}",
"\n",
"}",
"\n",
"return",
"new",
"(",
"nopLogger",
")",
"\n",
"}"
] | // For will return a logger for a given context | [
"For",
"will",
"return",
"a",
"logger",
"for",
"a",
"given",
"context"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/log/logger.go#L26-L33 |
10,554 | Azure/azure-amqp-common-go | retry.go | Retry | func Retry(times int, delay time.Duration, action func() (interface{}, error)) (interface{}, error) {
var lastErr error
for i := 0; i < times; i++ {
item, err := action()
if err != nil {
if retryable, ok := err.(Retryable); ok {
lastErr = retryable
time.Sleep(delay)
continue
} else {
return nil, err
}
}
return item, nil
}
return nil, lastErr
} | go | func Retry(times int, delay time.Duration, action func() (interface{}, error)) (interface{}, error) {
var lastErr error
for i := 0; i < times; i++ {
item, err := action()
if err != nil {
if retryable, ok := err.(Retryable); ok {
lastErr = retryable
time.Sleep(delay)
continue
} else {
return nil, err
}
}
return item, nil
}
return nil, lastErr
} | [
"func",
"Retry",
"(",
"times",
"int",
",",
"delay",
"time",
".",
"Duration",
",",
"action",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"var",
"lastErr",
"error",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"times",
";",
"i",
"++",
"{",
"item",
",",
"err",
":=",
"action",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"retryable",
",",
"ok",
":=",
"err",
".",
"(",
"Retryable",
")",
";",
"ok",
"{",
"lastErr",
"=",
"retryable",
"\n",
"time",
".",
"Sleep",
"(",
"delay",
")",
"\n",
"continue",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"item",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"lastErr",
"\n",
"}"
] | // Retry will attempt to retry an action a number of times if the action returns a retryable error | [
"Retry",
"will",
"attempt",
"to",
"retry",
"an",
"action",
"a",
"number",
"of",
"times",
"if",
"the",
"action",
"returns",
"a",
"retryable",
"error"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/retry.go#L38-L54 |
10,555 | Azure/azure-amqp-common-go | conn/conn.go | newParsedConnection | func newParsedConnection(namespace, suffix, hubName, keyName, key string) *ParsedConn {
return &ParsedConn{
Host: "amqps://" + namespace + "." + suffix,
Suffix: suffix,
Namespace: namespace,
KeyName: keyName,
Key: key,
HubName: hubName,
}
} | go | func newParsedConnection(namespace, suffix, hubName, keyName, key string) *ParsedConn {
return &ParsedConn{
Host: "amqps://" + namespace + "." + suffix,
Suffix: suffix,
Namespace: namespace,
KeyName: keyName,
Key: key,
HubName: hubName,
}
} | [
"func",
"newParsedConnection",
"(",
"namespace",
",",
"suffix",
",",
"hubName",
",",
"keyName",
",",
"key",
"string",
")",
"*",
"ParsedConn",
"{",
"return",
"&",
"ParsedConn",
"{",
"Host",
":",
"\"",
"\"",
"+",
"namespace",
"+",
"\"",
"\"",
"+",
"suffix",
",",
"Suffix",
":",
"suffix",
",",
"Namespace",
":",
"namespace",
",",
"KeyName",
":",
"keyName",
",",
"Key",
":",
"key",
",",
"HubName",
":",
"hubName",
",",
"}",
"\n",
"}"
] | // newParsedConnection is a constructor for a parsedConn and verifies each of the inputs is non-null. | [
"newParsedConnection",
"is",
"a",
"constructor",
"for",
"a",
"parsedConn",
"and",
"verifies",
"each",
"of",
"the",
"inputs",
"is",
"non",
"-",
"null",
"."
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/conn/conn.go#L52-L61 |
10,556 | Azure/azure-amqp-common-go | conn/conn.go | ParsedConnectionFromStr | func ParsedConnectionFromStr(connStr string) (*ParsedConn, error) {
var namespace, suffix, hubName, keyName, secret string
splits := strings.Split(connStr, ";")
for _, split := range splits {
keyAndValue := strings.Split(split, "=")
if len(keyAndValue) < 2 {
return nil, errors.New("failed parsing connection string due to unmatched key value separated by '='")
}
// if a key value pair has `=` in the value, recombine them
key := keyAndValue[0]
value := strings.Join(keyAndValue[1:], "=")
switch {
case strings.EqualFold(endpointKey, key):
u, err := url.Parse(value)
if err != nil {
return nil, errors.New("failed parsing connection string due to an incorrectly formatted Endpoint value")
}
hostSplits := strings.Split(u.Host, ".")
if len(hostSplits) < 2 {
return nil, errors.New("failed parsing connection string due to Endpoint value not containing a URL with a namespace and a suffix")
}
namespace = hostSplits[0]
suffix = strings.Join(hostSplits[1:], ".")
case strings.EqualFold(sharedAccessKeyNameKey, key):
keyName = value
case strings.EqualFold(sharedAccessKeyKey, key):
secret = value
case strings.EqualFold(entityPathKey, key):
hubName = value
}
}
parsed := newParsedConnection(namespace, suffix, hubName, keyName, secret)
if namespace == "" {
return parsed, fmt.Errorf("key %q must not be empty", endpointKey)
}
if keyName == "" {
return parsed, fmt.Errorf("key %q must not be empty", sharedAccessKeyNameKey)
}
if secret == "" {
return parsed, fmt.Errorf("key %q must not be empty", sharedAccessKeyKey)
}
return parsed, nil
} | go | func ParsedConnectionFromStr(connStr string) (*ParsedConn, error) {
var namespace, suffix, hubName, keyName, secret string
splits := strings.Split(connStr, ";")
for _, split := range splits {
keyAndValue := strings.Split(split, "=")
if len(keyAndValue) < 2 {
return nil, errors.New("failed parsing connection string due to unmatched key value separated by '='")
}
// if a key value pair has `=` in the value, recombine them
key := keyAndValue[0]
value := strings.Join(keyAndValue[1:], "=")
switch {
case strings.EqualFold(endpointKey, key):
u, err := url.Parse(value)
if err != nil {
return nil, errors.New("failed parsing connection string due to an incorrectly formatted Endpoint value")
}
hostSplits := strings.Split(u.Host, ".")
if len(hostSplits) < 2 {
return nil, errors.New("failed parsing connection string due to Endpoint value not containing a URL with a namespace and a suffix")
}
namespace = hostSplits[0]
suffix = strings.Join(hostSplits[1:], ".")
case strings.EqualFold(sharedAccessKeyNameKey, key):
keyName = value
case strings.EqualFold(sharedAccessKeyKey, key):
secret = value
case strings.EqualFold(entityPathKey, key):
hubName = value
}
}
parsed := newParsedConnection(namespace, suffix, hubName, keyName, secret)
if namespace == "" {
return parsed, fmt.Errorf("key %q must not be empty", endpointKey)
}
if keyName == "" {
return parsed, fmt.Errorf("key %q must not be empty", sharedAccessKeyNameKey)
}
if secret == "" {
return parsed, fmt.Errorf("key %q must not be empty", sharedAccessKeyKey)
}
return parsed, nil
} | [
"func",
"ParsedConnectionFromStr",
"(",
"connStr",
"string",
")",
"(",
"*",
"ParsedConn",
",",
"error",
")",
"{",
"var",
"namespace",
",",
"suffix",
",",
"hubName",
",",
"keyName",
",",
"secret",
"string",
"\n",
"splits",
":=",
"strings",
".",
"Split",
"(",
"connStr",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"split",
":=",
"range",
"splits",
"{",
"keyAndValue",
":=",
"strings",
".",
"Split",
"(",
"split",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"keyAndValue",
")",
"<",
"2",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// if a key value pair has `=` in the value, recombine them",
"key",
":=",
"keyAndValue",
"[",
"0",
"]",
"\n",
"value",
":=",
"strings",
".",
"Join",
"(",
"keyAndValue",
"[",
"1",
":",
"]",
",",
"\"",
"\"",
")",
"\n",
"switch",
"{",
"case",
"strings",
".",
"EqualFold",
"(",
"endpointKey",
",",
"key",
")",
":",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"hostSplits",
":=",
"strings",
".",
"Split",
"(",
"u",
".",
"Host",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"hostSplits",
")",
"<",
"2",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"namespace",
"=",
"hostSplits",
"[",
"0",
"]",
"\n",
"suffix",
"=",
"strings",
".",
"Join",
"(",
"hostSplits",
"[",
"1",
":",
"]",
",",
"\"",
"\"",
")",
"\n",
"case",
"strings",
".",
"EqualFold",
"(",
"sharedAccessKeyNameKey",
",",
"key",
")",
":",
"keyName",
"=",
"value",
"\n",
"case",
"strings",
".",
"EqualFold",
"(",
"sharedAccessKeyKey",
",",
"key",
")",
":",
"secret",
"=",
"value",
"\n",
"case",
"strings",
".",
"EqualFold",
"(",
"entityPathKey",
",",
"key",
")",
":",
"hubName",
"=",
"value",
"\n",
"}",
"\n",
"}",
"\n\n",
"parsed",
":=",
"newParsedConnection",
"(",
"namespace",
",",
"suffix",
",",
"hubName",
",",
"keyName",
",",
"secret",
")",
"\n",
"if",
"namespace",
"==",
"\"",
"\"",
"{",
"return",
"parsed",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"endpointKey",
")",
"\n",
"}",
"\n\n",
"if",
"keyName",
"==",
"\"",
"\"",
"{",
"return",
"parsed",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sharedAccessKeyNameKey",
")",
"\n",
"}",
"\n\n",
"if",
"secret",
"==",
"\"",
"\"",
"{",
"return",
"parsed",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"sharedAccessKeyKey",
")",
"\n",
"}",
"\n\n",
"return",
"parsed",
",",
"nil",
"\n",
"}"
] | // ParsedConnectionFromStr takes a string connection string from the Azure portal and returns the parsed representation.
// The method will return an error if the Endpoint, SharedAccessKeyName or SharedAccessKey is empty. | [
"ParsedConnectionFromStr",
"takes",
"a",
"string",
"connection",
"string",
"from",
"the",
"Azure",
"portal",
"and",
"returns",
"the",
"parsed",
"representation",
".",
"The",
"method",
"will",
"return",
"an",
"error",
"if",
"the",
"Endpoint",
"SharedAccessKeyName",
"or",
"SharedAccessKey",
"is",
"empty",
"."
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/conn/conn.go#L65-L112 |
10,557 | Azure/azure-amqp-common-go | rpc/rpc.go | NewLink | func NewLink(conn *amqp.Client, address string) (*Link, error) {
authSession, err := conn.NewSession()
if err != nil {
return nil, err
}
return NewLinkWithSession(conn, authSession, address)
} | go | func NewLink(conn *amqp.Client, address string) (*Link, error) {
authSession, err := conn.NewSession()
if err != nil {
return nil, err
}
return NewLinkWithSession(conn, authSession, address)
} | [
"func",
"NewLink",
"(",
"conn",
"*",
"amqp",
".",
"Client",
",",
"address",
"string",
")",
"(",
"*",
"Link",
",",
"error",
")",
"{",
"authSession",
",",
"err",
":=",
"conn",
".",
"NewSession",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"NewLinkWithSession",
"(",
"conn",
",",
"authSession",
",",
"address",
")",
"\n",
"}"
] | // NewLink will build a new request response link | [
"NewLink",
"will",
"build",
"a",
"new",
"request",
"response",
"link"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/rpc/rpc.go#L67-L74 |
10,558 | Azure/azure-amqp-common-go | rpc/rpc.go | NewLinkWithSession | func NewLinkWithSession(conn *amqp.Client, session *amqp.Session, address string) (*Link, error) {
authSender, err := session.NewSender(
amqp.LinkTargetAddress(address),
)
if err != nil {
return nil, err
}
linkID, err := uuid.NewV4()
if err != nil {
return nil, err
}
id := linkID.String()
clientAddress := strings.Replace("$", "", address, -1) + replyPostfix + id
authReceiver, err := session.NewReceiver(
amqp.LinkSourceAddress(address),
amqp.LinkTargetAddress(clientAddress),
)
if err != nil {
return nil, err
}
return &Link{
sender: authSender,
receiver: authReceiver,
session: session,
clientAddress: clientAddress,
id: id,
}, nil
} | go | func NewLinkWithSession(conn *amqp.Client, session *amqp.Session, address string) (*Link, error) {
authSender, err := session.NewSender(
amqp.LinkTargetAddress(address),
)
if err != nil {
return nil, err
}
linkID, err := uuid.NewV4()
if err != nil {
return nil, err
}
id := linkID.String()
clientAddress := strings.Replace("$", "", address, -1) + replyPostfix + id
authReceiver, err := session.NewReceiver(
amqp.LinkSourceAddress(address),
amqp.LinkTargetAddress(clientAddress),
)
if err != nil {
return nil, err
}
return &Link{
sender: authSender,
receiver: authReceiver,
session: session,
clientAddress: clientAddress,
id: id,
}, nil
} | [
"func",
"NewLinkWithSession",
"(",
"conn",
"*",
"amqp",
".",
"Client",
",",
"session",
"*",
"amqp",
".",
"Session",
",",
"address",
"string",
")",
"(",
"*",
"Link",
",",
"error",
")",
"{",
"authSender",
",",
"err",
":=",
"session",
".",
"NewSender",
"(",
"amqp",
".",
"LinkTargetAddress",
"(",
"address",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"linkID",
",",
"err",
":=",
"uuid",
".",
"NewV4",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"id",
":=",
"linkID",
".",
"String",
"(",
")",
"\n",
"clientAddress",
":=",
"strings",
".",
"Replace",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"address",
",",
"-",
"1",
")",
"+",
"replyPostfix",
"+",
"id",
"\n",
"authReceiver",
",",
"err",
":=",
"session",
".",
"NewReceiver",
"(",
"amqp",
".",
"LinkSourceAddress",
"(",
"address",
")",
",",
"amqp",
".",
"LinkTargetAddress",
"(",
"clientAddress",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"Link",
"{",
"sender",
":",
"authSender",
",",
"receiver",
":",
"authReceiver",
",",
"session",
":",
"session",
",",
"clientAddress",
":",
"clientAddress",
",",
"id",
":",
"id",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewLinkWithSession will build a new request response link, but will reuse an existing AMQP session | [
"NewLinkWithSession",
"will",
"build",
"a",
"new",
"request",
"response",
"link",
"but",
"will",
"reuse",
"an",
"existing",
"AMQP",
"session"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/rpc/rpc.go#L77-L108 |
10,559 | Azure/azure-amqp-common-go | rpc/rpc.go | RetryableRPC | func (l *Link) RetryableRPC(ctx context.Context, times int, delay time.Duration, msg *amqp.Message) (*Response, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "az-amqp-common.rpc.RetryableRPC")
defer span.End()
res, err := common.Retry(times, delay, func() (interface{}, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "az-amqp-common.rpc.RetryableRPC.retry")
defer span.End()
res, err := l.RPC(ctx, msg)
if err != nil {
log.For(ctx).Error(fmt.Errorf("error in RPC via link %s: %v", l.id, err))
return nil, err
}
switch {
case res.Code >= 200 && res.Code < 300:
log.For(ctx).Debug(fmt.Sprintf("successful rpc on link %s: status code %d and description: %s", l.id, res.Code, res.Description))
return res, nil
case res.Code >= 500:
errMessage := fmt.Sprintf("server error link %s: status code %d and description: %s", l.id, res.Code, res.Description)
log.For(ctx).Error(errors.New(errMessage))
return nil, common.Retryable(errMessage)
default:
errMessage := fmt.Sprintf("unhandled error link %s: status code %d and description: %s", l.id, res.Code, res.Description)
log.For(ctx).Error(errors.New(errMessage))
return nil, common.Retryable(errMessage)
}
})
if err != nil {
return nil, err
}
return res.(*Response), nil
} | go | func (l *Link) RetryableRPC(ctx context.Context, times int, delay time.Duration, msg *amqp.Message) (*Response, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "az-amqp-common.rpc.RetryableRPC")
defer span.End()
res, err := common.Retry(times, delay, func() (interface{}, error) {
span, ctx := tracing.StartSpanFromContext(ctx, "az-amqp-common.rpc.RetryableRPC.retry")
defer span.End()
res, err := l.RPC(ctx, msg)
if err != nil {
log.For(ctx).Error(fmt.Errorf("error in RPC via link %s: %v", l.id, err))
return nil, err
}
switch {
case res.Code >= 200 && res.Code < 300:
log.For(ctx).Debug(fmt.Sprintf("successful rpc on link %s: status code %d and description: %s", l.id, res.Code, res.Description))
return res, nil
case res.Code >= 500:
errMessage := fmt.Sprintf("server error link %s: status code %d and description: %s", l.id, res.Code, res.Description)
log.For(ctx).Error(errors.New(errMessage))
return nil, common.Retryable(errMessage)
default:
errMessage := fmt.Sprintf("unhandled error link %s: status code %d and description: %s", l.id, res.Code, res.Description)
log.For(ctx).Error(errors.New(errMessage))
return nil, common.Retryable(errMessage)
}
})
if err != nil {
return nil, err
}
return res.(*Response), nil
} | [
"func",
"(",
"l",
"*",
"Link",
")",
"RetryableRPC",
"(",
"ctx",
"context",
".",
"Context",
",",
"times",
"int",
",",
"delay",
"time",
".",
"Duration",
",",
"msg",
"*",
"amqp",
".",
"Message",
")",
"(",
"*",
"Response",
",",
"error",
")",
"{",
"span",
",",
"ctx",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"End",
"(",
")",
"\n\n",
"res",
",",
"err",
":=",
"common",
".",
"Retry",
"(",
"times",
",",
"delay",
",",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"span",
",",
"ctx",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"End",
"(",
")",
"\n\n",
"res",
",",
"err",
":=",
"l",
".",
"RPC",
"(",
"ctx",
",",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"For",
"(",
"ctx",
")",
".",
"Error",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"l",
".",
"id",
",",
"err",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"switch",
"{",
"case",
"res",
".",
"Code",
">=",
"200",
"&&",
"res",
".",
"Code",
"<",
"300",
":",
"log",
".",
"For",
"(",
"ctx",
")",
".",
"Debug",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"l",
".",
"id",
",",
"res",
".",
"Code",
",",
"res",
".",
"Description",
")",
")",
"\n",
"return",
"res",
",",
"nil",
"\n",
"case",
"res",
".",
"Code",
">=",
"500",
":",
"errMessage",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"l",
".",
"id",
",",
"res",
".",
"Code",
",",
"res",
".",
"Description",
")",
"\n",
"log",
".",
"For",
"(",
"ctx",
")",
".",
"Error",
"(",
"errors",
".",
"New",
"(",
"errMessage",
")",
")",
"\n",
"return",
"nil",
",",
"common",
".",
"Retryable",
"(",
"errMessage",
")",
"\n",
"default",
":",
"errMessage",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"l",
".",
"id",
",",
"res",
".",
"Code",
",",
"res",
".",
"Description",
")",
"\n",
"log",
".",
"For",
"(",
"ctx",
")",
".",
"Error",
"(",
"errors",
".",
"New",
"(",
"errMessage",
")",
")",
"\n",
"return",
"nil",
",",
"common",
".",
"Retryable",
"(",
"errMessage",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"res",
".",
"(",
"*",
"Response",
")",
",",
"nil",
"\n",
"}"
] | // RetryableRPC attempts to retry a request a number of times with delay | [
"RetryableRPC",
"attempts",
"to",
"retry",
"a",
"request",
"a",
"number",
"of",
"times",
"with",
"delay"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/rpc/rpc.go#L111-L143 |
10,560 | Azure/azure-amqp-common-go | rpc/rpc.go | RPC | func (l *Link) RPC(ctx context.Context, msg *amqp.Message) (*Response, error) {
const altStatusCodeKey, altDescriptionKey = "statusCode", "statusDescription"
l.rpcMu.Lock()
defer l.rpcMu.Unlock()
span, ctx := tracing.StartSpanFromContext(ctx, "az-amqp-common.rpc.RPC")
defer span.End()
if msg.Properties == nil {
msg.Properties = &amqp.MessageProperties{}
}
msg.Properties.ReplyTo = l.clientAddress
if msg.ApplicationProperties == nil {
msg.ApplicationProperties = make(map[string]interface{})
}
if _, ok := msg.ApplicationProperties["server-timeout"]; !ok {
if deadline, ok := ctx.Deadline(); ok {
msg.ApplicationProperties["server-timeout"] = uint(time.Until(deadline) / time.Millisecond)
}
}
err := l.sender.Send(ctx, msg)
if err != nil {
return nil, err
}
res, err := l.receiver.Receive(ctx)
if err != nil {
return nil, err
}
var statusCode int
statusCodeCandidates := []string{statusCodeKey, altStatusCodeKey}
for i := range statusCodeCandidates {
if rawStatusCode, ok := res.ApplicationProperties[statusCodeCandidates[i]]; ok {
if cast, ok := rawStatusCode.(int32); ok {
statusCode = int(cast)
break
} else {
return nil, errors.New("status code was not of expected type int32")
}
}
}
if statusCode == 0 {
return nil, errors.New("status codes was not found on rpc message")
}
var description string
descriptionCandidates := []string{descriptionKey, altDescriptionKey}
for i := range descriptionCandidates {
if rawDescription, ok := res.ApplicationProperties[descriptionCandidates[i]]; ok {
if description, ok = rawDescription.(string); ok || rawDescription == nil {
break
} else {
return nil, errors.New("status description was not of expected type string")
}
}
}
res.Accept()
return &Response{
Code: int(statusCode),
Description: description,
Message: res,
}, err
} | go | func (l *Link) RPC(ctx context.Context, msg *amqp.Message) (*Response, error) {
const altStatusCodeKey, altDescriptionKey = "statusCode", "statusDescription"
l.rpcMu.Lock()
defer l.rpcMu.Unlock()
span, ctx := tracing.StartSpanFromContext(ctx, "az-amqp-common.rpc.RPC")
defer span.End()
if msg.Properties == nil {
msg.Properties = &amqp.MessageProperties{}
}
msg.Properties.ReplyTo = l.clientAddress
if msg.ApplicationProperties == nil {
msg.ApplicationProperties = make(map[string]interface{})
}
if _, ok := msg.ApplicationProperties["server-timeout"]; !ok {
if deadline, ok := ctx.Deadline(); ok {
msg.ApplicationProperties["server-timeout"] = uint(time.Until(deadline) / time.Millisecond)
}
}
err := l.sender.Send(ctx, msg)
if err != nil {
return nil, err
}
res, err := l.receiver.Receive(ctx)
if err != nil {
return nil, err
}
var statusCode int
statusCodeCandidates := []string{statusCodeKey, altStatusCodeKey}
for i := range statusCodeCandidates {
if rawStatusCode, ok := res.ApplicationProperties[statusCodeCandidates[i]]; ok {
if cast, ok := rawStatusCode.(int32); ok {
statusCode = int(cast)
break
} else {
return nil, errors.New("status code was not of expected type int32")
}
}
}
if statusCode == 0 {
return nil, errors.New("status codes was not found on rpc message")
}
var description string
descriptionCandidates := []string{descriptionKey, altDescriptionKey}
for i := range descriptionCandidates {
if rawDescription, ok := res.ApplicationProperties[descriptionCandidates[i]]; ok {
if description, ok = rawDescription.(string); ok || rawDescription == nil {
break
} else {
return nil, errors.New("status description was not of expected type string")
}
}
}
res.Accept()
return &Response{
Code: int(statusCode),
Description: description,
Message: res,
}, err
} | [
"func",
"(",
"l",
"*",
"Link",
")",
"RPC",
"(",
"ctx",
"context",
".",
"Context",
",",
"msg",
"*",
"amqp",
".",
"Message",
")",
"(",
"*",
"Response",
",",
"error",
")",
"{",
"const",
"altStatusCodeKey",
",",
"altDescriptionKey",
"=",
"\"",
"\"",
",",
"\"",
"\"",
"\n\n",
"l",
".",
"rpcMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"rpcMu",
".",
"Unlock",
"(",
")",
"\n\n",
"span",
",",
"ctx",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"End",
"(",
")",
"\n\n",
"if",
"msg",
".",
"Properties",
"==",
"nil",
"{",
"msg",
".",
"Properties",
"=",
"&",
"amqp",
".",
"MessageProperties",
"{",
"}",
"\n",
"}",
"\n",
"msg",
".",
"Properties",
".",
"ReplyTo",
"=",
"l",
".",
"clientAddress",
"\n\n",
"if",
"msg",
".",
"ApplicationProperties",
"==",
"nil",
"{",
"msg",
".",
"ApplicationProperties",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"msg",
".",
"ApplicationProperties",
"[",
"\"",
"\"",
"]",
";",
"!",
"ok",
"{",
"if",
"deadline",
",",
"ok",
":=",
"ctx",
".",
"Deadline",
"(",
")",
";",
"ok",
"{",
"msg",
".",
"ApplicationProperties",
"[",
"\"",
"\"",
"]",
"=",
"uint",
"(",
"time",
".",
"Until",
"(",
"deadline",
")",
"/",
"time",
".",
"Millisecond",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"err",
":=",
"l",
".",
"sender",
".",
"Send",
"(",
"ctx",
",",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"res",
",",
"err",
":=",
"l",
".",
"receiver",
".",
"Receive",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"statusCode",
"int",
"\n",
"statusCodeCandidates",
":=",
"[",
"]",
"string",
"{",
"statusCodeKey",
",",
"altStatusCodeKey",
"}",
"\n",
"for",
"i",
":=",
"range",
"statusCodeCandidates",
"{",
"if",
"rawStatusCode",
",",
"ok",
":=",
"res",
".",
"ApplicationProperties",
"[",
"statusCodeCandidates",
"[",
"i",
"]",
"]",
";",
"ok",
"{",
"if",
"cast",
",",
"ok",
":=",
"rawStatusCode",
".",
"(",
"int32",
")",
";",
"ok",
"{",
"statusCode",
"=",
"int",
"(",
"cast",
")",
"\n",
"break",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"statusCode",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"description",
"string",
"\n",
"descriptionCandidates",
":=",
"[",
"]",
"string",
"{",
"descriptionKey",
",",
"altDescriptionKey",
"}",
"\n",
"for",
"i",
":=",
"range",
"descriptionCandidates",
"{",
"if",
"rawDescription",
",",
"ok",
":=",
"res",
".",
"ApplicationProperties",
"[",
"descriptionCandidates",
"[",
"i",
"]",
"]",
";",
"ok",
"{",
"if",
"description",
",",
"ok",
"=",
"rawDescription",
".",
"(",
"string",
")",
";",
"ok",
"||",
"rawDescription",
"==",
"nil",
"{",
"break",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"res",
".",
"Accept",
"(",
")",
"\n",
"return",
"&",
"Response",
"{",
"Code",
":",
"int",
"(",
"statusCode",
")",
",",
"Description",
":",
"description",
",",
"Message",
":",
"res",
",",
"}",
",",
"err",
"\n",
"}"
] | // RPC sends a request and waits on a response for that request | [
"RPC",
"sends",
"a",
"request",
"and",
"waits",
"on",
"a",
"response",
"for",
"that",
"request"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/rpc/rpc.go#L146-L214 |
10,561 | Azure/azure-amqp-common-go | rpc/rpc.go | Close | func (l *Link) Close(ctx context.Context) error {
span, ctx := tracing.StartSpanFromContext(ctx, "az-amqp-common.rpc.Close")
defer span.End()
if err := l.closeReceiver(ctx); err != nil {
_ = l.closeSender(ctx)
_ = l.closeSession(ctx)
return err
}
if err := l.closeSender(ctx); err != nil {
_ = l.closeSession(ctx)
return err
}
return l.closeSession(ctx)
} | go | func (l *Link) Close(ctx context.Context) error {
span, ctx := tracing.StartSpanFromContext(ctx, "az-amqp-common.rpc.Close")
defer span.End()
if err := l.closeReceiver(ctx); err != nil {
_ = l.closeSender(ctx)
_ = l.closeSession(ctx)
return err
}
if err := l.closeSender(ctx); err != nil {
_ = l.closeSession(ctx)
return err
}
return l.closeSession(ctx)
} | [
"func",
"(",
"l",
"*",
"Link",
")",
"Close",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"span",
",",
"ctx",
":=",
"tracing",
".",
"StartSpanFromContext",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"span",
".",
"End",
"(",
")",
"\n\n",
"if",
"err",
":=",
"l",
".",
"closeReceiver",
"(",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"_",
"=",
"l",
".",
"closeSender",
"(",
"ctx",
")",
"\n",
"_",
"=",
"l",
".",
"closeSession",
"(",
"ctx",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"l",
".",
"closeSender",
"(",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"_",
"=",
"l",
".",
"closeSession",
"(",
"ctx",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"l",
".",
"closeSession",
"(",
"ctx",
")",
"\n",
"}"
] | // Close the link receiver, sender and session | [
"Close",
"the",
"link",
"receiver",
"sender",
"and",
"session"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/rpc/rpc.go#L217-L233 |
10,562 | Azure/azure-amqp-common-go | aad/jwt.go | JWTProviderWithAzureEnvironment | func JWTProviderWithAzureEnvironment(env *azure.Environment) JWTProviderOption {
return func(config *TokenProviderConfiguration) error {
config.Env = env
return nil
}
} | go | func JWTProviderWithAzureEnvironment(env *azure.Environment) JWTProviderOption {
return func(config *TokenProviderConfiguration) error {
config.Env = env
return nil
}
} | [
"func",
"JWTProviderWithAzureEnvironment",
"(",
"env",
"*",
"azure",
".",
"Environment",
")",
"JWTProviderOption",
"{",
"return",
"func",
"(",
"config",
"*",
"TokenProviderConfiguration",
")",
"error",
"{",
"config",
".",
"Env",
"=",
"env",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // JWTProviderWithAzureEnvironment configures the token provider to use a specific Azure Environment | [
"JWTProviderWithAzureEnvironment",
"configures",
"the",
"token",
"provider",
"to",
"use",
"a",
"specific",
"Azure",
"Environment"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/aad/jwt.go#L69-L74 |
10,563 | Azure/azure-amqp-common-go | aad/jwt.go | JWTProviderWithResourceURI | func JWTProviderWithResourceURI(resourceURI string) JWTProviderOption {
return func(config *TokenProviderConfiguration) error {
config.ResourceURI = resourceURI
return nil
}
} | go | func JWTProviderWithResourceURI(resourceURI string) JWTProviderOption {
return func(config *TokenProviderConfiguration) error {
config.ResourceURI = resourceURI
return nil
}
} | [
"func",
"JWTProviderWithResourceURI",
"(",
"resourceURI",
"string",
")",
"JWTProviderOption",
"{",
"return",
"func",
"(",
"config",
"*",
"TokenProviderConfiguration",
")",
"error",
"{",
"config",
".",
"ResourceURI",
"=",
"resourceURI",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // JWTProviderWithResourceURI configures the token provider to use a specific eventhubResourceURI URI | [
"JWTProviderWithResourceURI",
"configures",
"the",
"token",
"provider",
"to",
"use",
"a",
"specific",
"eventhubResourceURI",
"URI"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/aad/jwt.go#L108-L113 |
10,564 | Azure/azure-amqp-common-go | aad/jwt.go | JWTProviderWithAADToken | func JWTProviderWithAADToken(aadToken *adal.ServicePrincipalToken) JWTProviderOption {
return func(config *TokenProviderConfiguration) error {
config.aadToken = aadToken
return nil
}
} | go | func JWTProviderWithAADToken(aadToken *adal.ServicePrincipalToken) JWTProviderOption {
return func(config *TokenProviderConfiguration) error {
config.aadToken = aadToken
return nil
}
} | [
"func",
"JWTProviderWithAADToken",
"(",
"aadToken",
"*",
"adal",
".",
"ServicePrincipalToken",
")",
"JWTProviderOption",
"{",
"return",
"func",
"(",
"config",
"*",
"TokenProviderConfiguration",
")",
"error",
"{",
"config",
".",
"aadToken",
"=",
"aadToken",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // JWTProviderWithAADToken configures the token provider to use a specific Azure Active Directory Service Principal token | [
"JWTProviderWithAADToken",
"configures",
"the",
"token",
"provider",
"to",
"use",
"a",
"specific",
"Azure",
"Active",
"Directory",
"Service",
"Principal",
"token"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/aad/jwt.go#L116-L121 |
10,565 | Azure/azure-amqp-common-go | aad/jwt.go | NewJWTProvider | func NewJWTProvider(opts ...JWTProviderOption) (*TokenProvider, error) {
config := &TokenProviderConfiguration{
ResourceURI: eventhubResourceURI,
}
for _, opt := range opts {
err := opt(config)
if err != nil {
return nil, err
}
}
if config.aadToken == nil {
spToken, err := config.NewServicePrincipalToken()
if err != nil {
return nil, err
}
config.aadToken = spToken
}
return &TokenProvider{tokenProvider: config.aadToken}, nil
} | go | func NewJWTProvider(opts ...JWTProviderOption) (*TokenProvider, error) {
config := &TokenProviderConfiguration{
ResourceURI: eventhubResourceURI,
}
for _, opt := range opts {
err := opt(config)
if err != nil {
return nil, err
}
}
if config.aadToken == nil {
spToken, err := config.NewServicePrincipalToken()
if err != nil {
return nil, err
}
config.aadToken = spToken
}
return &TokenProvider{tokenProvider: config.aadToken}, nil
} | [
"func",
"NewJWTProvider",
"(",
"opts",
"...",
"JWTProviderOption",
")",
"(",
"*",
"TokenProvider",
",",
"error",
")",
"{",
"config",
":=",
"&",
"TokenProviderConfiguration",
"{",
"ResourceURI",
":",
"eventhubResourceURI",
",",
"}",
"\n\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"err",
":=",
"opt",
"(",
"config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"config",
".",
"aadToken",
"==",
"nil",
"{",
"spToken",
",",
"err",
":=",
"config",
".",
"NewServicePrincipalToken",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"config",
".",
"aadToken",
"=",
"spToken",
"\n",
"}",
"\n",
"return",
"&",
"TokenProvider",
"{",
"tokenProvider",
":",
"config",
".",
"aadToken",
"}",
",",
"nil",
"\n",
"}"
] | // NewJWTProvider builds an Azure Active Directory claims-based security token provider | [
"NewJWTProvider",
"builds",
"an",
"Azure",
"Active",
"Directory",
"claims",
"-",
"based",
"security",
"token",
"provider"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/aad/jwt.go#L124-L144 |
10,566 | Azure/azure-amqp-common-go | aad/jwt.go | NewServicePrincipalToken | func (c *TokenProviderConfiguration) NewServicePrincipalToken() (*adal.ServicePrincipalToken, error) {
oauthConfig, err := adal.NewOAuthConfig(c.Env.ActiveDirectoryEndpoint, c.TenantID)
if err != nil {
return nil, err
}
// 1.Client Credentials
if c.ClientSecret != "" {
spToken, err := adal.NewServicePrincipalToken(*oauthConfig, c.ClientID, c.ClientSecret, c.ResourceURI)
if err != nil {
return nil, fmt.Errorf("failed to get oauth token from client credentials: %v", err)
}
if err := spToken.Refresh(); err != nil {
return nil, fmt.Errorf("failed to refersh token: %v", spToken)
}
return spToken, nil
}
// 2. Client Certificate
if c.CertificatePath != "" {
certData, err := ioutil.ReadFile(c.CertificatePath)
if err != nil {
return nil, fmt.Errorf("failed to read the certificate file (%s): %v", c.CertificatePath, err)
}
certificate, rsaPrivateKey, err := decodePkcs12(certData, c.CertificatePassword)
if err != nil {
return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err)
}
spToken, err := adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, c.ClientID, certificate, rsaPrivateKey, c.ResourceURI)
if err != nil {
return nil, fmt.Errorf("failed to get oauth token from certificate auth: %v", err)
}
if err := spToken.Refresh(); err != nil {
return nil, fmt.Errorf("failed to refersh token: %v", spToken)
}
return spToken, nil
}
// 3. By default return MSI
msiEndpoint, err := adal.GetMSIVMEndpoint()
if err != nil {
return nil, err
}
spToken, err := adal.NewServicePrincipalTokenFromMSI(msiEndpoint, c.ResourceURI)
if err != nil {
return nil, fmt.Errorf("failed to get oauth token from MSI: %v", err)
}
if err := spToken.Refresh(); err != nil {
return nil, fmt.Errorf("failed to refersh token: %v", spToken)
}
return spToken, nil
} | go | func (c *TokenProviderConfiguration) NewServicePrincipalToken() (*adal.ServicePrincipalToken, error) {
oauthConfig, err := adal.NewOAuthConfig(c.Env.ActiveDirectoryEndpoint, c.TenantID)
if err != nil {
return nil, err
}
// 1.Client Credentials
if c.ClientSecret != "" {
spToken, err := adal.NewServicePrincipalToken(*oauthConfig, c.ClientID, c.ClientSecret, c.ResourceURI)
if err != nil {
return nil, fmt.Errorf("failed to get oauth token from client credentials: %v", err)
}
if err := spToken.Refresh(); err != nil {
return nil, fmt.Errorf("failed to refersh token: %v", spToken)
}
return spToken, nil
}
// 2. Client Certificate
if c.CertificatePath != "" {
certData, err := ioutil.ReadFile(c.CertificatePath)
if err != nil {
return nil, fmt.Errorf("failed to read the certificate file (%s): %v", c.CertificatePath, err)
}
certificate, rsaPrivateKey, err := decodePkcs12(certData, c.CertificatePassword)
if err != nil {
return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err)
}
spToken, err := adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, c.ClientID, certificate, rsaPrivateKey, c.ResourceURI)
if err != nil {
return nil, fmt.Errorf("failed to get oauth token from certificate auth: %v", err)
}
if err := spToken.Refresh(); err != nil {
return nil, fmt.Errorf("failed to refersh token: %v", spToken)
}
return spToken, nil
}
// 3. By default return MSI
msiEndpoint, err := adal.GetMSIVMEndpoint()
if err != nil {
return nil, err
}
spToken, err := adal.NewServicePrincipalTokenFromMSI(msiEndpoint, c.ResourceURI)
if err != nil {
return nil, fmt.Errorf("failed to get oauth token from MSI: %v", err)
}
if err := spToken.Refresh(); err != nil {
return nil, fmt.Errorf("failed to refersh token: %v", spToken)
}
return spToken, nil
} | [
"func",
"(",
"c",
"*",
"TokenProviderConfiguration",
")",
"NewServicePrincipalToken",
"(",
")",
"(",
"*",
"adal",
".",
"ServicePrincipalToken",
",",
"error",
")",
"{",
"oauthConfig",
",",
"err",
":=",
"adal",
".",
"NewOAuthConfig",
"(",
"c",
".",
"Env",
".",
"ActiveDirectoryEndpoint",
",",
"c",
".",
"TenantID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// 1.Client Credentials",
"if",
"c",
".",
"ClientSecret",
"!=",
"\"",
"\"",
"{",
"spToken",
",",
"err",
":=",
"adal",
".",
"NewServicePrincipalToken",
"(",
"*",
"oauthConfig",
",",
"c",
".",
"ClientID",
",",
"c",
".",
"ClientSecret",
",",
"c",
".",
"ResourceURI",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"spToken",
".",
"Refresh",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"spToken",
")",
"\n",
"}",
"\n",
"return",
"spToken",
",",
"nil",
"\n",
"}",
"\n\n",
"// 2. Client Certificate",
"if",
"c",
".",
"CertificatePath",
"!=",
"\"",
"\"",
"{",
"certData",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"c",
".",
"CertificatePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
".",
"CertificatePath",
",",
"err",
")",
"\n",
"}",
"\n",
"certificate",
",",
"rsaPrivateKey",
",",
"err",
":=",
"decodePkcs12",
"(",
"certData",
",",
"c",
".",
"CertificatePassword",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"spToken",
",",
"err",
":=",
"adal",
".",
"NewServicePrincipalTokenFromCertificate",
"(",
"*",
"oauthConfig",
",",
"c",
".",
"ClientID",
",",
"certificate",
",",
"rsaPrivateKey",
",",
"c",
".",
"ResourceURI",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"spToken",
".",
"Refresh",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"spToken",
")",
"\n",
"}",
"\n",
"return",
"spToken",
",",
"nil",
"\n",
"}",
"\n\n",
"// 3. By default return MSI",
"msiEndpoint",
",",
"err",
":=",
"adal",
".",
"GetMSIVMEndpoint",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"spToken",
",",
"err",
":=",
"adal",
".",
"NewServicePrincipalTokenFromMSI",
"(",
"msiEndpoint",
",",
"c",
".",
"ResourceURI",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"spToken",
".",
"Refresh",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"spToken",
")",
"\n",
"}",
"\n",
"return",
"spToken",
",",
"nil",
"\n",
"}"
] | // NewServicePrincipalToken creates a new Azure Active Directory Service Principal token provider | [
"NewServicePrincipalToken",
"creates",
"a",
"new",
"Azure",
"Active",
"Directory",
"Service",
"Principal",
"token",
"provider"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/aad/jwt.go#L147-L198 |
10,567 | Azure/azure-amqp-common-go | aad/jwt.go | GetToken | func (t *TokenProvider) GetToken(audience string) (*auth.Token, error) {
token := t.tokenProvider.Token()
expireTicks, err := strconv.ParseInt(string(token.ExpiresOn), 10, 64)
if err != nil {
return nil, err
}
expires := time.Unix(expireTicks, 0)
if expires.Before(time.Now()) {
if err := t.tokenProvider.Refresh(); err != nil {
return nil, err
}
token = t.tokenProvider.Token()
}
return auth.NewToken(auth.CBSTokenTypeJWT, token.AccessToken, string(token.ExpiresOn)), nil
} | go | func (t *TokenProvider) GetToken(audience string) (*auth.Token, error) {
token := t.tokenProvider.Token()
expireTicks, err := strconv.ParseInt(string(token.ExpiresOn), 10, 64)
if err != nil {
return nil, err
}
expires := time.Unix(expireTicks, 0)
if expires.Before(time.Now()) {
if err := t.tokenProvider.Refresh(); err != nil {
return nil, err
}
token = t.tokenProvider.Token()
}
return auth.NewToken(auth.CBSTokenTypeJWT, token.AccessToken, string(token.ExpiresOn)), nil
} | [
"func",
"(",
"t",
"*",
"TokenProvider",
")",
"GetToken",
"(",
"audience",
"string",
")",
"(",
"*",
"auth",
".",
"Token",
",",
"error",
")",
"{",
"token",
":=",
"t",
".",
"tokenProvider",
".",
"Token",
"(",
")",
"\n",
"expireTicks",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"string",
"(",
"token",
".",
"ExpiresOn",
")",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"expires",
":=",
"time",
".",
"Unix",
"(",
"expireTicks",
",",
"0",
")",
"\n\n",
"if",
"expires",
".",
"Before",
"(",
"time",
".",
"Now",
"(",
")",
")",
"{",
"if",
"err",
":=",
"t",
".",
"tokenProvider",
".",
"Refresh",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"token",
"=",
"t",
".",
"tokenProvider",
".",
"Token",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"auth",
".",
"NewToken",
"(",
"auth",
".",
"CBSTokenTypeJWT",
",",
"token",
".",
"AccessToken",
",",
"string",
"(",
"token",
".",
"ExpiresOn",
")",
")",
",",
"nil",
"\n",
"}"
] | // GetToken gets a CBS JWT | [
"GetToken",
"gets",
"a",
"CBS",
"JWT"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/aad/jwt.go#L201-L217 |
10,568 | Azure/azure-amqp-common-go | auth/token.go | NewToken | func NewToken(tokenType TokenType, token, expiry string) *Token {
return &Token{
TokenType: tokenType,
Token: token,
Expiry: expiry,
}
} | go | func NewToken(tokenType TokenType, token, expiry string) *Token {
return &Token{
TokenType: tokenType,
Token: token,
Expiry: expiry,
}
} | [
"func",
"NewToken",
"(",
"tokenType",
"TokenType",
",",
"token",
",",
"expiry",
"string",
")",
"*",
"Token",
"{",
"return",
"&",
"Token",
"{",
"TokenType",
":",
"tokenType",
",",
"Token",
":",
"token",
",",
"Expiry",
":",
"expiry",
",",
"}",
"\n",
"}"
] | // NewToken constructs a new auth token | [
"NewToken",
"constructs",
"a",
"new",
"auth",
"token"
] | b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a | https://github.com/Azure/azure-amqp-common-go/blob/b5ea4829bce0d96bc7b4d11bfc8ccd2afdf0ec4a/auth/token.go#L52-L58 |
10,569 | cloudfoundry/auction | auctionrunner/scheduler.go | removeNonApplicableProblems | func removeNonApplicableProblems(problems map[string]struct{}, err error) {
if ierr, ok := err.(rep.InsufficientResourcesError); ok {
for problem, _ := range problems {
if _, ok := ierr.Problems[problem]; !ok {
delete(problems, problem)
}
}
}
} | go | func removeNonApplicableProblems(problems map[string]struct{}, err error) {
if ierr, ok := err.(rep.InsufficientResourcesError); ok {
for problem, _ := range problems {
if _, ok := ierr.Problems[problem]; !ok {
delete(problems, problem)
}
}
}
} | [
"func",
"removeNonApplicableProblems",
"(",
"problems",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
",",
"err",
"error",
")",
"{",
"if",
"ierr",
",",
"ok",
":=",
"err",
".",
"(",
"rep",
".",
"InsufficientResourcesError",
")",
";",
"ok",
"{",
"for",
"problem",
",",
"_",
":=",
"range",
"problems",
"{",
"if",
"_",
",",
"ok",
":=",
"ierr",
".",
"Problems",
"[",
"problem",
"]",
";",
"!",
"ok",
"{",
"delete",
"(",
"problems",
",",
"problem",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // removeNonApplicableProblems modifies the 'problems' map to remove any problems that didn't show up on err.
//
// The list of problems to report should only consist of the problems that exist on every cell
// For example, if there is not enough memory on one cell and not enough disk on another, we should
// not call out memory or disk as being a specific problem. | [
"removeNonApplicableProblems",
"modifies",
"the",
"problems",
"map",
"to",
"remove",
"any",
"problems",
"that",
"didn",
"t",
"show",
"up",
"on",
"err",
".",
"The",
"list",
"of",
"problems",
"to",
"report",
"should",
"only",
"consist",
"of",
"the",
"problems",
"that",
"exist",
"on",
"every",
"cell",
"For",
"example",
"if",
"there",
"is",
"not",
"enough",
"memory",
"on",
"one",
"cell",
"and",
"not",
"enough",
"disk",
"on",
"another",
"we",
"should",
"not",
"call",
"out",
"memory",
"or",
"disk",
"as",
"being",
"a",
"specific",
"problem",
"."
] | f5726c4858daf51bfa1216c5b3aefb212fc59fd1 | https://github.com/cloudfoundry/auction/blob/f5726c4858daf51bfa1216c5b3aefb212fc59fd1/auctionrunner/scheduler.go#L384-L392 |
10,570 | cloudfoundry/auction | simulation/simulationrep/simulation_rep.go | StopLRPInstance | func (rep *SimulationRep) StopLRPInstance(lager.Logger, models.ActualLRPKey, models.ActualLRPInstanceKey) error {
panic("UNIMPLEMENTED METHOD")
} | go | func (rep *SimulationRep) StopLRPInstance(lager.Logger, models.ActualLRPKey, models.ActualLRPInstanceKey) error {
panic("UNIMPLEMENTED METHOD")
} | [
"func",
"(",
"rep",
"*",
"SimulationRep",
")",
"StopLRPInstance",
"(",
"lager",
".",
"Logger",
",",
"models",
".",
"ActualLRPKey",
",",
"models",
".",
"ActualLRPInstanceKey",
")",
"error",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | //these are rep client methods the auction does not use | [
"these",
"are",
"rep",
"client",
"methods",
"the",
"auction",
"does",
"not",
"use"
] | f5726c4858daf51bfa1216c5b3aefb212fc59fd1 | https://github.com/cloudfoundry/auction/blob/f5726c4858daf51bfa1216c5b3aefb212fc59fd1/simulation/simulationrep/simulation_rep.go#L137-L139 |
10,571 | ipfans/echo-session | session.go | Default | func Default(ctx echo.Context) Session {
session := ctx.Get(DefaultKey)
if session == nil {
return nil
}
return ctx.Get(DefaultKey).(Session)
} | go | func Default(ctx echo.Context) Session {
session := ctx.Get(DefaultKey)
if session == nil {
return nil
}
return ctx.Get(DefaultKey).(Session)
} | [
"func",
"Default",
"(",
"ctx",
"echo",
".",
"Context",
")",
"Session",
"{",
"session",
":=",
"ctx",
".",
"Get",
"(",
"DefaultKey",
")",
"\n",
"if",
"session",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"ctx",
".",
"Get",
"(",
"DefaultKey",
")",
".",
"(",
"Session",
")",
"\n",
"}"
] | // shortcut to get session | [
"shortcut",
"to",
"get",
"session"
] | acc7adbf89867d8c5be673e0000f5c6f57ad50c1 | https://github.com/ipfans/echo-session/blob/acc7adbf89867d8c5be673e0000f5c6f57ad50c1/session.go#L151-L157 |
10,572 | gravitational/trace | httplib.go | WriteError | func WriteError(w http.ResponseWriter, err error) {
if IsAggregate(err) {
for i := 0; i < maxHops; i++ {
var aggErr Aggregate
var ok bool
if aggErr, ok = Unwrap(err).(Aggregate); !ok {
break
}
errors := aggErr.Errors()
if len(errors) == 0 {
break
}
err = errors[0]
}
}
replyJSON(w, ErrorToCode(err), err)
} | go | func WriteError(w http.ResponseWriter, err error) {
if IsAggregate(err) {
for i := 0; i < maxHops; i++ {
var aggErr Aggregate
var ok bool
if aggErr, ok = Unwrap(err).(Aggregate); !ok {
break
}
errors := aggErr.Errors()
if len(errors) == 0 {
break
}
err = errors[0]
}
}
replyJSON(w, ErrorToCode(err), err)
} | [
"func",
"WriteError",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"err",
"error",
")",
"{",
"if",
"IsAggregate",
"(",
"err",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"maxHops",
";",
"i",
"++",
"{",
"var",
"aggErr",
"Aggregate",
"\n",
"var",
"ok",
"bool",
"\n",
"if",
"aggErr",
",",
"ok",
"=",
"Unwrap",
"(",
"err",
")",
".",
"(",
"Aggregate",
")",
";",
"!",
"ok",
"{",
"break",
"\n",
"}",
"\n",
"errors",
":=",
"aggErr",
".",
"Errors",
"(",
")",
"\n",
"if",
"len",
"(",
"errors",
")",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n",
"err",
"=",
"errors",
"[",
"0",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"replyJSON",
"(",
"w",
",",
"ErrorToCode",
"(",
"err",
")",
",",
"err",
")",
"\n",
"}"
] | // WriteError sets up HTTP error response and writes it to writer w | [
"WriteError",
"sets",
"up",
"HTTP",
"error",
"response",
"and",
"writes",
"it",
"to",
"writer",
"w"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/httplib.go#L10-L26 |
10,573 | gravitational/trace | httplib.go | ErrorToCode | func ErrorToCode(err error) int {
switch {
case IsAggregate(err):
return http.StatusGatewayTimeout
case IsNotFound(err):
return http.StatusNotFound
case IsBadParameter(err) || IsOAuth2(err):
return http.StatusBadRequest
case IsNotImplemented(err):
return http.StatusNotImplemented
case IsCompareFailed(err):
return http.StatusPreconditionFailed
case IsAccessDenied(err):
return http.StatusForbidden
case IsAlreadyExists(err):
return http.StatusConflict
case IsLimitExceeded(err):
return http.StatusTooManyRequests
case IsConnectionProblem(err):
return http.StatusGatewayTimeout
default:
return http.StatusInternalServerError
}
} | go | func ErrorToCode(err error) int {
switch {
case IsAggregate(err):
return http.StatusGatewayTimeout
case IsNotFound(err):
return http.StatusNotFound
case IsBadParameter(err) || IsOAuth2(err):
return http.StatusBadRequest
case IsNotImplemented(err):
return http.StatusNotImplemented
case IsCompareFailed(err):
return http.StatusPreconditionFailed
case IsAccessDenied(err):
return http.StatusForbidden
case IsAlreadyExists(err):
return http.StatusConflict
case IsLimitExceeded(err):
return http.StatusTooManyRequests
case IsConnectionProblem(err):
return http.StatusGatewayTimeout
default:
return http.StatusInternalServerError
}
} | [
"func",
"ErrorToCode",
"(",
"err",
"error",
")",
"int",
"{",
"switch",
"{",
"case",
"IsAggregate",
"(",
"err",
")",
":",
"return",
"http",
".",
"StatusGatewayTimeout",
"\n",
"case",
"IsNotFound",
"(",
"err",
")",
":",
"return",
"http",
".",
"StatusNotFound",
"\n",
"case",
"IsBadParameter",
"(",
"err",
")",
"||",
"IsOAuth2",
"(",
"err",
")",
":",
"return",
"http",
".",
"StatusBadRequest",
"\n",
"case",
"IsNotImplemented",
"(",
"err",
")",
":",
"return",
"http",
".",
"StatusNotImplemented",
"\n",
"case",
"IsCompareFailed",
"(",
"err",
")",
":",
"return",
"http",
".",
"StatusPreconditionFailed",
"\n",
"case",
"IsAccessDenied",
"(",
"err",
")",
":",
"return",
"http",
".",
"StatusForbidden",
"\n",
"case",
"IsAlreadyExists",
"(",
"err",
")",
":",
"return",
"http",
".",
"StatusConflict",
"\n",
"case",
"IsLimitExceeded",
"(",
"err",
")",
":",
"return",
"http",
".",
"StatusTooManyRequests",
"\n",
"case",
"IsConnectionProblem",
"(",
"err",
")",
":",
"return",
"http",
".",
"StatusGatewayTimeout",
"\n",
"default",
":",
"return",
"http",
".",
"StatusInternalServerError",
"\n",
"}",
"\n",
"}"
] | // ErrorToCode returns an appropriate HTTP status code based on the provided error type | [
"ErrorToCode",
"returns",
"an",
"appropriate",
"HTTP",
"status",
"code",
"based",
"on",
"the",
"provided",
"error",
"type"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/httplib.go#L29-L52 |
10,574 | gravitational/trace | httplib.go | ReadError | func ReadError(statusCode int, re []byte) error {
var e error
switch statusCode {
case http.StatusNotFound:
e = &NotFoundError{Message: string(re)}
case http.StatusBadRequest:
e = &BadParameterError{Message: string(re)}
case http.StatusNotImplemented:
e = &NotImplementedError{Message: string(re)}
case http.StatusPreconditionFailed:
e = &CompareFailedError{Message: string(re)}
case http.StatusForbidden:
e = &AccessDeniedError{Message: string(re)}
case http.StatusConflict:
e = &AlreadyExistsError{Message: string(re)}
case http.StatusTooManyRequests:
e = &LimitExceededError{Message: string(re)}
case http.StatusGatewayTimeout:
e = &ConnectionProblemError{Message: string(re)}
default:
if statusCode < 200 || statusCode > 299 {
return Errorf(string(re))
}
return nil
}
return unmarshalError(e, re)
} | go | func ReadError(statusCode int, re []byte) error {
var e error
switch statusCode {
case http.StatusNotFound:
e = &NotFoundError{Message: string(re)}
case http.StatusBadRequest:
e = &BadParameterError{Message: string(re)}
case http.StatusNotImplemented:
e = &NotImplementedError{Message: string(re)}
case http.StatusPreconditionFailed:
e = &CompareFailedError{Message: string(re)}
case http.StatusForbidden:
e = &AccessDeniedError{Message: string(re)}
case http.StatusConflict:
e = &AlreadyExistsError{Message: string(re)}
case http.StatusTooManyRequests:
e = &LimitExceededError{Message: string(re)}
case http.StatusGatewayTimeout:
e = &ConnectionProblemError{Message: string(re)}
default:
if statusCode < 200 || statusCode > 299 {
return Errorf(string(re))
}
return nil
}
return unmarshalError(e, re)
} | [
"func",
"ReadError",
"(",
"statusCode",
"int",
",",
"re",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"e",
"error",
"\n",
"switch",
"statusCode",
"{",
"case",
"http",
".",
"StatusNotFound",
":",
"e",
"=",
"&",
"NotFoundError",
"{",
"Message",
":",
"string",
"(",
"re",
")",
"}",
"\n",
"case",
"http",
".",
"StatusBadRequest",
":",
"e",
"=",
"&",
"BadParameterError",
"{",
"Message",
":",
"string",
"(",
"re",
")",
"}",
"\n",
"case",
"http",
".",
"StatusNotImplemented",
":",
"e",
"=",
"&",
"NotImplementedError",
"{",
"Message",
":",
"string",
"(",
"re",
")",
"}",
"\n",
"case",
"http",
".",
"StatusPreconditionFailed",
":",
"e",
"=",
"&",
"CompareFailedError",
"{",
"Message",
":",
"string",
"(",
"re",
")",
"}",
"\n",
"case",
"http",
".",
"StatusForbidden",
":",
"e",
"=",
"&",
"AccessDeniedError",
"{",
"Message",
":",
"string",
"(",
"re",
")",
"}",
"\n",
"case",
"http",
".",
"StatusConflict",
":",
"e",
"=",
"&",
"AlreadyExistsError",
"{",
"Message",
":",
"string",
"(",
"re",
")",
"}",
"\n",
"case",
"http",
".",
"StatusTooManyRequests",
":",
"e",
"=",
"&",
"LimitExceededError",
"{",
"Message",
":",
"string",
"(",
"re",
")",
"}",
"\n",
"case",
"http",
".",
"StatusGatewayTimeout",
":",
"e",
"=",
"&",
"ConnectionProblemError",
"{",
"Message",
":",
"string",
"(",
"re",
")",
"}",
"\n",
"default",
":",
"if",
"statusCode",
"<",
"200",
"||",
"statusCode",
">",
"299",
"{",
"return",
"Errorf",
"(",
"string",
"(",
"re",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"unmarshalError",
"(",
"e",
",",
"re",
")",
"\n",
"}"
] | // ReadError converts http error to internal error type
// based on HTTP response code and HTTP body contents
// if status code does not indicate error, it will return nil | [
"ReadError",
"converts",
"http",
"error",
"to",
"internal",
"error",
"type",
"based",
"on",
"HTTP",
"response",
"code",
"and",
"HTTP",
"body",
"contents",
"if",
"status",
"code",
"does",
"not",
"indicate",
"error",
"it",
"will",
"return",
"nil"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/httplib.go#L57-L83 |
10,575 | gravitational/trace | trail/trail.go | ToGRPC | func ToGRPC(err error) error {
if err == nil {
return nil
}
userMessage := trace.UserMessage(err)
if trace.IsNotFound(err) {
return grpc.Errorf(codes.NotFound, userMessage)
}
if trace.IsAlreadyExists(err) {
return grpc.Errorf(codes.AlreadyExists, userMessage)
}
if trace.IsAccessDenied(err) {
return grpc.Errorf(codes.PermissionDenied, userMessage)
}
if trace.IsCompareFailed(err) {
return grpc.Errorf(codes.FailedPrecondition, userMessage)
}
if trace.IsBadParameter(err) || trace.IsOAuth2(err) {
return grpc.Errorf(codes.InvalidArgument, userMessage)
}
if trace.IsLimitExceeded(err) {
return grpc.Errorf(codes.ResourceExhausted, userMessage)
}
if trace.IsConnectionProblem(err) {
return grpc.Errorf(codes.Unavailable, userMessage)
}
if trace.IsNotImplemented(err) {
return grpc.Errorf(codes.Unimplemented, userMessage)
}
return grpc.Errorf(codes.Unknown, userMessage)
} | go | func ToGRPC(err error) error {
if err == nil {
return nil
}
userMessage := trace.UserMessage(err)
if trace.IsNotFound(err) {
return grpc.Errorf(codes.NotFound, userMessage)
}
if trace.IsAlreadyExists(err) {
return grpc.Errorf(codes.AlreadyExists, userMessage)
}
if trace.IsAccessDenied(err) {
return grpc.Errorf(codes.PermissionDenied, userMessage)
}
if trace.IsCompareFailed(err) {
return grpc.Errorf(codes.FailedPrecondition, userMessage)
}
if trace.IsBadParameter(err) || trace.IsOAuth2(err) {
return grpc.Errorf(codes.InvalidArgument, userMessage)
}
if trace.IsLimitExceeded(err) {
return grpc.Errorf(codes.ResourceExhausted, userMessage)
}
if trace.IsConnectionProblem(err) {
return grpc.Errorf(codes.Unavailable, userMessage)
}
if trace.IsNotImplemented(err) {
return grpc.Errorf(codes.Unimplemented, userMessage)
}
return grpc.Errorf(codes.Unknown, userMessage)
} | [
"func",
"ToGRPC",
"(",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"userMessage",
":=",
"trace",
".",
"UserMessage",
"(",
"err",
")",
"\n",
"if",
"trace",
".",
"IsNotFound",
"(",
"err",
")",
"{",
"return",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"NotFound",
",",
"userMessage",
")",
"\n",
"}",
"\n",
"if",
"trace",
".",
"IsAlreadyExists",
"(",
"err",
")",
"{",
"return",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"AlreadyExists",
",",
"userMessage",
")",
"\n",
"}",
"\n",
"if",
"trace",
".",
"IsAccessDenied",
"(",
"err",
")",
"{",
"return",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"PermissionDenied",
",",
"userMessage",
")",
"\n",
"}",
"\n",
"if",
"trace",
".",
"IsCompareFailed",
"(",
"err",
")",
"{",
"return",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"FailedPrecondition",
",",
"userMessage",
")",
"\n",
"}",
"\n",
"if",
"trace",
".",
"IsBadParameter",
"(",
"err",
")",
"||",
"trace",
".",
"IsOAuth2",
"(",
"err",
")",
"{",
"return",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"userMessage",
")",
"\n",
"}",
"\n",
"if",
"trace",
".",
"IsLimitExceeded",
"(",
"err",
")",
"{",
"return",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"ResourceExhausted",
",",
"userMessage",
")",
"\n",
"}",
"\n",
"if",
"trace",
".",
"IsConnectionProblem",
"(",
"err",
")",
"{",
"return",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"Unavailable",
",",
"userMessage",
")",
"\n",
"}",
"\n",
"if",
"trace",
".",
"IsNotImplemented",
"(",
"err",
")",
"{",
"return",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"Unimplemented",
",",
"userMessage",
")",
"\n",
"}",
"\n",
"return",
"grpc",
".",
"Errorf",
"(",
"codes",
".",
"Unknown",
",",
"userMessage",
")",
"\n",
"}"
] | // ToGRPC converts error to GRPC-compatible error | [
"ToGRPC",
"converts",
"error",
"to",
"GRPC",
"-",
"compatible",
"error"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trail/trail.go#L80-L110 |
10,576 | gravitational/trace | trail/trail.go | FromGRPC | func FromGRPC(err error, args ...interface{}) error {
if err == nil {
return nil
}
code := grpc.Code(err)
message := grpc.ErrorDesc(err)
var e error
switch code {
case codes.OK:
return nil
case codes.NotFound:
e = &trace.NotFoundError{Message: message}
case codes.AlreadyExists:
e = &trace.AlreadyExistsError{Message: message}
case codes.PermissionDenied:
e = &trace.AccessDeniedError{Message: message}
case codes.FailedPrecondition:
e = &trace.CompareFailedError{Message: message}
case codes.InvalidArgument:
e = &trace.BadParameterError{Message: message}
case codes.ResourceExhausted:
e = &trace.LimitExceededError{Message: message}
case codes.Unavailable:
e = &trace.ConnectionProblemError{Message: message}
case codes.Unimplemented:
e = &trace.NotImplementedError{Message: message}
default:
e = errors.New(message)
}
if len(args) != 0 {
if meta, ok := args[0].(metadata.MD); ok {
e = DecodeDebugInfo(e, meta)
}
}
return e
} | go | func FromGRPC(err error, args ...interface{}) error {
if err == nil {
return nil
}
code := grpc.Code(err)
message := grpc.ErrorDesc(err)
var e error
switch code {
case codes.OK:
return nil
case codes.NotFound:
e = &trace.NotFoundError{Message: message}
case codes.AlreadyExists:
e = &trace.AlreadyExistsError{Message: message}
case codes.PermissionDenied:
e = &trace.AccessDeniedError{Message: message}
case codes.FailedPrecondition:
e = &trace.CompareFailedError{Message: message}
case codes.InvalidArgument:
e = &trace.BadParameterError{Message: message}
case codes.ResourceExhausted:
e = &trace.LimitExceededError{Message: message}
case codes.Unavailable:
e = &trace.ConnectionProblemError{Message: message}
case codes.Unimplemented:
e = &trace.NotImplementedError{Message: message}
default:
e = errors.New(message)
}
if len(args) != 0 {
if meta, ok := args[0].(metadata.MD); ok {
e = DecodeDebugInfo(e, meta)
}
}
return e
} | [
"func",
"FromGRPC",
"(",
"err",
"error",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"code",
":=",
"grpc",
".",
"Code",
"(",
"err",
")",
"\n",
"message",
":=",
"grpc",
".",
"ErrorDesc",
"(",
"err",
")",
"\n",
"var",
"e",
"error",
"\n",
"switch",
"code",
"{",
"case",
"codes",
".",
"OK",
":",
"return",
"nil",
"\n",
"case",
"codes",
".",
"NotFound",
":",
"e",
"=",
"&",
"trace",
".",
"NotFoundError",
"{",
"Message",
":",
"message",
"}",
"\n",
"case",
"codes",
".",
"AlreadyExists",
":",
"e",
"=",
"&",
"trace",
".",
"AlreadyExistsError",
"{",
"Message",
":",
"message",
"}",
"\n",
"case",
"codes",
".",
"PermissionDenied",
":",
"e",
"=",
"&",
"trace",
".",
"AccessDeniedError",
"{",
"Message",
":",
"message",
"}",
"\n",
"case",
"codes",
".",
"FailedPrecondition",
":",
"e",
"=",
"&",
"trace",
".",
"CompareFailedError",
"{",
"Message",
":",
"message",
"}",
"\n",
"case",
"codes",
".",
"InvalidArgument",
":",
"e",
"=",
"&",
"trace",
".",
"BadParameterError",
"{",
"Message",
":",
"message",
"}",
"\n",
"case",
"codes",
".",
"ResourceExhausted",
":",
"e",
"=",
"&",
"trace",
".",
"LimitExceededError",
"{",
"Message",
":",
"message",
"}",
"\n",
"case",
"codes",
".",
"Unavailable",
":",
"e",
"=",
"&",
"trace",
".",
"ConnectionProblemError",
"{",
"Message",
":",
"message",
"}",
"\n",
"case",
"codes",
".",
"Unimplemented",
":",
"e",
"=",
"&",
"trace",
".",
"NotImplementedError",
"{",
"Message",
":",
"message",
"}",
"\n",
"default",
":",
"e",
"=",
"errors",
".",
"New",
"(",
"message",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"args",
")",
"!=",
"0",
"{",
"if",
"meta",
",",
"ok",
":=",
"args",
"[",
"0",
"]",
".",
"(",
"metadata",
".",
"MD",
")",
";",
"ok",
"{",
"e",
"=",
"DecodeDebugInfo",
"(",
"e",
",",
"meta",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"e",
"\n",
"}"
] | // FromGRPC converts error from GRPC error back to trace.Error
// Debug information will be retrieved from the metadata if specified in args | [
"FromGRPC",
"converts",
"error",
"from",
"GRPC",
"error",
"back",
"to",
"trace",
".",
"Error",
"Debug",
"information",
"will",
"be",
"retrieved",
"from",
"the",
"metadata",
"if",
"specified",
"in",
"args"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trail/trail.go#L114-L149 |
10,577 | gravitational/trace | trail/trail.go | DecodeDebugInfo | func DecodeDebugInfo(err error, meta metadata.MD) error {
if len(meta) == 0 {
return err
}
encoded, ok := meta[DebugReportMetadata]
if !ok || len(encoded) != 1 {
return err
}
data, decodeErr := base64.StdEncoding.DecodeString(encoded[0])
if decodeErr != nil {
return err
}
var raw trace.RawTrace
if unmarshalErr := json.Unmarshal(data, &raw); unmarshalErr != nil {
return err
}
if len(raw.Traces) != 0 && len(raw.Err) != 0 {
return &trace.TraceErr{Traces: raw.Traces, Err: err, Message: raw.Message}
}
return err
} | go | func DecodeDebugInfo(err error, meta metadata.MD) error {
if len(meta) == 0 {
return err
}
encoded, ok := meta[DebugReportMetadata]
if !ok || len(encoded) != 1 {
return err
}
data, decodeErr := base64.StdEncoding.DecodeString(encoded[0])
if decodeErr != nil {
return err
}
var raw trace.RawTrace
if unmarshalErr := json.Unmarshal(data, &raw); unmarshalErr != nil {
return err
}
if len(raw.Traces) != 0 && len(raw.Err) != 0 {
return &trace.TraceErr{Traces: raw.Traces, Err: err, Message: raw.Message}
}
return err
} | [
"func",
"DecodeDebugInfo",
"(",
"err",
"error",
",",
"meta",
"metadata",
".",
"MD",
")",
"error",
"{",
"if",
"len",
"(",
"meta",
")",
"==",
"0",
"{",
"return",
"err",
"\n",
"}",
"\n",
"encoded",
",",
"ok",
":=",
"meta",
"[",
"DebugReportMetadata",
"]",
"\n",
"if",
"!",
"ok",
"||",
"len",
"(",
"encoded",
")",
"!=",
"1",
"{",
"return",
"err",
"\n",
"}",
"\n",
"data",
",",
"decodeErr",
":=",
"base64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"encoded",
"[",
"0",
"]",
")",
"\n",
"if",
"decodeErr",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"raw",
"trace",
".",
"RawTrace",
"\n",
"if",
"unmarshalErr",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"raw",
")",
";",
"unmarshalErr",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"raw",
".",
"Traces",
")",
"!=",
"0",
"&&",
"len",
"(",
"raw",
".",
"Err",
")",
"!=",
"0",
"{",
"return",
"&",
"trace",
".",
"TraceErr",
"{",
"Traces",
":",
"raw",
".",
"Traces",
",",
"Err",
":",
"err",
",",
"Message",
":",
"raw",
".",
"Message",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // DecodeDebugInfo decodes debug information about error
// from the metadata and returns error with enriched metadata about it | [
"DecodeDebugInfo",
"decodes",
"debug",
"information",
"about",
"error",
"from",
"the",
"metadata",
"and",
"returns",
"error",
"with",
"enriched",
"metadata",
"about",
"it"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/trail/trail.go#L168-L188 |
10,578 | gravitational/trace | errors.go | NotFound | func NotFound(message string, args ...interface{}) error {
return WrapWithMessage(&NotFoundError{
Message: fmt.Sprintf(message, args...),
}, message, args...)
} | go | func NotFound(message string, args ...interface{}) error {
return WrapWithMessage(&NotFoundError{
Message: fmt.Sprintf(message, args...),
}, message, args...)
} | [
"func",
"NotFound",
"(",
"message",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"NotFoundError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"message",
",",
"args",
"...",
")",
",",
"}",
",",
"message",
",",
"args",
"...",
")",
"\n",
"}"
] | // NotFound returns new instance of not found error | [
"NotFound",
"returns",
"new",
"instance",
"of",
"not",
"found",
"error"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L29-L33 |
10,579 | gravitational/trace | errors.go | IsNotFound | func IsNotFound(e error) bool {
type nf interface {
IsNotFoundError() bool
}
err := Unwrap(e)
_, ok := err.(nf)
if !ok {
return os.IsNotExist(err)
}
return ok
} | go | func IsNotFound(e error) bool {
type nf interface {
IsNotFoundError() bool
}
err := Unwrap(e)
_, ok := err.(nf)
if !ok {
return os.IsNotExist(err)
}
return ok
} | [
"func",
"IsNotFound",
"(",
"e",
"error",
")",
"bool",
"{",
"type",
"nf",
"interface",
"{",
"IsNotFoundError",
"(",
")",
"bool",
"\n",
"}",
"\n",
"err",
":=",
"Unwrap",
"(",
"e",
")",
"\n",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"nf",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsNotFound returns whether this error is of NotFoundError type | [
"IsNotFound",
"returns",
"whether",
"this",
"error",
"is",
"of",
"NotFoundError",
"type"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L59-L69 |
10,580 | gravitational/trace | errors.go | AlreadyExists | func AlreadyExists(message string, args ...interface{}) error {
return WrapWithMessage(&AlreadyExistsError{
fmt.Sprintf(message, args...),
}, message, args...)
} | go | func AlreadyExists(message string, args ...interface{}) error {
return WrapWithMessage(&AlreadyExistsError{
fmt.Sprintf(message, args...),
}, message, args...)
} | [
"func",
"AlreadyExists",
"(",
"message",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"AlreadyExistsError",
"{",
"fmt",
".",
"Sprintf",
"(",
"message",
",",
"args",
"...",
")",
",",
"}",
",",
"message",
",",
"args",
"...",
")",
"\n",
"}"
] | // AlreadyExists returns a new instance of AlreadyExists error | [
"AlreadyExists",
"returns",
"a",
"new",
"instance",
"of",
"AlreadyExists",
"error"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L72-L76 |
10,581 | gravitational/trace | errors.go | IsAlreadyExists | func IsAlreadyExists(e error) bool {
type ae interface {
IsAlreadyExistsError() bool
}
_, ok := Unwrap(e).(ae)
return ok
} | go | func IsAlreadyExists(e error) bool {
type ae interface {
IsAlreadyExistsError() bool
}
_, ok := Unwrap(e).(ae)
return ok
} | [
"func",
"IsAlreadyExists",
"(",
"e",
"error",
")",
"bool",
"{",
"type",
"ae",
"interface",
"{",
"IsAlreadyExistsError",
"(",
")",
"bool",
"\n",
"}",
"\n",
"_",
",",
"ok",
":=",
"Unwrap",
"(",
"e",
")",
".",
"(",
"ae",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsAlreadyExists returns whether this is error indicating that object
// already exists | [
"IsAlreadyExists",
"returns",
"whether",
"this",
"is",
"error",
"indicating",
"that",
"object",
"already",
"exists"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L104-L110 |
10,582 | gravitational/trace | errors.go | BadParameter | func BadParameter(message string, args ...interface{}) error {
return WrapWithMessage(&BadParameterError{
Message: fmt.Sprintf(message, args...),
}, message, args...)
} | go | func BadParameter(message string, args ...interface{}) error {
return WrapWithMessage(&BadParameterError{
Message: fmt.Sprintf(message, args...),
}, message, args...)
} | [
"func",
"BadParameter",
"(",
"message",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"BadParameterError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"message",
",",
"args",
"...",
")",
",",
"}",
",",
"message",
",",
"args",
"...",
")",
"\n",
"}"
] | // BadParameter returns a new instance of BadParameterError | [
"BadParameter",
"returns",
"a",
"new",
"instance",
"of",
"BadParameterError"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L113-L117 |
10,583 | gravitational/trace | errors.go | IsBadParameter | func IsBadParameter(e error) bool {
type bp interface {
IsBadParameterError() bool
}
_, ok := Unwrap(e).(bp)
return ok
} | go | func IsBadParameter(e error) bool {
type bp interface {
IsBadParameterError() bool
}
_, ok := Unwrap(e).(bp)
return ok
} | [
"func",
"IsBadParameter",
"(",
"e",
"error",
")",
"bool",
"{",
"type",
"bp",
"interface",
"{",
"IsBadParameterError",
"(",
")",
"bool",
"\n",
"}",
"\n",
"_",
",",
"ok",
":=",
"Unwrap",
"(",
"e",
")",
".",
"(",
"bp",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsBadParameter returns whether this error is of BadParameterType | [
"IsBadParameter",
"returns",
"whether",
"this",
"error",
"is",
"of",
"BadParameterType"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L141-L147 |
10,584 | gravitational/trace | errors.go | NotImplemented | func NotImplemented(message string, args ...interface{}) error {
return WrapWithMessage(&NotImplementedError{
Message: fmt.Sprintf(message, args...),
}, message, args...)
} | go | func NotImplemented(message string, args ...interface{}) error {
return WrapWithMessage(&NotImplementedError{
Message: fmt.Sprintf(message, args...),
}, message, args...)
} | [
"func",
"NotImplemented",
"(",
"message",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"NotImplementedError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"message",
",",
"args",
"...",
")",
",",
"}",
",",
"message",
",",
"args",
"...",
")",
"\n",
"}"
] | // NotImplemented returns a new instance of NotImplementedError | [
"NotImplemented",
"returns",
"a",
"new",
"instance",
"of",
"NotImplementedError"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L150-L154 |
10,585 | gravitational/trace | errors.go | IsNotImplemented | func IsNotImplemented(e error) bool {
type ni interface {
IsNotImplementedError() bool
}
err, ok := Unwrap(e).(ni)
return ok && err.IsNotImplementedError()
} | go | func IsNotImplemented(e error) bool {
type ni interface {
IsNotImplementedError() bool
}
err, ok := Unwrap(e).(ni)
return ok && err.IsNotImplementedError()
} | [
"func",
"IsNotImplemented",
"(",
"e",
"error",
")",
"bool",
"{",
"type",
"ni",
"interface",
"{",
"IsNotImplementedError",
"(",
")",
"bool",
"\n",
"}",
"\n",
"err",
",",
"ok",
":=",
"Unwrap",
"(",
"e",
")",
".",
"(",
"ni",
")",
"\n",
"return",
"ok",
"&&",
"err",
".",
"IsNotImplementedError",
"(",
")",
"\n",
"}"
] | // IsNotImplemented returns whether this error is of NotImplementedError type | [
"IsNotImplemented",
"returns",
"whether",
"this",
"error",
"is",
"of",
"NotImplementedError",
"type"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L178-L184 |
10,586 | gravitational/trace | errors.go | CompareFailed | func CompareFailed(message string, args ...interface{}) error {
return WrapWithMessage(&CompareFailedError{Message: fmt.Sprintf(message, args...)}, message, args...)
} | go | func CompareFailed(message string, args ...interface{}) error {
return WrapWithMessage(&CompareFailedError{Message: fmt.Sprintf(message, args...)}, message, args...)
} | [
"func",
"CompareFailed",
"(",
"message",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"CompareFailedError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"message",
",",
"args",
"...",
")",
"}",
",",
"message",
",",
"args",
"...",
")",
"\n",
"}"
] | // CompareFailed returns new instance of CompareFailedError | [
"CompareFailed",
"returns",
"new",
"instance",
"of",
"CompareFailedError"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L187-L189 |
10,587 | gravitational/trace | errors.go | IsCompareFailed | func IsCompareFailed(e error) bool {
type cf interface {
IsCompareFailedError() bool
}
_, ok := Unwrap(e).(cf)
return ok
} | go | func IsCompareFailed(e error) bool {
type cf interface {
IsCompareFailedError() bool
}
_, ok := Unwrap(e).(cf)
return ok
} | [
"func",
"IsCompareFailed",
"(",
"e",
"error",
")",
"bool",
"{",
"type",
"cf",
"interface",
"{",
"IsCompareFailedError",
"(",
")",
"bool",
"\n",
"}",
"\n",
"_",
",",
"ok",
":=",
"Unwrap",
"(",
"e",
")",
".",
"(",
"cf",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsCompareFailed detects if this error is of CompareFailed type | [
"IsCompareFailed",
"detects",
"if",
"this",
"error",
"is",
"of",
"CompareFailed",
"type"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L216-L222 |
10,588 | gravitational/trace | errors.go | AccessDenied | func AccessDenied(message string, args ...interface{}) error {
return WrapWithMessage(&AccessDeniedError{
Message: fmt.Sprintf(message, args...),
}, message, args...)
} | go | func AccessDenied(message string, args ...interface{}) error {
return WrapWithMessage(&AccessDeniedError{
Message: fmt.Sprintf(message, args...),
}, message, args...)
} | [
"func",
"AccessDenied",
"(",
"message",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"AccessDeniedError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"message",
",",
"args",
"...",
")",
",",
"}",
",",
"message",
",",
"args",
"...",
")",
"\n",
"}"
] | // AccessDenied returns new instance of AccessDeniedError | [
"AccessDenied",
"returns",
"new",
"instance",
"of",
"AccessDeniedError"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L225-L229 |
10,589 | gravitational/trace | errors.go | IsAccessDenied | func IsAccessDenied(e error) bool {
type ad interface {
IsAccessDeniedError() bool
}
_, ok := Unwrap(e).(ad)
return ok
} | go | func IsAccessDenied(e error) bool {
type ad interface {
IsAccessDeniedError() bool
}
_, ok := Unwrap(e).(ad)
return ok
} | [
"func",
"IsAccessDenied",
"(",
"e",
"error",
")",
"bool",
"{",
"type",
"ad",
"interface",
"{",
"IsAccessDeniedError",
"(",
")",
"bool",
"\n",
"}",
"\n",
"_",
",",
"ok",
":=",
"Unwrap",
"(",
"e",
")",
".",
"(",
"ad",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsAccessDenied detects if this error is of AccessDeniedError type | [
"IsAccessDenied",
"detects",
"if",
"this",
"error",
"is",
"of",
"AccessDeniedError",
"type"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L255-L261 |
10,590 | gravitational/trace | errors.go | ConvertSystemError | func ConvertSystemError(err error) error {
innerError := Unwrap(err)
if os.IsExist(innerError) {
return WrapWithMessage(&AlreadyExistsError{Message: innerError.Error()}, innerError.Error())
}
if os.IsNotExist(innerError) {
return WrapWithMessage(&NotFoundError{Message: innerError.Error()}, innerError.Error())
}
if os.IsPermission(innerError) {
return WrapWithMessage(&AccessDeniedError{Message: innerError.Error()}, innerError.Error())
}
switch realErr := innerError.(type) {
case *net.OpError:
return WrapWithMessage(&ConnectionProblemError{
Message: realErr.Error(),
Err: realErr}, realErr.Error())
case *os.PathError:
message := fmt.Sprintf("failed to execute command %v error: %v", realErr.Path, realErr.Err)
return WrapWithMessage(&AccessDeniedError{
Message: message,
}, message)
case x509.SystemRootsError, x509.UnknownAuthorityError:
return wrapWithDepth(&TrustError{Err: innerError}, 2)
}
if _, ok := innerError.(net.Error); ok {
return WrapWithMessage(&ConnectionProblemError{
Message: innerError.Error(),
Err: innerError}, innerError.Error())
}
return err
} | go | func ConvertSystemError(err error) error {
innerError := Unwrap(err)
if os.IsExist(innerError) {
return WrapWithMessage(&AlreadyExistsError{Message: innerError.Error()}, innerError.Error())
}
if os.IsNotExist(innerError) {
return WrapWithMessage(&NotFoundError{Message: innerError.Error()}, innerError.Error())
}
if os.IsPermission(innerError) {
return WrapWithMessage(&AccessDeniedError{Message: innerError.Error()}, innerError.Error())
}
switch realErr := innerError.(type) {
case *net.OpError:
return WrapWithMessage(&ConnectionProblemError{
Message: realErr.Error(),
Err: realErr}, realErr.Error())
case *os.PathError:
message := fmt.Sprintf("failed to execute command %v error: %v", realErr.Path, realErr.Err)
return WrapWithMessage(&AccessDeniedError{
Message: message,
}, message)
case x509.SystemRootsError, x509.UnknownAuthorityError:
return wrapWithDepth(&TrustError{Err: innerError}, 2)
}
if _, ok := innerError.(net.Error); ok {
return WrapWithMessage(&ConnectionProblemError{
Message: innerError.Error(),
Err: innerError}, innerError.Error())
}
return err
} | [
"func",
"ConvertSystemError",
"(",
"err",
"error",
")",
"error",
"{",
"innerError",
":=",
"Unwrap",
"(",
"err",
")",
"\n\n",
"if",
"os",
".",
"IsExist",
"(",
"innerError",
")",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"AlreadyExistsError",
"{",
"Message",
":",
"innerError",
".",
"Error",
"(",
")",
"}",
",",
"innerError",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"innerError",
")",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"NotFoundError",
"{",
"Message",
":",
"innerError",
".",
"Error",
"(",
")",
"}",
",",
"innerError",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"os",
".",
"IsPermission",
"(",
"innerError",
")",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"AccessDeniedError",
"{",
"Message",
":",
"innerError",
".",
"Error",
"(",
")",
"}",
",",
"innerError",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"switch",
"realErr",
":=",
"innerError",
".",
"(",
"type",
")",
"{",
"case",
"*",
"net",
".",
"OpError",
":",
"return",
"WrapWithMessage",
"(",
"&",
"ConnectionProblemError",
"{",
"Message",
":",
"realErr",
".",
"Error",
"(",
")",
",",
"Err",
":",
"realErr",
"}",
",",
"realErr",
".",
"Error",
"(",
")",
")",
"\n",
"case",
"*",
"os",
".",
"PathError",
":",
"message",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"realErr",
".",
"Path",
",",
"realErr",
".",
"Err",
")",
"\n",
"return",
"WrapWithMessage",
"(",
"&",
"AccessDeniedError",
"{",
"Message",
":",
"message",
",",
"}",
",",
"message",
")",
"\n",
"case",
"x509",
".",
"SystemRootsError",
",",
"x509",
".",
"UnknownAuthorityError",
":",
"return",
"wrapWithDepth",
"(",
"&",
"TrustError",
"{",
"Err",
":",
"innerError",
"}",
",",
"2",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"innerError",
".",
"(",
"net",
".",
"Error",
")",
";",
"ok",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"ConnectionProblemError",
"{",
"Message",
":",
"innerError",
".",
"Error",
"(",
")",
",",
"Err",
":",
"innerError",
"}",
",",
"innerError",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // ConvertSystemError converts system error to appropriate trace error
// if it is possible, otherwise, returns original error | [
"ConvertSystemError",
"converts",
"system",
"error",
"to",
"appropriate",
"trace",
"error",
"if",
"it",
"is",
"possible",
"otherwise",
"returns",
"original",
"error"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L265-L296 |
10,591 | gravitational/trace | errors.go | ConnectionProblem | func ConnectionProblem(err error, message string, args ...interface{}) error {
return WrapWithMessage(&ConnectionProblemError{
Message: fmt.Sprintf(message, args...),
Err: err,
}, message, args...)
} | go | func ConnectionProblem(err error, message string, args ...interface{}) error {
return WrapWithMessage(&ConnectionProblemError{
Message: fmt.Sprintf(message, args...),
Err: err,
}, message, args...)
} | [
"func",
"ConnectionProblem",
"(",
"err",
"error",
",",
"message",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"ConnectionProblemError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"message",
",",
"args",
"...",
")",
",",
"Err",
":",
"err",
",",
"}",
",",
"message",
",",
"args",
"...",
")",
"\n",
"}"
] | // ConnectionProblem returns new instance of ConnectionProblemError | [
"ConnectionProblem",
"returns",
"new",
"instance",
"of",
"ConnectionProblemError"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L299-L304 |
10,592 | gravitational/trace | errors.go | IsConnectionProblem | func IsConnectionProblem(e error) bool {
type ad interface {
IsConnectionProblemError() bool
}
_, ok := Unwrap(e).(ad)
return ok
} | go | func IsConnectionProblem(e error) bool {
type ad interface {
IsConnectionProblemError() bool
}
_, ok := Unwrap(e).(ad)
return ok
} | [
"func",
"IsConnectionProblem",
"(",
"e",
"error",
")",
"bool",
"{",
"type",
"ad",
"interface",
"{",
"IsConnectionProblemError",
"(",
")",
"bool",
"\n",
"}",
"\n",
"_",
",",
"ok",
":=",
"Unwrap",
"(",
"e",
")",
".",
"(",
"ad",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsConnectionProblem returns whether this error is of ConnectionProblemError | [
"IsConnectionProblem",
"returns",
"whether",
"this",
"error",
"is",
"of",
"ConnectionProblemError"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L331-L337 |
10,593 | gravitational/trace | errors.go | LimitExceeded | func LimitExceeded(message string, args ...interface{}) error {
return WrapWithMessage(&LimitExceededError{
Message: fmt.Sprintf(message, args...),
}, message, args...)
} | go | func LimitExceeded(message string, args ...interface{}) error {
return WrapWithMessage(&LimitExceededError{
Message: fmt.Sprintf(message, args...),
}, message, args...)
} | [
"func",
"LimitExceeded",
"(",
"message",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"LimitExceededError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"message",
",",
"args",
"...",
")",
",",
"}",
",",
"message",
",",
"args",
"...",
")",
"\n",
"}"
] | // LimitExceeded returns whether new instance of LimitExceededError | [
"LimitExceeded",
"returns",
"whether",
"new",
"instance",
"of",
"LimitExceededError"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L340-L344 |
10,594 | gravitational/trace | errors.go | IsLimitExceeded | func IsLimitExceeded(e error) bool {
type ad interface {
IsLimitExceededError() bool
}
_, ok := Unwrap(e).(ad)
return ok
} | go | func IsLimitExceeded(e error) bool {
type ad interface {
IsLimitExceededError() bool
}
_, ok := Unwrap(e).(ad)
return ok
} | [
"func",
"IsLimitExceeded",
"(",
"e",
"error",
")",
"bool",
"{",
"type",
"ad",
"interface",
"{",
"IsLimitExceededError",
"(",
")",
"bool",
"\n",
"}",
"\n",
"_",
",",
"ok",
":=",
"Unwrap",
"(",
"e",
")",
".",
"(",
"ad",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsLimitExceeded detects if this error is of LimitExceededError | [
"IsLimitExceeded",
"detects",
"if",
"this",
"error",
"is",
"of",
"LimitExceededError"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L367-L373 |
10,595 | gravitational/trace | errors.go | IsTrustError | func IsTrustError(e error) bool {
type te interface {
IsTrustError() bool
}
_, ok := Unwrap(e).(te)
return ok
} | go | func IsTrustError(e error) bool {
type te interface {
IsTrustError() bool
}
_, ok := Unwrap(e).(te)
return ok
} | [
"func",
"IsTrustError",
"(",
"e",
"error",
")",
"bool",
"{",
"type",
"te",
"interface",
"{",
"IsTrustError",
"(",
")",
"bool",
"\n",
"}",
"\n",
"_",
",",
"ok",
":=",
"Unwrap",
"(",
"e",
")",
".",
"(",
"te",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsTrustError returns if this is a trust error | [
"IsTrustError",
"returns",
"if",
"this",
"is",
"a",
"trust",
"error"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L398-L404 |
10,596 | gravitational/trace | errors.go | OAuth2 | func OAuth2(code, message string, query url.Values) Error {
return WrapWithMessage(&OAuth2Error{
Code: code,
Message: message,
Query: query,
}, message)
} | go | func OAuth2(code, message string, query url.Values) Error {
return WrapWithMessage(&OAuth2Error{
Code: code,
Message: message,
Query: query,
}, message)
} | [
"func",
"OAuth2",
"(",
"code",
",",
"message",
"string",
",",
"query",
"url",
".",
"Values",
")",
"Error",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"OAuth2Error",
"{",
"Code",
":",
"code",
",",
"Message",
":",
"message",
",",
"Query",
":",
"query",
",",
"}",
",",
"message",
")",
"\n",
"}"
] | // OAuth2 returns new instance of OAuth2Error | [
"OAuth2",
"returns",
"new",
"instance",
"of",
"OAuth2Error"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L407-L413 |
10,597 | gravitational/trace | errors.go | Error | func (o *OAuth2Error) Error() string {
return fmt.Sprintf("OAuth2 error code=%v, message=%v", o.Code, o.Message)
} | go | func (o *OAuth2Error) Error() string {
return fmt.Sprintf("OAuth2 error code=%v, message=%v", o.Code, o.Message)
} | [
"func",
"(",
"o",
"*",
"OAuth2Error",
")",
"Error",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"o",
".",
"Code",
",",
"o",
".",
"Message",
")",
"\n",
"}"
] | //Error returns log friendly description of an error | [
"Error",
"returns",
"log",
"friendly",
"description",
"of",
"an",
"error"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L423-L425 |
10,598 | gravitational/trace | errors.go | IsOAuth2 | func IsOAuth2(e error) bool {
type oe interface {
IsOAuth2Error() bool
}
_, ok := Unwrap(e).(oe)
return ok
} | go | func IsOAuth2(e error) bool {
type oe interface {
IsOAuth2Error() bool
}
_, ok := Unwrap(e).(oe)
return ok
} | [
"func",
"IsOAuth2",
"(",
"e",
"error",
")",
"bool",
"{",
"type",
"oe",
"interface",
"{",
"IsOAuth2Error",
"(",
")",
"bool",
"\n",
"}",
"\n",
"_",
",",
"ok",
":=",
"Unwrap",
"(",
"e",
")",
".",
"(",
"oe",
")",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsOAuth2 returns if this is a OAuth2-related error | [
"IsOAuth2",
"returns",
"if",
"this",
"is",
"a",
"OAuth2",
"-",
"related",
"error"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L433-L439 |
10,599 | gravitational/trace | errors.go | Retry | func Retry(err error, message string, args ...interface{}) error {
return WrapWithMessage(&RetryError{
Message: fmt.Sprintf(message, args...),
Err: err,
}, message, args...)
} | go | func Retry(err error, message string, args ...interface{}) error {
return WrapWithMessage(&RetryError{
Message: fmt.Sprintf(message, args...),
Err: err,
}, message, args...)
} | [
"func",
"Retry",
"(",
"err",
"error",
",",
"message",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"WrapWithMessage",
"(",
"&",
"RetryError",
"{",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"message",
",",
"args",
"...",
")",
",",
"Err",
":",
"err",
",",
"}",
",",
"message",
",",
"args",
"...",
")",
"\n",
"}"
] | // Retry return new instance of RetryError which indicates a transient error type | [
"Retry",
"return",
"new",
"instance",
"of",
"RetryError",
"which",
"indicates",
"a",
"transient",
"error",
"type"
] | f30095ced5ff011085d26f160468dcc477607730 | https://github.com/gravitational/trace/blob/f30095ced5ff011085d26f160468dcc477607730/errors.go#L447-L452 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.