_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fileinfo.go#L275-L334
func goFileInfo(path, rel string) fileInfo { info := fileNameInfo(path) fset := token.NewFileSet() pf, err := parser.ParseFile(fset, info.path, nil, parser.ImportsOnly|parser.ParseComments) if err != nil { log.Printf("%s: error reading go file: %v", info.path, err) return info } info.packageName = pf.Name.Name if info.isTest && strings.HasSuffix(info.packageName, "_test") { info.packageName = info.packageName[:len(info.packageName)-len("_test")] } for _, decl := range pf.Decls { d, ok := decl.(*ast.GenDecl) if !ok { continue } for _, dspec := range d.Specs { spec, ok := dspec.(*ast.ImportSpec) if !ok { continue } quoted := spec.Path.Value path, err := strconv.Unquote(quoted) if err != nil { log.Printf("%s: error reading go file: %v", info.path, err) continue } if path == "C" { if info.isTest { log.Printf("%s: warning: use of cgo in test not supported", info.path) } info.isCgo = true cg := spec.Doc if cg == nil && len(d.Specs) == 1 { cg = d.Doc } if cg != nil { if err := saveCgo(&info, rel, cg); err != nil { log.Printf("%s: error reading go file: %v", info.path, err) } } continue } info.imports = append(info.imports, path) } } tags, err := readTags(info.path) if err != nil { log.Printf("%s: error reading go file: %v", info.path, err) return info } info.tags = tags return info }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/benchmark.go#L39-L84
func LaunchContainers(c lxd.ContainerServer, count int, parallel int, image string, privileged bool, start bool, freeze bool) (time.Duration, error) { var duration time.Duration batchSize, err := getBatchSize(parallel) if err != nil { return duration, err } printTestConfig(count, batchSize, image, privileged, freeze) fingerprint, err := ensureImage(c, image) if err != nil { return duration, err } batchStart := func(index int, wg *sync.WaitGroup) { defer wg.Done() name := getContainerName(count, index) err := createContainer(c, fingerprint, name, privileged) if err != nil { logf("Failed to launch container '%s': %s", name, err) return } if start { err := startContainer(c, name) if err != nil { logf("Failed to start container '%s': %s", name, err) return } if freeze { err := freezeContainer(c, name) if err != nil { logf("Failed to freeze container '%s': %s", name, err) return } } } } duration = processBatch(count, batchSize, batchStart) return duration, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2909-L2913
func (v *GetResourceTreeReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage30(&r, v) return r.Error() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L288-L290
func NewDryRunClient(getToken func() []byte, graphqlEndpoint string, bases ...string) *Client { return NewDryRunClientWithFields(logrus.Fields{}, getToken, graphqlEndpoint, bases...) }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/value.go#L33-L62
func (t Type) String() string { switch t { case Nil: return "nil" case Bool: return "bool" case Int: return "int" case Uint: return "uint" case Float: return "float" case String: return "string" case Bytes: return "bytes" case Time: return "time" case Duration: return "duration" case Error: return "error" case Array: return "array" case Map: return "map" default: return "<type>" } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/progress.go#L232-L242
func (in *inflights) growBuf() { newSize := len(in.buffer) * 2 if newSize == 0 { newSize = 1 } else if newSize > in.size { newSize = in.size } newBuffer := make([]uint64, newSize) copy(newBuffer, in.buffer) in.buffer = newBuffer }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/keepalive_listener.go#L89-L94
func newTLSKeepaliveListener(inner net.Listener, config *tls.Config) net.Listener { l := &tlsKeepaliveListener{} l.Listener = inner l.config = config return l }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L1313-L1376
func unbindServiceInstance(w http.ResponseWriter, r *http.Request, t auth.Token) error { instanceName, appName, serviceName := r.URL.Query().Get(":instance"), r.URL.Query().Get(":app"), r.URL.Query().Get(":service") noRestart, _ := strconv.ParseBool(InputValue(r, "noRestart")) force, _ := strconv.ParseBool(InputValue(r, "force")) instance, a, err := getServiceInstance(serviceName, instanceName, appName) if err != nil { return err } allowed := permission.Check(t, permission.PermServiceInstanceUpdateUnbind, append(permission.Contexts(permTypes.CtxTeam, instance.Teams), permission.Context(permTypes.CtxServiceInstance, instance.Name), )..., ) if !allowed { return permission.ErrUnauthorized } allowed = permission.Check(t, permission.PermAppUpdateUnbind, contextsForApp(a)..., ) if !allowed { return permission.ErrUnauthorized } if force { s, errGet := service.Get(instance.ServiceName) if errGet != nil { return errGet } allowed = permission.Check(t, permission.PermServiceUpdate, contextsForServiceProvision(&s)..., ) if !allowed { return permission.ErrUnauthorized } } evt, err := event.New(&event.Opts{ Target: appTarget(appName), Kind: permission.PermAppUpdateUnbind, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(a)...), }) if err != nil { return err } defer func() { evt.Done(err) }() w.Header().Set("Content-Type", "application/x-json-stream") keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "") defer keepAliveWriter.Stop() writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)} evt.SetLogWriter(writer) err = instance.UnbindApp(service.UnbindAppArgs{ App: a, Restart: !noRestart, ForceRemove: force, Event: evt, RequestID: requestIDHeader(r), }) if err != nil { return err } fmt.Fprintf(evt, "\nInstance %q is not bound to the app %q anymore.\n", instanceName, appName) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L3051-L3055
func (v *GetResourceContentReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage32(&r, v) return r.Error() }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peer.go#L534-L536
func (p *Peer) Connect(ctx context.Context) (*Connection, error) { return p.channel.Connect(ctx, p.hostPort) }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L829-L831
func Debug(val ...interface{}) error { return glg.out(DEBG, blankFormat(len(val)), val...) }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/context.go#L206-L208
func (c *Context) Query() bson.M { return bson.M{"$and": append([]bson.M{c.Selector}, c.Filters...)} }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/pretty/pretty.go#L80-L89
func PrintPipelineInfo(w io.Writer, pipelineInfo *ppsclient.PipelineInfo, fullTimestamps bool) { fmt.Fprintf(w, "%s\t", pipelineInfo.Pipeline.Name) fmt.Fprintf(w, "%s\t", ShorthandInput(pipelineInfo.Input)) if fullTimestamps { fmt.Fprintf(w, "%s\t", pipelineInfo.CreatedAt.String()) } else { fmt.Fprintf(w, "%s\t", pretty.Ago(pipelineInfo.CreatedAt)) } fmt.Fprintf(w, "%s / %s\t\n", pipelineState(pipelineInfo.State), jobState(pipelineInfo.LastJobState)) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/server.go#L1779-L1793
func (s *EtcdServer) sync(timeout time.Duration) { req := pb.Request{ Method: "SYNC", ID: s.reqIDGen.Next(), Time: time.Now().UnixNano(), } data := pbutil.MustMarshal(&req) // There is no promise that node has leader when do SYNC request, // so it uses goroutine to propose. ctx, cancel := context.WithTimeout(s.ctx, timeout) s.goAttach(func() { s.r.Propose(ctx, data) cancel() }) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2679-L2683
func (v *RemoveBreakpointParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger27(&r, v) return r.Error() }
https://github.com/adamzy/cedar-go/blob/80a9c64b256db37ac20aff007907c649afb714f1/api.go#L95-L110
func (da *Cedar) Update(key []byte, value int) error { p := da.get(key, 0, 0) // key was not inserted if *p == ValueLimit { *p = value return nil } // key was inserted before if *p+value < 0 || *p+value >= ValueLimit { return ErrInvalidValue } *p += value return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/easyjson.go#L142-L146
func (v TakeResponseBodyAsStreamParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoFetch1(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/gerrit/reporter/reporter.go#L62-L112
func (c *Client) ShouldReport(pj *v1.ProwJob) bool { if pj.Status.State == v1.TriggeredState || pj.Status.State == v1.PendingState { // not done yet logrus.WithField("prowjob", pj.ObjectMeta.Name).Info("PJ not finished") return false } if pj.Status.State == v1.AbortedState { // aborted (new patchset) logrus.WithField("prowjob", pj.ObjectMeta.Name).Info("PJ aborted") return false } // has gerrit metadata (scheduled by gerrit adapter) if pj.ObjectMeta.Annotations[client.GerritID] == "" || pj.ObjectMeta.Annotations[client.GerritInstance] == "" || pj.ObjectMeta.Labels[client.GerritRevision] == "" { logrus.WithField("prowjob", pj.ObjectMeta.Name).Info("Not a gerrit job") return false } // Only report when all jobs of the same type on the same revision finished selector := labels.Set{ client.GerritRevision: pj.ObjectMeta.Labels[client.GerritRevision], kube.ProwJobTypeLabel: pj.ObjectMeta.Labels[kube.ProwJobTypeLabel], } if pj.ObjectMeta.Labels[client.GerritReportLabel] == "" { // Shouldn't happen, adapter should already have defaulted to Code-Review logrus.Errorf("Gerrit report label not set for job %s", pj.Spec.Job) } else { selector[client.GerritReportLabel] = pj.ObjectMeta.Labels[client.GerritReportLabel] } pjs, err := c.lister.List(selector.AsSelector()) if err != nil { logrus.WithError(err).Errorf("Cannot list prowjob with selector %v", selector) return false } for _, pjob := range pjs { if pjob.Status.State == v1.TriggeredState || pjob.Status.State == v1.PendingState { // other jobs with same label are still running on this revision, skip report logrus.WithField("prowjob", pjob.ObjectMeta.Name).Info("Other jobs with same label are still running on this revision") return false } } return true }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L207-L217
func (a *Action) MandatoryParams() []*ActionParam { m := make([]*ActionParam, len(a.Params)) i := 0 for _, p := range a.Params { if p.Mandatory { m[i] = p i++ } } return m[:i] }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/guest.go#L703-L736
func (g *Guest) RunProgram(path, args string, options RunProgramOption) (uint64, int, int, error) { var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE var err C.VixError = C.VIX_OK var pid *C.uint64 var elapsedtime *C.int var exitCode *C.int cpath := C.CString(path) cargs := C.CString(args) defer C.free(unsafe.Pointer(cpath)) defer C.free(unsafe.Pointer(cargs)) jobHandle = C.VixVM_RunProgramInGuest(g.handle, cpath, //guestProgramName cargs, //commandLineArgs C.VixRunProgramOptions(options), //options C.VIX_INVALID_HANDLE, //propertyListHandle nil, // callbackProc nil) // clientData defer C.Vix_ReleaseHandle(jobHandle) err = C.get_program_output(jobHandle, pid, elapsedtime, exitCode) if C.VIX_OK != err { return 0, 0, 0, &Error{ Operation: "guest.RunProgram", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } return uint64(*pid), int(*elapsedtime), int(*exitCode), nil }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L557-L590
func (v *VM) Clone(cloneType CloneType, destVmxFile string) (*VM, error) { var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE var clonedHandle C.VixHandle = C.VIX_INVALID_HANDLE var err C.VixError = C.VIX_OK dstVmxFile := C.CString(destVmxFile) defer C.free(unsafe.Pointer(dstVmxFile)) jobHandle = C.VixVM_Clone(v.handle, C.VIX_INVALID_HANDLE, // snapshotHandle C.VixCloneType(cloneType), // cloneType dstVmxFile, // destConfigPathName 0, // options, C.VIX_INVALID_HANDLE, // propertyListHandle nil, // callbackProc nil) // clientData defer C.Vix_ReleaseHandle(jobHandle) err = C.get_vix_handle(jobHandle, C.VIX_PROPERTY_JOB_RESULT_HANDLE, &clonedHandle, C.VIX_PROPERTY_NONE) if C.VIX_OK != err { return nil, &Error{ Operation: "vm.Clone", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } return NewVirtualMachine(clonedHandle, destVmxFile) }
https://github.com/codemodus/kace/blob/e3ecf78ee2a5e58652cb2be34d3159ad9c89acf8/kace.go#L100-L102
func (k *Kace) Snake(s string) string { return delimitedCase(s, snakeDelim, false) }
https://github.com/knq/sdhook/blob/41b9ccbff0b5fa5a56fbdccf2eb8653e7afe8d4b/sdhook.go#L80-L121
func New(opts ...Option) (*StackdriverHook, error) { var err error sh := &StackdriverHook{ levels: logrus.AllLevels, } // apply opts for _, o := range opts { err = o(sh) if err != nil { return nil, err } } // check service, resource, logName set if sh.service == nil && sh.agentClient == nil { return nil, errors.New("no stackdriver service was provided") } if sh.resource == nil && sh.agentClient == nil { return nil, errors.New("the monitored resource was not provided") } if sh.projectID == "" && sh.agentClient == nil { return nil, errors.New("the project id was not provided") } // set default project name if sh.logName == "" { err = LogName(DefaultName)(sh) if err != nil { return nil, err } } // If error reporting log name not set, set it to log name // plus string suffix if sh.errorReportingLogName == "" { sh.errorReportingLogName = sh.logName + "_errors" } return sh, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L226-L233
func (in *ProwJobSpec) DeepCopy() *ProwJobSpec { if in == nil { return nil } out := new(ProwJobSpec) in.DeepCopyInto(out) return out }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/pool.go#L262-L295
func poolUpdateHandler(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { allowed := permission.Check(t, permission.PermPoolUpdate) if !allowed { return permission.ErrUnauthorized } poolName := r.URL.Query().Get(":name") evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypePool, Value: poolName}, Kind: permission.PermPoolUpdate, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermPoolReadEvents, permission.Context(permTypes.CtxPool, poolName)), }) if err != nil { return err } defer func() { evt.Done(err) }() var updateOpts pool.UpdatePoolOptions err = ParseInput(r, &updateOpts) if err != nil { return err } err = pool.PoolUpdate(poolName, updateOpts) if err == pool.ErrPoolNotFound { return &terrors.HTTP{Code: http.StatusNotFound, Message: err.Error()} } if err == pool.ErrDefaultPoolAlreadyExists { return &terrors.HTTP{ Code: http.StatusConflict, Message: err.Error(), } } return err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/easyjson.go#L475-L479
func (v *SynthesizeScrollGestureParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoInput2(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L974-L978
func (v SetBreakpointReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger10(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/plugins.go#L208-L223
func (pa *ConfigAgent) Load(path string) error { b, err := ioutil.ReadFile(path) if err != nil { return err } np := &Configuration{} if err := yaml.Unmarshal(b, np); err != nil { return err } if err := np.Validate(); err != nil { return err } pa.Set(np) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1497-L1501
func (v *EventTargetCrashed) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget16(&r, v) return r.Error() }
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/router/wildcard.go#L16-L21
func Wildcard(path string) *wildcard { matches := strings.Split(path, "/") return &wildcard{ matches: matches, } }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L176-L178
func (img *IplImage) Set(value Scalar) { C.cvSet(unsafe.Pointer(img), (C.CvScalar)(value), nil) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L778-L780
func (api *API) CurrentUserLocator(href string) *CurrentUserLocator { return &CurrentUserLocator{Href(href), api} }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L123-L126
func (m *Map) GetString(name string) string { m.schema.assertKeyType(name, String) return m.GetRaw(name) }
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L792-L819
func (p *PubSub) SubscribeByTopicDescriptor(td *pb.TopicDescriptor, opts ...SubOpt) (*Subscription, error) { if td.GetAuth().GetMode() != pb.TopicDescriptor_AuthOpts_NONE { return nil, fmt.Errorf("auth mode not yet supported") } if td.GetEnc().GetMode() != pb.TopicDescriptor_EncOpts_NONE { return nil, fmt.Errorf("encryption mode not yet supported") } sub := &Subscription{ topic: td.GetName(), } for _, opt := range opts { err := opt(sub) if err != nil { return nil, err } } out := make(chan *Subscription, 1) p.addSub <- &addSubReq{ sub: sub, resp: out, } return <-out, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/type_filter_wrapper.go#L55-L61
func (t *TypeFilterWrapperPlugin) CheckFlags() error { if t.pullRequests && t.issues { return fmt.Errorf( "you can't ignore both pull-requests and issues") } return nil }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/access_log_apache.go#L210-L215
func (u *accessLogUtil) StatusCode() int { if u.R.Env["STATUS_CODE"] != nil { return u.R.Env["STATUS_CODE"].(int) } return 0 }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/rpcerror/grpc.go#L15-L20
func UnaryServerInterceptor(fn ConvertFunc) grpc.UnaryServerInterceptor { return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { resp, err = handler(ctx, req) return resp, fn(err) } }
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L182-L211
func (c *Client) stdPagedQuery(service *bigquery.Service, pageSize int, dataset, project, queryStr string, dataChan chan Data) ([][]interface{}, []string, error) { c.printDebug("std paged query") datasetRef := &bigquery.DatasetReference{ DatasetId: dataset, ProjectId: project, } query := &bigquery.QueryRequest{ DefaultDataset: datasetRef, MaxResults: int64(pageSize), Kind: "json", Query: queryStr, } qr, err := service.Jobs.Query(project, query).Do() // extract the initial rows that have already been returned with the Query headers, rows := c.headersAndRows(qr.Schema, qr.Rows) if err != nil { c.printDebug("Error loading query: ", err) if dataChan != nil { dataChan <- Data{Err: err} } return nil, nil, err } return c.processPagedQuery(qr.JobReference, qr.PageToken, dataChan, headers, rows) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/types.go#L629-L631
func (t *MonotonicTime) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/history/history.go#L140-L153
func (h *History) Record(poolKey, action, baseSHA, err string, targets []prowapi.Pull) { t := now() sort.Sort(ByNum(targets)) h.addRecord( poolKey, &Record{ Time: t, Action: action, BaseSHA: baseSHA, Target: targets, Err: err, }, ) }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/get_apps_app_routes_route_parameters.go#L115-L118
func (o *GetAppsAppRoutesRouteParams) WithApp(app string) *GetAppsAppRoutesRouteParams { o.SetApp(app) return o }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/termios/termios_windows.go#L34-L42
func MakeRaw(fd int) (*State, error) { state, err := terminal.MakeRaw(fd) if err != nil { return nil, err } oldState := State(*state) return &oldState, nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L157-L161
func (wb *WriteBatch) Error() error { wb.Lock() defer wb.Unlock() return wb.err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/mason/storage.go#L53-L55
func (s *Storage) UpdateConfig(conf common.ResourcesConfig) error { return s.configs.Update(conf) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2525-L2529
func (v RestartFrameReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger25(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L3122-L3126
func (v GetResourceContentParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage33(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/cmd/gazelle/metaresolver.go#L47-L49
func (mr *metaResolver) MappedKind(pkgRel string, kind config.MappedKind) { mr.mappedKinds[pkgRel] = append(mr.mappedKinds[pkgRel], kind) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L39-L45
func NewAPIAnalyzer(resources map[string]interface{}, attributeTypes map[string]string) *APIAnalyzer { return &APIAnalyzer{ rawResources: resources, attributeTypes: attributeTypes, rawTypes: make(map[string][]*gen.ObjectDataType), } }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/post_apps_app_routes_parameters.go#L95-L98
func (o *PostAppsAppRoutesParams) WithContext(ctx context.Context) *PostAppsAppRoutesParams { o.SetContext(ctx) return o }
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/database/elasticsearch/elasticsearch.go#L82-L126
func (db *Database) Init() error { // Create URL from host/port db.getURL() // Test connection to ElasticSearch err := db.TestConnection() if err != nil { return errors.Wrap(err, "failed to connect to database") } client, err := elastic.NewSimpleClient( elastic.SetURL(db.URL), elastic.SetBasicAuth( utils.Getopts(db.Username, "MALICE_ELASTICSEARCH_USERNAME", ""), utils.Getopts(db.Password, "MALICE_ELASTICSEARCH_PASSWORD", ""), ), ) if err != nil { return errors.Wrap(err, "failed to create elasticsearch simple client") } exists, err := client.IndexExists(db.Index).Do(context.Background()) if err != nil { return errors.Wrap(err, "failed to check if index exists") } if !exists { // Index does not exist yet. createIndex, err := client.CreateIndex(db.Index).BodyString(mapping).Do(context.Background()) if err != nil { return errors.Wrapf(err, "failed to create index: %s", db.Index) } if !createIndex.Acknowledged { log.Error("index creation not acknowledged") } else { log.Debugf("created index %s", db.Index) } } else { log.Debugf("index %s already exists", db.Index) } return nil }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L325-L331
func Map(arr []string, iterator func(string) string) []string { r := []string{} for _, item := range arr { r = append(r, iterator(item)) } return r }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L942-L951
func (c *Cluster) ImageGetNodesWithoutImage(fingerprint string) ([]string, error) { q := ` SELECT DISTINCT nodes.address FROM nodes WHERE nodes.address NOT IN ( SELECT DISTINCT nodes.address FROM nodes LEFT JOIN images_nodes ON images_nodes.node_id = nodes.id LEFT JOIN images ON images_nodes.image_id = images.id WHERE images.fingerprint = ?) ` return c.getNodesByImageFingerprint(q, fingerprint) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/wal/wal.go#L97-L224
func Create(lg *zap.Logger, dirpath string, metadata []byte) (*WAL, error) { if Exist(dirpath) { return nil, os.ErrExist } // keep temporary wal directory so WAL initialization appears atomic tmpdirpath := filepath.Clean(dirpath) + ".tmp" if fileutil.Exist(tmpdirpath) { if err := os.RemoveAll(tmpdirpath); err != nil { return nil, err } } if err := fileutil.CreateDirAll(tmpdirpath); err != nil { if lg != nil { lg.Warn( "failed to create a temporary WAL directory", zap.String("tmp-dir-path", tmpdirpath), zap.String("dir-path", dirpath), zap.Error(err), ) } return nil, err } p := filepath.Join(tmpdirpath, walName(0, 0)) f, err := fileutil.LockFile(p, os.O_WRONLY|os.O_CREATE, fileutil.PrivateFileMode) if err != nil { if lg != nil { lg.Warn( "failed to flock an initial WAL file", zap.String("path", p), zap.Error(err), ) } return nil, err } if _, err = f.Seek(0, io.SeekEnd); err != nil { if lg != nil { lg.Warn( "failed to seek an initial WAL file", zap.String("path", p), zap.Error(err), ) } return nil, err } if err = fileutil.Preallocate(f.File, SegmentSizeBytes, true); err != nil { if lg != nil { lg.Warn( "failed to preallocate an initial WAL file", zap.String("path", p), zap.Int64("segment-bytes", SegmentSizeBytes), zap.Error(err), ) } return nil, err } w := &WAL{ lg: lg, dir: dirpath, metadata: metadata, } w.encoder, err = newFileEncoder(f.File, 0) if err != nil { return nil, err } w.locks = append(w.locks, f) if err = w.saveCrc(0); err != nil { return nil, err } if err = w.encoder.encode(&walpb.Record{Type: metadataType, Data: metadata}); err != nil { return nil, err } if err = w.SaveSnapshot(walpb.Snapshot{}); err != nil { return nil, err } if w, err = w.renameWAL(tmpdirpath); err != nil { if lg != nil { lg.Warn( "failed to rename the temporary WAL directory", zap.String("tmp-dir-path", tmpdirpath), zap.String("dir-path", w.dir), zap.Error(err), ) } return nil, err } // directory was renamed; sync parent dir to persist rename pdir, perr := fileutil.OpenDir(filepath.Dir(w.dir)) if perr != nil { if lg != nil { lg.Warn( "failed to open the parent data directory", zap.String("parent-dir-path", filepath.Dir(w.dir)), zap.String("dir-path", w.dir), zap.Error(perr), ) } return nil, perr } if perr = fileutil.Fsync(pdir); perr != nil { if lg != nil { lg.Warn( "failed to fsync the parent data directory file", zap.String("parent-dir-path", filepath.Dir(w.dir)), zap.String("dir-path", w.dir), zap.Error(perr), ) } return nil, perr } if perr = pdir.Close(); err != nil { if lg != nil { lg.Warn( "failed to close the parent data directory file", zap.String("parent-dir-path", filepath.Dir(w.dir)), zap.String("dir-path", w.dir), zap.Error(perr), ) } return nil, perr } return w, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L1940-L1957
func listCertificates(w http.ResponseWriter, r *http.Request, t auth.Token) error { a, err := getAppFromContext(r.URL.Query().Get(":app"), r) if err != nil { return err } allowed := permission.Check(t, permission.PermAppReadCertificate, contextsForApp(&a)..., ) if !allowed { return permission.ErrUnauthorized } w.Header().Set("Content-Type", "application/json") result, err := a.GetCertificates() if err != nil { return err } return json.NewEncoder(w).Encode(&result) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/repository/repository.go#L68-L77
func Manager() RepositoryManager { managerName, err := config.GetString("repo-manager") if err != nil { managerName = defaultManager } if _, ok := managers[managerName]; !ok { managerName = "nop" } return managers[managerName] }
https://github.com/btcsuite/btclog/blob/84c8d2346e9fc8c7b947e243b9c24e6df9fd206a/log.go#L432-L437
func (l *slog) Errorf(format string, args ...interface{}) { lvl := l.Level() if lvl <= LevelError { l.b.printf("ERR", l.tag, format, args...) } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/codegen_client.go#L1009-L1011
func (r *IpAddressBinding) Locator(api *API) *IpAddressBindingLocator { return api.IpAddressBindingLocator(r.Href) }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L211-L213
func IncrementExisting(c context.Context, key string, delta int64) (newValue uint64, err error) { return incr(c, key, delta, nil) }
https://github.com/fgrid/uuid/blob/6f72a2d331c927473b9b19f590d43ccb5018c844/v5.go#L7-L11
func NewV5(namespaceUUID *UUID, name []byte) *UUID { uuid := newByHash(sha1.New(), namespaceUUID, name) uuid[6] = (uuid[6] & 0x0f) | 0x50 return uuid }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gexec/build.go#L29-L31
func Build(packagePath string, args ...string) (compiledPath string, err error) { return doBuild(build.Default.GOPATH, packagePath, nil, args...) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/plugin/vault/pachyderm/helpers.go#L14-L16
func errMissingField(field string) *logical.Response { return logical.ErrorResponse(fmt.Sprintf("missing required field '%s'", field)) }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/snapshot.go#L162-L167
func cleanupSnapshot(s *Snapshot) { if s.handle != C.VIX_INVALID_HANDLE { C.Vix_ReleaseHandle(s.handle) s.handle = C.VIX_INVALID_HANDLE } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cert/logging_conn.go#L61-L67
func (p *loggingPipe) clientConn() *loggingConn { return &loggingConn{ pipe: p, r: p.clientReader, w: p.serverWriter, } }
https://github.com/knq/sdhook/blob/41b9ccbff0b5fa5a56fbdccf2eb8653e7afe8d4b/opts.go#L138-L143
func Labels(labels map[string]string) Option { return func(sh *StackdriverHook) error { sh.labels = labels return nil } }
https://github.com/jayeshsolanki93/devgorant/blob/69fb03e5c3b1da904aacf77240e04d85dd8e1c3c/devrant.go#L26-L47
func (c *Client) Rants(sort string, limit int, skip int) ([]RantModel, error) { if sort == "" { sort = "algo" } else if (sort != "algo") && (sort != "recent") && (sort != "top") { return nil, errors.New("Invalid string in sort method") } if limit <= 0 { limit = 50 } url := fmt.Sprintf(RANTS_PATH, API, sort, limit, skip, APP_VERSION) res, err := http.Get(url) if err != nil { return nil, err } var data RantsResponse json.NewDecoder(res.Body).Decode(&data) if !data.Success && data.Error != "" { return nil, errors.New(data.Error) } return data.Rants, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L185-L206
func (c *ClusterTx) NodeRename(old, new string) error { count, err := query.Count(c.tx, "nodes", "name=?", new) if err != nil { return errors.Wrap(err, "failed to check existing nodes") } if count != 0 { return ErrAlreadyDefined } stmt := `UPDATE nodes SET name=? WHERE name=?` result, err := c.tx.Exec(stmt, new, old) if err != nil { return errors.Wrap(err, "failed to update node name") } n, err := result.RowsAffected() if err != nil { return errors.Wrap(err, "failed to get rows count") } if n != 1 { return fmt.Errorf("expected to update one row, not %d", n) } return nil }
https://github.com/VividCortex/ewma/blob/43880d236f695d39c62cf7aa4ebd4508c258e6c0/ewma.go#L40-L47
func NewMovingAverage(age ...float64) MovingAverage { if len(age) == 0 || age[0] == AVG_METRIC_AGE { return new(SimpleEWMA) } return &VariableEWMA{ decay: 2 / (age[0] + 1), } }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/auth/oauth/oauth.go#L61-L109
func (s *OAuthScheme) loadConfig() (oauth2.Config, error) { if s.BaseConfig.ClientID != "" { return s.BaseConfig, nil } if s.Parser == nil { s.Parser = s } var emptyConfig oauth2.Config clientId, err := config.GetString("auth:oauth:client-id") if err != nil { return emptyConfig, err } clientSecret, err := config.GetString("auth:oauth:client-secret") if err != nil { return emptyConfig, err } scope, err := config.GetString("auth:oauth:scope") if err != nil { return emptyConfig, err } authURL, err := config.GetString("auth:oauth:auth-url") if err != nil { return emptyConfig, err } tokenURL, err := config.GetString("auth:oauth:token-url") if err != nil { return emptyConfig, err } infoURL, err := config.GetString("auth:oauth:info-url") if err != nil { return emptyConfig, err } callbackPort, err := config.GetInt("auth:oauth:callback-port") if err != nil { log.Debugf("auth:oauth:callback-port not found using random port: %s", err) } s.InfoURL = infoURL s.CallbackPort = callbackPort s.BaseConfig = oauth2.Config{ ClientID: clientId, ClientSecret: clientSecret, Scopes: []string{scope}, Endpoint: oauth2.Endpoint{ AuthURL: authURL, TokenURL: tokenURL, }, } return s.BaseConfig, nil }
https://github.com/Financial-Times/base-ft-rw-app-go/blob/1ea8a13e1f37b95318cd965796558d932750f407/baseftrwapp/baseftapp.go#L132-L141
func OutputMetricsIfRequired(graphiteTCPAddress string, graphitePrefix string, logMetrics bool) { if graphiteTCPAddress != "" { addr, _ := net.ResolveTCPAddr("tcp", graphiteTCPAddress) go graphite.Graphite(metrics.DefaultRegistry, 5*time.Second, graphitePrefix, addr) } if logMetrics { //useful locally //messy use of the 'standard' log package here as this method takes the log struct, not an interface, so can't use logrus.Logger go metrics.Log(metrics.DefaultRegistry, 60*time.Second, standardLog.New(os.Stdout, "metrics", standardLog.Lmicroseconds)) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/easyjson.go#L416-L420
func (v GetDOMStorageItemsReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomstorage3(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L212-L226
func (gc *GraphicContext) FillStroke(paths ...*draw2d.Path) { var rule string if gc.Current.FillRule != draw2d.FillRuleWinding { rule = "*" } _, _, _, alphaS := gc.Current.StrokeColor.RGBA() _, _, _, alphaF := gc.Current.FillColor.RGBA() if alphaS == alphaF { gc.draw("FD"+rule, alphaF, paths...) } else { gc.draw("F"+rule, alphaF, paths...) gc.draw("S", alphaS, paths...) } gc.Current.Path.Clear() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/cache.go#L77-L95
func (c *MergeCache) Merge(w *Writer, base io.Reader, filter Filter) (retErr error) { var trees []*Reader if base != nil { trees = append(trees, NewReader(base, filter)) } for _, key := range c.Keys() { r, err := c.Cache.Get(key) if err != nil { return err } defer func() { if err := r.Close(); err != nil && retErr == nil { retErr = err } }() trees = append(trees, NewReader(r, filter)) } return Merge(w, trees) }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/cloudconfig_manifest_primatives.go#L37-L46
func (s *CloudConfigManifest) ContainsAZName(azName string) (result bool) { result = false for _, az := range s.AZs { if az.Name == azName { result = true return } } return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1779-L1815
func (c *Client) UnrequestReview(org, repo string, number int, logins []string) error { c.log("UnrequestReview", org, repo, number, logins) var pr PullRequest body, err := prepareReviewersBody(logins, org) if len(body) == 0 { // No point in doing request for none, // if some logins didn't make it to body, extras.Users will catch them. return err } _, err = c.request(&request{ method: http.MethodDelete, path: fmt.Sprintf("/repos/%s/%s/pulls/%d/requested_reviewers", org, repo, number), accept: "application/vnd.github.symmetra-preview+json", requestBody: body, exitCodes: []int{http.StatusOK /*200*/}, }, &pr) if err != nil { return err } extras := ExtraUsers{action: "remove the PR review request for"} for _, user := range pr.RequestedReviewers { found := false for _, toDelete := range logins { if NormLogin(user.Login) == NormLogin(toDelete) { found = true break } } if found { extras.Users = append(extras.Users, user.Login) } } if len(extras.Users) > 0 { return extras } return nil }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/api_client.go#L169-L171
func (c Client) Request(method, path string, query url.Values, body io.Reader, accept []string) (resp *http.Response, err error) { return c.RequestContext(nil, method, path, query, body, accept) }
https://github.com/pandemicsyn/oort/blob/fca1d3baddc1d944387cc8bbe8b21f911ec9091b/oort/cmdctrl.go#L106-L109
func (o *Server) shutdownFinished() { time.Sleep(10 * time.Millisecond) close(o.ShutdownComplete) }
https://github.com/skyrings/skyring-common/blob/d1c0bb1cbd5ed8438be1385c85c4f494608cde1e/dbprovider/mongodb/user.go#L28-L36
func (m MongoDb) User(username string) (user models.User, e error) { c := m.Connect(models.COLL_NAME_USER) defer m.Close(c) err := c.Find(bson.M{"username": username}).One(&user) if err != nil { return user, ErrMissingUser } return user, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/kubernetes_cluster_clients.go#L146-L156
func (o *ExperimentalKubernetesOptions) InfrastructureClusterClient(dryRun bool) (kubernetesClient kubernetes.Interface, err error) { if err := o.resolve(dryRun); err != nil { return nil, err } if o.dryRun { return nil, errors.New("no dry-run kubernetes client is supported in dry-run mode") } return o.kubernetesClientsByContext[kube.InClusterContext], nil }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/mnemosyned/daemon.go#L142-L290
func (d *Daemon) Run() (err error) { var ( cl *cluster.Cluster tracer opentracing.Tracer ) if cl, err = initCluster(d.logger, d.opts.ClusterListenAddr, d.opts.ClusterSeeds...); err != nil { return } if err = d.initStorage(d.logger, d.opts.PostgresTable, d.opts.PostgresSchema); err != nil { return } interceptor := promgrpc.NewInterceptor(promgrpc.InterceptorOpts{}) if d.opts.TracingAgentAddress != "" { if tracer, d.tracerCloser, err = initJaeger( constant.Subsystem, d.opts.ClusterListenAddr, d.opts.TracingAgentAddress, d.logger.Named("tracer"), ); err != nil { return } d.logger.Info("tracing enabled", zap.String("agent_address", d.opts.TracingAgentAddress)) } else { tracer = opentracing.NoopTracer{} } d.clientOptions = []grpc.DialOption{ // User agent is required for example to determine if incoming request is internal. grpc.WithUserAgent(fmt.Sprintf("%s:%s", constant.Subsystem, d.opts.Version)), grpc.WithStatsHandler(interceptor), grpc.WithDialer(interceptor.Dialer(func(addr string, timeout time.Duration) (net.Conn, error) { return net.DialTimeout("tcp", addr, timeout) })), grpc.WithUnaryInterceptor(unaryClientInterceptors( interceptor.UnaryClient(), otgrpc.OpenTracingClientInterceptor(tracer)), ), grpc.WithStreamInterceptor(interceptor.StreamClient()), } d.serverOptions = []grpc.ServerOption{ grpc.StatsHandler(interceptor), grpc.UnaryInterceptor(unaryServerInterceptors( otgrpc.OpenTracingServerInterceptor(tracer), errorInterceptor(d.logger), interceptor.UnaryServer(), )), } if d.opts.TLS { servCreds, err := credentials.NewServerTLSFromFile(d.opts.TLSCertFile, d.opts.TLSKeyFile) if err != nil { return err } d.serverOptions = append(d.serverOptions, grpc.Creds(servCreds)) clientCreds, err := credentials.NewClientTLSFromFile(d.opts.TLSCertFile, "") if err != nil { return err } d.clientOptions = append(d.clientOptions, grpc.WithTransportCredentials(clientCreds)) } else { d.clientOptions = append(d.clientOptions, grpc.WithInsecure()) } d.server = grpc.NewServer(d.serverOptions...) cache := cache.New(5*time.Second, constant.Subsystem) mnemosyneServer, err := newSessionManager(sessionManagerOpts{ addr: d.opts.ClusterListenAddr, cluster: cl, logger: d.logger, storage: d.storage, ttc: d.opts.SessionTTC, cache: cache, tracer: tracer, }) if err != nil { return err } mnemosynerpc.RegisterSessionManagerServer(d.server, mnemosyneServer) grpc_health_v1.RegisterHealthServer(d.server, health.NewServer()) if !d.opts.IsTest { prometheus.DefaultRegisterer.Register(d.storage.(storage.InstrumentedStorage)) prometheus.DefaultRegisterer.Register(cache) prometheus.DefaultRegisterer.Register(mnemosyneServer) prometheus.DefaultRegisterer.Register(interceptor) promgrpc.RegisterInterceptor(d.server, interceptor) } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err = cl.Connect(ctx, d.clientOptions...); err != nil { return err } go func() { d.logger.Info("rpc server is running", zap.String("address", d.rpcListener.Addr().String())) if err := d.server.Serve(d.rpcListener); err != nil { if err == grpc.ErrServerStopped { d.logger.Info("grpc server has been stopped") return } if !strings.Contains(err.Error(), "use of closed network connection") { d.logger.Error("rpc server failure", zap.Error(err)) } } }() if d.debugListener != nil { go func() { d.logger.Info("debug server is running", zap.String("address", d.debugListener.Addr().String())) mux := http.NewServeMux() mux.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index)) mux.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline)) mux.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile)) mux.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol)) mux.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace)) mux.Handle("/metrics", promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{})) mux.Handle("/healthz", &livenessHandler{ livenessResponse: livenessResponse{ Version: d.opts.Version, }, logger: d.logger, }) mux.Handle("/healthr", &readinessHandler{ livenessResponse: livenessResponse{ Version: d.opts.Version, }, logger: d.logger, postgres: d.postgres, cluster: cl, }) if err := http.Serve(d.debugListener, mux); err != nil { d.logger.Error("debug server failure", zap.Error(err)) } }() } go mnemosyneServer.cleanup(d.done) return }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L368-L377
func (o *MapByteOption) Set(value string) error { parts := stringMapRegex.Split(value, 2) if len(parts) != 2 { return fmt.Errorf("expected KEY=VALUE got '%s'", value) } val := ByteOption{} val.Set(parts[1]) (*o)[parts[0]] = val return nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/inbound.go#L151-L195
func (c *Connection) dispatchInbound(_ uint32, _ uint32, call *InboundCall, frame *Frame) { if call.log.Enabled(LogLevelDebug) { call.log.Debugf("Received incoming call for %s from %s", call.ServiceName(), c.remotePeerInfo) } if err := call.readMethod(); err != nil { call.log.WithFields( LogField{"remotePeer", c.remotePeerInfo}, ErrField(err), ).Error("Couldn't read method.") c.opts.FramePool.Release(frame) return } call.commonStatsTags["endpoint"] = call.methodString call.statsReporter.IncCounter("inbound.calls.recvd", call.commonStatsTags, 1) if span := call.response.span; span != nil { span.SetOperationName(call.methodString) } // TODO(prashant): This is an expensive way to check for cancellation. Use a heap for timeouts. go func() { select { case <-call.mex.ctx.Done(): // checking if message exchange timedout or was cancelled // only two possible errors at this step: // context.DeadlineExceeded // context.Canceled if call.mex.ctx.Err() != nil { call.mex.inboundExpired() } case <-call.mex.errCh.c: if c.log.Enabled(LogLevelDebug) { call.log.Debugf("Wait for timeout/cancellation interrupted by error: %v", call.mex.errCh.err) } // when an exchange errors out, mark the exchange as expired // and call cancel so the server handler's context is canceled // TODO: move the cancel to the parent context at connnection level call.response.cancel() call.mex.inboundExpired() } }() c.handler.Handle(call.mex.ctx, call) }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L1257-L1377
func (r *Raft) installSnapshot(rpc RPC, req *InstallSnapshotRequest) { defer metrics.MeasureSince([]string{"raft", "rpc", "installSnapshot"}, time.Now()) // Setup a response resp := &InstallSnapshotResponse{ Term: r.getCurrentTerm(), Success: false, } var rpcErr error defer func() { io.Copy(ioutil.Discard, rpc.Reader) // ensure we always consume all the snapshot data from the stream [see issue #212] rpc.Respond(resp, rpcErr) }() // Sanity check the version if req.SnapshotVersion < SnapshotVersionMin || req.SnapshotVersion > SnapshotVersionMax { rpcErr = fmt.Errorf("unsupported snapshot version %d", req.SnapshotVersion) return } // Ignore an older term if req.Term < r.getCurrentTerm() { r.logger.Info(fmt.Sprintf("Ignoring installSnapshot request with older term of %d vs currentTerm %d", req.Term, r.getCurrentTerm())) return } // Increase the term if we see a newer one if req.Term > r.getCurrentTerm() { // Ensure transition to follower r.setState(Follower) r.setCurrentTerm(req.Term) resp.Term = req.Term } // Save the current leader r.setLeader(ServerAddress(r.trans.DecodePeer(req.Leader))) // Create a new snapshot var reqConfiguration Configuration var reqConfigurationIndex uint64 if req.SnapshotVersion > 0 { reqConfiguration = decodeConfiguration(req.Configuration) reqConfigurationIndex = req.ConfigurationIndex } else { reqConfiguration = decodePeers(req.Peers, r.trans) reqConfigurationIndex = req.LastLogIndex } version := getSnapshotVersion(r.protocolVersion) sink, err := r.snapshots.Create(version, req.LastLogIndex, req.LastLogTerm, reqConfiguration, reqConfigurationIndex, r.trans) if err != nil { r.logger.Error(fmt.Sprintf("Failed to create snapshot to install: %v", err)) rpcErr = fmt.Errorf("failed to create snapshot: %v", err) return } // Spill the remote snapshot to disk n, err := io.Copy(sink, rpc.Reader) if err != nil { sink.Cancel() r.logger.Error(fmt.Sprintf("Failed to copy snapshot: %v", err)) rpcErr = err return } // Check that we received it all if n != req.Size { sink.Cancel() r.logger.Error(fmt.Sprintf("Failed to receive whole snapshot: %d / %d", n, req.Size)) rpcErr = fmt.Errorf("short read") return } // Finalize the snapshot if err := sink.Close(); err != nil { r.logger.Error(fmt.Sprintf("Failed to finalize snapshot: %v", err)) rpcErr = err return } r.logger.Info(fmt.Sprintf("Copied %d bytes to local snapshot", n)) // Restore snapshot future := &restoreFuture{ID: sink.ID()} future.init() select { case r.fsmMutateCh <- future: case <-r.shutdownCh: future.respond(ErrRaftShutdown) return } // Wait for the restore to happen if err := future.Error(); err != nil { r.logger.Error(fmt.Sprintf("Failed to restore snapshot: %v", err)) rpcErr = err return } // Update the lastApplied so we don't replay old logs r.setLastApplied(req.LastLogIndex) // Update the last stable snapshot info r.setLastSnapshot(req.LastLogIndex, req.LastLogTerm) // Restore the peer set r.configurations.latest = reqConfiguration r.configurations.latestIndex = reqConfigurationIndex r.configurations.committed = reqConfiguration r.configurations.committedIndex = reqConfigurationIndex // Compact logs, continue even if this fails if err := r.compactLogs(req.LastLogIndex); err != nil { r.logger.Error(fmt.Sprintf("Failed to compact logs: %v", err)) } r.logger.Info("Installed remote snapshot") resp.Success = true r.setLastContact() return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/clientset/versioned/typed/prowjobs/v1/fake/fake_prowjob.go#L105-L113
func (c *FakeProwJobs) UpdateStatus(prowJob *prowjobsv1.ProwJob) (*prowjobsv1.ProwJob, error) { obj, err := c.Fake. Invokes(testing.NewUpdateSubresourceAction(prowjobsResource, "status", c.ns, prowJob), &prowjobsv1.ProwJob{}) if obj == nil { return nil, err } return obj.(*prowjobsv1.ProwJob), err }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L330-L335
func txUnmarkRaw(st *State) { if reflect.ValueOf(st.sa).Type() == rawStringType { st.sa = string(interfaceToString(st.sa)) } st.Advance() }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L68-L73
func Pipe(s string, funcs ...func(string) string) string { for _, fn := range funcs { s = fn(s) } return s }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/schema.go#L49-L54
func (s Schema) assertKeyType(name string, code Type) { key := s.mustGetKey(name) if key.Type != code { panic(fmt.Sprintf("key '%s' has type code %d, not %d", name, key.Type, code)) } }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection.go#L53-L63
func (s *Selection) Elements() ([]*api.Element, error) { elements, err := s.elements.Get() if err != nil { return nil, err } apiElements := []*api.Element{} for _, selectedElement := range elements { apiElements = append(apiElements, selectedElement.(*api.Element)) } return apiElements, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/types.go#L332-L374
func (n *Node) xpath(stopAtDocument, stopAtID bool) string { n.RLock() defer n.RUnlock() p := "" pos := "" id := n.AttributeValue("id") switch { case n.Parent == nil: return n.LocalName case stopAtDocument && n.NodeType == NodeTypeDocument: return "" case stopAtID && id != "": p = "/" pos = `[@id='` + id + `']` case n.Parent != nil: var i int var found bool n.Parent.RLock() for j := 0; j < len(n.Parent.Children); j++ { if n.Parent.Children[j].LocalName == n.LocalName { i++ } if n.Parent.Children[j].NodeID == n.NodeID { found = true break } } n.Parent.RUnlock() if found { pos = "[" + strconv.Itoa(i) + "]" } p = n.Parent.xpath(stopAtDocument, stopAtID) } return p + "/" + n.LocalName + pos }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/api_server.go#L266-L299
func (a *apiServer) retrieveOrGeneratePPSToken() { var tokenProto types.StringValue // will contain PPS token ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() b := backoff.NewExponentialBackOff() b.MaxElapsedTime = 60 * time.Second b.MaxInterval = 5 * time.Second if err := backoff.Retry(func() error { if _, err := col.NewSTM(ctx, a.env.GetEtcdClient(), func(stm col.STM) error { superUserTokenCol := col.NewCollection(a.env.GetEtcdClient(), ppsconsts.PPSTokenKey, nil, &types.StringValue{}, nil, nil).ReadWrite(stm) // TODO(msteffen): Don't use an empty key, as it will not be erased by // superUserTokenCol.DeleteAll() err := superUserTokenCol.Get("", &tokenProto) if err == nil { return nil } if col.IsErrNotFound(err) { // no existing token yet -- generate token token := uuid.NewWithoutDashes() tokenProto.Value = token if err := superUserTokenCol.Create("", &tokenProto); err != nil { return err } } return nil }); err != nil { return err } a.ppsToken = tokenProto.Value return nil }, b); err != nil { panic(fmt.Sprintf("couldn't create/retrieve PPS superuser token within 60s of starting up: %v", err)) } }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L321-L372
func (gc *GraphicContext) embedSvgFont(text string) *Font { fontName := gc.Current.FontData.Name gc.loadCurrentFont() // find or create font Element svgFont := (*Font)(nil) for _, font := range gc.svg.Fonts { if font.Name == fontName { svgFont = font break } } if svgFont == nil { // create new svgFont = &Font{} // and attach gc.svg.Fonts = append(gc.svg.Fonts, svgFont) } // fill with glyphs gc.Save() defer gc.Restore() gc.SetFontSize(2048) defer gc.SetDPI(gc.GetDPI()) gc.SetDPI(92) filling: for _, rune := range text { for _, g := range svgFont.Glyphs { if g.Rune == Rune(rune) { continue filling } } glyph := gc.glyphCache.Fetch(gc, gc.GetFontName(), rune) // glyphCache.Load indirectly calls CreateStringPath for single rune string glypPath := glyph.Path.VerticalFlip() // svg font glyphs have oposite y axe svgFont.Glyphs = append(svgFont.Glyphs, &Glyph{ Rune: Rune(rune), Desc: toSvgPathDesc(glypPath), HorizAdvX: glyph.Width, }) } // set attrs svgFont.Id = "font-" + strconv.Itoa(len(gc.svg.Fonts)) svgFont.Name = fontName // TODO use css @font-face with id instead of this svgFont.Face = &Face{Family: fontName, Units: 2048, HorizAdvX: 2048} return svgFont }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/signature.go#L194-L201
func (s untrustedSignature) sign(mech SigningMechanism, keyIdentity string) ([]byte, error) { json, err := json.Marshal(s) if err != nil { return nil, err } return mech.Sign(json, keyIdentity) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L4535-L4539
func (v GetMediaQueriesParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss40(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L464-L466
func (b *Base) Warningm(m *Attrs, msg string, a ...interface{}) error { return b.Log(LevelWarning, m, msg, a...) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L3149-L3172
func (c *containerLXC) getLxcState() (lxc.State, error) { if c.IsSnapshot() { return lxc.StateMap["STOPPED"], nil } // Load the go-lxc struct err := c.initLXC(false) if err != nil { return lxc.StateMap["STOPPED"], err } monitor := make(chan lxc.State, 1) go func(c *lxc.Container) { monitor <- c.State() }(c.c) select { case state := <-monitor: return state, nil case <-time.After(5 * time.Second): return lxc.StateMap["FROZEN"], LxcMonitorStateError } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cmdutil/cobra.go#L63-L78
func ParseCommit(arg string) (*pfs.Commit, error) { parts := strings.SplitN(arg, "@", 2) if parts[0] == "" { return nil, fmt.Errorf("invalid format \"%s\": repo cannot be empty", arg) } commit := &pfs.Commit{ Repo: &pfs.Repo{ Name: parts[0], }, ID: "", } if len(parts) == 2 { commit.ID = parts[1] } return commit, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L885-L897
func (c *putFileClient) PutFileOverwrite(repoName string, commitID string, path string, reader io.Reader, overwriteIndex int64) (_ int, retErr error) { writer, err := c.newPutFileWriteCloser(repoName, commitID, path, pfs.Delimiter_NONE, 0, 0, 0, &pfs.OverwriteIndex{Index: overwriteIndex}) if err != nil { return 0, grpcutil.ScrubGRPC(err) } defer func() { if err := writer.Close(); err != nil && retErr == nil { retErr = err } }() written, err := io.Copy(writer, reader) return int(written), grpcutil.ScrubGRPC(err) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssm/codegen_client.go#L842-L844
func (api *API) NotificationLocator(href string) *NotificationLocator { return &NotificationLocator{Href(href), api} }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/strings.go#L48-L56
func (s *Strings) Set(value string) error { if !s.beenSet { s.beenSet = true // Value is being set, don't use default. s.vals = nil } s.vals = append(s.vals, value) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L994-L996
func (p *StepOutParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandStepOut, nil, nil) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/oci.go#L100-L121
func (m *OCI1) Inspect(configGetter func(types.BlobInfo) ([]byte, error)) (*types.ImageInspectInfo, error) { config, err := configGetter(m.ConfigInfo()) if err != nil { return nil, err } v1 := &imgspecv1.Image{} if err := json.Unmarshal(config, v1); err != nil { return nil, err } d1 := &Schema2V1Image{} json.Unmarshal(config, d1) i := &types.ImageInspectInfo{ Tag: "", Created: v1.Created, DockerVersion: d1.DockerVersion, Labels: v1.Config.Labels, Architecture: v1.Architecture, Os: v1.OS, Layers: layerInfosToStrings(m.LayerInfos()), } return i, nil }