_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1266-L1269
func (p SetAttributesAsTextParams) WithName(name string) *SetAttributesAsTextParams { p.Name = name return &p }
https://github.com/ianschenck/envflag/blob/9111d830d133f952887a936367fb0211c3134f0d/envflag.go#L137-L139
func Float64Var(p *float64, name string, value float64, usage string) { EnvironmentFlags.Float64Var(p, name, value, usage) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/config.go#L607-L616
func (c *Configuration) TriggerFor(org, repo string) Trigger { for _, tr := range c.Triggers { for _, r := range tr.Repos { if r == org || r == fmt.Sprintf("%s/%s", org, repo) { return tr } } } return Trigger{} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/easyjson.go#L224-L228
func (v SetEventListenerBreakpointParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomdebugger2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/dag/dag.go#L46-L55
func (d *DAG) Leaves() []string { var result []string for id, isLeaf := range d.leaves { // isLeaf might be false, explicit mark nodes as non leaves if isLeaf { result = append(result, id) } } return result }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/relay.go#L104-L108
func (r *relayItems) Add(id uint32, item relayItem) { r.Lock() r.items[id] = item r.Unlock() }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/git/git.go#L68-L84
func (r *Repository) RemoteURL(name string) (string, error) { config, err := os.Open(filepath.Join(r.path, "config")) if err != nil { return "", err } defer config.Close() line := fmt.Sprintf("[remote %q]", name) scanner := bufio.NewScanner(config) scanner.Split(bufio.ScanLines) for scanner.Scan() { if scanner.Text() == line { scanner.Scan() return strings.Split(scanner.Text(), " = ")[1], nil } } return "", errRemoteNotFound{name} }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L1060-L1073
func (seq *Sequence) Release() error { seq.Lock() defer seq.Unlock() err := seq.db.Update(func(txn *Txn) error { var buf [8]byte binary.BigEndian.PutUint64(buf[:], seq.next) return txn.Set(seq.key, buf[:]) }) if err != nil { return err } seq.leased = seq.next return nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L442-L453
func syncDir(dir string) error { f, err := openDir(dir) if err != nil { return errors.Wrapf(err, "While opening directory: %s.", dir) } err = f.Sync() closeErr := f.Close() if err != nil { return errors.Wrapf(err, "While syncing directory: %s.", dir) } return errors.Wrapf(closeErr, "While closing directory: %s.", dir) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/codegen_client.go#L1652-L1654
func (r *Server) Locator(api *API) *ServerLocator { return api.ServerLocator(r.Href) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/connectivity.go#L36-L58
func (cse *connectivityStateEvaluator) recordTransition(oldState, newState connectivity.State) connectivity.State { // Update counters. for idx, state := range []connectivity.State{oldState, newState} { updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new. switch state { case connectivity.Ready: cse.numReady += updateVal case connectivity.Connecting: cse.numConnecting += updateVal case connectivity.TransientFailure: cse.numTransientFailure += updateVal } } // Evaluate. if cse.numReady > 0 { return connectivity.Ready } if cse.numConnecting > 0 { return connectivity.Connecting } return connectivity.TransientFailure }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/route.go#L15-L20
func (a *App) Routes() RouteList { if a.root != nil { return a.root.routes } return a.routes }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L666-L675
func (p *GetRelayoutBoundaryParams) Do(ctx context.Context) (nodeID cdp.NodeID, err error) { // execute var res GetRelayoutBoundaryReturns err = cdp.Execute(ctx, CommandGetRelayoutBoundary, p, &res) if err != nil { return 0, err } return res.NodeID, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L1322-L1324
func (p *ClearCompilationCacheParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandClearCompilationCache, nil, nil) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/label/label.go#L99-L116
func getLabelsFromGenericMatches(matches [][]string, additionalLabels []string) []string { if len(additionalLabels) == 0 { return nil } var labels []string for _, match := range matches { parts := strings.Split(match[0], " ") if ((parts[0] != "/label") && (parts[0] != "/remove-label")) || len(parts) != 2 { continue } for _, l := range additionalLabels { if l == parts[1] { labels = append(labels, parts[1]) } } } return labels }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L301-L321
func (g *Gateway) Shutdown() error { logger.Debugf("Stop database gateway") if g.raft != nil { err := g.raft.Shutdown() if err != nil { return errors.Wrap(err, "Failed to shutdown raft") } } if g.server != nil { g.Sync() g.server.Close() // Unset the memory dial, since Shutdown() is also called for // switching between in-memory and network mode. g.memoryDial = nil } return nil }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip.go#L78-L96
func newGossipSender( makeMsg func(msg []byte) protocolMsg, makeBroadcastMsg func(srcName PeerName, msg []byte) protocolMsg, sender protocolSender, stop <-chan struct{}, ) *gossipSender { more := make(chan struct{}, 1) flush := make(chan chan<- bool) s := &gossipSender{ makeMsg: makeMsg, makeBroadcastMsg: makeBroadcastMsg, sender: sender, broadcasts: make(map[PeerName]GossipData), more: more, flush: flush, } go s.run(stop, more, flush) return s }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L719-L721
func SubScalarRev(value Scalar, src, dst *IplImage) { SubScalarWithMaskRev(value, src, dst, nil) }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L521-L523
func (b *Base) Fatalf(msg string, a ...interface{}) error { return b.Log(LevelFatal, nil, msg, a...) }
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/proc_master.go#L336-L343
func (mp *master) forkLoop() error { //loop, restart command for { if err := mp.fork(); err != nil { return err } } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/operations.go#L319-L346
func (c *ClusterTx) operations(where string, args ...interface{}) ([]Operation, error) { operations := []Operation{} dest := func(i int) []interface{} { operations = append(operations, Operation{}) return []interface{}{ &operations[i].ID, &operations[i].UUID, &operations[i].NodeAddress, &operations[i].Type, } } sql := ` SELECT operations.id, uuid, nodes.address, type FROM operations JOIN nodes ON nodes.id = node_id ` if where != "" { sql += fmt.Sprintf("WHERE %s ", where) } sql += "ORDER BY operations.id" stmt, err := c.tx.Prepare(sql) if err != nil { return nil, err } defer stmt.Close() err = query.SelectObjects(stmt, dest, args...) if err != nil { return nil, errors.Wrap(err, "Failed to fetch operations") } return operations, nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/iterator.go#L93-L112
func (item *Item) Value(fn func(val []byte) error) error { item.wg.Wait() if item.status == prefetched { if item.err == nil && fn != nil { if err := fn(item.val); err != nil { return err } } return item.err } buf, cb, err := item.yieldItemValue() defer runCallback(cb) if err != nil { return err } if fn != nil { return fn(buf) } return nil }
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/outgoing.go#L120-L146
func (op *outgoingMessageBase) getBaseQueryString() querystring { toReturn := map[string]string{} if op.Recipient.isChannel() { //Channel. toReturn["chat_id"] = fmt.Sprint(*op.Recipient.ChannelID) } else { toReturn["chat_id"] = fmt.Sprint(*op.Recipient.ChatID) } if op.replyToMessageIDSet { toReturn["reply_to_message_id"] = fmt.Sprint(op.ReplyToMessageID) } if op.replyMarkupSet { b, err := json.Marshal(op.ReplyMarkup) if err != nil { panic(err) } toReturn["reply_markup"] = string(b) } if op.DisableNotification { toReturn["disable_notification"] = fmt.Sprint(op.DisableNotification) } return querystring(toReturn) }
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/cors/cors.go#L129-L137
func (o *Options) IsOriginAllowed(origin string) (allowed bool) { for _, pattern := range o.AllowOrigins { allowed, _ = regexp.MatchString(pattern, origin) if allowed { return } } return }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L210-L278
func (d *Daemon) Authenticate(r *http.Request) (bool, string, string, error) { // Allow internal cluster traffic if r.TLS != nil { cert, _ := x509.ParseCertificate(d.endpoints.NetworkCert().KeyPair().Certificate[0]) clusterCerts := map[string]x509.Certificate{"0": *cert} for i := range r.TLS.PeerCertificates { trusted, _ := util.CheckTrustState(*r.TLS.PeerCertificates[i], clusterCerts) if trusted { return true, "", "cluster", nil } } } // Local unix socket queries if r.RemoteAddr == "@" { return true, "", "unix", nil } // Devlxd unix socket credentials on main API if r.RemoteAddr == "@devlxd" { return false, "", "", fmt.Errorf("Main API query can't come from /dev/lxd socket") } // Cluster notification with wrong certificate if isClusterNotification(r) { return false, "", "", fmt.Errorf("Cluster notification isn't using cluster certificate") } // Bad query, no TLS found if r.TLS == nil { return false, "", "", fmt.Errorf("Bad/missing TLS on network query") } if d.externalAuth != nil && r.Header.Get(httpbakery.BakeryProtocolHeader) != "" { // Validate external authentication ctx := httpbakery.ContextWithRequest(context.TODO(), r) authChecker := d.externalAuth.bakery.Checker.Auth(httpbakery.RequestMacaroons(r)...) ops := []bakery.Op{{ Entity: r.URL.Path, Action: r.Method, }} info, err := authChecker.Allow(ctx, ops...) if err != nil { // Bad macaroon return false, "", "", err } if info != nil && info.Identity != nil { // Valid identity macaroon found return true, info.Identity.Id(), "candid", nil } // Valid macaroon with no identity information return true, "", "candid", nil } // Validate normal TLS access for i := range r.TLS.PeerCertificates { trusted, username := util.CheckTrustState(*r.TLS.PeerCertificates[i], d.clientCerts) if trusted { return true, username, "tls", nil } } // Reject unauthorized return false, "", "", nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L370-L374
func (v TakeTypeProfileParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoProfiler3(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/commands.go#L26-L40
func (a *API) RunCommand(cmd string) (*http.Response, error) { parsed, err := a.ParseCommand(cmd, "/api", commandValues) if err != nil { return nil, err } href := parsed.URI if !strings.HasPrefix(href, "/api") { href = path.Join("/api", href) } req, err := a.BuildHTTPRequest("GET", href, "1.6", parsed.QueryParams, nil) if err != nil { return nil, err } return a.PerformRequest(req) }
https://github.com/justinian/dice/blob/6a18b51d929caddbe795e1609195dee1d1cc729e/dice.go#L38-L55
func Roll(desc string) (RollResult, string, error) { for _, rollHandler := range rollHandlers { rollHandler.Pattern().Longest() if r := rollHandler.Pattern().FindStringSubmatch(desc); r != nil { result, err := rollHandler.Roll(r) if err != nil { return nil, "", err } indexes := rollHandler.Pattern().FindStringSubmatchIndex(desc) reason := strings.Trim(desc[indexes[0]+len(r[0]):], " \t\r\n") return result, reason, nil } } return nil, "", errors.New("Bad roll format: " + desc) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L2631-L2635
func (v CoverageRange) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoProfiler26(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1485-L1489
func (v EventTargetCrashed) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget16(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_transport.go#L137-L139
func (ref dockerReference) NewImage(ctx context.Context, sys *types.SystemContext) (types.ImageCloser, error) { return newImage(ctx, sys, ref) }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_store.go#L126-L130
func (i *InmemStore) GetUint64(key []byte) (uint64, error) { i.l.RLock() defer i.l.RUnlock() return i.kvInt[string(key)], nil }
https://github.com/akutz/gotil/blob/6fa2e80bd3ac40f15788cfc3d12ebba49a0add92/gotil.go#L226-L232
func ParseAddress(addr string) (proto string, path string, err error) { m := netAddrRx.FindStringSubmatch(addr) if m == nil { return "", "", goof.WithField("address", addr, "invalid address") } return m[1], m[2], nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/token-counter/token-counter.go#L65-L75
func GetUsername(client *github.Client) (string, error) { user, _, err := client.Users.Get(context.Background(), "") if err != nil { return "", err } if user.Login == nil { return "", errors.New("Users.Get(\"\") returned empty login") } return *user.Login, nil }
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/utils/utils.go#L100-L123
func RunCommand(ctx context.Context, cmd string, args ...string) (string, error) { var c *exec.Cmd if ctx != nil { c = exec.CommandContext(ctx, cmd, args...) } else { c = exec.Command(cmd, args...) } output, err := c.Output() if err != nil { return string(output), err } // check for exec context timeout if ctx != nil { if ctx.Err() == context.DeadlineExceeded { return "", fmt.Errorf("command %s timed out", cmd) } } return string(output), nil }
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L61-L69
func AddLoader(predicate DocMatcher, load DocLoader) { prev := loaders loaders = &loader{ Match: predicate, Fn: load, Next: prev, } spec.PathLoader = loaders.Fn }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L71-L74
func (p MailBuilder) ToAddrs(to []mail.Address) MailBuilder { p.to = to return p }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/node_amd64.go#L104-L124
func (n *Node) dcasNext(level int, prevPtr, newPtr *Node, prevIsdeleted, newIsdeleted bool) bool { nodeRefAddr := uintptr(unsafe.Pointer(n)) + nodeHdrSize + nodeRefSize*uintptr(level) wordAddr := (*uint64)(unsafe.Pointer(nodeRefAddr + uintptr(7))) prevVal := uint64(uintptr(unsafe.Pointer(prevPtr)) << 8) newVal := uint64(uintptr(unsafe.Pointer(newPtr)) << 8) if newIsdeleted { newVal |= deletedFlag } swapped := atomic.CompareAndSwapUint64(wordAddr, prevVal, newVal) // This is required to make go1.5+ concurrent garbage collector happy // It makes writebarrier to mark newPtr as reachable if swapped { atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(nodeRefAddr+nodeRefFlagSize)), unsafe.Pointer(newPtr), unsafe.Pointer(newPtr)) } return swapped }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/easyjson.go#L93-L97
func (v *StorageID) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomstorage(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/backoff/backoff.go#L86-L91
func (b *ConstantBackOff) NextBackOff() time.Duration { if b.MaxElapsedTime != 0 && b.GetElapsedTime() > b.MaxElapsedTime { return Stop } return b.Interval }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1490-L1494
func GetHashTreeObject(pachClient *client.APIClient, storageRoot string, treeRef *pfs.Object) (HashTree, error) { return getHashTree(storageRoot, func(w io.Writer) error { return pachClient.GetObject(treeRef.Hash, w) }) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3737-L3741
func (v GetFlattenedDocumentReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom42(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/util.go#L119-L126
func backoff(base time.Duration, round, limit uint64) time.Duration { power := min(round, limit) for power > 2 { base *= 2 power-- } return base }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/cmpopts/struct_filter.go#L21-L28
func filterField(typ interface{}, name string, opt cmp.Option) cmp.Option { // TODO: This is currently unexported over concerns of how helper filters // can be composed together easily. // TODO: Add tests for FilterField. sf := newStructFilter(typ, name) return cmp.FilterPath(sf.filter, opt) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/easyjson.go#L460-L464
func (v *RequestCachedResponseParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCachestorage3(&r, v) return r.Error() }
https://github.com/olorin/nagiosplugin/blob/893f9702af4ea1e2dc4cd6528cbdcdb3dc7ca064/check.go#L113-L121
func (c Check) exitInfoText() string { var importantMessages []string for _, result := range c.results { if result.status == c.status { importantMessages = append(importantMessages, result.message) } } return strings.Join(importantMessages, messageSeparator) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L2208-L2212
func (v CreateBrowserContextParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget25(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/encoder.go#L99-L106
func EncodeBool(w io.Writer, b bool) (err error) { if b { err = EncodeUint8(w, 1) // same as EncodeUvarint(w, 1). } else { err = EncodeUint8(w, 0) // same as EncodeUvarint(w, 0). } return }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_operations.go#L81-L88
func (r *ProtocolLXD) GetOperationWebsocket(uuid string, secret string) (*websocket.Conn, error) { path := fmt.Sprintf("/operations/%s/websocket", url.QueryEscape(uuid)) if secret != "" { path = fmt.Sprintf("%s?secret=%s", path, url.QueryEscape(secret)) } return r.websocket(path) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L6528-L6534
func (c *containerLXC) Storage() storage { if c.storage == nil { c.initStorage() } return c.storage }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L111-L114
func (gc *GraphicContext) Clear() { width, height := gc.pdf.GetPageSize() clearRect(gc, 0, 0, width, height) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/storage.go#L100-L105
func (ms *MemoryStorage) SetHardState(st pb.HardState) error { ms.Lock() defer ms.Unlock() ms.hardState = st return nil }
https://github.com/ianschenck/envflag/blob/9111d830d133f952887a936367fb0211c3134f0d/envflag.go#L123-L125
func StringVar(p *string, name string, value string, usage string) { EnvironmentFlags.StringVar(p, name, value, usage) }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/recorder.go#L55-L65
func (w *recorderResponseWriter) WriteJson(v interface{}) error { b, err := w.EncodeJson(v) if err != nil { return err } _, err = w.Write(b) if err != nil { return err } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L623-L632
func (p *NavigateParams) Do(ctx context.Context) (frameID cdp.FrameID, loaderID cdp.LoaderID, errorText string, err error) { // execute var res NavigateReturns err = cdp.Execute(ctx, CommandNavigate, p, &res) if err != nil { return "", "", "", err } return res.FrameID, res.LoaderID, res.ErrorText, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1310-L1314
func (v *RequestNodeParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom13(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/log.go#L50-L52
func newLog(storage Storage, logger Logger) *raftLog { return newLogWithSize(storage, logger, noLimit) }
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/level.go#L77-L87
func AddModuleLevel(backend Backend) LeveledBackend { var leveled LeveledBackend var ok bool if leveled, ok = backend.(LeveledBackend); !ok { leveled = &moduleLeveled{ levels: make(map[string]Level), backend: backend, } } return leveled }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.mapper.go#L418-L519
func (c *ClusterTx) ProfileDevicesRef(filter ProfileFilter) (map[string]map[string]map[string]map[string]string, error) { // Result slice. objects := make([]struct { Project string Name string Device string Type int Key string Value string }, 0) // Check which filter criteria are active. criteria := map[string]interface{}{} if filter.Project != "" { criteria["Project"] = filter.Project } if filter.Name != "" { criteria["Name"] = filter.Name } // Pick the prepared statement and arguments to use based on active criteria. var stmt *sql.Stmt var args []interface{} if criteria["Project"] != nil && criteria["Name"] != nil { stmt = c.stmt(profileDevicesRefByProjectAndName) args = []interface{}{ filter.Project, filter.Name, } } else if criteria["Project"] != nil { stmt = c.stmt(profileDevicesRefByProject) args = []interface{}{ filter.Project, } } else { stmt = c.stmt(profileDevicesRef) args = []interface{}{} } // Dest function for scanning a row. dest := func(i int) []interface{} { objects = append(objects, struct { Project string Name string Device string Type int Key string Value string }{}) return []interface{}{ &objects[i].Project, &objects[i].Name, &objects[i].Device, &objects[i].Type, &objects[i].Key, &objects[i].Value, } } // Select. err := query.SelectObjects(stmt, dest, args...) if err != nil { return nil, errors.Wrap(err, "Failed to fetch ref for profiles") } // Build index by primary name. index := map[string]map[string]map[string]map[string]string{} for _, object := range objects { _, ok := index[object.Project] if !ok { subIndex := map[string]map[string]map[string]string{} index[object.Project] = subIndex } item, ok := index[object.Project][object.Name] if !ok { item = map[string]map[string]string{} } index[object.Project][object.Name] = item config, ok := item[object.Device] if !ok { // First time we see this device, let's int the config // and add the type. deviceType, err := dbDeviceTypeToString(object.Type) if err != nil { return nil, errors.Wrapf( err, "unexpected device type code '%d'", object.Type) } config = map[string]string{} config["type"] = deviceType item[object.Device] = config } if object.Key != "" { config[object.Key] = object.Value } } return index, nil }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/rand/cryptorand.go#L23-L31
func MustGenerateRandomBytes(length int) []byte { res, err := GenerateRandomBytes(length) if err != nil { panic("Could not generate random bytes") } return res }
https://github.com/btcsuite/btclog/blob/84c8d2346e9fc8c7b947e243b9c24e6df9fd206a/log.go#L66-L75
func init() { for _, f := range strings.Split(os.Getenv("LOGFLAGS"), ",") { switch f { case "longfile": defaultFlags |= Llongfile case "shortfile": defaultFlags |= Lshortfile } } }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/trie/impl.go#L409-L426
func (t *Trie) FindRoutesForPath(path string) []*Match { context := newFindContext() matches := []*Match{} context.matchFunc = func(httpMethod, path string, node *node) { params := context.paramsAsMap() for _, route := range node.HttpMethodToRoute { matches = append( matches, &Match{ Route: route, Params: params, }, ) } } t.root.find("", path, context) return matches }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L967-L974
func (c APIClient) PutFileSplitWriter(repoName string, commitID string, path string, delimiter pfs.Delimiter, targetFileDatums int64, targetFileBytes int64, headerRecords int64, overwrite bool) (io.WriteCloser, error) { pfc, err := c.newOneoffPutFileClient() if err != nil { return nil, err } return pfc.PutFileSplitWriter(repoName, commitID, path, delimiter, targetFileDatums, targetFileBytes, headerRecords, overwrite) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_pools.go#L314-L385
func storagePoolPut(d *Daemon, r *http.Request) Response { poolName := mux.Vars(r)["name"] // Get the existing storage pool. _, dbInfo, err := d.cluster.StoragePoolGet(poolName) if err != nil { return SmartError(err) } req := api.StoragePoolPut{} if err := json.NewDecoder(r.Body).Decode(&req); err != nil { return BadRequest(err) } clustered, err := cluster.Enabled(d.db) if err != nil { return SmartError(err) } config := dbInfo.Config if clustered { err := storagePoolValidateClusterConfig(req.Config) if err != nil { return BadRequest(err) } config = storagePoolClusterConfigForEtag(config) } // Validate the ETag etag := []interface{}{dbInfo.Name, dbInfo.Driver, config} err = util.EtagCheck(r, etag) if err != nil { return PreconditionFailed(err) } // Validate the configuration err = storagePoolValidateConfig(poolName, dbInfo.Driver, req.Config, dbInfo.Config) if err != nil { return BadRequest(err) } config = req.Config if clustered { // For clustered requests, we need to complement the request's config // with our node-specific values. config = storagePoolClusterFillWithNodeConfig(dbInfo.Config, config) } // Notify the other nodes, unless this is itself a notification. if clustered && !isClusterNotification(r) { cert := d.endpoints.NetworkCert() notifier, err := cluster.NewNotifier(d.State(), cert, cluster.NotifyAll) if err != nil { return SmartError(err) } err = notifier(func(client lxd.ContainerServer) error { return client.UpdateStoragePool(poolName, req, r.Header.Get("If-Match")) }) if err != nil { return SmartError(err) } } withDB := !isClusterNotification(r) err = storagePoolUpdate(d.State(), poolName, req.Description, config, withDB) if err != nil { return InternalError(err) } return EmptySyncResponse }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/util.go#L53-L61
func numConnectedSince(transport rafthttp.Transporter, since time.Time, self types.ID, members []*membership.Member) int { connectedNum := 0 for _, m := range members { if m.ID == self || isConnectedSince(transport, since, m.ID) { connectedNum++ } } return connectedNum }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/mock_client.go#L60-L62
func (p *mockClient) VerifyProvider(request types.VerifyRequest) (types.ProviderVerifierResponse, error) { return p.VerifyProviderResponse, p.VerifyProviderError }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_actions.go#L175-L194
func (s *Selection) Tap(event Tap) error { var touchFunc func(*api.Element) error switch event { case SingleTap: touchFunc = s.session.TouchClick case DoubleTap: touchFunc = s.session.TouchDoubleClick case LongTap: touchFunc = s.session.TouchLongClick default: return fmt.Errorf("failed to %s on %s: invalid tap event", event, s) } return s.forEachElement(func(selectedElement element.Element) error { if err := touchFunc(selectedElement.(*api.Element)); err != nil { return fmt.Errorf("failed to %s on %s: %s", event, s, err) } return nil }) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L5085-L5089
func (v EventScreencastFrame) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage52(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L570-L574
func (v SetPausedInDebuggerMessageParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoOverlay7(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/hyperbahn/advertise.go#L116-L132
func (c *Client) initialAdvertise() error { var err error for attempt := uint(0); attempt < maxAdvertiseFailures; attempt++ { err = c.sendAdvertise() if err == nil || err == errEphemeralPeer { break } c.tchan.Logger().WithFields(tchannel.ErrField(err)).Info( "Hyperbahn client initial registration failure, will retry") // Back off for a while. sleepFor := fuzzInterval(advertiseRetryInterval * time.Duration(1<<attempt)) c.sleep(sleepFor) } return err }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L985-L992
func NewDataEntryExt(v int32, value interface{}) (result DataEntryExt, err error) { result.V = v switch int32(v) { case 0: // void } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L3336-L3340
func (v *MediaQueryExpression) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss29(&r, v) return r.Error() }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/sync.go#L71-L116
func (b *bindSyncer) start() error { if b.started { return errors.New("syncer already started") } if b.appLister == nil { return errors.New("must set app lister function") } if b.interval == 0 { b.interval = 5 * time.Minute } b.shutdown = make(chan struct{}, 1) b.done = make(chan struct{}) b.started = true log.Debugf("[bind-syncer] starting. Running every %s.\n", b.interval) go func(d time.Duration) { for { select { case <-time.After(d): start := time.Now() log.Debug("[bind-syncer] starting run") apps, err := b.appLister() if err != nil { log.Errorf("[bind-syncer] error listing apps: %v. Aborting sync.", err) syncDuration.Set(time.Since(start).Seconds()) break } for _, a := range apps { err = b.sync(a) if err != nil { log.Errorf("[bind-syncer] error syncing app %q: %v", a.GetName(), err) } if len(b.shutdown) > 0 { break } } log.Debugf("[bind-syncer] finished running. Synced %d apps.", len(apps)) d = b.interval syncDuration.Set(time.Since(start).Seconds()) case <-b.shutdown: b.done <- struct{}{} return } } }(time.Millisecond * 100) return nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/socket/socket_classic.go#L141-L146
func withDeadline(parent context.Context, deadline time.Time) (context.Context, context.CancelFunc) { if deadline.IsZero() { return parent, func() {} } return context.WithDeadline(parent, deadline) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/docker/config/config.go#L176-L210
func modifyJSON(sys *types.SystemContext, editor func(auths *dockerConfigFile) (bool, error)) error { path, err := getPathToAuth(sys) if err != nil { return err } dir := filepath.Dir(path) if _, err := os.Stat(dir); os.IsNotExist(err) { if err = os.MkdirAll(dir, 0700); err != nil { return errors.Wrapf(err, "error creating directory %q", dir) } } auths, err := readJSONFile(path, false) if err != nil { return errors.Wrapf(err, "error reading JSON file %q", path) } updated, err := editor(&auths) if err != nil { return errors.Wrapf(err, "error updating %q", path) } if updated { newData, err := json.MarshalIndent(auths, "", "\t") if err != nil { return errors.Wrapf(err, "error marshaling JSON %q", path) } if err = ioutil.WriteFile(path, newData, 0755); err != nil { return errors.Wrapf(err, "error writing to file %q", path) } } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2492-L2496
func (v *PerformSearchReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom27(&r, v) return r.Error() }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L668-L697
func resolveLocalPaths(config *clientcmdConfig) error { for _, cluster := range config.Clusters { if len(cluster.LocationOfOrigin) == 0 { continue } base, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin)) if err != nil { return errors.Wrapf(err, "Could not determine the absolute path of config file %s", cluster.LocationOfOrigin) } if err := resolvePaths(getClusterFileReferences(cluster), base); err != nil { return err } } for _, authInfo := range config.AuthInfos { if len(authInfo.LocationOfOrigin) == 0 { continue } base, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin)) if err != nil { return errors.Wrapf(err, "Could not determine the absolute path of config file %s", authInfo.LocationOfOrigin) } if err := resolvePaths(getAuthInfoFileReferences(authInfo), base); err != nil { return err } } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/heartbeat.go#L158-L205
func heartbeatNode(taskCtx context.Context, address string, cert *shared.CertInfo, raftNodes []db.RaftNode) error { logger.Debugf("Sending heartbeat request to %s", address) config, err := tlsClientConfig(cert) if err != nil { return err } url := fmt.Sprintf("https://%s%s", address, databaseEndpoint) client := &http.Client{Transport: &http.Transport{TLSClientConfig: config}} buffer := bytes.Buffer{} err = json.NewEncoder(&buffer).Encode(raftNodes) if err != nil { return err } request, err := http.NewRequest("PUT", url, bytes.NewReader(buffer.Bytes())) if err != nil { return err } ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() request = request.WithContext(ctx) request.Close = true // Immediately close the connection after the request is done // Perform the request asynchronously, so we can abort it if the task context is done. errCh := make(chan error) go func() { response, err := client.Do(request) if err != nil { errCh <- errors.Wrap(err, "failed to send HTTP request") return } defer response.Body.Close() if response.StatusCode != http.StatusOK { errCh <- fmt.Errorf("HTTP request failed: %s", response.Status) return } errCh <- nil }() select { case err := <-errCh: return err case <-taskCtx.Done(): return taskCtx.Err() } }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L314-L317
func (gc *GraphicContext) SetLineCap(Cap draw2d.LineCap) { gc.StackGraphicContext.SetLineCap(Cap) gc.pdf.SetLineCapStyle(caps[Cap]) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/performance/easyjson.go#L265-L269
func (v GetMetricsReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPerformance2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L414-L427
func (t *Tree) Minimum() (string, interface{}, bool) { n := t.root for { if n.isLeaf() { return n.leaf.key, n.leaf.val, true } if len(n.edges) > 0 { n = n.edges[0].node } else { break } } return "", nil, false }
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L122-L125
func (render *Render) Funcs(funcMap template.FuncMap) *Template { tmpl := &Template{render: render, usingDefaultLayout: true} return tmpl.Funcs(funcMap) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2747-L2751
func (v *LayoutViewport) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage28(&r, v) return r.Error() }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/taskmanager/task.go#L52-L58
func (s *Task) Update(update func(*Task) interface{}) interface{} { s.mutex.Lock() var ret = update(s) s.taskManager.SaveTask(s) s.mutex.Unlock() return ret }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_profiles.go#L34-L44
func (r *ProtocolLXD) GetProfiles() ([]api.Profile, error) { profiles := []api.Profile{} // Fetch the raw value _, err := r.queryStruct("GET", "/profiles?recursion=1", nil, "", &profiles) if err != nil { return nil, err } return profiles, nil }
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/proc_master.go#L181-L196
func (mp *master) fetchLoop() { min := mp.Config.MinFetchInterval time.Sleep(min) for { t0 := time.Now() mp.fetch() //duration fetch of fetch diff := time.Now().Sub(t0) if diff < min { delay := min - diff //ensures at least MinFetchInterval delay. //should be throttled by the fetcher! time.Sleep(delay) } } }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/paths.go#L144-L146
func fwruleColPath(dcid, srvid, nicid string) string { return nicPath(dcid, srvid, nicid) + slash("firewallrules") }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/usermanagment.go#L328-L333
func (c *Client) ListResourcesByType(resourcetype string) (*Resources, error) { url := umResourcesType(resourcetype) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &Resources{} err := c.client.Get(url, ret, http.StatusOK) return ret, err }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/util.go#L40-L43
func isConnectedSince(transport rafthttp.Transporter, since time.Time, remote types.ID) bool { t := transport.ActiveSince(remote) return !t.IsZero() && t.Before(since) }
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive.go#L150-L226
func (v *volume) nextVolName() { if v.num == 0 { // check file extensions i := strings.LastIndex(v.file, ".") if i < 0 { // no file extension, add one i = len(v.file) v.file += ".rar" } else { ext := strings.ToLower(v.file[i+1:]) // replace with .rar for empty extensions & self extracting archives if ext == "" || ext == "exe" || ext == "sfx" { v.file = v.file[:i+1] + "rar" } } if a, ok := v.fileBlockReader.(*archive15); ok { v.old = a.old } // new naming scheme must have volume number in filename if !v.old && reDigits.FindStringIndex(v.file) == nil { v.old = true } // For old style naming if 2nd and 3rd character of file extension is not a digit replace // with "00" and ignore any trailing characters. if v.old && (len(v.file) < i+4 || v.file[i+2] < '0' || v.file[i+2] > '9' || v.file[i+3] < '0' || v.file[i+3] > '9') { v.file = v.file[:i+2] + "00" return } } // new style volume naming if !v.old { // find all numbers in volume name m := reDigits.FindAllStringIndex(v.file, -1) if l := len(m); l > 1 { // More than 1 match so assume name.part###of###.rar style. // Take the last 2 matches where the first is the volume number. m = m[l-2 : l] if strings.Contains(v.file[m[0][1]:m[1][0]], ".") || !strings.Contains(v.file[:m[0][0]], ".") { // Didn't match above style as volume had '.' between the two numbers or didnt have a '.' // before the first match. Use the second number as volume number. m = m[1:] } } // extract and increment volume number lo, hi := m[0][0], m[0][1] n, err := strconv.Atoi(v.file[lo:hi]) if err != nil { n = 0 } else { n++ } // volume number must use at least the same number of characters as previous volume vol := fmt.Sprintf("%0"+fmt.Sprint(hi-lo)+"d", n) v.file = v.file[:lo] + vol + v.file[hi:] return } // old style volume naming i := strings.LastIndex(v.file, ".") // get file extension b := []byte(v.file[i+1:]) // start incrementing volume number digits from rightmost for j := 2; j >= 0; j-- { if b[j] != '9' { b[j]++ break } // digit overflow if j == 0 { // last character before '.' b[j] = 'A' } else { // set to '0' and loop to next character b[j] = '0' } } v.file = v.file[:i+1] + string(b) }
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/usage.go#L23-L70
func (p *Parser) WriteUsage(w io.Writer) { var positionals, options []*spec for _, spec := range p.specs { if spec.positional { positionals = append(positionals, spec) } else { options = append(options, spec) } } if p.version != "" { fmt.Fprintln(w, p.version) } fmt.Fprintf(w, "Usage: %s", p.config.Program) // write the option component of the usage message for _, spec := range options { // prefix with a space fmt.Fprint(w, " ") if !spec.required { fmt.Fprint(w, "[") } fmt.Fprint(w, synopsis(spec, "--"+spec.long)) if !spec.required { fmt.Fprint(w, "]") } } // write the positional component of the usage message for _, spec := range positionals { // prefix with a space fmt.Fprint(w, " ") up := strings.ToUpper(spec.long) if spec.multiple { if !spec.required { fmt.Fprint(w, "[") } fmt.Fprintf(w, "%s [%s ...]", up, up) if !spec.required { fmt.Fprint(w, "]") } } else { fmt.Fprint(w, up) } } fmt.Fprint(w, "\n") }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/op.go#L52-L108
func (o op) MarshalBinary() ([]byte, error) { buf := rbpool.Get() defer rbpool.Release(buf) // Write the code/opcode if err := binary.Write(buf, binary.LittleEndian, int64(o.OpType)); err != nil { return nil, errors.Wrap(err, "failed to marshal op to binary") } // If this has args, we need to encode the args tArg := reflect.TypeOf(o.uArg) hasArg := tArg != nil if hasArg { binary.Write(buf, binary.LittleEndian, int8(1)) } else { binary.Write(buf, binary.LittleEndian, int8(0)) } if hasArg { switch tArg.Kind() { case reflect.Int: binary.Write(buf, binary.LittleEndian, int64(2)) binary.Write(buf, binary.LittleEndian, int64(o.uArg.(int))) case reflect.Int64: binary.Write(buf, binary.LittleEndian, int64(2)) binary.Write(buf, binary.LittleEndian, int64(o.uArg.(int64))) case reflect.Slice: if tArg.Elem().Kind() != reflect.Uint8 { panic("Slice of what?") } binary.Write(buf, binary.LittleEndian, int64(5)) binary.Write(buf, binary.LittleEndian, int64(len(o.uArg.([]byte)))) for _, v := range o.uArg.([]byte) { binary.Write(buf, binary.LittleEndian, v) } case reflect.String: binary.Write(buf, binary.LittleEndian, int64(6)) binary.Write(buf, binary.LittleEndian, int64(len(o.uArg.(string)))) for _, v := range []byte(o.uArg.(string)) { binary.Write(buf, binary.LittleEndian, v) } default: panic("Unknown type " + tArg.String()) } } v := o.comment hasComment := v != "" if hasComment { binary.Write(buf, binary.LittleEndian, int8(1)) binary.Write(buf, binary.LittleEndian, v) } else { binary.Write(buf, binary.LittleEndian, int8(0)) } return buf.Bytes(), nil }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/pad.go#L197-L202
func zfillInt(src int, z int) string { if z < 2 { return strconv.Itoa(src) } return fmt.Sprintf(fmt.Sprintf("%%0%dd", z), src) }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/resolve/index.go#L173-L188
func (ix *RuleIndex) buildImportIndex() { ix.importMap = make(map[ImportSpec][]*ruleRecord) for _, r := range ix.rules { if r.embedded { continue } indexed := make(map[ImportSpec]bool) for _, imp := range r.importedAs { if indexed[imp] { continue } indexed[imp] = true ix.importMap[imp] = append(ix.importMap[imp], r) } } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2152-L2156
func (v PushNodesByBackendIdsToFrontendReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom23(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/quota.go#L60-L101
func changeUserQuota(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { email := r.URL.Query().Get(":email") allowed := permission.Check(t, permission.PermUserUpdateQuota, permission.Context(permTypes.CtxUser, email)) if !allowed { return permission.ErrUnauthorized } user, err := auth.GetUserByEmail(email) if err == authTypes.ErrUserNotFound { return &errors.HTTP{ Code: http.StatusNotFound, Message: err.Error(), } } else if err != nil { return err } evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypeUser, Value: email}, Kind: permission.PermUserUpdateQuota, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermUserReadEvents, permission.Context(permTypes.CtxUser, email)), }) if err != nil { return err } defer func() { evt.Done(err) }() limit, err := strconv.Atoi(InputValue(r, "limit")) if err != nil { return &errors.HTTP{ Code: http.StatusBadRequest, Message: "Invalid limit", } } err = servicemanager.UserQuota.SetLimit(user.Email, limit) if err == quota.ErrLimitLowerThanAllocated { return &errors.HTTP{ Code: http.StatusForbidden, Message: err.Error(), } } return err }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/surrogate_gossiper.go#L33-L35
func (*surrogateGossiper) OnGossipBroadcast(_ PeerName, update []byte) (GossipData, error) { return newSurrogateGossipData(update), nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/clientset/versioned/fake/clientset_generated.go#L54-L56
func (c *Clientset) TsuruV1() tsuruv1.TsuruV1Interface { return &faketsuruv1.FakeTsuruV1{Fake: &c.Fake} }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/delete_apps_app_routes_route_parameters.go#L115-L118
func (o *DeleteAppsAppRoutesRouteParams) WithApp(app string) *DeleteAppsAppRoutesRouteParams { o.SetApp(app) return o }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L174-L181
func (o Owners) GetOwnersSet() sets.String { owners := sets.NewString() for _, fn := range o.filenames { owners.Insert(o.repo.FindApproverOwnersForFile(fn)) } o.removeSubdirs(owners) return owners }