_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3 values | text stringlengths 52 85.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q17000 | PodStatus | train | func (r *marathonClient) PodStatus(name string) (*PodStatus, error) {
var podStatus PodStatus
if err := r.apiGet(buildPodStatusURI(name), nil, &podStatus); err != nil {
return nil, err
}
return &podStatus, nil
} | go | {
"resource": ""
} |
q17001 | PodStatuses | train | func (r *marathonClient) PodStatuses() ([]*PodStatus, error) {
var podStatuses []*PodStatus
if err := r.apiGet(buildPodStatusURI(""), nil, &podStatuses); err != nil {
return nil, err
}
return podStatuses, nil
} | go | {
"resource": ""
} |
q17002 | WaitOnPod | train | func (r *marathonClient) WaitOnPod(name string, timeout time.Duration) error {
return r.wait(name, timeout, r.PodIsRunning)
} | go | {
"resource": ""
} |
q17003 | PodIsRunning | train | func (r *marathonClient) PodIsRunning(name string) bool {
podStatus, err := r.PodStatus(name)
if apiErr, ok := err.(*APIError); ok && apiErr.ErrCode == ErrCodeNotFound {
return false
}
if err == nil && podStatus.Status == PodStateStable {
return true
}
return false
} | go | {
"resource": ""
} |
q17004 | SetName | train | func (rc *ReadinessCheck) SetName(name string) *ReadinessCheck {
rc.Name = &name
return rc
} | go | {
"resource": ""
} |
q17005 | SetProtocol | train | func (rc *ReadinessCheck) SetProtocol(proto string) *ReadinessCheck {
rc.Protocol = proto
return rc
} | go | {
"resource": ""
} |
q17006 | SetPath | train | func (rc *ReadinessCheck) SetPath(p string) *ReadinessCheck {
rc.Path = p
return rc
} | go | {
"resource": ""
} |
q17007 | SetPortName | train | func (rc *ReadinessCheck) SetPortName(name string) *ReadinessCheck {
rc.PortName = name
return rc
} | go | {
"resource": ""
} |
q17008 | SetInterval | train | func (rc *ReadinessCheck) SetInterval(interval time.Duration) *ReadinessCheck {
secs := int(interval.Seconds())
rc.IntervalSeconds = secs
return rc
} | go | {
"resource": ""
} |
q17009 | SetTimeout | train | func (rc *ReadinessCheck) SetTimeout(timeout time.Duration) *ReadinessCheck {
secs := int(timeout.Seconds())
rc.TimeoutSeconds = secs
return rc
} | go | {
"resource": ""
} |
q17010 | SetHTTPStatusCodesForReady | train | func (rc *ReadinessCheck) SetHTTPStatusCodesForReady(codes []int) *ReadinessCheck {
rc.HTTPStatusCodesForReady = &codes
return rc
} | go | {
"resource": ""
} |
q17011 | SetPreserveLastResponse | train | func (rc *ReadinessCheck) SetPreserveLastResponse(preserve bool) *ReadinessCheck {
rc.PreserveLastResponse = &preserve
return rc
} | go | {
"resource": ""
} |
q17012 | Deployments | train | func (r *marathonClient) Deployments() ([]*Deployment, error) {
var deployments []*Deployment
err := r.apiGet(marathonAPIDeployments, nil, &deployments)
if err != nil {
return nil, err
}
// Allows loading of deployment steps from the Marathon v1.X API
// Implements a fix for issue https://github.com/gambol99/go-marathon/issues/153
for _, deployment := range deployments {
// Unmarshal pre-v1.X step
if err := json.Unmarshal(deployment.XXStepsRaw, &deployment.Steps); err != nil {
deployment.Steps = make([][]*DeploymentStep, 0)
var steps []*StepActions
// Unmarshal v1.X Marathon step
if err := json.Unmarshal(deployment.XXStepsRaw, &steps); err != nil {
return nil, err
}
for stepIndex, step := range steps {
deployment.Steps = append(deployment.Steps, make([]*DeploymentStep, len(step.Actions)))
for actionIndex, action := range step.Actions {
var stepAction string
if action.Type != "" {
stepAction = action.Type
} else {
stepAction = action.Action
}
deployment.Steps[stepIndex][actionIndex] = &DeploymentStep{
Action: stepAction,
App: action.App,
}
}
}
}
}
return deployments, nil
} | go | {
"resource": ""
} |
q17013 | NewPodVolume | train | func NewPodVolume(name, path string) *PodVolume {
return &PodVolume{
Name: name,
Host: path,
}
} | go | {
"resource": ""
} |
q17014 | NewPodVolumeMount | train | func NewPodVolumeMount(name, mount string) *PodVolumeMount {
return &PodVolumeMount{
Name: name,
MountPath: mount,
}
} | go | {
"resource": ""
} |
q17015 | SetPersistentVolume | train | func (pv *PodVolume) SetPersistentVolume(p *PersistentVolume) *PodVolume {
pv.Persistent = p
return pv
} | go | {
"resource": ""
} |
q17016 | Info | train | func (r *marathonClient) Info() (*Info, error) {
info := new(Info)
if err := r.apiGet(marathonAPIInfo, nil, info); err != nil {
return nil, err
}
return info, nil
} | go | {
"resource": ""
} |
q17017 | Leader | train | func (r *marathonClient) Leader() (string, error) {
var leader struct {
Leader string `json:"leader"`
}
if err := r.apiGet(marathonAPILeader, nil, &leader); err != nil {
return "", err
}
return leader.Leader, nil
} | go | {
"resource": ""
} |
q17018 | AbdicateLeader | train | func (r *marathonClient) AbdicateLeader() (string, error) {
var message struct {
Message string `json:"message"`
}
if err := r.apiDelete(marathonAPILeader, nil, &message); err != nil {
return "", err
}
return message.Message, nil
} | go | {
"resource": ""
} |
q17019 | SetKind | train | func (i *PodContainerImage) SetKind(typ ImageType) *PodContainerImage {
i.Kind = typ
return i
} | go | {
"resource": ""
} |
q17020 | SetID | train | func (i *PodContainerImage) SetID(id string) *PodContainerImage {
i.ID = id
return i
} | go | {
"resource": ""
} |
q17021 | Groups | train | func (r *marathonClient) Groups() (*Groups, error) {
groups := new(Groups)
if err := r.apiGet(marathonAPIGroups, "", groups); err != nil {
return nil, err
}
return groups, nil
} | go | {
"resource": ""
} |
q17022 | buildAPIRequest | train | func (r *marathonClient) buildAPIRequest(method, path string, reader io.Reader) (request *http.Request, member string, err error) {
// Grab a member from the cluster
member, err = r.hosts.getMember()
if err != nil {
return nil, "", ErrMarathonDown
}
// Build the HTTP request to Marathon
request, err = r.client.buildMarathonJSONRequest(method, member, path, reader)
if err != nil {
return nil, member, newRequestError{err}
}
return request, member, nil
} | go | {
"resource": ""
} |
q17023 | oneLogLine | train | func oneLogLine(in []byte) []byte {
return bytes.Replace(oneLogLineRegex.ReplaceAll(in, nil), []byte("\n"), []byte("\\n "), -1)
} | go | {
"resource": ""
} |
q17024 | SetIPAddressPerTask | train | func (r *Application) SetIPAddressPerTask(ipAddressPerTask IPAddressPerTask) *Application {
r.Ports = make([]int, 0)
r.EmptyPortDefinitions()
r.IPAddressPerTask = &ipAddressPerTask
return r
} | go | {
"resource": ""
} |
q17025 | Command | train | func (r *Application) Command(cmd string) *Application {
r.Cmd = &cmd
return r
} | go | {
"resource": ""
} |
q17026 | AllTaskRunning | train | func (r *Application) AllTaskRunning() bool {
if r.Instances == nil || *r.Instances == 0 {
return true
}
if r.Tasks == nil {
return false
}
if r.TasksRunning == *r.Instances {
return true
}
return false
} | go | {
"resource": ""
} |
q17027 | AddPortDefinition | train | func (r *Application) AddPortDefinition(portDefinition PortDefinition) *Application {
if r.PortDefinitions == nil {
r.EmptyPortDefinitions()
}
portDefinitions := *r.PortDefinitions
portDefinitions = append(portDefinitions, portDefinition)
r.PortDefinitions = &portDefinitions
return r
} | go | {
"resource": ""
} |
q17028 | SetExecutor | train | func (r *Application) SetExecutor(executor string) *Application {
r.Executor = &executor
return r
} | go | {
"resource": ""
} |
q17029 | AddHealthCheck | train | func (r *Application) AddHealthCheck(healthCheck HealthCheck) *Application {
if r.HealthChecks == nil {
r.EmptyHealthChecks()
}
healthChecks := *r.HealthChecks
healthChecks = append(healthChecks, healthCheck)
r.HealthChecks = &healthChecks
return r
} | go | {
"resource": ""
} |
q17030 | HasHealthChecks | train | func (r *Application) HasHealthChecks() bool {
return r.HealthChecks != nil && len(*r.HealthChecks) > 0
} | go | {
"resource": ""
} |
q17031 | AddReadinessCheck | train | func (r *Application) AddReadinessCheck(readinessCheck ReadinessCheck) *Application {
if r.ReadinessChecks == nil {
r.EmptyReadinessChecks()
}
readinessChecks := *r.ReadinessChecks
readinessChecks = append(readinessChecks, readinessCheck)
r.ReadinessChecks = &readinessChecks
return r
} | go | {
"resource": ""
} |
q17032 | DeploymentIDs | train | func (r *Application) DeploymentIDs() []*DeploymentID {
var deployments []*DeploymentID
if r.Deployments == nil {
return deployments
}
// step: extract the deployment id from the result
for _, deploy := range r.Deployments {
if id, found := deploy["id"]; found {
deployment := &DeploymentID{
Version: r.Version,
DeploymentID: id,
}
deployments = append(deployments, deployment)
}
}
return deployments
} | go | {
"resource": ""
} |
q17033 | SetUpgradeStrategy | train | func (r *Application) SetUpgradeStrategy(us UpgradeStrategy) *Application {
r.UpgradeStrategy = &us
return r
} | go | {
"resource": ""
} |
q17034 | SetUnreachableStrategy | train | func (r *Application) SetUnreachableStrategy(us UnreachableStrategy) *Application {
r.UnreachableStrategy = &us
return r
} | go | {
"resource": ""
} |
q17035 | SetResidency | train | func (r *Application) SetResidency(whenLost TaskLostBehaviorType) *Application {
r.Residency = &Residency{
TaskLostBehavior: whenLost,
}
return r
} | go | {
"resource": ""
} |
q17036 | String | train | func (r *Application) String() string {
s, err := json.MarshalIndent(r, "", " ")
if err != nil {
return fmt.Sprintf(`{"error": "error decoding type into json: %s"}`, err)
}
return string(s)
} | go | {
"resource": ""
} |
q17037 | Applications | train | func (r *marathonClient) Applications(v url.Values) (*Applications, error) {
query := v.Encode()
if query != "" {
query = "?" + query
}
applications := new(Applications)
err := r.apiGet(marathonAPIApps+query, nil, applications)
if err != nil {
return nil, err
}
return applications, nil
} | go | {
"resource": ""
} |
q17038 | ListApplications | train | func (r *marathonClient) ListApplications(v url.Values) ([]string, error) {
applications, err := r.Applications(v)
if err != nil {
return nil, err
}
var list []string
for _, application := range applications.Apps {
list = append(list, application.ID)
}
return list, nil
} | go | {
"resource": ""
} |
q17039 | SetNetwork | train | func (r *Application) SetNetwork(name string, mode PodNetworkMode) *Application {
if r.Networks == nil {
r.EmptyNetworks()
}
network := PodNetwork{Name: name, Mode: mode}
networks := *r.Networks
networks = append(networks, network)
r.Networks = &networks
return r
} | go | {
"resource": ""
} |
q17040 | HasHealthCheckResults | train | func (r *Task) HasHealthCheckResults() bool {
return r.HealthCheckResults != nil && len(r.HealthCheckResults) > 0
} | go | {
"resource": ""
} |
q17041 | SetPort | train | func (p *PortDefinition) SetPort(port int) *PortDefinition {
if p.Port == nil {
p.EmptyPort()
}
p.Port = &port
return p
} | go | {
"resource": ""
} |
q17042 | UnmarshalJSON | train | func (p *Pod) UnmarshalJSON(b []byte) error {
aux := &struct {
*PodAlias
Env map[string]interface{} `json:"environment"`
Secrets map[string]TmpSecret `json:"secrets"`
}{
PodAlias: (*PodAlias)(p),
}
if err := json.Unmarshal(b, aux); err != nil {
return fmt.Errorf("malformed pod definition %v", err)
}
env := map[string]string{}
secrets := map[string]Secret{}
for envName, genericEnvValue := range aux.Env {
switch envValOrSecret := genericEnvValue.(type) {
case string:
env[envName] = envValOrSecret
case map[string]interface{}:
for secret, secretStore := range envValOrSecret {
if secStore, ok := secretStore.(string); ok && secret == "secret" {
secrets[secStore] = Secret{EnvVar: envName}
break
}
return fmt.Errorf("unexpected secret field %v of value type %T", secret, envValOrSecret[secret])
}
default:
return fmt.Errorf("unexpected environment variable type %T", envValOrSecret)
}
}
p.Env = env
for k, v := range aux.Secrets {
tmp := secrets[k]
tmp.Source = v.Source
secrets[k] = tmp
}
p.Secrets = secrets
return nil
} | go | {
"resource": ""
} |
q17043 | MarshalJSON | train | func (p *Pod) MarshalJSON() ([]byte, error) {
env := make(map[string]interface{})
secrets := make(map[string]TmpSecret)
if p.Env != nil {
for k, v := range p.Env {
env[string(k)] = string(v)
}
}
if p.Secrets != nil {
for k, v := range p.Secrets {
// Only add it to the root level pod environment if it's used
// Otherwise it's likely in one of the container environments
if v.EnvVar != "" {
env[v.EnvVar] = TmpEnvSecret{Secret: k}
}
secrets[k] = TmpSecret{v.Source}
}
}
aux := &struct {
*PodAlias
Env map[string]interface{} `json:"environment,omitempty"`
Secrets map[string]TmpSecret `json:"secrets,omitempty"`
}{PodAlias: (*PodAlias)(p), Env: env, Secrets: secrets}
return json.Marshal(aux)
} | go | {
"resource": ""
} |
q17044 | NewDefaultConfig | train | func NewDefaultConfig() Config {
return Config{
URL: "http://127.0.0.1:8080",
EventsTransport: EventsTransportCallback,
EventsPort: 10001,
EventsInterface: "eth0",
LogOutput: ioutil.Discard,
PollingWaitTime: defaultPollingWaitTime,
}
} | go | {
"resource": ""
} |
q17045 | newInvalidEndpointError | train | func newInvalidEndpointError(message string, args ...interface{}) error {
return &InvalidEndpointError{message: fmt.Sprintf(message, args...)}
} | go | {
"resource": ""
} |
q17046 | NewAPIError | train | func NewAPIError(code int, content []byte) error {
var errDef errorDefinition
switch {
case code == http.StatusBadRequest:
errDef = &badRequestDef{}
case code == http.StatusUnauthorized:
errDef = &simpleErrDef{code: ErrCodeUnauthorized}
case code == http.StatusForbidden:
errDef = &simpleErrDef{code: ErrCodeForbidden}
case code == http.StatusNotFound:
errDef = &simpleErrDef{code: ErrCodeNotFound}
case code == http.StatusMethodNotAllowed:
errDef = &simpleErrDef{code: ErrCodeMethodNotAllowed}
case code == http.StatusConflict:
errDef = &conflictDef{}
case code == 422:
errDef = &unprocessableEntityDef{}
case code >= http.StatusInternalServerError:
errDef = &simpleErrDef{code: ErrCodeServer}
default:
errDef = &simpleErrDef{code: ErrCodeUnknown}
}
return parseContent(errDef, content)
} | go | {
"resource": ""
} |
q17047 | NewPodContainer | train | func NewPodContainer() *PodContainer {
return &PodContainer{
Endpoints: []*PodEndpoint{},
Env: map[string]string{},
VolumeMounts: []*PodVolumeMount{},
Artifacts: []*PodArtifact{},
Labels: map[string]string{},
Resources: NewResources(),
}
} | go | {
"resource": ""
} |
q17048 | SetName | train | func (p *PodContainer) SetName(name string) *PodContainer {
p.Name = name
return p
} | go | {
"resource": ""
} |
q17049 | SetCommand | train | func (p *PodContainer) SetCommand(name string) *PodContainer {
p.Exec = &PodExec{
Command: PodCommand{
Shell: name,
},
}
return p
} | go | {
"resource": ""
} |
q17050 | CPUs | train | func (p *PodContainer) CPUs(cpu float64) *PodContainer {
p.Resources.Cpus = cpu
return p
} | go | {
"resource": ""
} |
q17051 | Memory | train | func (p *PodContainer) Memory(memory float64) *PodContainer {
p.Resources.Mem = memory
return p
} | go | {
"resource": ""
} |
q17052 | Storage | train | func (p *PodContainer) Storage(disk float64) *PodContainer {
p.Resources.Disk = disk
return p
} | go | {
"resource": ""
} |
q17053 | GPUs | train | func (p *PodContainer) GPUs(gpu int32) *PodContainer {
p.Resources.Gpus = gpu
return p
} | go | {
"resource": ""
} |
q17054 | AddEndpoint | train | func (p *PodContainer) AddEndpoint(endpoint *PodEndpoint) *PodContainer {
p.Endpoints = append(p.Endpoints, endpoint)
return p
} | go | {
"resource": ""
} |
q17055 | SetImage | train | func (p *PodContainer) SetImage(image *PodContainerImage) *PodContainer {
p.Image = image
return p
} | go | {
"resource": ""
} |
q17056 | EmptyEnvs | train | func (p *PodContainer) EmptyEnvs() *PodContainer {
p.Env = make(map[string]string)
return p
} | go | {
"resource": ""
} |
q17057 | AddEnv | train | func (p *PodContainer) AddEnv(name, value string) *PodContainer {
if p.Env == nil {
p = p.EmptyEnvs()
}
p.Env[name] = value
return p
} | go | {
"resource": ""
} |
q17058 | ExtendEnv | train | func (p *PodContainer) ExtendEnv(env map[string]string) *PodContainer {
if p.Env == nil {
p = p.EmptyEnvs()
}
for k, v := range env {
p.AddEnv(k, v)
}
return p
} | go | {
"resource": ""
} |
q17059 | AddSecret | train | func (p *PodContainer) AddSecret(name, secretName string) *PodContainer {
if p.Env == nil {
p = p.EmptyEnvs()
}
p.Env[name] = secretName
return p
} | go | {
"resource": ""
} |
q17060 | SetHealthCheck | train | func (p *PodContainer) SetHealthCheck(healthcheck *PodHealthCheck) *PodContainer {
p.HealthCheck = healthcheck
return p
} | go | {
"resource": ""
} |
q17061 | AddVolumeMount | train | func (p *PodContainer) AddVolumeMount(mount *PodVolumeMount) *PodContainer {
p.VolumeMounts = append(p.VolumeMounts, mount)
return p
} | go | {
"resource": ""
} |
q17062 | AddArtifact | train | func (p *PodContainer) AddArtifact(artifact *PodArtifact) *PodContainer {
p.Artifacts = append(p.Artifacts, artifact)
return p
} | go | {
"resource": ""
} |
q17063 | AddLabel | train | func (p *PodContainer) AddLabel(key, value string) *PodContainer {
p.Labels[key] = value
return p
} | go | {
"resource": ""
} |
q17064 | SetLifecycle | train | func (p *PodContainer) SetLifecycle(lifecycle PodLifecycle) *PodContainer {
p.Lifecycle = lifecycle
return p
} | go | {
"resource": ""
} |
q17065 | MarshalJSON | train | func (app *Application) MarshalJSON() ([]byte, error) {
env := make(map[string]interface{})
secrets := make(map[string]TmpSecret)
if app.Env != nil {
for k, v := range *app.Env {
env[string(k)] = string(v)
}
}
if app.Secrets != nil {
for k, v := range *app.Secrets {
env[v.EnvVar] = TmpEnvSecret{Secret: k}
secrets[k] = TmpSecret{v.Source}
}
}
aux := &struct {
*Alias
Env map[string]interface{} `json:"env,omitempty"`
Secrets map[string]TmpSecret `json:"secrets,omitempty"`
}{Alias: (*Alias)(app), Env: env, Secrets: secrets}
return json.Marshal(aux)
} | go | {
"resource": ""
} |
q17066 | pushRecord | train | func (s *scanner) pushRecord(state, pos int) {
s.stateRecord = append(s.stateRecord, Record{state:state, pos:pos}) //state are at even positions, pos are at odd positions in stateRecord array
} | go | {
"resource": ""
} |
q17067 | peekPos | train | func (s *scanner) peekPos() int {
if s.readPos >= len(s.stateRecord){
return s.cacheRecord.pos// peek can be called when the array is over , only if unmarshal error occured, so return last read position
}
if !s.cached {
s.cached = true
s.cacheRecord = s.stateRecord[s.readPos]
}
return s.cacheRecord.pos
} | go | {
"resource": ""
} |
q17068 | takeState | train | func (s *scanner) takeState() int {
if s.cached {
s.cached = false
}else{
s.peekState()
}
s.readPos += 1
return s.cacheRecord.state
} | go | {
"resource": ""
} |
q17069 | isNeededState | train | func (s *scanner) isNeededState(state int) bool {
if s.endLiteral {
return true
}
if state > scanEndArray || state < scanBeginLiteral {
return false
}
return true
} | go | {
"resource": ""
} |
q17070 | stateTru | train | func stateTru(s *scanner, c byte) int {
if c == 'e' {
s.step = stateEndValue
s.endLiteral = true
return scanContinue
}
return s.error(c, "in literal true (expecting 'e')")
} | go | {
"resource": ""
} |
q17071 | next | train | func (d *decodeState) next() []byte {
startop, start := d.peekRecord()
var endop int
switch startop {
case scanBeginArray:
endop = scanEndArray
case scanBeginObject:
endop = scanEndObject
case scanBeginLiteral:
endop = scanEndLiteral
default:
panic(errPhase)
}
count := 1 //counts number of open and not closed brackets.
d.skipRecord()
end := 0 //end of value
op := startop
for count != 0 { //we need here cycle because of nested objects and slices
op, end = d.takeRecord()
if op == startop {
count++
}
if op == endop {
count--
}
}
return d.data[start : end+1]
} | go | {
"resource": ""
} |
q17072 | takeRecord | train | func (d *decodeState) takeRecord() (int, int) {
return d.scan.peekState(), d.scan.takePos()
} | go | {
"resource": ""
} |
q17073 | GetEnv | train | func GetEnv(envName, defaultValue string) string {
value := os.Getenv(envName)
if value == "" {
return defaultValue
}
return value
} | go | {
"resource": ""
} |
q17074 | NewExpireCache | train | func NewExpireCache(ttl time.Duration) *ExpireCache {
return &ExpireCache{
cache: make(map[interface{}]*expireRecord),
ttl: ttl,
}
} | go | {
"resource": ""
} |
q17075 | Get | train | func (c *ExpireCache) Get(key interface{}) (interface{}, bool) {
c.mutex.Lock()
defer c.mutex.Unlock()
record, ok := c.cache[key]
if !ok {
c.stats.Miss++
return nil, ok
}
// Since this was recently accessed, keep it in
// the cache by resetting the expire time
record.ExpireAt = time.Now().UTC().Add(c.ttl)
c.stats.Hit++
return record.Value, ok
} | go | {
"resource": ""
} |
q17076 | Add | train | func (c *ExpireCache) Add(key interface{}, value interface{}) {
c.mutex.Lock()
defer c.mutex.Unlock()
record := expireRecord{
Value: value,
ExpireAt: time.Now().UTC().Add(c.ttl),
}
// Add the record to the cache
c.cache[key] = &record
} | go | {
"resource": ""
} |
q17077 | Update | train | func (c *ExpireCache) Update(key interface{}, value interface{}) error {
c.mutex.Lock()
defer c.mutex.Unlock()
record, ok := c.cache[key]
if !ok {
return errors.Errorf("ExpoireCache() - No record found for '%+v'", key)
}
record.Value = value
return nil
} | go | {
"resource": ""
} |
q17078 | Peek | train | func (c *ExpireCache) Peek(key interface{}) (value interface{}, ok bool) {
defer c.mutex.Unlock()
c.mutex.Lock()
if record, hit := c.cache[key]; hit {
return record.Value, true
}
return nil, false
} | go | {
"resource": ""
} |
q17079 | Each | train | func (c *ExpireCache) Each(concurrent int, callBack func(key interface{}, value interface{}) error) []error {
fanOut := NewFanOut(concurrent)
keys := c.Keys()
for _, key := range keys {
fanOut.Run(func(key interface{}) error {
c.mutex.Lock()
record, ok := c.cache[key]
c.mutex.Unlock()
if !ok {
return errors.Errorf("Each() - key '%+v' disapeared "+
"from cache during iteration", key)
}
err := callBack(key, record.Value)
if err != nil {
return err
}
c.mutex.Lock()
if record.ExpireAt.Before(time.Now().UTC()) {
delete(c.cache, key)
}
c.mutex.Unlock()
return nil
}, key)
}
// Wait for all the routines to complete
errs := fanOut.Wait()
if errs != nil {
return errs
}
return nil
} | go | {
"resource": ""
} |
q17080 | GetStats | train | func (c *ExpireCache) GetStats() ExpireCacheStats {
c.mutex.Lock()
c.stats.Size = int64(len(c.cache))
defer func() {
c.stats = ExpireCacheStats{}
c.mutex.Unlock()
}()
return c.stats
} | go | {
"resource": ""
} |
q17081 | Size | train | func (c *ExpireCache) Size() int64 {
defer c.mutex.Unlock()
c.mutex.Lock()
return int64(len(c.cache))
} | go | {
"resource": ""
} |
q17082 | Run | train | func (p *FanOut) Run(callBack func(interface{}) error, data interface{}) {
p.size <- true
go func() {
err := callBack(data)
if err != nil {
p.errChan <- err
}
<-p.size
}()
} | go | {
"resource": ""
} |
q17083 | Wait | train | func (p *FanOut) Wait() []error {
// Wait for all the routines to complete
for i := 0; i < cap(p.size); i++ {
p.size <- true
}
// Close the err channel
if p.errChan != nil {
close(p.errChan)
}
// Wait until the error collector routine is complete
p.wg.Wait()
// If there are no errors
if len(p.errs) == 0 {
return nil
}
return p.errs
} | go | {
"resource": ""
} |
q17084 | RandomRunes | train | func RandomRunes(prefix string, length int, runes ...string) string {
chars := strings.Join(runes, "")
var bytes = make([]byte, length)
rand.Read(bytes)
for i, b := range bytes {
bytes[i] = chars[b%byte(len(chars))]
}
return prefix + string(bytes)
} | go | {
"resource": ""
} |
q17085 | RandomAlpha | train | func RandomAlpha(prefix string, length int) string {
return RandomRunes(prefix, length, AlphaRunes)
} | go | {
"resource": ""
} |
q17086 | RandomString | train | func RandomString(prefix string, length int) string {
return RandomRunes(prefix, length, AlphaRunes, NumericRunes)
} | go | {
"resource": ""
} |
q17087 | RandomItem | train | func RandomItem(items ...string) string {
var bytes = make([]byte, 1)
rand.Read(bytes)
return items[bytes[0]%byte(len(items))]
} | go | {
"resource": ""
} |
q17088 | Advance | train | func Advance(d time.Duration) time.Duration {
ft, ok := provider.(*frozenTime)
if !ok {
panic("Freeze time first!")
}
ft.advance(d)
return Now().UTC().Sub(frozenAt)
} | go | {
"resource": ""
} |
q17089 | Wait4Scheduled | train | func Wait4Scheduled(count int, timeout time.Duration) bool {
return provider.Wait4Scheduled(count, timeout)
} | go | {
"resource": ""
} |
q17090 | AfterFunc | train | func AfterFunc(d time.Duration, f func()) Timer {
return provider.AfterFunc(d, f)
} | go | {
"resource": ""
} |
q17091 | SignRequest | train | func (s *Service) SignRequest(r *http.Request) error {
if s.secretKey == nil {
return fmt.Errorf("service not loaded with key.")
}
return s.SignRequestWithKey(r, s.secretKey)
} | go | {
"resource": ""
} |
q17092 | AuthenticateRequest | train | func (s *Service) AuthenticateRequest(r *http.Request) error {
if s.secretKey == nil {
return fmt.Errorf("service not loaded with key.")
}
return s.AuthenticateRequestWithKey(r, s.secretKey)
} | go | {
"resource": ""
} |
q17093 | AuthenticateRequestWithKey | train | func (s *Service) AuthenticateRequestWithKey(r *http.Request, secretKey []byte) (err error) {
// Emit a success or failure metric on return.
defer func() {
if err == nil {
s.metricsClient.Inc("success", 1, 1)
} else {
s.metricsClient.Inc("failure", 1, 1)
}
}()
// extract parameters
signature := r.Header.Get(s.config.SignatureHeaderName)
if signature == "" {
return fmt.Errorf("header not found: %v", s.config.SignatureHeaderName)
}
nonce := r.Header.Get(s.config.NonceHeaderName)
if nonce == "" {
return fmt.Errorf("header not found: %v", s.config.NonceHeaderName)
}
timestamp := r.Header.Get(s.config.TimestampHeaderName)
if timestamp == "" {
return fmt.Errorf("header not found: %v", s.config.TimestampHeaderName)
}
// extract request body bytes
bodyBytes, err := readBody(r)
if err != nil {
return err
}
// extract any headers if requested
headerValues, err := extractHeaderValues(r, s.config.HeadersToSign)
if err != nil {
return err
}
// check the hmac
isValid, err := checkMAC(secretKey, s.config.SignVerbAndURI, r.Method, r.URL.RequestURI(),
timestamp, nonce, bodyBytes, headerValues, signature)
if !isValid {
return err
}
// check timestamp
isValid, err = s.CheckTimestamp(timestamp)
if !isValid {
return err
}
// check to see if we have seen nonce before
inCache := s.nonceCache.InCache(nonce)
if inCache {
return fmt.Errorf("nonce already in cache: %v", nonce)
}
// set the body bytes we read in to nil to hint to the gc to pick it up
bodyBytes = nil
return nil
} | go | {
"resource": ""
} |
q17094 | CheckTimestamp | train | func (s *Service) CheckTimestamp(timestampHeader string) (bool, error) {
// convert unix timestamp string into time struct
timestamp, err := strconv.ParseInt(timestampHeader, 10, 0)
if err != nil {
return false, fmt.Errorf("unable to parse %v: %v", s.config.TimestampHeaderName, timestampHeader)
}
now := s.clock.Now().UTC().Unix()
// if timestamp is from the future, it's invalid
if timestamp >= now+MaxSkewSec {
return false, fmt.Errorf("timestamp header from the future; now: %v; %v: %v; difference: %v",
now, s.config.TimestampHeaderName, timestamp, timestamp-now)
}
// if the timestamp is older than ttl - skew, it's invalid
if timestamp <= now-int64(s.nonceCache.cacheTTL-MaxSkewSec) {
return false, fmt.Errorf("timestamp header too old; now: %v; %v: %v; difference: %v",
now, s.config.TimestampHeaderName, timestamp, now-timestamp)
}
return true, nil
} | go | {
"resource": ""
} |
q17095 | GetLastFrame | train | func GetLastFrame(frames errors.StackTrace) FrameInfo {
if len(frames) == 0 {
return FrameInfo{}
}
pc := uintptr(frames[0]) - 1
fn := runtime.FuncForPC(pc)
if fn == nil {
return FrameInfo{Func: fmt.Sprintf("unknown func at %v", pc)}
}
filePath, lineNo := fn.FileLine(pc)
return FrameInfo{
CallStack: GetCallStack(frames),
Func: FuncName(fn),
File: filePath,
LineNo: lineNo,
}
} | go | {
"resource": ""
} |
q17096 | New | train | func New(config *Config) (SecretService, error) {
var err error
var keyBytes *[SecretKeyLength]byte
var metricsClient metrics.Client
// Read in key from KeyPath or if not given, try getting them from KeyBytes.
if config.KeyPath != "" {
if keyBytes, err = ReadKeyFromDisk(config.KeyPath); err != nil {
return nil, err
}
} else {
if config.KeyBytes == nil {
return nil, errors.New("No key bytes provided.")
}
keyBytes = config.KeyBytes
}
// setup metrics service
if config.EmitStats {
// get hostname of box
hostname, err := os.Hostname()
if err != nil {
return nil, fmt.Errorf("failed to obtain hostname: %v", err)
}
// build lemma prefix
prefix := "lemma." + strings.Replace(hostname, ".", "_", -1)
if config.StatsdPrefix != "" {
prefix += "." + config.StatsdPrefix
}
// build metrics client
hostport := fmt.Sprintf("%v:%v", config.StatsdHost, config.StatsdPort)
metricsClient, err = metrics.NewWithOptions(hostport, prefix, metrics.Options{UseBuffering: true})
if err != nil {
return nil, err
}
} else {
// if you don't want to emit stats, use the nop client
metricsClient = metrics.NewNop()
}
return &Service{
secretKey: keyBytes,
metricsClient: metricsClient,
}, nil
} | go | {
"resource": ""
} |
q17097 | Seal | train | func Seal(value []byte, secretKey *[SecretKeyLength]byte) (SealedData, error) {
if secretKey == nil {
return nil, fmt.Errorf("secret key is nil")
}
secretService, err := New(&Config{KeyBytes: secretKey})
if err != nil {
return nil, err
}
return secretService.Seal(value)
} | go | {
"resource": ""
} |
q17098 | Open | train | func Open(e SealedData, secretKey *[SecretKeyLength]byte) ([]byte, error) {
if secretKey == nil {
return nil, fmt.Errorf("secret key is nil")
}
secretService, err := New(&Config{KeyBytes: secretKey})
if err != nil {
return nil, err
}
return secretService.Open(e)
} | go | {
"resource": ""
} |
q17099 | Seal | train | func (s *Service) Seal(value []byte) (SealedData, error) {
// generate nonce
nonce, err := generateNonce()
if err != nil {
return nil, fmt.Errorf("unable to generate nonce: %v", err)
}
// use nacl secret box to encrypt plaintext
var encrypted []byte
encrypted = secretbox.Seal(encrypted, value, nonce, s.secretKey)
// return sealed ciphertext
return &SealedBytes{
Ciphertext: encrypted,
Nonce: nonce[:],
}, nil
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.