_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/VividCortex/godaemon/blob/3d9f6e0b234fe7d17448b345b2e14ac05814a758/daemon_freebsd.go#L20-L49
func GetExecutablePath() (string, error) { PATH_MAX := 1024 // From <sys/syslimits.h> exePath := make([]byte, PATH_MAX) exeLen := C.size_t(len(exePath)) // Beware: sizeof(int) != sizeof(C.int) var mib [4]C.int // From <sys/sysctl.h> mib[0] = 1 // CTL_KERN mib[1] = 14 // KERN_PROC mib[2] = 12 // KERN_PROC_PATHNAME mib[3] = -1 status, err := C.sysctl((*C.int)(unsafe.Pointer(&mib[0])), 4, unsafe.Pointer(&exePath[0]), &exeLen, nil, 0) if err != nil { return "", fmt.Errorf("sysctl: %v", err) } // Not sure why this might happen with err being nil, but... if status != 0 { return "", fmt.Errorf("sysctl returned %d", status) } // Convert from null-padded []byte to a clean string. (Can't simply cast!) exePathStringLen := bytes.Index(exePath, []byte{0}) exePathString := string(exePath[:exePathStringLen]) return filepath.Clean(exePathString), nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L1064-L1099
func (m *member) Restart(t testing.TB) error { lg.Info( "restarting a member", zap.String("name", m.Name), zap.Strings("advertise-peer-urls", m.PeerURLs.StringSlice()), zap.Strings("listen-client-urls", m.ClientURLs.StringSlice()), zap.String("grpc-address", m.grpcAddr), ) newPeerListeners := make([]net.Listener, 0) for _, ln := range m.PeerListeners { newPeerListeners = append(newPeerListeners, NewListenerWithAddr(t, ln.Addr().String())) } m.PeerListeners = newPeerListeners newClientListeners := make([]net.Listener, 0) for _, ln := range m.ClientListeners { newClientListeners = append(newClientListeners, NewListenerWithAddr(t, ln.Addr().String())) } m.ClientListeners = newClientListeners if m.grpcListener != nil { if err := m.listenGRPC(); err != nil { t.Fatal(err) } } err := m.Launch() lg.Info( "restarted a member", zap.String("name", m.Name), zap.Strings("advertise-peer-urls", m.PeerURLs.StringSlice()), zap.Strings("listen-client-urls", m.ClientURLs.StringSlice()), zap.String("grpc-address", m.grpcAddr), zap.Error(err), ) return err }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/guest.go#L135-L160
func (g *Guest) MkTemp() (string, error) { var jobHandle C.VixHandle = C.VIX_INVALID_HANDLE var err C.VixError = C.VIX_OK var tempFilePath *C.char jobHandle = C.VixVM_CreateTempFileInGuest(g.handle, 0, // options C.VIX_INVALID_HANDLE, // propertyListHandle nil, // callbackProc nil) // clientData defer C.Vix_ReleaseHandle(jobHandle) err = C.get_temp_filepath(jobHandle, tempFilePath) defer C.Vix_FreeBuffer(unsafe.Pointer(tempFilePath)) if C.VIX_OK != err { return "", &Error{ Operation: "guest.MkTemp", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } return C.GoString(tempFilePath), nil }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L502-L507
func UnescapeHTML(s string) string { if Verbose { fmt.Println("Use html.UnescapeString instead of UnescapeHTML") } return html.UnescapeString(s) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/service_instance.go#L233-L281
func (si *ServiceInstance) BindUnit(app bind.App, unit bind.Unit) error { s, err := Get(si.ServiceName) if err != nil { return err } endpoint, err := s.getClient("production") if err != nil { return err } conn, err := db.Conn() if err != nil { return err } updateOp := bson.M{ "$addToSet": bson.M{ "bound_units": bson.D([]bson.DocElem{ {Name: "appname", Value: app.GetName()}, {Name: "id", Value: unit.GetID()}, {Name: "ip", Value: unit.GetIp()}, }), }, } err = conn.ServiceInstances().Update(bson.M{"name": si.Name, "service_name": si.ServiceName, "bound_units.id": bson.M{"$ne": unit.GetID()}}, updateOp) conn.Close() if err != nil { if err == mgo.ErrNotFound { return nil } return err } err = endpoint.BindUnit(si, app, unit) if err != nil { updateOp = bson.M{ "$pull": bson.M{ "bound_units": bson.D([]bson.DocElem{ {Name: "appname", Value: app.GetName()}, {Name: "id", Value: unit.GetID()}, {Name: "ip", Value: unit.GetIp()}, }), }, } rollbackErr := si.updateData(updateOp) if rollbackErr != nil { log.Errorf("[bind unit] could not remove stil unbound unit from db after failure: %s", rollbackErr) } return err } return nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/fuzzy/transport.go#L216-L219
func (t *transport) InstallSnapshot(id raft.ServerID, target raft.ServerAddress, args *raft.InstallSnapshotRequest, resp *raft.InstallSnapshotResponse, data io.Reader) error { t.log.Printf("INSTALL SNAPSHOT *************************************") return errors.New("huh") }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logging/format.go#L71-L82
func LogfmtFormat() log.Format { return log.FormatFunc(func(r *log.Record) []byte { common := []interface{}{r.KeyNames.Time, r.Time, r.KeyNames.Lvl, r.Lvl, r.KeyNames.Msg, r.Msg} buf := &bytes.Buffer{} logfmt(buf, common, 0, false) buf.Truncate(buf.Len() - 1) buf.WriteByte(' ') logfmt(buf, r.Ctx, 0, true) return buf.Bytes() }) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/types.go#L47-L49
func (t GestureType) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L865-L892
func (c *Cluster) StoragePoolVolumeUpdate(volumeName string, volumeType int, poolID int64, volumeDescription string, volumeConfig map[string]string) error { volumeID, _, err := c.StoragePoolNodeVolumeGetType(volumeName, volumeType, poolID) if err != nil { return err } err = c.Transaction(func(tx *ClusterTx) error { err = storagePoolVolumeReplicateIfCeph(tx.tx, volumeID, "default", volumeName, volumeType, poolID, func(volumeID int64) error { err = StorageVolumeConfigClear(tx.tx, volumeID) if err != nil { return err } err = StorageVolumeConfigAdd(tx.tx, volumeID, volumeConfig) if err != nil { return err } return StorageVolumeDescriptionUpdate(tx.tx, volumeID, volumeDescription) }) if err != nil { return err } return nil }) return err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L5221-L5225
func (v BreakLocation) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger49(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/portforwarder.go#L83-L147
func (f *PortForwarder) Run(appName string, localPort, remotePort uint16) error { podNameSelector := map[string]string{ "suite": "pachyderm", "app": appName, } podList, err := f.core.Pods(f.namespace).List(metav1.ListOptions{ LabelSelector: metav1.FormatLabelSelector(metav1.SetAsLabelSelector(podNameSelector)), TypeMeta: metav1.TypeMeta{ Kind: "ListOptions", APIVersion: "v1", }, }) if err != nil { return err } if len(podList.Items) == 0 { return fmt.Errorf("No pods found for app %s", appName) } // Choose a random pod podName := podList.Items[rand.Intn(len(podList.Items))].Name url := f.client.Post(). Resource("pods"). Namespace(f.namespace). Name(podName). SubResource("portforward"). URL() transport, upgrader, err := spdy.RoundTripperFor(f.config) if err != nil { return err } dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, "POST", url) ports := []string{fmt.Sprintf("%d:%d", localPort, remotePort)} readyChan := make(chan struct{}, 1) stopChan := make(chan struct{}, 1) // Ensure that the port forwarder isn't already shutdown, and append the // shutdown channel so this forwarder can be closed f.stopChansLock.Lock() if f.shutdown { f.stopChansLock.Unlock() return fmt.Errorf("port forwarder is shutdown") } f.stopChans = append(f.stopChans, stopChan) f.stopChansLock.Unlock() fw, err := portforward.New(dialer, ports, stopChan, readyChan, ioutil.Discard, f.logger) if err != nil { return err } errChan := make(chan error, 1) go func() { errChan <- fw.ForwardPorts() }() select { case err = <-errChan: return fmt.Errorf("port forwarding failed: %v", err) case <-fw.Ready: return nil } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L4627-L4631
func (v GetAttributesReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom52(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/mkbuild-cluster/main.go#L120-L147
func getCredentials(o options) error { if !o.changeContext { cur, err := currentContext(o) if err != nil { return fmt.Errorf("read current-context: %v", err) } defer useContext(o, cur) } // TODO(fejta): we ought to update kube.Client to support modern auth methods. // More info: https://github.com/kubernetes/kubernetes/issues/30617 old, set := os.LookupEnv(useClientCertEnv) if set { defer os.Setenv(useClientCertEnv, old) } if err := os.Setenv("CLOUDSDK_CONTAINER_USE_CLIENT_CERTIFICATE", "True"); err != nil { return fmt.Errorf("failed to set %s: %v", useClientCertEnv, err) } args, cmd := command( "gcloud", "container", "clusters", "get-credentials", o.cluster, "--project", o.project, "--zone", o.zone, ) if err := cmd.Run(); err != nil { return fmt.Errorf("%s: %v", strings.Join(args, " "), err) } return nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/table/iterator.go#L415-L421
func (itr *Iterator) Seek(key []byte) { if !itr.reversed { itr.seek(key) } else { itr.seekForPrev(key) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L3977-L3981
func (v EventResumed) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger39(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/ranch/ranch.go#L319-L328
func (r *Ranch) SyncConfig(config string) error { resources, err := ParseConfig(config) if err != nil { return err } if err := r.Storage.SyncResources(resources); err != nil { return err } return nil }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcnotify/tcnotify.go#L207-L218
func (notify *Notify) ListDenylist(continuationToken, limit string) (*ListOfNotificationAdresses, error) { v := url.Values{} if continuationToken != "" { v.Add("continuationToken", continuationToken) } if limit != "" { v.Add("limit", limit) } cd := tcclient.Client(*notify) responseObject, _, err := (&cd).APICall(nil, "GET", "/denylist/list", new(ListOfNotificationAdresses), v) return responseObject.(*ListOfNotificationAdresses), err }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service_instance.go#L498-L514
func serviceDoc(w http.ResponseWriter, r *http.Request, t auth.Token) error { serviceName := r.URL.Query().Get(":name") s, err := getService(serviceName) if err != nil { return err } if s.IsRestricted { allowed := permission.Check(t, permission.PermServiceReadDoc, contextsForService(&s)..., ) if !allowed { return permission.ErrUnauthorized } } w.Write([]byte(s.Doc)) return nil }
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/atomic_rbuf.go#L375-L398
func (b *AtomicFixedSizeRingBuf) ReadFrom(r io.Reader) (n int64, err error) { b.tex.Lock() defer b.tex.Unlock() for { writeCapacity := b.N - b.readable if writeCapacity <= 0 { // we are all full return n, nil } writeStart := (b.Beg + b.readable) % b.N upperLim := intMin2(writeStart+writeCapacity, b.N) m, e := r.Read(b.A[b.Use][writeStart:upperLim]) n += int64(m) b.readable += m if e == io.EOF { return n, nil } if e != nil { return n, e } } }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/helpers.go#L70-L98
func DataSize(str string) uint64 { const msg = "fire: data size must be like 4K, 20M or 5G" // check length if len(str) < 2 { panic(msg) } // get symbol sym := string(str[len(str)-1]) // parse number num, err := strconv.ParseUint(str[:len(str)-1], 10, 64) if err != nil { panic(msg) } // calculate size switch sym { case "K": return num * 1000 case "M": return num * 1000 * 1000 case "G": return num * 1000 * 1000 * 1000 } panic(msg) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gopherage/pkg/cov/junit/calculation/coveragelist.go#L66-L76
func (covList CoverageList) ListDirectories() []string { dirSet := map[string]bool{} for _, cov := range covList.Group { dirSet[path.Dir(cov.Name)] = true } var result []string for key := range dirSet { result = append(result, key) } return result }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/header.go#L200-L233
func parseMediaType(ctype string) (mtype string, params map[string]string, invalidParams []string, err error) { mtype, params, err = mime.ParseMediaType(ctype) if err != nil { // Small hack to remove harmless charset duplicate params. mctype := fixMangledMediaType(ctype, ";") mtype, params, err = mime.ParseMediaType(mctype) if err != nil { // Some badly formed media types forget to send ; between fields. mctype := fixMangledMediaType(ctype, " ") if strings.Contains(mctype, `name=""`) { mctype = strings.Replace(mctype, `name=""`, `name=" "`, -1) } mtype, params, err = mime.ParseMediaType(mctype) if err != nil { // If the media parameter has special characters, ensure that it is quoted. mtype, params, err = mime.ParseMediaType(fixUnquotedSpecials(mctype)) if err != nil { return "", nil, nil, errors.WithStack(err) } } } } if mtype == ctPlaceholder { mtype = "" } for name, value := range params { if value != pvPlaceholder { continue } invalidParams = append(invalidParams, name) delete(params, name) } return mtype, params, invalidParams, err }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxc/utils/progress.go#L84-L141
func (p *ProgressRenderer) Update(status string) { // Wait if needed timeout := p.wait.Sub(time.Now()) if timeout.Seconds() > 0 { time.Sleep(timeout) } // Acquire rendering lock p.lock.Lock() defer p.lock.Unlock() // Check if we're already done if p.done { return } // Handle quiet mode if p.Quiet { return } // Skip status updates when not dealing with a terminal if p.terminal == 0 { if !termios.IsTerminal(int(os.Stdout.Fd())) { p.terminal = -1 } p.terminal = 1 } if p.terminal != 1 { return } // Print the new message msg := "%s" if p.Format != "" { msg = p.Format } msg = fmt.Sprintf(msg, status) // Truncate msg to terminal length msg = "\r" + p.truncate(msg) // Don't print if empty and never printed if len(msg) == 1 && p.maxLength == 0 { return } if len(msg) > p.maxLength { p.maxLength = len(msg) } else { fmt.Printf("\r%s", strings.Repeat(" ", p.maxLength)) } fmt.Print(msg) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2983-L2986
func (e ManageOfferEffect) String() string { name, _ := manageOfferEffectMap[int32(e)] return name }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L208-L214
func (rs readSet) cmps() []v3.Cmp { cmps := make([]v3.Cmp, 0, len(rs)) for k, rk := range rs { cmps = append(cmps, isKeyCurrent(k, rk)) } return cmps }
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/time.go#L132-L135
func (t *Time) SetValid(v time.Time) { t.Time = v t.Valid = true }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/domstorage.go#L99-L108
func (p *GetDOMStorageItemsParams) Do(ctx context.Context) (entries []Item, err error) { // execute var res GetDOMStorageItemsReturns err = cdp.Execute(ctx, CommandGetDOMStorageItems, p, &res) if err != nil { return nil, err } return res.Entries, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/adt/interval_tree.go#L384-L397
func (ivt *IntervalTree) replaceParent(x *intervalNode, y *intervalNode) { y.parent = x.parent if x.parent == nil { ivt.root = y } else { if x == x.parent.left { x.parent.left = y } else { x.parent.right = y } x.parent.updateMax() } x.parent = y }
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/clitable/table.go#L276-L281
func (t *Table) lineLength() (sum int) { for _, l := range t.fieldSizes { sum += l + 1 } return sum + 1 }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/fakes/fake.go#L222-L226
func (s *MockPersistence) FindOne(query interface{}, result interface{}) (err error) { goutil.Unpack([]interface{}{s.Result}, result) err = s.Err return }
https://github.com/VividCortex/godaemon/blob/3d9f6e0b234fe7d17448b345b2e14ac05814a758/daemon_darwin.go#L19-L40
func GetExecutablePath() (string, error) { PATH_MAX := 1024 // From <sys/syslimits.h> exePath := make([]byte, PATH_MAX) exeLen := C.uint32_t(len(exePath)) status, err := C._NSGetExecutablePath((*C.char)(unsafe.Pointer(&exePath[0])), &exeLen) if err != nil { return "", fmt.Errorf("_NSGetExecutablePath: %v", err) } // Not sure why this might happen with err being nil, but... if status != 0 { return "", fmt.Errorf("_NSGetExecutablePath returned %d", status) } // Convert from null-padded []byte to a clean string. (Can't simply cast!) exePathStringLen := bytes.Index(exePath, []byte{0}) exePathString := string(exePath[:exePathStringLen]) return filepath.Clean(exePathString), nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_volumes.go#L154-L227
func storagePoolVolumesTypeGet(d *Daemon, r *http.Request) Response { project := projectParam(r) // Get the name of the pool the storage volume is supposed to be // attached to. poolName := mux.Vars(r)["name"] // Get the name of the volume type. volumeTypeName := mux.Vars(r)["type"] recursion := util.IsRecursionRequest(r) // Convert the volume type name to our internal integer representation. volumeType, err := storagePoolVolumeTypeNameToType(volumeTypeName) if err != nil { return BadRequest(err) } // Check that the storage volume type is valid. if !shared.IntInSlice(volumeType, supportedVolumeTypes) { return BadRequest(fmt.Errorf("invalid storage volume type %s", volumeTypeName)) } // Retrieve ID of the storage pool (and check if the storage pool // exists). poolID, err := d.cluster.StoragePoolGetID(poolName) if err != nil { return SmartError(err) } // Get the names of all storage volumes of a given volume type currently // attached to the storage pool. volumes, err := d.cluster.StoragePoolNodeVolumesGetType(volumeType, poolID) if err != nil { return SmartError(err) } resultString := []string{} resultMap := []*api.StorageVolume{} for _, volume := range volumes { if !recursion { apiEndpoint, err := storagePoolVolumeTypeToAPIEndpoint(volumeType) if err != nil { return InternalError(err) } if apiEndpoint == storagePoolVolumeAPIEndpointContainers { apiEndpoint = "container" } else if apiEndpoint == storagePoolVolumeAPIEndpointImages { apiEndpoint = "image" } resultString = append(resultString, fmt.Sprintf("/%s/storage-pools/%s/volumes/%s/%s", version.APIVersion, poolName, apiEndpoint, volume)) } else { _, vol, err := d.cluster.StoragePoolNodeVolumeGetType(volume, volumeType, poolID) if err != nil { continue } volumeUsedBy, err := storagePoolVolumeUsedByGet(d.State(), project, vol.Name, vol.Type) if err != nil { return SmartError(err) } vol.UsedBy = volumeUsedBy resultMap = append(resultMap, vol) } } if !recursion { return SyncResponse(true, resultString) } return SyncResponse(true, resultMap) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/fragmenting_writer.go#L72-L79
func newWritableChunk(checksum Checksum, contents *typed.WriteBuffer) *writableChunk { return &writableChunk{ size: 0, sizeRef: contents.DeferUint16(), checksum: checksum, contents: contents, } }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/meshconn/peer.go#L164-L166
func (p *Peer) OnGossip(buf []byte) (delta mesh.GossipData, err error) { return pktSlice{makePkt(buf)}, nil }
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/page.go#L21-L52
func (r *Reader) Page(num int) Page { num-- // now 0-indexed page := r.Trailer().Key("Root").Key("Pages") Search: for page.Key("Type").Name() == "Pages" { count := int(page.Key("Count").Int64()) if count < num { return Page{} } kids := page.Key("Kids") for i := 0; i < kids.Len(); i++ { kid := kids.Index(i) if kid.Key("Type").Name() == "Pages" { c := int(kid.Key("Count").Int64()) if num < c { page = kid continue Search } num -= c continue } if kid.Key("Type").Name() == "Page" { if num == 0 { return Page{kid} } num-- } } break } return Page{} }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/commands.go#L42-L44
func (a *API) ShowAPIActions(cmd string) error { return a.ShowActions(cmd, "/rll", commandValues) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/subchannel.go#L100-L104
func (c *SubChannel) Isolated() bool { c.RLock() defer c.RUnlock() return c.topChannel.Peers() != c.peers }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L306-L311
func (s *FileSequence) FrameRangePadded() string { if s.frameSet == nil { return "" } return s.frameSet.FrameRangePadded(s.zfill) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/types.go#L133-L135
func (t *ScrollRectType) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/stagePlanner.go#L556-L596
func reorderStages(rootStage *evaluationStage) { // traverse every rightStage until we find multiples in a row of the same precedence. var identicalPrecedences []*evaluationStage var currentStage, nextStage *evaluationStage var precedence, currentPrecedence operatorPrecedence nextStage = rootStage precedence = findOperatorPrecedenceForSymbol(rootStage.symbol) for nextStage != nil { currentStage = nextStage nextStage = currentStage.rightStage // left depth first, since this entire method only looks for precedences down the right side of the tree if currentStage.leftStage != nil { reorderStages(currentStage.leftStage) } currentPrecedence = findOperatorPrecedenceForSymbol(currentStage.symbol) if currentPrecedence == precedence { identicalPrecedences = append(identicalPrecedences, currentStage) continue } // precedence break. // See how many in a row we had, and reorder if there's more than one. if len(identicalPrecedences) > 1 { mirrorStageSubtree(identicalPrecedences) } identicalPrecedences = []*evaluationStage{currentStage} precedence = currentPrecedence } if len(identicalPrecedences) > 1 { mirrorStageSubtree(identicalPrecedences) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/easyjson.go#L379-L383
func (v StartParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTracing1(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/sorted_list.go#L54-L62
func removeStr(ss *[]string, s string) bool { idx := sort.SearchStrings(*ss, s) if idx == len(*ss) { return false } copy((*ss)[idx:], (*ss)[idx+1:]) *ss = (*ss)[:len(*ss)-1] return true }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L1158-L1162
func (v ReleaseObjectGroupParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime11(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/server/api_server.go#L159-L233
func NewAuthServer(env *serviceenv.ServiceEnv, etcdPrefix string, public bool) (authclient.APIServer, error) { s := &apiServer{ env: env, pachLogger: log.NewLogger("authclient.API"), adminCache: make(map[string]struct{}), tokens: col.NewCollection( env.GetEtcdClient(), path.Join(etcdPrefix, tokensPrefix), nil, &authclient.TokenInfo{}, nil, nil, ), authenticationCodes: col.NewCollection( env.GetEtcdClient(), path.Join(etcdPrefix, authenticationCodesPrefix), nil, &authclient.OTPInfo{}, nil, nil, ), acls: col.NewCollection( env.GetEtcdClient(), path.Join(etcdPrefix, aclsPrefix), nil, &authclient.ACL{}, nil, nil, ), admins: col.NewCollection( env.GetEtcdClient(), path.Join(etcdPrefix, adminsPrefix), nil, &types.BoolValue{}, // smallest value that etcd actually stores nil, nil, ), members: col.NewCollection( env.GetEtcdClient(), path.Join(etcdPrefix, membersPrefix), nil, &authclient.Groups{}, nil, nil, ), groups: col.NewCollection( env.GetEtcdClient(), path.Join(etcdPrefix, groupsPrefix), nil, &authclient.Users{}, nil, nil, ), authConfig: col.NewCollection( env.GetEtcdClient(), path.Join(etcdPrefix, configKey), nil, &authclient.AuthConfig{}, nil, nil, ), public: public, } go s.retrieveOrGeneratePPSToken() go s.watchAdmins(path.Join(etcdPrefix, adminsPrefix)) if public { // start SAML service (won't respond to // anything until config is set) go s.serveSAML() } // Watch for new auth config options go s.watchConfig() return s, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L815-L839
func ContainerUpdate(tx *sql.Tx, id int, description string, architecture int, ephemeral bool, expiryDate time.Time) error { str := fmt.Sprintf("UPDATE containers SET description=?, architecture=?, ephemeral=?, expiry_date=? WHERE id=?") stmt, err := tx.Prepare(str) if err != nil { return err } defer stmt.Close() ephemeralInt := 0 if ephemeral { ephemeralInt = 1 } if expiryDate.IsZero() { _, err = stmt.Exec(description, architecture, ephemeralInt, "", id) } else { _, err = stmt.Exec(description, architecture, ephemeralInt, expiryDate, id) } if err != nil { return err } return nil }
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/atomic_rbuf.go#L428-L437
func (b *AtomicFixedSizeRingBuf) unatomic_advance(n int) { if n <= 0 { return } if n > b.readable { n = b.readable } b.readable -= n b.Beg = (b.Beg + n) % b.N }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L51-L55
func CreateImage(w, h, depth, channels int) *IplImage { size := C.cvSize(C.int(w), C.int(h)) img := C.cvCreateImage(size, C.int(depth), C.int(channels)) return (*IplImage)(img) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L6080-L6084
func (v EventResponseReceived) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork48(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L2163-L2167
func (v ClearObjectStoreParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoIndexeddb19(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/networks.go#L347-L363
func (c *Cluster) networkNodes(networkID int64) ([]string, error) { stmt := ` SELECT nodes.name FROM nodes JOIN networks_nodes ON networks_nodes.node_id = nodes.id WHERE networks_nodes.network_id = ? ` var nodes []string err := c.Transaction(func(tx *ClusterTx) error { var err error nodes, err = query.SelectStrings(tx.tx, stmt, networkID) return err }) if err != nil { return nil, err } return nodes, nil }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L435-L461
func (p *Page) ReadNewLogs(logType string) ([]Log, error) { if p.logs == nil { p.logs = map[string][]Log{} } clientLogs, err := p.session.NewLogs(logType) if err != nil { return nil, fmt.Errorf("failed to retrieve logs: %s", err) } messageMatcher := regexp.MustCompile(`^(?s:(.+))\s\(([^)]*:\w*)\)$`) var logs []Log for _, clientLog := range clientLogs { matches := messageMatcher.FindStringSubmatch(clientLog.Message) message, location := clientLog.Message, "" if len(matches) > 2 { message, location = matches[1], matches[2] } log := Log{message, location, clientLog.Level, msToTime(clientLog.Timestamp)} logs = append(logs, log) } p.logs[logType] = append(p.logs[logType], logs...) return logs, nil }
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/client.go#L555-L565
func (r *FileResponse) FileName() string { value := r.headers.Get("Content-Disposition") if len(value) == 0 { return "" } _, params, err := mime.ParseMediaType(value) if err != nil { return "" } return params["filename"] }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L303-L329
func AllocateIDs(c context.Context, kind string, parent *Key, n int) (low, high int64, err error) { if kind == "" { return 0, 0, errors.New("datastore: AllocateIDs given an empty kind") } if n < 0 { return 0, 0, fmt.Errorf("datastore: AllocateIDs given a negative count: %d", n) } if n == 0 { return 0, 0, nil } req := &pb.AllocateIdsRequest{ ModelKey: keyToProto("", NewIncompleteKey(c, kind, parent)), Size: proto.Int64(int64(n)), } res := &pb.AllocateIdsResponse{} if err := internal.Call(c, "datastore_v3", "AllocateIds", req, res); err != nil { return 0, 0, err } // The protobuf is inclusive at both ends. Idiomatic Go (e.g. slices, for loops) // is inclusive at the low end and exclusive at the high end, so we add 1. low = res.GetStart() high = res.GetEnd() + 1 if low+int64(n) != high { return 0, 0, fmt.Errorf("datastore: internal error: could not allocate %d IDs", n) } return low, high, nil }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/paths.go#L119-L121
func serverCdromPath(dcid, srvid, cdid string) string { return serverCdromColPath(dcid, srvid) + slash(cdid) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L520-L522
func (t BlockedReason) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/reqres.go#L226-L256
func (r *reqResReader) recvNextFragment(initial bool) (*readableFragment, error) { if r.initialFragment != nil { fragment := r.initialFragment r.initialFragment = nil r.previousFragment = fragment return fragment, nil } // Wait for the appropriate message from the peer message := r.messageForFragment(initial) frame, err := r.mex.recvPeerFrameOfType(message.messageType()) if err != nil { if err, ok := err.(errorMessage); ok { // If we received a serialized error from the other side, then we should go through // the normal doneReading path so stats get updated with this error. r.err = err.AsSystemError() return nil, err } return nil, r.failed(err) } // Parse the message and setup the fragment fragment, err := parseInboundFragment(r.mex.framePool, frame, message) if err != nil { return nil, r.failed(err) } r.previousFragment = fragment return fragment, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L6081-L6085
func (v *EventFrameNavigated) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage64(&r, v) return r.Error() }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/examples/thrift/gen-go/example/first.go#L41-L46
func (p *FirstClient) Echo(msg string) (r string, err error) { if err = p.sendEcho(msg); err != nil { return } return p.recvEcho() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/easyjson.go#L381-L385
func (v Value) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoAccessibility1(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/profiles/digitalocean/controller_ubuntu_16_04.go#L30-L215
func NewControllerUbuntuCluster(name string) *cluster.Cluster { controlPlaneProviderConfig := &cluster.ControlPlaneProviderConfig{ Cloud: cluster.CloudDigitalOcean, Location: "nyc3", SSH: &cluster.SSH{ PublicKeyPath: "~/.ssh/id_rsa.pub", User: "root", }, KubernetesAPI: &cluster.KubernetesAPI{ Port: "443", }, Values: &cluster.Values{ ItemMap: map[string]string{ "INJECTEDTOKEN": kubeadm.GetRandomToken(), }, }, } machineSetsProviderConfigs := []*cluster.MachineProviderConfig{ { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeMaster, Name: fmt.Sprintf("%s-master", name), MaxCount: 1, MinCount: 1, Image: "ubuntu-16-04-x64", Size: "s-2vcpu-2gb", BootstrapScripts: []string{ "bootstrap/digitalocean_k8s_ubuntu_16.04_master.sh", }, Firewalls: []*cluster.Firewall{ { Name: fmt.Sprintf("%s-master", name), IngressRules: []*cluster.IngressRule{ { IngressToPort: "22", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressToPort: "443", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressToPort: "all", IngressSource: fmt.Sprintf("%s-node", name), IngressProtocol: "tcp", }, { IngressToPort: "all", IngressSource: fmt.Sprintf("%s-node", name), IngressProtocol: "udp", }, }, EgressRules: []*cluster.EgressRule{ { EgressToPort: "all", // By default all egress from VM EgressDestination: "0.0.0.0/0", EgressProtocol: "tcp", }, { EgressToPort: "all", // By default all egress from VM EgressDestination: "0.0.0.0/0", EgressProtocol: "udp", }, }, }, }, }, }, { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeNode, Name: fmt.Sprintf("%s-node", name), MaxCount: 1, MinCount: 1, Image: "ubuntu-16-04-x64", Size: "s-1vcpu-2gb", BootstrapScripts: []string{ "bootstrap/digitalocean_k8s_ubuntu_16.04_node.sh", }, Firewalls: []*cluster.Firewall{ { Name: fmt.Sprintf("%s-node", name), IngressRules: []*cluster.IngressRule{ { IngressToPort: "22", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressToPort: "all", IngressSource: fmt.Sprintf("%s-master", name), IngressProtocol: "tcp", }, { IngressToPort: "all", IngressSource: fmt.Sprintf("%s-master", name), IngressProtocol: "udp", }, }, EgressRules: []*cluster.EgressRule{ { EgressToPort: "all", // By default all egress from VM EgressDestination: "0.0.0.0/0", EgressProtocol: "tcp", }, { EgressToPort: "all", // By default all egress from VM EgressDestination: "0.0.0.0/0", EgressProtocol: "udp", }, }, }, }, }, }, } deployment := &appsv1beta2.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "kubicorn-controller", }, Spec: appsv1beta2.DeploymentSpec{ Replicas: ptrconvenient.Int32Ptr(1), Selector: &metav1.LabelSelector{ MatchLabels: map[string]string{ "app": "kubicorn-controller", }, }, Template: apiv1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ "app": "kubicorn-controller", }, }, Spec: apiv1.PodSpec{ Containers: []apiv1.Container{ { Name: "kubicorn-controller", Image: "kubicorn/controller:latest", //Ports: []apiv1.ContainerPort{ // { // Name: "http", // Protocol: apiv1.ProtocolTCP, // ContainerPort: 80, // }, //}, }, }, }, }, }, } c := cluster.NewCluster(name) c.SetProviderConfig(controlPlaneProviderConfig) c.NewMachineSetsFromProviderConfigs(machineSetsProviderConfigs) // // // Here we define the replicas for the controller // // cpms := c.MachineSets[1] cpms.Spec.Replicas = ptrconvenient.Int32Ptr(3) c.MachineSets[1] = cpms // // // // // c.ControllerDeployment = deployment secret := &apiv1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: "digitalocean", Namespace: "kube-system", }, StringData: map[string]string{"access-token": string(os.Getenv("DIGITALOCEAN_ACCESS_TOKEN"))}, } c.APITokenSecret = secret return c }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/label_sync/main.go#L402-L405
func rename(repo string, previous, wanted Label) Update { logrus.WithField("repo", repo).WithField("from", previous.Name).WithField("to", wanted.Name).Info("rename") return Update{Why: "rename", Current: &previous, Wanted: &wanted, repo: repo} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/easyjson.go#L360-L364
func (v *GetFramesWithManifestsReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoApplicationcache3(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/auth/cmds/cmds.go#L472-L489
func UseAuthTokenCmd() *cobra.Command { useAuthToken := &cobra.Command{ Short: "Read a Pachyderm auth token from stdin, and write it to the " + "current user's Pachyderm config file", Long: "Read a Pachyderm auth token from stdin, and write it to the " + "current user's Pachyderm config file", Run: cmdutil.RunFixedArgs(0, func(args []string) error { fmt.Println("Please paste your Pachyderm auth token:") token, err := bufio.NewReader(os.Stdin).ReadString('\n') if err != nil { return fmt.Errorf("error reading token: %v", err) } writePachTokenToCfg(strings.TrimSpace(token)) // drop trailing newline return nil }), } return cmdutil.CreateAlias(useAuthToken, "auth use-auth-token") }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/server/driver.go#L2619-L2642
func nodeToFileInfo(ci *pfs.CommitInfo, path string, node *hashtree.NodeProto, full bool) *pfs.FileInfo { fileInfo := &pfs.FileInfo{ File: &pfs.File{ Commit: ci.Commit, Path: path, }, SizeBytes: uint64(node.SubtreeSize), Hash: node.Hash, Committed: ci.Finished, } if node.FileNode != nil { fileInfo.FileType = pfs.FileType_FILE if full { fileInfo.Objects = node.FileNode.Objects fileInfo.BlockRefs = node.FileNode.BlockRefs } } else if node.DirNode != nil { fileInfo.FileType = pfs.FileType_DIR if full { fileInfo.Children = node.DirNode.Children } } return fileInfo }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv2/command/get_command.go#L27-L41
func NewGetCommand() cli.Command { return cli.Command{ Name: "get", Usage: "retrieve the value of a key", ArgsUsage: "<key>", Flags: []cli.Flag{ cli.BoolFlag{Name: "sort", Usage: "returns result in sorted order"}, cli.BoolFlag{Name: "quorum, q", Usage: "require quorum for get request"}, }, Action: func(c *cli.Context) error { getCommandFunc(c, mustNewKeyAPI(c)) return nil }, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L1937-L1941
func (v DatabaseWithObjectStores) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoIndexeddb17(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L368-L371
func (e AssetType) String() string { name, _ := assetTypeMap[int32(e)] return name }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L601-L655
func GetMessage(ap Approvers, linkURL *url.URL, org, repo, branch string) *string { linkURL.Path = org + "/" + repo message, err := GenerateTemplate(`{{if (and (not .ap.RequirementsMet) (call .ap.ManuallyApproved )) }} Approval requirements bypassed by manually added approval. {{end -}} This pull-request has been approved by:{{range $index, $approval := .ap.ListApprovals}}{{if $index}}, {{else}} {{end}}{{$approval}}{{end}} {{- if (and (not .ap.AreFilesApproved) (not (call .ap.ManuallyApproved))) }} To fully approve this pull request, please assign additional approvers. We suggest the following additional approver{{if ne 1 (len .ap.GetCCs)}}s{{end}}: {{range $index, $cc := .ap.GetCCs}}{{if $index}}, {{end}}**{{$cc}}**{{end}} If they are not already assigned, you can assign the PR to them by writing `+"`/assign {{range $index, $cc := .ap.GetCCs}}{{if $index}} {{end}}@{{$cc}}{{end}}`"+` in a comment when ready. {{- end}} {{if not .ap.RequireIssue -}} {{else if .ap.AssociatedIssue -}} Associated issue: *#{{.ap.AssociatedIssue}}* {{ else if len .ap.NoIssueApprovers -}} Associated issue requirement bypassed by:{{range $index, $approval := .ap.ListNoIssueApprovals}}{{if $index}}, {{else}} {{end}}{{$approval}}{{end}} {{ else if call .ap.ManuallyApproved -}} *No associated issue*. Requirement bypassed by manually added approval. {{ else -}} *No associated issue*. Update pull-request body to add a reference to an issue, or get approval with `+"`/approve no-issue`"+` {{ end -}} The full list of commands accepted by this bot can be found [here](https://go.k8s.io/bot-commands?repo={{ .org }}%2F{{ .repo }}). The pull request process is described [here](https://git.k8s.io/community/contributors/guide/owners.md#the-code-review-process) <details {{if (and (not .ap.AreFilesApproved) (not (call .ap.ManuallyApproved))) }}open{{end}}> Needs approval from an approver in each of these files: {{range .ap.GetFiles .baseURL .branch}}{{.}}{{end}} Approvers can indicate their approval by writing `+"`/approve`"+` in a comment Approvers can cancel approval by writing `+"`/approve cancel`"+` in a comment </details>`, "message", map[string]interface{}{"ap": ap, "baseURL": linkURL, "org": org, "repo": repo, "branch": branch}) if err != nil { ap.owners.log.WithError(err).Errorf("Error generating message.") return nil } message += getGubernatorMetadata(ap.GetCCs()) title, err := GenerateTemplate("This PR is **{{if not .IsApproved}}NOT {{end}}APPROVED**", "title", ap) if err != nil { ap.owners.log.WithError(err).Errorf("Error generating title.") return nil } return notification(ApprovalNotificationName, title, message) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L4364-L4368
func (v *GetContentQuadsParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom49(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/io/easyjson.go#L236-L240
func (v ReadReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoIo2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L653-L690
func ContainerProfilesInsert(tx *sql.Tx, id int, project string, profiles []string) error { enabled, err := projectHasProfiles(tx, project) if err != nil { return errors.Wrap(err, "Check if project has profiles") } if !enabled { project = "default" } applyOrder := 1 str := ` INSERT INTO containers_profiles (container_id, profile_id, apply_order) VALUES ( ?, (SELECT profiles.id FROM profiles JOIN projects ON projects.id=profiles.project_id WHERE projects.name=? AND profiles.name=?), ? ) ` stmt, err := tx.Prepare(str) if err != nil { return err } defer stmt.Close() for _, profile := range profiles { _, err = stmt.Exec(id, project, profile, applyOrder) if err != nil { logger.Debugf("Error adding profile %s to container: %s", profile, err) return err } applyOrder = applyOrder + 1 } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L365-L367
func (p *SetEmulatedMediaParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetEmulatedMedia, p, nil) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L586-L600
func (prm *prmMatchRepository) UnmarshalJSON(data []byte) error { *prm = prmMatchRepository{} var tmp prmMatchRepository if err := paranoidUnmarshalJSONObjectExactFields(data, map[string]interface{}{ "type": &tmp.Type, }); err != nil { return err } if tmp.Type != prmTypeMatchRepository { return InvalidPolicyFormatError(fmt.Sprintf("Unexpected policy requirement type \"%s\"", tmp.Type)) } *prm = *newPRMMatchRepository() return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/accessibility.go#L71-L74
func (p GetPartialAXTreeParams) WithNodeID(nodeID cdp.NodeID) *GetPartialAXTreeParams { p.NodeID = nodeID return &p }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/change_trust.go#L51-L58
func (m Asset) MutateChangeTrust(o *xdr.ChangeTrustOp) (err error) { if m.Native { return errors.New("Native asset not allowed") } o.Line, err = m.ToXdrObject() return }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/events.go#L50-L70
func (e *EventListener) RemoveHandler(target *EventTarget) error { if target == nil { return fmt.Errorf("A valid event target must be provided") } // Handle locking e.targetsLock.Lock() defer e.targetsLock.Unlock() // Locate and remove the function from the list for i, entry := range e.targets { if entry == target { copy(e.targets[i:], e.targets[i+1:]) e.targets[len(e.targets)-1] = nil e.targets = e.targets[:len(e.targets)-1] return nil } } return fmt.Errorf("Couldn't find this function and event types combination") }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1683-L1687
func (v *EventAddHeapSnapshotChunk) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeapprofiler19(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/health/health.go#L27-L32
func (h *healthServer) Health(context.Context, *types.Empty) (*types.Empty, error) { if !h.ready { return nil, fmt.Errorf("server not ready") } return &types.Empty{}, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L465-L469
func ParseSimpleConfig(b []byte) (SimpleConfig, error) { simple := new(SimpleConfig) err := yaml.Unmarshal(b, simple) return *simple, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/layertree.go#L265-L268
func (p ReplaySnapshotParams) WithFromStep(fromStep int64) *ReplaySnapshotParams { p.FromStep = fromStep return &p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L925-L928
func (p SearchInResourceParams) WithIsRegex(isRegex bool) *SearchInResourceParams { p.IsRegex = isRegex return &p }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/frame.go#L165-L179
func (f *Frame) WriteOut(w io.Writer) error { var wbuf typed.WriteBuffer wbuf.Wrap(f.headerBuffer) if err := f.Header.write(&wbuf); err != nil { return err } fullFrame := f.buffer[:f.Header.FrameSize()] if _, err := w.Write(fullFrame); err != nil { return err } return nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/retry.go#L169-L174
func (rs *RequestState) SinceStart(now time.Time, fallback time.Duration) time.Duration { if rs == nil { return fallback } return now.Sub(rs.Start) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/apply.go#L438-L462
func applyCompare(rv mvcc.ReadView, c *pb.Compare) bool { // TODO: possible optimizations // * chunk reads for large ranges to conserve memory // * rewrite rules for common patterns: // ex. "[a, b) createrev > 0" => "limit 1 /\ kvs > 0" // * caching rr, err := rv.Range(c.Key, mkGteRange(c.RangeEnd), mvcc.RangeOptions{}) if err != nil { return false } if len(rr.KVs) == 0 { if c.Target == pb.Compare_VALUE { // Always fail if comparing a value on a key/keys that doesn't exist; // nil == empty string in grpc; no way to represent missing value return false } return compareKV(c, mvccpb.KeyValue{}) } for _, kv := range rr.KVs { if !compareKV(c, kv) { return false } } return true }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/projects.mapper.go#L114-L182
func (c *ClusterTx) ProjectList(filter ProjectFilter) ([]api.Project, error) { // Result slice. objects := make([]api.Project, 0) // Check which filter criteria are active. criteria := map[string]interface{}{} if filter.Name != "" { criteria["Name"] = filter.Name } // Pick the prepared statement and arguments to use based on active criteria. var stmt *sql.Stmt var args []interface{} if criteria["Name"] != nil { stmt = c.stmt(projectObjectsByName) args = []interface{}{ filter.Name, } } else { stmt = c.stmt(projectObjects) args = []interface{}{} } // Dest function for scanning a row. dest := func(i int) []interface{} { objects = append(objects, api.Project{}) return []interface{}{ &objects[i].Description, &objects[i].Name, } } // Select. err := query.SelectObjects(stmt, dest, args...) if err != nil { return nil, errors.Wrap(err, "Failed to fetch projects") } // Fill field Config. configObjects, err := c.ProjectConfigRef(filter) if err != nil { return nil, errors.Wrap(err, "Failed to fetch field Config") } for i := range objects { value := configObjects[objects[i].Name] if value == nil { value = map[string]string{} } objects[i].Config = value } // Fill field UsedBy. usedByObjects, err := c.ProjectUsedByRef(filter) if err != nil { return nil, errors.Wrap(err, "Failed to fetch field UsedBy") } for i := range objects { value := usedByObjects[objects[i].Name] if value == nil { value = []string{} } objects[i].UsedBy = value } return objects, nil }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/builder.go#L149-L167
func (p MailBuilder) AddFileAttachment(path string) MailBuilder { // Only allow first p.err value if p.err != nil { return p } f, err := os.Open(path) if err != nil { p.err = err return p } b, err := ioutil.ReadAll(f) if err != nil { p.err = err return p } name := filepath.Base(path) ctype := mime.TypeByExtension(filepath.Ext(name)) return p.AddAttachment(b, ctype, name) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/auth/auth.go#L116-L121
func IsErrBadToken(err error) bool { if err == nil { return false } return strings.Contains(err.Error(), status.Convert(ErrBadToken).Message()) }
https://github.com/abronan/leadership/blob/76df1b7fa3841b453d70d7183e8c02a87538c0ee/candidate.go#L45-L49
func (c *Candidate) IsLeader() bool { c.lock.Lock() defer c.lock.Unlock() return c.leader }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/fuzzy/cluster.go#L116-L130
func (c *cluster) Leader(timeout time.Duration) *raftNode { start := time.Now() for true { for _, n := range c.nodes { if n.raft.State() == raft.Leader { return n } } if time.Now().Sub(start) > timeout { return nil } time.Sleep(time.Millisecond) } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/containers_get.go#L265-L300
func doContainersGetFromNode(project, node string, cert *shared.CertInfo) ([]api.Container, error) { f := func() ([]api.Container, error) { client, err := cluster.Connect(node, cert, true) if err != nil { return nil, errors.Wrapf(err, "Failed to connect to node %s", node) } client = client.UseProject(project) containers, err := client.GetContainers() if err != nil { return nil, errors.Wrapf(err, "Failed to get containers from node %s", node) } return containers, nil } timeout := time.After(30 * time.Second) done := make(chan struct{}) var containers []api.Container var err error go func() { containers, err = f() done <- struct{}{} }() select { case <-timeout: err = fmt.Errorf("Timeout getting containers from node %s", node) case <-done: } return containers, err }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L104-L110
func (p *Pact) AddMessage() *Message { log.Println("[DEBUG] pact add message") m := &Message{} p.MessageInteractions = append(p.MessageInteractions, m) return m }
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L1134-L1136
func (c *Condition) Where(cond interface{}, args ...interface{}) *Condition { return c.appendQueryByCondOrExpr("Where", 0, Where, cond, args...) }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/iterator.go#L62-L68
func (it *Iterator) Seek(itm unsafe.Pointer) bool { it.valid = true found := it.s.findPath(itm, it.cmp, it.buf, &it.s.Stats) != nil it.prev = it.buf.preds[0] it.curr = it.buf.succs[0] return found }
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L89-L91
func (now *Now) EndOfQuarter() time.Time { return now.BeginningOfQuarter().AddDate(0, 3, 0).Add(-time.Nanosecond) }
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/nsqlookup/topology.go#L45-L48
func ClientIP(ctx context.Context) net.IP { ip, _ := ctx.Value(clientIPKey{}).(net.IP) return ip }
https://github.com/stvp/pager/blob/17442a04891b757880b72d926848df3e3af06c15/pager.go#L69-L71
func (p *Pager) Trigger(description string) (incidentKey string, err error) { return p.trigger(description, "", map[string]interface{}{}) }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/object.go#L230-L232
func (p *Process) Addr(x Object) core.Address { return core.Address(x) }
https://github.com/adamzy/cedar-go/blob/80a9c64b256db37ac20aff007907c649afb714f1/io.go#L55-L63
func (da *Cedar) LoadFromFile(fileName string, dataType string) error { file, err := os.OpenFile(fileName, os.O_RDONLY, 0600) defer file.Close() if err != nil { return err } in := bufio.NewReader(file) return da.Load(in, dataType) }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tclogin/tclogin.go#L126-L130
func (login *Login) OidcCredentials(provider string) (*CredentialsResponse, error) { cd := tcclient.Client(*login) responseObject, _, err := (&cd).APICall(nil, "GET", "/oidc-credentials/"+url.QueryEscape(provider), new(CredentialsResponse), nil) return responseObject.(*CredentialsResponse), err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/easyjson.go#L736-L740
func (v *InsertTextParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoInput5(&r, v) return r.Error() }