_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/partitions.go#L95-L99
func (c *partitionConsumer) Close() error { c.AsyncClose() <-c.dead return c.closeErr }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/service/broker_service.go#L91-L102
func getBrokeredService(name string) (Service, error) { catalogName, serviceName, err := splitBrokerService(name) if err != nil { return Service{}, err } client, err := newBrokeredServiceClient(name) if err != nil { return Service{}, err } s, _, err := client.getService(serviceName, catalogName) return s, err }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/binding/binding.go#L66-L71
func Register(contentType string, fn Binder) { lock.Lock() defer lock.Unlock() binders[strings.ToLower(contentType)] = fn }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd-benchmark/benchmark/benchmark.go#L131-L157
func StartContainers(c lxd.ContainerServer, containers []api.Container, parallel int) (time.Duration, error) { var duration time.Duration batchSize, err := getBatchSize(parallel) if err != nil { return duration, err } count := len(containers) logf("Starting %d containers", count) batchStart := func(index int, wg *sync.WaitGroup) { defer wg.Done() container := containers[index] if !container.IsActive() { err := startContainer(c, container.Name) if err != nil { logf("Failed to start container '%s': %s", container.Name, err) return } } } duration = processBatch(count, batchSize, batchStart) return duration, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/lease/lessor.go#L841-L845
func (l *Lease) forever() { l.expiryMu.Lock() defer l.expiryMu.Unlock() l.expiry = forever }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/key_index.go#L304-L325
func (ki *keyIndex) findGeneration(rev int64) *generation { lastg := len(ki.generations) - 1 cg := lastg for cg >= 0 { if len(ki.generations[cg].revs) == 0 { cg-- continue } g := ki.generations[cg] if cg != lastg { if tomb := g.revs[len(g.revs)-1].main; tomb <= rev { return nil } } if g.revs[0].main <= rev { return &ki.generations[cg] } cg-- } return nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/reader.go#L45-L50
func NewReader(reader io.Reader) *Reader { r := readerPool.Get().(*Reader) r.reader = reader r.err = nil return r }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/tide.go#L419-L430
func (cp *TideContextPolicy) Validate() error { if inter := sets.NewString(cp.RequiredContexts...).Intersection(sets.NewString(cp.OptionalContexts...)); inter.Len() > 0 { return fmt.Errorf("contexts %s are defined as required and optional", strings.Join(inter.List(), ", ")) } if inter := sets.NewString(cp.RequiredContexts...).Intersection(sets.NewString(cp.RequiredIfPresentContexts...)); inter.Len() > 0 { return fmt.Errorf("contexts %s are defined as required and required if present", strings.Join(inter.List(), ", ")) } if inter := sets.NewString(cp.OptionalContexts...).Intersection(sets.NewString(cp.RequiredIfPresentContexts...)); inter.Len() > 0 { return fmt.Errorf("contexts %s are defined as optional and required if present", strings.Join(inter.List(), ", ")) } return nil }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/encode.go#L32-L64
func (p *Part) Encode(writer io.Writer) error { if p.Header == nil { p.Header = make(textproto.MIMEHeader) } cte := p.setupMIMEHeaders() // Encode this part. b := bufio.NewWriter(writer) p.encodeHeader(b) if len(p.Content) > 0 { b.Write(crnl) if err := p.encodeContent(b, cte); err != nil { return err } } if p.FirstChild == nil { return b.Flush() } // Encode children. endMarker := []byte("\r\n--" + p.Boundary + "--") marker := endMarker[:len(endMarker)-2] c := p.FirstChild for c != nil { b.Write(marker) b.Write(crnl) if err := c.Encode(b); err != nil { return err } c = c.NextSibling } b.Write(endMarker) b.Write(crnl) return b.Flush() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L922-L926
func (v *GetTargetInfoParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget9(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/security/easyjson.go#L203-L207
func (v StateExplanation) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoSecurity(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/agent/server.go#L61-L74
func NewServer( lg *zap.Logger, network string, address string, ) *Server { return &Server{ lg: lg, network: network, address: address, last: rpcpb.Operation_NOT_STARTED, advertiseClientPortToProxy: make(map[int]proxy.Server), advertisePeerPortToProxy: make(map[int]proxy.Server), } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L470-L472
func (p *SendMessageToTargetParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSendMessageToTarget, p, nil) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1509-L1513
func (v *EventLastSeenObjectID) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeapprofiler17(&r, v) return r.Error() }
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/token.go#L420-L431
func (tkn *Tokenizer) Lex(lval *yySymType) int { typ, val := tkn.Scan() for typ == COMMENT { if tkn.AllowComments { break } typ, val = tkn.Scan() } lval.bytes = val tkn.lastToken = val return typ }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pubsub/subscriber/subscriber.go#L48-L53
func (pe *PeriodicProwJobEvent) FromPayload(data []byte) error { if err := json.Unmarshal(data, pe); err != nil { return err } return nil }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/item.go#L61-L76
func (m *Nitro) EncodeItem(itm *Item, buf []byte, w io.Writer) error { l := 2 if len(buf) < l { return errNotEnoughSpace } binary.BigEndian.PutUint16(buf[0:2], uint16(itm.dataLen)) if _, err := w.Write(buf[0:2]); err != nil { return err } if _, err := w.Write(itm.Bytes()); err != nil { return err } return nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L205-L209
func (n *NetworkTransport) setupStreamContext() { ctx, cancel := context.WithCancel(context.Background()) n.streamCtx = ctx n.streamCancel = cancel }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/types.go#L459-L461
func (t APIType) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_src.go#L245-L262
func (s *dockerImageSource) GetBlob(ctx context.Context, info types.BlobInfo, cache types.BlobInfoCache) (io.ReadCloser, int64, error) { if len(info.URLs) != 0 { return s.getExternalBlob(ctx, info.URLs) } path := fmt.Sprintf(blobsPath, reference.Path(s.ref.ref), info.Digest.String()) logrus.Debugf("Downloading %s", path) res, err := s.c.makeRequest(ctx, "GET", path, nil, nil, v2Auth, nil) if err != nil { return nil, 0, err } if res.StatusCode != http.StatusOK { // print url also return nil, 0, errors.Errorf("Invalid status code returned when fetching blob %d (%s)", res.StatusCode, http.StatusText(res.StatusCode)) } cache.RecordKnownLocation(s.ref.Transport(), bicTransportScope(s.ref), info.Digest, newBICLocationReference(s.ref)) return res.Body, getBlobSize(res), nil }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dsvg/gc.go#L67-L70
func (gc *GraphicContext) FillStroke(paths ...*draw2d.Path) { gc.drawPaths(filled|stroked, paths...) gc.Current.Path.Clear() }
https://github.com/jpillora/velox/blob/42845d32322027cde41ba6b065a083ea4120238f/go/conn.go#L76-L123
func (c *conn) connect(w http.ResponseWriter, r *http.Request) error { //choose transport if r.Header.Get("Accept") == "text/event-stream" { c.transport = &eventSourceTransport{writeTimeout: c.state.WriteTimeout} } else if r.Header.Get("Upgrade") == "websocket" { c.transport = &websocketsTransport{writeTimeout: c.state.WriteTimeout} } else { return fmt.Errorf("Invalid sync request") } //non-blocking connect to client over set transport if err := c.transport.connect(w, r); err != nil { return err } //initial ping if err := c.send(&update{Ping: true}); err != nil { return fmt.Errorf("Failed to send initial event") } //successfully connected c.connected = true c.waiter.Add(1) //while connected, ping loop (every 25s, browser timesout after 30s) go func() { for { select { case <-time.After(c.state.PingInterval): if err := c.send(&update{Ping: true}); err != nil { goto disconnected } case <-c.connectedCh: goto disconnected } } disconnected: c.connected = false c.Close() //unblock waiters c.waiter.Done() }() //non-blocking wait on connection go func() { if err := c.transport.wait(); err != nil { //log error? } close(c.connectedCh) }() //now connected, consumer can connection.Wait() return nil }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/task_all_of1.go#L116-L121
func (m *TaskAllOf1) validateReasonEnum(path, location string, value string) error { if err := validate.Enum(path, location, value, taskAllOf1TypeReasonPropEnum); err != nil { return err } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L4978-L4982
func (v EventScreencastVisibilityChanged) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage51(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/module/module.go#L31-L45
func NumInstances(c context.Context, module, version string) (int, error) { req := &pb.GetNumInstancesRequest{} if module != "" { req.Module = &module } if version != "" { req.Version = &version } res := &pb.GetNumInstancesResponse{} if err := internal.Call(c, "modules", "GetNumInstances", req, res); err != nil { return 0, err } return int(*res.Instances), nil }
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsPZ.go#L154-L158
func SliceF(start, end int) func(string) string { return func(s string) string { return Slice(s, start, end) } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L961-L1009
func (c *Cluster) StoragePoolVolumeCreate(project, volumeName, volumeDescription string, volumeType int, snapshot bool, poolID int64, volumeConfig map[string]string) (int64, error) { var thisVolumeID int64 err := c.Transaction(func(tx *ClusterTx) error { nodeIDs := []int{int(c.nodeID)} driver, err := storagePoolDriverGet(tx.tx, poolID) if err != nil { return err } // If the driver is ceph, create a volume entry for each node. if driver == "ceph" { nodeIDs, err = query.SelectIntegers(tx.tx, "SELECT id FROM nodes") if err != nil { return err } } for _, nodeID := range nodeIDs { result, err := tx.tx.Exec(` INSERT INTO storage_volumes (storage_pool_id, node_id, type, snapshot, name, description, project_id) VALUES (?, ?, ?, ?, ?, ?, (SELECT id FROM projects WHERE name = ?)) `, poolID, nodeID, volumeType, snapshot, volumeName, volumeDescription, project) if err != nil { return err } volumeID, err := result.LastInsertId() if err != nil { return err } if int64(nodeID) == c.nodeID { // Return the ID of the volume created on this node. thisVolumeID = volumeID } err = StorageVolumeConfigAdd(tx.tx, volumeID, volumeConfig) if err != nil { tx.tx.Rollback() return err } } return nil }) if err != nil { thisVolumeID = -1 } return thisVolumeID, err }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/metadata/resource.go#L61-L68
func (r *Resource) HasLink(name string) bool { for n, _ := range r.Links { if n == name { return true } } return false }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/clientset/versioned/clientset.go#L51-L69
func NewForConfig(c *rest.Config) (*Clientset, error) { configShallowCopy := *c if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) } var cs Clientset var err error cs.tsuruV1, err = tsuruv1.NewForConfig(&configShallowCopy) if err != nil { return nil, err } cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) if err != nil { glog.Errorf("failed to create the DiscoveryClient: %v", err) return nil, err } return &cs, nil }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/swagger.go#L110-L116
func (d *Doc) Ref(r Ref) *Definition { if refIF, ok := r["$ref"]; ok { refKey := strings.TrimPrefix(refIF.(string), "#/definitions/") return d.Definitions[refKey] } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/agent.go#L46-L100
func (ca *Agent) Start(prowConfig, jobConfig string) error { c, err := Load(prowConfig, jobConfig) if err != nil { return err } ca.Set(c) go func() { var lastModTime time.Time // Rarely, if two changes happen in the same second, mtime will // be the same for the second change, and an mtime-based check would // fail. Reload periodically just in case. skips := 0 for range time.Tick(1 * time.Second) { if skips < 600 { // Check if the file changed to see if it needs to be re-read. // os.Stat follows symbolic links, which is how ConfigMaps work. prowStat, err := os.Stat(prowConfig) if err != nil { logrus.WithField("prowConfig", prowConfig).WithError(err).Error("Error loading prow config.") continue } recentModTime := prowStat.ModTime() // TODO(krzyzacy): allow empty jobConfig till fully migrate config to subdirs if jobConfig != "" { jobConfigStat, err := os.Stat(jobConfig) if err != nil { logrus.WithField("jobConfig", jobConfig).WithError(err).Error("Error loading job configs.") continue } if jobConfigStat.ModTime().After(recentModTime) { recentModTime = jobConfigStat.ModTime() } } if !recentModTime.After(lastModTime) { skips++ continue // file hasn't been modified } lastModTime = recentModTime } if c, err := Load(prowConfig, jobConfig); err != nil { logrus.WithField("prowConfig", prowConfig). WithField("jobConfig", jobConfig). WithError(err).Error("Error loading config.") } else { skips = 0 ca.Set(c) } } }() return nil }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/type.go#L129-L165
func fromString(str string) (Type, error) { enum := strings.ToLower(str) switch enum { case "unknown": return Unknown, nil case "internal": return Internal, nil case "invalid argument": return InvalidArgument, nil case "out of range": return OutOfRange, nil case "not found": return NotFound, nil case "conflict": return Conflict, nil case "already exists": return AlreadyExists, nil case "unauthorized": return Unauthorized, nil case "permission denied": return PermissionDenied, nil case "timeout": return Timeout, nil case "not implemented": return NotImplemented, nil case "temporarily unavailable": return TemporarilyUnavailable, nil case "permanently unavailable": return PermanentlyUnavailable, nil case "canceled": return Canceled, nil case "resource exhausted": return ResourceExhausted, nil default: return Unknown, fmt.Errorf("Invalid error type") } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L5379-L5383
func (v EventInlineStyleInvalidated) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom60(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/etcdhttp/metrics.go#L37-L40
func HandleMetricsHealth(mux *http.ServeMux, srv etcdserver.ServerV2) { mux.Handle(PathMetrics, promhttp.Handler()) mux.Handle(PathHealth, NewHealthHandler(func() Health { return checkHealth(srv) })) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L55-L65
func defaultPolicyPath(sys *types.SystemContext) string { if sys != nil { if sys.SignaturePolicyPath != "" { return sys.SignaturePolicyPath } if sys.RootForImplicitAbsolutePaths != "" { return filepath.Join(sys.RootForImplicitAbsolutePaths, systemDefaultPolicyPath) } } return systemDefaultPolicyPath }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/concourse.go#L77-L83
func (s *ConcoursePipeline) AddResource(name string, typename string, source map[string]interface{}) { s.Resources = append(s.Resources, atc.ResourceConfig{ Name: name, Type: typename, Source: source, }) }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L549-L551
func FindSequencesOnDisk(path string, opts ...FileOption) (FileSequences, error) { return findSequencesOnDisk(path, opts...) }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L3219-L3224
func (o *ListStringOption) Set(value string) error { val := StringOption{} val.Set(value) *o = append(*o, val) return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/netutil/routes_linux.go#L36-L65
func GetDefaultHost() (string, error) { rmsgs, rerr := getDefaultRoutes() if rerr != nil { return "", rerr } // prioritize IPv4 if rmsg, ok := rmsgs[syscall.AF_INET]; ok { if host, err := chooseHost(syscall.AF_INET, rmsg); host != "" || err != nil { return host, err } delete(rmsgs, syscall.AF_INET) } // sort so choice is deterministic var families []int for family := range rmsgs { families = append(families, int(family)) } sort.Ints(families) for _, f := range families { family := uint8(f) if host, err := chooseHost(family, rmsgs[family]); host != "" || err != nil { return host, err } } return "", errNoDefaultHost }
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/filehandler.go#L86-L91
func (h *RotatingFileHandler) Write(p []byte) (n int, err error) { h.doRollover() n, err = h.fd.Write(p) h.curBytes += n return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/reporter/reporter.go#L54-L72
func (c *Client) ShouldReport(pj *v1.ProwJob) bool { if !pj.Spec.Report { // Respect report field return false } if pj.Spec.Type != v1.PresubmitJob && pj.Spec.Type != v1.PostsubmitJob { // Report presubmit and postsubmit github jobs for github reporter return false } if c.reportAgent != "" && pj.Spec.Agent != c.reportAgent { // Only report for specified agent return false } return true }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/datacenter.go#L91-L95
func (c *Client) DeleteDatacenter(dcid string) (*http.Header, error) { url := dcPath(dcid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &http.Header{} return ret, c.client.Delete(url, ret, http.StatusAccepted) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L5427-L5431
func (v *AwaitPromiseReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime50(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L294-L337
func (c *Cluster) ProfileContainersGet(project, profile string) (map[string][]string, error) { err := c.Transaction(func(tx *ClusterTx) error { enabled, err := tx.ProjectHasProfiles(project) if err != nil { return errors.Wrap(err, "Check if project has profiles") } if !enabled { project = "default" } return nil }) if err != nil { return nil, err } q := `SELECT containers.name, projects.name FROM containers JOIN containers_profiles ON containers.id == containers_profiles.container_id JOIN projects ON projects.id == containers.project_id WHERE containers_profiles.profile_id == (SELECT profiles.id FROM profiles JOIN projects ON projects.id == profiles.project_id WHERE profiles.name=? AND projects.name=?) AND containers.type == 0` results := map[string][]string{} inargs := []interface{}{profile, project} var name string outfmt := []interface{}{name, name} output, err := queryScan(c.db, q, inargs, outfmt) if err != nil { return nil, err } for _, r := range output { if results[r[1].(string)] == nil { results[r[1].(string)] = []string{} } results[r[1].(string)] = append(results[r[1].(string)], r[0].(string)) } return results, nil }
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/format.go#L341-L360
func formatFuncName(v fmtVerb, f string) string { i := strings.LastIndex(f, "/") j := strings.Index(f[i+1:], ".") if j < 1 { return "???" } pkg, fun := f[:i+j+1], f[i+j+2:] switch v { case fmtVerbLongpkg: return pkg case fmtVerbShortpkg: return path.Base(pkg) case fmtVerbLongfunc: return fun case fmtVerbShortfunc: i = strings.LastIndex(fun, ".") return fun[i+1:] } panic("unexpected func formatter") }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/peribolos/main.go#L850-L895
func configureTeam(client editTeamClient, orgName, teamName string, team org.Team, gt github.Team, parent *int) error { // Do we need to reconfigure any team settings? patch := false if gt.Name != teamName { patch = true } gt.Name = teamName if team.Description != nil && gt.Description != *team.Description { patch = true gt.Description = *team.Description } else { gt.Description = "" } // doesn't have parent in github, but has parent in config if gt.Parent == nil && parent != nil { patch = true gt.ParentTeamID = parent } if gt.Parent != nil { // has parent in github ... if parent == nil { // ... but doesn't need one patch = true gt.Parent = nil gt.ParentTeamID = parent } else if gt.Parent.ID != *parent { // but it's different than the config patch = true gt.Parent = nil gt.ParentTeamID = parent } } if team.Privacy != nil && gt.Privacy != string(*team.Privacy) { patch = true gt.Privacy = string(*team.Privacy) } else if team.Privacy == nil && (parent != nil || len(team.Children) > 0) && gt.Privacy != "closed" { patch = true gt.Privacy = github.PrivacyClosed // nested teams must be closed } if patch { // yes we need to patch if _, err := client.EditTeam(gt); err != nil { return fmt.Errorf("failed to edit %s team %d(%s): %v", orgName, gt.ID, gt.Name, err) } } return nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/replication.go#L121-L170
func (r *Raft) replicate(s *followerReplication) { // Start an async heartbeating routing stopHeartbeat := make(chan struct{}) defer close(stopHeartbeat) r.goFunc(func() { r.heartbeat(s, stopHeartbeat) }) RPC: shouldStop := false for !shouldStop { select { case maxIndex := <-s.stopCh: // Make a best effort to replicate up to this index if maxIndex > 0 { r.replicateTo(s, maxIndex) } return case <-s.triggerCh: lastLogIdx, _ := r.getLastLog() shouldStop = r.replicateTo(s, lastLogIdx) // This is _not_ our heartbeat mechanism but is to ensure // followers quickly learn the leader's commit index when // raft commits stop flowing naturally. The actual heartbeats // can't do this to keep them unblocked by disk IO on the // follower. See https://github.com/hashicorp/raft/issues/282. case <-randomTimeout(r.conf.CommitTimeout): lastLogIdx, _ := r.getLastLog() shouldStop = r.replicateTo(s, lastLogIdx) } // If things looks healthy, switch to pipeline mode if !shouldStop && s.allowPipeline { goto PIPELINE } } return PIPELINE: // Disable until re-enabled s.allowPipeline = false // Replicates using a pipeline for high performance. This method // is not able to gracefully recover from errors, and so we fall back // to standard mode on failure. if err := r.pipelineReplicate(s); err != nil { if err != ErrPipelineReplicationNotSupported { r.logger.Error(fmt.Sprintf("Failed to start pipeline replication to %s: %s", s.peer, err)) } } goto RPC }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/membership/cluster.go#L331-L354
func (c *RaftCluster) AddMember(m *Member) { c.Lock() defer c.Unlock() if c.v2store != nil { mustSaveMemberToStore(c.v2store, m) } if c.be != nil { mustSaveMemberToBackend(c.be, m) } c.members[m.ID] = m if c.lg != nil { c.lg.Info( "added member", zap.String("cluster-id", c.cid.String()), zap.String("local-member-id", c.localID.String()), zap.String("added-peer-id", m.ID.String()), zap.Strings("added-peer-peer-urls", m.PeerURLs), ) } else { plog.Infof("added member %s %v to cluster %s", m.ID, m.PeerURLs, c.cid) } }
https://github.com/fossapps/pushy/blob/4c6045d7a1d3c310d61168ff1ccd5421d5c162f6/pushy.go#L75-L81
func (p *Pushy) DeleteNotification(pushID string) (*SimpleSuccess, *Error, error) { url := fmt.Sprintf("%s/pushes/%s?api_key=%s", p.APIEndpoint, pushID, p.APIToken) var success *SimpleSuccess var pushyErr *Error err := del(p.httpClient, url, &success, &pushyErr) return success, pushyErr, err }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L936-L938
func (r *NotificationRule) Locator(api *API) *NotificationRuleLocator { return api.NotificationRuleLocator(r.Href) }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/minifier/minifier.go#L45-L53
func NewHandler(h http.Handler, logFunc LogFunc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mw := &minifyResponseWriter{mw: minifier.ResponseWriter(w, r), w: w} h.ServeHTTP(mw, r) if err := mw.Close(); err != nil && err != minify.ErrNotExist && logFunc != nil { logFunc("minifier %q: %v", r.URL.String(), err) } }) }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/options.go#L327-L337
func Comparer(f interface{}) Option { v := reflect.ValueOf(f) if !function.IsType(v.Type(), function.Equal) || v.IsNil() { panic(fmt.Sprintf("invalid comparer function: %T", f)) } cm := &comparer{fnc: v} if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 { cm.typ = ti } return cm }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/secret/secret.go#L26-L37
func LoadSecrets(paths []string) (map[string][]byte, error) { secretsMap := make(map[string][]byte, len(paths)) for _, path := range paths { secretValue, err := LoadSingleSecret(path) if err != nil { return nil, err } secretsMap[path] = secretValue } return secretsMap, nil }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L145-L165
func (b *Base) AddLogger(logger Logger) error { if b.IsInitialized() && !logger.IsInitialized() { err := logger.InitLogger() if err != nil { return err } } else if !b.IsInitialized() && logger.IsInitialized() { err := logger.ShutdownLogger() if err != nil { return err } } b.loggers = append(b.loggers, logger) if hook, ok := logger.(HookPreQueue); ok { b.hookPreQueue = append(b.hookPreQueue, hook) } logger.SetBase(b) return nil }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ss.go#L76-L81
func removePrefixes(r *regexp.Regexp, num int) (result *regexp.Regexp) { path := strings.TrimLeft(r.String(), "/") paths := strings.Split(path, "/") result = regexp.MustCompile("/" + strings.Join(paths[num:], "/")) return }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/plugin/vault/pachyderm/helpers.go#L19-L32
func validateFields(req *logical.Request, data *framework.FieldData) error { var unknownFields []string for k := range req.Data { if _, ok := data.Schema[k]; !ok { unknownFields = append(unknownFields, k) } } if len(unknownFields) > 0 { return fmt.Errorf("unknown fields: %q", unknownFields) } return nil }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqinfo/seqinfo.go#L188-L200
func printJsonResults(results Results) error { data, err := json.MarshalIndent(results, "", " ") if err != nil { return fmt.Errorf("Failed to convert results to JSON: %s", err.Error()) } if _, err = io.Copy(os.Stdout, bytes.NewReader(data)); err != nil { return fmt.Errorf("Failed to write json output: %s", err.Error()) } fmt.Print("\n") return nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L1092-L1098
func clientcmdNewConfig() *clientcmdConfig { return &clientcmdConfig{ Clusters: make(map[string]*clientcmdCluster), AuthInfos: make(map[string]*clientcmdAuthInfo), Contexts: make(map[string]*clientcmdContext), } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/node.go#L110-L116
func (n *node) Read() (string, *v2error.Error) { if n.IsDir() { return "", v2error.NewError(v2error.EcodeNotFile, "", n.store.CurrentIndex) } return n.Value, nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/subchannel.go#L194-L199
func (subChMap *subChannelMap) get(serviceName string) (*SubChannel, bool) { subChMap.RLock() sc, ok := subChMap.subchannels[serviceName] subChMap.RUnlock() return sc, ok }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/generate.go#L493-L542
func (g *generator) options(opts rule.PlatformStrings, pkgRel string) rule.PlatformStrings { fixPath := func(opt string) string { if strings.HasPrefix(opt, "/") { return opt } return path.Clean(path.Join(pkgRel, opt)) } fixGroups := func(groups []string) ([]string, error) { fixedGroups := make([]string, len(groups)) for i, group := range groups { opts := strings.Split(group, optSeparator) fixedOpts := make([]string, len(opts)) isPath := false for j, opt := range opts { if isPath { opt = fixPath(opt) isPath = false goto next } for _, short := range shortOptPrefixes { if strings.HasPrefix(opt, short) && len(opt) > len(short) { opt = short + fixPath(opt[len(short):]) goto next } } for _, long := range longOptPrefixes { if opt == long { isPath = true goto next } } next: fixedOpts[j] = escapeOption(opt) } fixedGroups[i] = strings.Join(fixedOpts, " ") } return fixedGroups, nil } opts, errs := opts.MapSlice(fixGroups) if errs != nil { log.Panicf("unexpected error when transforming options with pkg %q: %v", pkgRel, errs) } return opts }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/samples/gopher/gopher.go#L17-L26
func Main(gc draw2d.GraphicContext, ext string) (string, error) { gc.Save() gc.Scale(0.5, 0.5) // Draw a (partial) gopher Draw(gc) gc.Restore() // Return the output filename return samples.Output("gopher", ext), nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L337-L340
func (p SetEmitTouchEventsForMouseParams) WithConfiguration(configuration SetEmitTouchEventsForMouseConfiguration) *SetEmitTouchEventsForMouseParams { p.Configuration = configuration return &p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L6698-L6702
func (v AddRuleReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss63(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/clientset/versioned/typed/prowjobs/v1/prowjob.go#L78-L87
func (c *prowJobs) List(opts metav1.ListOptions) (result *v1.ProwJobList, err error) { result = &v1.ProwJobList{} err = c.client.Get(). Namespace(c.ns). Resource("prowjobs"). VersionedParams(&opts, scheme.ParameterCodec). Do(). Into(result) return }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gexec/session.go#L255-L261
func Kill() { trackedSessionsMutex.Lock() defer trackedSessionsMutex.Unlock() for _, session := range trackedSessions { session.Kill() } }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L525-L535
func layerDigestsDiffer(a, b []types.BlobInfo) bool { if len(a) != len(b) { return true } for i := range a { if a[i].Digest != b[i].Digest { return true } } return false }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxtype.go#L531-L533
func (r *Rect) BR() Point { return Point{int(r.x) + int(r.width), int(r.y) + int(r.height)} }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/types.go#L346-L358
func (t *ExceptionsState) UnmarshalEasyJSON(in *jlexer.Lexer) { switch ExceptionsState(in.String()) { case ExceptionsStateNone: *t = ExceptionsStateNone case ExceptionsStateUncaught: *t = ExceptionsStateUncaught case ExceptionsStateAll: *t = ExceptionsStateAll default: in.AddError(errors.New("unknown ExceptionsState value")) } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/dco/dco.go#L103-L121
func checkCommitMessages(gc gitHubClient, l *logrus.Entry, org, repo string, number int) ([]github.GitCommit, error) { allCommits, err := gc.ListPRCommits(org, repo, number) if err != nil { return nil, fmt.Errorf("error listing commits for pull request: %v", err) } l.Debugf("Found %d commits in PR", len(allCommits)) var commitsMissingDCO []github.GitCommit for _, commit := range allCommits { if !testRe.MatchString(commit.Commit.Message) { c := commit.Commit c.SHA = commit.SHA commitsMissingDCO = append(commitsMissingDCO, c) } } l.Debugf("All commits in PR have DCO signoff: %t", len(commitsMissingDCO) == 0) return commitsMissingDCO, nil }
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/response_wrapper.go#L48-L55
func (w *ResponseWrapper) CloseNotify() <-chan bool { if notifier, ok := w.writer.(http.CloseNotifier); ok { c := notifier.CloseNotify() return c } return make(chan bool) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/skl/arena.go#L63-L78
func (s *Arena) putNode(height int) uint32 { // Compute the amount of the tower that will never be used, since the height // is less than maxHeight. unusedSize := (maxHeight - height) * offsetSize // Pad the allocation with enough bytes to ensure pointer alignment. l := uint32(MaxNodeSize - unusedSize + nodeAlign) n := atomic.AddUint32(&s.n, l) y.AssertTruef(int(n) <= len(s.buf), "Arena too small, toWrite:%d newTotal:%d limit:%d", l, n, len(s.buf)) // Return the aligned offset. m := (n - l + uint32(nodeAlign)) & ^uint32(nodeAlign) return m }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/frameset.go#L152-L154
func (s *FrameSet) Frame(index int) (int, error) { return s.rangePtr.Value(index) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L5966-L5970
func (v EventStyleSheetAdded) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss53(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L356-L358
func (l *Logger) Warnln(args ...interface{}) { l.Output(2, LevelWarn, fmt.Sprintln(args...)) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1055-L1068
func (w *Writer) Copy(r *Reader) error { for { n, err := r.Read() if err != nil { if err == io.EOF { return nil } return err } if err := w.Write(n); err != nil { return err } } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L270-L277
func (w *WriteBuffer) WriteLen16String(s string) { if int(uint16(len(s))) != len(s) { w.setErr(errStringTooLong) } w.WriteUint16(uint16(len(s))) w.WriteString(s) }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/decode.go#L1133-L1148
func (d Decoder) DecodeArray(f func(Decoder) error) (err error) { var typ Type if d.off != 0 { if d.off, err = 0, d.Parser.ParseMapValue(d.off-1); err != nil { return } } if typ, err = d.Parser.ParseType(); err != nil { return } err = d.decodeArrayImpl(typ, f) return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L4675-L4679
func (v CompileScriptReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime44(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L471-L492
func (v Value) Kind() ValueKind { switch v.data.(type) { default: return Null case bool: return Bool case int64: return Integer case float64: return Real case string: return String case name: return Name case dict: return Dict case array: return Array case stream: return Stream } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L4325-L4329
func (v *EventBreakpointResolved) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger41(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/storage.go#L36-L38
func (p *ClearDataForOriginParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandClearDataForOrigin, p, nil) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/types/id.go#L29-L32
func IDFromString(s string) (ID, error) { i, err := strconv.ParseUint(s, 16, 64) return ID(i), err }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2auth/auth.go#L564-L572
func (p Permissions) Revoke(lg *zap.Logger, n *Permissions) (Permissions, error) { var out Permissions var err error if n == nil { return p, nil } out.KV, err = p.KV.Revoke(lg, n.KV) return out, err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/history/history.go#L114-L137
func New(maxRecordsPerKey int, opener io.Opener, path string) (*History, error) { hist := &History{ logs: map[string]*recordLog{}, logSizeLimit: maxRecordsPerKey, opener: opener, path: path, } if path != "" { // Load existing history from GCS. var err error start := time.Now() hist.logs, err = readHistory(maxRecordsPerKey, hist.opener, hist.path) if err != nil { return nil, err } logrus.WithFields(logrus.Fields{ "duration": time.Since(start).String(), "path": hist.path, }).Debugf("Successfully read action history for %d pools.", len(hist.logs)) } return hist, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L562-L566
func (v RareIntegerData) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomsnapshot2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L5382-L5386
func (v *EventLifecycleEvent) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage55(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L3025-L3049
func (c *containerLXC) setupHostVethDevice(device types.Device) error { // If not already, populate network device with host name. if device["host_name"] == "" { device["host_name"] = c.getHostInterface(device["name"]) } // Check whether host device resolution succeeded. if device["host_name"] == "" { return fmt.Errorf("LXC doesn't know about this device and the host_name property isn't set, can't find host side veth name") } // Refresh tc limits err := c.setNetworkLimits(device) if err != nil { return err } // Setup static routes to container err = c.setNetworkRoutes(device) if err != nil { return err } return nil }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L69-L71
func (s *selectable) Find(selector string) *Selection { return newSelection(s.session, s.selectors.Append(target.CSS, selector).Single()) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_pools.go#L480-L487
func storagePoolValidateClusterConfig(reqConfig map[string]string) error { for key := range reqConfig { if shared.StringInSlice(key, db.StoragePoolNodeConfigKeys) { return fmt.Errorf("node-specific config key %s can't be changed", key) } } return nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5497-L5504
func NewLedgerHeaderHistoryEntryExt(v int32, value interface{}) (result LedgerHeaderHistoryEntryExt, err error) { result.V = v switch int32(v) { case 0: // void } return }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/log.go#L76-L80
func Debugf(format string, args ...interface{}) { if Log != nil { Log.Debug(fmt.Sprintf(format, args...)) } }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cv.go#L220-L227
func Erode(src, dst *IplImage, element *IplConvKernel, iterations int) { C.cvErode( unsafe.Pointer(src), unsafe.Pointer(dst), (*C.IplConvKernel)(unsafe.Pointer(element)), C.int(iterations), ) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/peers/prefer.go#L58-L70
func fnv32a(s string) uint32 { const ( initial = 2166136261 prime = 16777619 ) hash := uint32(initial) for i := 0; i < len(s); i++ { hash ^= uint32(s[i]) hash *= prime } return hash }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcauth/tcauth.go#L562-L566
func (auth *Auth) AzureTableSAS(account, table, level string) (*AzureTableSharedAccessSignature, error) { cd := tcclient.Client(*auth) responseObject, _, err := (&cd).APICall(nil, "GET", "/azure/"+url.QueryEscape(account)+"/table/"+url.QueryEscape(table)+"/"+url.QueryEscape(level), new(AzureTableSharedAccessSignature), nil) return responseObject.(*AzureTableSharedAccessSignature), err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L1117-L1121
func (v GetBrowserSamplingProfileReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoMemory12(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L1798-L1802
func (v CanEmulateParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoEmulation21(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L411-L419
func (kt sbKeyType) IsValid() bool { switch kt { case SBKeyTypeGPGKeys, SBKeyTypeSignedByGPGKeys, SBKeyTypeX509Certificates, SBKeyTypeSignedByX509CAs: return true default: return false } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L322-L480
func (r *ProtocolLXD) CreateImage(image api.ImagesPost, args *ImageCreateArgs) (Operation, error) { if image.CompressionAlgorithm != "" { if !r.HasExtension("image_compression_algorithm") { return nil, fmt.Errorf("The server is missing the required \"image_compression_algorithm\" API extension") } } // Send the JSON based request if args == nil { op, _, err := r.queryOperation("POST", "/images", image, "") if err != nil { return nil, err } return op, nil } // Prepare an image upload if args.MetaFile == nil { return nil, fmt.Errorf("Metadata file is required") } // Prepare the body var body io.Reader var contentType string if args.RootfsFile == nil { // If unified image, just pass it through body = args.MetaFile contentType = "application/octet-stream" } else { // If split image, we need mime encoding tmpfile, err := ioutil.TempFile("", "lxc_image_") if err != nil { return nil, err } defer os.Remove(tmpfile.Name()) // Setup the multipart writer w := multipart.NewWriter(tmpfile) // Metadata file fw, err := w.CreateFormFile("metadata", args.MetaName) if err != nil { return nil, err } _, err = io.Copy(fw, args.MetaFile) if err != nil { return nil, err } // Rootfs file fw, err = w.CreateFormFile("rootfs", args.RootfsName) if err != nil { return nil, err } _, err = io.Copy(fw, args.RootfsFile) if err != nil { return nil, err } // Done writing to multipart w.Close() // Figure out the size of the whole thing size, err := tmpfile.Seek(0, 2) if err != nil { return nil, err } _, err = tmpfile.Seek(0, 0) if err != nil { return nil, err } // Setup progress handler if args.ProgressHandler != nil { body = &ioprogress.ProgressReader{ ReadCloser: tmpfile, Tracker: &ioprogress.ProgressTracker{ Length: size, Handler: func(percent int64, speed int64) { args.ProgressHandler(ioprogress.ProgressData{Text: fmt.Sprintf("%d%% (%s/s)", percent, shared.GetByteSizeString(speed, 2))}) }, }, } } else { body = tmpfile } contentType = w.FormDataContentType() } // Prepare the HTTP request reqURL, err := r.setQueryAttributes(fmt.Sprintf("%s/1.0/images", r.httpHost)) if err != nil { return nil, err } req, err := http.NewRequest("POST", reqURL, body) if err != nil { return nil, err } // Setup the headers req.Header.Set("Content-Type", contentType) if image.Public { req.Header.Set("X-LXD-public", "true") } if image.Filename != "" { req.Header.Set("X-LXD-filename", image.Filename) } if len(image.Properties) > 0 { imgProps := url.Values{} for k, v := range image.Properties { imgProps.Set(k, v) } req.Header.Set("X-LXD-properties", imgProps.Encode()) } // Set the user agent if r.httpUserAgent != "" { req.Header.Set("User-Agent", r.httpUserAgent) } // Send the request resp, err := r.do(req) if err != nil { return nil, err } defer resp.Body.Close() // Handle errors response, _, err := lxdParseResponse(resp) if err != nil { return nil, err } // Get to the operation respOperation, err := response.MetadataAsOperation() if err != nil { return nil, err } // Setup an Operation wrapper op := operation{ Operation: *respOperation, r: r, chActive: make(chan bool), } return &op, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L4424-L4428
func (v *EvaluateOnCallFrameReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger42(&r, v) return r.Error() }