_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3election/v3electionpb/gw/v3election.pb.gw.go#L132-L134
func RegisterElectionHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { return RegisterElectionHandlerClient(ctx, mux, v3electionpb.NewElectionClient(conn)) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/ranch/ranch.go#L209-L229
func (r *Ranch) Release(name, dest, owner string) error { r.resourcesLock.Lock() defer r.resourcesLock.Unlock() res, err := r.Storage.GetResource(name) if err != nil { logrus.WithError(err).Errorf("unable to release resource %s", name) return &ResourceNotFound{name} } if owner != res.Owner { return &OwnerNotMatch{owner: owner, request: res.Owner} } res.LastUpdate = r.UpdateTime() res.Owner = "" res.State = dest if err := r.Storage.UpdateResource(res); err != nil { logrus.WithError(err).Errorf("could not update resource %s", res.Name) return err } return nil }
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/log/access.go#L36-L40
func DateFormat(f string) Option { return Option{func(o *options) { o.dateFormat = f }} }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L523-L545
func (c APIClient) SubscribeCommitF(repo, branch, from string, state pfs.CommitState, f func(*pfs.CommitInfo) error) error { req := &pfs.SubscribeCommitRequest{ Repo: NewRepo(repo), Branch: branch, State: state, } if from != "" { req.From = NewCommit(repo, from) } stream, err := c.PfsAPIClient.SubscribeCommit(c.Ctx(), req) if err != nil { return grpcutil.ScrubGRPC(err) } for { ci, err := stream.Recv() if err != nil { return grpcutil.ScrubGRPC(err) } if err := f(ci); err != nil { return grpcutil.ScrubGRPC(err) } } }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gbytes/io_wrappers.go#L23-L25
func TimeoutWriter(w io.Writer, timeout time.Duration) io.Writer { return timeoutReaderWriterCloser{w: w, d: timeout} }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/read.go#L137-L145
func (p *Process) ReadCString(a Address) string { for n := int64(0); ; n++ { if p.ReadUint8(a.Add(n)) == 0 { b := make([]byte, n) p.ReadAt(b, a) return string(b) } } }
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L239-L241
func (s *Seekret) AddException(exception models.Exception) { s.exceptionList = append(s.exceptionList, exception) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L236-L245
func (p *GetBackgroundColorsParams) Do(ctx context.Context) (backgroundColors []string, computedFontSize string, computedFontWeight string, err error) { // execute var res GetBackgroundColorsReturns err = cdp.Execute(ctx, CommandGetBackgroundColors, p, &res) if err != nil { return nil, "", "", err } return res.BackgroundColors, res.ComputedFontSize, res.ComputedFontWeight, nil }
https://github.com/btcsuite/btclog/blob/84c8d2346e9fc8c7b947e243b9c24e6df9fd206a/log.go#L454-L459
func (l *slog) Criticalf(format string, args ...interface{}) { lvl := l.Level() if lvl <= LevelCritical { l.b.printf("CRT", l.tag, format, args...) } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/tools/etcd-dump-logs/main.go#L305-L378
func listEntriesType(entrytype string, streamdecoder string, ents []raftpb.Entry) { entryFilters := evaluateEntrytypeFlag(entrytype) printerMap := map[string]EntryPrinter{"InternalRaftRequest": printInternalRaftRequest, "Request": printRequest, "ConfigChange": printConfChange, "UnknownNormal": printUnknownNormal} var stderr bytes.Buffer args := strings.Split(streamdecoder, " ") cmd := exec.Command(args[0], args[1:]...) stdin, err := cmd.StdinPipe() if err != nil { log.Panic(err) } stdout, err := cmd.StdoutPipe() if err != nil { log.Panic(err) } cmd.Stderr = &stderr if streamdecoder != "" { err = cmd.Start() if err != nil { log.Panic(err) } } cnt := 0 for _, e := range ents { passed := false currtype := "" for _, filter := range entryFilters { passed, currtype = filter(e) if passed { cnt++ break } } if passed { printer := printerMap[currtype] printer(e) if streamdecoder == "" { fmt.Println() continue } // if decoder is set, pass the e.Data to stdin and read the stdout from decoder io.WriteString(stdin, hex.EncodeToString(e.Data)) io.WriteString(stdin, "\n") outputReader := bufio.NewReader(stdout) decoderoutput, currerr := outputReader.ReadString('\n') if currerr != nil { fmt.Println(currerr) return } decoder_status, decoded_data := parseDecoderOutput(decoderoutput) fmt.Printf("\t%s\t%s", decoder_status, decoded_data) } } stdin.Close() err = cmd.Wait() if streamdecoder != "" { if err != nil { log.Panic(err) } if stderr.String() != "" { os.Stderr.WriteString("decoder stderr: " + stderr.String()) } } fmt.Printf("\nEntry types (%s) count is : %d", entrytype, cnt) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L6698-L6704
func (c *containerLXC) deviceExistsInDevicesFolder(prefix string, path string) bool { relativeDestPath := strings.TrimPrefix(path, "/") devName := fmt.Sprintf("%s.%s", strings.Replace(prefix, "/", "-", -1), strings.Replace(relativeDestPath, "/", "-", -1)) devPath := filepath.Join(c.DevicesPath(), devName) return shared.PathExists(devPath) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/exec/exec.go#L740-L761
func dedupEnvCase(caseInsensitive bool, env []string) []string { out := make([]string, 0, len(env)) saw := map[string]int{} // key => index into out for _, kv := range env { eq := strings.Index(kv, "=") if eq < 0 { out = append(out, kv) continue } k := kv[:eq] if caseInsensitive { k = strings.ToLower(k) } if dupIdx, isDup := saw[k]; isDup { out[dupIdx] = kv continue } saw[k] = len(out) out = append(out, kv) } return out }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L5501-L5505
func (v *EventJavascriptDialogOpening) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage56(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/driver.go#L1630-L1745
func (d *driver) createBranch(pachClient *client.APIClient, branch *pfs.Branch, commit *pfs.Commit, provenance []*pfs.Branch) error { ctx := pachClient.Ctx() if err := d.checkIsAuthorized(pachClient, branch.Repo, auth.Scope_WRITER); err != nil { return err } // Validate request. The request must do exactly one of: // 1) updating 'branch's provenance (commit is nil OR commit == branch) // 2) re-pointing 'branch' at a new commit if commit != nil { // Determine if this is a provenance update sameTarget := branch.Repo.Name == commit.Repo.Name && branch.Name == commit.ID if !sameTarget && provenance != nil { return fmt.Errorf("cannot point branch \"%s\" at target commit \"%s/%s\" without clearing its provenance", branch.Name, commit.Repo.Name, commit.ID) } } _, err := col.NewSTM(ctx, d.etcdClient, func(stm col.STM) error { // if 'commit' is a branch, resolve it var err error if commit != nil { _, err = d.resolveCommit(stm, commit) // if 'commit' is a branch, resolve it if err != nil { // possible that branch exists but has no head commit. This is fine, but // branchInfo.Head must also be nil if !isNoHeadErr(err) { return fmt.Errorf("unable to inspect %s/%s: %v", err, commit.Repo.Name, commit.ID) } commit = nil } } // Retrieve (and create, if necessary) the current version of this branch branches := d.branches(branch.Repo.Name).ReadWrite(stm) branchInfo := &pfs.BranchInfo{} if err := branches.Upsert(branch.Name, branchInfo, func() error { branchInfo.Name = branch.Name // set in case 'branch' is new branchInfo.Branch = branch branchInfo.Head = commit branchInfo.DirectProvenance = nil for _, provBranch := range provenance { add(&branchInfo.DirectProvenance, provBranch) } return nil }); err != nil { return err } repos := d.repos.ReadWrite(stm) repoInfo := &pfs.RepoInfo{} if err := repos.Update(branch.Repo.Name, repoInfo, func() error { add(&repoInfo.Branches, branch) return nil }); err != nil { return err } // Update (or create) // 1) 'branch's Provenance // 2) the Provenance of all branches in 'branch's Subvenance (in the case of an update), and // 3) the Subvenance of all branches in the *old* provenance of 'branch's Subvenance toUpdate := []*pfs.BranchInfo{branchInfo} for _, subvBranch := range branchInfo.Subvenance { subvBranchInfo := &pfs.BranchInfo{} if err := d.branches(subvBranch.Repo.Name).ReadWrite(stm).Get(subvBranch.Name, subvBranchInfo); err != nil { return err } toUpdate = append(toUpdate, subvBranchInfo) } // Sorting is important here because it sorts topologically. This means // that when evaluating element i of `toUpdate` all elements < i will // have already been evaluated and thus we can safely use their // Provenance field. sort.Slice(toUpdate, func(i, j int) bool { return len(toUpdate[i].Provenance) < len(toUpdate[j].Provenance) }) for _, branchInfo := range toUpdate { oldProvenance := branchInfo.Provenance branchInfo.Provenance = nil // Re-compute Provenance for _, provBranch := range branchInfo.DirectProvenance { if err := d.addBranchProvenance(branchInfo, provBranch, stm); err != nil { return err } provBranchInfo := &pfs.BranchInfo{} if err := d.branches(provBranch.Repo.Name).ReadWrite(stm).Get(provBranch.Name, provBranchInfo); err != nil { return err } for _, provBranch := range provBranchInfo.Provenance { if err := d.addBranchProvenance(branchInfo, provBranch, stm); err != nil { return err } } } if err := d.branches(branchInfo.Branch.Repo.Name).ReadWrite(stm).Put(branchInfo.Branch.Name, branchInfo); err != nil { return err } // Update Subvenance of 'branchInfo's Provenance (incl. all Subvenance) for _, oldProvBranch := range oldProvenance { if !has(&branchInfo.Provenance, oldProvBranch) { // Provenance was deleted, so we delete ourselves from their subvenance oldProvBranchInfo := &pfs.BranchInfo{} if err := d.branches(oldProvBranch.Repo.Name).ReadWrite(stm).Update(oldProvBranch.Name, oldProvBranchInfo, func() error { del(&oldProvBranchInfo.Subvenance, branchInfo.Branch) return nil }); err != nil { return err } } } } // propagate the head commit to 'branch'. This may also modify 'branch', by // creating a new HEAD commit if 'branch's provenance was changed and its // current HEAD commit has old provenance return d.propagateCommit(stm, branch) }) return err }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/auth/auth.go#L108-L113
func IsErrNoMetadata(err error) bool { if err == nil { return false } return strings.Contains(err.Error(), status.Convert(ErrNoMetadata).Message()) }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L115-L117
func (s *selectable) FirstByXPath(selector string) *Selection { return newSelection(s.session, s.selectors.Append(target.XPath, selector).At(0)) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/auth_command.go#L25-L35
func NewAuthCommand() *cobra.Command { ac := &cobra.Command{ Use: "auth <enable or disable>", Short: "Enable or disable authentication", } ac.AddCommand(newAuthEnableCommand()) ac.AddCommand(newAuthDisableCommand()) return ac }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L588-L596
func (f *FakeClient) TeamHasMember(teamID int, memberLogin string) (bool, error) { teamMembers, _ := f.ListTeamMembers(teamID, github.RoleAll) for _, member := range teamMembers { if member.Login == memberLogin { return true, nil } } return false, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3126-L3130
func (v GetRelayoutBoundaryParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom35(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L434-L463
func assignsTo(x *ast.Ident, scope []ast.Stmt) bool { assigned := false ff := func(n interface{}) { if assigned { return } switch n := n.(type) { case *ast.UnaryExpr: // use of &x if n.Op == token.AND && refersTo(n.X, x) { assigned = true return } case *ast.AssignStmt: for _, l := range n.Lhs { if refersTo(l, x) { assigned = true return } } } } for _, n := range scope { if assigned { break } walk(n, ff) } return assigned }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_transport.go#L115-L121
func (ref dockerReference) PolicyConfigurationIdentity() string { res, err := policyconfiguration.DockerReferenceIdentity(ref.ref) if res == "" || err != nil { // Coverage: Should never happen, NewReference above should refuse values which could cause a failure. panic(fmt.Sprintf("Internal inconsistency: policyconfiguration.DockerReferenceIdentity returned %#v, %v", res, err)) } return res }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/histogram.go#L138-L169
func (histogram histogramData) printHistogram() { fmt.Printf("Total count: %d\n", histogram.totalCount) fmt.Printf("Min value: %d\n", histogram.min) fmt.Printf("Max value: %d\n", histogram.max) fmt.Printf("Mean: %.2f\n", float64(histogram.sum)/float64(histogram.totalCount)) fmt.Printf("%24s %9s\n", "Range", "Count") numBins := len(histogram.bins) for index, count := range histogram.countPerBin { if count == 0 { continue } // The last bin represents the bin that contains the range from // the last bin up to infinity so it's processed differently than the // other bins. if index == len(histogram.countPerBin)-1 { lowerBound := int(histogram.bins[numBins-1]) fmt.Printf("[%10d, %10s) %9d\n", lowerBound, "infinity", count) continue } upperBound := int(histogram.bins[index]) lowerBound := 0 if index > 0 { lowerBound = int(histogram.bins[index-1]) } fmt.Printf("[%10d, %10d) %9d\n", lowerBound, upperBound, count) } fmt.Println() }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L149-L173
func (p *Page) SetCookie(cookie *http.Cookie) error { if cookie == nil { return errors.New("nil cookie is invalid") } var expiry int64 if !cookie.Expires.IsZero() { expiry = cookie.Expires.Unix() } apiCookie := &api.Cookie{ Name: cookie.Name, Value: cookie.Value, Path: cookie.Path, Domain: cookie.Domain, Secure: cookie.Secure, HTTPOnly: cookie.HttpOnly, Expiry: float64(expiry), } if err := p.session.SetCookie(apiCookie); err != nil { return fmt.Errorf("failed to set cookie: %s", err) } return nil }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/run/showcmd.go#L20-L25
func NewShowCmd(releaseRepo pull.Release, release string) *ShowCmd { return &ShowCmd{ releaseRepo: releaseRepo, release: release, } }
https://github.com/akutz/gotil/blob/6fa2e80bd3ac40f15788cfc3d12ebba49a0add92/gotil.go#L191-L207
func RandomString(length int) string { src := rand.NewSource(time.Now().UnixNano()) b := make([]byte, length) for i, cache, remain := length-1, src.Int63(), letterIndexMax; i >= 0; { if remain == 0 { cache, remain = src.Int63(), letterIndexMax } if idx := int(cache & letterIndexMask); idx < len(letterBytes) { b[i] = letterBytes[idx] i-- } cache >>= letterIndexBits remain-- } return string(b) }
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/multi.go#L16-L22
func MultiLogger(backends ...Backend) LeveledBackend { var leveledBackends []LeveledBackend for _, backend := range backends { leveledBackends = append(leveledBackends, AddModuleLevel(backend)) } return &multiLogger{leveledBackends} }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/error_registry.go#L79-L83
func (r *MapErrorRegistry) MustAddError(code int, err error) { if e := r.AddError(code, err); e != nil { panic(e) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L204-L211
func SetDeviceMetricsOverride(width int64, height int64, deviceScaleFactor float64, mobile bool) *SetDeviceMetricsOverrideParams { return &SetDeviceMetricsOverrideParams{ Width: width, Height: height, DeviceScaleFactor: deviceScaleFactor, Mobile: mobile, } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L756-L758
func (api *API) EndUserLocator(href string) *EndUserLocator { return &EndUserLocator{Href(href), api} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/webaudio/types.go#L63-L65
func (t *ContextType) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/s3/util.go#L24-L33
func writeXML(w http.ResponseWriter, r *http.Request, code int, v interface{}) { w.Header().Set("Content-Type", "application/xml") w.WriteHeader(code) encoder := xml.NewEncoder(w) if err := encoder.Encode(v); err != nil { // just log a message since a response has already been partially // written requestLogger(r).Errorf("could not encode xml response: %v", err) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1931-L1935
func (v *AddInspectedHeapObjectParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeapprofiler23(&r, v) return r.Error() }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/router.go#L205-L211
func (router *Router) sendAllGossipDown(conn Connection) { for channel := range router.gossipChannelSet() { if gossip := channel.gossiper.Gossip(); gossip != nil { channel.SendDown(conn, gossip) } } }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L717-L739
func (v *VM) RemoveSnapshot(snapshot *Snapshot, options RemoveSnapshotOption) error { var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE var err C.VixError = C.VIX_OK jobHandle = C.VixVM_RemoveSnapshot(v.handle, //vmHandle snapshot.handle, //snapshotHandle C.VixRemoveSnapshotOptions(options), //options nil, //callbackProc nil) //clientData defer C.Vix_ReleaseHandle(jobHandle) err = C.vix_job_wait(jobHandle) if C.VIX_OK != err { return &Error{ Operation: "vm.RemoveSnapshot", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } return nil }
https://github.com/danott/envflag/blob/14c5f9aaa227ddb49f3206fe06432edfc27735a5/envflag.go#L113-L118
func flagAsEnv(name string) string { name = strings.ToUpper(EnvPrefix + name) name = strings.Replace(name, ".", "_", -1) name = strings.Replace(name, "-", "_", -1) return name }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/item.go#L69-L73
func CompareInt(this, that unsafe.Pointer) int { thisItem := (*intKeyItem)(this) thatItem := (*intKeyItem)(that) return int(*thisItem - *thatItem) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/assign/assign.go#L112-L163
func handle(h *handler) error { e := h.event org := e.Repo.Owner.Login repo := e.Repo.Name matches := h.regexp.FindAllStringSubmatch(e.Body, -1) if matches == nil { return nil } users := make(map[string]bool) for _, re := range matches { add := re[1] != "un" // un<cmd> == !add if re[2] == "" { users[e.User.Login] = add } else { for _, login := range parseLogins(re[2]) { users[login] = add } } } var toAdd, toRemove []string for login, add := range users { if add { toAdd = append(toAdd, login) } else { toRemove = append(toRemove, login) } } if len(toRemove) > 0 { h.log.Printf("Removing %s from %s/%s#%d: %v", h.userType, org, repo, e.Number, toRemove) if err := h.remove(org, repo, e.Number, toRemove); err != nil { return err } } if len(toAdd) > 0 { h.log.Printf("Adding %s to %s/%s#%d: %v", h.userType, org, repo, e.Number, toAdd) if err := h.add(org, repo, e.Number, toAdd); err != nil { if mu, ok := err.(github.MissingUsers); ok { msg := h.addFailureResponse(mu) if len(msg) == 0 { return nil } if err := h.gc.CreateComment(org, repo, e.Number, plugins.FormatResponseRaw(e.Body, e.HTMLURL, e.User.Login, msg)); err != nil { return fmt.Errorf("comment err: %v", err) } return nil } return err } } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/node.go#L74-L88
func (c *ClusterTx) NodeByName(name string) (NodeInfo, error) { null := NodeInfo{} nodes, err := c.nodes(false /* not pending */, "name=?", name) if err != nil { return null, err } switch len(nodes) { case 0: return null, ErrNoSuchObject case 1: return nodes[0], nil default: return null, fmt.Errorf("more than one node matches") } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/auth/options.go#L54-L60
func (opts *jwtOptions) ParseWithDefaults(optMap map[string]string) error { if opts.TTL == 0 && optMap[optTTL] == "" { opts.TTL = DefaultTTL } return opts.Parse(optMap) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L435-L481
func (c *Cluster) StoragePoolGet(poolName string) (int64, *api.StoragePool, error) { var poolDriver string poolID := int64(-1) description := sql.NullString{} var state int query := "SELECT id, driver, description, state FROM storage_pools WHERE name=?" inargs := []interface{}{poolName} outargs := []interface{}{&poolID, &poolDriver, &description, &state} err := dbQueryRowScan(c.db, query, inargs, outargs) if err != nil { if err == sql.ErrNoRows { return -1, nil, ErrNoSuchObject } return -1, nil, err } config, err := c.StoragePoolConfigGet(poolID) if err != nil { return -1, nil, err } storagePool := api.StoragePool{ Name: poolName, Driver: poolDriver, } storagePool.Description = description.String storagePool.Config = config switch state { case storagePoolPending: storagePool.Status = "Pending" case storagePoolCreated: storagePool.Status = "Created" default: storagePool.Status = "Unknown" } nodes, err := c.storagePoolNodes(poolID) if err != nil { return -1, nil, err } storagePool.Locations = nodes return poolID, &storagePool, nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/metadata.go#L60-L78
func KindProperties(ctx context.Context, kind string) (map[string][]string, error) { // TODO(djd): Support range queries. kindKey := NewKey(ctx, kindKind, kind, 0, nil) q := NewQuery(propertyKind).Ancestor(kindKey) propMap := map[string][]string{} props := []struct { Repr []string `datastore:"property_representation"` }{} keys, err := q.GetAll(ctx, &props) if err != nil { return nil, err } for i, p := range props { propMap[keys[i].StringID()] = p.Repr } return propMap, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/worker/client.go#L123-L134
func NewClient(address string) (Client, error) { port, err := strconv.Atoi(os.Getenv(client.PPSWorkerPortEnv)) if err != nil { return Client{}, err } conn, err := grpc.Dial(fmt.Sprintf("%s:%d", address, port), append(client.DefaultDialOptions(), grpc.WithInsecure())...) if err != nil { return Client{}, err } return newClient(conn), nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L390-L392
func (p *SetWindowBoundsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetWindowBounds, p, nil) }
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L203-L232
func (f *packedFileReader) next() (*fileBlockHeader, error) { if f.h != nil { // skip to last block in current file for !f.h.last { // discard remaining block data if _, err := io.Copy(ioutil.Discard, f.r); err != nil { return nil, err } if err := f.nextBlockInFile(); err != nil { return nil, err } } // discard last block data if _, err := io.Copy(ioutil.Discard, f.r); err != nil { return nil, err } } var err error f.h, err = f.r.next() // get next file block if err != nil { if err == errArchiveEnd { return nil, io.EOF } return nil, err } if !f.h.first { return nil, errInvalidFileBlock } return f.h, nil }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/recorder.go#L79-L82
func (w *recorderResponseWriter) CloseNotify() <-chan bool { notifier := w.ResponseWriter.(http.CloseNotifier) return notifier.CloseNotify() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_profiles.go#L71-L79
func (r *ProtocolLXD) UpdateProfile(name string, profile api.ProfilePut, ETag string) error { // Send the request _, _, err := r.query("PUT", fmt.Sprintf("/profiles/%s", url.QueryEscape(name)), profile, ETag) if err != nil { return err } return nil }
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/examples/boilerplate/boilerplate.go#L86-L155
func RunBotOnWebhook(apiKey string, bot BotFunc, name, description, webhookHost string, webhookPort uint16, pubkey, privkey string) { closing := make(chan struct{}) fmt.Printf("%s: %s\n", name, description) fmt.Println("Starting...") u := url.URL{ Host: webhookHost + ":" + fmt.Sprint(webhookPort), Scheme: "https", Path: apiKey, } api, handler, err := tbotapi.NewWithWebhook(apiKey, u.String(), pubkey) if err != nil { log.Fatal(err) } // Just to show its working. fmt.Printf("User ID: %d\n", api.ID) fmt.Printf("Bot Name: %s\n", api.Name) fmt.Printf("Bot Username: %s\n", api.Username) closed := make(chan struct{}) wg := &sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() for { select { case <-closed: return case update := <-api.Updates: if update.Error() != nil { // TODO handle this properly fmt.Printf("Update error: %s\n", update.Error()) continue } bot(update.Update(), api) } } }() http.HandleFunc("/"+apiKey, handler) fmt.Println("Starting webhook...") go func() { log.Fatal(http.ListenAndServeTLS("0.0.0.0:"+fmt.Sprint(webhookPort), pubkey, privkey, nil)) }() // Ensure a clean shutdown. shutdown := make(chan os.Signal) signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM) go func() { <-shutdown close(closing) }() fmt.Println("Bot started. Press CTRL-C to close...") // Wait for the signal. <-closing fmt.Println("Closing...") // Always close the API first. api.Close() close(closed) wg.Wait() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util_linux.go#L295-L318
func Uname() (*Utsname, error) { /* * Based on: https://groups.google.com/forum/#!topic/golang-nuts/Jel8Bb-YwX8 * there is really no better way to do this, which is * unfortunate. Also, we ditch the more accepted CharsToString * version in that thread, since it doesn't seem as portable, * viz. github issue #206. */ uname := syscall.Utsname{} err := syscall.Uname(&uname) if err != nil { return nil, err } return &Utsname{ Sysname: intArrayToString(uname.Sysname), Nodename: intArrayToString(uname.Nodename), Release: intArrayToString(uname.Release), Version: intArrayToString(uname.Version), Machine: intArrayToString(uname.Machine), Domainname: intArrayToString(uname.Domainname), }, nil }
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/strip/prefix.go#L12-L23
func Prefix(prefix string) martini.Handler { return func(w http.ResponseWriter, r *http.Request) { if prefix == "" { return } if p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) { r.URL.Path = p } else { http.NotFound(w, r) } } }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L204-L213
func StripTags(s string, tags ...string) string { if len(tags) == 0 { tags = append(tags, "") } for _, tag := range tags { stripTagsRe := regexp.MustCompile(`(?i)<\/?` + tag + `[^<>]*>`) s = stripTagsRe.ReplaceAllString(s, "") } return s }
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/key.go#L118-L131
func GenerateKeyPairWithReader(typ, bits int, src io.Reader) (PrivKey, PubKey, error) { switch typ { case RSA: return GenerateRSAKeyPair(bits, src) case Ed25519: return GenerateEd25519Key(src) case Secp256k1: return GenerateSecp256k1Key(src) case ECDSA: return GenerateECDSAKeyPair(src) default: return nil, nil, ErrBadKeyType } }
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/ast.go#L1339-L1345
func (node *ShowFilter) Format(buf *TrackedBuffer) { if node.Like != "" { buf.Myprintf("like '%s'", node.Like) } else { buf.Myprintf("where %v", node.Filter) } }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcqueue/tcqueue.go#L899-L910
func (queue *Queue) ListWorkerTypes(provisionerId, continuationToken, limit string) (*ListWorkerTypesResponse, error) { v := url.Values{} if continuationToken != "" { v.Add("continuationToken", continuationToken) } if limit != "" { v.Add("limit", limit) } cd := tcclient.Client(*queue) responseObject, _, err := (&cd).APICall(nil, "GET", "/provisioners/"+url.QueryEscape(provisionerId)+"/worker-types", new(ListWorkerTypesResponse), v) return responseObject.(*ListWorkerTypesResponse), err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/easyjson.go#L502-L506
func (v GetUsageAndQuotaReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoStorage5(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/domstorage.go#L35-L37
func (p *ClearParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandClear, p, nil) }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L21-L24
func MetadataFromOutgoingContext(ctx context.Context) metadata.MD { md, _ := metadata.FromOutgoingContext(ctx) return md }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/api.go#L607-L631
func (r *Raft) Apply(cmd []byte, timeout time.Duration) ApplyFuture { metrics.IncrCounter([]string{"raft", "apply"}, 1) var timer <-chan time.Time if timeout > 0 { timer = time.After(timeout) } // Create a log future, no index or term yet logFuture := &logFuture{ log: Log{ Type: LogCommand, Data: cmd, }, } logFuture.init() select { case <-timer: return errorFuture{ErrEnqueueTimeout} case <-r.shutdownCh: return errorFuture{ErrRaftShutdown} case r.applyCh <- logFuture: return logFuture } }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L168-L188
func VerifyProtoRepresenting(expected proto.Message) http.HandlerFunc { return CombineHandlers( VerifyContentType("application/x-protobuf"), func(w http.ResponseWriter, req *http.Request) { body, err := ioutil.ReadAll(req.Body) Expect(err).ShouldNot(HaveOccurred()) req.Body.Close() expectedType := reflect.TypeOf(expected) actualValuePtr := reflect.New(expectedType.Elem()) actual, ok := actualValuePtr.Interface().(proto.Message) Expect(ok).Should(BeTrue(), "Message value is not a proto.Message") err = proto.Unmarshal(body, actual) Expect(err).ShouldNot(HaveOccurred(), "Failed to unmarshal protobuf") Expect(actual).Should(Equal(expected), "ProtoBuf Mismatch") }, ) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L920-L922
func (p *SetSkipAllPausesParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetSkipAllPauses, p, nil) }
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/lyra2.go#L55-L57
func rotr64(w uint64, c byte) uint64 { return (w >> c) | (w << (64 - c)) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_server.go#L13-L40
func (r *ProtocolLXD) GetServer() (*api.Server, string, error) { server := api.Server{} // Fetch the raw value etag, err := r.queryStruct("GET", "", nil, "", &server) if err != nil { return nil, "", err } // Fill in certificate fingerprint if not provided if server.Environment.CertificateFingerprint == "" && server.Environment.Certificate != "" { var err error server.Environment.CertificateFingerprint, err = shared.CertFingerprintStr(server.Environment.Certificate) if err != nil { return nil, "", err } } if !server.Public && len(server.AuthMethods) == 0 { // TLS is always available for LXD servers server.AuthMethods = []string{"tls"} } // Add the value to the cache r.server = &server return &server, etag, nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/set_options.go#L78-L82
func (m MasterWeight) MutateSetOptions(o *xdr.SetOptionsOp) (err error) { val := xdr.Uint32(m) o.MasterWeight = &val return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L31-L61
func (in *DecorationConfig) DeepCopyInto(out *DecorationConfig) { *out = *in out.Timeout = in.Timeout out.GracePeriod = in.GracePeriod if in.UtilityImages != nil { in, out := &in.UtilityImages, &out.UtilityImages *out = new(UtilityImages) **out = **in } if in.GCSConfiguration != nil { in, out := &in.GCSConfiguration, &out.GCSConfiguration *out = new(GCSConfiguration) **out = **in } if in.SSHKeySecrets != nil { in, out := &in.SSHKeySecrets, &out.SSHKeySecrets *out = make([]string, len(*in)) copy(*out, *in) } if in.SSHHostFingerprints != nil { in, out := &in.SSHHostFingerprints, &out.SSHHostFingerprints *out = make([]string, len(*in)) copy(*out, *in) } if in.SkipCloning != nil { in, out := &in.SkipCloning, &out.SkipCloning *out = new(bool) **out = **in } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L2279-L2283
func (v CloseTargetReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget26(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/logger.go#L69-L89
func (r *Record) Message() string { if r.message == nil { // Redact the arguments that implements the Redactor interface for i, arg := range r.Args { if redactor, ok := arg.(Redactor); ok == true { r.Args[i] = redactor.Redacted() } } var buf bytes.Buffer if r.fmt != nil { fmt.Fprintf(&buf, *r.fmt, r.Args...) } else { // use Fprintln to make sure we always get space between arguments fmt.Fprintln(&buf, r.Args...) buf.Truncate(buf.Len() - 1) // strip newline } msg := buf.String() r.message = &msg } return *r.message }
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L123-L135
func (s *Seekret) LoadRulesFromPath(path string, defaulEnabled bool) error { if path == "" { path = DefaultRulesPath() } dirList := strings.Split(path, ":") for _, dir := range dirList { err := s.LoadRulesFromDir(dir, defaulEnabled) if err != nil { return err } } return nil }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/policy.go#L94-L102
func DefaultTokenData(_ Client, ro ResourceOwner, _ GenericToken) map[string]interface{} { if ro != nil { return map[string]interface{}{ "user": ro.ID(), } } return nil }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/taskmanager/task.go#L69-L72
func (s *Task) Protect(taskmanager TaskManagerInterface, mutex sync.RWMutex) { s.taskManager = taskmanager s.mutex = mutex }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L213-L217
func (w *WriteBuffer) WriteBytes(in []byte) { if b := w.reserve(len(in)); b != nil { copy(b, in) } }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/txn.go#L635-L658
func (txn *Txn) CommitWith(cb func(error)) { txn.commitPrecheck() // Precheck before discarding txn. defer txn.Discard() if cb == nil { panic("Nil callback provided to CommitWith") } if len(txn.writes) == 0 { // Do not run these callbacks from here, because the CommitWith and the // callback might be acquiring the same locks. Instead run the callback // from another goroutine. go runTxnCallback(&txnCb{user: cb, err: nil}) return } commitCb, err := txn.commitAndSend() if err != nil { go runTxnCallback(&txnCb{user: cb, err: err}) return } go runTxnCallback(&txnCb{user: cb, commit: commitCb}) }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/file.go#L35-L51
func (l *FileTemplateFetcher) FetchTemplate(path string) (TemplateSource, error) { if filepath.IsAbs(path) { return nil, ErrAbsolutePathNotAllowed } for _, dir := range l.Paths { fullpath := filepath.Join(dir, path) _, err := os.Stat(fullpath) if err != nil { continue } return NewFileSource(fullpath), nil } return nil, ErrTemplateNotFound }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/check.go#L286-L411
func newCheckDatascaleCommand(cmd *cobra.Command, args []string) { var checkDatascaleAlias = map[string]string{ "s": "s", "small": "s", "m": "m", "medium": "m", "l": "l", "large": "l", "xl": "xl", "xLarge": "xl", } model, ok := checkDatascaleAlias[checkDatascaleLoad] if !ok { ExitWithError(ExitBadFeature, fmt.Errorf("unknown load option %v", checkDatascaleLoad)) } cfg := checkDatascaleCfgMap[model] requests := make(chan v3.Op, cfg.clients) cc := clientConfigFromCmd(cmd) clients := make([]*v3.Client, cfg.clients) for i := 0; i < cfg.clients; i++ { clients[i] = cc.mustClient() } // get endpoints eps, errEndpoints := endpointsFromCmd(cmd) if errEndpoints != nil { ExitWithError(ExitError, errEndpoints) } ctx, cancel := context.WithCancel(context.Background()) resp, err := clients[0].Get(ctx, checkDatascalePrefix, v3.WithPrefix(), v3.WithLimit(1)) cancel() if err != nil { ExitWithError(ExitError, err) } if len(resp.Kvs) > 0 { ExitWithError(ExitInvalidInput, fmt.Errorf("prefix %q has keys. Delete with etcdctl del --prefix %s first", checkDatascalePrefix, checkDatascalePrefix)) } ksize, vsize := 512, 512 k, v := make([]byte, ksize), string(make([]byte, vsize)) r := report.NewReport("%4.4f") var wg sync.WaitGroup wg.Add(len(clients)) // get the process_resident_memory_bytes and process_virtual_memory_bytes before the put operations bytesBefore := endpointMemoryMetrics(eps[0]) if bytesBefore == 0 { fmt.Println("FAIL: Could not read process_resident_memory_bytes before the put operations.") os.Exit(ExitError) } fmt.Println(fmt.Sprintf("Start data scale check for work load [%v key-value pairs, %v bytes per key-value, %v concurrent clients].", cfg.limit, cfg.kvSize, cfg.clients)) bar := pb.New(cfg.limit) bar.Format("Bom !") bar.Start() for i := range clients { go func(c *v3.Client) { defer wg.Done() for op := range requests { st := time.Now() _, derr := c.Do(context.Background(), op) r.Results() <- report.Result{Err: derr, Start: st, End: time.Now()} bar.Increment() } }(clients[i]) } go func() { for i := 0; i < cfg.limit; i++ { binary.PutVarint(k, rand.Int63n(math.MaxInt64)) requests <- v3.OpPut(checkDatascalePrefix+string(k), v) } close(requests) }() sc := r.Stats() wg.Wait() close(r.Results()) bar.Finish() s := <-sc // get the process_resident_memory_bytes after the put operations bytesAfter := endpointMemoryMetrics(eps[0]) if bytesAfter == 0 { fmt.Println("FAIL: Could not read process_resident_memory_bytes after the put operations.") os.Exit(ExitError) } // delete the created kv pairs ctx, cancel = context.WithCancel(context.Background()) dresp, derr := clients[0].Delete(ctx, checkDatascalePrefix, v3.WithPrefix()) defer cancel() if derr != nil { ExitWithError(ExitError, derr) } if autoCompact { compact(clients[0], dresp.Header.Revision) } if autoDefrag { for _, ep := range clients[0].Endpoints() { defrag(clients[0], ep) } } if bytesAfter == 0 { fmt.Println("FAIL: Could not read process_resident_memory_bytes after the put operations.") os.Exit(ExitError) } bytesUsed := bytesAfter - bytesBefore mbUsed := bytesUsed / (1024 * 1024) if len(s.ErrorDist) != 0 { fmt.Println("FAIL: too many errors") for k, v := range s.ErrorDist { fmt.Printf("FAIL: ERROR(%v) -> %d\n", k, v) } os.Exit(ExitError) } else { fmt.Println(fmt.Sprintf("PASS: Approximate system memory used : %v MB.", strconv.FormatFloat(mbUsed, 'f', 2, 64))) } }
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/string.go#L87-L90
func (s *String) SetValid(v string) { s.String = v s.Valid = true }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/connection.go#L237-L244
func getTimeout(ctx context.Context) time.Duration { deadline, ok := ctx.Deadline() if !ok { return DefaultConnectTimeout } return deadline.Sub(time.Now()) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/stream.go#L276-L325
func (st *Stream) Orchestrate(ctx context.Context) error { st.rangeCh = make(chan keyRange, 3) // Contains keys for posting lists. // kvChan should only have a small capacity to ensure that we don't buffer up too much data if // sending is slow. Page size is set to 4MB, which is used to lazily cap the size of each // KVList. To get around 64MB buffer, we can set the channel size to 16. st.kvChan = make(chan *pb.KVList, 16) if st.KeyToList == nil { st.KeyToList = st.ToList } // Picks up ranges from Badger, and sends them to rangeCh. go st.produceRanges(ctx) errCh := make(chan error, 1) // Stores error by consumeKeys. var wg sync.WaitGroup for i := 0; i < st.NumGo; i++ { wg.Add(1) go func() { defer wg.Done() // Picks up ranges from rangeCh, generates KV lists, and sends them to kvChan. if err := st.produceKVs(ctx); err != nil { select { case errCh <- err: default: } } }() } // Pick up key-values from kvChan and send to stream. kvErr := make(chan error, 1) go func() { // Picks up KV lists from kvChan, and sends them to Output. kvErr <- st.streamKVs(ctx) }() wg.Wait() // Wait for produceKVs to be over. close(st.kvChan) // Now we can close kvChan. select { case err := <-errCh: // Check error from produceKVs. return err default: } // Wait for key streaming to be over. err := <-kvErr return err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L289-L305
func (f *FakeClient) AddLabel(owner, repo string, number int, label string) error { labelString := fmt.Sprintf("%s/%s#%d:%s", owner, repo, number, label) if sets.NewString(f.IssueLabelsAdded...).Has(labelString) { return fmt.Errorf("cannot add %v to %s/%s/#%d", label, owner, repo, number) } if f.RepoLabelsExisting == nil { f.IssueLabelsAdded = append(f.IssueLabelsAdded, labelString) return nil } for _, l := range f.RepoLabelsExisting { if label == l { f.IssueLabelsAdded = append(f.IssueLabelsAdded, labelString) return nil } } return fmt.Errorf("cannot add %v to %s/%s/#%d", label, owner, repo, number) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/backgroundservice.go#L104-L106
func (p *ClearEventsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandClearEvents, p, nil) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4801-L4811
func (u LedgerUpgrade) ArmForSwitch(sw int32) (string, bool) { switch LedgerUpgradeType(sw) { case LedgerUpgradeTypeLedgerUpgradeVersion: return "NewLedgerVersion", true case LedgerUpgradeTypeLedgerUpgradeBaseFee: return "NewBaseFee", true case LedgerUpgradeTypeLedgerUpgradeMaxTxSetSize: return "NewMaxTxSetSize", true } return "-", false }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L979-L983
func (v GetDOMCountersReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoMemory10(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L163-L169
func FrameSet_Start(id FrameSetId) C.int { fs, ok := sFrameSets.Get(id) if !ok { return C.int(0) } return C.int(fs.Start()) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/http.go#L270-L291
func (a *API) LoadResponse(resp *http.Response) (interface{}, error) { defer resp.Body.Close() var respBody interface{} jsonResp, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("Failed to read response (%s)", err) } if len(jsonResp) > 0 { err = json.Unmarshal(jsonResp, &respBody) if err != nil { return nil, fmt.Errorf("Failed to load response (%s)", err) } } // Special case for "Location" header, assume that if there is a location there is no body loc := resp.Header.Get("Location") if len(loc) > 0 { var bodyMap = make(map[string]interface{}) bodyMap["Location"] = loc respBody = interface{}(bodyMap) } return respBody, err }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/tlsutil/tlsutil.go#L53-L73
func NewCert(certfile, keyfile string, parseFunc func([]byte, []byte) (tls.Certificate, error)) (*tls.Certificate, error) { cert, err := ioutil.ReadFile(certfile) if err != nil { return nil, err } key, err := ioutil.ReadFile(keyfile) if err != nil { return nil, err } if parseFunc == nil { parseFunc = tls.X509KeyPair } tlsCert, err := parseFunc(cert, key) if err != nil { return nil, err } return &tlsCert, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L341-L375
func ensureUpdatesAreApplied(tx *sql.Tx, current int, updates []Update, hook Hook) error { if current > len(updates) { return fmt.Errorf( "schema version '%d' is more recent than expected '%d'", current, len(updates)) } // If there are no updates, there's nothing to do. if len(updates) == 0 { return nil } // Apply missing updates. for _, update := range updates[current:] { if hook != nil { err := hook(current, tx) if err != nil { return fmt.Errorf( "failed to execute hook (version %d): %v", current, err) } } err := update(tx) if err != nil { return fmt.Errorf("failed to apply update %d: %v", current, err) } current++ err = insertSchemaVersion(tx, current) if err != nil { return fmt.Errorf("failed to insert version %d", current) } } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/network.go#L194-L201
func (l *networkListener) Config(cert *shared.CertInfo) { config := util.ServerTLSConfig(cert) l.mu.Lock() defer l.mu.Unlock() l.config = config }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L1089-L1093
func (v *EventWorkerRegistrationUpdated) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoServiceworker11(&r, v) return r.Error() }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vix.go#L329-L375
func Connect(config ConnectConfig) (*Host, error) { var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE var hostHandle C.VixHandle = C.VIX_INVALID_HANDLE var err C.VixError = C.VIX_OK chostname := C.CString(config.Hostname) cusername := C.CString(config.Username) cpassword := C.CString(config.Password) defer C.free(unsafe.Pointer(chostname)) defer C.free(unsafe.Pointer(cusername)) defer C.free(unsafe.Pointer(cpassword)) jobHandle = C.VixHost_Connect(C.VIX_API_VERSION, C.VixServiceProvider(config.Provider), chostname, C.int(config.Port), cusername, cpassword, C.VixHostOptions(config.Options), C.VIX_INVALID_HANDLE, // propertyListHandle nil, // callbackProc nil) // clientData err = C.get_vix_handle(jobHandle, C.VIX_PROPERTY_JOB_RESULT_HANDLE, &hostHandle, C.VIX_PROPERTY_NONE) defer C.Vix_ReleaseHandle(jobHandle) if C.VIX_OK != err { return nil, &Error{ Operation: "vix.Connect", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } host := &Host{ handle: hostHandle, Provider: config.Provider, } //runtime.SetFinalizer(host, cleanupHost) return host, nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/relay_messages.go#L144-L147
func (f lazyCallReq) Service() []byte { l := f.Payload[_serviceLenIndex] return f.Payload[_serviceNameIndex : _serviceNameIndex+l] }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_networks.go#L70-L84
func (r *ProtocolLXD) GetNetworkLeases(name string) ([]api.NetworkLease, error) { if !r.HasExtension("network_leases") { return nil, fmt.Errorf("The server is missing the required \"network_leases\" API extension") } leases := []api.NetworkLease{} // Fetch the raw value _, err := r.queryStruct("GET", fmt.Sprintf("/networks/%s/leases", url.QueryEscape(name)), nil, "", &leases) if err != nil { return nil, err } return leases, nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/json/call.go#L139-L152
func wrapCall(ctx Context, call *tchannel.OutboundCall, method string, arg, resp interface{}) error { var respHeaders map[string]string var respErr ErrApplication isOK, errAt, err := makeCall(call, ctx.Headers(), arg, &respHeaders, resp, &respErr) if err != nil { return fmt.Errorf("%s: %v", errAt, err) } if !isOK { return respErr } ctx.SetResponseHeaders(respHeaders) return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logging/log_windows.go#L10-L12
func getSystemHandler(syslog string, debug bool, format log.Format) log.Handler { return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/listers/prowjobs/v1/prowjob.go#L56-L58
func (s *prowJobLister) ProwJobs(namespace string) ProwJobNamespaceLister { return prowJobNamespaceLister{indexer: s.indexer, namespace: namespace} }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/worker/api_server.go#L1622-L1671
func (a *APIServer) cancelCtxIfJobFails(jobCtx context.Context, jobCancel func(), jobID string) { logger := a.getWorkerLogger() // this worker's formatting logger backoff.RetryNotify(func() error { // Check if job was cancelled while backoff was sleeping if isDone(jobCtx) { return nil } // Start watching for job state changes watcher, err := a.jobs.ReadOnly(jobCtx).WatchOne(jobID) if err != nil { if col.IsErrNotFound(err) { jobCancel() // job deleted before we started--cancel the job ctx return nil } return fmt.Errorf("worker: could not create state watcher for job %s, err is %v", jobID, err) } // If any job events indicate that the job is done, cancel jobCtx for { select { case e := <-watcher.Watch(): switch e.Type { case watch.EventPut: var jobID string jobPtr := &pps.EtcdJobInfo{} if err := e.Unmarshal(&jobID, jobPtr); err != nil { return fmt.Errorf("worker: error unmarshalling while watching job state (%v)", err) } if ppsutil.IsTerminal(jobPtr.State) { jobCancel() // cancel the job } case watch.EventDelete: jobCancel() // cancel the job case watch.EventError: return fmt.Errorf("job state watch error: %v", e.Err) } case <-jobCtx.Done(): break } } }, backoff.NewInfiniteBackOff(), func(err error, d time.Duration) error { if jobCtx.Err() == context.Canceled { return err // worker is done, nothing else to do } logger.Logf("worker: error watching job %s (%v); retrying in %v", jobID, err, d) return nil }) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L7127-L7136
func (u ScpStatementPledges) GetConfirm() (result ScpStatementConfirm, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "Confirm" { result = *u.Confirm ok = true } return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/statusreconciler/controller.go#L388-L417
func migratedBlockingPresubmits(old, new map[string][]config.Presubmit) map[string][]presubmitMigration { migrated := map[string][]presubmitMigration{} for repo, oldPresubmits := range old { migrated[repo] = []presubmitMigration{} for _, newPresubmit := range new[repo] { if !newPresubmit.ContextRequired() { continue } for _, oldPresubmit := range oldPresubmits { if oldPresubmit.Context != newPresubmit.Context && oldPresubmit.Name == newPresubmit.Name { migrated[repo] = append(migrated[repo], presubmitMigration{from: oldPresubmit, to: newPresubmit}) logrus.WithFields(logrus.Fields{ "repo": repo, "name": oldPresubmit.Name, "from": oldPresubmit.Context, "to": newPresubmit.Context, }).Debug("Identified a migrated blocking presubmit.") } } } } var numMigrated int for _, presubmits := range migrated { numMigrated += len(presubmits) } logrus.Infof("Identified %d migrated blocking presubmits.", numMigrated) return migrated }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_src.go#L103-L122
func (s *ociImageSource) GetBlob(ctx context.Context, info types.BlobInfo, cache types.BlobInfoCache) (io.ReadCloser, int64, error) { if len(info.URLs) != 0 { return s.getExternalBlob(ctx, info.URLs) } path, err := s.ref.blobPath(info.Digest, s.sharedBlobDir) if err != nil { return nil, 0, err } r, err := os.Open(path) if err != nil { return nil, 0, err } fi, err := r.Stat() if err != nil { return nil, 0, err } return r, fi.Size(), nil }
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/collection.go#L294-L299
func (c *Collection) DeleteOne(query bson.M) error { sess := c.Connection.Session.Clone() defer sess.Close() col := c.collectionOnSession(sess) return col.Remove(query) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/images.go#L639-L658
func imageCreateInPool(d *Daemon, info *api.Image, storagePool string) error { if storagePool == "" { return fmt.Errorf("No storage pool specified") } // Initialize a new storage interface. s, err := storagePoolInit(d.State(), storagePool) if err != nil { return err } // Create the storage volume for the image on the requested storage // pool. err = s.ImageCreate(info.Fingerprint, nil) if err != nil { return err } return nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/channel.go#L201-L304
func NewChannel(serviceName string, opts *ChannelOptions) (*Channel, error) { if serviceName == "" { return nil, ErrNoServiceName } if opts == nil { opts = &ChannelOptions{} } processName := opts.ProcessName if processName == "" { processName = fmt.Sprintf("%s[%d]", filepath.Base(os.Args[0]), os.Getpid()) } logger := opts.Logger if logger == nil { logger = NullLogger } statsReporter := opts.StatsReporter if statsReporter == nil { statsReporter = NullStatsReporter } timeNow := opts.TimeNow if timeNow == nil { timeNow = time.Now } timeTicker := opts.TimeTicker if timeTicker == nil { timeTicker = time.NewTicker } chID := _nextChID.Inc() logger = logger.WithFields( LogField{"serviceName", serviceName}, LogField{"process", processName}, LogField{"chID", chID}, ) if err := opts.validateIdleCheck(); err != nil { return nil, err } ch := &Channel{ channelConnectionCommon: channelConnectionCommon{ log: logger, relayLocal: toStringSet(opts.RelayLocalHandlers), statsReporter: statsReporter, subChannels: &subChannelMap{}, timeNow: timeNow, timeTicker: timeTicker, tracer: opts.Tracer, }, chID: chID, connectionOptions: opts.DefaultConnectionOptions.withDefaults(), relayHost: opts.RelayHost, relayMaxTimeout: validateRelayMaxTimeout(opts.RelayMaxTimeout, logger), relayTimerVerify: opts.RelayTimerVerification, closed: make(chan struct{}), } ch.peers = newRootPeerList(ch, opts.OnPeerStatusChanged).newChild() if opts.Handler != nil { ch.handler = opts.Handler } else { ch.handler = channelHandler{ch} } ch.mutable.peerInfo = LocalPeerInfo{ PeerInfo: PeerInfo{ ProcessName: processName, HostPort: ephemeralHostPort, IsEphemeral: true, Version: PeerVersion{ Language: "go", LanguageVersion: strings.TrimPrefix(runtime.Version(), "go"), TChannelVersion: VersionInfo, }, }, ServiceName: serviceName, } ch.mutable.state = ChannelClient ch.mutable.conns = make(map[uint32]*Connection) ch.createCommonStats() // Register internal unless the root handler has been overridden, since // Register will panic. if opts.Handler == nil { ch.registerInternal() } registerNewChannel(ch) if opts.RelayHost != nil { opts.RelayHost.SetChannel(ch) } // Start the idle connection timer. ch.mutable.idleSweep = startIdleSweep(ch, opts) return ch, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/container.go#L120-L140
func GetRootDiskDevice(devices map[string]map[string]string) (string, map[string]string, error) { var devName string var dev map[string]string for n, d := range devices { if IsRootDiskDevice(d) { if devName != "" { return "", nil, fmt.Errorf("More than one root device found") } devName = n dev = d } } if devName != "" { return devName, dev, nil } return "", nil, fmt.Errorf("No root device could be found") }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L528-L537
func (p *GetResourceTreeParams) Do(ctx context.Context) (frameTree *FrameResourceTree, err error) { // execute var res GetResourceTreeReturns err = cdp.Execute(ctx, CommandGetResourceTree, nil, &res) if err != nil { return nil, err } return res.FrameTree, nil }