_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/get_apps_app_parameters.go#L99-L102
func (o *GetAppsAppParams) WithHTTPClient(client *http.Client) *GetAppsAppParams { o.SetHTTPClient(client) return o }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nitro.go#L875-L985
func (m *Nitro) StoreToDisk(dir string, snap *Snapshot, concurr int, itmCallback ItemCallback) (err error) { var snapClosed bool defer func() { if !snapClosed { snap.Close() } }() if m.useMemoryMgmt { m.shutdownWg1.Add(1) defer m.shutdownWg1.Done() } datadir := filepath.Join(dir, "data") os.MkdirAll(datadir, 0755) shards := runtime.NumCPU() writers := make([]FileWriter, shards) files := make([]string, shards) defer func() { for _, w := range writers { if w != nil { w.Close() } } }() for shard := 0; shard < shards; shard++ { w := m.newFileWriter(m.fileType) file := fmt.Sprintf("shard-%d", shard) datafile := filepath.Join(datadir, file) if err := w.Open(datafile); err != nil { return err } writers[shard] = w files[shard] = file } // Initialize and setup delta processing if m.useDeltaFiles { deltaWriters := make([]FileWriter, m.numWriters()) deltaFiles := make([]string, m.numWriters()) defer func() { for _, w := range deltaWriters { if w != nil { w.Close() } } }() deltadir := filepath.Join(dir, "delta") os.MkdirAll(deltadir, 0755) for id := 0; id < m.numWriters(); id++ { dw := m.newFileWriter(m.fileType) file := fmt.Sprintf("shard-%d", id) deltafile := filepath.Join(deltadir, file) if err = dw.Open(deltafile); err != nil { return err } deltaWriters[id] = dw deltaFiles[id] = file } if err = m.changeDeltaWrState(dwStateInit, deltaWriters, snap); err != nil { return err } // Create a placeholder snapshot object. We are decoupled from holding snapshot items // The fakeSnap object is to use the same iterator without any special handling for // usual refcount based freeing. snap.Close() snapClosed = true fakeSnap := *snap fakeSnap.refCount = 1 snap = &fakeSnap defer func() { if err = m.changeDeltaWrState(dwStateTerminate, nil, nil); err == nil { bs, _ := json.Marshal(deltaFiles) err = ioutil.WriteFile(filepath.Join(deltadir, "files.json"), bs, 0660) } }() } visitorCallback := func(itm *Item, shard int) error { if m.hasShutdown { return ErrShutdown } w := writers[shard] if err := w.WriteItem(itm); err != nil { return err } if itmCallback != nil { itmCallback(&ItemEntry{itm: itm, n: nil}) } return nil } if err = m.Visitor(snap, visitorCallback, shards, concurr); err == nil { bs, _ := json.Marshal(files) err = ioutil.WriteFile(filepath.Join(datadir, "files.json"), bs, 0660) } return err }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/cmpopts/ignore.go#L184-L207
func IgnoreMapEntries(discardFunc interface{}) cmp.Option { vf := reflect.ValueOf(discardFunc) if !function.IsType(vf.Type(), function.KeyValuePredicate) || vf.IsNil() { panic(fmt.Sprintf("invalid discard function: %T", discardFunc)) } return cmp.FilterPath(func(p cmp.Path) bool { mi, ok := p.Index(-1).(cmp.MapIndex) if !ok { return false } if !mi.Key().Type().AssignableTo(vf.Type().In(0)) || !mi.Type().AssignableTo(vf.Type().In(1)) { return false } k := mi.Key() vx, vy := mi.Values() if vx.IsValid() && vf.Call([]reflect.Value{k, vx})[0].Bool() { return true } if vy.IsValid() && vf.Call([]reflect.Value{k, vy})[0].Bool() { return true } return false }, cmp.Ignore()) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/cachestorage/cachestorage.go#L50-L55
func DeleteEntry(cacheID CacheID, request string) *DeleteEntryParams { return &DeleteEntryParams{ CacheID: cacheID, Request: request, } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/benchmark/options.go#L48-L52
func WithTimeout(timeout time.Duration) Option { return func(opts *options) { opts.timeout = timeout } }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L729-L757
func txFunCall(st *State) { // Everything in our lvars up to the current tip is our argument list mark := st.CurrentMark() tip := st.stack.Size() - 1 var args []reflect.Value if tip-mark-1 > 0 { args = make([]reflect.Value, tip-mark-1) for i := mark + 1; tip > i; i++ { v, _ := st.stack.Get(i) args[i-mark] = reflect.ValueOf(v) } } x := st.sa st.sa = nil if x == nil { // Do nothing, just advance st.Advance() return } v := reflect.ValueOf(x) if v.Type().Kind() == reflect.Func { fun := reflect.ValueOf(x) invokeFuncSingleReturn(st, fun, args) } st.Advance() }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L656-L661
func (o *ListComplex128Option) Set(value string) error { val := Complex128Option{} val.Set(value) *o = append(*o, val) return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L234-L251
func (f *FakeClient) CreateStatus(owner, repo, SHA string, s github.Status) error { if f.CreatedStatuses == nil { f.CreatedStatuses = make(map[string][]github.Status) } statuses := f.CreatedStatuses[SHA] var updated bool for i := range statuses { if statuses[i].Context == s.Context { statuses[i] = s updated = true } } if !updated { statuses = append(statuses, s) } f.CreatedStatuses[SHA] = statuses return nil }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L906-L949
func (loc *CurrentUserLocator) CloudAccounts(awsAccessKeyId string, awsAccountNumber string, awsSecretAccessKey string, cloudVendorName string) error { if awsAccessKeyId == "" { return fmt.Errorf("awsAccessKeyId is required") } if awsAccountNumber == "" { return fmt.Errorf("awsAccountNumber is required") } if awsSecretAccessKey == "" { return fmt.Errorf("awsSecretAccessKey is required") } if cloudVendorName == "" { return fmt.Errorf("cloudVendorName is required") } var params rsapi.APIParams var p rsapi.APIParams p = rsapi.APIParams{ "aws_access_key_id": awsAccessKeyId, "aws_account_number": awsAccountNumber, "aws_secret_access_key": awsSecretAccessKey, "cloud_vendor_name": cloudVendorName, } uri, err := loc.ActionPath("CurrentUser", "cloud_accounts") if err != nil { return err } req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p) if err != nil { return err } resp, err := loc.api.PerformRequest(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { respBody, _ := ioutil.ReadAll(resp.Body) sr := string(respBody) if sr != "" { sr = ": " + sr } return fmt.Errorf("invalid response %s%s", resp.Status, sr) } return nil }
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L560-L593
func (c *Consumer) rebalance() (map[string][]int32, error) { memberID, _ := c.membership() sarama.Logger.Printf("cluster/consumer %s rebalance\n", memberID) allTopics, err := c.client.Topics() if err != nil { return nil, err } c.extraTopics = c.selectExtraTopics(allTopics) sort.Strings(c.extraTopics) // Re-join consumer group strategy, err := c.joinGroup() switch { case err == sarama.ErrUnknownMemberId: c.membershipMu.Lock() c.memberID = "" c.membershipMu.Unlock() return nil, err case err != nil: return nil, err } // Sync consumer group state, fetch subscriptions subs, err := c.syncGroup(strategy) switch { case err == sarama.ErrRebalanceInProgress: return nil, err case err != nil: _ = c.leaveGroup() return nil, err } return subs, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/metrics.go#L247-L250
func ReportEventReceived(n int) { pendingEventsGauge.Sub(float64(n)) totalEventsCounter.Add(float64(n)) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_pools_utils.go#L297-L307
func dbStoragePoolDeleteAndUpdateCache(db *db.Cluster, poolName string) error { _, err := db.StoragePoolDelete(poolName) if err != nil { return err } // Update the storage drivers cache in api_1.0.go. storagePoolDriversCacheUpdate(db) return err }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/file-server/server.go#L45-L137
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { urlPath := r.URL.Path if !strings.HasPrefix(urlPath, "/") { urlPath = "/" + urlPath r.URL.Path = urlPath } p := path.Clean(urlPath) if s.root != "" { if p = strings.TrimPrefix(p, s.root); len(p) >= len(r.URL.Path) { s.httpError(w, r, errNotFound) return } } if s.IndexPage != "" && strings.HasSuffix(r.URL.Path, s.IndexPage) { redirect(w, r, "./") return } if (s.Hasher != nil && !s.NoHashQueryStrings) || (s.Hasher != nil && s.NoHashQueryStrings && len(r.URL.RawQuery) == 0) { cPath := s.canonicalPath(p) h, cont, err := s.hash(cPath) switch err { case errNotRegularFile: // continue as usual if it is not a regular file case nil: if hPath := s.hashedPath(cPath, h); hPath != p { redirect(w, r, path.Join(s.root, hPath)) return } if s.RedirectTrailingSlash && urlPath[len(urlPath)-1] == '/' { redirect(w, r, path.Join(s.root, p)) return } p = cPath r.URL.Path = path.Join(s.root, cPath) default: if !cont { s.httpError(w, r, err) return } } } f, err := s.open(p) if err != nil { s.httpError(w, r, err) return } defer f.Close() d, err := f.Stat() if err != nil { s.httpError(w, r, err) return } if s.RedirectTrailingSlash { url := r.URL.Path if d.IsDir() { if url[len(url)-1] != '/' { redirect(w, r, url+"/") return } } else { if url[len(url)-1] == '/' { redirect(w, r, "../"+path.Base(url)) return } } } if d.IsDir() { index := strings.TrimSuffix(p, "/") + s.IndexPage ff, err := s.open(index) if err == nil { defer ff.Close() dd, err := ff.Stat() if err == nil { p = index d = dd f = ff } } } if d.IsDir() { s.httpError(w, r, errNotFound) return } http.ServeContent(w, r, d.Name(), d.ModTime(), f) }
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L44-L47
func (now *Now) BeginningOfMonth() time.Time { y, m, _ := now.Date() return time.Date(y, m, 1, 0, 0, 0, 0, now.Location()) }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/service_mock.go#L33-L36
func (s *ServiceMock) Stop(pid int) (bool, error) { s.ServiceStopCount++ return s.ServiceStopResult, s.ServiceStopError }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_btrfs.go#L2270-L2299
func btrfsSnapshot(source string, dest string, readonly bool) error { var output string var err error if readonly { output, err = shared.RunCommand( "btrfs", "subvolume", "snapshot", "-r", source, dest) } else { output, err = shared.RunCommand( "btrfs", "subvolume", "snapshot", source, dest) } if err != nil { return fmt.Errorf( "subvolume snapshot failed, source=%s, dest=%s, output=%s", source, dest, output, ) } return err }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/collection/transaction.go#L360-L363
func (s *stmReadCommitted) commit() *v3.TxnResponse { s.rset = nil return s.stm.commit() }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5142-L5150
func (u LedgerKey) MustData() LedgerKeyData { val, ok := u.GetData() if !ok { panic("arm Data is not set") } return val }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L129-L132
func (m *Map) GetBool(name string) bool { m.schema.assertKeyType(name, Bool) return shared.IsTrue(m.GetRaw(name)) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/membership/member.go#L54-L74
func NewMember(name string, peerURLs types.URLs, clusterName string, now *time.Time) *Member { m := &Member{ RaftAttributes: RaftAttributes{PeerURLs: peerURLs.StringSlice()}, Attributes: Attributes{Name: name}, } var b []byte sort.Strings(m.PeerURLs) for _, p := range m.PeerURLs { b = append(b, []byte(p)...) } b = append(b, []byte(clusterName)...) if now != nil { b = append(b, []byte(fmt.Sprintf("%d", now.Unix()))...) } hash := sha1.Sum(b) m.ID = types.ID(binary.BigEndian.Uint64(hash[:8])) return m }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/lease.go#L363-L398
func (l *lessor) closeRequireLeader() { l.mu.Lock() defer l.mu.Unlock() for _, ka := range l.keepAlives { reqIdxs := 0 // find all required leader channels, close, mark as nil for i, ctx := range ka.ctxs { md, ok := metadata.FromOutgoingContext(ctx) if !ok { continue } ks := md[rpctypes.MetadataRequireLeaderKey] if len(ks) < 1 || ks[0] != rpctypes.MetadataHasLeader { continue } close(ka.chs[i]) ka.chs[i] = nil reqIdxs++ } if reqIdxs == 0 { continue } // remove all channels that required a leader from keepalive newChs := make([]chan<- *LeaseKeepAliveResponse, len(ka.chs)-reqIdxs) newCtxs := make([]context.Context, len(newChs)) newIdx := 0 for i := range ka.chs { if ka.chs[i] == nil { continue } newChs[newIdx], newCtxs[newIdx] = ka.chs[i], ka.ctxs[newIdx] newIdx++ } ka.chs, ka.ctxs = newChs, newCtxs } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L6707-L6847
func (c *containerLXC) createUnixDevice(prefix string, m types.Device, defaultMode bool) ([]string, error) { var err error var major, minor int // Extra checks for nesting if c.state.OS.RunningInUserNS { for key, value := range m { if shared.StringInSlice(key, []string{"major", "minor", "mode", "uid", "gid"}) && value != "" { return nil, fmt.Errorf("The \"%s\" property may not be set when adding a device to a nested container", key) } } } srcPath := m["source"] if srcPath == "" { srcPath = m["path"] } srcPath = shared.HostPath(srcPath) // Get the major/minor of the device we want to create if m["major"] == "" && m["minor"] == "" { // If no major and minor are set, use those from the device on the host _, major, minor, err = deviceGetAttributes(srcPath) if err != nil { return nil, fmt.Errorf("Failed to get device attributes for %s: %s", m["path"], err) } } else if m["major"] == "" || m["minor"] == "" { return nil, fmt.Errorf("Both major and minor must be supplied for device: %s", m["path"]) } else { major, err = strconv.Atoi(m["major"]) if err != nil { return nil, fmt.Errorf("Bad major %s in device %s", m["major"], m["path"]) } minor, err = strconv.Atoi(m["minor"]) if err != nil { return nil, fmt.Errorf("Bad minor %s in device %s", m["minor"], m["path"]) } } // Get the device mode mode := os.FileMode(0660) if m["mode"] != "" { tmp, err := deviceModeOct(m["mode"]) if err != nil { return nil, fmt.Errorf("Bad mode %s in device %s", m["mode"], m["path"]) } mode = os.FileMode(tmp) } else if !defaultMode { mode, err = shared.GetPathMode(srcPath) if err != nil { errno, isErrno := shared.GetErrno(err) if !isErrno || errno != syscall.ENOENT { return nil, fmt.Errorf("Failed to retrieve mode of device %s: %s", m["path"], err) } mode = os.FileMode(0660) } } if m["type"] == "unix-block" { mode |= syscall.S_IFBLK } else { mode |= syscall.S_IFCHR } // Get the device owner uid := 0 gid := 0 if m["uid"] != "" { uid, err = strconv.Atoi(m["uid"]) if err != nil { return nil, fmt.Errorf("Invalid uid %s in device %s", m["uid"], m["path"]) } } if m["gid"] != "" { gid, err = strconv.Atoi(m["gid"]) if err != nil { return nil, fmt.Errorf("Invalid gid %s in device %s", m["gid"], m["path"]) } } // Create the devices directory if missing if !shared.PathExists(c.DevicesPath()) { os.Mkdir(c.DevicesPath(), 0711) if err != nil { return nil, fmt.Errorf("Failed to create devices path: %s", err) } } destPath := m["path"] if destPath == "" { destPath = m["source"] } relativeDestPath := strings.TrimPrefix(destPath, "/") devName := fmt.Sprintf("%s.%s", strings.Replace(prefix, "/", "-", -1), strings.Replace(relativeDestPath, "/", "-", -1)) devPath := filepath.Join(c.DevicesPath(), devName) // Create the new entry if !c.state.OS.RunningInUserNS { encoded_device_number := (minor & 0xff) | (major << 8) | ((minor & ^0xff) << 12) if err := syscall.Mknod(devPath, uint32(mode), encoded_device_number); err != nil { return nil, fmt.Errorf("Failed to create device %s for %s: %s", devPath, m["path"], err) } if err := os.Chown(devPath, uid, gid); err != nil { return nil, fmt.Errorf("Failed to chown device %s: %s", devPath, err) } // Needed as mknod respects the umask if err := os.Chmod(devPath, mode); err != nil { return nil, fmt.Errorf("Failed to chmod device %s: %s", devPath, err) } idmapset, err := c.CurrentIdmap() if err != nil { return nil, err } if idmapset != nil { if err := idmapset.ShiftFile(devPath); err != nil { // uidshift failing is weird, but not a big problem. Log and proceed logger.Debugf("Failed to uidshift device %s: %s\n", m["path"], err) } } } else { f, err := os.Create(devPath) if err != nil { return nil, err } f.Close() err = deviceMountDisk(srcPath, devPath, false, false, "") if err != nil { return nil, err } } return []string{devPath, relativeDestPath}, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/plugin/vault/pachyderm/backend.go#L16-L44
func Factory(ctx context.Context, c *logical.BackendConfig) (logical.Backend, error) { result := &backend{} result.Backend = &framework.Backend{ BackendType: logical.TypeLogical, PathsSpecial: &logical.Paths{ Unauthenticated: []string{"login"}, }, Paths: []*framework.Path{ result.configPath(), result.loginPath(), result.versionPath(), }, Secrets: []*framework.Secret{{ Type: "pachyderm_tokens", Fields: map[string]*framework.FieldSchema{ "user_token": &framework.FieldSchema{ Type: framework.TypeString, Description: "Pachyderm authentication tokens", }, }, Renew: result.Renew, Revoke: result.Revoke, }}, } if err := result.Setup(ctx, c); err != nil { return nil, err } return result, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/snapshot_sender.go#L149-L185
func (s *snapshotSender) post(req *http.Request) (err error) { ctx, cancel := context.WithCancel(context.Background()) req = req.WithContext(ctx) defer cancel() type responseAndError struct { resp *http.Response body []byte err error } result := make(chan responseAndError, 1) go func() { resp, err := s.tr.pipelineRt.RoundTrip(req) if err != nil { result <- responseAndError{resp, nil, err} return } // close the response body when timeouts. // prevents from reading the body forever when the other side dies right after // successfully receives the request body. time.AfterFunc(snapResponseReadTimeout, func() { httputil.GracefulClose(resp) }) body, err := ioutil.ReadAll(resp.Body) result <- responseAndError{resp, body, err} }() select { case <-s.stopc: return errStopped case r := <-result: if r.err != nil { return r.err } return checkPostResponse(r.resp, r.body, req, s.to) } }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L351-L396
func AllocateIDRange(c context.Context, kind string, parent *Key, start, end int64) (err error) { if kind == "" { return errors.New("datastore: AllocateIDRange given an empty kind") } if start < 1 || end < 1 { return errors.New("datastore: AllocateIDRange start and end must both be greater than 0") } if start > end { return errors.New("datastore: AllocateIDRange start must be before end") } req := &pb.AllocateIdsRequest{ ModelKey: keyToProto("", NewIncompleteKey(c, kind, parent)), Max: proto.Int64(end), } res := &pb.AllocateIdsResponse{} if err := internal.Call(c, "datastore_v3", "AllocateIds", req, res); err != nil { return err } // Check for collisions, i.e. existing entities with IDs in this range. // We could do this before the allocation, but we'd still have to do it // afterward as well to catch the race condition where an entity is inserted // after that initial check but before the allocation. Skip the up-front check // and just do it once. q := NewQuery(kind).Filter("__key__ >=", NewKey(c, kind, "", start, parent)). Filter("__key__ <=", NewKey(c, kind, "", end, parent)).KeysOnly().Limit(1) keys, err := q.GetAll(c, nil) if err != nil { return err } if len(keys) != 0 { return &KeyRangeCollisionError{start: start, end: end} } // Check for a race condition, i.e. cases where the datastore may have // cached ID batches that contain IDs in this range. if start < res.GetStart() { return &KeyRangeContentionError{start: start, end: end} } return nil }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/axe/queue.go#L46-L58
func (q *Queue) Enqueue(name string, data Model, delay time.Duration) (*Job, error) { // copy store store := q.store.Copy() defer store.Close() // enqueue job job, err := Enqueue(store, name, data, delay) if err != nil { return nil, err } return job, nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/allow_trust.go#L50-L53
func (m Authorize) MutateAllowTrust(o *xdr.AllowTrustOp) error { o.Authorize = m.Value return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/easyjson.go#L764-L768
func (v *GetCategoriesReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTracing6(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/db/lex.go#L16-L22
func entityType(pkg string, entity string) string { typ := lex.Capital(entity) if pkg != "db" { typ = pkg + "." + typ } return typ }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/client.go#L654-L670
func IsConnCanceled(err error) bool { if err == nil { return false } // >= gRPC v1.10.x s, ok := status.FromError(err) if ok { // connection is canceled or server has already closed the connection return s.Code() == codes.Canceled || s.Message() == "transport is closing" } // >= gRPC v1.10.x if err == context.Canceled { return true } // <= gRPC v1.7.x returns 'errors.New("grpc: the client connection is closing")' return strings.Contains(err.Error(), "grpc: the client connection is closing") }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcauth/tcauth.go#L100-L104
func (auth *Auth) Ping() error { cd := tcclient.Client(*auth) _, _, err := (&cd).APICall(nil, "GET", "/ping", nil, nil) return err }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssd/codegen_client.go#L376-L378
func (r *Template) Locator(api *API) *TemplateLocator { return api.TemplateLocator(r.Href) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/easyjson.go#L71-L75
func (v StopObservingParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoBackgroundservice(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L344-L361
func (g *Gateway) Reset(cert *shared.CertInfo) error { err := g.Shutdown() if err != nil { return err } err = os.RemoveAll(filepath.Join(g.db.Dir(), "global")) if err != nil { return err } err = g.db.Transaction(func(tx *db.NodeTx) error { return tx.RaftNodesReplace(nil) }) if err != nil { return err } g.cert = cert return g.init() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/resolve.go#L12-L41
func ResolveTarget(cluster *db.Cluster, target string) (string, error) { address := "" err := cluster.Transaction(func(tx *db.ClusterTx) error { name, err := tx.NodeName() if err != nil { return err } if target == name { return nil } node, err := tx.NodeByName(target) if err != nil { if err == db.ErrNoSuchObject { return fmt.Errorf("No cluster member called '%s'", target) } return err } if node.Name != name { address = node.Address } return nil }) return address, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L984-L993
func (p *QuerySelectorAllParams) Do(ctx context.Context) (nodeIds []cdp.NodeID, err error) { // execute var res QuerySelectorAllReturns err = cdp.Execute(ctx, CommandQuerySelectorAll, p, &res) if err != nil { return nil, err } return res.NodeIds, nil }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_actions.go#L77-L102
func (s *Selection) UploadFile(filename string) error { absFilePath, err := filepath.Abs(filename) if err != nil { return fmt.Errorf("failed to find absolute path for filename: %s", err) } return s.forEachElement(func(selectedElement element.Element) error { tagName, err := selectedElement.GetName() if err != nil { return fmt.Errorf("failed to determine tag name of %s: %s", s, err) } if tagName != "input" { return fmt.Errorf("element for %s is not an input element", s) } inputType, err := selectedElement.GetAttribute("type") if err != nil { return fmt.Errorf("failed to determine type attribute of %s: %s", s, err) } if inputType != "file" { return fmt.Errorf("element for %s is not a file uploader", s) } if err := selectedElement.Value(absFilePath); err != nil { return fmt.Errorf("failed to enter text into %s: %s", s, err) } return nil }) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plank/controller.go#L144-L148
func (c *Controller) incrementNumPendingJobs(job string) { c.lock.Lock() defer c.lock.Unlock() c.pendingJobs[job]++ }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/firewallrule.go#L77-L82
func (c *Client) DeleteFirewallRule(dcID string, serverID string, nicID string, fwID string) (*http.Header, error) { url := fwrulePath(dcID, serverID, nicID, fwID) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &http.Header{} err := c.client.Delete(url, ret, http.StatusAccepted) return ret, err }
https://github.com/go-bongo/bongo/blob/761759e31d8fed917377aa7085db01d218ce50d8/cascade.go#L232-L275
func MapFromCascadeProperties(properties []string, doc Document) map[string]interface{} { data := make(map[string]interface{}) for _, prop := range properties { split := strings.Split(prop, ".") if len(split) == 1 { data[prop], _ = dotaccess.Get(doc, prop) } else { actualProp := split[len(split)-1] split := append([]string{}, split[:len(split)-1]...) curData := data for _, s := range split { if _, ok := curData[s]; ok { if mapped, ok := curData[s].(map[string]interface{}); ok { curData = mapped } else { panic("Cannot access non-map property via dot notation") } } else { curData[s] = make(map[string]interface{}) if mapped, ok := curData[s].(map[string]interface{}); ok { curData = mapped } else { panic("Cannot access non-map property via dot notation") } } } val, _ := dotaccess.Get(doc, prop) // if bsonId, ok := val.(bson.ObjectId); ok { // if !bsonId.Valid() { // curData[actualProp] = "" // continue // } // } curData[actualProp] = val } } return data }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L323-L327
func (v *TakeTypeProfileReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler2(&r, v) return r.Error() }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcqueue/types.go#L2473-L2476
func (this *PostArtifactResponse) MarshalJSON() ([]byte, error) { x := json.RawMessage(*this) return (&x).MarshalJSON() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/spyglass/lenses/buildlog/lens.go#L120-L144
func (lens Lens) Body(artifacts []lenses.Artifact, resourceDir string, data string) string { buildLogsView := BuildLogsView{ LogViews: []LogArtifactView{}, RawGetAllRequests: make(map[string]string), RawGetMoreRequests: make(map[string]string), } // Read log artifacts and construct template structs for _, a := range artifacts { av := LogArtifactView{ ArtifactName: a.JobPath(), ArtifactLink: a.CanonicalLink(), } lines, err := logLinesAll(a) if err != nil { logrus.WithError(err).Info("Error reading log.") continue } av.LineGroups = groupLines(highlightLines(lines, 0)) av.ViewAll = true buildLogsView.LogViews = append(buildLogsView.LogViews, av) } return executeTemplate(resourceDir, "body", buildLogsView) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L6372-L6379
func (r *NetworkGateway) Locator(api *API) *NetworkGatewayLocator { for _, l := range r.Links { if l["rel"] == "self" { return api.NetworkGatewayLocator(l["href"]) } } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L2575-L2579
func (v AttachToBrowserTargetReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget30(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L13445-L13447
func (api *API) SubnetLocator(href string) *SubnetLocator { return &SubnetLocator{Href(href), api} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L575-L579
func (v ReplaySnapshotParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoLayertree5(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image.go#L27-L37
func newImage(ctx context.Context, sys *types.SystemContext, ref dockerReference) (types.ImageCloser, error) { s, err := newImageSource(ctx, sys, ref) if err != nil { return nil, err } img, err := image.FromSource(ctx, sys, s) if err != nil { return nil, err } return &Image{ImageCloser: img, src: s}, nil }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L100-L104
func CharAtF(index int) func(string) string { return func(s string) string { return CharAt(s, index) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/systeminfo/easyjson.go#L93-L97
func (v ProcessInfo) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoSysteminfo(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L97-L100
func (img *IplImage) ReleaseHeader() { img_c := (*C.IplImage)(img) C.cvReleaseImageHeader(&img_c) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/backgroundservice.go#L35-L37
func (p *StartObservingParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandStartObserving, p, nil) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/git/git.go#L136-L181
func (c *Client) Clone(repo string) (*Repo, error) { c.lockRepo(repo) defer c.unlockRepo(repo) base := c.base user, pass := c.getCredentials() if user != "" && pass != "" { base = fmt.Sprintf("https://%s:%s@%s", user, pass, github) } cache := filepath.Join(c.dir, repo) + ".git" if _, err := os.Stat(cache); os.IsNotExist(err) { // Cache miss, clone it now. c.logger.Infof("Cloning %s for the first time.", repo) if err := os.MkdirAll(filepath.Dir(cache), os.ModePerm); err != nil && !os.IsExist(err) { return nil, err } remote := fmt.Sprintf("%s/%s", base, repo) if b, err := retryCmd(c.logger, "", c.git, "clone", "--mirror", remote, cache); err != nil { return nil, fmt.Errorf("git cache clone error: %v. output: %s", err, string(b)) } } else if err != nil { return nil, err } else { // Cache hit. Do a git fetch to keep updated. c.logger.Infof("Fetching %s.", repo) if b, err := retryCmd(c.logger, cache, c.git, "fetch"); err != nil { return nil, fmt.Errorf("git fetch error: %v. output: %s", err, string(b)) } } t, err := ioutil.TempDir("", "git") if err != nil { return nil, err } if b, err := exec.Command(c.git, "clone", cache, t).CombinedOutput(); err != nil { return nil, fmt.Errorf("git repo clone error: %v. output: %s", err, string(b)) } return &Repo{ Dir: t, logger: c.logger, git: c.git, base: base, repo: repo, user: user, pass: pass, }, nil }
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/parse.go#L480-L515
func canParse(t reflect.Type) (parseable, boolean, multiple bool) { parseable = scalar.CanParse(t) boolean = isBoolean(t) if parseable { return } // Look inside pointer types if t.Kind() == reflect.Ptr { t = t.Elem() } // Look inside slice types if t.Kind() == reflect.Slice { multiple = true t = t.Elem() } parseable = scalar.CanParse(t) boolean = isBoolean(t) if parseable { return } // Look inside pointer types (again, in case of []*Type) if t.Kind() == reflect.Ptr { t = t.Elem() } parseable = scalar.CanParse(t) boolean = isBoolean(t) if parseable { return } return false, false, false }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/server/api_server.go#L2035-L2097
func (a *apiServer) inspectPipeline(pachClient *client.APIClient, name string) (*pps.PipelineInfo, error) { if err := checkLoggedIn(pachClient); err != nil { return nil, err } kubeClient := a.env.GetKubeClient() name, ancestors := ancestry.Parse(name) pipelinePtr := pps.EtcdPipelineInfo{} if err := a.pipelines.ReadOnly(pachClient.Ctx()).Get(name, &pipelinePtr); err != nil { if col.IsErrNotFound(err) { return nil, fmt.Errorf("pipeline \"%s\" not found", name) } return nil, err } pipelinePtr.SpecCommit.ID = ancestry.Add(pipelinePtr.SpecCommit.ID, ancestors) pipelineInfo, err := ppsutil.GetPipelineInfo(pachClient, &pipelinePtr, true) if err != nil { return nil, err } if pipelineInfo.Service != nil { rcName := ppsutil.PipelineRcName(pipelineInfo.Pipeline.Name, pipelineInfo.Version) if err != nil { return nil, err } service, err := kubeClient.CoreV1().Services(a.namespace).Get(fmt.Sprintf("%s-user", rcName), metav1.GetOptions{}) if err != nil { if !isNotFoundErr(err) { return nil, err } } else { pipelineInfo.Service.IP = service.Spec.ClusterIP } } var hasGitInput bool pps.VisitInput(pipelineInfo.Input, func(input *pps.Input) { if input.Git != nil { hasGitInput = true } }) if hasGitInput { pipelineInfo.GithookURL = "pending" svc, err := getGithookService(kubeClient, a.namespace) if err != nil { return pipelineInfo, nil } numIPs := len(svc.Status.LoadBalancer.Ingress) if numIPs == 0 { // When running locally, no external IP is set return pipelineInfo, nil } if numIPs != 1 { return nil, fmt.Errorf("unexpected number of external IPs set for githook service") } ingress := svc.Status.LoadBalancer.Ingress[0] if ingress.IP != "" { // GKE load balancing pipelineInfo.GithookURL = githook.URLFromDomain(ingress.IP) } else if ingress.Hostname != "" { // AWS load balancing pipelineInfo.GithookURL = githook.URLFromDomain(ingress.Hostname) } } return pipelineInfo, nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/transaction.go#L25-L28
func RegisterTransactionSetter(f interface{}) { v := reflect.ValueOf(f) transactionSetters[v.Type().In(0)] = v }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/functions/depot.go#L15-L17
func NewFuncDepot(namespace string) *FuncDepot { return &FuncDepot{namespace, make(map[string]reflect.Value)} }
https://github.com/adamzy/cedar-go/blob/80a9c64b256db37ac20aff007907c649afb714f1/io.go#L13-L23
func (da *Cedar) Save(out io.Writer, dataType string) error { switch dataType { case "gob", "GOB": dataEecoder := gob.NewEncoder(out) return dataEecoder.Encode(da.cedar) case "json", "JSON": dataEecoder := json.NewEncoder(out) return dataEecoder.Encode(da.cedar) } return ErrInvalidDataType }
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/memory.go#L158-L168
func (b *ChannelMemoryBackend) Start() { b.mu.Lock() defer b.mu.Unlock() // Launch the goroutine unless it's already running. if b.running != true { b.running = true b.stopWg.Add(1) go b.process() } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L307-L311
func (v SetVariableValueParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger3(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L427-L443
func (p *PubSub) handleRemoveSubscription(sub *Subscription) { subs := p.myTopics[sub.topic] if subs == nil { return } sub.err = fmt.Errorf("subscription cancelled by calling sub.Cancel()") close(sub.ch) delete(subs, sub) if len(subs) == 0 { delete(p.myTopics, sub.topic) p.announce(sub.topic, false) p.rt.Leave(sub.topic) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L1756-L1760
func (v *EventScreenshotRequested) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoOverlay17(&r, v) return r.Error() }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/get_apps_parameters.go#L81-L84
func (o *GetAppsParams) WithContext(ctx context.Context) *GetAppsParams { o.SetContext(ctx) return o }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqls/manager.go#L196-L204
func (w *workManager) isInputDone() bool { if w.inDirs != nil { return false } if w.inSeqs != nil { return false } return true }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/ash/enforcer.go#L10-L12
func E(name string, m fire.Matcher, h fire.Handler) *Enforcer { return fire.C(name, m, h) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/exec/exec.go#L141-L154
func Command(name string, arg ...string) *Cmd { cmd := &Cmd{ Path: name, Args: append([]string{name}, arg...), } if filepath.Base(name) == name { if lp, err := exec.LookPath(name); err != nil { cmd.lookPathErr = err } else { cmd.Path = lp } } return cmd }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/frame.go#L79-L86
func (fh FrameHeader) MarshalJSON() ([]byte, error) { s := struct { ID uint32 `json:"id"` MsgType messageType `json:"msgType"` Size uint16 `json:"size"` }{fh.ID, fh.messageType, fh.size} return json.Marshal(s) }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cv.go#L89-L94
func Canny(image, edges *IplImage, threshold1, threshold2 float64, aperture_size int) { C.cvCanny(unsafe.Pointer(image), unsafe.Pointer(edges), C.double(threshold1), C.double(threshold2), C.int(aperture_size), ) }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/api/api_client.go#L207-L209
func (c Client) JSON(method, path string, query url.Values, body io.Reader, response interface{}) (err error) { return c.JSONContext(nil, method, path, query, body, response) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/easyjson.go#L378-L382
func (v RemoveXHRBreakpointParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomdebugger4(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vm.go#L773-L804
func (v *VM) Delete(options VmDeleteOption) error { var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE var err C.VixError = C.VIX_OK if (options & VMDELETE_FORCE) != 0 { vmxPath, err := v.VmxPath() if err != nil { return err } err = os.RemoveAll(vmxPath + ".lck") if err != nil { return err } } jobHandle = C.VixVM_Delete(v.handle, C.VixVMDeleteOptions(options), nil, nil) defer C.Vix_ReleaseHandle(jobHandle) err = C.vix_job_wait(jobHandle) if C.VIX_OK != err { return &Error{ Operation: "vm.Delete", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } C.Vix_ReleaseHandle(v.handle) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L1209-L1213
func (v ScriptTypeProfile) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoProfiler14(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/commands.go#L209-L239
func (a *API) ParseCommandAndFlags(cmd, hrefPrefix string, values ActionCommands) (*CommandTarget, []string, error) { resource, vars, err := a.parseResource(cmd, hrefPrefix, values) if err != nil { return nil, nil, err } var action *metadata.Action elems := strings.Split(cmd, " ") actionName := elems[len(elems)-1] for _, a := range resource.Actions { if a.Name == actionName { action = a break } } if action == nil { supported := make([]string, len(resource.Actions)) for i, a := range resource.Actions { supported[i] = a.Name } return nil, nil, fmt.Errorf("Unknown %s action '%s'. Supported actions are: %s", resource.Name, actionName, strings.Join(supported, ", ")) } path, err := action.URL(vars) if err != nil { return nil, nil, err } flags := values[cmd] return &CommandTarget{resource, action, path, flags.Href}, flags.Params, nil }
https://github.com/bluekeyes/hatpear/blob/ffb42d5bb417aa8e12b3b7ff73d028b915dafa10/hatpear.go#L39-L45
func Get(r *http.Request) error { errptr, ok := r.Context().Value(errorKey).(*error) if !ok { return nil } return *errptr }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L3451-L3455
func (v MediaQuery) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss30(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L660-L779
func Delete(app *App, evt *event.Event, requestID string) error { w := evt isSwapped, swappedWith, err := router.IsSwapped(app.GetName()) if err != nil { return errors.Wrap(err, "unable to check if app is swapped") } if isSwapped { return errors.Errorf("application is swapped with %q, cannot remove it", swappedWith) } appName := app.Name fmt.Fprintf(w, "---- Removing application %q...\n", appName) var hasErrors bool defer func() { var problems string if hasErrors { problems = " Some errors occurred during removal." } fmt.Fprintf(w, "---- Done removing application.%s\n", problems) }() logErr := func(msg string, err error) { msg = fmt.Sprintf("%s: %s", msg, err) fmt.Fprintf(w, "%s\n", msg) log.Errorf("[delete-app: %s] %s", appName, msg) hasErrors = true } prov, err := app.getProvisioner() if err != nil { return err } err = prov.Destroy(app) if err != nil { logErr("Unable to destroy app in provisioner", err) } err = registry.RemoveAppImages(appName) if err != nil { log.Errorf("failed to remove images from registry for app %s: %s", appName, err) } if cleanProv, ok := prov.(provision.CleanImageProvisioner); ok { var imgs []string imgs, err = image.ListAppImages(appName) if err != nil { log.Errorf("failed to list images for app %s: %s", appName, err) } var imgsBuild []string imgsBuild, err = image.ListAppBuilderImages(appName) if err != nil { log.Errorf("failed to list build images for app %s: %s", appName, err) } for _, img := range append(imgs, imgsBuild...) { err = cleanProv.CleanImage(appName, img) if err != nil { log.Errorf("failed to remove image from provisioner %s: %s", appName, err) } } } err = image.DeleteAllAppImageNames(appName) if err != nil { log.Errorf("failed to remove image names from storage for app %s: %s", appName, err) } err = app.unbind(evt, requestID) if err != nil { logErr("Unable to unbind app", err) } routers := app.GetRouters() for _, appRouter := range routers { var r router.Router r, err = router.Get(appRouter.Name) if err == nil { err = r.RemoveBackend(app.Name) } if err != nil { logErr("Failed to remove router backend", err) } } err = router.Remove(app.Name) if err != nil { logErr("Failed to remove router backend from database", err) } err = app.unbindVolumes() if err != nil { logErr("Unable to unbind volumes", err) } err = repository.Manager().RemoveRepository(appName) if err != nil { logErr("Unable to remove app from repository manager", err) } token := app.Env["TSURU_APP_TOKEN"].Value err = AuthScheme.AppLogout(token) if err != nil { logErr("Unable to remove app token in destroy", err) } owner, err := auth.GetUserByEmail(app.Owner) if err == nil { err = servicemanager.UserQuota.Inc(owner.Email, -1) } if err != nil { logErr("Unable to release app quota", err) } logConn, err := db.LogConn() if err == nil { defer logConn.Close() err = logConn.AppLogCollection(appName).DropCollection() } if err != nil { logErr("Unable to remove logs collection", err) } conn, err := db.Conn() if err == nil { defer conn.Close() err = conn.Apps().Remove(bson.M{"name": appName}) } if err != nil { logErr("Unable to remove app from db", err) } err = event.MarkAsRemoved(event.Target{Type: event.TargetTypeApp, Value: appName}) if err != nil { logErr("Unable to mark old events as removed", err) } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/endpoints/socket.go#L37-L59
func CheckAlreadyRunning(path string) error { // If socket activated, nothing to do pid, err := strconv.Atoi(os.Getenv("LISTEN_PID")) if err == nil { if pid == os.Getpid() { return nil } } // If there's no socket file at all, there's nothing to do. if !shared.PathExists(path) { return nil } _, err = lxd.ConnectLXDUnix(path, nil) // If the connection succeeded it means there's another LXD running. if err == nil { return fmt.Errorf("LXD is already running") } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L622-L626
func (v *SkipWaitingParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoServiceworker6(&r, v) return r.Error() }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L803-L810
func CreateSeq(seq_flags, elem_size int) *Seq { return (*Seq)(C.cvCreateSeq( C.int(seq_flags), C.size_t(unsafe.Sizeof(Seq{})), C.size_t(elem_size), C.cvCreateMemStorage(C.int(0)), )) }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/guest.go#L255-L284
func (g *Guest) IsDir(path string) (bool, error) { var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE var err C.VixError = C.VIX_OK var result C.int cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) jobHandle = C.VixVM_DirectoryExistsInGuest(g.handle, cpath, // dir path name nil, // callbackProc nil) // clientData defer C.Vix_ReleaseHandle(jobHandle) err = C.is_file_or_dir(jobHandle, &result) if C.VIX_OK != err { return false, &Error{ Operation: "guest.IsDir", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } if int(result) == C.FALSE { return false, nil } return true, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/termios/termios_windows.go#L45-L49
func Restore(fd int, state *State) error { newState := terminal.State(*state) return terminal.Restore(fd, &newState) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/jobs.go#L240-L268
func (br Brancher) Intersects(other Brancher) bool { if br.RunsAgainstAllBranch() || other.RunsAgainstAllBranch() { return true } if len(br.Branches) > 0 { baseBranches := sets.NewString(br.Branches...) if len(other.Branches) > 0 { otherBranches := sets.NewString(other.Branches...) if baseBranches.Intersection(otherBranches).Len() > 0 { return true } return false } // Actually test our branches against the other brancher - if there are regex skip lists, simple comparison // is insufficient. for _, b := range baseBranches.List() { if other.ShouldRun(b) { return true } } return false } if len(other.Branches) == 0 { // There can only be one Brancher with skip_branches. return true } return other.Intersects(br) }
https://github.com/adamzy/cedar-go/blob/80a9c64b256db37ac20aff007907c649afb714f1/api.go#L8-L19
func (da *Cedar) Status() (keys, nodes, size, capacity int) { for i := 0; i < da.Size; i++ { n := da.Array[i] if n.Check >= 0 { nodes++ if n.Value >= 0 { keys++ } } } return keys, nodes, da.Size, da.Capacity }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/har/easyjson.go#L1984-L1988
func (v Creator) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoHar11(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/author_logger_wrapper.go#L45-L57
func (a *AuthorLoggerPluginWrapper) ReceiveIssue(issue sql.Issue) []Point { points := a.plugin.ReceiveIssue(issue) if a.enabled { for i := range points { if points[i].Values == nil { points[i].Values = map[string]interface{}{} } points[i].Values["author"] = issue.User } } return points }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/callbacks.go#L17-L41
func C(name string, m Matcher, h Handler) *Callback { // panic if matcher or handler is not set if m == nil || h == nil { panic("fire: missing matcher or handler") } return &Callback{ Matcher: m, Handler: func(ctx *Context) error { // begin trace ctx.Tracer.Push(name) // call handler err := h(ctx) if err != nil { return err } // finish trace ctx.Tracer.Pop() return nil }, } }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peers.go#L328-L332
func (peers *Peers) dereference(peer *Peer) { peers.Lock() defer peers.Unlock() peer.localRefCount-- }
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/atomic_rbuf.go#L164-L199
func (b *AtomicFixedSizeRingBuf) AdvanceBytesTwo(tb TwoBuffers) { b.tex.Lock() defer b.tex.Unlock() tblen := len(tb.First) + len(tb.Second) if tblen == 0 { return // nothing to do } // sanity check: insure we have re-located in the meantime if tblen > b.readable { panic(fmt.Sprintf("tblen was %d, and this was greater than b.readerable = %d. Usage error detected and data loss may have occurred (available data appears to have shrunken out from under us!).", tblen, b.readable)) } tbnow := b.unatomic_BytesTwo() if len(tb.First) > 0 { if tb.First[0] != tbnow.First[0] { panic(fmt.Sprintf("slice contents of First have changed out from under us!: '%s' vs '%s'", string(tb.First), string(tbnow.First))) } } if len(tb.Second) > 0 { if len(tb.First) > len(tbnow.First) { panic(fmt.Sprintf("slice contents of Second have changed out from under us! tbnow.First length(%d) is less than tb.First(%d.", len(tbnow.First), len(tb.First))) } if len(tbnow.Second) == 0 { panic(fmt.Sprintf("slice contents of Second have changed out from under us! tbnow.Second is empty, but tb.Second was not")) } if tb.Second[0] != tbnow.Second[0] { panic(fmt.Sprintf("slice contents of Second have changed out from under us!: '%s' vs '%s'", string(tb.Second), string(tbnow.Second))) } } b.unatomic_advance(tblen) }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/queue/simple.go#L23-L29
func NewSimple() Simple { q := &simpleQueue{ queue: make([]interface{}, 0), } q.available = sync.NewCond(&q.mu) return q }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/node_amd64.go#L50-L52
func (n Node) Size() int { return int(nodeHdrSize + uintptr(n.level+1)*nodeRefSize) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L3380-L3384
func (v *EventExecutionContextDestroyed) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime31(&r, v) return r.Error() }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/ghttp/handlers.go#L20-L26
func CombineHandlers(handlers ...http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { for _, handler := range handlers { handler(w, req) } } }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/matchers/selection_matchers.go#L28-L30
func HaveAttribute(attribute string, value string) types.GomegaMatcher { return &internal.HaveAttributeMatcher{ExpectedAttribute: attribute, ExpectedValue: value} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L627-L636
func (p *GetOuterHTMLParams) Do(ctx context.Context) (outerHTML string, err error) { // execute var res GetOuterHTMLReturns err = cdp.Execute(ctx, CommandGetOuterHTML, p, &res) if err != nil { return "", err } return res.OuterHTML, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/client.go#L472-L479
func (c *Client) GetProwJob(name string) (prowapi.ProwJob, error) { c.log("GetProwJob", name) var pj prowapi.ProwJob err := c.request(&request{ path: fmt.Sprintf("/apis/prow.k8s.io/v1/namespaces/%s/prowjobs/%s", c.namespace, name), }, &pj) return pj, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L4538-L4542
func (v *GetBoxModelParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom51(&r, v) return r.Error() }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/gopher/gopher.go#L30-L63
func Draw(gc draw2d.GraphicContext) { // Initialize Stroke Attribute gc.SetLineWidth(3) gc.SetLineCap(draw2d.RoundCap) gc.SetStrokeColor(color.Black) // Left hand // <path fill-rule="evenodd" clip-rule="evenodd" fill="#F6D2A2" stroke="#000000" stroke-width="3" stroke-linecap="round" d=" // M10.634,300.493c0.764,15.751,16.499,8.463,23.626,3.539c6.765-4.675,8.743-0.789,9.337-10.015 // c0.389-6.064,1.088-12.128,0.744-18.216c-10.23-0.927-21.357,1.509-29.744,7.602C10.277,286.542,2.177,296.561,10.634,300.493"/> gc.SetFillColor(color.RGBA{0xF6, 0xD2, 0xA2, 0xff}) gc.MoveTo(10.634, 300.493) rCubicCurveTo(gc, 0.764, 15.751, 16.499, 8.463, 23.626, 3.539) rCubicCurveTo(gc, 6.765, -4.675, 8.743, -0.789, 9.337, -10.015) rCubicCurveTo(gc, 0.389, -6.064, 1.088, -12.128, 0.744, -18.216) rCubicCurveTo(gc, -10.23, -0.927, -21.357, 1.509, -29.744, 7.602) gc.CubicCurveTo(10.277, 286.542, 2.177, 296.561, 10.634, 300.493) gc.FillStroke() // <path fill-rule="evenodd" clip-rule="evenodd" fill="#C6B198" stroke="#000000" stroke-width="3" stroke-linecap="round" d=" // M10.634,300.493c2.29-0.852,4.717-1.457,6.271-3.528"/> gc.MoveTo(10.634, 300.493) rCubicCurveTo(gc, 2.29, -0.852, 4.717, -1.457, 6.271, -3.528) gc.Stroke() // Left Ear // <path fill-rule="evenodd" clip-rule="evenodd" fill="#6AD7E5" stroke="#000000" stroke-width="3" stroke-linecap="round" d=" // M46.997,112.853C-13.3,95.897,31.536,19.189,79.956,50.74L46.997,112.853z"/> gc.MoveTo(46.997, 112.853) gc.CubicCurveTo(-13.3, 95.897, 31.536, 19.189, 79.956, 50.74) gc.LineTo(46.997, 112.853) gc.Close() gc.Stroke() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L231-L236
func (s *Schema) Trim(version int) []Update { trimmed := s.updates[version:] s.updates = s.updates[:version] s.fresh = "" return trimmed }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/devlxd.go#L30-L35
func DevLxdServer(d *Daemon) *http.Server { return &http.Server{ Handler: devLxdAPI(d), ConnState: pidMapper.ConnStateHandler, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/database/easyjson.go#L499-L503
func (v EventAddDatabase) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDatabase4(&w, v) return w.Buffer.BuildBytes(), w.Error }