_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/decorate/podspec.go#L245-L271
func cookiefileVolume(secret string) (coreapi.Volume, coreapi.VolumeMount, string) { // Separate secret-name/key-in-secret parts := strings.SplitN(secret, "/", 2) cookieSecret := parts[0] var base string if len(parts) == 1 { base = parts[0] // Assume key-in-secret == secret-name } else { base = parts[1] } var cookiefileMode int32 = 0400 // u+r vol := coreapi.Volume{ Name: "cookiefile", VolumeSource: coreapi.VolumeSource{ Secret: &coreapi.SecretVolumeSource{ SecretName: cookieSecret, DefaultMode: &cookiefileMode, }, }, } mount := coreapi.VolumeMount{ Name: vol.Name, MountPath: "/secrets/cookiefile", // append base to flag ReadOnly: true, } return vol, mount, path.Join(mount.MountPath, base) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/unique_strings.go#L69-L71
func UniqueStringsFromFlag(fs *flag.FlagSet, flagName string) []string { return (*fs.Lookup(flagName).Value.(*UniqueStringsValue)).stringSlice() }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/tracer.go#L125-L136
func (t *Tracer) Pop() { // check list if len(t.spans) == 0 { return } // finish last span t.Last().Finish() // resize slice t.spans = t.spans[:len(t.spans)-1] }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1689-L1698
func (o *Ordered) PutFile(path string, hash []byte, size int64, fileNodeProto *FileNodeProto) { path = clean(path) nodeProto := &NodeProto{ Name: base(path), Hash: hash, SubtreeSize: size, FileNode: fileNodeProto, } o.putFile(path, nodeProto) }
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/atomic_rbuf.go#L56-L70
func NewAtomicFixedSizeRingBuf(maxViewInBytes int) *AtomicFixedSizeRingBuf { n := maxViewInBytes r := &AtomicFixedSizeRingBuf{ Use: 0, // 0 or 1, whichever is actually in use at the moment. // If we are asked for Bytes() and we wrap, linearize into the other. N: n, Beg: 0, readable: 0, } r.A[0] = make([]byte, n, n) r.A[1] = make([]byte, n, n) return r }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L336-L357
func ReadParts(r io.Reader) (*Part, error) { br := bufio.NewReader(r) root := &Part{PartID: "0"} // Read header; top-level default CT is text/plain us-ascii according to RFC 822. err := root.setupHeaders(br, `text/plain; charset="us-ascii"`) if err != nil { return nil, err } if strings.HasPrefix(root.ContentType, ctMultipartPrefix) { // Content is multipart, parse it. err = parseParts(root, br) if err != nil { return nil, err } } else { // Content is text or data, decode it. if err := root.decodeContent(br); err != nil { return nil, err } } return root, nil }
https://github.com/r3labs/sse/blob/2f90368216802092e9ed520c43e974e11d50438d/client.go#L44-L51
func NewClient(url string) *Client { return &Client{ URL: url, Connection: &http.Client{}, Headers: make(map[string]string), subscribed: make(map[chan *Event]chan bool), } }
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/nsqlookup/response.go#L36-L62
func ReadResponse(r *bufio.Reader) (res Response, err error) { var data []byte var size int32 if err = binary.Read(r, binary.BigEndian, &size); err != nil { return } data = make([]byte, int(size)) if _, err = io.ReadFull(r, data); err != nil { return } switch { case bytes.Equal(data, []byte("OK")): res = OK{} case bytes.HasPrefix(data, []byte("E_")): res = readError(data) default: res = RawResponse(data) } return }
https://github.com/bitgoin/lyra2rev2/blob/bae9ad2043bb55facb14c4918e909f88a7d3ed84/lyra2.go#L60-L70
func g(a, b, c, d uint64) (uint64, uint64, uint64, uint64) { a = a + b d = rotr64(d^a, 32) c = c + d b = rotr64(b^c, 24) a = a + b d = rotr64(d^a, 16) c = c + d b = rotr64(b^c, 63) return a, b, c, d }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/plugins.go#L274-L285
func (pa *ConfigAgent) IssueHandlers(owner, repo string) map[string]IssueHandler { pa.mut.Lock() defer pa.mut.Unlock() hs := map[string]IssueHandler{} for _, p := range pa.getPlugins(owner, repo) { if h, ok := issueHandlers[p]; ok { hs[p] = h } } return hs }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L6376-L6380
func (v *CreateStyleSheetParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss59(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/indexeddb.go#L152-L161
func RequestData(securityOrigin string, databaseName string, objectStoreName string, indexName string, skipCount int64, pageSize int64) *RequestDataParams { return &RequestDataParams{ SecurityOrigin: securityOrigin, DatabaseName: databaseName, ObjectStoreName: objectStoreName, IndexName: indexName, SkipCount: skipCount, PageSize: pageSize, } }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/node.go#L302-L361
func updateNodeHandler(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { var params provision.UpdateNodeOptions err = ParseInput(r, &params) if err != nil { return err } if params.Disable && params.Enable { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: "A node can't be enabled and disabled simultaneously.", } } if params.Address == "" { return &tsuruErrors.HTTP{Code: http.StatusBadRequest, Message: "address is required"} } prov, node, err := node.FindNode(params.Address) if err != nil { if err == provision.ErrNodeNotFound { return &tsuruErrors.HTTP{ Code: http.StatusNotFound, Message: err.Error(), } } return err } nodeProv := prov.(provision.NodeProvisioner) oldPool := node.Pool() allowedOldPool := permission.Check(t, permission.PermNodeUpdate, permission.Context(permTypes.CtxPool, oldPool), ) if !allowedOldPool { return permission.ErrUnauthorized } var ok bool params.Pool, ok = params.Metadata[provision.PoolMetadataName] if ok { delete(params.Metadata, provision.PoolMetadataName) allowedNewPool := permission.Check(t, permission.PermNodeUpdate, permission.Context(permTypes.CtxPool, params.Pool), ) if !allowedNewPool { return permission.ErrUnauthorized } } evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypeNode, Value: node.Address()}, Kind: permission.PermNodeUpdate, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermPoolReadEvents, permission.Context(permTypes.CtxPool, oldPool), permission.Context(permTypes.CtxPool, params.Pool), ), }) if err != nil { return err } defer func() { evt.Done(err) }() return nodeProv.UpdateNode(params) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/balancer.go#L126-L171
func (bb *baseBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) { if err != nil { bb.lg.Warn("HandleResolvedAddrs called with error", zap.String("balancer-id", bb.id), zap.Error(err)) return } bb.lg.Info("resolved", zap.String("balancer-id", bb.id), zap.Strings("addresses", addrsToStrings(addrs))) bb.mu.Lock() defer bb.mu.Unlock() resolved := make(map[resolver.Address]struct{}) for _, addr := range addrs { resolved[addr] = struct{}{} if _, ok := bb.addrToSc[addr]; !ok { sc, err := bb.currentConn.NewSubConn([]resolver.Address{addr}, balancer.NewSubConnOptions{}) if err != nil { bb.lg.Warn("NewSubConn failed", zap.String("balancer-id", bb.id), zap.Error(err), zap.String("address", addr.Addr)) continue } bb.addrToSc[addr] = sc bb.scToAddr[sc] = addr bb.scToSt[sc] = connectivity.Idle sc.Connect() } } for addr, sc := range bb.addrToSc { if _, ok := resolved[addr]; !ok { // was removed by resolver or failed to create subconn bb.currentConn.RemoveSubConn(sc) delete(bb.addrToSc, addr) bb.lg.Info( "removed subconn", zap.String("balancer-id", bb.id), zap.String("address", addr.Addr), zap.String("subconn", scToString(sc)), ) // Keep the state of this sc in bb.scToSt until sc's state becomes Shutdown. // The entry will be deleted in HandleSubConnStateChange. // (DO NOT) delete(bb.scToAddr, sc) // (DO NOT) delete(bb.scToSt, sc) } } }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/y.go#L117-L122
func ParseTs(key []byte) uint64 { if len(key) <= 8 { return 0 } return math.MaxUint64 - binary.BigEndian.Uint64(key[len(key)-8:]) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cdp/types.go#L644-L651
func (t *FrameID) UnmarshalEasyJSON(in *jlexer.Lexer) { buf := in.Raw() if l := len(buf); l > 2 && buf[0] == '"' && buf[l-1] == '"' { buf = buf[1 : l-1] } *t = FrameID(buf) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L3902-L3906
func (v ReplayXHRParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork26(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/olorin/nagiosplugin/blob/893f9702af4ea1e2dc4cd6528cbdcdb3dc7ca064/check.go#L160-L162
func (c *Check) Unknownf(format string, v ...interface{}) { c.Exitf(UNKNOWN, format, v...) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L274-L278
func (v *RequestDatabaseNamesReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb2(&r, v) return r.Error() }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/table.go#L82-L105
func (t *Table) DecrRef() error { newRef := atomic.AddInt32(&t.ref, -1) if newRef == 0 { // We can safely delete this file, because for all the current files, we always have // at least one reference pointing to them. // It's necessary to delete windows files if t.loadingMode == options.MemoryMap { y.Munmap(t.mmap) } if err := t.fd.Truncate(0); err != nil { // This is very important to let the FS know that the file is deleted. return err } filename := t.fd.Name() if err := t.fd.Close(); err != nil { return err } if err := os.Remove(filename); err != nil { return err } } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/stack/stack.go#L117-L127
func Callers() Trace { pcs := poolBuf() pcs = pcs[:cap(pcs)] n := runtime.Callers(2, pcs) cs := make([]Call, n) for i, pc := range pcs[:n] { cs[i] = Call(pc) } putPoolBuf(pcs) return cs }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/worker/api_server.go#L179-L188
func (a *APIServer) DatumID(data []*Input) string { hash := sha256.New() for _, d := range data { hash.Write([]byte(d.FileInfo.File.Path)) hash.Write(d.FileInfo.Hash) } // InputFileID is a single string id for the data from this input, it's used in logs and in // the statsTree return hex.EncodeToString(hash.Sum(nil)) }
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L533-L540
func (t *Tree) ToMap() map[string]interface{} { out := make(map[string]interface{}, t.size) t.Walk(func(k string, v interface{}) bool { out[k] = v return false }) return out }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/client.go#L342-L387
func (c *Client) dial(target string, creds *credentials.TransportCredentials, dopts ...grpc.DialOption) (*grpc.ClientConn, error) { opts, err := c.dialSetupOpts(creds, dopts...) if err != nil { return nil, fmt.Errorf("failed to configure dialer: %v", err) } if c.Username != "" && c.Password != "" { c.tokenCred = &authTokenCredential{ tokenMu: &sync.RWMutex{}, } ctx, cancel := c.ctx, func() {} if c.cfg.DialTimeout > 0 { ctx, cancel = context.WithTimeout(ctx, c.cfg.DialTimeout) } err = c.getToken(ctx) if err != nil { if toErr(ctx, err) != rpctypes.ErrAuthNotEnabled { if err == ctx.Err() && ctx.Err() != c.ctx.Err() { err = context.DeadlineExceeded } cancel() return nil, err } } else { opts = append(opts, grpc.WithPerRPCCredentials(c.tokenCred)) } cancel() } opts = append(opts, c.cfg.DialOptions...) dctx := c.ctx if c.cfg.DialTimeout > 0 { var cancel context.CancelFunc dctx, cancel = context.WithTimeout(c.ctx, c.cfg.DialTimeout) defer cancel() // TODO: Is this right for cases where grpc.WithBlock() is not set on the dial options? } conn, err := grpc.DialContext(dctx, target, opts...) if err != nil { return nil, err } return conn, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L170-L177
func (c *ClusterTx) ContainerNames(project string) ([]string, error) { stmt := ` SELECT containers.name FROM containers JOIN projects ON projects.id = containers.project_id WHERE projects.name = ? AND containers.type = ? ` return query.SelectStrings(c.tx, stmt, project, CTypeRegular) }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cv.go#L207-L214
func Dilate(src, dst *IplImage, element *IplConvKernel, iterations int) { C.cvDilate( unsafe.Pointer(src), unsafe.Pointer(dst), (*C.IplConvKernel)(unsafe.Pointer(element)), C.int(iterations), ) }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/matchers.go#L191-L196
func HavePrefix(prefix string, args ...interface{}) types.GomegaMatcher { return &matchers.HavePrefixMatcher{ Prefix: prefix, Args: args, } }
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/client.go#L640-L647
func newFileBuffer(file File) fileBuffer { buf := &bytes.Buffer{} return fileBuffer{ Reader: io.TeeReader(file.Reader, buf), File: file, cache: buf, } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/names.go#L115-L142
func camelCase(name string, publicName bool) string { parts := strings.Split(name, "_") startAt := 1 if publicName { startAt = 0 } for i := startAt; i < len(parts); i++ { name := parts[i] if name == "" { continue } // For all words except the first, if the first letter of the word is // uppercase, Thrift keeps the underscore. if i > 0 && strings.ToUpper(name[0:1]) == name[0:1] { name = "_" + name } else { name = strings.ToUpper(name[0:1]) + name[1:] } if isInitialism := commonInitialisms[strings.ToUpper(name)]; isInitialism { name = strings.ToUpper(name) } parts[i] = name } return strings.Join(parts, "") }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/concourse.go#L91-L93
func (s *ConcoursePipeline) AddBoshIOResource(name string, source map[string]interface{}) { s.AddResource(name, BoshIOResourceName, source) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/tackle/main.go#L369-L387
func applyCreate(ctx string, args ...string) error { create := exec.Command("kubectl", append([]string{"--dry-run=true", "--output=yaml", "create"}, args...)...) create.Stderr = os.Stderr obj, err := create.StdoutPipe() if err != nil { return fmt.Errorf("rolebinding pipe: %v", err) } if err := create.Start(); err != nil { return fmt.Errorf("start create: %v", err) } if err := apply(ctx, obj); err != nil { return fmt.Errorf("apply: %v", err) } if err := create.Wait(); err != nil { return fmt.Errorf("create: %v", err) } return nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L335-L337
func AddMulti(c context.Context, item []*Item) error { return set(c, item, nil, pb.MemcacheSetRequest_ADD) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L427-L450
func (c APIClient) FlushCommitF(commits []*pfs.Commit, toRepos []*pfs.Repo, f func(*pfs.CommitInfo) error) error { stream, err := c.PfsAPIClient.FlushCommit( c.Ctx(), &pfs.FlushCommitRequest{ Commits: commits, ToRepos: toRepos, }, ) if err != nil { return grpcutil.ScrubGRPC(err) } for { ci, err := stream.Recv() if err != nil { if err == io.EOF { return nil } return grpcutil.ScrubGRPC(err) } if err := f(ci); err != nil { return err } } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/v3_server.go#L541-L561
func (s *EtcdServer) doSerialize(ctx context.Context, chk func(*auth.AuthInfo) error, get func()) error { ai, err := s.AuthInfoFromCtx(ctx) if err != nil { return err } if ai == nil { // chk expects non-nil AuthInfo; use empty credentials ai = &auth.AuthInfo{} } if err = chk(ai); err != nil { return err } // fetch response for serialized request get() // check for stale token revision in case the auth store was updated while // the request has been handled. if ai.Revision != 0 && ai.Revision != s.authStore.Revision() { return auth.ErrAuthOldRevision } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/operations.go#L86-L97
func (op *operation) Refresh() error { // Get the current version of the operation newOp, _, err := op.r.GetOperation(op.ID) if err != nil { return err } // Update the operation struct op.Operation = *newOp return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L6305-L6309
func (v *CreateStyleSheetReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss58(&r, v) return r.Error() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/mkbuild-cluster/main.go#L150-L154
func command(bin string, args ...string) ([]string, *exec.Cmd) { cmd := exec.Command(bin, args...) cmd.Stderr = os.Stderr return append([]string{bin}, args...), cmd }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/mnemosyned/session_manager.go#L176-L178
func (sm *sessionManager) Collect(in chan<- prometheus.Metric) { sm.cleanupErrorsTotal.Collect(in) }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L359-L368
func (l *InclusiveRanges) Max() int { val := l.End() for _, aRange := range l.blocks { next := aRange.Max() if next > val { val = next } } return val }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L100-L113
func analyze(tags []string) (*app, error) { ctxt := buildContext(tags) hasMain, appFiles, err := checkMain(ctxt) if err != nil { return nil, err } gopath := filepath.SplitList(ctxt.GOPATH) im, err := imports(ctxt, *rootDir, gopath) return &app{ hasMain: hasMain, appFiles: appFiles, imports: im, }, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L1200-L1204
func (v *SetBypassCSPParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage13(&r, v) return r.Error() }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L233-L244
func (gc *GraphicContext) draw(style string, alpha uint32, paths ...*draw2d.Path) { paths = append(paths, gc.Current.Path) for _, p := range paths { ConvertPath(p, gc.pdf) } a := float64(alpha) / alphaMax current, blendMode := gc.pdf.GetAlpha() if a != current { gc.pdf.SetAlpha(a, blendMode) } gc.pdf.DrawPath(style) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L3155-L3159
func (v *ExceptionDetails) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime28(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/adt/interval_tree.go#L442-L452
func (ivt *IntervalTree) Intersects(iv Interval) bool { x := ivt.root for x != nil && iv.Compare(&x.iv.Ivl) != 0 { if x.left != nil && x.left.max.Compare(iv.Begin) > 0 { x = x.left } else { x = x.right } } return x != nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/util.go#L184-L190
func addRemoteFromRequest(tr Transporter, r *http.Request) { if from, err := types.IDFromString(r.Header.Get("X-Server-From")); err == nil { if urls := r.Header.Get("X-PeerURLs"); urls != "" { tr.AddRemote(from, strings.Split(urls, ",")) } } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L640-L661
func (c *Cluster) ImageAliasDelete(project, name string) error { err := c.Transaction(func(tx *ClusterTx) error { enabled, err := tx.ProjectHasImages(project) if err != nil { return errors.Wrap(err, "Check if project has images") } if !enabled { project = "default" } return nil }) if err != nil { return err } err = exec(c.db, ` DELETE FROM images_aliases WHERE project_id = (SELECT id FROM projects WHERE name = ?) AND name = ? `, project, name) return err }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1112-L1121
func (u LedgerEntryData) GetAccount() (result AccountEntry, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "Account" { result = *u.Account ok = true } return }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L45-L49
func PadLeftF(c string, n int) func(string) string { return func(s string) string { return PadLeft(s, c, n) } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L280-L282
func (r *Application) Locator(api *API) *ApplicationLocator { return api.ApplicationLocator(r.Href) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L1459-L1463
func (v *PropertyPreview) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime14(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_operations.go#L14-L31
func (r *ProtocolLXD) GetOperationUUIDs() ([]string, error) { urls := []string{} // Fetch the raw value _, err := r.queryStruct("GET", "/operations", nil, "", &urls) if err != nil { return nil, err } // Parse it uuids := []string{} for _, url := range urls { fields := strings.Split(url, "/operations/") uuids = append(uuids, fields[len(fields)-1]) } return uuids, nil }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/http.go#L258-L283
func (client *Client) SignedURL(route string, query url.Values, duration time.Duration) (u *url.URL, err error) { u, err = setURL(client, route, query) if err != nil { return } credentials := &hawk.Credentials{ ID: client.Credentials.ClientID, Key: client.Credentials.AccessToken, Hash: sha256.New, } reqAuth, err := hawk.NewURLAuth(u.String(), credentials, duration) if err != nil { return } reqAuth.Ext, err = getExtHeader(client.Credentials) if err != nil { return } bewitSignature := reqAuth.Bewit() if query == nil { query = url.Values{} } query.Set("bewit", bewitSignature) u.RawQuery = query.Encode() return }
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/clitable/table.go#L57-L63
func PrintTable(fields []string, rows []map[string]interface{}) { table := New(fields) for _, r := range rows { table.AddRow(r) } table.Print() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_dir.go#L327-L362
func (s *storageDir) StoragePoolVolumeCreate() error { logger.Infof("Creating DIR storage volume \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name) _, err := s.StoragePoolMount() if err != nil { return err } source := s.pool.Config["source"] if source == "" { return fmt.Errorf("no \"source\" property found for the storage pool") } isSnapshot := shared.IsSnapshot(s.volume.Name) var storageVolumePath string if isSnapshot { storageVolumePath = getStoragePoolVolumeSnapshotMountPoint(s.pool.Name, s.volume.Name) } else { storageVolumePath = getStoragePoolVolumeMountPoint(s.pool.Name, s.volume.Name) } err = os.MkdirAll(storageVolumePath, 0711) if err != nil { return err } err = s.initQuota(storageVolumePath, s.volumeID) if err != nil { return err } logger.Infof("Created DIR storage volume \"%s\" on storage pool \"%s\"", s.volume.Name, s.pool.Name) return nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L161-L180
func (s *MergeIterator) initHeap() { s.h = s.h[:0] for idx, itr := range s.all { if !itr.Valid() { continue } e := &elem{itr: itr, nice: idx, reversed: s.reversed} s.h = append(s.h, e) } heap.Init(&s.h) for len(s.h) > 0 { it := s.h[0].itr if it == nil || !it.Valid() { heap.Pop(&s.h) continue } s.storeKey(s.h[0].itr) break } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/endpoints.go#L104-L131
func Up(config *Config) (*Endpoints, error) { if config.Dir == "" { return nil, fmt.Errorf("No directory configured") } if config.UnixSocket == "" { return nil, fmt.Errorf("No unix socket configured") } if config.RestServer == nil { return nil, fmt.Errorf("No REST server configured") } if config.DevLxdServer == nil { return nil, fmt.Errorf("No devlxd server configured") } if config.Cert == nil { return nil, fmt.Errorf("No TLS certificate configured") } endpoints := &Endpoints{ systemdListenFDsStart: util.SystemdListenFDsStart, } err := endpoints.up(config) if err != nil { endpoints.Down() return nil, err } return endpoints, nil }
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L48-L123
func (db *DB) Select(output interface{}, args ...interface{}) (err error) { defer func() { if e := recover(); e != nil { buf := make([]byte, 4096) n := runtime.Stack(buf, false) err = fmt.Errorf("%v\n%v", e, string(buf[:n])) } }() rv := reflect.ValueOf(output) if rv.Kind() != reflect.Ptr { return fmt.Errorf("Select: first argument must be a pointer") } for rv.Kind() == reflect.Ptr { rv = rv.Elem() } var tableName string for _, arg := range args { if f, ok := arg.(*From); ok { if tableName != "" { return fmt.Errorf("Select: From statement specified more than once") } tableName = f.TableName } } var selectFunc selectFunc ptrN := 0 switch rv.Kind() { case reflect.Slice: t := rv.Type().Elem() for ; t.Kind() == reflect.Ptr; ptrN++ { t = t.Elem() } if t.Kind() != reflect.Struct { return fmt.Errorf("Select: argument of slice must be slice of struct, but %v", rv.Type()) } if tableName == "" { tableName = db.tableName(t) } selectFunc = db.selectToSlice case reflect.Invalid: return fmt.Errorf("Select: nil pointer dereference") default: if tableName == "" { return fmt.Errorf("Select: From statement must be given if any Function is given") } selectFunc = db.selectToValue } col, from, conditions, err := db.classify(tableName, args) if err != nil { return err } queries := []string{`SELECT`, col, `FROM`, db.dialect.Quote(from)} var values []interface{} for _, cond := range conditions { q, a := cond.build(0, false) queries = append(queries, q...) values = append(values, a...) } query := strings.Join(queries, " ") stmt, err := db.prepare(query, values...) if err != nil { return err } defer stmt.Close() rows, err := stmt.Query(values...) if err != nil { return err } defer rows.Close() value, err := selectFunc(rows, rv.Type()) if err != nil { return err } rv.Set(value) return nil }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_reflect.go#L262-L268
func formatPointer(v reflect.Value) string { p := v.Pointer() if flags.Deterministic { p = 0xdeadf00f // Only used for stable testing purposes } return fmt.Sprintf("⟪0x%x⟫", p) }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L1395-L1452
func (r *Raft) electSelf() <-chan *voteResult { // Create a response channel respCh := make(chan *voteResult, len(r.configurations.latest.Servers)) // Increment the term r.setCurrentTerm(r.getCurrentTerm() + 1) // Construct the request lastIdx, lastTerm := r.getLastEntry() req := &RequestVoteRequest{ RPCHeader: r.getRPCHeader(), Term: r.getCurrentTerm(), Candidate: r.trans.EncodePeer(r.localID, r.localAddr), LastLogIndex: lastIdx, LastLogTerm: lastTerm, } // Construct a function to ask for a vote askPeer := func(peer Server) { r.goFunc(func() { defer metrics.MeasureSince([]string{"raft", "candidate", "electSelf"}, time.Now()) resp := &voteResult{voterID: peer.ID} err := r.trans.RequestVote(peer.ID, peer.Address, req, &resp.RequestVoteResponse) if err != nil { r.logger.Error(fmt.Sprintf("Failed to make RequestVote RPC to %v: %v", peer, err)) resp.Term = req.Term resp.Granted = false } respCh <- resp }) } // For each peer, request a vote for _, server := range r.configurations.latest.Servers { if server.Suffrage == Voter { if server.ID == r.localID { // Persist a vote for ourselves if err := r.persistVote(req.Term, req.Candidate); err != nil { r.logger.Error(fmt.Sprintf("Failed to persist vote : %v", err)) return nil } // Include our own vote respCh <- &voteResult{ RequestVoteResponse: RequestVoteResponse{ RPCHeader: r.getRPCHeader(), Term: req.Term, Granted: true, }, voterID: r.localID, } } else { askPeer(server) } } } return respCh }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L420-L431
func CreateMatND(sizes []int, type_ int) *MatND { dims := C.int(len(sizes)) sizes_c := make([]C.int, len(sizes)) for i := 0; i < len(sizes); i++ { sizes_c[i] = C.int(sizes[i]) } mat := C.cvCreateMatND( dims, (*C.int)(&sizes_c[0]), C.int(type_), ) return (*MatND)(mat) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/grpc1.7-health.go#L112-L146
func NewGRPC17Health( eps []string, timeout time.Duration, dialFunc DialFunc, ) *GRPC17Health { notifyCh := make(chan []grpc.Address) addrs := eps2addrs(eps) hb := &GRPC17Health{ addrs: addrs, eps: eps, notifyCh: notifyCh, readyc: make(chan struct{}), healthCheck: func(ep string) (bool, error) { return grpcHealthCheck(ep, dialFunc) }, unhealthyHostPorts: make(map[string]time.Time), upc: make(chan struct{}), stopc: make(chan struct{}), downc: make(chan struct{}), donec: make(chan struct{}), updateAddrsC: make(chan NotifyMsg), hostPort2ep: getHostPort2ep(eps), } if timeout < minHealthRetryDuration { timeout = minHealthRetryDuration } hb.healthCheckTimeout = timeout close(hb.downc) go hb.updateNotifyLoop() hb.wg.Add(1) go func() { defer hb.wg.Done() hb.updateUnhealthy() }() return hb }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/spyglass/podlogartifact.go#L106-L119
func (a *PodLogArtifact) ReadAll() ([]byte, error) { size, err := a.Size() if err != nil { return nil, fmt.Errorf("error getting pod log size: %v", err) } if size > a.sizeLimit { return nil, lenses.ErrFileTooLarge } logs, err := a.jobAgent.GetJobLog(a.name, a.buildID) if err != nil { return nil, fmt.Errorf("error getting pod log: %v", err) } return logs, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/invalidcommitmsg/invalidcommitmsg.go#L158-L169
func hasPRChanged(pr github.PullRequestEvent) bool { switch pr.Action { case github.PullRequestActionOpened: return true case github.PullRequestActionReopened: return true case github.PullRequestActionSynchronize: return true default: return false } }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L105-L111
func multiKeyToProto(appID string, key []*Key) []*pb.Reference { ret := make([]*pb.Reference, len(key)) for i, k := range key { ret[i] = keyToProto(appID, k) } return ret }
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L150-L154
func (c *Consumer) MarkPartitionOffset(topic string, partition int32, offset int64, metadata string) { if sub := c.subs.Fetch(topic, partition); sub != nil { sub.MarkOffset(offset, metadata) } }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L186-L203
func (v *VM) PowerState() (VMPowerState, error) { var err C.VixError = C.VIX_OK var state C.VixPowerState = 0x0 err = C.get_property(v.handle, C.VIX_PROPERTY_VM_POWER_STATE, unsafe.Pointer(&state)) if C.VIX_OK != err { return VMPowerState(0x0), &Error{ Operation: "vm.PowerState", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } return VMPowerState(state), nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/security/types.go#L180-L182
func (t *CertificateErrorAction) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1929-L1937
func (u OperationBody) MustCreatePassiveOfferOp() CreatePassiveOfferOp { val, ok := u.GetCreatePassiveOfferOp() if !ok { panic("arm CreatePassiveOfferOp is not set") } return val }
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L138-L187
func (now *Now) Parse(strs ...string) (t time.Time, err error) { var ( setCurrentTime bool parseTime []int currentTime = []int{now.Nanosecond(), now.Second(), now.Minute(), now.Hour(), now.Day(), int(now.Month()), now.Year()} currentLocation = now.Location() onlyTimeInStr = true ) for _, str := range strs { hasTimeInStr := hasTimeRegexp.MatchString(str) // match 15:04:05, 15 onlyTimeInStr = hasTimeInStr && onlyTimeInStr && onlyTimeRegexp.MatchString(str) if t, err = parseWithFormat(str); err == nil { location := t.Location() if location.String() == "UTC" { location = currentLocation } parseTime = []int{t.Nanosecond(), t.Second(), t.Minute(), t.Hour(), t.Day(), int(t.Month()), t.Year()} for i, v := range parseTime { // Don't reset hour, minute, second if current time str including time if hasTimeInStr && i <= 3 { continue } // If value is zero, replace it with current time if v == 0 { if setCurrentTime { parseTime[i] = currentTime[i] } } else { setCurrentTime = true } // if current time only includes time, should change day, month to current time if onlyTimeInStr { if i == 4 || i == 5 { parseTime[i] = currentTime[i] continue } } } t = time.Date(parseTime[6], time.Month(parseTime[5]), parseTime[4], parseTime[3], parseTime[2], parseTime[1], parseTime[0], location) currentTime = []int{t.Nanosecond(), t.Second(), t.Minute(), t.Hour(), t.Day(), int(t.Month()), t.Year()} } } return }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/log_adapter.go#L57-L59
func (la *LogAdapter) SetAttr(key string, value interface{}) { la.attrs.SetAttr(key, value) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L679-L694
func (c APIClient) TagObject(hash string, tags ...string) error { var _tags []*pfs.Tag for _, tag := range tags { _tags = append(_tags, &pfs.Tag{Name: tag}) } if _, err := c.ObjectAPIClient.TagObject( c.Ctx(), &pfs.TagObjectRequest{ Object: &pfs.Object{Hash: hash}, Tags: _tags, }, ); err != nil { return grpcutil.ScrubGRPC(err) } return nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/archive/oci_src.go#L95-L97
func (s *ociArchiveImageSource) GetSignatures(ctx context.Context, instanceDigest *digest.Digest) ([][]byte, error) { return s.unpackedSrc.GetSignatures(ctx, instanceDigest) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L593-L595
func (p *SetUserAgentOverrideParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetUserAgentOverride, p, nil) }
https://github.com/marcuswestin/go-errs/blob/b09b17aacd5a8213690bc30f9ccfe7400be7b380/errs.go#L85-L100
func Wrap(wrapErr error, info Info, publicMsg ...interface{}) Err { if wrapErr == nil { return nil } if info == nil { info = Info{} } if errsErr, isErr := IsErr(wrapErr); isErr { if errStructErr, isErrsErr := errsErr.(*err); isErrsErr { errStructErr.mergeIn(info, publicMsg) return errStructErr } return errsErr } return newErr(debug.Stack(), wrapErr, false, info, publicMsg) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1618-L1627
func (u AllowTrustOpAsset) GetAssetCode12() (result [12]byte, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "AssetCode12" { result = *u.AssetCode12 ok = true } return }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/roundtrip.go#L26-L28
func (f RoundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/audits/types.go#L41-L53
func (t *GetEncodedResponseEncoding) UnmarshalEasyJSON(in *jlexer.Lexer) { switch GetEncodedResponseEncoding(in.String()) { case GetEncodedResponseEncodingWebp: *t = GetEncodedResponseEncodingWebp case GetEncodedResponseEncodingJpeg: *t = GetEncodedResponseEncodingJpeg case GetEncodedResponseEncodingPng: *t = GetEncodedResponseEncodingPng default: in.AddError(errors.New("unknown GetEncodedResponseEncoding value")) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L1117-L1121
func (v SetDocumentContentParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage12(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/workload/workload.go#L155-L164
func (w *worker) putFile(c *client.APIClient) error { if len(w.started) == 0 { return nil } commit := w.started[w.rand.Intn(len(w.started))] if _, err := c.PutFile(commit.Repo.Name, commit.ID, w.randString(10), w.reader()); err != nil { return err } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2916-L2920
func (v *Location) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger30(&r, v) return r.Error() }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/google/googleSDK/sdk.go#L29-L44
func NewSdk() (*Sdk, error) { sdk := &Sdk{} client, err := google.DefaultClient(context.TODO(), compute.ComputeScope) if err != nil { return nil, err } service, err := compute.New(client) if err != nil { return nil, err } sdk.Service = service return sdk, nil }
https://github.com/Unknwon/goconfig/blob/3dba17dd7b9ec8509b3621a73a30a4b333eb28da/read.go#L31-L175
func (c *ConfigFile) read(reader io.Reader) (err error) { buf := bufio.NewReader(reader) // Handle BOM-UTF8. // http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding mask, err := buf.Peek(3) if err == nil && len(mask) >= 3 && mask[0] == 239 && mask[1] == 187 && mask[2] == 191 { buf.Read(mask) } count := 1 // Counter for auto increment. // Current section name. section := DEFAULT_SECTION var comments string // Parse line-by-line for { line, err := buf.ReadString('\n') line = strings.TrimSpace(line) lineLengh := len(line) //[SWH|+] if err != nil { if err != io.EOF { return err } // Reached end of file, if nothing to read then break, // otherwise handle the last line. if lineLengh == 0 { break } } // switch written for readability (not performance) switch { case lineLengh == 0: // Empty line continue case line[0] == '#' || line[0] == ';': // Comment // Append comments if len(comments) == 0 { comments = line } else { comments += LineBreak + line } continue case line[0] == '[' && line[lineLengh-1] == ']': // New section. // Get section name. section = strings.TrimSpace(line[1 : lineLengh-1]) // Set section comments and empty if it has comments. if len(comments) > 0 { c.SetSectionComments(section, comments) comments = "" } // Make section exist even though it does not have any key. c.SetValue(section, " ", " ") // Reset counter. count = 1 continue case section == "": // No section defined so far return readError{ERR_BLANK_SECTION_NAME, line} default: // Other alternatives var ( i int keyQuote string key string valQuote string value string ) //[SWH|+]:支持引号包围起来的字串 if line[0] == '"' { if lineLengh >= 6 && line[0:3] == `"""` { keyQuote = `"""` } else { keyQuote = `"` } } else if line[0] == '`' { keyQuote = "`" } if keyQuote != "" { qLen := len(keyQuote) pos := strings.Index(line[qLen:], keyQuote) if pos == -1 { return readError{ERR_COULD_NOT_PARSE, line} } pos = pos + qLen i = strings.IndexAny(line[pos:], "=:") if i <= 0 { return readError{ERR_COULD_NOT_PARSE, line} } i = i + pos key = line[qLen:pos] //保留引号内的两端的空格 } else { i = strings.IndexAny(line, "=:") if i <= 0 { return readError{ERR_COULD_NOT_PARSE, line} } key = strings.TrimSpace(line[0:i]) } //[SWH|+]; // Check if it needs auto increment. if key == "-" { key = "#" + fmt.Sprint(count) count++ } //[SWH|+]:支持引号包围起来的字串 lineRight := strings.TrimSpace(line[i+1:]) lineRightLength := len(lineRight) firstChar := "" if lineRightLength >= 2 { firstChar = lineRight[0:1] } if firstChar == "`" { valQuote = "`" } else if lineRightLength >= 6 && lineRight[0:3] == `"""` { valQuote = `"""` } if valQuote != "" { qLen := len(valQuote) pos := strings.LastIndex(lineRight[qLen:], valQuote) if pos == -1 { return readError{ERR_COULD_NOT_PARSE, line} } pos = pos + qLen value = lineRight[qLen:pos] } else { value = strings.TrimSpace(lineRight[0:]) } //[SWH|+]; c.SetValue(section, key, value) // Set key comments and empty if it has comments. if len(comments) > 0 { c.SetKeyComments(section, key, comments) comments = "" } } // Reached end of file. if err == io.EOF { break } } return nil }
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/parse.go#L449-L477
func setSlice(dest reflect.Value, values []string, trunc bool) error { if !dest.CanSet() { return fmt.Errorf("field is not writable") } var ptr bool elem := dest.Type().Elem() if elem.Kind() == reflect.Ptr && !elem.Implements(textUnmarshalerType) { ptr = true elem = elem.Elem() } // Truncate the dest slice in case default values exist if trunc && !dest.IsNil() { dest.SetLen(0) } for _, s := range values { v := reflect.New(elem) if err := scalar.ParseValue(v.Elem(), s); err != nil { return err } if !ptr { v = v.Elem() } dest.Set(reflect.Append(dest, v)) } return nil }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/boundary.go#L28-L37
func newBoundaryReader(reader *bufio.Reader, boundary string) *boundaryReader { fullBoundary := []byte("\n--" + boundary + "--") return &boundaryReader{ r: reader, nlPrefix: fullBoundary[:len(fullBoundary)-2], prefix: fullBoundary[1 : len(fullBoundary)-2], final: fullBoundary[1:], buffer: new(bytes.Buffer), } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/driver.go#L431-L646
func (d *driver) makeCommit(pachClient *client.APIClient, ID string, parent *pfs.Commit, branch string, provenance []*pfs.CommitProvenance, treeRef *pfs.Object, recordFiles []string, records []*pfs.PutFileRecords, description string) (*pfs.Commit, error) { // Validate arguments: if parent == nil { return nil, fmt.Errorf("parent cannot be nil") } // Check that caller is authorized if err := d.checkIsAuthorized(pachClient, parent.Repo, auth.Scope_WRITER); err != nil { return nil, err } // New commit and commitInfo newCommit := &pfs.Commit{ Repo: parent.Repo, ID: ID, } if newCommit.ID == "" { newCommit.ID = uuid.NewWithoutDashes() } newCommitInfo := &pfs.CommitInfo{ Commit: newCommit, Started: now(), Description: description, } // FinishCommit case. We need to create AND finish 'newCommit' in two cases: // 1. PutFile has been called on a finished commit (records != nil), and // we want to apply 'records' to the parentCommit's HashTree, use that new // HashTree for this commit's filesystem, and then finish this commit // 2. BuildCommit has been called by migration (treeRef != nil) and we // want a new, finished commit with the given treeRef // - In either case, store this commit's HashTree in 'tree', so we have its // size, and store a pointer to the tree (in object store) in 'treeRef', to // put in newCommitInfo.Tree. // - We also don't want to resolve 'branch' or 'parent.ID' (if it's a branch) // outside the txn below, so the 'PutFile' case is handled (by computing // 'tree' and 'treeRef') below as well var tree hashtree.HashTree if treeRef != nil { var err error tree, err = hashtree.GetHashTreeObject(pachClient, d.storageRoot, treeRef) if err != nil { return nil, err } } // Txn: create the actual commit in etcd and update the branch + parent/child if _, err := col.NewSTM(pachClient.Ctx(), d.etcdClient, func(stm col.STM) error { // Clone the parent, as this stm modifies it and might wind up getting // run more than once (if there's a conflict.) parent := proto.Clone(parent).(*pfs.Commit) repos := d.repos.ReadWrite(stm) commits := d.commits(parent.Repo.Name).ReadWrite(stm) branches := d.branches(parent.Repo.Name).ReadWrite(stm) // Check if repo exists repoInfo := new(pfs.RepoInfo) if err := repos.Get(parent.Repo.Name, repoInfo); err != nil { return err } // create/update 'branch' (if it was set) and set parent.ID (if, in // addition, 'parent.ID' was not set) if branch != "" { branchInfo := &pfs.BranchInfo{} if err := branches.Upsert(branch, branchInfo, func() error { // validate branch if parent.ID == "" && branchInfo.Head != nil { parent.ID = branchInfo.Head.ID } // Don't count the __spec__ repo towards the provenance count // since spouts will have __spec__ as provenance, but need to accept commits provenanceCount := len(branchInfo.Provenance) for _, p := range branchInfo.Provenance { if p.Repo.Name == ppsconsts.SpecRepo { provenanceCount-- break } } if provenanceCount > 0 && treeRef == nil { return fmt.Errorf("cannot start a commit on an output branch") } // Point 'branch' at the new commit branchInfo.Name = branch // set in case 'branch' is new branchInfo.Head = newCommit branchInfo.Branch = client.NewBranch(newCommit.Repo.Name, branch) return nil }); err != nil { return err } // Add branch to repo (see "Update repoInfo" below) add(&repoInfo.Branches, branchInfo.Branch) // and add the branch to the commit info newCommitInfo.Branch = branchInfo.Branch } // Set newCommit.ParentCommit (if 'parent' and/or 'branch' was set) and add // newCommit to parent's ChildCommits if parent.ID != "" { // Resolve parent.ID if it's a branch that isn't 'branch' (which can // happen if 'branch' is new and diverges from the existing branch in // 'parent.ID') parentCommitInfo, err := d.resolveCommit(stm, parent) if err != nil { return fmt.Errorf("parent commit not found: %v", err) } // fail if the parent commit has not been finished if parentCommitInfo.Finished == nil { return fmt.Errorf("parent commit %s has not been finished", parent.ID) } if err := commits.Update(parent.ID, parentCommitInfo, func() error { newCommitInfo.ParentCommit = parent // If we don't know the branch the commit belongs to at this point, assume it is the same as the parent branch if newCommitInfo.Branch == nil { newCommitInfo.Branch = parentCommitInfo.Branch } parentCommitInfo.ChildCommits = append(parentCommitInfo.ChildCommits, newCommit) return nil }); err != nil { // Note: error is emitted if parent.ID is a missing/invalid branch OR a // missing/invalid commit ID return fmt.Errorf("could not resolve parent commit \"%s\": %v", parent.ID, err) } } // 1. Write 'newCommit' to 'openCommits' collection OR // 2. Finish 'newCommit' (if treeRef != nil or records != nil); see // "FinishCommit case" above) if treeRef != nil || records != nil { if records != nil { parentTree, err := d.getTreeForCommit(pachClient, parent) if err != nil { return err } tree, err = parentTree.Copy() if err != nil { return err } for i, record := range records { if err := d.applyWrite(recordFiles[i], record, tree); err != nil { return err } } if err := tree.Hash(); err != nil { return err } treeRef, err = hashtree.PutHashTree(pachClient, tree) if err != nil { return err } } // now 'treeRef' is guaranteed to be set newCommitInfo.Tree = treeRef newCommitInfo.SizeBytes = uint64(tree.FSSize()) newCommitInfo.Finished = now() // If we're updating the master branch, also update the repo size (see // "Update repoInfo" below) if branch == "master" { repoInfo.SizeBytes = newCommitInfo.SizeBytes } } else { if err := d.openCommits.ReadWrite(stm).Put(newCommit.ID, newCommit); err != nil { return err } } // Update repoInfo (potentially with new branch and new size) if err := repos.Put(parent.Repo.Name, repoInfo); err != nil { return err } // Build newCommit's full provenance. B/c commitInfo.Provenance is a // transitive closure, there's no need to search the full provenance graph, // just take the union of the immediate parents' (in the 'provenance' arg) // commitInfo.Provenance newCommitProv := make(map[string]*pfs.CommitProvenance) for _, prov := range provenance { newCommitProv[prov.Commit.ID] = prov provCommitInfo := &pfs.CommitInfo{} if err := d.commits(prov.Commit.Repo.Name).ReadWrite(stm).Get(prov.Commit.ID, provCommitInfo); err != nil { return err } for _, c := range provCommitInfo.Provenance { newCommitProv[c.Commit.ID] = c } } // Copy newCommitProv into newCommitInfo.Provenance, and update upstream subv for _, prov := range newCommitProv { newCommitInfo.Provenance = append(newCommitInfo.Provenance, prov) provCommitInfo := &pfs.CommitInfo{} if err := d.commits(prov.Commit.Repo.Name).ReadWrite(stm).Update(prov.Commit.ID, provCommitInfo, func() error { appendSubvenance(provCommitInfo, newCommitInfo) return nil }); err != nil { return err } } // Finally, create the commit if err := commits.Create(newCommit.ID, newCommitInfo); err != nil { return err } // We propagate the branch last so propagateCommit can write to the // now-existing commit's subvenance if branch != "" { return d.propagateCommit(stm, client.NewBranch(newCommit.Repo.Name, branch)) } return nil }); err != nil { return nil, err } return newCommit, nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4202-L4210
func (u OperationResultTr) MustInflationResult() InflationResult { val, ok := u.GetInflationResult() if !ok { panic("arm InflationResult is not set") } return val }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/src.go#L248-L259
func (s *Source) loadTarManifest() ([]ManifestItem, error) { // FIXME? Do we need to deal with the legacy format? bytes, err := s.readTarComponent(manifestFileName) if err != nil { return nil, err } var items []ManifestItem if err := json.Unmarshal(bytes, &items); err != nil { return nil, errors.Wrap(err, "Error decoding tar manifest.json") } return items, nil }
https://github.com/knq/sdhook/blob/41b9ccbff0b5fa5a56fbdccf2eb8653e7afe8d4b/sdhook.go#L144-L183
func (sh *StackdriverHook) Fire(entry *logrus.Entry) error { sh.waitGroup.Add(1) go func(entry *logrus.Entry) { defer sh.waitGroup.Done() var httpReq *logging.HttpRequest // convert entry data to labels labels := make(map[string]string, len(entry.Data)) for k, v := range entry.Data { switch x := v.(type) { case string: labels[k] = x case *http.Request: httpReq = &logging.HttpRequest{ Referer: x.Referer(), RemoteIp: x.RemoteAddr, RequestMethod: x.Method, RequestUrl: x.URL.String(), UserAgent: x.UserAgent(), } case *logging.HttpRequest: httpReq = x default: labels[k] = fmt.Sprintf("%v", v) } } // write log entry if sh.agentClient != nil { sh.sendLogMessageViaAgent(entry, labels, httpReq) } else { sh.sendLogMessageViaAPI(entry, labels, httpReq) } }(sh.copyEntry(entry)) return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/client.go#L50-L54
func (o *KubernetesClientOptions) AddFlags(fs *flag.FlagSet) { fs.StringVar(&o.namespace, "namespace", v1.NamespaceDefault, "namespace to install on") fs.StringVar(&o.kubeConfig, "kubeconfig", "", "absolute path to the kubeConfig file") fs.BoolVar(&o.inMemory, "in_memory", false, "Use in memory client instead of CRD") }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/easyjson.go#L237-L241
func (v RequestPattern) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoFetch2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/nightlyone/lockfile/blob/0ad87eef1443f64d3d8c50da647e2b1552851124/lockfile.go#L52-L80
func (l Lockfile) GetOwner() (*os.Process, error) { name := string(l) // Ok, see, if we have a stale lockfile here content, err := ioutil.ReadFile(name) if err != nil { return nil, err } // try hard for pids. If no pid, the lockfile is junk anyway and we delete it. pid, err := scanPidLine(content) if err != nil { return nil, err } running, err := isRunning(pid) if err != nil { return nil, err } if running { proc, err := os.FindProcess(pid) if err != nil { return nil, err } return proc, nil } return nil, ErrDeadOwner }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L1767-L1781
func (r *ProtocolLXD) GetContainerBackups(containerName string) ([]api.ContainerBackup, error) { if !r.HasExtension("container_backup") { return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension") } // Fetch the raw value backups := []api.ContainerBackup{} _, err := r.queryStruct("GET", fmt.Sprintf("/containers/%s/backups?recursion=1", url.QueryEscape(containerName)), nil, "", &backups) if err != nil { return nil, err } return backups, nil }
https://github.com/abh/geoip/blob/07cea4480daa3f28edd2856f2a0490fbe83842eb/geoip.go#L190-L230
func (gi *GeoIP) GetRecord(ip string) *GeoIPRecord { if gi.db == nil { return nil } cip := C.CString(ip) defer C.free(unsafe.Pointer(cip)) gi.mu.Lock() record := C.GeoIP_record_by_addr(gi.db, cip) gi.mu.Unlock() if record == nil { return nil } // defer C.free(unsafe.Pointer(record)) defer C.GeoIPRecord_delete(record) rec := new(GeoIPRecord) rec.CountryCode = C.GoString(record.country_code) rec.CountryCode3 = C.GoString(record.country_code3) rec.CountryName = C.GoString(record.country_name) rec.Region = C.GoString(record.region) rec.City = C.GoString(record.city) rec.PostalCode = C.GoString(record.postal_code) rec.Latitude = float32(record.latitude) rec.Longitude = float32(record.longitude) rec.CharSet = int(record.charset) rec.ContinentCode = C.GoString(record.continent_code) if gi.db.databaseType != C.GEOIP_CITY_EDITION_REV0 { /* DIRTY HACK BELOW: The GeoIPRecord struct in GeoIPCity.h contains an int32 union of metro_code and dma_code. The union is unnamed, so cgo names it anon0 and assumes it's a 4-byte array. */ union_int := (*int32)(unsafe.Pointer(&record.anon0)) rec.MetroCode = int(*union_int) rec.AreaCode = int(record.area_code) } return rec }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/config.go#L20-L36
func LoadConfig(path string) (*ClientConfig, error) { content, err := ioutil.ReadFile(path) if err != nil { return nil, err } var config ClientConfig err = json.Unmarshal(content, &config) if err != nil { return nil, err } config.Password, err = Decrypt(config.Password) if err != nil { return nil, err } config.RefreshToken, err = Decrypt(config.RefreshToken) return &config, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/types.go#L123-L125
func (t AuthChallengeSource) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1530-L1551
func PutHashTree(pachClient *client.APIClient, tree HashTree, tags ...string) (*pfs.Object, error) { r, w := io.Pipe() var eg errgroup.Group eg.Go(func() (retErr error) { defer func() { if err := w.Close(); err != nil && retErr == nil { retErr = err } }() return tree.Serialize(w) }) var treeRef *pfs.Object eg.Go(func() error { var err error treeRef, _, err = pachClient.PutObject(r, tags...) return err }) if err := eg.Wait(); err != nil { return nil, err } return treeRef, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L390-L392
func (p *RemoveBreakpointParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandRemoveBreakpoint, p, nil) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/migration.go#L21-L91
func LoadPreClusteringData(tx *sql.Tx) (*Dump, error) { // Sanitize broken foreign key references that might be around from the // time where we didn't enforce foreign key constraints. _, err := tx.Exec(` DELETE FROM containers_config WHERE container_id NOT IN (SELECT id FROM containers); DELETE FROM containers_devices WHERE container_id NOT IN (SELECT id FROM containers); DELETE FROM containers_devices_config WHERE container_device_id NOT IN (SELECT id FROM containers_devices); DELETE FROM containers_profiles WHERE container_id NOT IN (SELECT id FROM containers); DELETE FROM containers_profiles WHERE profile_id NOT IN (SELECT id FROM profiles); DELETE FROM images_aliases WHERE image_id NOT IN (SELECT id FROM images); DELETE FROM images_properties WHERE image_id NOT IN (SELECT id FROM images); DELETE FROM images_source WHERE image_id NOT IN (SELECT id FROM images); DELETE FROM networks_config WHERE network_id NOT IN (SELECT id FROM networks); DELETE FROM profiles_config WHERE profile_id NOT IN (SELECT id FROM profiles); DELETE FROM profiles_devices WHERE profile_id NOT IN (SELECT id FROM profiles); DELETE FROM profiles_devices_config WHERE profile_device_id NOT IN (SELECT id FROM profiles_devices); DELETE FROM storage_pools_config WHERE storage_pool_id NOT IN (SELECT id FROM storage_pools); DELETE FROM storage_volumes WHERE storage_pool_id NOT IN (SELECT id FROM storage_pools); DELETE FROM storage_volumes_config WHERE storage_volume_id NOT IN (SELECT id FROM storage_volumes); `) if err != nil { return nil, errors.Wrap(err, "failed to sanitize broken foreign key references") } // Dump all tables. dump := &Dump{ Schema: map[string][]string{}, Data: map[string][][]interface{}{}, } for _, table := range preClusteringTables { logger.Debugf("Loading data from table %s", table) data := [][]interface{}{} stmt := fmt.Sprintf("SELECT * FROM %s", table) rows, err := tx.Query(stmt) if err != nil { return nil, errors.Wrapf(err, "failed to fetch rows from %s", table) } columns, err := rows.Columns() if err != nil { rows.Close() return nil, errors.Wrapf(err, "failed to get columns of %s", table) } dump.Schema[table] = columns for rows.Next() { values := make([]interface{}, len(columns)) row := make([]interface{}, len(columns)) for i := range values { row[i] = &values[i] } err := rows.Scan(row...) if err != nil { rows.Close() return nil, errors.Wrapf(err, "failed to scan row from %s", table) } data = append(data, values) } err = rows.Err() if err != nil { rows.Close() return nil, errors.Wrapf(err, "error while fetching rows from %s", table) } rows.Close() dump.Data[table] = data } return dump, nil }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/apps_client.go#L152-L175
func (a *Client) PostApps(params *PostAppsParams) (*PostAppsOK, error) { // TODO: Validate the params before sending if params == nil { params = NewPostAppsParams() } result, err := a.transport.Submit(&runtime.ClientOperation{ ID: "PostApps", Method: "POST", PathPattern: "/apps", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json"}, Schemes: []string{"http", "https"}, Params: params, Reader: &PostAppsReader{formats: a.formats}, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return nil, err } return result.(*PostAppsOK), nil }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/actions/options.go#L19-L36
func (opts *Options) Validate() error { if len(opts.Name) == 0 { return errors.New("you must provide a name") } if len(opts.Actions) == 0 { return errors.New("you must provide at least one action name") } if opts.App.IsZero() { opts.App = meta.New(".") } if len(opts.Method) == 0 { opts.Method = "GET" } return nil }