_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/api_server.go#L2152-L2163
func getAuthToken(ctx context.Context) (string, error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { return "", authclient.ErrNoMetadata } if len(md[authclient.ContextTokenKey]) > 1 { return "", fmt.Errorf("multiple authentication token keys found in context") } else if len(md[authclient.ContextTokenKey]) == 0 { return "", authclient.ErrNotSignedIn } return md[authclient.ContextTokenKey][0], nil }
https://github.com/fossapps/captain/blob/0f30dc3a624d523638831aa2bcb08bc962234a95/captain.go#L80-L89
func (config *Config) Run() { err := config.ensureLock() if err != nil { panic(err) } err = config.runWorker() if err != nil { panic(err) } }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/http/http.go#L61-L74
func (s *Server) ServeTCP(ln net.Listener) (err error) { if l, ok := ln.(*net.TCPListener); ok { ln = tcpKeepAliveListener{TCPListener: l} } if s.TLSConfig != nil { ln = tls.NewListener(ln, s.TLSConfig) } err = s.Server.Serve(ln) if err == http.ErrServerClosed { return nil } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/easyjson.go#L582-L586
func (v EventDomStorageItemsCleared) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomstorage5(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/secret/agent.go#L54-L85
func (a *Agent) reloadSecret(secretPath string) { var lastModTime time.Time logger := logrus.NewEntry(logrus.StandardLogger()) skips := 0 for range time.Tick(1 * time.Second) { if skips < 600 { // Check if the file changed to see if it needs to be re-read. secretStat, err := os.Stat(secretPath) if err != nil { logger.WithField("secret-path", secretPath). WithError(err).Error("Error loading secret file.") continue } recentModTime := secretStat.ModTime() if !recentModTime.After(lastModTime) { skips++ continue // file hasn't been modified } lastModTime = recentModTime } if secretValue, err := LoadSingleSecret(secretPath); err != nil { logger.WithField("secret-path: ", secretPath). WithError(err).Error("Error loading secret.") } else { a.setSecret(secretPath, secretValue) skips = 0 } } }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1891-L1900
func (u OperationBody) GetPathPaymentOp() (result PathPaymentOp, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "PathPaymentOp" { result = *u.PathPaymentOp ok = true } return }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/node.go#L517-L548
func nodeHealingDelete(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { poolName := r.URL.Query().Get("pool") var ctxs []permTypes.PermissionContext if poolName != "" { ctxs = append(ctxs, permission.Context(permTypes.CtxPool, poolName)) } if !permission.Check(t, permission.PermHealingDelete, ctxs...) { return permission.ErrUnauthorized } evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypePool, Value: poolName}, Kind: permission.PermHealingDelete, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), DisableLock: true, Allowed: event.Allowed(permission.PermPoolReadEvents, ctxs...), }) if err != nil { return err } defer func() { evt.Done(err) }() if len(r.URL.Query()["name"]) == 0 { return healer.RemoveConfig(poolName, "") } for _, v := range r.URL.Query()["name"] { err := healer.RemoveConfig(poolName, v) if err != nil { return err } } return nil }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L310-L316
func Letters(s string) []string { result := []string{} for _, r := range s { result = append(result, string(r)) } return result }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L75-L103
func appDelete(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { a, err := getAppFromContext(r.URL.Query().Get(":app"), r) if err != nil { return err } canDelete := permission.Check(t, permission.PermAppDelete, contextsForApp(&a)..., ) if !canDelete { return permission.ErrUnauthorized } evt, err := event.New(&event.Opts{ Target: appTarget(a.Name), Kind: permission.PermAppDelete, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(&a)...), }) if err != nil { return err } defer func() { evt.Done(err) }() keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "") defer keepAliveWriter.Stop() writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)} evt.SetLogWriter(writer) w.Header().Set("Content-Type", "application/x-json-stream") return app.Delete(&a, evt, requestIDHeader(r)) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L7103-L7107
func (v BoxModel) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom78(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L280-L288
func (in *Refs) DeepCopyInto(out *Refs) { *out = *in if in.Pulls != nil { in, out := &in.Pulls, &out.Pulls *out = make([]Pull, len(*in)) copy(*out, *in) } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/headlessexperimental/easyjson.go#L93-L97
func (v *ScreenshotParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeadlessexperimental(&r, v) return r.Error() }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L396-L401
func (d *Destination) PutSignatures(ctx context.Context, signatures [][]byte) error { if len(signatures) != 0 { return errors.Errorf("Storing signatures for docker tar files is not supported") } return nil }
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/garbler.go#L81-L90
func NewPassword(reqs *PasswordStrengthRequirements) (string, error) { if reqs == nil { reqs = &Medium } if ok, problems := reqs.sanityCheck(); !ok { return "", errors.New("requirements failed validation: " + problems) } e := Garbler{} return e.password(*reqs) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/tide.go#L566-L585
func unsuccessfulContexts(contexts []Context, cc contextChecker, log *logrus.Entry) []Context { var failed []Context for _, ctx := range contexts { if string(ctx.Context) == statusContext { continue } if cc.IsOptional(string(ctx.Context)) { continue } if ctx.State != githubql.StatusStateSuccess { failed = append(failed, ctx) } } for _, c := range cc.MissingRequiredContexts(contextsToStrings(contexts)) { failed = append(failed, newExpectedContext(c)) } log.Debugf("from %d total contexts (%v) found %d failing contexts: %v", len(contexts), contextsToStrings(contexts), len(failed), contextsToStrings(failed)) return failed }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L90-L97
func CharAt(s string, index int) string { l := len(s) shortcut := index < 0 || index > l-1 || l == 0 if shortcut { return "" } return s[index : index+1] }
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/time.go#L59-L64
func TimeFromPtr(t *time.Time) Time { if t == nil { return NewTime(time.Time{}, false) } return TimeFrom(*t) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/boskos.go#L340-L384
func handleUpdate(r *ranch.Ranch) http.HandlerFunc { return func(res http.ResponseWriter, req *http.Request) { logrus.WithField("handler", "handleUpdate").Infof("From %v", req.RemoteAddr) if req.Method != http.MethodPost { msg := fmt.Sprintf("Method %v, /update only accepts POST.", req.Method) logrus.Warning(msg) http.Error(res, msg, http.StatusMethodNotAllowed) return } name := req.URL.Query().Get("name") owner := req.URL.Query().Get("owner") state := req.URL.Query().Get("state") if name == "" || owner == "" || state == "" { msg := fmt.Sprintf("Name: %v, owner: %v, state : %v, all of them must be set in the request.", name, owner, state) logrus.Warning(msg) http.Error(res, msg, http.StatusBadRequest) return } var userData common.UserData if req.Body != nil { err := json.NewDecoder(req.Body).Decode(&userData) switch { case err == io.EOF: // empty body case err != nil: logrus.WithError(err).Warning("Unable to read from response body") http.Error(res, err.Error(), http.StatusBadRequest) return } } if err := r.Update(name, owner, state, &userData); err != nil { logrus.WithError(err).Errorf("Update failed: %v - %v (%v)", name, state, owner) http.Error(res, err.Error(), ErrorToStatus(err)) return } logrus.Infof("Updated resource %v", name) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/io/io.go#L124-L133
func (p *ResolveBlobParams) Do(ctx context.Context) (uuid string, err error) { // execute var res ResolveBlobReturns err = cdp.Execute(ctx, CommandResolveBlob, p, &res) if err != nil { return "", err } return res.UUID, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/unique_urls.go#L85-L87
func UniqueURLsFromFlag(fs *flag.FlagSet, urlsFlagName string) []url.URL { return (*fs.Lookup(urlsFlagName).Value.(*UniqueURLs)).uss }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/easyjson.go#L1512-L1516
func (v ContinueRequestParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoFetch13(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqls/manager.go#L228-L238
func (w *workManager) load(paths []string) { dirs, seqs := preparePaths(paths) for _, s := range seqs { w.inSeqs <- s } for _, r := range dirs { w.inDirs <- r } }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/trie/impl.go#L387-L406
func (t *Trie) FindRoutesAndPathMatched(httpMethod, path string) ([]*Match, bool) { context := newFindContext() pathMatched := false matches := []*Match{} context.matchFunc = func(httpMethod, path string, node *node) { pathMatched = true if node.HttpMethodToRoute[httpMethod] != nil { // path and method match, found a route ! matches = append( matches, &Match{ Route: node.HttpMethodToRoute[httpMethod], Params: context.paramsAsMap(), }, ) } } t.root.find(httpMethod, path, context) return matches, pathMatched }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L475-L481
func FileSequence_Len(id FileSeqId) C.size_t { fs, ok := sFileSeqs.Get(id) if !ok { return 0 } return C.size_t(fs.Len()) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2807-L2828
func NewPathPaymentResult(code PathPaymentResultCode, value interface{}) (result PathPaymentResult, err error) { result.Code = code switch PathPaymentResultCode(code) { case PathPaymentResultCodePathPaymentSuccess: tv, ok := value.(PathPaymentResultSuccess) if !ok { err = fmt.Errorf("invalid value, must be PathPaymentResultSuccess") return } result.Success = &tv case PathPaymentResultCodePathPaymentNoIssuer: tv, ok := value.(Asset) if !ok { err = fmt.Errorf("invalid value, must be Asset") return } result.NoIssuer = &tv default: // void } return }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/server.go#L1958-L2043
func (s *EtcdServer) applyEntryNormal(e *raftpb.Entry) { shouldApplyV3 := false if e.Index > s.consistIndex.ConsistentIndex() { // set the consistent index of current executing entry s.consistIndex.setConsistentIndex(e.Index) shouldApplyV3 = true } // raft state machine may generate noop entry when leader confirmation. // skip it in advance to avoid some potential bug in the future if len(e.Data) == 0 { select { case s.forceVersionC <- struct{}{}: default: } // promote lessor when the local member is leader and finished // applying all entries from the last term. if s.isLeader() { s.lessor.Promote(s.Cfg.electionTimeout()) } return } var raftReq pb.InternalRaftRequest if !pbutil.MaybeUnmarshal(&raftReq, e.Data) { // backward compatible var r pb.Request rp := &r pbutil.MustUnmarshal(rp, e.Data) s.w.Trigger(r.ID, s.applyV2Request((*RequestV2)(rp))) return } if raftReq.V2 != nil { req := (*RequestV2)(raftReq.V2) s.w.Trigger(req.ID, s.applyV2Request(req)) return } // do not re-apply applied entries. if !shouldApplyV3 { return } id := raftReq.ID if id == 0 { id = raftReq.Header.ID } var ar *applyResult needResult := s.w.IsRegistered(id) if needResult || !noSideEffect(&raftReq) { if !needResult && raftReq.Txn != nil { removeNeedlessRangeReqs(raftReq.Txn) } ar = s.applyV3.Apply(&raftReq) } if ar == nil { return } if ar.err != ErrNoSpace || len(s.alarmStore.Get(pb.AlarmType_NOSPACE)) > 0 { s.w.Trigger(id, ar) return } if lg := s.getLogger(); lg != nil { lg.Warn( "message exceeded backend quota; raising alarm", zap.Int64("quota-size-bytes", s.Cfg.QuotaBackendBytes), zap.String("quota-size", humanize.Bytes(uint64(s.Cfg.QuotaBackendBytes))), zap.Error(ar.err), ) } else { plog.Errorf("applying raft message exceeded backend quota") } s.goAttach(func() { a := &pb.AlarmRequest{ MemberID: uint64(s.ID()), Action: pb.AlarmRequest_ACTIVATE, Alarm: pb.AlarmType_NOSPACE, } s.raftRequest(s.ctx, pb.InternalRaftRequest{Alarm: a}) s.w.Trigger(id, ar) }) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/issue-creator/sources/triage-filer.go#L242-L281
func (f *TriageFiler) loadClusters(jsonIn []byte) ([]*Cluster, error) { var err error f.data, err = parseTriageData(jsonIn) if err != nil { return nil, err } if err = f.filterAndValidate(f.windowDays); err != nil { return nil, err } // Aggregate failing builds in each cluster by job (independent of tests). for _, clust := range f.data.Clustered { clust.filer = f clust.jobs = make(map[string][]int) for _, test := range clust.Tests { for _, job := range test.Jobs { for _, buildnum := range job.Builds { found := false for _, oldBuild := range clust.jobs[job.Name] { if oldBuild == buildnum { found = true break } } if !found { clust.jobs[job.Name] = append(clust.jobs[job.Name], buildnum) } } } } clust.totalJobs = len(clust.jobs) clust.totalTests = len(clust.Tests) clust.totalBuilds = 0 for _, builds := range clust.jobs { clust.totalBuilds += len(builds) } } return f.data.Clustered, nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift.go#L262-L308
func (s *openshiftImageSource) ensureImageIsResolved(ctx context.Context) error { if s.docker != nil { return nil } // FIXME: validate components per validation.IsValidPathSegmentName? path := fmt.Sprintf("/oapi/v1/namespaces/%s/imagestreams/%s", s.client.ref.namespace, s.client.ref.stream) body, err := s.client.doRequest(ctx, "GET", path, nil) if err != nil { return err } // Note: This does absolutely no kind/version checking or conversions. var is imageStream if err := json.Unmarshal(body, &is); err != nil { return err } var te *tagEvent for _, tag := range is.Status.Tags { if tag.Tag != s.client.ref.dockerReference.Tag() { continue } if len(tag.Items) > 0 { te = &tag.Items[0] break } } if te == nil { return errors.Errorf("No matching tag found") } logrus.Debugf("tag event %#v", te) dockerRefString, err := s.client.convertDockerImageReference(te.DockerImageReference) if err != nil { return err } logrus.Debugf("Resolved reference %#v", dockerRefString) dockerRef, err := docker.ParseReference("//" + dockerRefString) if err != nil { return err } d, err := dockerRef.NewImageSource(ctx, s.sys) if err != nil { return err } s.docker = d s.imageStreamImageName = te.Image return nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/keypair/main.go#L44-L59
func Random() (*Full, error) { var rawSeed [32]byte _, err := io.ReadFull(rand.Reader, rawSeed[:]) if err != nil { return nil, err } kp, err := FromRawSeed(rawSeed) if err != nil { return nil, err } return kp, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/deploy.go#L375-L434
func deployRollbackUpdate(w http.ResponseWriter, r *http.Request, t auth.Token) error { appName := r.URL.Query().Get(":appname") instance, err := app.GetByName(appName) if err != nil { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: fmt.Sprintf("App %s was not found", appName), } } canUpdateRollback := permission.Check(t, permission.PermAppUpdateDeployRollback, contextsForApp(instance)...) if !canUpdateRollback { return &tsuruErrors.HTTP{ Code: http.StatusForbidden, Message: "User does not have permission to do this action in this app", } } img := InputValue(r, "image") if img == "" { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: "you must specify an image", } } disable := InputValue(r, "disable") disableRollback, err := strconv.ParseBool(disable) if err != nil { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: fmt.Sprintf("Cannot set 'disable' status to: '%s', instead of 'true' or 'false'", disable), } } reason := InputValue(r, "reason") if (reason == "") && (disableRollback) { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: "Reason cannot be empty while disabling a image rollback", } } evt, err := event.New(&event.Opts{ Target: appTarget(appName), Kind: permission.PermAppUpdateDeployRollback, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(instance)...), AllowedCancel: event.Allowed(permission.PermAppUpdateEvents, contextsForApp(instance)...), Cancelable: false, }) if err != nil { return err } defer func() { evt.Done(err) }() err = app.RollbackUpdate(instance.Name, img, reason, disableRollback) if err != nil { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: err.Error(), } } return err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L213-L215
func (f *FakeClient) GetPullRequestChanges(org, repo string, number int) ([]github.PullRequestChange, error) { return f.PullRequestChanges[number], nil }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/envelope.go#L95-L102
func (e *Envelope) DeleteHeader(name string) error { if name == "" { return fmt.Errorf("Provide non-empty header name") } e.header.Del(name) return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/objects.go#L43-L64
func UpsertObject(tx *sql.Tx, table string, columns []string, values []interface{}) (int64, error) { n := len(columns) if n == 0 { return -1, fmt.Errorf("columns length is zero") } if n != len(values) { return -1, fmt.Errorf("columns length does not match values length") } stmt := fmt.Sprintf( "INSERT OR REPLACE INTO %s (%s) VALUES %s", table, strings.Join(columns, ", "), Params(n)) result, err := tx.Exec(stmt, values...) if err != nil { return -1, err } id, err := result.LastInsertId() if err != nil { return -1, err } return id, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/git/localgit/localgit.go#L95-L118
func (lg *LocalGit) MakeFakeRepo(org, repo string) error { rdir := filepath.Join(lg.Dir, org, repo) if err := os.MkdirAll(rdir, os.ModePerm); err != nil { return err } if err := runCmd(lg.Git, rdir, "init"); err != nil { return err } if err := runCmd(lg.Git, rdir, "config", "user.email", "test@test.test"); err != nil { return err } if err := runCmd(lg.Git, rdir, "config", "user.name", "test test"); err != nil { return err } if err := runCmd(lg.Git, rdir, "config", "commit.gpgsign", "false"); err != nil { return err } if err := lg.AddCommit(org, repo, map[string][]byte{"initial": {}}); err != nil { return err } return nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_eval.go#L135-L163
func (pc *PolicyContext) requirementsForImageRef(ref types.ImageReference) PolicyRequirements { // Do we have a PolicyTransportScopes for this transport? transportName := ref.Transport().Name() if transportScopes, ok := pc.Policy.Transports[transportName]; ok { // Look for a full match. identity := ref.PolicyConfigurationIdentity() if req, ok := transportScopes[identity]; ok { logrus.Debugf(` Using transport "%s" policy section %s`, transportName, identity) return req } // Look for a match of the possible parent namespaces. for _, name := range ref.PolicyConfigurationNamespaces() { if req, ok := transportScopes[name]; ok { logrus.Debugf(` Using transport "%s" specific policy section %s`, transportName, name) return req } } // Look for a default match for the transport. if req, ok := transportScopes[""]; ok { logrus.Debugf(` Using transport "%s" policy section ""`, transportName) return req } } logrus.Debugf(" Using default policy section") return pc.Policy.Default }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/streambuffer/streambuffer.go#L63-L70
func (s *Stream) Recv(recv func() interface{}) <-chan interface{} { s.mu.Lock() s.recvFunc = recv buf := make(chan interface{}, cap(s.sendBuffer)) s.recvBuffer = buf s.mu.Unlock() return buf }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/socket/socket_classic.go#L280-L286
func (cn *Conn) KeepAlive() error { req := &pb.GetSocketNameRequest{ SocketDescriptor: &cn.desc, } res := &pb.GetSocketNameReply{} return internal.Call(cn.ctx, "remote_socket", "GetSocketName", req, res) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/pprof.go#L77-L83
func traceHandler(w http.ResponseWriter, r *http.Request, t auth.Token) error { if !permission.Check(t, permission.PermDebug) { return permission.ErrUnauthorized } pprof.Trace(w, r) return nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/quota/quota.go#L16-L26
func (s *QuotaService) Inc(appName string, quantity int) error { quota, err := s.Storage.Get(appName) if err != nil { return err } err = s.checkLimit(quota, quantity) if err != nil { return err } return s.Storage.Inc(appName, quantity) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L46-L51
func NewFile(repoName string, commitID string, path string) *pfs.File { return &pfs.File{ Commit: NewCommit(repoName, commitID), Path: path, } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L272-L290
func (c *ClusterTx) ProfileGet(project string, name string) (*Profile, error) { filter := ProfileFilter{} filter.Project = project filter.Name = name objects, err := c.ProfileList(filter) if err != nil { return nil, errors.Wrap(err, "Failed to fetch Profile") } switch len(objects) { case 0: return nil, ErrNoSuchObject case 1: return &objects[0], nil default: return nil, fmt.Errorf("More than one profile matches") } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/easyjson.go#L823-L827
func (v GetEventListenersParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomdebugger9(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5657-L5660
func (e LedgerEntryChangeType) String() string { name, _ := ledgerEntryChangeTypeMap[int32(e)] return name }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/common/common.go#L225-L232
func (ud *UserData) ToMap() UserDataMap { m := UserDataMap{} ud.Range(func(key, value interface{}) bool { m[key.(string)] = value.(string) return true }) return m }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L1579-L1583
func (v Log) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoHar8(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L1205-L1209
func (v *HighlightFrameParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoOverlay12(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/serviceworker.go#L30-L36
func DeliverPushMessage(origin string, registrationID RegistrationID, data string) *DeliverPushMessageParams { return &DeliverPushMessageParams{ Origin: origin, RegistrationID: registrationID, Data: data, } }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/stream.go#L81-L93
func (s *Stream) Close() { // get mutex s.mutex.Lock() defer s.mutex.Unlock() // set flag s.closed = true // close active change stream if s.current != nil { _ = s.current.Close() } }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2299-L2307
func (u Memo) MustHash() Hash { val, ok := u.GetHash() if !ok { panic("arm Hash is not set") } return val }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L720-L743
func (c *Cluster) ContainerConfig(id int) (map[string]string, error) { var key, value string q := `SELECT key, value FROM containers_config WHERE container_id=?` inargs := []interface{}{id} outfmt := []interface{}{key, value} // Results is already a slice here, not db Rows anymore. results, err := queryScan(c.db, q, inargs, outfmt) if err != nil { return nil, err //SmartError will wrap this and make "not found" errors pretty } config := map[string]string{} for _, r := range results { key = r[0].(string) value = r[1].(string) config[key] = value } return config, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L87-L107
func (c *Cluster) StorageVolumeNodeGet(volumeID int64) (string, error) { name := "" query := ` SELECT nodes.name FROM storage_volumes JOIN nodes ON nodes.id=storage_volumes.node_id WHERE storage_volumes.id=? ` inargs := []interface{}{volumeID} outargs := []interface{}{&name} err := dbQueryRowScan(c.db, query, inargs, outargs) if err != nil { if err == sql.ErrNoRows { return "", ErrNoSuchObject } return "", err } return name, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L6326-L6330
func (v EventDownloadWillBegin) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage67(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6060-L6063
func (e IpAddrType) ValidEnum(v int32) bool { _, ok := ipAddrTypeMap[v] return ok }
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/OperatorSymbol.go#L244-L309
func (this OperatorSymbol) String() string { switch this { case NOOP: return "NOOP" case VALUE: return "VALUE" case EQ: return "=" case NEQ: return "!=" case GT: return ">" case LT: return "<" case GTE: return ">=" case LTE: return "<=" case REQ: return "=~" case NREQ: return "!~" case AND: return "&&" case OR: return "||" case IN: return "in" case BITWISE_AND: return "&" case BITWISE_OR: return "|" case BITWISE_XOR: return "^" case BITWISE_LSHIFT: return "<<" case BITWISE_RSHIFT: return ">>" case PLUS: return "+" case MINUS: return "-" case MULTIPLY: return "*" case DIVIDE: return "/" case MODULUS: return "%" case EXPONENT: return "**" case NEGATE: return "-" case INVERT: return "!" case BITWISE_NOT: return "~" case TERNARY_TRUE: return "?" case TERNARY_FALSE: return ":" case COALESCE: return "??" } return "" }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/linecapjoin/linecapjoin.go#L16-L29
func Main(gc draw2d.GraphicContext, ext string) (string, error) { // Draw the line const offset = 75.0 x := 35.0 caps := []draw2d.LineCap{draw2d.ButtCap, draw2d.SquareCap, draw2d.RoundCap} joins := []draw2d.LineJoin{draw2d.BevelJoin, draw2d.MiterJoin, draw2d.RoundJoin} for i := range caps { Draw(gc, caps[i], joins[i], x, 50, x, 160, offset) x += offset } // Return the output filename return samples.Output("linecapjoin", ext), nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/config/config.go#L53-L55
func (c *Config) ServerCertPath(remote string) string { return c.ConfigPath("servercerts", fmt.Sprintf("%s.crt", remote)) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L181-L183
func (c *ClusterTx) StoragePoolConfigAdd(poolID, nodeID int64, config map[string]string) error { return storagePoolConfigAdd(c.tx, poolID, nodeID, config) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L1670-L1674
func (v *PropertyDescriptor) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime15(&r, v) return r.Error() }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L381-L383
func (c *copier) Printf(format string, a ...interface{}) { fmt.Fprintf(c.reportWriter, format, a...) }
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/bit_reader.go#L77-L98
func (r *rarBitReader) readUint32() (uint32, error) { n, err := r.readBits(2) if err != nil { return 0, err } if n != 1 { n, err = r.readBits(4 << uint(n)) return uint32(n), err } n, err = r.readBits(4) if err != nil { return 0, err } if n == 0 { n, err = r.readBits(8) n |= -1 << 8 return uint32(n), err } nlow, err := r.readBits(4) n = n<<4 | nlow return uint32(n), err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L264-L270
func (f *FakeClient) GetRepoLabels(owner, repo string) ([]github.Label, error) { la := []github.Label{} for _, l := range f.RepoLabelsExisting { la = append(la, github.Label{Name: l}) } return la, nil }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L166-L178
func (receiver *lengthPrefixTCPReceiver) Receive() ([]byte, error) { lenPrefix := make([]byte, 4) if _, err := io.ReadFull(receiver.reader, lenPrefix); err != nil { return nil, err } l := binary.BigEndian.Uint32(lenPrefix) if l > maxTCPMsgSize { return nil, fmt.Errorf("incoming message exceeds maximum size: %d > %d", l, maxTCPMsgSize) } msg := make([]byte, l) _, err := io.ReadFull(receiver.reader, msg) return msg, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/easyjson.go#L798-L802
func (v DeleteEntryParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCachestorage7(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L451-L462
func (cdc *Codec) MarshalJSONIndent(o interface{}, prefix, indent string) ([]byte, error) { bz, err := cdc.MarshalJSON(o) if err != nil { return nil, err } var out bytes.Buffer err = json.Indent(&out, bz, prefix, indent) if err != nil { return nil, err } return out.Bytes(), nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/stack/stack.go#L31-L113
func (pc Call) Format(s fmt.State, c rune) { // BUG(ChrisHines): Subtracting one from pc is a work around for // https://code.google.com/p/go/issues/detail?id=7690. The idea for this // work around comes from rsc's initial patch at // https://codereview.appspot.com/84100043/#ps20001, but as noted in the // issue discussion, it is not a complete fix since it doesn't handle some // cases involving signals. Just the same, it handles all of the other // cases I have tested. pcFix := uintptr(pc) - 1 fn := runtime.FuncForPC(pcFix) if fn == nil { fmt.Fprintf(s, "%%!%c(NOFUNC)", c) return } switch c { case 's', 'v': file, line := fn.FileLine(pcFix) switch { case s.Flag('#'): // done case s.Flag('+'): // Here we want to get the source file path relative to the // compile time GOPATH. As of Go 1.3.x there is no direct way to // know the compiled GOPATH at runtime, but we can infer the // number of path segments in the GOPATH. We note that fn.Name() // returns the function name qualified by the import path, which // does not include the GOPATH. Thus we can trim segments from the // beginning of the file path until the number of path separators // remaining is one more than the number of path separators in the // function name. For example, given: // // GOPATH /home/user // file /home/user/src/pkg/sub/file.go // fn.Name() pkg/sub.Type.Method // // We want to produce: // // pkg/sub/file.go // // From this we can easily see that fn.Name() has one less path // separator than our desired output. const sep = "/" impCnt := strings.Count(fn.Name(), sep) + 1 pathCnt := strings.Count(file, sep) for pathCnt > impCnt { i := strings.Index(file, sep) if i == -1 { break } file = file[i+len(sep):] pathCnt-- } default: const sep = "/" if i := strings.LastIndex(file, sep); i != -1 { file = file[i+len(sep):] } } fmt.Fprint(s, file) if c == 'v' { fmt.Fprint(s, ":", line) } case 'd': _, line := fn.FileLine(pcFix) fmt.Fprint(s, line) case 'n': name := fn.Name() if !s.Flag('+') { const pathSep = "/" if i := strings.LastIndex(name, pathSep); i != -1 { name = name[i+len(pathSep):] } const pkgSep = "." if i := strings.Index(name, pkgSep); i != -1 { name = name[i+len(pkgSep):] } } fmt.Fprint(s, name) } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gopherage/cmd/filter/filter.go#L36-L50
func MakeCommand() *cobra.Command { flags := &flags{} cmd := &cobra.Command{ Use: "filter [file]", Short: "Filters a Go coverage file.", Long: `Filters a Go coverage file, removing entries that do not match the given flags.`, Run: func(cmd *cobra.Command, args []string) { run(flags, cmd, args) }, } cmd.Flags().StringVarP(&flags.OutputFile, "output", "o", "-", "output file") cmd.Flags().StringSliceVar(&flags.IncludePaths, "include-path", nil, "If specified at least once, only files with paths matching one of these regexes are included.") cmd.Flags().StringSliceVar(&flags.ExcludePaths, "exclude-path", nil, "Files with paths matching one of these regexes are excluded. Can be used repeatedly.") return cmd }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcsecrets/tcsecrets.go#L126-L130
func (secrets *Secrets) Remove(name string) error { cd := tcclient.Client(*secrets) _, _, err := (&cd).APICall(nil, "DELETE", "/secret/"+url.QueryEscape(name), nil, nil) return err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L277-L279
func (p *FocusParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandFocus, p, nil) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/commands.go#L572-L591
func shortenPattern(res *metadata.Resource, pattern, suffix string) (string, bool) { if strings.HasSuffix(pattern, suffix) { pat := strings.TrimSuffix(pattern, suffix) for _, action := range res.Actions { for _, pattern2 := range action.PathPatterns { vars := pattern2.Variables ivars := make([]interface{}, len(vars)) for i, v := range vars { ivars[i] = interface{}(":" + v) } subPattern := pattern2.Pattern pat2 := fmt.Sprintf(subPattern, ivars...) if pat == pat2 { return pat, true } } } } return pattern, false }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/git/git.go#L323-L340
func retryCmd(l *logrus.Entry, dir, cmd string, arg ...string) ([]byte, error) { var b []byte var err error sleepyTime := time.Second for i := 0; i < 3; i++ { c := exec.Command(cmd, arg...) c.Dir = dir b, err = c.CombinedOutput() if err != nil { l.Warningf("Running %s %v returned error %v with output %s.", cmd, arg, err, string(b)) time.Sleep(sleepyTime) sleepyTime *= 2 continue } break } return b, err }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L624-L634
func (c APIClient) GetObjectReader(hash string) (io.ReadCloser, error) { ctx, cancel := context.WithCancel(c.Ctx()) getObjectClient, err := c.ObjectAPIClient.GetObject( ctx, &pfs.Object{Hash: hash}, ) if err != nil { return nil, grpcutil.ScrubGRPC(err) } return grpcutil.NewStreamingBytesReader(getObjectClient, cancel), nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/ranch/ranch.go#L304-L316
func (r *Ranch) LogStatus() { resources, err := r.Storage.GetResources() if err != nil { return } resJSON, err := json.Marshal(resources) if err != nil { logrus.WithError(err).Errorf("Fail to marshal Resources. %v", resources) } logrus.Infof("Current Resources : %v", string(resJSON)) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/introspection.go#L350-L371
func (c *Connection) IntrospectState(opts *IntrospectionOptions) ConnectionRuntimeState { c.stateMut.RLock() defer c.stateMut.RUnlock() // TODO(prashantv): Add total number of health checks, and health check options. state := ConnectionRuntimeState{ ID: c.connID, ConnectionState: c.state.String(), LocalHostPort: c.conn.LocalAddr().String(), RemoteHostPort: c.conn.RemoteAddr().String(), OutboundHostPort: c.outboundHP, RemotePeer: c.remotePeerInfo, InboundExchange: c.inbound.IntrospectState(opts), OutboundExchange: c.outbound.IntrospectState(opts), HealthChecks: c.healthCheckHistory.asBools(), LastActivity: c.lastActivity.Load(), } if c.relay != nil { state.Relayer = c.relay.IntrospectState(opts) } return state }
https://github.com/ccding/go-config-reader/blob/8b6c2b50197f20da3b1c5944c274c173634dc056/config/config.go#L42-L47
func NewConfig(filename string) *Config { c := new(Config) c.filename = filename c.config = make(map[string]map[string]string) return c }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/google/compute/resources/instancegroup.go#L98-L118
func (r *InstanceGroup) Expected(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("instanceGroup.Expected") if r.CachedExpected != nil { logger.Debug("Using instance subnet [expected]") return immutable, r.CachedExpected, nil } expected := &InstanceGroup{ Shared: Shared{ Name: r.Name, CloudID: r.ServerPool.Identifier, }, Size: r.ServerPool.Size, Location: immutable.ProviderConfig().Location, Image: r.ServerPool.Image, Count: r.ServerPool.MaxCount, SSHFingerprint: immutable.ProviderConfig().SSH.PublicKeyFingerprint, BootstrapScripts: r.ServerPool.BootstrapScripts, } r.CachedExpected = expected return immutable, expected, nil }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/ash/authorizer.go#L62-L88
func And(a, b *Authorizer) *Authorizer { return A("ash/And", func(ctx *fire.Context) bool { return a.Matcher(ctx) && b.Matcher(ctx) }, func(ctx *fire.Context) ([]*Enforcer, error) { // run first callback enforcers1, err := a.Handler(ctx) if err != nil { return nil, err } else if enforcers1 == nil { return nil, nil } // run second callback enforcers2, err := b.Handler(ctx) if err != nil { return nil, err } else if enforcers2 == nil { return nil, nil } // merge both sets enforcers := append(S{}, enforcers1...) enforcers = append(enforcers, enforcers2...) return enforcers, nil }) }
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/cascade.go#L121-L152
func cascadeDeleteWithConfig(conf *CascadeConfig) (*mgo.ChangeInfo, error) { switch conf.RelType { case REL_ONE: update := map[string]map[string]interface{}{ "$set": map[string]interface{}{}, } if len(conf.ThroughProp) > 0 { update["$set"][conf.ThroughProp] = nil } else { for _, p := range conf.Properties { update["$set"][p] = nil } } return conf.Collection.Collection().UpdateAll(conf.Query, update) case REL_MANY: update := map[string]map[string]interface{}{ "$pull": map[string]interface{}{}, } q := bson.M{} for _, f := range conf.ReferenceQuery { q[f.BsonName] = f.Value } update["$pull"][conf.ThroughProp] = q return conf.Collection.Collection().UpdateAll(conf.Query, update) } return &mgo.ChangeInfo{}, errors.New("Invalid relation type") }
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/nsqlookup/local.go#L52-L73
func NewLocalEngine(config LocalConfig) *LocalEngine { if config.NodeTimeout == 0 { config.NodeTimeout = DefaultLocalEngineNodeTimeout } if config.TombstoneTimeout == 0 { config.TombstoneTimeout = DefaultLocalEngineTombstoneTimeout } e := &LocalEngine{ nodeTimeout: config.NodeTimeout, tombTimeout: config.TombstoneTimeout, done: make(chan struct{}), join: make(chan struct{}), nodes: make(map[string]*LocalNode), } go e.run() return e }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L3260-L3264
func (v Response) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork22(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/database/elasticsearch/elasticsearch.go#L164-L191
func (db *Database) WaitForConnection(ctx context.Context, timeout int) error { var err error secondsWaited := 0 connCtx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second) defer cancel() log.Debug("===> trying to connect to elasticsearch") for { // Try to connect to Elasticsearch select { case <-connCtx.Done(): return errors.Wrapf(err, "connecting to elasticsearch timed out after %d seconds", secondsWaited) default: err = db.TestConnection() if err == nil { log.Debugf("elasticsearch came online after %d seconds", secondsWaited) return nil } // not ready yet secondsWaited++ log.Debug(" * could not connect to elasticsearch (sleeping for 1 second)") time.Sleep(1 * time.Second) } } }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L15-L48
func RootTracer() func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // split url segments := strings.Split(r.URL.Path, "/") // replace ids for i, s := range segments { if bson.IsObjectIdHex(s) { segments[i] = ":id" } } // construct name path := strings.Join(segments, "/") name := fmt.Sprintf("%s %s", r.Method, path) // create root span from request tracer := NewTracerFromRequest(r, name) tracer.Tag("peer.address", r.RemoteAddr) tracer.Tag("http.proto", r.Proto) tracer.Tag("http.method", r.Method) tracer.Tag("http.host", r.Host) tracer.Log("http.url", r.URL.String()) tracer.Log("http.length", r.ContentLength) tracer.Log("http.header", r.Header) r = r.WithContext(tracer.Context(r.Context())) defer tracer.Finish(true) // call next handler next.ServeHTTP(w, r) }) } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L10451-L10453
func (api *API) SchedulerLocator(href string) *SchedulerLocator { return &SchedulerLocator{Href(href), api} }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L4562-L4571
func (o *MapUintptrOption) Set(value string) error { parts := stringMapRegex.Split(value, 2) if len(parts) != 2 { return fmt.Errorf("expected KEY=VALUE got '%s'", value) } val := UintptrOption{} val.Set(parts[1]) (*o)[parts[0]] = val return nil }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L484-L491
func FileSequence_String(id FileSeqId) *C.char { fs, ok := sFileSeqs.Get(id) // caller must free string if !ok { return C.CString("") } return C.CString(fs.String()) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L338-L342
func (v UnregisterParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoServiceworker2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/requestbuilder.go#L30-L32
func (r *RequestBuilder) BodyString(body string) *RequestBuilder { return r.Body(strings.NewReader(body)) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/config.go#L87-L90
func (c *Config) AutoUpdateInterval() time.Duration { n := c.m.GetInt64("images.auto_update_interval") return time.Duration(n) * time.Hour }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/remote.go#L201-L264
func (r *RemoteCache) Root(importPath string) (root, name string, err error) { // Try prefixes of the import path in the cache, but don't actually go out // to vcs yet. We do this before handling known special cases because // the cache is pre-populated with repository rules, and we want to use their // names if we can. prefix := importPath for { v, ok, err := r.root.get(prefix) if ok { if err != nil { return "", "", err } value := v.(rootValue) return value.root, value.name, nil } prefix = path.Dir(prefix) if prefix == "." || prefix == "/" { break } } // Try known prefixes. for _, p := range knownPrefixes { if pathtools.HasPrefix(importPath, p.prefix) { rest := pathtools.TrimPrefix(importPath, p.prefix) var components []string if rest != "" { components = strings.Split(rest, "/") } if len(components) < p.missing { return "", "", fmt.Errorf("import path %q is shorter than the known prefix %q", importPath, p.prefix) } root = p.prefix for _, c := range components[:p.missing] { root = path.Join(root, c) } name = label.ImportPathToBazelRepoName(root) return root, name, nil } } // gopkg.in is special, and might have either one or two levels of // missing paths. See http://labix.org/gopkg.in for URL patterns. if match := gopkginPattern.FindStringSubmatch(importPath); len(match) > 0 { root = match[1] name = label.ImportPathToBazelRepoName(root) return root, name, nil } // Find the prefix using vcs and cache the result. v, err := r.root.ensure(importPath, func() (interface{}, error) { res, err := r.RepoRootForImportPath(importPath, false) if err != nil { return nil, err } return rootValue{res.Root, label.ImportPathToBazelRepoName(res.Root)}, nil }) if err != nil { return "", "", err } value := v.(rootValue) return value.root, value.name, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/pkg/ghclient/core.go#L49-L67
func NewClient(token string, dryRun bool) *Client { httpClient := &http.Client{ Transport: &oauth2.Transport{ Base: http.DefaultTransport, Source: oauth2.ReuseTokenSource(nil, oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})), }, } client := github.NewClient(httpClient) return &Client{ issueService: client.Issues, prService: client.PullRequests, repoService: client.Repositories, userService: client.Users, retries: 5, retryInitialBackoff: time.Second, tokenReserve: 50, dryRun: dryRun, } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/config.go#L574-L590
func ReadFileMaybeGZIP(path string) ([]byte, error) { b, err := ioutil.ReadFile(path) if err != nil { return nil, err } // check if file contains gzip header: http://www.zlib.org/rfc-gzip.html if !bytes.HasPrefix(b, []byte("\x1F\x8B")) { // go ahead and return the contents if not gzipped return b, nil } // otherwise decode gzipReader, err := gzip.NewReader(bytes.NewBuffer(b)) if err != nil { return nil, err } return ioutil.ReadAll(gzipReader) }
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/lyra2.go#L179-L194
func absorbBlockBlake2Safe(state []uint64, in []uint64) { //XORs the first BLOCK_LEN_BLAKE2_SAFE_INT64 words of "in" with the current state state[0] ^= in[0] state[1] ^= in[1] state[2] ^= in[2] state[3] ^= in[3] state[4] ^= in[4] state[5] ^= in[5] state[6] ^= in[6] state[7] ^= in[7] //Applies the transformation f to the sponge's state blake2bLyra(state) }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L100-L103
func (p MailBuilder) BCCAddrs(bcc []mail.Address) MailBuilder { p.bcc = bcc return p }
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xtypes.go#L80-L86
func (s String) Num() Num { num, err := strconv.ParseFloat(strings.TrimSpace(string(s)), 64) if err != nil { return Num(math.NaN()) } return Num(num) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/deviceorientation/easyjson.go#L105-L109
func (v *SetDeviceOrientationOverrideParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDeviceorientation(&r, v) return r.Error() }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/create.go#L35-L87
func CreateCmd() *cobra.Command { var co = &cli.CreateOptions{} var createCmd = &cobra.Command{ Use: "create [NAME] [-p|--profile PROFILENAME] [-c|--cloudid CLOUDID]", Short: "Create a Kubicorn API model from a profile", Long: `Use this command to create a Kubicorn API model in a defined state store. This command will create a cluster API model as a YAML manifest in a state store. Once the API model has been created, a user can optionally change the model to their liking. After a model is defined and configured properly, the user can then apply the model.`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: co.Name = viper.GetString(keyKubicornName) if co.Name == "" { co.Name = namer.RandomName() } case 1: co.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := RunCreate(co); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := createCmd.Flags() bindCommonStateStoreFlags(&co.StateStoreOptions, fs) bindCommonAwsFlags(&co.AwsOptions, fs) fs.StringVarP(&co.Profile, keyProfile, "p", viper.GetString(keyProfile), descProfile) fs.StringVarP(&co.CloudID, keyCloudID, "c", viper.GetString(keyCloudID), descCloudID) fs.StringVar(&co.KubeConfigLocalFile, keyKubeConfigLocalFile, viper.GetString(keyKubeConfigLocalFile), descKubeConfigLocalFile) fs.StringArrayVarP(&co.Set, keySet, "C", viper.GetStringSlice(keySet), descSet) fs.StringArrayVarP(&co.MasterSet, keyMasterSet, "M", viper.GetStringSlice(keyMasterSet), descMasterSet) fs.StringArrayVarP(&co.NodeSet, keyNodeSet, "N", viper.GetStringSlice(keyNodeSet), descNodeSet) fs.StringVarP(&co.GitRemote, keyGitConfig, "g", viper.GetString(keyGitConfig), descGitConfig) fs.StringArrayVar(&co.AwsOptions.PolicyAttachments, keyPolicyAttachments, co.AwsOptions.PolicyAttachments, descPolicyAttachments) flagApplyAnnotations(createCmd, "profile", "__kubicorn_parse_profiles") flagApplyAnnotations(createCmd, "cloudid", "__kubicorn_parse_cloudid") createCmd.SetUsageTemplate(cli.UsageTemplate) return createCmd }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/config.go#L360-L367
func splitValue(value string) []string { parts := strings.Split(value, ",") values := make([]string, 0, len(parts)) for _, part := range parts { values = append(values, strings.TrimSpace(part)) } return values }
https://github.com/texttheater/golang-levenshtein/blob/d188e65d659ef53fcdb0691c12f1bba64928b649/levenshtein/levenshtein.go#L119-L130
func RatioForMatrix(matrix [][]int) float64 { sourcelength := len(matrix) - 1 targetlength := len(matrix[0]) - 1 sum := sourcelength + targetlength if sum == 0 { return 0 } dist := DistanceForMatrix(matrix) return float64(sum-dist) / float64(sum) }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/read.go#L96-L98
func (p *Process) ReadInt8(a Address) int8 { return int8(p.ReadUint8(a)) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1287-L1315
func Merge(w *Writer, rs []*Reader) error { if len(rs) == 0 { return nil } mq := &mergePQ{q: make([]*nodeStream, len(rs)+1)} // Setup first set of nodes for _, r := range rs { if err := mq.insert(&nodeStream{r: r}); err != nil { return err } } for mq.q[1] != nil { // Get next nodes to merge ns, err := mq.next() if err != nil { return err } // Merge nodes n, err := merge(ns) if err != nil { return err } // Write out result if err := w.Write(n); err != nil { return err } } return nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/local_client.go#L12-L17
func NewLocalClient(root string) (Client, error) { if err := os.MkdirAll(root, 0755); err != nil { return nil, err } return &localClient{root}, nil }