_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/app.go#L33-L40
func (m *App) Validate(formats strfmt.Registry) error { var res []error if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L518-L521
func (capture *Capture) Release() { cap_c := (*C.CvCapture)(capture) C.cvReleaseCapture(&cap_c) }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_reflect.go#L218-L235
func formatString(s string) string { // Use quoted string if it the same length as a raw string literal. // Otherwise, attempt to use the raw string form. qs := strconv.Quote(s) if len(qs) == 1+len(s)+1 { return qs } // Disallow newlines to ensure output is a single line. // Only allow printable runes for readability purposes. rawInvalid := func(r rune) bool { return r == '`' || r == '\n' || !(unicode.IsPrint(r) || r == '\t') } if strings.IndexFunc(s, rawInvalid) < 0 { return "`" + s + "`" } return qs }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L1081-L1085
func (v *SetBreakpointParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger11(&r, v) return r.Error() }
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/atomic_rbuf.go#L416-L421
func (b *AtomicFixedSizeRingBuf) Advance(n int) { b.tex.Lock() defer b.tex.Unlock() b.unatomic_advance(n) }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/controller.go#L118-L132
func (c *Controller) Int64Range(fieldName string, p interface{}, n int64, m int64) int64 { if p == nil { p = 0 } value, ok := c.toNumber64(p) if ok == false { panic((&ValidationError{}).New(fieldName + "必须是数字")) } b := c.Validate.Range64(value, n, m) if b == false { panic((&ValidationError{}).New(fieldName + "值的范围应该从 " + strconv.FormatInt(n, 10) + " 到 " + strconv.FormatInt(m, 10))) } return value }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/errors.go#L91-L96
func (e *ValidationError) New(message string) *ValidationError { e.HTTPCode = http.StatusBadRequest e.Errno = 0 e.Message = message return e }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/jsonp.go#L59-L65
func (w *jsonpResponseWriter) WriteHeader(code int) { w.Header().Set("Content-Type", "text/javascript") w.ResponseWriter.WriteHeader(code) w.wroteHeader = true }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/config.go#L268-L272
func (c *ServerConfig) ReqTimeout() time.Duration { // 5s for queue waiting, computation and disk IO delay // + 2 * election timeout for possible leader election return 5*time.Second + 2*time.Duration(c.ElectionTicks*int(c.TickMs))*time.Millisecond }
https://github.com/OneOfOne/xxhash/blob/c1e3185f167680b62832a0a11938a04b1ab265fc/xxhash.go#L116-L122
func NewS64(seed uint64) (xx *XXHash64) { xx = &XXHash64{ seed: seed, } xx.Reset() return }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L98-L100
func VerifyHeaderKV(key string, values ...string) http.HandlerFunc { return VerifyHeader(http.Header{key: values}) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L495-L526
func (db *DB) get(key []byte) (y.ValueStruct, error) { tables, decr := db.getMemTables() // Lock should be released. defer decr() var maxVs *y.ValueStruct var version uint64 if bytes.HasPrefix(key, badgerMove) { // If we are checking badgerMove key, we should look into all the // levels, so we can pick up the newer versions, which might have been // compacted down the tree. maxVs = &y.ValueStruct{} version = y.ParseTs(key) } y.NumGets.Add(1) for i := 0; i < len(tables); i++ { vs := tables[i].Get(key) y.NumMemtableGets.Add(1) if vs.Meta == 0 && vs.Value == nil { continue } // Found a version of the key. For user keyspace, return immediately. For move keyspace, // continue iterating, unless we found a version == given key version. if maxVs == nil || vs.Version == version { return vs, nil } if maxVs.Version < vs.Version { *maxVs = vs } } return db.lc.get(key, maxVs) }
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/exception.go#L40-L47
func (x *Exception) SetRule(rule string) error { ruleRegexp, err := regexp.Compile("(?i)" + rule) if err != nil { return err } x.Rule = ruleRegexp return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L397-L401
func (v ScrollRect) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoLayertree3(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gomega_dsl.go#L375-L377
func (g *WithT) Expect(actual interface{}, extra ...interface{}) Assertion { return assertion.New(actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), 0, extra...) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L769-L772
func (p SetCookieParams) WithDomain(domain string) *SetCookieParams { p.Domain = domain return &p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1130-L1134
func (v *GetObjectByHeapObjectIDParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeapprofiler12(&r, v) return r.Error() }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/clientset/versioned/typed/tsuru/v1/app.go#L87-L96
func (c *apps) Create(app *v1.App) (result *v1.App, err error) { result = &v1.App{} err = c.client.Post(). Namespace(c.ns). Resource("apps"). Body(app). Do(). Into(result) return }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/relay_timer_pool.go#L88-L95
func (tp *relayTimerPool) Put(rt *relayTimer) { if tp.verify { // If we are trying to verify correct pool behavior, then we don't release // the timer, and instead ensure no methods are called after being released. return } tp.pool.Put(rt) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L76-L78
func WithAbortContext(ctx context.Context) stmOption { return func(so *stmOptions) { so.ctx = ctx } }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6095-L6103
func (u PeerAddressIp) ArmForSwitch(sw int32) (string, bool) { switch IpAddrType(sw) { case IpAddrTypeIPv4: return "Ipv4", true case IpAddrTypeIPv6: return "Ipv6", true } return "-", false }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L155-L161
func LoadMacroData(path, pkg, defName string, data []byte) (*File, error) { ast, err := bzl.ParseBzl(path, data) if err != nil { return nil, err } return ScanASTBody(pkg, defName, ast), nil }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L245-L256
func (s *MockSpan) LogKV(keyValues ...interface{}) { if len(keyValues)%2 != 0 { s.LogFields(log.Error(fmt.Errorf("Non-even keyValues len: %v", len(keyValues)))) return } fields, err := log.InterleavedKVToFields(keyValues...) if err != nil { s.LogFields(log.Error(err), log.String("function", "LogKV")) return } s.LogFields(fields...) }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer_name_hash.go#L27-L31
func PeerNameFromUserInput(userInput string) (PeerName, error) { // fixed-length identity nameByteAry := sha256.Sum256([]byte(userInput)) return PeerNameFromBin(nameByteAry[:NameSize]), nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/ppsdb/ppsdb.go#L43-L52
func Jobs(etcdClient *etcd.Client, etcdPrefix string) col.Collection { return col.NewCollection( etcdClient, path.Join(etcdPrefix, jobsPrefix), []*col.Index{JobsPipelineIndex, JobsOutputIndex}, &pps.EtcdJobInfo{}, nil, nil, ) }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/diff/result.go#L44-L48
func (r *Result) Concat(other *Result) { for _, dj := range other.DeltaJob { r.DeltaJob = append(r.DeltaJob, dj) } }
https://github.com/stefantalpalaru/pool/blob/df8b849d27751462526089005979b28064c1e08e/pool.go#L76-L96
func (pool *Pool) worker(worker_id uint) { job_pipe := make(chan *Job) WORKER_LOOP: for { pool.job_wanted_pipe <- job_pipe job := <-job_pipe if job == nil { time.Sleep(pool.interval * time.Millisecond) } else { job.Worker_id = worker_id pool.subworker(job) pool.done_pipe <- job } select { case <-pool.worker_kill_pipe: break WORKER_LOOP default: } } pool.worker_wg.Done() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/unique_strings.go#L57-L66
func NewUniqueStringsValue(s string) (us *UniqueStringsValue) { us = &UniqueStringsValue{Values: make(map[string]struct{})} if s == "" { return us } if err := us.Set(s); err != nil { plog.Panicf("new UniqueStringsValue should never fail: %v", err) } return us }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ss.go#L84-L114
func setupMetadata() (result map[string]*metadata.Resource) { result = make(map[string]*metadata.Resource) for n, r := range ssd.GenMetadata { result[n] = r for _, a := range r.Actions { for _, p := range a.PathPatterns { // remove "/api/designer" prefix p.Regexp = removePrefixes(p.Regexp, 2) } } } for n, r := range ssc.GenMetadata { result[n] = r for _, a := range r.Actions { for _, p := range a.PathPatterns { // remove "/api/catalog" prefix p.Regexp = removePrefixes(p.Regexp, 2) } } } for n, r := range ssm.GenMetadata { result[n] = r for _, a := range r.Actions { for _, p := range a.PathPatterns { // remove "/api/manager" prefix p.Regexp = removePrefixes(p.Regexp, 2) } } } return }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2614-L2617
func (e PaymentResultCode) ValidEnum(v int32) bool { _, ok := paymentResultCodeMap[v] return ok }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L280-L284
func (v *TextBoxSnapshot) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomsnapshot(&r, v) return r.Error() }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/clientset/versioned/typed/tsuru/v1/app.go#L44-L49
func newApps(c *TsuruV1Client, namespace string) *apps { return &apps{ client: c.RESTClient(), ns: namespace, } }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/process.go#L99-L101
func (p *Process) FindFunc(pc core.Address) *Func { return p.funcTab.find(pc) }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/policy.go#L84-L91
func DefaultGrantStrategy(scope oauth2.Scope, _ Client, _ ResourceOwner) (oauth2.Scope, error) { // check scope if !scope.Empty() { return nil, ErrInvalidScope } return scope, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/decorate/podspec.go#L409-L417
func PlaceEntrypoint(image string, toolsMount coreapi.VolumeMount) coreapi.Container { return coreapi.Container{ Name: "place-entrypoint", Image: image, Command: []string{"/bin/cp"}, Args: []string{"/entrypoint", entrypointLocation(toolsMount)}, VolumeMounts: []coreapi.VolumeMount{toolsMount}, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/database/easyjson.go#L333-L337
func (v ExecuteSQLReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDatabase2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/replication.go#L456-L485
func (r *Raft) pipelineDecode(s *followerReplication, p AppendPipeline, stopCh, finishCh chan struct{}) { defer close(finishCh) respCh := p.Consumer() for { select { case ready := <-respCh: req, resp := ready.Request(), ready.Response() appendStats(string(s.peer.ID), ready.Start(), float32(len(req.Entries))) // Check for a newer term, stop running if resp.Term > req.Term { r.handleStaleTerm(s) return } // Update the last contact s.setLastContact() // Abort pipeline if not successful if !resp.Success { return } // Update our replication state updateLastAppended(s, req) case <-stopCh: return } } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1547-L1551
func (v RemoveAttributeParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom16(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/inspector/easyjson.go#L258-L262
func (v *EnableParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoInspector3(&r, v) return r.Error() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/fetcher/client.go#L135-L174
func (client *Client) FetchIssues(latest time.Time, c chan *github.Issue) { opt := &github.IssueListByRepoOptions{Since: latest, Sort: "updated", State: "all", Direction: "asc"} githubClient, err := client.getGitHubClient() if err != nil { close(c) glog.Error(err) return } count := 0 for { client.limitsCheckAndWait() issues, resp, err := githubClient.Issues.ListByRepo( context.Background(), client.Org, client.Project, opt, ) if err != nil { close(c) glog.Error(err) return } for _, issue := range issues { c <- issue count++ } if resp.NextPage == 0 { break } opt.ListOptions.Page = resp.NextPage } glog.Infof("Fetched %d issues updated issue since %v.", count, latest) close(c) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L915-L917
func (p *SetRequestInterceptionParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetRequestInterception, p, nil) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/easyjson.go#L653-L657
func (v SetIgnoreInputEventsParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoInput4(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/hyperbahn/client.go#L65-L75
func (f *FailStrategy) UnmarshalText(text []byte) error { switch strategy := string(text); strategy { case "", "fatal": *f = FailStrategyFatal case "ignore": *f = FailStrategyIgnore default: return fmt.Errorf("not a valid fail strategy: %q", strategy) } return nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/tracing_keys.go#L78-L81
func (c tracingHeadersCarrier) Set(key, val string) { prefixedKey := tracingKeyEncoding.mapAndCache(key) c[prefixedKey] = val }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/cache_stats.go#L24-L36
func RegisterCacheStats(cacheName string, groupCacheStats *groupcache.Stats) { c := &cacheStats{ cacheName: cacheName, descriptions: make(map[string]*prometheus.Desc), stats: groupCacheStats, } if err := prometheus.Register(c); err != nil { // metrics may be redundantly registered; ignore these errors if _, ok := err.(prometheus.AlreadyRegisteredError); !ok { logrus.Infof("error registering prometheus metric: %v", err) } } }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/ledger_entry.go#L6-L43
func (entry *LedgerEntry) LedgerKey() LedgerKey { var body interface{} switch entry.Data.Type { case LedgerEntryTypeAccount: account := entry.Data.MustAccount() body = LedgerKeyAccount{ AccountId: account.AccountId, } case LedgerEntryTypeData: data := entry.Data.MustData() body = LedgerKeyData{ AccountId: data.AccountId, DataName: data.DataName, } case LedgerEntryTypeOffer: offer := entry.Data.MustOffer() body = LedgerKeyOffer{ SellerId: offer.SellerId, OfferId: offer.OfferId, } case LedgerEntryTypeTrustline: tline := entry.Data.MustTrustLine() body = LedgerKeyTrustLine{ AccountId: tline.AccountId, Asset: tline.Asset, } default: panic(fmt.Errorf("Unknown entry type: %v", entry.Data.Type)) } ret, err := NewLedgerKey(entry.Data.Type, body) if err != nil { panic(err) } return ret }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/streambuffer/streambuffer.go#L88-L102
func (s *Stream) SendMsg(msg interface{}) { select { case s.sendBuffer <- msg: // normal flow if the channel is not blocked default: s.log.Debug("streambuffer: dropping message before send") atomic.AddUint64(&s.dropped, 1) <-s.sendBuffer // drop oldest and try again (if conn temporarily unavailable) select { case s.sendBuffer <- msg: default: // drop newest (too many cuncurrent SendMsg) s.log.Debug("streambuffer: dropping message before send") atomic.AddUint64(&s.dropped, 1) } } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3292-L3296
func (v GetOuterHTMLParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom37(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/datacenter.go#L98-L112
func (c *Client) WaitTillProvisioned(path string) error { waitCount := 300 for i := 0; i < waitCount; i++ { request, err := c.GetRequestStatus(path) if err != nil { return err } if request.Metadata.Status == "DONE" { return nil } time.Sleep(1 * time.Second) i++ } return fmt.Errorf("timeout expired while waiting for request to complete") }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L634-L643
func (p *SetRuleSelectorParams) Do(ctx context.Context) (selectorList *SelectorList, err error) { // execute var res SetRuleSelectorReturns err = cdp.Execute(ctx, CommandSetRuleSelector, p, &res) if err != nil { return nil, err } return res.SelectorList, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/connect.go#L64-L99
func ConnectIfVolumeIsRemote(cluster *db.Cluster, poolID int64, volumeName string, volumeType int, cert *shared.CertInfo) (lxd.ContainerServer, error) { var addresses []string // Node addresses err := cluster.Transaction(func(tx *db.ClusterTx) error { var err error addresses, err = tx.StorageVolumeNodeAddresses(poolID, "default", volumeName, volumeType) return err }) if err != nil { return nil, err } if len(addresses) > 1 { var driver string err := cluster.Transaction(func(tx *db.ClusterTx) error { var err error driver, err = tx.StoragePoolDriver(poolID) return err }) if err != nil { return nil, err } if driver == "ceph" { return nil, nil } return nil, fmt.Errorf("more than one node has a volume named %s", volumeName) } address := addresses[0] if address == "" { return nil, nil } return Connect(address, cert, false) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2http/client.go#L556-L578
func writeKeyEvent(w http.ResponseWriter, resp etcdserver.Response, noValueOnSuccess bool) error { ev := resp.Event if ev == nil { return errors.New("cannot write empty Event") } w.Header().Set("Content-Type", "application/json") w.Header().Set("X-Etcd-Index", fmt.Sprint(ev.EtcdIndex)) w.Header().Set("X-Raft-Index", fmt.Sprint(resp.Index)) w.Header().Set("X-Raft-Term", fmt.Sprint(resp.Term)) if ev.IsCreated() { w.WriteHeader(http.StatusCreated) } ev = trimEventPrefix(ev, etcdserver.StoreKeysPrefix) if noValueOnSuccess && (ev.Action == v2store.Set || ev.Action == v2store.CompareAndSwap || ev.Action == v2store.Create || ev.Action == v2store.Update) { ev.Node = nil ev.PrevNode = nil } return json.NewEncoder(w).Encode(ev) }
https://github.com/pandemicsyn/oort/blob/fca1d3baddc1d944387cc8bbe8b21f911ec9091b/oort/oort.go#L94-L98
func (o *Server) Ring() ring.Ring { o.RLock() defer o.RUnlock() return o.ring }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/client.go#L87-L89
func NewClient() *PactClient { return newClient(&client.MockService{}, &client.VerificationService{}, &client.MessageService{}, &client.PublishService{}) }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L63-L66
func isErrFieldMismatch(err error) bool { _, ok := err.(*datastore.ErrFieldMismatch) return ok }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L344-L349
func (p *Page) SwitchToParentFrame() error { if err := p.session.FrameParent(); err != nil { return fmt.Errorf("failed to switch to parent frame: %s", err) } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/applicationcache.go#L130-L139
func (p *GetManifestForFrameParams) Do(ctx context.Context) (manifestURL string, err error) { // execute var res GetManifestForFrameReturns err = cdp.Execute(ctx, CommandGetManifestForFrame, p, &res) if err != nil { return "", err } return res.ManifestURL, nil }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/local_peer.go#L36-L44
func (peer *localPeer) getConnections() connectionSet { connections := make(connectionSet) peer.RLock() defer peer.RUnlock() for _, conn := range peer.connections { connections[conn] = struct{}{} } return connections }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L870-L872
func Warnf(format string, val ...interface{}) error { return glg.out(WARN, format, val...) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/database/easyjson.go#L170-L174
func (v GetDatabaseTableNamesParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDatabase1(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/jobs.go#L301-L303
func (ps Postsubmit) CouldRun(baseRef string) bool { return ps.Brancher.ShouldRun(baseRef) }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/state.go#L98-L116
func (st *state) mergeDelta(set map[mesh.PeerName]int) (delta mesh.GossipData) { st.mtx.Lock() defer st.mtx.Unlock() for peer, v := range set { if v <= st.set[peer] { delete(set, peer) // requirement: it's not part of a delta continue } st.set[peer] = v } if len(set) <= 0 { return nil // per OnGossip requirements } return &state{ set: set, // all remaining elements were novel to us } }
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/server.go#L45-L49
func (mux *ServerMux) err(err error) { if mux.ErrorHandle != nil { mux.ErrorHandle(err) } }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L199-L229
func goTrackbarCallback(barName_, winName_ *C.char, pos C.int) { runtime.LockOSThread() defer runtime.UnlockOSThread() winName := C.GoString(winName_) barName := C.GoString(barName_) win, ok := allWindows[winName] if !ok { return } trackbarHandle, ok := win.trackbarHandle[barName] if !ok { return } if trackbarHandle == nil { return } if fa, ok := trackbarHandle.(func(pos int)); ok { fa(int(pos)) } else if fb, ok := trackbarHandle.(func(pos int, param ...interface{})); ok { param := win.trackbarParam[barName] if param != nil { fb(int(pos), param...) } else { fb(int(pos)) } } }
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/format.go#L199-L258
func NewStringFormatter(format string) (Formatter, error) { var fmter = &stringFormatter{} // Find the boundaries of all %{vars} matches := formatRe.FindAllStringSubmatchIndex(format, -1) if matches == nil { return nil, errors.New("logger: invalid log format: " + format) } // Collect all variables and static text for the format prev := 0 for _, m := range matches { start, end := m[0], m[1] if start > prev { fmter.add(fmtVerbStatic, format[prev:start]) } name := format[m[2]:m[3]] verb := getFmtVerbByName(name) if verb == fmtVerbUnknown { return nil, errors.New("logger: unknown variable: " + name) } // Handle layout customizations or use the default. If this is not for the // time, color formatting or callpath, we need to prefix with %. layout := defaultVerbsLayout[verb] if m[4] != -1 { layout = format[m[4]:m[5]] } if verb != fmtVerbTime && verb != fmtVerbLevelColor && verb != fmtVerbCallpath { layout = "%" + layout } fmter.add(verb, layout) prev = end } end := format[prev:] if end != "" { fmter.add(fmtVerbStatic, end) } // Make a test run to make sure we can format it correctly. t, err := time.Parse(time.RFC3339, "2010-02-04T21:00:57-08:00") if err != nil { panic(err) } testFmt := "hello %s" r := &Record{ ID: 12345, Time: t, Module: "logger", Args: []interface{}{"go"}, fmt: &testFmt, } if err := fmter.Format(0, r, &bytes.Buffer{}); err != nil { return nil, err } return fmter, nil }
https://github.com/stvp/pager/blob/17442a04891b757880b72d926848df3e3af06c15/pager.go#L49-L51
func TriggerWithDetails(description string, details map[string]interface{}) (incidentKey string, err error) { return trigger(description, "", details) }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/dwarf.go#L217-L232
func dwarfSize(dt dwarf.Type, ptrSize int64) int64 { s := dt.Size() if s >= 0 { return s } switch x := dt.(type) { case *dwarf.FuncType: return ptrSize // Fix for issue 21097. case *dwarf.ArrayType: return x.Count * dwarfSize(x.Type, ptrSize) case *dwarf.TypedefType: return dwarfSize(x.Type, ptrSize) default: panic(fmt.Sprintf("unhandled: %s, %T", x, x)) } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/config.go#L151-L159
func (c *Configuration) MDYAMLEnabled(org, repo string) bool { full := fmt.Sprintf("%s/%s", org, repo) for _, elem := range c.Owners.MDYAMLRepos { if elem == org || elem == full { return true } } return false }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/figtree.go#L321-L324
func Merge(dst, src interface{}) { m := NewMerger() m.mergeStructs(reflect.ValueOf(dst), reflect.ValueOf(src)) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2auth/auth.go#L197-L205
func (s *store) CreateOrUpdateUser(user User) (out User, created bool, err error) { _, err = s.getUser(user.User, true) if err == nil { out, err = s.UpdateUser(user) return out, false, err } u, err := s.CreateUser(user) return u, true, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/types.go#L53-L63
func (t *RequestStage) UnmarshalEasyJSON(in *jlexer.Lexer) { switch RequestStage(in.String()) { case RequestStageRequest: *t = RequestStageRequest case RequestStageResponse: *t = RequestStageResponse default: in.AddError(errors.New("unknown RequestStage value")) } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/mapping.go#L43-L55
func (m *Mapping) ContainsFields(fields []*Field) bool { matches := map[*Field]bool{} for _, field := range m.Fields { for _, other := range fields { if field.Name == other.Name && field.Type.Name == other.Type.Name { matches[field] = true } } } return len(matches) == len(fields) }
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L606-L618
func (v Value) Text() string { x, ok := v.data.(string) if !ok { return "" } if isPDFDocEncoded(x) { return pdfDocDecode(x) } if isUTF16(x) { return utf16Decode(x[2:]) } return x }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L1455-L1463
func (r *Raft) persistVote(term uint64, candidate []byte) error { if err := r.stable.SetUint64(keyLastVoteTerm, term); err != nil { return err } if err := r.stable.Set(keyLastVoteCand, candidate); err != nil { return err } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2821-L2825
func (v *PauseOnAsyncCallParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger29(&r, v) return r.Error() }
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/dependency/sqltypes/plan_value.go#L212-L259
func ResolveRows(pvs []PlanValue, bindVars map[string]*querypb.BindVariable) ([][]Value, error) { count, err := rowCount(pvs, bindVars) if err != nil { return nil, err } // Allocate the rows. rows := make([][]Value, count) for i := range rows { rows[i] = make([]Value, len(pvs)) } // Using j becasue we're resolving by columns. for j, pv := range pvs { switch { case pv.Key != "": bv, err := pv.lookupValue(bindVars) if err != nil { return nil, err } for i := range rows { rows[i][j] = MakeTrusted(bv.Type, bv.Value) } case !pv.Value.IsNull(): for i := range rows { rows[i][j] = pv.Value } case pv.ListKey != "": bv, err := pv.lookupList(bindVars) if err != nil { // This code is unreachable because pvRowCount already checks this. return nil, err } for i := range rows { rows[i][j] = MakeTrusted(bv.Values[i].Type, bv.Values[i].Value) } case pv.Values != nil: for i := range rows { rows[i][j], err = pv.Values[i].ResolveValue(bindVars) if err != nil { return nil, err } } // default case is a NULL value, which the row values are already initialized to. } } return rows, nil }
https://github.com/apparentlymart/go-rundeck-api/blob/2c962acae81080a937c350a5bea054c239f27a81/rundeck/project.go#L52-L56
func (c *Client) GetProject(name string) (*Project, error) { p := &Project{} err := c.get([]string{"project", name}, nil, p) return p, err }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3989-L3998
func (u OperationResultTr) GetCreateAccountResult() (result CreateAccountResult, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "CreateAccountResult" { result = *u.CreateAccountResult ok = true } return }
https://github.com/wawandco/fako/blob/c36a0bc97398c9100daa83ebef1c4e7af32c7654/fakers.go#L93-L111
func Fuzz(e interface{}) { ty := reflect.TypeOf(e) if ty.Kind() == reflect.Ptr { ty = ty.Elem() } if ty.Kind() == reflect.Struct { value := reflect.ValueOf(e).Elem() for i := 0; i < ty.NumField(); i++ { field := value.Field(i) if field.CanSet() { field.Set(fuzzValueFor(field.Kind())) } } } }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6345-L6375
func (u StellarMessage) ArmForSwitch(sw int32) (string, bool) { switch MessageType(sw) { case MessageTypeErrorMsg: return "Error", true case MessageTypeHello: return "Hello", true case MessageTypeAuth: return "Auth", true case MessageTypeDontHave: return "DontHave", true case MessageTypeGetPeers: return "", true case MessageTypePeers: return "Peers", true case MessageTypeGetTxSet: return "TxSetHash", true case MessageTypeTxSet: return "TxSet", true case MessageTypeTransaction: return "Transaction", true case MessageTypeGetScpQuorumset: return "QSetHash", true case MessageTypeScpQuorumset: return "QSet", true case MessageTypeScpMessage: return "Envelope", true case MessageTypeGetScpState: return "GetScpLedgerSeq", true } return "-", false }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/easyjson.go#L545-L549
func (v ResolveAnimationParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoAnimation5(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/provisioner.go#L486-L488
func isTerminating(pod apiv1.Pod) bool { return pod.Spec.ActiveDeadlineSeconds != nil && *pod.Spec.ActiveDeadlineSeconds >= int64(0) || pod.DeletionTimestamp != nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L388-L491
func (c *ClusterTx) ContainerNodeMove(oldName, newName, newNode string) error { // First check that the container to be moved is backed by a ceph // volume. poolName, err := c.ContainerPool("default", oldName) if err != nil { return errors.Wrap(err, "failed to get container's storage pool name") } poolID, err := c.StoragePoolID(poolName) if err != nil { return errors.Wrap(err, "failed to get container's storage pool ID") } poolDriver, err := c.StoragePoolDriver(poolID) if err != nil { return errors.Wrap(err, "failed to get container's storage pool driver") } if poolDriver != "ceph" { return fmt.Errorf("container's storage pool is not of type ceph") } // Update the name of the container and of its snapshots, and the node // ID they are associated with. containerID, err := c.ContainerID("default", oldName) if err != nil { return errors.Wrap(err, "failed to get container's ID") } snapshots, err := c.SnapshotIDsAndNames(oldName) if err != nil { return errors.Wrap(err, "failed to get container's snapshots") } node, err := c.NodeByName(newNode) if err != nil { return errors.Wrap(err, "failed to get new node's info") } stmt := "UPDATE containers SET node_id=?, name=? WHERE id=?" result, err := c.tx.Exec(stmt, node.ID, newName, containerID) if err != nil { return errors.Wrap(err, "failed to update container's name and node ID") } n, err := result.RowsAffected() if err != nil { return errors.Wrap(err, "failed to get rows affected by container update") } if n != 1 { return fmt.Errorf("unexpected number of updated rows in containers table: %d", n) } for snapshotID, snapshotName := range snapshots { newSnapshotName := newName + shared.SnapshotDelimiter + snapshotName stmt := "UPDATE containers SET node_id=?, name=? WHERE id=?" result, err := c.tx.Exec(stmt, node.ID, newSnapshotName, snapshotID) if err != nil { return errors.Wrap(err, "failed to update snapshot's name and node ID") } n, err := result.RowsAffected() if err != nil { return errors.Wrap(err, "failed to get rows affected by snapshot update") } if n != 1 { return fmt.Errorf("unexpected number of updated snapshot rows: %d", n) } } // No need to update storage_volumes if the name is identical if newName == oldName { return nil } // Update the container's and snapshots' storage volume name (since this is ceph, // there's a clone of the volume for each node). count, err := c.NodesCount() if err != nil { return errors.Wrap(err, "failed to get node's count") } stmt = "UPDATE storage_volumes SET name=? WHERE name=? AND storage_pool_id=? AND type=?" result, err = c.tx.Exec(stmt, newName, oldName, poolID, StoragePoolVolumeTypeContainer) if err != nil { return errors.Wrap(err, "failed to update container's volume name") } n, err = result.RowsAffected() if err != nil { return errors.Wrap(err, "failed to get rows affected by container volume update") } if n != int64(count) { return fmt.Errorf("unexpected number of updated rows in volumes table: %d", n) } for _, snapshotName := range snapshots { oldSnapshotName := oldName + shared.SnapshotDelimiter + snapshotName newSnapshotName := newName + shared.SnapshotDelimiter + snapshotName stmt := "UPDATE storage_volumes SET name=? WHERE name=? AND storage_pool_id=? AND type=?" result, err := c.tx.Exec( stmt, newSnapshotName, oldSnapshotName, poolID, StoragePoolVolumeTypeContainer) if err != nil { return errors.Wrap(err, "failed to update snapshot volume") } n, err = result.RowsAffected() if err != nil { return errors.Wrap(err, "failed to get rows affected by snapshot volume update") } if n != int64(count) { return fmt.Errorf("unexpected number of updated snapshots in volumes table: %d", n) } } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L493-L502
func (p *SearchInContentParams) Do(ctx context.Context) (result []*SearchMatch, err error) { // execute var res SearchInContentReturns err = cdp.Execute(ctx, CommandSearchInContent, p, &res) if err != nil { return nil, err } return res.Result, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/config.go#L143-L152
func (ownersDirBlacklist OwnersDirBlacklist) DirBlacklist(org, repo string) (blacklist []string) { blacklist = append(blacklist, ownersDirBlacklist.Default...) if bl, ok := ownersDirBlacklist.Repos[org]; ok { blacklist = append(blacklist, bl...) } if bl, ok := ownersDirBlacklist.Repos[org+"/"+repo]; ok { blacklist = append(blacklist, bl...) } return }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/examples/keyvalue/gen-go/keyvalue/keyvalue.go#L128-L133
func (p *KeyValueClient) Set(key string, value string) (err error) { if err = p.sendSet(key, value); err != nil { return } return p.recvSet() }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/skiplist.go#L129-L132
func (s *Skiplist) FreeNode(n *Node, sts *Stats) { s.freeNode(n) sts.AddInt64(&sts.nodeFrees, 1) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L605-L623
func (c *Client) BuildFromSpec(spec *prowapi.ProwJobSpec, buildID, prowJobID string) error { if c.dryRun { return nil } env, err := downwardapi.EnvForSpec(downwardapi.NewJobSpec(*spec, buildID, prowJobID)) if err != nil { return err } params := url.Values{} for key, value := range env { params.Set(key, value) } if err := c.EnsureBuildableJob(spec); err != nil { return fmt.Errorf("Job %v cannot be build: %v", spec.Job, err) } return c.LaunchBuild(spec, params) }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L153-L157
func (eC2Manager *EC2Manager) WorkerTypeErrors(workerType string) (*Errors, error) { cd := tcclient.Client(*eC2Manager) responseObject, _, err := (&cd).APICall(nil, "GET", "/worker-types/"+url.QueryEscape(workerType)+"/errors", new(Errors), nil) return responseObject.(*Errors), err }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/driver.go#L2459-L2469
func provenantOnInput(provenance []*pfs.CommitProvenance) bool { provenanceCount := len(provenance) for _, p := range provenance { // in particular, we want to exclude provenance on the spec repo (used e.g. for spouts) if p.Commit.Repo.Name == ppsconsts.SpecRepo { provenanceCount-- break } } return provenanceCount > 0 }
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/seekret.go#L95-L119
func (s *Seekret) LoadRulesFromDir(dir string, defaulEnabled bool) error { fi, err := os.Stat(dir) if err != nil { return err } if !fi.IsDir() { err := fmt.Errorf("%s is not a directory", dir) return err } fileList, err := filepath.Glob(dir + "/*") if err != nil { return err } for _, file := range fileList { if strings.HasSuffix(file, ".rule") { err := s.LoadRulesFromFile(file, defaulEnabled) if err != nil { return err } } } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pluginhelp/pluginhelp.go#L71-L73
func (pluginHelp *PluginHelp) AddCommand(command Command) { pluginHelp.Commands = append(pluginHelp.Commands, command) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1100-L1102
func (p *RequestChildNodesParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandRequestChildNodes, p, nil) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/author_filter_wrapper.go#L63-L68
func (a *AuthorFilterPluginWrapper) ReceiveIssueEvent(event sql.IssueEvent) []Point { if event.Actor != nil && a.match(*event.Actor) { return nil } return a.plugin.ReceiveIssueEvent(event) }
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/spanish/common.go#L10-L36
func removeAccuteAccents(word *snowballword.SnowballWord) (didReplacement bool) { for i := 0; i < len(word.RS); i++ { switch word.RS[i] { case 225: // á -> a word.RS[i] = 97 didReplacement = true case 233: // é -> e word.RS[i] = 101 didReplacement = true case 237: // í -> i word.RS[i] = 105 didReplacement = true case 243: // ó -> o word.RS[i] = 111 didReplacement = true case 250: // ú -> u word.RS[i] = 117 didReplacement = true } } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L889-L898
func (p *SetScriptSourceParams) Do(ctx context.Context) (callFrames []*CallFrame, stackChanged bool, asyncStackTrace *runtime.StackTrace, asyncStackTraceID *runtime.StackTraceID, exceptionDetails *runtime.ExceptionDetails, err error) { // execute var res SetScriptSourceReturns err = cdp.Execute(ctx, CommandSetScriptSource, p, &res) if err != nil { return nil, false, nil, nil, nil, err } return res.CallFrames, res.StackChanged, res.AsyncStackTrace, res.AsyncStackTraceID, res.ExceptionDetails, nil }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L32-L35
func NewBasicAuthenticator(username, password string, accountID int) Authenticator { builder := basicLoginRequestBuilder{username: username, password: password, accountID: accountID} return newCookieSigner(&builder, accountID) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pluginhelp/hook/hook.go#L69-L76
func NewHelpAgent(pa pluginAgent, ghc githubClient) *HelpAgent { l := logrus.WithField("client", "plugin-help") return &HelpAgent{ log: l, pa: pa, oa: newOrgAgent(l, ghc, newRepoDetectionLimit), } }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L216-L229
func Substr(s string, index int, n int) string { L := len(s) if index < 0 || index >= L || s == "" { return "" } end := index + n if end >= L { end = L } if end <= index { return "" } return s[index:end] }
https://github.com/felixge/httpsnoop/blob/eadd4fad6aac69ae62379194fe0219f3dbc80fd3/wrap_generated_lt_1.8.go#L61-L182
func Wrap(w http.ResponseWriter, hooks Hooks) http.ResponseWriter { rw := &rw{w: w, h: hooks} _, i0 := w.(http.Flusher) _, i1 := w.(http.CloseNotifier) _, i2 := w.(http.Hijacker) _, i3 := w.(io.ReaderFrom) switch { // combination 1/16 case !i0 && !i1 && !i2 && !i3: return struct { http.ResponseWriter }{rw} // combination 2/16 case !i0 && !i1 && !i2 && i3: return struct { http.ResponseWriter io.ReaderFrom }{rw, rw} // combination 3/16 case !i0 && !i1 && i2 && !i3: return struct { http.ResponseWriter http.Hijacker }{rw, rw} // combination 4/16 case !i0 && !i1 && i2 && i3: return struct { http.ResponseWriter http.Hijacker io.ReaderFrom }{rw, rw, rw} // combination 5/16 case !i0 && i1 && !i2 && !i3: return struct { http.ResponseWriter http.CloseNotifier }{rw, rw} // combination 6/16 case !i0 && i1 && !i2 && i3: return struct { http.ResponseWriter http.CloseNotifier io.ReaderFrom }{rw, rw, rw} // combination 7/16 case !i0 && i1 && i2 && !i3: return struct { http.ResponseWriter http.CloseNotifier http.Hijacker }{rw, rw, rw} // combination 8/16 case !i0 && i1 && i2 && i3: return struct { http.ResponseWriter http.CloseNotifier http.Hijacker io.ReaderFrom }{rw, rw, rw, rw} // combination 9/16 case i0 && !i1 && !i2 && !i3: return struct { http.ResponseWriter http.Flusher }{rw, rw} // combination 10/16 case i0 && !i1 && !i2 && i3: return struct { http.ResponseWriter http.Flusher io.ReaderFrom }{rw, rw, rw} // combination 11/16 case i0 && !i1 && i2 && !i3: return struct { http.ResponseWriter http.Flusher http.Hijacker }{rw, rw, rw} // combination 12/16 case i0 && !i1 && i2 && i3: return struct { http.ResponseWriter http.Flusher http.Hijacker io.ReaderFrom }{rw, rw, rw, rw} // combination 13/16 case i0 && i1 && !i2 && !i3: return struct { http.ResponseWriter http.Flusher http.CloseNotifier }{rw, rw, rw} // combination 14/16 case i0 && i1 && !i2 && i3: return struct { http.ResponseWriter http.Flusher http.CloseNotifier io.ReaderFrom }{rw, rw, rw, rw} // combination 15/16 case i0 && i1 && i2 && !i3: return struct { http.ResponseWriter http.Flusher http.CloseNotifier http.Hijacker }{rw, rw, rw, rw} // combination 16/16 case i0 && i1 && i2 && i3: return struct { http.ResponseWriter http.Flusher http.CloseNotifier http.Hijacker io.ReaderFrom }{rw, rw, rw, rw, rw} } panic("unreachable") }