_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/jenkins-operator/main.go#L267-L271
func serve(jc *jenkins.Client) { http.Handle("/", gziphandler.GzipHandler(handleLog(jc))) http.Handle("/metrics", promhttp.Handler()) logrus.WithError(http.ListenAndServe(":8080", nil)).Fatal("ListenAndServe returned.") }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L159-L167
func (r *ReadBuffer) FillFrom(ior io.Reader, n int) (int, error) { if len(r.buffer) < n { return 0, ErrEOF } r.err = nil r.remaining = r.buffer[:n] return io.ReadFull(ior, r.remaining) }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L3863-L3872
func (o *MapUint32Option) Set(value string) error { parts := stringMapRegex.Split(value, 2) if len(parts) != 2 { return fmt.Errorf("expected KEY=VALUE got '%s'", value) } val := Uint32Option{} val.Set(parts[1]) (*o)[parts[0]] = val return nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/cmds/cmds.go#L376-L397
func ListAdminsCmd(noMetrics, noPortForwarding *bool) *cobra.Command { listAdmins := &cobra.Command{ Short: "List the current cluster admins", Long: "List the current cluster admins", Run: cmdutil.Run(func([]string) error { c, err := client.NewOnUserMachine(!*noMetrics, !*noPortForwarding, "user") if err != nil { return err } defer c.Close() resp, err := c.GetAdmins(c.Ctx(), &auth.GetAdminsRequest{}) if err != nil { return grpcutil.ScrubGRPC(err) } for _, user := range resp.Admins { fmt.Println(user) } return nil }), } return cmdutil.CreateAlias(listAdmins, "auth list-admins") }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/config.go#L63-L129
func CreateConfig(path string) error { config, _ := LoadConfig(path) var emailDef, passwordDef, accountDef, hostDef, refreshTokenDef string if config != nil { yn := PromptConfirmation("Found existing configuration file %v, overwrite? (y/N): ", path) if yn != "y" { PrintSuccess("Exiting") return nil } emailDef = fmt.Sprintf(" (%v)", config.Email) accountDef = fmt.Sprintf(" (%v)", config.Account) passwordDef = " (leave blank to leave unchanged)" if config.LoginHost == "" { config.LoginHost = "my.rightscale.com" } hostDef = fmt.Sprintf(" (%v)", config.LoginHost) refreshTokenDef = " (leave blank to leave unchanged)" } else { config = &ClientConfig{} } fmt.Fprintf(out, "Account ID%v: ", accountDef) var newAccount string fmt.Fscanln(in, &newAccount) if newAccount != "" { a, err := strconv.Atoi(newAccount) if err != nil { return fmt.Errorf("Account ID must be an integer, got '%s'.", newAccount) } config.Account = a } fmt.Fprintf(out, "Login email%v: ", emailDef) var newEmail string fmt.Fscanln(in, &newEmail) if newEmail != "" { config.Email = newEmail } fmt.Fprintf(out, "Login password%v: ", passwordDef) var newPassword string fmt.Fscanln(in, &newPassword) if newPassword != "" { config.Password = newPassword } fmt.Fprintf(out, "API Login host%v: ", hostDef) var newLoginHost string fmt.Fscanln(in, &newLoginHost) if newLoginHost != "" { config.LoginHost = newLoginHost } fmt.Fprintf(out, "API Refresh Token%v: ", refreshTokenDef) var newRefreshToken string fmt.Fscanln(in, &newRefreshToken) if newRefreshToken != "" { config.RefreshToken = newRefreshToken } err := config.Save(path) if err != nil { return fmt.Errorf("Failed to save config: %s", err) } return nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/asset.go#L68-L86
func (a Asset) Equals(other Asset) bool { if a.Type != other.Type { return false } switch a.Type { case AssetTypeAssetTypeNative: return true case AssetTypeAssetTypeCreditAlphanum4: l := a.MustAlphaNum4() r := other.MustAlphaNum4() return l.AssetCode == r.AssetCode && l.Issuer.Equals(r.Issuer) case AssetTypeAssetTypeCreditAlphanum12: l := a.MustAlphaNum12() r := other.MustAlphaNum12() return l.AssetCode == r.AssetCode && l.Issuer.Equals(r.Issuer) default: panic(fmt.Errorf("Unknown asset type: %v", a.Type)) } }
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/consumer.go#L347-L383
func RateLimit(limit int, messages <-chan Message) <-chan Message { if limit <= 0 { return messages } output := make(chan Message) go func() { ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() defer close(output) input := messages count := 0 for { select { case <-ticker.C: count = 0 input = messages case msg, ok := <-input: if !ok { return } output <- msg if count++; count >= limit { input = nil } } } }() return output }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/portforwarder.go#L49-L79
func NewPortForwarder(namespace string) (*PortForwarder, error) { if namespace == "" { namespace = "default" } rules := clientcmd.NewDefaultClientConfigLoadingRules() overrides := &clientcmd.ConfigOverrides{} kubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides) config, err := kubeConfig.ClientConfig() if err != nil { return nil, err } client, err := kubernetes.NewForConfig(config) if err != nil { return nil, err } core := client.CoreV1() return &PortForwarder{ core: core, client: core.RESTClient(), config: config, namespace: namespace, logger: log.StandardLogger().Writer(), stopChansLock: &sync.Mutex{}, stopChans: []chan struct{}{}, shutdown: false, }, nil }
https://github.com/felixge/httpsnoop/blob/eadd4fad6aac69ae62379194fe0219f3dbc80fd3/capture_metrics.go#L38-L84
func CaptureMetricsFn(w http.ResponseWriter, fn func(http.ResponseWriter)) Metrics { var ( start = time.Now() m = Metrics{Code: http.StatusOK} headerWritten bool lock sync.Mutex hooks = Hooks{ WriteHeader: func(next WriteHeaderFunc) WriteHeaderFunc { return func(code int) { next(code) lock.Lock() defer lock.Unlock() if !headerWritten { m.Code = code headerWritten = true } } }, Write: func(next WriteFunc) WriteFunc { return func(p []byte) (int, error) { n, err := next(p) lock.Lock() defer lock.Unlock() m.Written += int64(n) headerWritten = true return n, err } }, ReadFrom: func(next ReadFromFunc) ReadFromFunc { return func(src io.Reader) (int64, error) { n, err := next(src) lock.Lock() defer lock.Unlock() headerWritten = true m.Written += n return n, err } }, } ) fn(Wrap(w, hooks)) m.Duration = time.Since(start) return m }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_cluster.go#L12-L24
func (r *ProtocolLXD) GetCluster() (*api.Cluster, string, error) { if !r.HasExtension("clustering") { return nil, "", fmt.Errorf("The server is missing the required \"clustering\" API extension") } cluster := &api.Cluster{} etag, err := r.queryStruct("GET", "/cluster", nil, "", &cluster) if err != nil { return nil, "", err } return cluster, etag, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L495-L498
func (p SynthesizeScrollGestureParams) WithSpeed(speed int64) *SynthesizeScrollGestureParams { p.Speed = speed return &p }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L908-L922
func (v *VM) TotalRootSnapshots() (int, error) { var result C.int var err C.VixError = C.VIX_OK err = C.VixVM_GetNumRootSnapshots(v.handle, &result) if C.VIX_OK != err { return 0, &Error{ Operation: "vm.TotalRootSnapshots", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } return int(result), nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L3437-L3441
func (v *GetLayoutMetricsReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage36(&r, v) return r.Error() }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L2659-L2666
func (r *Credential) Locator(api *API) *CredentialLocator { for _, l := range r.Links { if l["rel"] == "self" { return api.CredentialLocator(l["href"]) } } return nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/auth.go#L776-L797
func showAPIToken(w http.ResponseWriter, r *http.Request, t auth.Token) error { u, err := auth.ConvertNewUser(t.User()) if err != nil { return err } email := r.URL.Query().Get("user") if email != "" { if !permission.Check(t, permission.PermUserUpdateToken) { return permission.ErrUnauthorized } u, err = auth.GetUserByEmail(email) if err != nil { return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()} } } apiKey, err := u.ShowAPIKey() if err != nil { return err } w.Header().Add("Content-Type", "application/json") return json.NewEncoder(w).Encode(apiKey) }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L589-L591
func IsFrameRange(frange *C.char) bool { return fileseq.IsFrameRange(C.GoString(frange)) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L643-L645
func (o *RepoOwners) LeafApprovers(path string) sets.String { return o.entriesForFile(path, o.approvers, true) }
https://github.com/pandemicsyn/oort/blob/fca1d3baddc1d944387cc8bbe8b21f911ec9091b/api/groupstore_GEN_.go#L161-L166
func (stor *groupStore) Shutdown(ctx context.Context) error { stor.lock.Lock() err := stor.shutdown() stor.lock.Unlock() return err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/spyglass/lenses/lenses.go#L138-L181
func LastNLinesChunked(a Artifact, n, chunkSize int64) ([]string, error) { toRead := chunkSize + 1 // Add 1 for exclusive upper bound read range chunks := int64(1) var contents []byte var linesInContents int64 artifactSize, err := a.Size() if err != nil { return nil, fmt.Errorf("error getting artifact size: %v", err) } offset := artifactSize - chunks*chunkSize lastOffset := offset var lastRead int64 for linesInContents < n && offset != 0 { offset = lastOffset - lastRead if offset < 0 { toRead = offset + chunkSize + 1 offset = 0 } bytesRead := make([]byte, toRead) numBytesRead, err := a.ReadAt(bytesRead, offset) if err != nil && err != io.EOF { return nil, fmt.Errorf("error reading artifact: %v", err) } lastRead = int64(numBytesRead) lastOffset = offset bytesRead = bytes.Trim(bytesRead, "\x00") linesInContents += int64(bytes.Count(bytesRead, []byte("\n"))) contents = append(bytesRead, contents...) chunks++ } var lines []string scanner := bufio.NewScanner(bytes.NewReader(contents)) scanner.Split(bufio.ScanLines) for scanner.Scan() { line := scanner.Text() lines = append(lines, line) } l := int64(len(lines)) if l < n { return lines, nil } return lines[l-n:], nil }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L53-L57
func VerifyContentType(contentType string) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { Expect(req.Header.Get("Content-Type")).Should(Equal(contentType)) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/tracing.go#L148-L151
func (p StartParams) WithStreamFormat(streamFormat StreamFormat) *StartParams { p.StreamFormat = streamFormat return &p }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/plugins.go#L101-L104
func RegisterPushEventHandler(name string, fn PushEventHandler, help HelpProvider) { pluginHelp[name] = help pushEventHandlers[name] = fn }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/watch/watch.go#L195-L200
func MakeWatcher(eventCh chan *Event, done chan struct{}) Watcher { return &watcher{ eventCh: eventCh, done: done, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L409-L413
func (v *ScrollRect) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoLayertree3(&r, v) return r.Error() }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5104-L5113
func (u LedgerKey) GetTrustLine() (result LedgerKeyTrustLine, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "TrustLine" { result = *u.TrustLine ok = true } return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/pipeline/controller.go#L90-L122
func (c *controller) hasSynced() bool { if !c.pjInformer.HasSynced() { if c.wait != "prowjobs" { c.wait = "prowjobs" ns := c.pjNamespace() if ns == "" { ns = "controllers" } logrus.Infof("Waiting on prowjobs in %s namespace...", ns) } return false // still syncing prowjobs } if !c.prowJobsDone { c.prowJobsDone = true logrus.Info("Synced prow jobs") } if c.pipelinesDone == nil { c.pipelinesDone = map[string]bool{} } for n, cfg := range c.pipelines { if !cfg.informer.Informer().HasSynced() { if c.wait != n { c.wait = n logrus.Infof("Waiting on %s pipelines...", n) } return false // still syncing pipelines in at least one cluster } else if !c.pipelinesDone[n] { c.pipelinesDone[n] = true logrus.Infof("Synced %s pipelines", n) } } return true // Everyone is synced }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4139-L4148
func (u OperationResultTr) GetChangeTrustResult() (result ChangeTrustResult, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "ChangeTrustResult" { result = *u.ChangeTrustResult ok = true } return }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/status.go#L91-L129
func (mw *StatusMiddleware) GetStatus() *Status { mw.lock.RLock() now := time.Now() uptime := now.Sub(mw.start) totalCount := 0 for _, count := range mw.responseCounts { totalCount += count } totalResponseTime := mw.totalResponseTime.Sub(time.Time{}) averageResponseTime := time.Duration(0) if totalCount > 0 { avgNs := int64(totalResponseTime) / int64(totalCount) averageResponseTime = time.Duration(avgNs) } status := &Status{ Pid: mw.pid, UpTime: uptime.String(), UpTimeSec: uptime.Seconds(), Time: now.String(), TimeUnix: now.Unix(), StatusCodeCount: mw.responseCounts, TotalCount: totalCount, TotalResponseTime: totalResponseTime.String(), TotalResponseTimeSec: totalResponseTime.Seconds(), AverageResponseTime: averageResponseTime.String(), AverageResponseTimeSec: averageResponseTime.Seconds(), } mw.lock.RUnlock() return status }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/pool.go#L92-L136
func addPoolHandler(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { allowed := permission.Check(t, permission.PermPoolCreate) if !allowed { return permission.ErrUnauthorized } var addOpts pool.AddPoolOptions err = ParseInput(r, &addOpts) if err != nil { return err } if addOpts.Name == "" { return &terrors.HTTP{ Code: http.StatusBadRequest, Message: pool.ErrPoolNameIsRequired.Error(), } } evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypePool, Value: addOpts.Name}, Kind: permission.PermPoolCreate, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermPoolReadEvents, permission.Context(permTypes.CtxPool, addOpts.Name)), }) if err != nil { return err } defer func() { evt.Done(err) }() err = pool.AddPool(addOpts) if err == pool.ErrDefaultPoolAlreadyExists || err == pool.ErrPoolAlreadyExists { return &terrors.HTTP{ Code: http.StatusConflict, Message: err.Error(), } } if err == pool.ErrPoolNameIsRequired { return &terrors.HTTP{ Code: http.StatusBadRequest, Message: err.Error(), } } if err == nil { w.WriteHeader(http.StatusCreated) } return err }
https://github.com/apparentlymart/go-rundeck-api/blob/2c962acae81080a937c350a5bea054c239f27a81/rundeck/job.go#L337-L339
func (c *Client) CreateJob(job *JobDetail) (*JobSummary, error) { return c.importJob(job, "create") }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/quic/quic.go#L44-L58
func New(handler http.Handler, opts ...Option) (s *Server) { o := &Options{} for _, opt := range opts { opt(o) } s = &Server{ Server: &h2quic.Server{ Server: &http.Server{ Handler: handler, TLSConfig: o.tlsConfig, }, }, } return }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_transport.go#L159-L168
func (ref dockerReference) tagOrDigest() (string, error) { if ref, ok := ref.ref.(reference.Canonical); ok { return ref.Digest().String(), nil } if ref, ok := ref.ref.(reference.NamedTagged); ok { return ref.Tag(), nil } // This should not happen, NewReference above refuses reference.IsNameOnly values. return "", errors.Errorf("Internal inconsistency: Reference %s unexpectedly has neither a digest nor a tag", reference.FamiliarString(ref.ref)) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/logger.go#L43-L49
func SetLogger(l grpclog.LoggerV2) { lgMu.Lock() lg = logutil.NewLogger(l) // override grpclog so that any changes happen with locking grpclog.SetLoggerV2(lg) lgMu.Unlock() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/label_sync/main.go#L340-L387
func loadLabels(gc client, org string, repos []string) (*RepoLabels, error) { repoChan := make(chan string, len(repos)) for _, repo := range repos { repoChan <- repo } close(repoChan) wg := sync.WaitGroup{} wg.Add(maxConcurrentWorkers) labels := make(chan RepoLabels, len(repos)) errChan := make(chan error, len(repos)) for i := 0; i < maxConcurrentWorkers; i++ { go func(repositories <-chan string) { defer wg.Done() for repository := range repositories { logrus.WithField("org", org).WithField("repo", repository).Info("Listing labels for repo") repoLabels, err := gc.GetRepoLabels(org, repository) if err != nil { logrus.WithField("org", org).WithField("repo", repository).Error("Failed listing labels for repo") errChan <- err } labels <- RepoLabels{repository: repoLabels} } }(repoChan) } wg.Wait() close(labels) close(errChan) rl := RepoLabels{} for data := range labels { for repo, repoLabels := range data { rl[repo] = repoLabels } } var overallErr error if len(errChan) > 0 { var listErrs []error for listErr := range errChan { listErrs = append(listErrs, listErr) } overallErr = fmt.Errorf("failed to list labels: %v", listErrs) } return &rl, overallErr }
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L43-L55
func NewConsumer(addrs []string, groupID string, topics []string, config *Config) (*Consumer, error) { client, err := NewClient(addrs, config) if err != nil { return nil, err } consumer, err := NewConsumerFromClient(client, groupID, topics) if err != nil { return nil, err } consumer.ownClient = true return consumer, nil }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/timer.go#L13-L26
func (mw *TimerMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc { return func(w ResponseWriter, r *Request) { start := time.Now() r.Env["START_TIME"] = &start // call the handler h(w, r) end := time.Now() elapsed := end.Sub(start) r.Env["ELAPSED_TIME"] = &elapsed } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1165-L1169
func (v *ExposeDevToolsProtocolParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget12(&r, v) return r.Error() }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol_crypto.go#L27-L34
func formSessionKey(remotePublicKey, localPrivateKey *[32]byte, secretKey []byte) *[32]byte { var sharedKey [32]byte box.Precompute(&sharedKey, remotePublicKey, localPrivateKey) sharedKeySlice := sharedKey[:] sharedKeySlice = append(sharedKeySlice, secretKey...) sessionKey := sha256.Sum256(sharedKeySlice) return &sessionKey }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L7038-L7050
func (u ScpStatementPledges) ArmForSwitch(sw int32) (string, bool) { switch ScpStatementType(sw) { case ScpStatementTypeScpStPrepare: return "Prepare", true case ScpStatementTypeScpStConfirm: return "Confirm", true case ScpStatementTypeScpStExternalize: return "Externalize", true case ScpStatementTypeScpStNominate: return "Nominate", true } return "-", false }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/types.go#L214-L216
func (t *TransferMode) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/types.go#L52-L54
func (t InspectMode) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/pjutil.go#L109-L123
func PresubmitSpec(p config.Presubmit, refs prowapi.Refs) prowapi.ProwJobSpec { pjs := specFromJobBase(p.JobBase) pjs.Type = prowapi.PresubmitJob pjs.Context = p.Context pjs.Report = !p.SkipReport pjs.RerunCommand = p.RerunCommand if p.JenkinsSpec != nil { pjs.JenkinsSpec = &prowapi.JenkinsSpec{ GitHubBranchSourceJob: p.JenkinsSpec.GitHubBranchSourceJob, } } pjs.Refs = completePrimaryRefs(refs, p.JobBase) return pjs }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/delay/delay.go#L162-L203
func Func(key string, i interface{}) *Function { f := &Function{fv: reflect.ValueOf(i)} // Derive unique, somewhat stable key for this func. _, file, _, _ := runtime.Caller(1) fk, err := fileKey(file) if err != nil { // Not fatal, but log the error stdlog.Printf("delay: %v", err) } f.key = fk + ":" + key t := f.fv.Type() if t.Kind() != reflect.Func { f.err = errors.New("not a function") return f } if t.NumIn() == 0 || !isContext(t.In(0)) { f.err = errFirstArg return f } // Register the function's arguments with the gob package. // This is required because they are marshaled inside a []interface{}. // gob.Register only expects to be called during initialization; // that's fine because this function expects the same. for i := 0; i < t.NumIn(); i++ { // Only concrete types may be registered. If the argument has // interface type, the client is resposible for registering the // concrete types it will hold. if t.In(i).Kind() == reflect.Interface { continue } gob.Register(reflect.Zero(t.In(i)).Interface()) } if old := funcs[f.key]; old != nil { old.err = fmt.Errorf("multiple functions registered for %s in %s", key, file) } funcs[f.key] = f return f }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L172-L175
func (p CaptureSnapshotParams) WithFormat(format CaptureSnapshotFormat) *CaptureSnapshotParams { p.Format = format return &p }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/pkg/ghclient/core.go#L95-L120
func (c *Client) retry(action string, call func() (*github.Response, error)) (*github.Response, error) { var err error var resp *github.Response for retryCount := 0; retryCount <= c.retries; retryCount++ { if resp, err = call(); err == nil { c.limitRate(&resp.Rate) return resp, nil } switch err := err.(type) { case *github.RateLimitError: c.limitRate(&err.Rate) case *github.TwoFactorAuthError: return resp, err case *retryAbort: return resp, err } if retryCount == c.retries { return resp, err } glog.Errorf("error %s: %v. Will retry.\n", action, err) c.sleepForAttempt(retryCount) } return resp, err }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/typestate.go#L69-L78
func (s *State) rootType(thriftType *parser.Type) *parser.Type { if state, newType, include := s.checkInclude(thriftType); include != nil { return state.rootType(newType) } if v, ok := s.typedefs[thriftType.Name]; ok { return s.rootType(v) } return thriftType }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/payment.go#L125-L156
func (m PayWithPath) MutatePayment(o interface{}) (err error) { var pathPaymentOp *xdr.PathPaymentOp var ok bool if pathPaymentOp, ok = o.(*xdr.PathPaymentOp); !ok { return errors.New("Unexpected operation type") } // MaxAmount pathPaymentOp.SendMax, err = amount.Parse(m.MaxAmount) if err != nil { return } // Path var path []xdr.Asset var xdrAsset xdr.Asset for _, asset := range m.Path { xdrAsset, err = asset.ToXdrObject() if err != nil { return err } path = append(path, xdrAsset) } pathPaymentOp.Path = path // Asset pathPaymentOp.SendAsset, err = m.Asset.ToXdrObject() return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/clientset/versioned/typed/prowjobs/v1/prowjob.go#L57-L62
func newProwJobs(c *ProwV1Client, namespace string) *prowJobs { return &prowJobs{ client: c.RESTClient(), ns: namespace, } }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L259-L267
func (q *Query) BatchSize(size int) *Query { q = q.clone() if size <= 0 || size > math.MaxInt32 { q.err = errors.New("datastore: query batch size overflow") return q } q.count = int32(size) return q }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_store.go#L39-L43
func (i *InmemStore) LastIndex() (uint64, error) { i.l.RLock() defer i.l.RUnlock() return i.highIndex, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/collection/collection.go#L178-L180
func (c *collection) indexPath(index *Index, indexVal interface{}, key string) string { return path.Join(c.indexDir(index, indexVal), key) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/admin.go#L66-L79
func (c APIClient) ExtractURL(url string) error { extractClient, err := c.AdminAPIClient.Extract(c.Ctx(), &admin.ExtractRequest{URL: url}) if err != nil { return grpcutil.ScrubGRPC(err) } resp, err := extractClient.Recv() if err == nil { return fmt.Errorf("unexpected response from extract: %v", resp) } if err != io.EOF { return err } return nil }
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L82-L84
func limitByteReader(r byteReader, n int64) *limitedByteReader { return &limitedByteReader{limitedReader{r, n, io.ErrUnexpectedEOF}, r} }
https://github.com/omniscale/go-mapnik/blob/710dfcc5e486e5760d0a5c46be909d91968e1ffb/mapnik.go#L301-L329
func (m *Map) Render(opts RenderOpts) ([]byte, error) { scaleFactor := opts.ScaleFactor if scaleFactor == 0.0 { scaleFactor = 1.0 } i := C.mapnik_map_render_to_image(m.m, C.double(opts.Scale), C.double(scaleFactor)) if i == nil { return nil, m.lastError() } defer C.mapnik_image_free(i) if opts.Format == "raw" { size := 0 raw := C.mapnik_image_to_raw(i, (*C.size_t)(unsafe.Pointer(&size))) return C.GoBytes(unsafe.Pointer(raw), C.int(size)), nil } var format *C.char if opts.Format != "" { format = C.CString(opts.Format) } else { format = C.CString("png256") } b := C.mapnik_image_to_blob(i, format) if b == nil { return nil, errors.New("mapnik: " + C.GoString(C.mapnik_image_last_error(i))) } C.free(unsafe.Pointer(format)) defer C.mapnik_image_blob_free(b) return C.GoBytes(unsafe.Pointer(b.ptr), C.int(b.len)), nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/slices.go#L16-L54
func SelectURIs(stmt *sql.Stmt, f func(a ...interface{}) string, args ...interface{}) ([]string, error) { rows, err := stmt.Query(args...) if err != nil { return nil, errors.Wrapf(err, "Failed to query URIs") } defer rows.Close() columns, err := rows.Columns() if err != nil { return nil, errors.Wrap(err, "Rows columns") } params := make([]interface{}, len(columns)) dest := make([]interface{}, len(params)) for i := range params { params[i] = "" dest[i] = &params[i] } uris := []string{} for rows.Next() { err := rows.Scan(dest...) if err != nil { return nil, errors.Wrapf(err, "Failed to scan URI params") } uri := f(params...) uris = append(uris, uri) } err = rows.Err() if err != nil { return nil, errors.Wrapf(err, "Failed to close URI result set") } return uris, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1754-L1778
func (app *App) Log(message, source, unit string) error { messages := strings.Split(message, "\n") logs := make([]interface{}, 0, len(messages)) for _, msg := range messages { if msg != "" { l := Applog{ Date: time.Now().In(time.UTC), Message: msg, Source: source, AppName: app.Name, Unit: unit, } logs = append(logs, l) } } if len(logs) > 0 { conn, err := db.LogConn() if err != nil { return err } defer conn.Close() return conn.AppLogCollection(app.Name).Insert(logs...) } return nil }
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L379-L411
func (t *Tree) LongestPrefix(s string) (string, interface{}, bool) { var last *leafNode n := t.root search := s for { // Look for a leaf node if n.isLeaf() { last = n.leaf } // Check for key exhaution if len(search) == 0 { break } // Look for an edge n = n.getEdge(search[0]) if n == nil { break } // Consume the search prefix if strings.HasPrefix(search, n.prefix) { search = search[len(n.prefix):] } else { break } } if last != nil { return last.key, last.val, true } return "", nil, false }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L416-L420
func (v SetNodeValueParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom3(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/client.go#L518-L527
func (c *Client) ReplaceProwJob(name string, job prowapi.ProwJob) (prowapi.ProwJob, error) { c.log("ReplaceProwJob", name, job) var retJob prowapi.ProwJob err := c.request(&request{ method: http.MethodPut, path: fmt.Sprintf("/apis/prow.k8s.io/v1/namespaces/%s/prowjobs/%s", c.namespace, name), requestBody: &job, }, &retJob) return retJob, err }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/enterprise/server/api_server.go#L205-L252
func (a *apiServer) Activate(ctx context.Context, req *ec.ActivateRequest) (resp *ec.ActivateResponse, retErr error) { a.LogReq(req) defer func(start time.Time) { a.pachLogger.Log(req, resp, retErr, time.Since(start)) }(time.Now()) // Validate the activation code expiration, err := validateActivationCode(req.ActivationCode) if err != nil { return nil, fmt.Errorf("error validating activation code: %s", err.Error()) } // Allow request to override expiration in the activation code, for testing if req.Expires != nil { customExpiration, err := types.TimestampFromProto(req.Expires) if err == nil && expiration.After(customExpiration) { expiration = customExpiration } } expirationProto, err := types.TimestampProto(expiration) if err != nil { return nil, fmt.Errorf("could not convert expiration time \"%s\" to proto: %s", expiration.String(), err.Error()) } if _, err := col.NewSTM(ctx, a.env.GetEtcdClient(), func(stm col.STM) error { e := a.enterpriseToken.ReadWrite(stm) // blind write return e.Put(enterpriseTokenKey, &ec.EnterpriseRecord{ ActivationCode: req.ActivationCode, Expires: expirationProto, }) }); err != nil { return nil, err } // Wait until watcher observes the write if err := backoff.Retry(func() error { if t := a.enterpriseExpiration.Load().(time.Time); t.IsZero() { return fmt.Errorf("enterprise not activated") } return nil }, backoff.RetryEvery(time.Second)); err != nil { return nil, err } time.Sleep(time.Second) // give other pachd nodes time to observe the write return &ec.ActivateResponse{ Info: &ec.TokenInfo{ Expires: expirationProto, }, }, nil }
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/object.go#L64-L75
func (o *Object) SetMetadata(key string, value string, attr MetadataAttributes) error { o.Metadata[key] = MetadataData{ value: value, attr: attr, } if attr.PrimaryKey { o.updatePrimaryKeyHash() } return nil }
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/client.go#L74-L79
func BasicAuth(username, password string) ClientParam { return func(c *Client) error { c.auth = &basicAuth{username: username, password: password} return nil } }
https://github.com/go-audio/transforms/blob/51830ccc35a5ce4be9d09b1d1f3f82dad376c240/gain.go#L10-L20
func Gain(buf *audio.FloatBuffer, multiplier float64) error { if buf == nil { return audio.ErrInvalidBuffer } for i := 0; i < len(buf.Data); i++ { buf.Data[i] *= multiplier } return nil }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/cmd/viewcore/main.go#L793-L834
func typeFieldName(t *gocore.Type, off int64) string { switch t.Kind { case gocore.KindBool, gocore.KindInt, gocore.KindUint, gocore.KindFloat: return "" case gocore.KindComplex: if off == 0 { return ".real" } return ".imag" case gocore.KindIface, gocore.KindEface: if off == 0 { return ".type" } return ".data" case gocore.KindPtr, gocore.KindFunc: return "" case gocore.KindString: if off == 0 { return ".ptr" } return ".len" case gocore.KindSlice: if off == 0 { return ".ptr" } if off <= t.Size/2 { return ".len" } return ".cap" case gocore.KindArray: s := t.Elem.Size i := off / s return fmt.Sprintf("[%d]%s", i, typeFieldName(t.Elem, off-i*s)) case gocore.KindStruct: for _, f := range t.Fields { if f.Off <= off && off < f.Off+f.Type.Size { return "." + f.Name + typeFieldName(f.Type, off-f.Off) } } } return ".???" }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/cachestorage.go#L131-L140
func (p *RequestCachedResponseParams) Do(ctx context.Context) (response *CachedResponse, err error) { // execute var res RequestCachedResponseReturns err = cdp.Execute(ctx, CommandRequestCachedResponse, p, &res) if err != nil { return nil, err } return res.Response, nil }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/encoder.go#L114-L116
func EncodeFloat64(w io.Writer, f float64) (err error) { return EncodeUint64(w, math.Float64bits(f)) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/easyjson.go#L283-L287
func (v RemoveDOMStorageItemParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomstorage2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/types.go#L52-L66
func (t *WindowState) UnmarshalEasyJSON(in *jlexer.Lexer) { switch WindowState(in.String()) { case WindowStateNormal: *t = WindowStateNormal case WindowStateMinimized: *t = WindowStateMinimized case WindowStateMaximized: *t = WindowStateMaximized case WindowStateFullscreen: *t = WindowStateFullscreen default: in.AddError(errors.New("unknown WindowState value")) } }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L339-L344
func (l *InclusiveRanges) End() int { if l.blocks == nil { return 0 } return l.blocks[len(l.blocks)-1].End() }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L7090-L7092
func (api *API) Oauth2Locator(href string) *Oauth2Locator { return &Oauth2Locator{Href(href), api} }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3158-L3167
func (u ManageOfferResult) GetSuccess() (result ManageOfferSuccessResult, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Code)) if armName == "Success" { result = *u.Success ok = true } return }
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L176-L180
func (c *Consumer) ResetOffset(msg *sarama.ConsumerMessage, metadata string) { if sub := c.subs.Fetch(msg.Topic, msg.Partition); sub != nil { sub.ResetOffset(msg.Offset, metadata) } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/util.go#L58-L60
func newStreamRoundTripper(tlsInfo transport.TLSInfo, dialTimeout time.Duration) (http.RoundTripper, error) { return transport.NewTimeoutTransport(tlsInfo, dialTimeout, ConnReadTimeout, ConnWriteTimeout) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/exec/exec.go#L286-L291
func (c *Cmd) Run() error { if err := c.Start(); err != nil { return err } return c.Wait() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L847-L851
func (v InspectWorkerParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoServiceworker9(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L259-L262
func (p FocusParams) WithNodeID(nodeID cdp.NodeID) *FocusParams { p.NodeID = nodeID return &p }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/branch_protection.go#L148-L156
func (p Policy) Apply(child Policy) Policy { return Policy{ Protect: selectBool(p.Protect, child.Protect), RequiredStatusChecks: mergeContextPolicy(p.RequiredStatusChecks, child.RequiredStatusChecks), Admins: selectBool(p.Admins, child.Admins), Restrictions: mergeRestrictions(p.Restrictions, child.Restrictions), RequiredPullRequestReviews: mergeReviewPolicy(p.RequiredPullRequestReviews, child.RequiredPullRequestReviews), } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/branch_protection.go#L222-L232
func (c *Config) GetBranchProtection(org, repo, branch string) (*Policy, error) { if _, present := c.BranchProtection.Orgs[org]; !present { return nil, nil // only consider branches in configured orgs } b, err := c.BranchProtection.GetOrg(org).GetRepo(repo).GetBranch(branch) if err != nil { return nil, err } return c.GetPolicy(org, repo, branch, *b) }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L149-L160
func (st *State) Reset() { st.opidx = 0 st.sa = nil st.sb = nil st.stack.Reset() st.markstack.Reset() st.frames.Reset() st.framestack.Reset() st.Pushmark() st.PushFrame() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L1810-L1814
func (v *CanEmulateParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoEmulation21(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L170-L173
func (p DeleteCookiesParams) WithDomain(domain string) *DeleteCookiesParams { p.Domain = domain return &p }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/move_leader_command.go#L26-L33
func NewMoveLeaderCommand() *cobra.Command { cmd := &cobra.Command{ Use: "move-leader <transferee-member-id>", Short: "Transfers leadership to another etcd cluster member.", Run: transferLeadershipCommandFunc, } return cmd }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L178-L205
func ScanASTBody(pkg, defName string, bzlFile *bzl.File) *File { f := &File{ File: bzlFile, Pkg: pkg, Path: bzlFile.Path, } var defStmt *bzl.DefStmt f.Rules, f.Loads, defStmt = scanExprs(defName, bzlFile.Stmt) if defStmt != nil { f.Rules, _, _ = scanExprs("", defStmt.Body) f.function = &function{ stmt: defStmt, inserted: true, } if len(defStmt.Body) == 1 { if v, ok := defStmt.Body[0].(*bzl.BranchStmt); ok && v.Token == "pass" { f.function.hasPass = true } } } else if defName != "" { f.function = &function{ stmt: &bzl.DefStmt{Name: defName}, inserted: false, } } f.Directives = ParseDirectives(bzlFile) return f }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L221-L224
func (p SetDeviceMetricsOverrideParams) WithScreenWidth(screenWidth int64) *SetDeviceMetricsOverrideParams { p.ScreenWidth = screenWidth return &p }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/command_line.go#L21-L109
func ParseCommandLine(app *kingpin.Application) (*cmd.CommandLine, error) { // 1. Register all commands app.Command("setup", "create config file, defaults to $HOME/.rsc, use '--config' to override") app.Command("json", "apply jsonselect expression to STDIN") RegisterClientCommands(app) // 2. Parse flags cmdLine := cmd.CommandLine{} app.Flag("config", "path to rsc config file").Short('c').Default(path.Join(os.Getenv("HOME"), ".rsc")).StringVar(&cmdLine.ConfigPath) app.Flag("retry", "Number of retry attempts for non-successful API responses (500, 503, and timeouts only)").Short('R').Default("0").IntVar(&cmdLine.Retry) app.Flag("account", "RightScale account ID").Short('a').IntVar(&cmdLine.Account) app.Flag("host", "RightScale login endpoint (e.g. 'us-3.rightscale.com')").Short('h').StringVar(&cmdLine.Host) app.Flag("email", "Login email, use --email and --pwd or use --refreshToken, --accessToken, --apiToken or --rl10").StringVar(&cmdLine.Username) app.Flag("pwd", "Login password, use --email and --pwd or use --refreshToken, --accessToken, --apiToken or --rl10").StringVar(&cmdLine.Password) app.Flag("refreshToken", "OAuth refresh token, use --email and --pwd or use --refreshToken, --accessToken, --apiToken or --rl10").Short('r').StringVar(&cmdLine.OAuthToken) app.Flag("accessToken", "OAuth access token, use --email and --pwd or use --refreshToken, --accessToken, --apiToken or --rl10").Short('s').StringVar(&cmdLine.OAuthAccessToken) app.Flag("apiToken", "Instance API token, use --email and --pwd or use --refreshToken, --accessToken, --apiToken or --rl10").Short('p').StringVar(&cmdLine.APIToken) app.Flag("rl10", "Proxy requests through RightLink 10 agent, use --email and --pwd or use --refreshToken, --accessToken, --apiToken or --rl10").BoolVar(&cmdLine.RL10) app.Flag("noAuth", "Make unauthenticated requests, used for testing").BoolVar(&cmdLine.NoAuth) app.Flag("timeout", "Set the request timeout, defaults to 300s").Short('t').Default("300").IntVar(&cmdLine.Timeout) app.Flag("x1", "Extract single value using JSON:select").StringVar(&cmdLine.ExtractOneSelect) app.Flag("xm", "Extract zero, one or more values using JSON:select and return newline separated list").StringVar(&cmdLine.ExtractSelector) app.Flag("xj", "Extract zero, one or more values using JSON:select and return JSON").StringVar(&cmdLine.ExtractSelectorJSON) app.Flag("xh", "Extract header with given name").StringVar(&cmdLine.ExtractHeader) app.Flag("fetch", "Fetch resource with href present in 'Location' header").BoolVar(&cmdLine.FetchResource) app.Flag("dump", "Dump HTTP request and response. Possible values are 'debug' or 'json'.").EnumVar(&cmdLine.Dump, "debug", "json", "record") app.Flag("verbose", "Dump HTTP request and response including auth requests and headers, enables --dump=debug by default, use --dump=json to switch format").Short('v').BoolVar(&cmdLine.Verbose) app.Flag("pp", "Pretty print response body").BoolVar(&cmdLine.Pretty) // Keep around for a few releases for backwards compatibility app.Flag("key", "OAuth refresh token, use --email and --pwd or use --refreshToken, --accessToken, --apiToken or --rl10").Short('k').Hidden().StringVar(&cmdLine.OAuthToken) args := os.Args[1:] if len(args) == 0 { args = []string{"--help"} } // This is a bit hacky: basically doing `rsc api15 index clouds --help` results // in a command line that kingpin hijacks. So capture the `--help` try parsing // without it so we can print our own help. lastArgIndex := len(args) help := args[lastArgIndex-1] var cmd string var err error if help == "--help" || help == "-h" || help == "-help" || help == "-?" { cmdLine.ShowHelp = true lastArgIndex-- cmd, err = app.Parse(args[:lastArgIndex]) } else { cmd, err = app.Parse(args) } if err != nil { return nil, err } // 3. Complement with defaults from config at given path if !cmdLine.NoAuth { if config, err := LoadConfig(cmdLine.ConfigPath); err == nil { if cmdLine.OAuthAccessToken == "" && cmdLine.OAuthToken == "" { if cmdLine.Account == 0 { cmdLine.Account = config.Account } if cmdLine.Username == "" { cmdLine.Username = config.Email } if cmdLine.Password == "" { cmdLine.Password = config.Password } } if cmdLine.Host == "" { cmdLine.Host = config.LoginHost } if cmdLine.OAuthToken == "" { cmdLine.OAuthToken = config.RefreshToken } } } cmdLine.Command = cmd // 4. Special RL10 case (auth is handled differently) if strings.Split(cmdLine.Command, " ")[0] == "rl10" { cmdLine.RL10 = true } // 6. Validate we have everything we need validateCommandLine(&cmdLine) // 7. We're done return &cmdLine, nil }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/value.go#L71-L84
func zeroValueOf(t reflect.Type) reflect.Value { zeroMutex.RLock() v, ok := zeroCache[t] zeroMutex.RUnlock() if !ok { v = reflect.Zero(t) zeroMutex.Lock() zeroCache[t] = v zeroMutex.Unlock() } return v }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/lease/leasehttp/http.go#L193-L242
func TimeToLiveHTTP(ctx context.Context, id lease.LeaseID, keys bool, url string, rt http.RoundTripper) (*leasepb.LeaseInternalResponse, error) { // will post lreq protobuf to leader lreq, err := (&leasepb.LeaseInternalRequest{ LeaseTimeToLiveRequest: &pb.LeaseTimeToLiveRequest{ ID: int64(id), Keys: keys, }, }).Marshal() if err != nil { return nil, err } req, err := http.NewRequest("POST", url, bytes.NewReader(lreq)) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/protobuf") req = req.WithContext(ctx) cc := &http.Client{Transport: rt} var b []byte // buffer errc channel so that errc don't block inside the go routinue resp, err := cc.Do(req) if err != nil { return nil, err } b, err = readResponse(resp) if err != nil { return nil, err } if resp.StatusCode == http.StatusRequestTimeout { return nil, ErrLeaseHTTPTimeout } if resp.StatusCode == http.StatusNotFound { return nil, lease.ErrLeaseNotFound } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("lease: unknown error(%s)", string(b)) } lresp := &leasepb.LeaseInternalResponse{} if err := lresp.Unmarshal(b); err != nil { return nil, fmt.Errorf(`lease: %v. data = "%s"`, err, string(b)) } if lresp.LeaseTimeToLiveResponse.ID != int64(id) { return nil, fmt.Errorf("lease: renew id mismatch") } return lresp, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps.go#L134-L141
func NewCronInput(name string, spec string) *pps.Input { return &pps.Input{ Cron: &pps.CronInput{ Name: name, Spec: spec, }, } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container.go#L39-L46
func containerGetParentAndSnapshotName(name string) (string, string, bool) { fields := strings.SplitN(name, shared.SnapshotDelimiter, 2) if len(fields) == 1 { return name, "", false } return fields[0], fields[1], true }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/client/mock_service.go#L9-L17
func (m *MockService) NewService(args []string) Service { m.Args = []string{ "service", } m.Args = append(m.Args, args...) m.Cmd = getMockServiceCommandPath() return m }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/listers/tsuru/v1/app.go#L67-L72
func (s appNamespaceLister) List(selector labels.Selector) (ret []*v1.App, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { ret = append(ret, m.(*v1.App)) }) return ret, err }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L7090-L7098
func (u ScpStatementPledges) MustPrepare() ScpStatementPrepare { val, ok := u.GetPrepare() if !ok { panic("arm Prepare is not set") } return val }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/fileseq.go#L257-L263
func minMaxFrame(frames []int) (int, int) { srcframes := make([]int, len(frames), len(frames)) copy(srcframes, frames) sort.Ints(srcframes) min, max := srcframes[0], srcframes[len(srcframes)-1] return min, max }
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/marshal.go#L17-L22
func MarshalStr(n tree.Node) (string, error) { ret := bytes.NewBufferString("") err := marshal(n, ret) return ret.String(), err }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/xslate.go#L108-L111
func DefaultCompiler(tx *Xslate, args Args) error { tx.Compiler = compiler.New() return nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4906-L4915
func (u LedgerUpgrade) GetNewMaxTxSetSize() (result Uint32, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "NewMaxTxSetSize" { result = *u.NewMaxTxSetSize ok = true } return }
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/ctors.go#L38-L51
func (api *TelegramBotAPI) NewOutgoingVenue(recipient Recipient, latitude, longitude float32, title, address string) *OutgoingVenue { return &OutgoingVenue{ outgoingMessageBase: outgoingMessageBase{ outgoingBase: outgoingBase{ api: api, Recipient: recipient, }, }, Latitude: latitude, Longitude: longitude, Title: title, Address: address, } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/embed/serve.go#L302-L304
func createAccessController(lg *zap.Logger, s *etcdserver.EtcdServer, mux *http.ServeMux) http.Handler { return &accessController{lg: lg, s: s, mux: mux} }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/gcs/upload.go#L38-L64
func Upload(bucket *storage.BucketHandle, uploadTargets map[string]UploadFunc) error { errCh := make(chan error, len(uploadTargets)) group := &sync.WaitGroup{} group.Add(len(uploadTargets)) for dest, upload := range uploadTargets { obj := bucket.Object(dest) logrus.WithField("dest", dest).Info("Queued for upload") go func(f UploadFunc, obj *storage.ObjectHandle, name string) { defer group.Done() if err := f(obj); err != nil { errCh <- err } logrus.WithField("dest", name).Info("Finished upload") }(upload, obj, dest) } group.Wait() close(errCh) if len(errCh) != 0 { var uploadErrors []error for err := range errCh { uploadErrors = append(uploadErrors, err) } return fmt.Errorf("encountered errors during upload: %v", uploadErrors) } return nil }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/edit.go#L31-L65
func EditCmd() *cobra.Command { var eo = &cli.EditOptions{} var editCmd = &cobra.Command{ Use: "edit <NAME>", Short: "Edit a cluster state", Long: `Use this command to edit a state.`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: eo.Name = viper.GetString(keyKubicornName) case 1: eo.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runEdit(eo); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := editCmd.Flags() bindCommonStateStoreFlags(&eo.StateStoreOptions, fs) bindCommonAwsFlags(&eo.AwsOptions, fs) fs.StringVarP(&eo.Editor, keyEditor, "e", viper.GetString(keyEditor), descEditor) fs.StringVar(&eo.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) return editCmd }