_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcindex/tcindex.go#L211-L214
func (index *Index) FindArtifactFromTask_SignedURL(indexPath, name string, duration time.Duration) (*url.URL, error) { cd := tcclient.Client(*index) return (&cd).SignedURL("/task/"+url.QueryEscape(indexPath)+"/artifacts/"+url.QueryEscape(name), nil, duration) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L5193-L5197
func (v *EventPseudoElementRemoved) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom58(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/tracing.go#L50-L55
func (o *tracingObjClient) Walk(ctx context.Context, prefix string, fn func(name string) error) error { span, ctx := tracing.AddSpanToAnyExisting(ctx, o.provider+".Walk", "prefix", prefix) defer tracing.FinishAnySpan(span) return o.Client.Walk(ctx, prefix, fn) }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L1031-L1036
func FailFunc(f func() string) error { if isModeEnable(FAIL) { return glg.out(FAIL, "%s", f()) } return nil }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/json-decode.go#L230-L286
func (cdc *Codec) decodeReflectJSONArray(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) { if !rv.CanAddr() { panic("rv not addressable") } if printLog { fmt.Println("(d) decodeReflectJSONArray") defer func() { fmt.Printf("(d) -> err: %v\n", err) }() } ert := info.Type.Elem() length := info.Type.Len() switch ert.Kind() { case reflect.Uint8: // Special case: byte array var buf []byte err = json.Unmarshal(bz, &buf) if err != nil { return } if len(buf) != length { err = fmt.Errorf("decodeReflectJSONArray: byte-length mismatch, got %v want %v", len(buf), length) } reflect.Copy(rv, reflect.ValueOf(buf)) return default: // General case. var einfo *TypeInfo einfo, err = cdc.getTypeInfo_wlock(ert) if err != nil { return } // Read into rawSlice. var rawSlice []json.RawMessage if err = json.Unmarshal(bz, &rawSlice); err != nil { return } if len(rawSlice) != length { err = fmt.Errorf("decodeReflectJSONArray: length mismatch, got %v want %v", len(rawSlice), length) return } // Decode each item in rawSlice. for i := 0; i < length; i++ { erv := rv.Index(i) ebz := rawSlice[i] err = cdc.decodeReflectJSON(ebz, einfo, erv, fopts) if err != nil { return } } return } }
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/bit_reader.go#L18-L20
func limitBitReader(br bitReader, n int, err error) bitReader { return &limitedBitReader{br, n, err} }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/obj.go#L229-L246
func NewMicrosoftClientFromSecret(container string) (Client, error) { var err error if container == "" { container, err = readSecretFile("/microsoft-container") if err != nil { return nil, fmt.Errorf("microsoft-container not found") } } id, err := readSecretFile("/microsoft-id") if err != nil { return nil, fmt.Errorf("microsoft-id not found") } secret, err := readSecretFile("/microsoft-secret") if err != nil { return nil, fmt.Errorf("microsoft-secret not found") } return NewMicrosoftClient(container, id, secret) }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/format/format.go#L87-L101
func MessageWithDiff(actual, message, expected string) string { if TruncatedDiff && len(actual) >= truncateThreshold && len(expected) >= truncateThreshold { diffPoint := findFirstMismatch(actual, expected) formattedActual := truncateAndFormat(actual, diffPoint) formattedExpected := truncateAndFormat(expected, diffPoint) spacesBeforeFormattedMismatch := findFirstMismatch(formattedActual, formattedExpected) tabLength := 4 spaceFromMessageToActual := tabLength + len("<string>: ") - len(message) padding := strings.Repeat(" ", spaceFromMessageToActual+spacesBeforeFormattedMismatch) + "|" return Message(formattedActual, message+padding, formattedExpected) } return Message(actual, message, expected) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2274-L2282
func (u Memo) MustId() Uint64 { val, ok := u.GetId() if !ok { panic("arm Id is not set") } return val }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L690-L731
func (t *Iterator) Cursor() (Cursor, error) { if t.err != nil && t.err != Done { return Cursor{}, t.err } // If we are at either end of the current batch of results, // return the compiled cursor at that end. skipped := t.res.GetSkippedResults() if t.i == 0 && skipped == 0 { if t.prevCC == nil { // A nil pointer (of type *pb.CompiledCursor) means no constraint: // passing it as the end cursor of a new query means unlimited results // (glossing over the integer limit parameter for now). // A non-nil pointer to an empty pb.CompiledCursor means the start: // passing it as the end cursor of a new query means 0 results. // If prevCC was nil, then the original query had no start cursor, but // Iterator.Cursor should return "the start" instead of unlimited. return Cursor{&zeroCC}, nil } return Cursor{t.prevCC}, nil } if t.i == len(t.res.Result) { return Cursor{t.res.CompiledCursor}, nil } // Otherwise, re-run the query offset to this iterator's position, starting from // the most recent compiled cursor. This is done on a best-effort basis, as it // is racy; if a concurrent process has added or removed entities, then the // cursor returned may be inconsistent. q := t.q.clone() q.start = t.prevCC q.offset = skipped + int32(t.i) q.limit = 0 q.keysOnly = len(q.projection) == 0 t1 := q.Run(t.c) _, _, err := t1.next() if err != Done { if err == nil { err = fmt.Errorf("datastore: internal error: zero-limit query did not have zero results") } return Cursor{}, err } return Cursor{t1.res.CompiledCursor}, nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/state.go#L156-L160
func (r *raftState) getLastIndex() uint64 { r.lastLock.Lock() defer r.lastLock.Unlock() return max(r.lastLogIndex, r.lastSnapshotIndex) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L569-L578
func (p *TakeResponseBodyForInterceptionAsStreamParams) Do(ctx context.Context) (stream io.StreamHandle, err error) { // execute var res TakeResponseBodyForInterceptionAsStreamReturns err = cdp.Execute(ctx, CommandTakeResponseBodyForInterceptionAsStream, p, &res) if err != nil { return "", err } return res.Stream, nil }
https://github.com/gernest/mention/blob/d48aa4355f942e79e1a4ac2bd08c5c46371b78ca/mention.go#L27-L61
func GetTags(prefix rune, str string, terminator ...rune) (tags []Tag) { // If we have no terminators given, default to only whitespace if len(terminator) == 0 { terminator = []rune(" ") } // get list of indexes in our str that is a terminator // Always include the beginning of our str a terminator. This is so we can // detect the first character as a prefix termIndexes := []int{-1} for i, char := range str { if isTerminator(char, terminator...) { termIndexes = append(termIndexes, i) } } // Always include last character as a terminator termIndexes = append(termIndexes, len(str)) // check if the character AFTER our term index is our prefix for i, t := range termIndexes { // ensure term index is not the last character in str if t >= (len(str) - 1) { break } if str[t+1] == byte(prefix) { tagText := strings.TrimLeft(str[t+2:termIndexes[i+1]], string(prefix)) if tagText == "" { continue } index := t + 1 tags = append(tags, Tag{prefix, tagText, index}) } } return }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/address.go#L21-L26
func (a Address) Max(b Address) Address { if a > b { return a } return b }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/tide.go#L701-L750
func accumulate(presubmits map[int][]config.Presubmit, prs []PullRequest, pjs []prowapi.ProwJob, log *logrus.Entry) (successes, pendings, nones []PullRequest) { for _, pr := range prs { // Accumulate the best result for each job. psStates := make(map[string]simpleState) for _, pj := range pjs { if pj.Spec.Type != prowapi.PresubmitJob { continue } if pj.Spec.Refs.Pulls[0].Number != int(pr.Number) { continue } if pj.Spec.Refs.Pulls[0].SHA != string(pr.HeadRefOID) { continue } name := pj.Spec.Context oldState := psStates[name] newState := toSimpleState(pj.Status.State) if oldState == failureState || oldState == "" { psStates[name] = newState } else if oldState == pendingState && newState == successState { psStates[name] = successState } } // The overall result is the worst of the best. overallState := successState for _, ps := range presubmits[int(pr.Number)] { if s, ok := psStates[ps.Context]; !ok { overallState = failureState log.WithFields(pr.logFields()).Debugf("missing presubmit %s", ps.Context) break } else if s == failureState { overallState = failureState log.WithFields(pr.logFields()).Debugf("presubmit %s not passing", ps.Context) break } else if s == pendingState { log.WithFields(pr.logFields()).Debugf("presubmit %s pending", ps.Context) overallState = pendingState } } if overallState == successState { successes = append(successes, pr) } else if overallState == pendingState { pendings = append(pendings, pr) } else { nones = append(nones, pr) } } return }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L137-L141
func (s *MockSpan) Context() opentracing.SpanContext { s.Lock() defer s.Unlock() return s.SpanContext }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L4875-L4879
func (v ContinueToLocationParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger47(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L2063-L2104
func Swap(app1, app2 *App, cnameOnly bool) error { a1Routers := app1.GetRouters() a2Routers := app2.GetRouters() if len(a1Routers) != 1 || len(a2Routers) != 1 { return errors.New("swapping apps with multiple routers is not supported") } r1, err := router.Get(a1Routers[0].Name) if err != nil { return err } r2, err := router.Get(a2Routers[0].Name) if err != nil { return err } defer func(app1, app2 *App) { rebuild.RoutesRebuildOrEnqueue(app1.Name) rebuild.RoutesRebuildOrEnqueue(app2.Name) app1.GetRoutersWithAddr() app2.GetRoutersWithAddr() }(app1, app2) err = r1.Swap(app1.Name, app2.Name, cnameOnly) if err != nil { return err } conn, err := db.Conn() if err != nil { return err } defer conn.Close() app1.CName, app2.CName = app2.CName, app1.CName updateCName := func(app *App, r router.Router) error { return conn.Apps().Update( bson.M{"name": app.Name}, bson.M{"$set": bson.M{"cname": app.CName}}, ) } err = updateCName(app1, r1) if err != nil { return err } return updateCName(app2, r2) }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/servers.go#L251-L267
func (s *Servers) Shutdown(ctx context.Context) { wg := &sync.WaitGroup{} for _, srv := range s.servers { wg.Add(1) go func(srv *server) { defer s.recover() defer wg.Done() s.logger.Infof("%s shutting down", srv.label()) if err := srv.Shutdown(ctx); err != nil { s.logger.Errorf("%s shutdown: %v", srv.label(), err) } }(srv) } wg.Wait() return }
https://github.com/fossapps/captain/blob/0f30dc3a624d523638831aa2bcb08bc962234a95/captain.go#L44-L52
func CreateJob() Config { return Config{ LockProvider: nil, RuntimeProcessor: nil, ResultProcessor: nil, RuntimeProcessingFrequency: 200 * time.Millisecond, SummaryBuffer: 1, } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L283-L285
func (p *ActionParam) IsEquivalent(other *ActionParam) bool { return p.Name == other.Name && p.Type.IsEquivalent(other.Type) }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L75-L80
func (p *Page) Destroy() error { if err := p.session.Delete(); err != nil { return fmt.Errorf("failed to destroy session: %s", err) } return nil }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L59-L75
func NewInclusiveRange(start, end, step int) *InclusiveRange { if step == 0 { if start <= end { step = 1 } else { step = -1 } } r := &InclusiveRange{ start: start, end: end, step: step, } return r }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/xslate.go#L254-L267
func New(args ...Args) (*Xslate, error) { tx := &Xslate{} // We jump through hoops because there are A LOT of configuration options // but most of them only need to use the default values if len(args) <= 0 { args = []Args{Args{}} } err := tx.Configure(args[0]) if err != nil { return nil, err } return tx, nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/ledger_entry_change.go#L12-L28
func (change *LedgerEntryChange) LedgerKey() LedgerKey { switch change.Type { case LedgerEntryChangeTypeLedgerEntryCreated: change := change.MustCreated() return change.LedgerKey() case LedgerEntryChangeTypeLedgerEntryRemoved: return change.MustRemoved() case LedgerEntryChangeTypeLedgerEntryUpdated: change := change.MustUpdated() return change.LedgerKey() case LedgerEntryChangeTypeLedgerEntryState: change := change.MustState() return change.LedgerKey() default: panic(fmt.Errorf("Unknown change type: %v", change.Type)) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L453-L458
func SynthesizeScrollGesture(x float64, y float64) *SynthesizeScrollGestureParams { return &SynthesizeScrollGestureParams{ X: x, Y: y, } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/node.go#L57-L67
func newKV(store *store, nodePath string, value string, createdIndex uint64, parent *node, expireTime time.Time) *node { return &node{ Path: nodePath, CreatedIndex: createdIndex, ModifiedIndex: createdIndex, Parent: parent, store: store, ExpireTime: expireTime, Value: value, } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/introspection.go#L336-L347
func (p *Peer) IntrospectState(opts *IntrospectionOptions) PeerRuntimeState { p.RLock() defer p.RUnlock() return PeerRuntimeState{ HostPort: p.hostPort, InboundConnections: getConnectionRuntimeState(p.inboundConnections, opts), OutboundConnections: getConnectionRuntimeState(p.outboundConnections, opts), ChosenCount: p.chosenCount.Load(), SCCount: p.scCount, } }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/remote.go#L139-L175
func NewRemoteCache(knownRepos []Repo) (r *RemoteCache, cleanup func() error) { r = &RemoteCache{ RepoRootForImportPath: vcs.RepoRootForImportPath, HeadCmd: defaultHeadCmd, root: remoteCacheMap{cache: make(map[string]*remoteCacheEntry)}, remote: remoteCacheMap{cache: make(map[string]*remoteCacheEntry)}, head: remoteCacheMap{cache: make(map[string]*remoteCacheEntry)}, mod: remoteCacheMap{cache: make(map[string]*remoteCacheEntry)}, } r.ModInfo = func(importPath string) (string, error) { return defaultModInfo(r, importPath) } for _, repo := range knownRepos { r.root.cache[repo.GoPrefix] = &remoteCacheEntry{ value: rootValue{ root: repo.GoPrefix, name: repo.Name, }, } if repo.Remote != "" { r.remote.cache[repo.GoPrefix] = &remoteCacheEntry{ value: remoteValue{ remote: repo.Remote, vcs: repo.VCS, }, } } r.mod.cache[repo.GoPrefix] = &remoteCacheEntry{ value: modValue{ path: repo.GoPrefix, name: repo.Name, known: true, }, } } return r, r.cleanup }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/server_access_control.go#L37-L49
func (ac *AccessController) OriginAllowed(origin string) bool { ac.corsMu.RLock() defer ac.corsMu.RUnlock() if len(ac.CORS) == 0 { // allow all return true } _, ok := ac.CORS["*"] if ok { return true } _, ok = ac.CORS[origin] return ok }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/log/log.go#L68-L72
func (t *Target) SetLogger(l Logger) { t.mut.Lock() defer t.mut.Unlock() t.logger = l }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/read.go#L124-L129
func (p *Process) ReadInt(a Address) int64 { if p.ptrSize == 4 { return int64(p.ReadInt32(a)) } return p.ReadInt64(a) }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/user/user.go#L50-L52
func LoginURL(c context.Context, dest string) (string, error) { return LoginURLFederated(c, dest, "") }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/git/localgit/localgit.go#L121-L136
func (lg *LocalGit) AddCommit(org, repo string, files map[string][]byte) error { rdir := filepath.Join(lg.Dir, org, repo) for f, b := range files { path := filepath.Join(rdir, f) if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil { return err } if err := ioutil.WriteFile(path, b, os.ModePerm); err != nil { return err } if err := runCmd(lg.Git, rdir, "add", f); err != nil { return err } } return runCmd(lg.Git, rdir, "commit", "-m", "wow") }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/docker/scheduler.go#L330-L373
func (s *segregatedScheduler) minMaxNodes(nodes []cluster.Node, appName, process string) (string, string, error) { nodesList := make(node.NodeList, len(nodes)) for i := range nodes { nodesList[i] = &clusterNodeWrapper{Node: &nodes[i], prov: s.provisioner} } metaFreqList, _, err := nodesList.SplitMetadata() if err != nil { log.Debugf("[scheduler] ignoring metadata diff when selecting node: %s", err) } hostGroupMap := map[string]int{} for i, m := range metaFreqList { for _, n := range m.Nodes { hostGroupMap[net.URLToHost(n.Address())] = i } } hosts, hostsMap := s.nodesToHosts(nodes) hostCountMap, err := s.aggregateContainersByHost(hosts) if err != nil { return "", "", err } appCountMap, err := s.aggregateContainersByHostAppProcess(hosts, appName, process) if err != nil { return "", "", err } priorityEntries := []map[string]int{appGroupCount(hostGroupMap, appCountMap), appCountMap, hostCountMap} var minHost, maxHost string var minScore uint64 = math.MaxUint64 var maxScore uint64 = 0 for _, host := range hosts { var score uint64 for i, e := range priorityEntries { score += uint64(e[host]) << uint((len(priorityEntries)-i-1)*(64/len(priorityEntries))) } if score < minScore { minScore = score minHost = host } if score >= maxScore { maxScore = score maxHost = host } } return hostsMap[minHost], hostsMap[maxHost], nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/event_counter.go#L33-L35
func (e *EventCounterPlugin) AddFlags(cmd *cobra.Command) { cmd.Flags().StringVar(&e.desc, "event", "", "Match event (eg: `opened`)") }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/nodecontainer.go#L212-L268
func nodeContainerDelete(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { name := r.URL.Query().Get(":name") poolName := r.URL.Query().Get("pool") kill, _ := strconv.ParseBool(r.URL.Query().Get("kill")) var ctxs []permTypes.PermissionContext if poolName != "" { ctxs = append(ctxs, permission.Context(permTypes.CtxPool, poolName)) } if !permission.Check(t, permission.PermNodecontainerDelete, ctxs...) { return permission.ErrUnauthorized } evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypeNodeContainer, Value: name}, Kind: permission.PermNodecontainerDelete, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermPoolReadEvents, ctxs...), }) if err != nil { return err } defer func() { evt.Done(err) }() err = nodecontainer.RemoveContainer(poolName, name) if err == nodecontainer.ErrNodeContainerNotFound { return &tsuruErrors.HTTP{ Code: http.StatusNotFound, Message: fmt.Sprintf("node container %q not found for pool %q", name, poolName), } } if err != nil || !kill { return err } provs, err := provision.Registry() if err != nil { return err } w.Header().Set("Content-Type", "application/x-json-stream") keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 15*time.Second, "") defer keepAliveWriter.Stop() writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)} evt.SetLogWriter(writer) var allErrors []string for _, prov := range provs { ncProv, ok := prov.(provision.NodeContainerProvisioner) if !ok { continue } err = ncProv.RemoveNodeContainer(name, poolName, evt) if err != nil { allErrors = append(allErrors, err.Error()) } } if len(allErrors) > 0 { return errors.Errorf("multiple errors removing node container: %s", strings.Join(allErrors, "; ")) } return nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/skl/skl.go#L257-L276
func (s *Skiplist) findSpliceForLevel(key []byte, before *node, level int) (*node, *node) { for { // Assume before.key < key. next := s.getNext(before, level) if next == nil { return before, next } nextKey := next.key(s.arena) cmp := y.CompareKeys(key, nextKey) if cmp == 0 { // Equality case. return next, next } if cmp < 0 { // before.key < key < next.key. We are done for this level. return before, next } before = next // Keep moving right on this level. } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/agent/server.go#L122-L126
func (srv *Server) Stop() { srv.lg.Info("gRPC server stopping", zap.String("address", srv.address)) srv.grpcServer.Stop() srv.lg.Info("gRPC server stopped", zap.String("address", srv.address)) }
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/rsa.go#L117-L126
func UnmarshalRsaPrivateKey(b []byte) (PrivKey, error) { sk, err := x509.ParsePKCS1PrivateKey(b) if err != nil { return nil, err } if sk.N.BitLen() < 512 { return nil, ErrRsaKeyTooSmall } return &RsaPrivateKey{sk: sk}, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/adt/interval_tree.go#L355-L365
func (ivt *IntervalTree) rotateLeft(x *intervalNode) { y := x.right x.right = y.left if y.left != nil { y.left.parent = x } x.updateMax() ivt.replaceParent(x, y) y.left = x y.updateMax() }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/ttnctx/context.go#L93-L107
func ServiceInfoFromMetadata(md metadata.MD) (serviceName, serviceVersion, netAddress string, err error) { serviceNameL, ok := md["service-name"] if ok && len(serviceNameL) > 0 { serviceName = serviceNameL[0] } serviceVersionL, ok := md["service-version"] if ok && len(serviceVersionL) > 0 { serviceVersion = serviceVersionL[0] } netAddressL, ok := md["net-address"] if ok && len(netAddressL) > 0 { netAddress = netAddressL[0] } return }
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/fbuf.go#L23-L33
func NewFloat64RingBuf(maxViewItems int) *Float64RingBuf { n := maxViewItems r := &Float64RingBuf{ N: n, Beg: 0, Readable: 0, } r.A = make([]float64, n, n) return r }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L331-L333
func NewPRSignedByKeyPath(keyType sbKeyType, keyPath string, signedIdentity PolicyReferenceMatch) (PolicyRequirement, error) { return newPRSignedByKeyPath(keyType, keyPath, signedIdentity) }
https://github.com/google/acme/blob/7c6dfc908d68ed254a16c126f6770f4d9d9352da/main.go#L135-L142
func (c *command) Name() string { name := c.UsageLine i := strings.IndexRune(name, ' ') if i >= 0 { name = name[:i] } return name }
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/auth.go#L25-L42
func (c Auth) Write(w *bufio.Writer) (err error) { if _, err = w.WriteString("AUTH\n"); err != nil { err = errors.Wrap(err, "writing AUTH command") return } if err = binary.Write(w, binary.BigEndian, uint32(len(c.Secret))); err != nil { err = errors.Wrap(err, "writing AUTH secret size") return } if _, err = w.WriteString(c.Secret); err != nil { err = errors.Wrap(err, "writing AUTH secret data") return } return }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L106-L110
func (eC2Manager *EC2Manager) RunInstance(workerType string, payload *MakeASpotRequest) error { cd := tcclient.Client(*eC2Manager) _, _, err := (&cd).APICall(payload, "PUT", "/worker-types/"+url.QueryEscape(workerType)+"/instance", nil, nil) return err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L5418-L5422
func (v *EventWebSocketFrameSent) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork42(&r, v) return r.Error() }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/mmap_unix.go#L31-L37
func Mmap(fd *os.File, writable bool, size int64) ([]byte, error) { mtype := unix.PROT_READ if writable { mtype |= unix.PROT_WRITE } return unix.Mmap(int(fd.Fd()), 0, int(size), mtype, unix.MAP_SHARED) }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/prop.go#L324-L330
func SaveStruct(src interface{}) ([]Property, error) { x, err := newStructPLS(src) if err != nil { return nil, err } return x.Save() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L951-L967
func (c *Client) DeleteStaleComments(org, repo string, number int, comments []IssueComment, isStale func(IssueComment) bool) error { var err error if comments == nil { comments, err = c.ListIssueComments(org, repo, number) if err != nil { return fmt.Errorf("failed to list comments while deleting stale comments. err: %v", err) } } for _, comment := range comments { if isStale(comment) { if err := c.DeleteComment(org, repo, comment.ID); err != nil { return fmt.Errorf("failed to delete stale comment with ID '%d'", comment.ID) } } } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1189-L1193
func (v GetHeapObjectIDReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoHeapprofiler13(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/process.go#L138-L241
func Core(coreFile, base, exePath string) (*Process, error) { core, err := os.Open(coreFile) if err != nil { return nil, fmt.Errorf("failed to open core file: %v", err) } p := &Process{base: base, files: make(map[string]*file)} if exePath != "" { bin, err := os.Open(exePath) if err != nil { return nil, fmt.Errorf("failed to open executable file: %v", err) } p.exe = bin } if err := p.readExec(p.exe); err != nil { return nil, err } if err := p.readCore(core); err != nil { return nil, err } if err := p.readDebugInfo(); err != nil { return nil, err } // Sort then merge mappings, just to clean up a bit. mappings := p.memory.mappings sort.Slice(mappings, func(i, j int) bool { return mappings[i].min < mappings[j].min }) ms := mappings[1:] mappings = mappings[:1] for _, m := range ms { k := mappings[len(mappings)-1] if m.min == k.max && m.perm == k.perm && m.f == k.f && m.off == k.off+k.Size() { k.max = m.max // TODO: also check origF? } else { mappings = append(mappings, m) } } p.memory.mappings = mappings // Memory map all the mappings. hostPageSize := int64(syscall.Getpagesize()) for _, m := range p.memory.mappings { size := m.max.Sub(m.min) if m.f == nil { // We don't have any source for this data. // Could be a mapped file that we couldn't find. // Could be a mapping madvised as MADV_DONTDUMP. // Pretend this is read-as-zero. // The other option is to just throw away // the mapping (and thus make Read*s of this // mapping fail). p.warnings = append(p.warnings, fmt.Sprintf("Missing data at addresses [%x %x]. Assuming all zero.", m.min, m.max)) // TODO: this allocation could be large. // Use mmap to avoid real backing store for all those zeros, or // perhaps split the mapping up into chunks and share the zero contents among them. m.contents = make([]byte, size) continue } if m.perm&Write != 0 && m.f != core { p.warnings = append(p.warnings, fmt.Sprintf("Writeable data at [%x %x] missing from core. Using possibly stale backup source %s.", m.min, m.max, m.f.Name())) } // Data in core file might not be aligned enough for the host. // Expand memory range so we can map full pages. minOff := m.off maxOff := m.off + size minOff -= minOff % hostPageSize if maxOff%hostPageSize != 0 { maxOff += hostPageSize - maxOff%hostPageSize } // Read data from file. data, err := mapFile(int(m.f.Fd()), minOff, int(maxOff-minOff)) if err != nil { return nil, fmt.Errorf("can't memory map %s at %x: %s\n", m.f.Name(), minOff, err) } // Trim any data we mapped but don't need. data = data[m.off-minOff:] data = data[:size] m.contents = data } // Build page table for mapping lookup. for _, m := range p.memory.mappings { err := p.addMapping(m) if err != nil { return nil, err } } return p, nil }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L593-L598
func cleanupVM(v *VM) { if v.handle != C.VIX_INVALID_HANDLE { C.Vix_ReleaseHandle(v.handle) v.handle = C.VIX_INVALID_HANDLE } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/serviceworker.go#L122-L124
func (p *InspectWorkerParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandInspectWorker, p, nil) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/maas/controller.go#L348-L369
func (c *Controller) RenameContainer(name string, newName string) error { device, err := c.getDevice(name) if err != nil { return err } // FIXME: We should convince the Juju folks to implement an Update() method on Device uri, err := url.Parse(fmt.Sprintf("%s/devices/%s/", c.url, device.SystemID())) if err != nil { return err } values := url.Values{} values.Set("hostname", newName) _, err = c.srvRaw.Put(uri, values) if err != nil { return err } return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/storage.go#L216-L234
func (ms *MemoryStorage) Compact(compactIndex uint64) error { ms.Lock() defer ms.Unlock() offset := ms.ents[0].Index if compactIndex <= offset { return ErrCompacted } if compactIndex > ms.lastIndex() { raftLogger.Panicf("compact %d is out of bound lastindex(%d)", compactIndex, ms.lastIndex()) } i := compactIndex - offset ents := make([]pb.Entry, 1, 1+uint64(len(ms.ents))-i) ents[0].Index = ms.ents[i].Index ents[0].Term = ms.ents[i].Term ents = append(ents, ms.ents[i+1:]...) ms.ents = ents return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L1859-L1863
func (v *Animation) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoAnimation19(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/tabwriter/tabwriter.go#L42-L54
func (w *Writer) Write(buf []byte) (int, error) { if w.lines >= termHeight { if err := w.Flush(); err != nil { return 0, err } if _, err := w.w.Write(w.header); err != nil { return 0, err } w.lines++ } w.lines += bytes.Count(buf, []byte{'\n'}) return w.w.Write(buf) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction_envelope.go#L64-L76
func (b *TransactionEnvelopeBuilder) Bytes() ([]byte, error) { if b.Err != nil { return nil, b.Err } var txBytes bytes.Buffer _, err := xdr.Marshal(&txBytes, b.E) if err != nil { return nil, err } return txBytes.Bytes(), nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L313-L315
func (p *SetDocumentCookieDisabledParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetDocumentCookieDisabled, p, nil) }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/connection.go#L160-L257
func (conn *LocalConnection) run(errorChan <-chan error, finished chan<- struct{}, acceptNewPeer bool) { var err error // important to use this var and not create another one with 'err :=' defer func() { conn.teardown(err) }() defer close(finished) if err = conn.tcpConn.SetLinger(0); err != nil { return } intro, err := protocolIntroParams{ MinVersion: conn.router.ProtocolMinVersion, MaxVersion: ProtocolMaxVersion, Features: conn.makeFeatures(), Conn: conn.tcpConn, Password: conn.router.Password, Outbound: conn.outbound, }.doIntro() if err != nil { return } conn.sessionKey = intro.SessionKey conn.tcpSender = intro.Sender conn.version = intro.Version remote, err := conn.parseFeatures(intro.Features) if err != nil { return } if err = conn.registerRemote(remote, acceptNewPeer); err != nil { return } isRestartedPeer := conn.Remote().UID != remote.UID conn.logf("connection ready; using protocol version %v", conn.version) // only use negotiated session key for untrusted connections var sessionKey *[32]byte if conn.untrusted() { sessionKey = conn.sessionKey } params := OverlayConnectionParams{ RemotePeer: conn.remote, LocalAddr: conn.tcpConn.LocalAddr().(*net.TCPAddr), RemoteAddr: conn.tcpConn.RemoteAddr().(*net.TCPAddr), Outbound: conn.outbound, ConnUID: conn.uid, SessionKey: sessionKey, SendControlMessage: conn.sendOverlayControlMessage, Features: intro.Features, } if conn.OverlayConn, err = conn.router.Overlay.PrepareConnection(params); err != nil { return } // As soon as we do AddConnection, the new connection becomes // visible to the packet routing logic. So AddConnection must // come after PrepareConnection if err = conn.router.Ourself.doAddConnection(conn, isRestartedPeer); err != nil { return } conn.router.ConnectionMaker.connectionCreated(conn) // OverlayConnection confirmation comes after AddConnection, // because only after that completes do we know the connection is // valid: in particular that it is not a duplicate connection to // the same peer. Overlay communication on a duplicate connection // can cause problems such as tripping up overlay crypto at the // other end due to data being decoded by the other connection. It // is also generally wasteful to engage in any interaction with // the remote on a connection that turns out to be invalid. conn.OverlayConn.Confirm() // receiveTCP must follow also AddConnection. In the absence // of any indirect connectivity to the remote peer, the first // we hear about it (and any peers reachable from it) is // through topology gossip it sends us on the connection. We // must ensure that the connection has been added to Ourself // prior to processing any such gossip, otherwise we risk // immediately gc'ing part of that newly received portion of // the topology (though not the remote peer itself, since that // will have a positive ref count), leaving behind dangling // references to peers. Hence we must invoke AddConnection, // which is *synchronous*, first. conn.heartbeatTCP = time.NewTicker(tcpHeartbeat) go conn.receiveTCP(intro.Receiver) // AddConnection must precede actorLoop. More precisely, it // must precede shutdown, since that invokes DeleteConnection // and is invoked on termination of this entire // function. Essentially this boils down to a prohibition on // running AddConnection in a separate goroutine, at least not // without some synchronisation. Which in turn requires the // launching of the receiveTCP goroutine to precede actorLoop. err = conn.actorLoop(errorChan) }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/region.go#L106-L115
func (r region) String() string { if r.typ.Kind != KindString { panic("bad string type " + r.typ.Name) } p := r.p.proc.ReadPtr(r.a) n := r.p.proc.ReadUintptr(r.a.Add(r.p.proc.PtrSize())) b := make([]byte, n) r.p.proc.ReadAt(b, p) return string(b) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L87-L90
func (p ContinueInterceptedRequestParams) WithErrorReason(errorReason ErrorReason) *ContinueInterceptedRequestParams { p.ErrorReason = errorReason return &p }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L265-L274
func (g *Gateway) DialFunc() dqlite.DialFunc { return func(ctx context.Context, address string) (net.Conn, error) { // Memory connection. if g.memoryDial != nil { return g.memoryDial(ctx, address) } return dqliteNetworkDial(ctx, address, g.cert) } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/metadata/action.go#L99-L119
func (a *Action) URL(vars []*PathVariable) (*ActionPath, error) { candidates := make([]*ActionPath, len(a.PathPatterns)) allMissing := []string{} j := 0 for _, p := range a.PathPatterns { path, names := p.Substitute(vars) if path == "" { allMissing = append(allMissing, names...) } else { candidates[j] = &ActionPath{path, p.HTTPMethod, len(names)} j++ } } if j == 0 { return nil, fmt.Errorf("Missing variables to instantiate action URL, one or more of the following variables are needed: %s", strings.Join(allMissing, ", ")) } candidates = candidates[:j] sort.Sort(ByWeight(candidates)) return candidates[0], nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/headlessexperimental/easyjson.go#L468-L472
func (v BeginFrameParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoHeadlessexperimental5(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L253-L256
func StorageVolumeDescriptionUpdate(tx *sql.Tx, volumeID int64, description string) error { _, err := tx.Exec("UPDATE storage_volumes SET description=? WHERE id=?", description, volumeID) return err }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/node.go#L604-L611
func MustSync(st, prevst pb.HardState, entsnum int) bool { // Persistent state on all servers: // (Updated on stable storage before responding to RPCs) // currentTerm // votedFor // log entries[] return entsnum != 0 || st.Vote != prevst.Vote || st.Term != prevst.Term }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/swagger.go#L146-L154
func (ep *Endpoint) Service() string { if len(ep.Tags) > 0 { return ep.Tags[0] } if len(ep.OperationID) > 0 { return strings.Split(ep.OperationID, "#")[0] } return "" }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/dry_run_client.go#L100-L133
func (c *dryRunProwJobClient) requestRetry(path string, query map[string]string) ([]byte, error) { resp, err := c.retry(path, query) if err != nil { return nil, err } defer resp.Body.Close() rb, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } if resp.StatusCode == 404 { return nil, &kapierrors.StatusError{ErrStatus: metav1.Status{ Status: metav1.StatusFailure, Code: http.StatusNotFound, Reason: metav1.StatusReasonNotFound, }} } else if resp.StatusCode == 409 { return nil, &kapierrors.StatusError{ErrStatus: metav1.Status{ Status: metav1.StatusFailure, Code: http.StatusConflict, Reason: metav1.StatusReasonAlreadyExists, }} } else if resp.StatusCode == 422 { return nil, &kapierrors.StatusError{ErrStatus: metav1.Status{ Status: metav1.StatusFailure, Code: http.StatusUnprocessableEntity, Reason: metav1.StatusReasonInvalid, }} } else if resp.StatusCode < 200 || resp.StatusCode > 299 { return nil, fmt.Errorf("response has status \"%s\" and body \"%s\"", resp.Status, string(rb)) } return rb, nil }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/builder.go#L68-L76
func (b *Builder) NewSegment() *Segment { seg := &Segment{tail: make([]*Node, MaxLevel+1), head: make([]*Node, MaxLevel+1), builder: b, rand: rand.New(rand.NewSource(int64(rand.Int()))), } seg.sts.IsLocal(true) return seg }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/easyjson.go#L715-L719
func (v Header) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCachestorage6(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/image/platform.go#L81-L87
func (s *platformImageService) ListImagesOrDefault(platformName string) ([]string, error) { imgs, err := s.ListImages(platformName) if err != nil && err == imageTypes.ErrPlatformImageNotFound { return []string{platformBasicImageName(platformName)}, nil } return imgs, err }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L486-L491
func (l *Load) Remove(sym string) { if _, ok := l.symbols[sym]; ok { delete(l.symbols, sym) l.updated = true } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/storage.go#L70-L79
func (p *GetUsageAndQuotaParams) Do(ctx context.Context) (usage float64, quota float64, usageBreakdown []*UsageForType, err error) { // execute var res GetUsageAndQuotaReturns err = cdp.Execute(ctx, CommandGetUsageAndQuota, p, &res) if err != nil { return 0, 0, nil, err } return res.Usage, res.Quota, res.UsageBreakdown, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_btrfs.go#L817-L820
func (s *storageBtrfs) ContainerStorageReady(container container) bool { containerMntPoint := getContainerMountPoint(container.Project(), s.pool.Name, container.Name()) return isBtrfsSubVolume(containerMntPoint) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/idmap/idmapset_linux.go#L249-L261
func Extend(slice []IdmapEntry, element IdmapEntry) []IdmapEntry { n := len(slice) if n == cap(slice) { // Slice is full; must grow. // We double its size and add 1, so if the size is zero we still grow. newSlice := make([]IdmapEntry, len(slice), 2*len(slice)+1) copy(newSlice, slice) slice = newSlice } slice = slice[0 : n+1] slice[n] = element return slice }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/easyjson.go#L407-L411
func (v GetFramesWithManifestsParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoApplicationcache4(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/easyjson.go#L810-L814
func (v EventCacheStorageListUpdated) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoStorage9(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L469-L476
func (s *FileSequence) SetFrameRange(frameRange string) error { frameSet, err := NewFrameSet(frameRange) if err != nil { return err } s.frameSet = frameSet return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/tide.go#L1418-L1456
func headContexts(log *logrus.Entry, ghc githubClient, pr *PullRequest) ([]Context, error) { for _, node := range pr.Commits.Nodes { if node.Commit.OID == pr.HeadRefOID { return node.Commit.Status.Contexts, nil } } // We didn't get the head commit from the query (the commits must not be // logically ordered) so we need to specifically ask GitHub for the status // and coerce it to a graphql type. org := string(pr.Repository.Owner.Login) repo := string(pr.Repository.Name) // Log this event so we can tune the number of commits we list to minimize this. log.Warnf("'last' %d commits didn't contain logical last commit. Querying GitHub...", len(pr.Commits.Nodes)) combined, err := ghc.GetCombinedStatus(org, repo, string(pr.HeadRefOID)) if err != nil { return nil, fmt.Errorf("failed to get the combined status: %v", err) } contexts := make([]Context, 0, len(combined.Statuses)) for _, status := range combined.Statuses { contexts = append( contexts, Context{ Context: githubql.String(status.Context), Description: githubql.String(status.Description), State: githubql.StatusState(strings.ToUpper(status.State)), }, ) } // Add a commit with these contexts to pr for future look ups. pr.Commits.Nodes = append(pr.Commits.Nodes, struct{ Commit Commit }{ Commit: Commit{ OID: pr.HeadRefOID, Status: struct{ Contexts []Context }{Contexts: contexts}, }, }, ) return contexts, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3624-L3628
func (v GetFrameOwnerParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom41(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L1199-L1203
func (v SetDeviceMetricsOverrideParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoEmulation12(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/performance/easyjson.go#L152-L156
func (v Metric) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPerformance1(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/ip2location/ip2location-go/blob/a417f19539fd2a0eb0adf273b4190241cacc0499/ip2location.go#L681-L702
func Printrecord(x IP2Locationrecord) { fmt.Printf("country_short: %s\n", x.Country_short) fmt.Printf("country_long: %s\n", x.Country_long) fmt.Printf("region: %s\n", x.Region) fmt.Printf("city: %s\n", x.City) fmt.Printf("isp: %s\n", x.Isp) fmt.Printf("latitude: %f\n", x.Latitude) fmt.Printf("longitude: %f\n", x.Longitude) fmt.Printf("domain: %s\n", x.Domain) fmt.Printf("zipcode: %s\n", x.Zipcode) fmt.Printf("timezone: %s\n", x.Timezone) fmt.Printf("netspeed: %s\n", x.Netspeed) fmt.Printf("iddcode: %s\n", x.Iddcode) fmt.Printf("areacode: %s\n", x.Areacode) fmt.Printf("weatherstationcode: %s\n", x.Weatherstationcode) fmt.Printf("weatherstationname: %s\n", x.Weatherstationname) fmt.Printf("mcc: %s\n", x.Mcc) fmt.Printf("mnc: %s\n", x.Mnc) fmt.Printf("mobilebrand: %s\n", x.Mobilebrand) fmt.Printf("elevation: %f\n", x.Elevation) fmt.Printf("usagetype: %s\n", x.Usagetype) }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/geometry/geometry.go#L313-L344
func Draw(gc draw2d.GraphicContext, width, height float64) { mx, my := width*0.025, height*0.025 // margin dx, dy := (width-2*mx)/4, (height-2*my)/3 w, h := dx-2*mx, dy-2*my x0, y := 2*mx, 2*my x := x0 Bubble(gc, x, y, w, h) x += dx CurveRectangle(gc, x, y, w, h, color.NRGBA{0x80, 0, 0, 0x80}, color.NRGBA{0x80, 0x80, 0xFF, 0xFF}) x += dx Dash(gc, x, y, w, h) x += dx Arc(gc, x, y, w, h) x = x0 y += dy ArcNegative(gc, x, y, w, h) x += dx CubicCurve(gc, x, y, w, h) x += dx FillString(gc, x, y, w, h) x += dx FillStroke(gc, x, y, w, h) x = x0 y += dy FillStyle(gc, x, y, w, h) x += dx PathTransform(gc, x, y, w, h) x += dx Star(gc, x, y, w, h) x += dx gopher2.Draw(gc, x, y, w, h/2) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/idmap/idmapset_linux.go#L741-L892
func DefaultIdmapSet(rootfs string, username string) (*IdmapSet, error) { idmapset := new(IdmapSet) if username == "" { currentUser, err := user.Current() if err != nil { return nil, err } username = currentUser.Username } // Check if shadow's uidmap tools are installed subuidPath := path.Join(rootfs, "/etc/subuid") subgidPath := path.Join(rootfs, "/etc/subgid") if shared.PathExists(subuidPath) && shared.PathExists(subgidPath) { // Parse the shadow uidmap entries, err := getFromShadow(subuidPath, username) if err != nil { return nil, err } for _, entry := range entries { // Check that it's big enough to be useful if int(entry[1]) < 65536 { continue } e := IdmapEntry{Isuid: true, Nsid: 0, Hostid: entry[0], Maprange: entry[1]} idmapset.Idmap = Extend(idmapset.Idmap, e) // NOTE: Remove once LXD can deal with multiple shadow maps break } // Parse the shadow gidmap entries, err = getFromShadow(subgidPath, username) if err != nil { return nil, err } for _, entry := range entries { // Check that it's big enough to be useful if int(entry[1]) < 65536 { continue } e := IdmapEntry{Isgid: true, Nsid: 0, Hostid: entry[0], Maprange: entry[1]} idmapset.Idmap = Extend(idmapset.Idmap, e) // NOTE: Remove once LXD can deal with multiple shadow maps break } return idmapset, nil } // No shadow available, figure out a default map kernelMap, err := CurrentIdmapSet() if err != nil { // Hardcoded fallback map e := IdmapEntry{Isuid: true, Isgid: false, Nsid: 0, Hostid: 1000000, Maprange: 1000000000} idmapset.Idmap = Extend(idmapset.Idmap, e) e = IdmapEntry{Isuid: false, Isgid: true, Nsid: 0, Hostid: 1000000, Maprange: 1000000000} idmapset.Idmap = Extend(idmapset.Idmap, e) return idmapset, nil } // Look for mapped ranges kernelRanges, err := kernelMap.ValidRanges() if err != nil { return nil, err } // Special case for when we have the full kernel range fullKernelRanges := []*IdRange{ {true, false, int64(0), int64(4294967294)}, {false, true, int64(0), int64(4294967294)}} if reflect.DeepEqual(kernelRanges, fullKernelRanges) { // Hardcoded fallback map e := IdmapEntry{Isuid: true, Isgid: false, Nsid: 0, Hostid: 1000000, Maprange: 1000000000} idmapset.Idmap = Extend(idmapset.Idmap, e) e = IdmapEntry{Isuid: false, Isgid: true, Nsid: 0, Hostid: 1000000, Maprange: 1000000000} idmapset.Idmap = Extend(idmapset.Idmap, e) return idmapset, nil } // Find a suitable uid range for _, entry := range kernelRanges { // We only care about uids right now if !entry.Isuid { continue } // We want a map that's separate from the system's own POSIX allocation if entry.Endid < 100000 { continue } // Don't use the first 65536 ids if entry.Startid < 100000 { entry.Startid = 100000 } // Check if we have enough ids if entry.Endid-entry.Startid < 65536 { continue } // Add the map e := IdmapEntry{Isuid: true, Isgid: false, Nsid: 0, Hostid: entry.Startid, Maprange: entry.Endid - entry.Startid + 1} idmapset.Idmap = Extend(idmapset.Idmap, e) // NOTE: Remove once LXD can deal with multiple shadow maps break } // Find a suitable gid range for _, entry := range kernelRanges { // We only care about gids right now if !entry.Isgid { continue } // We want a map that's separate from the system's own POSIX allocation if entry.Endid < 100000 { continue } // Don't use the first 65536 ids if entry.Startid < 100000 { entry.Startid = 100000 } // Check if we have enough ids if entry.Endid-entry.Startid < 65536 { continue } // Add the map e := IdmapEntry{Isuid: false, Isgid: true, Nsid: 0, Hostid: entry.Startid, Maprange: entry.Endid - entry.Startid + 1} idmapset.Idmap = Extend(idmapset.Idmap, e) // NOTE: Remove once LXD can deal with multiple shadow maps break } return idmapset, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L584-L586
func (p *SetBlackboxedRangesParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetBlackboxedRanges, p, nil) }
https://github.com/nicholasjackson/bench/blob/2df9635f0ad020b2e82616b0fd87130aaa1ee12e/bench.go#L39-L53
func New( showProgress bool, threads int, duration time.Duration, rampUp time.Duration, timeout time.Duration) *Bench { return &Bench{ showProgress: showProgress, threads: threads, duration: duration, rampUp: rampUp, timeout: timeout, } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/retry.go#L89-L117
func (r RetryOn) CanRetry(err error) bool { if r == RetryNever { return false } if r == RetryDefault { r = RetryConnectionError } code := getErrCode(err) if code == ErrCodeBusy || code == ErrCodeDeclined { return true } // Never retry bad requests, since it will probably cause another bad request. if code == ErrCodeBadRequest { return false } switch r { case RetryConnectionError: return code == ErrCodeNetwork case RetryUnexpected: return code == ErrCodeUnexpected case RetryIdempotent: return true } return false }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L371-L373
func (m *Mat) Set2D(x, y int, value Scalar) { C.cvSet2D(unsafe.Pointer(m), C.int(x), C.int(y), (C.CvScalar)(value)) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_src.go#L284-L298
func (s *dockerImageSource) manifestDigest(ctx context.Context, instanceDigest *digest.Digest) (digest.Digest, error) { if instanceDigest != nil { return *instanceDigest, nil } if digested, ok := s.ref.ref.(reference.Digested); ok { d := digested.Digest() if d.Algorithm() == digest.Canonical { return d, nil } } if err := s.ensureManifestIsLoaded(ctx); err != nil { return "", err } return manifest.Digest(s.cachedManifest) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L90-L93
func (p CopyToParams) WithInsertBeforeNodeID(insertBeforeNodeID cdp.NodeID) *CopyToParams { p.InsertBeforeNodeID = insertBeforeNodeID return &p }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/op.go#L231-L261
func OpDelete(key string, opts ...OpOption) Op { // WithPrefix and WithFromKey are not supported together if isWithPrefix(opts) && isWithFromKey(opts) { panic("`WithPrefix` and `WithFromKey` cannot be set at the same time, choose one") } ret := Op{t: tDeleteRange, key: []byte(key)} ret.applyOpts(opts) switch { case ret.leaseID != 0: panic("unexpected lease in delete") case ret.limit != 0: panic("unexpected limit in delete") case ret.rev != 0: panic("unexpected revision in delete") case ret.sort != nil: panic("unexpected sort in delete") case ret.serializable: panic("unexpected serializable in delete") case ret.countOnly: panic("unexpected countOnly in delete") case ret.minModRev != 0, ret.maxModRev != 0: panic("unexpected mod revision filter in delete") case ret.minCreateRev != 0, ret.maxCreateRev != 0: panic("unexpected create revision filter in delete") case ret.filterDelete, ret.filterPut: panic("unexpected filter in delete") case ret.createdNotify: panic("unexpected createdNotify in delete") } return ret }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/easyjson.go#L1288-L1292
func (v GetFullAXTreeParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoAccessibility8(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L95-L104
func (p *CollectClassNamesParams) Do(ctx context.Context) (classNames []string, err error) { // execute var res CollectClassNamesReturns err = cdp.Execute(ctx, CommandCollectClassNames, p, &res) if err != nil { return nil, err } return res.ClassNames, nil }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqls/manager.go#L292-L334
func preparePaths(paths []string) ([]string, fileseq.FileSequences) { var ( fi os.FileInfo err error ) dirs := make([]string, 0) seqs := make(fileseq.FileSequences, 0) previous := make(map[string]struct{}) for _, p := range paths { p := strings.TrimSpace(filepath.Clean(p)) if p == "" { continue } if _, seen := previous[p]; seen { continue } previous[p] = struct{}{} if fi, err = os.Stat(p); err != nil { // If the path doesn't exist, test it for // a valid fileseq pattern if seq, err := fileseq.NewFileSequence(p); err == nil { seqs = append(seqs, seq) continue } fmt.Fprintf(errOut, "%s %q: %s\n", ErrorPath, p, err) continue } if !fi.IsDir() { continue } dirs = append(dirs, p) } return dirs, seqs }
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/fbuf.go#L153-L185
func (b *Float64RingBuf) Write(p []float64) (n int, err error) { for { if len(p) == 0 { // nothing (left) to copy in; notice we shorten our // local copy p (below) as we read from it. return } writeCapacity := b.N - b.Readable if writeCapacity <= 0 { // we are all full up already. return n, io.ErrShortWrite } if len(p) > writeCapacity { err = io.ErrShortWrite // leave err set and // keep going, write what we can. } writeStart := (b.Beg + b.Readable) % b.N upperLim := intMin(writeStart+writeCapacity, b.N) k := copy(b.A[writeStart:upperLim], p) n += k b.Readable += k p = p[k:] // we can fill from b.A[0:something] from // p's remainder, so loop } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/animation.go#L102-L111
func (p *GetPlaybackRateParams) Do(ctx context.Context) (playbackRate float64, err error) { // execute var res GetPlaybackRateReturns err = cdp.Execute(ctx, CommandGetPlaybackRate, nil, &res) if err != nil { return 0, err } return res.PlaybackRate, nil }