_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/enaml.go#L6-L14
func Paint(deployment Deployment) (result string, err error) { var deploymentManifest DeploymentManifest deploymentManifest = deployment.GetDeployment() var dmYaml []byte if dmYaml, err = yaml.Marshal(deploymentManifest); err == nil { result = string(dmYaml) } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L792-L796
func (v *SetFileInputFilesParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom7(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L502-L528
func (h *dbHashTree) Serialize(_w io.Writer) error { w := pbutil.NewWriter(_w) return h.View(func(tx *bolt.Tx) error { for _, bucket := range buckets { b := tx.Bucket(b(bucket)) if _, err := w.Write( &BucketHeader{ Bucket: bucket, }); err != nil { return err } if err := b.ForEach(func(k, v []byte) error { if _, err := w.WriteBytes(k); err != nil { return err } _, err := w.WriteBytes(v) return err }); err != nil { return err } if _, err := w.WriteBytes(SentinelByte); err != nil { return err } } return nil }) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/task/group.go#L83-L112
func (g *Group) Stop(timeout time.Duration) error { if g.cancel == nil { // We were not even started return nil } g.cancel() graceful := make(chan struct{}, 1) go func() { g.wg.Wait() close(graceful) }() // Wait for graceful termination, but abort if the context expires. ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() select { case <-ctx.Done(): running := []string{} for i, value := range g.running { if value { running = append(running, strconv.Itoa(i)) } } return fmt.Errorf("tasks %s are still running", strings.Join(running, ", ")) case <-graceful: return nil } }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/codegenerator/model/model.go#L116-L156
func LoadAPIs(rootURL string) APIDefinitions { apiManifestURL := tcurls.APIManifest(rootURL) fmt.Printf("Downloading manifest from url: '%v'...\n", apiManifestURL) resp, err := http.Get(apiManifestURL) if err != nil { fmt.Printf("Could not download api manifest from url: '%v'!\n", apiManifestURL) } exitOnFail(err) apiManifestDecoder := json.NewDecoder(resp.Body) apiMan := TaskclusterServiceManifest{} err = apiManifestDecoder.Decode(&apiMan) exitOnFail(err) apiDefs := []*APIDefinition{} for i := range apiMan.References { var resp *http.Response resp, err = http.Get(apiMan.References[i]) exitOnFail(err) defer resp.Body.Close() apiDef := &APIDefinition{ URL: apiMan.References[i], } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // SKIP worker-manager for now, as we currently can't handle // https://github.com/taskcluster/taskcluster/blob/6282ebbcf0ddd00d5b3f7ac4b718247d615739f3/services/worker-manager/schemas/v1/worker-configuration.yml#L13-L15 // despite it being valid jsonschema: https://json-schema.org/latest/json-schema-validation.html#rfc.section.6.1.1 if apiDef.URL == tcurls.APIReference(rootURL, "worker-manager", "v1") { continue } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if apiDef.loadJSON(resp.Body, rootURL) { apiDefs = append(apiDefs, apiDef) // check that the json schema is valid! validateJSON(apiDef.SchemaURL, apiDef.URL) } } return APIDefinitions(apiDefs) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L49-L51
func (d *Destination) AddRepoTags(tags []reference.NamedTagged) { d.repoTags = append(d.repoTags, tags...) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/mock/mockserver/mockserver.go#L161-L166
func (ms *MockServers) Stop() { for idx := range ms.Servers { ms.StopAt(idx) } ms.wg.Wait() }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/fakes/fake.go#L155-L158
func (s *FakeRenderer) JSON(status int, v interface{}) { s.SpyStatus = status s.SpyValue = v }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L1475-L1479
func (v GetBrowserCommandLineReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser15(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gopherage/pkg/util/util.go#L30-L47
func DumpProfile(destination string, profile []*cover.Profile) error { var output io.Writer if destination == "-" { output = os.Stdout } else { f, err := os.Create(destination) if err != nil { return fmt.Errorf("failed to open %s: %v", destination, err) } defer f.Close() output = f } err := cov.DumpProfile(profile, output) if err != nil { return fmt.Errorf("failed to dump profile: %v", err) } return nil }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/repo/repo.go#L95-L112
func ImportRepoRules(filename string, repoCache *RemoteCache) ([]*rule.Rule, error) { format := getLockFileFormat(filename) if format == unknownFormat { return nil, fmt.Errorf(`%s: unrecognized lock file format. Expected "Gopkg.lock", "go.mod", or "Godeps.json"`, filename) } parser := lockFileParsers[format] repos, err := parser(filename, repoCache) if err != nil { return nil, fmt.Errorf("error parsing %q: %v", filename, err) } sort.Stable(byName(repos)) rules := make([]*rule.Rule, 0, len(repos)) for _, repo := range repos { rules = append(rules, GenerateRule(repo)) } return rules, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/certificates.go#L116-L123
func (c *Cluster) CertDelete(fingerprint string) error { err := exec(c.db, "DELETE FROM certificates WHERE fingerprint=?", fingerprint) if err != nil { return err } return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/netutil/routes_linux.go#L189-L224
func GetDefaultInterfaces() (map[string]uint8, error) { interfaces := make(map[string]uint8) rmsgs, rerr := getDefaultRoutes() if rerr != nil { return interfaces, rerr } for family, rmsg := range rmsgs { _, oif, err := parsePREFSRC(rmsg) if err != nil { return interfaces, err } ifmsg, ierr := getIfaceLink(oif) if ierr != nil { return interfaces, ierr } attrs, aerr := syscall.ParseNetlinkRouteAttr(ifmsg) if aerr != nil { return interfaces, aerr } for _, attr := range attrs { if attr.Attr.Type == syscall.IFLA_IFNAME { // key is an interface name // possible values: 2 - AF_INET, 10 - AF_INET6, 12 - dualstack interfaces[string(attr.Value[:len(attr.Value)-1])] += family } } } if len(interfaces) > 0 { return interfaces, nil } return interfaces, errNoDefaultInterface }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/util.go#L121-L127
func DescribeEntries(ents []pb.Entry, f EntryFormatter) string { var buf bytes.Buffer for _, e := range ents { _, _ = buf.WriteString(DescribeEntry(e, f) + "\n") } return buf.String() }
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/security/utils.go#L50-L57
func GenerateSalt() (salt []byte, err error) { salt = make([]byte, S) _, err = rand.Read(salt) if err != nil { return nil, err } return }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util.go#L756-L820
func ParseByteSizeString(input string) (int64, error) { // Empty input if input == "" { return 0, nil } // Find where the suffix begins suffixLen := 0 for i, chr := range []byte(input) { _, err := strconv.Atoi(string([]byte{chr})) if err != nil { suffixLen = len(input) - i break } } if suffixLen == len(input) { return -1, fmt.Errorf("Invalid value: %s", input) } // Extract the suffix suffix := input[len(input)-suffixLen:] // Extract the value value := input[0 : len(input)-suffixLen] valueInt, err := strconv.ParseInt(value, 10, 64) if err != nil { return -1, fmt.Errorf("Invalid integer: %s", input) } // Figure out the multiplicator multiplicator := int64(0) switch suffix { case "", "B", " bytes": multiplicator = 1 case "kB": multiplicator = 1000 case "MB": multiplicator = 1000 * 1000 case "GB": multiplicator = 1000 * 1000 * 1000 case "TB": multiplicator = 1000 * 1000 * 1000 * 1000 case "PB": multiplicator = 1000 * 1000 * 1000 * 1000 * 1000 case "EB": multiplicator = 1000 * 1000 * 1000 * 1000 * 1000 * 1000 case "KiB": multiplicator = 1024 case "MiB": multiplicator = 1024 * 1024 case "GiB": multiplicator = 1024 * 1024 * 1024 case "TiB": multiplicator = 1024 * 1024 * 1024 * 1024 case "PiB": multiplicator = 1024 * 1024 * 1024 * 1024 * 1024 case "EiB": multiplicator = 1024 * 1024 * 1024 * 1024 * 1024 * 1024 default: return -1, fmt.Errorf("Invalid value: %s", input) } return valueInt * multiplicator, nil }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/reader.go#L14-L16
func NewReaderByteCodeLoader(p parser.Parser, c compiler.Compiler) *ReaderByteCodeLoader { return &ReaderByteCodeLoader{NewFlags(), p, c} }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L122-L129
func (in *ProwJob) DeepCopyInto(out *ProwJob) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/clone/clone.go#L156-L169
func (g *gitCtx) gitHeadTimestamp() (int, error) { gitShowCommand := g.gitCommand("show", "-s", "--format=format:%ct", "HEAD") _, gitOutput, err := gitShowCommand.run() if err != nil { logrus.WithError(err).Debug("Could not obtain timestamp of git HEAD") return 0, err } timestamp, convErr := strconv.Atoi(string(gitOutput)) if convErr != nil { logrus.WithError(convErr).Errorf("Failed to parse timestamp %q", gitOutput) return 0, convErr } return timestamp, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps/util.go#L31-L47
func InputName(input *Input) string { switch { case input == nil: return "" case input.Pfs != nil: return input.Pfs.Name case input.Cross != nil: if len(input.Cross) > 0 { return InputName(input.Cross[0]) } case input.Union != nil: if len(input.Union) > 0 { return InputName(input.Union[0]) } } return "" }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/client.go#L339-L348
func (c *Client) List(opts v1.ListOptions) (Collection, error) { result := c.NewCollection() err := c.cl.Get(). Namespace(c.ns). Resource(c.t.Plural). VersionedParams(&opts, c.codec). Do(). Into(result) return result, err }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_eval.go#L108-L117
func NewPolicyContext(policy *Policy) (*PolicyContext, error) { pc := &PolicyContext{Policy: policy, state: pcInitializing} // FIXME: initialize if err := pc.changeState(pcInitializing, pcReady); err != nil { // Huh?! This should never fail, we didn't give the pointer to anybody. // Just give up and leave unclean state around. return nil, err } return pc, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/spyglass/podlogartifact_fetcher.go#L36-L43
func (af *PodLogArtifactFetcher) artifact(jobName, buildID string, sizeLimit int64) (lenses.Artifact, error) { podLog, err := NewPodLogArtifact(jobName, buildID, sizeLimit, af.jobAgent) if err != nil { return nil, fmt.Errorf("Error accessing pod log from given source: %v", err) } return podLog, nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L146-L169
func NewNetworkTransportWithConfig( config *NetworkTransportConfig, ) *NetworkTransport { if config.Logger == nil { config.Logger = log.New(os.Stderr, "", log.LstdFlags) } trans := &NetworkTransport{ connPool: make(map[ServerAddress][]*netConn), consumeCh: make(chan RPC), logger: config.Logger, maxPool: config.MaxPool, shutdownCh: make(chan struct{}), stream: config.Stream, timeout: config.Timeout, TimeoutScale: DefaultTimeoutScale, serverAddressProvider: config.ServerAddressProvider, } // Create the connection context and then start our listener. trans.setupStreamContext() go trans.listen() return trans }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/httputil/response.go#L29-L31
func BindResponseWriter(w io.Writer, c *core.Context, before ...func([]byte)) { c.ResponseWriter = responseWriterBinder{w, c.ResponseWriter, before} }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/spyglass/lenses/junit/lens.go#L57-L67
func (lens Lens) Header(artifacts []lenses.Artifact, resourceDir string) string { t, err := template.ParseFiles(filepath.Join(resourceDir, "template.html")) if err != nil { return fmt.Sprintf("<!-- FAILED LOADING HEADER: %v -->", err) } var buf bytes.Buffer if err := t.ExecuteTemplate(&buf, "header", nil); err != nil { return fmt.Sprintf("<!-- FAILED EXECUTING HEADER TEMPLATE: %v -->", err) } return buf.String() }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/appengine.go#L125-L127
func WithAPICallFunc(ctx context.Context, f APICallFunc) context.Context { return internal.WithCallOverride(ctx, internal.CallOverrideFunc(f)) }
https://github.com/coreos/go-semver/blob/e214231b295a8ea9479f11b70b35d5acf3556d9b/semver/semver.go#L71-L104
func (v *Version) Set(version string) error { metadata := splitOff(&version, "+") preRelease := PreRelease(splitOff(&version, "-")) dotParts := strings.SplitN(version, ".", 3) if len(dotParts) != 3 { return fmt.Errorf("%s is not in dotted-tri format", version) } if err := validateIdentifier(string(preRelease)); err != nil { return fmt.Errorf("failed to validate pre-release: %v", err) } if err := validateIdentifier(metadata); err != nil { return fmt.Errorf("failed to validate metadata: %v", err) } parsed := make([]int64, 3, 3) for i, v := range dotParts[:3] { val, err := strconv.ParseInt(v, 10, 64) parsed[i] = val if err != nil { return err } } v.Metadata = metadata v.PreRelease = preRelease v.Major = parsed[0] v.Minor = parsed[1] v.Patch = parsed[2] return nil }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/nic.go#L49-L54
func (c *Client) ListNics(dcid, srvid string) (*Nics, error) { url := nicColPath(dcid, srvid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &Nics{} err := c.client.Get(url, ret, http.StatusOK) return ret, err }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/mvcc/backend/tx_buffer.go#L153-L175
func (bb *bucketBuffer) merge(bbsrc *bucketBuffer) { for i := 0; i < bbsrc.used; i++ { bb.add(bbsrc.buf[i].key, bbsrc.buf[i].val) } if bb.used == bbsrc.used { return } if bytes.Compare(bb.buf[(bb.used-bbsrc.used)-1].key, bbsrc.buf[0].key) < 0 { return } sort.Stable(bb) // remove duplicates, using only newest update widx := 0 for ridx := 1; ridx < bb.used; ridx++ { if !bytes.Equal(bb.buf[ridx].key, bb.buf[widx].key) { widx++ } bb.buf[widx] = bb.buf[ridx] } bb.used = widx + 1 }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/easyjson.go#L1116-L1120
func (v *ClearParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomstorage11(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L928-L933
func QuerySelector(nodeID cdp.NodeID, selector string) *QuerySelectorParams { return &QuerySelectorParams{ NodeID: nodeID, Selector: selector, } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/plugins.go#L303-L315
func (pa *ConfigAgent) PullRequestHandlers(owner, repo string) map[string]PullRequestHandler { pa.mut.Lock() defer pa.mut.Unlock() hs := map[string]PullRequestHandler{} for _, p := range pa.getPlugins(owner, repo) { if h, ok := pullRequestHandlers[p]; ok { hs[p] = h } } return hs }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/client.go#L120-L151
func createRESTConfig(kubeconfig string, t Type) (config *rest.Config, types *runtime.Scheme, err error) { if kubeconfig == "" { config, err = rest.InClusterConfig() } else { config, err = clientcmd.BuildConfigFromFlags("", kubeconfig) } if err != nil { return } version := schema.GroupVersion{ Group: group, Version: version, } config.GroupVersion = &version config.APIPath = "/apis" config.ContentType = runtime.ContentTypeJSON types = runtime.NewScheme() schemeBuilder := runtime.NewSchemeBuilder( func(scheme *runtime.Scheme) error { scheme.AddKnownTypes(version, t.Object, t.Collection) v1.AddToGroupVersion(scheme, version) return nil }) err = schemeBuilder.AddToScheme(types) config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: serializer.NewCodecFactory(types)} return }
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/bool.go#L97-L102
func (b Bool) MarshalText() ([]byte, error) { if !b.Valid || !b.Bool { return []byte("false"), nil } return []byte("true"), nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/janitor/janitor.go#L70-L73
func format(rtype string) string { splits := strings.Split(rtype, "-") return splits[len(splits)-1] }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/schedule/schedule.go#L119-L125
func (f *fifo) Stop() { f.mu.Lock() f.cancel() f.cancel = nil f.mu.Unlock() <-f.donec }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L163-L166
func (p DescribeNodeParams) WithPierce(pierce bool) *DescribeNodeParams { p.Pierce = pierce return &p }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/loadbalancer.go#L113-L118
func (c *Client) GetBalancedNic(dcid, lbalid, balnicid string) (*Nic, error) { url := balnicPath(dcid, lbalid, balnicid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &Nic{} err := c.client.Get(url, ret, http.StatusOK) return ret, err }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/resolver/endpoint/endpoint.go#L233-L240
func ParseHostPort(hostPort string) (host string, port string) { parts := strings.SplitN(hostPort, ":", 2) host = parts[0] if len(parts) > 1 { port = parts[1] } return host, port }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L533-L542
func (p *GetPropertiesParams) Do(ctx context.Context) (result []*PropertyDescriptor, internalProperties []*InternalPropertyDescriptor, privateProperties []*PrivatePropertyDescriptor, exceptionDetails *ExceptionDetails, err error) { // execute var res GetPropertiesReturns err = cdp.Execute(ctx, CommandGetProperties, p, &res) if err != nil { return nil, nil, nil, nil, err } return res.Result, res.InternalProperties, res.PrivateProperties, res.ExceptionDetails, nil }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/types.go#L542-L545
func (this *Var3) MarshalJSON() ([]byte, error) { x := json.RawMessage(*this) return (&x).MarshalJSON() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.go#L851-L855
func (c *Cluster) ContainerLastUsedUpdate(id int, date time.Time) error { stmt := `UPDATE containers SET last_use_date=? WHERE id=?` err := exec(c.db, stmt, date, id) return err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L454-L456
func (p *ResetNavigationHistoryParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandResetNavigationHistory, nil, nil) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1368-L1371
func (e OperationType) ValidEnum(v int32) bool { _, ok := operationTypeMap[v] return ok }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L1982-L1986
func (v *ObjectPreview) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoRuntime17(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/worker/api_server.go#L2251-L2298
func lookupDockerUser(userArg string) (_ *user.User, retErr error) { userParts := strings.Split(userArg, ":") userOrUID := userParts[0] groupOrGID := "" if len(userParts) > 1 { groupOrGID = userParts[1] } passwd, err := os.Open("/etc/passwd") if err != nil { return nil, err } defer func() { if err := passwd.Close(); err != nil && retErr == nil { retErr = err } }() scanner := bufio.NewScanner(passwd) for scanner.Scan() { parts := strings.Split(scanner.Text(), ":") if parts[0] == userOrUID || parts[2] == userOrUID { result := &user.User{ Username: parts[0], Uid: parts[2], Gid: parts[3], Name: parts[4], HomeDir: parts[5], } if groupOrGID != "" { if parts[0] == userOrUID { // groupOrGid is a group group, err := lookupGroup(groupOrGID) if err != nil { return nil, err } result.Gid = group.Gid } else { // groupOrGid is a gid result.Gid = groupOrGID } } return result, nil } } if err := scanner.Err(); err != nil { log.Fatal(err) } return nil, fmt.Errorf("user %s not found", userArg) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/webaudio/easyjson.go#L749-L753
func (v *BaseAudioContext) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoWebaudio8(&r, v) return r.Error() }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4164-L4173
func (u OperationResultTr) GetAllowTrustResult() (result AllowTrustResult, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "AllowTrustResult" { result = *u.AllowTrustResult ok = true } return }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/skiplist.go#L360-L390
func (s *Skiplist) GetRangeSplitItems(nways int) []unsafe.Pointer { var deleted bool repeat: var itms []unsafe.Pointer var finished bool l := int(atomic.LoadInt32(&s.level)) for ; l >= 0; l-- { c := int(atomic.LoadInt64(&s.Stats.levelNodesCount[l]) + 1) if c >= nways { perSplit := c / nways node := s.head for j := 0; node != s.tail && !finished; j++ { if j == perSplit { j = -1 itms = append(itms, node.Item()) finished = len(itms) == nways-1 } node, deleted = node.getNext(l) if deleted { goto repeat } } break } } return itms }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/tarball/tarball_reference.go#L34-L43
func (r *tarballReference) ConfigUpdate(config imgspecv1.Image, annotations map[string]string) error { r.config = config if r.annotations == nil { r.annotations = make(map[string]string) } for k, v := range annotations { r.annotations[k] = v } return nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/clientset/versioned/clientset.go#L82-L88
func New(c rest.Interface) *Clientset { var cs Clientset cs.tsuruV1 = tsuruv1.New(c) cs.DiscoveryClient = discovery.NewDiscoveryClient(c) return &cs }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/fileutil/read_dir.go#L44-L70
func ReadDir(d string, opts ...ReadDirOption) ([]string, error) { op := &ReadDirOp{} op.applyOpts(opts) dir, err := os.Open(d) if err != nil { return nil, err } defer dir.Close() names, err := dir.Readdirnames(-1) if err != nil { return nil, err } sort.Strings(names) if op.ext != "" { tss := make([]string, 0) for _, v := range names { if filepath.Ext(v) == op.ext { tss = append(tss, v) } } names = tss } return names, nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L274-L292
func NewKey(c context.Context, kind, stringID string, intID int64, parent *Key) *Key { // If there's a parent key, use its namespace. // Otherwise, use any namespace attached to the context. var namespace string if parent != nil { namespace = parent.namespace } else { namespace = internal.NamespaceFromContext(c) } return &Key{ kind: kind, stringID: stringID, intID: intID, parent: parent, appID: internal.FullyQualifiedAppID(c), namespace: namespace, } }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/cluster/cluster.go#L108-L116
func (c *Cluster) Get(k int32) (*Node, bool) { if len(c.nodes) == 0 { return nil, false } if len(c.nodes)-1 < int(k) { return nil, false } return c.nodes[k], true }
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/key.go#L137-L174
func GenerateEKeyPair(curveName string) ([]byte, GenSharedKey, error) { var curve elliptic.Curve switch curveName { case "P-256": curve = elliptic.P256() case "P-384": curve = elliptic.P384() case "P-521": curve = elliptic.P521() } priv, x, y, err := elliptic.GenerateKey(curve, rand.Reader) if err != nil { return nil, nil, err } pubKey := elliptic.Marshal(curve, x, y) done := func(theirPub []byte) ([]byte, error) { // Verify and unpack node's public key. x, y := elliptic.Unmarshal(curve, theirPub) if x == nil { return nil, fmt.Errorf("malformed public key: %d %v", len(theirPub), theirPub) } if !curve.IsOnCurve(x, y) { return nil, errors.New("invalid public key") } // Generate shared secret. secret, _ := curve.ScalarMult(x, y, priv) return secret.Bytes(), nil } return pubKey, done, nil }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/app_wrapper.go#L34-L51
func (m *AppWrapper) Validate(formats strfmt.Registry) error { var res []error if err := m.validateApp(formats); err != nil { // prop res = append(res, err) } if err := m.validateError(formats); err != nil { // prop res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/idutil/id.go#L67-L71
func (g *Generator) Next() uint64 { suffix := atomic.AddUint64(&g.suffix, 1) id := g.prefix | lowbit(suffix, suffixLen) return id }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/state.go#L102-L104
func (st *State) AppendOutputString(o string) { st.output.Write([]byte(o)) }
https://github.com/scorredoira/email/blob/c1787f8317a847a7adc13673be80723268e6e639/email.go#L87-L89
func (m *Message) Attach(file string) error { return m.attach(file, false) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/boltdb/boltdb.go#L283-L332
func (bdc *cache) CandidateLocations(transport types.ImageTransport, scope types.BICTransportScope, primaryDigest digest.Digest, canSubstitute bool) []types.BICReplacementCandidate { res := []prioritize.CandidateWithTime{} var uncompressedDigestValue digest.Digest // = "" if err := bdc.view(func(tx *bolt.Tx) error { scopeBucket := tx.Bucket(knownLocationsBucket) if scopeBucket == nil { return nil } scopeBucket = scopeBucket.Bucket([]byte(transport.Name())) if scopeBucket == nil { return nil } scopeBucket = scopeBucket.Bucket([]byte(scope.Opaque)) if scopeBucket == nil { return nil } res = bdc.appendReplacementCandidates(res, scopeBucket, primaryDigest) if canSubstitute { if uncompressedDigestValue = bdc.uncompressedDigest(tx, primaryDigest); uncompressedDigestValue != "" { b := tx.Bucket(digestByUncompressedBucket) if b != nil { b = b.Bucket([]byte(uncompressedDigestValue.String())) if b != nil { if err := b.ForEach(func(k, _ []byte) error { d, err := digest.Parse(string(k)) if err != nil { return err } if d != primaryDigest && d != uncompressedDigestValue { res = bdc.appendReplacementCandidates(res, scopeBucket, d) } return nil }); err != nil { return err } } } if uncompressedDigestValue != primaryDigest { res = bdc.appendReplacementCandidates(res, scopeBucket, uncompressedDigestValue) } } } return nil }); err != nil { // Including os.IsNotExist(err) return []types.BICReplacementCandidate{} // FIXME? Log err (but throttle the log volume on repeated accesses)? } return prioritize.DestructivelyPrioritizeReplacementCandidates(res, primaryDigest, uncompressedDigestValue) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/membership.go#L857-L866
func membershipCheckClusterStateForBootstrapOrJoin(tx *db.ClusterTx) error { nodes, err := tx.Nodes() if err != nil { return errors.Wrap(err, "failed to fetch current cluster nodes") } if len(nodes) != 1 { return fmt.Errorf("inconsistent state: found leftover entries in nodes") } return nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L1231-L1302
func bindServiceInstance(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { instanceName := r.URL.Query().Get(":instance") appName := r.URL.Query().Get(":app") serviceName := r.URL.Query().Get(":service") req := struct { NoRestart bool Parameters service.BindAppParameters }{} err = ParseInput(r, &req) if err != nil { return err } instance, a, err := getServiceInstance(serviceName, instanceName, appName) if err != nil { return err } allowed := permission.Check(t, permission.PermServiceInstanceUpdateBind, append(permission.Contexts(permTypes.CtxTeam, instance.Teams), permission.Context(permTypes.CtxServiceInstance, instance.Name), )..., ) if !allowed { return permission.ErrUnauthorized } allowed = permission.Check(t, permission.PermAppUpdateBind, contextsForApp(a)..., ) if !allowed { return permission.ErrUnauthorized } err = a.ValidateService(serviceName) if err != nil { if err == pool.ErrPoolHasNoService { return &errors.HTTP{Code: http.StatusBadRequest, Message: err.Error()} } return err } evt, err := event.New(&event.Opts{ Target: appTarget(appName), Kind: permission.PermAppUpdateBind, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(a)...), }) if err != nil { return err } defer func() { evt.Done(err) }() w.Header().Set("Content-Type", "application/x-json-stream") keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "") defer keepAliveWriter.Stop() writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)} evt.SetLogWriter(writer) err = instance.BindApp(a, req.Parameters, !req.NoRestart, evt, evt, requestIDHeader(r)) if err != nil { status, errStatus := instance.Status(requestIDHeader(r)) if errStatus != nil { return fmt.Errorf("%v (failed to retrieve instance status: %v)", err, errStatus) } return fmt.Errorf("%v (%q is %v)", err, instanceName, status) } fmt.Fprintf(writer, "\nInstance %q is now bound to the app %q.\n", instanceName, appName) envs := a.InstanceEnvs(serviceName, instanceName) if len(envs) > 0 { fmt.Fprintf(writer, "The following environment variables are available for use in your app:\n\n") for k := range envs { fmt.Fprintf(writer, "- %s\n", k) } fmt.Fprintf(writer, "- %s\n", app.TsuruServicesEnvVar) } return nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/config/config.go#L62-L84
func (c *Config) Write() error { rawConfig, err := json.MarshalIndent(c, "", " ") if err != nil { return err } // If we're not using a custom config path, create the default config path p := configPath() if _, ok := os.LookupEnv(configEnvVar); ok { // using overridden config path -- just make sure the parent dir exists d := filepath.Dir(p) if _, err := os.Stat(d); err != nil { return fmt.Errorf("cannot use config at %s: could not stat parent directory (%v)", p, err) } } else { // using the default config path, create the config directory err = os.MkdirAll(defaultConfigDir, 0755) if err != nil { return err } } return ioutil.WriteFile(p, rawConfig, 0644) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/recipes/key.go#L77-L116
func newSequentialKV(kv v3.KV, prefix, val string) (*RemoteKV, error) { resp, err := kv.Get(context.TODO(), prefix, v3.WithLastKey()...) if err != nil { return nil, err } // add 1 to last key, if any newSeqNum := 0 if len(resp.Kvs) != 0 { fields := strings.Split(string(resp.Kvs[0].Key), "/") _, serr := fmt.Sscanf(fields[len(fields)-1], "%d", &newSeqNum) if serr != nil { return nil, serr } newSeqNum++ } newKey := fmt.Sprintf("%s/%016d", prefix, newSeqNum) // base prefix key must be current (i.e., <=) with the server update; // the base key is important to avoid the following: // N1: LastKey() == 1, start txn. // N2: new Key 2, new Key 3, Delete Key 2 // N1: txn succeeds allocating key 2 when it shouldn't baseKey := "__" + prefix // current revision might contain modification so +1 cmp := v3.Compare(v3.ModRevision(baseKey), "<", resp.Header.Revision+1) reqPrefix := v3.OpPut(baseKey, "") reqnewKey := v3.OpPut(newKey, val) txn := kv.Txn(context.TODO()) txnresp, err := txn.If(cmp).Then(reqPrefix, reqnewKey).Commit() if err != nil { return nil, err } if !txnresp.Succeeded { return newSequentialKV(kv, prefix, val) } return &RemoteKV{kv, newKey, txnresp.Header.Revision, val}, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/states.go#L125-L136
func (m *MultiState) ReceiveEvent(eventName, label string, t time.Time) (State, bool) { oneChanged := false for i := range m.states { state, changed := m.states[i].ReceiveEvent(eventName, label, t) if changed { oneChanged = true } m.states[i] = state } return m, oneChanged }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/relay.go#L202-L220
func NewRelayer(ch *Channel, conn *Connection) *Relayer { r := &Relayer{ relayHost: ch.RelayHost(), maxTimeout: ch.relayMaxTimeout, localHandler: ch.relayLocal, outbound: newRelayItems(conn.log.WithFields(LogField{"relayItems", "outbound"})), inbound: newRelayItems(conn.log.WithFields(LogField{"relayItems", "inbound"})), peers: ch.RootPeers(), conn: conn, relayConn: &relay.Conn{ RemoteAddr: conn.conn.RemoteAddr().String(), RemoteProcessName: conn.RemotePeerInfo().ProcessName, IsOutbound: conn.connDirection == outbound, }, logger: conn.log, } r.timeouts = newRelayTimerPool(r.timeoutRelayItem, ch.relayTimerVerify) return r }
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/ed25519.go#L51-L60
func (k *Ed25519PrivateKey) Raw() ([]byte, error) { // The Ed25519 private key contains two 32-bytes curve points, the private // key and the public key. // It makes it more efficient to get the public key without re-computing an // elliptic curve multiplication. buf := make([]byte, len(k.k)) copy(buf, k.k) return buf, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/flagutil/kubernetes_cluster_clients.go#L83-L117
func (o *ExperimentalKubernetesOptions) resolve(dryRun bool) (err error) { if o.resolved { return nil } o.dryRun = dryRun if dryRun { return nil } clusterConfigs, err := kube.LoadClusterConfigs(o.kubeconfig, o.buildCluster) if err != nil { return fmt.Errorf("load --kubeconfig=%q --build-cluster=%q configs: %v", o.kubeconfig, o.buildCluster, err) } clients := map[string]kubernetes.Interface{} for context, config := range clusterConfigs { client, err := kubernetes.NewForConfig(&config) if err != nil { return fmt.Errorf("create %s kubernetes client: %v", context, err) } clients[context] = client } localCfg := clusterConfigs[kube.InClusterContext] pjClient, err := prow.NewForConfig(&localCfg) if err != nil { return err } o.prowJobClientset = pjClient o.kubernetesClientsByContext = clients o.resolved = true return nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5769-L5777
func (u LedgerEntryChange) MustUpdated() LedgerEntry { val, ok := u.GetUpdated() if !ok { panic("arm Updated is not set") } return val }
https://github.com/knq/sdhook/blob/41b9ccbff0b5fa5a56fbdccf2eb8653e7afe8d4b/opts.go#L176-L218
func GoogleServiceAccountCredentialsJSON(buf []byte) Option { return func(sh *StackdriverHook) error { var err error // load credentials gsa, err := gserviceaccount.FromJSON(buf) if err != nil { return err } // check project id if gsa.ProjectID == "" { return errors.New("google service account credentials missing project_id") } // set project id err = ProjectID(gsa.ProjectID)(sh) if err != nil { return err } // set resource type err = Resource(ResTypeProject, map[string]string{ "project_id": gsa.ProjectID, })(sh) if err != nil { return err } // create token source ts, err := gsa.TokenSource(nil, requiredScopes...) if err != nil { return err } // set client return HTTPClient(&http.Client{ Transport: &oauth2.Transport{ Source: oauth2.ReuseTokenSource(nil, ts), }, })(sh) } }
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/outgoing.go#L176-L179
func (oa *OutgoingAudio) SetDuration(to int) *OutgoingAudio { oa.Duration = to return oa }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/easyjson.go#L1175-L1179
func (v *EndParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTracing11(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/networks.go#L367-L408
func (c *Cluster) NetworkGetInterface(devName string) (int64, *api.Network, error) { id := int64(-1) name := "" value := "" q := "SELECT networks.id, networks.name, networks_config.value FROM networks LEFT JOIN networks_config ON networks.id=networks_config.network_id WHERE networks_config.key=\"bridge.external_interfaces\" AND networks_config.node_id=?" arg1 := []interface{}{c.nodeID} arg2 := []interface{}{id, name, value} result, err := queryScan(c.db, q, arg1, arg2) if err != nil { return -1, nil, err } for _, r := range result { for _, entry := range strings.Split(r[2].(string), ",") { entry = strings.TrimSpace(entry) if entry == devName { id = r[0].(int64) name = r[1].(string) } } } if id == -1 { return -1, nil, fmt.Errorf("No network found for interface: %s", devName) } config, err := c.NetworkConfigGet(id) if err != nil { return -1, nil, err } network := api.Network{ Name: name, Managed: true, Type: "bridge", } network.Config = config return id, &network, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/size/size.go#L217-L230
func isPRChanged(pe github.PullRequestEvent) bool { switch pe.Action { case github.PullRequestActionOpened: return true case github.PullRequestActionReopened: return true case github.PullRequestActionSynchronize: return true case github.PullRequestActionEdited: return true default: return false } }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/mechanism_openpgp.go#L157-L159
func (m openpgpSigningMechanism) UntrustedSignatureContents(untrustedSignature []byte) (untrustedContents []byte, shortKeyIdentifier string, err error) { return gpgUntrustedSignatureContents(untrustedSignature) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1749-L1769
func (c *Client) RequestReview(org, repo string, number int, logins []string) error { statusCode, err := c.tryRequestReview(org, repo, number, logins) if err != nil && statusCode == http.StatusUnprocessableEntity /*422*/ { // Failed to set all members of 'logins' as reviewers, try individually. missing := MissingUsers{action: "request a PR review from"} for _, user := range logins { statusCode, err = c.tryRequestReview(org, repo, number, []string{user}) if err != nil && statusCode == http.StatusUnprocessableEntity /*422*/ { // User is not a contributor, or team not in org. missing.Users = append(missing.Users, user) } else if err != nil { return fmt.Errorf("failed to add reviewer to PR. Status code: %d, errmsg: %v", statusCode, err) } } if len(missing.Users) > 0 { return missing } return nil } return err }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3676-L3685
func (u InflationResult) GetPayouts() (result []InflationPayout, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Code)) if armName == "Payouts" { result = *u.Payouts ok = true } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/types.go#L58-L60
func (t *DOMBreakpointType) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/prop.go#L176-L289
func getStructCodecLocked(t reflect.Type) (ret *structCodec, retErr error) { c, ok := structCodecs[t] if ok { return c, nil } c = &structCodec{ fields: make(map[string]fieldCodec), // We initialize keyField to -1 so that the zero-value is not // misinterpreted as index 0. keyField: -1, } // Add c to the structCodecs map before we are sure it is good. If t is // a recursive type, it needs to find the incomplete entry for itself in // the map. structCodecs[t] = c defer func() { if retErr != nil { delete(structCodecs, t) } }() for i := 0; i < t.NumField(); i++ { f := t.Field(i) // Skip unexported fields. // Note that if f is an anonymous, unexported struct field, // we will promote its fields. if f.PkgPath != "" && !f.Anonymous { continue } tags := strings.Split(f.Tag.Get("datastore"), ",") name := tags[0] opts := make(map[string]bool) for _, t := range tags[1:] { opts[t] = true } switch { case name == "": if !f.Anonymous { name = f.Name } case name == "-": continue case name == "__key__": if f.Type != typeOfKeyPtr { return nil, fmt.Errorf("datastore: __key__ field on struct %v is not a *datastore.Key", t) } c.keyField = i case !validPropertyName(name): return nil, fmt.Errorf("datastore: struct tag has invalid property name: %q", name) } substructType, fIsSlice := reflect.Type(nil), false switch f.Type.Kind() { case reflect.Struct: substructType = f.Type case reflect.Slice: if f.Type.Elem().Kind() == reflect.Struct { substructType = f.Type.Elem() } fIsSlice = f.Type != typeOfByteSlice c.hasSlice = c.hasSlice || fIsSlice } var sub *structCodec if substructType != nil && substructType != typeOfTime && substructType != typeOfGeoPoint { var err error sub, err = getStructCodecLocked(substructType) if err != nil { return nil, err } if !sub.complete { return nil, fmt.Errorf("datastore: recursive struct: field %q", f.Name) } if fIsSlice && sub.hasSlice { return nil, fmt.Errorf( "datastore: flattening nested structs leads to a slice of slices: field %q", f.Name) } c.hasSlice = c.hasSlice || sub.hasSlice // If f is an anonymous struct field, we promote the substruct's fields up to this level // in the linked list of struct codecs. if f.Anonymous { for subname, subfield := range sub.fields { if name != "" { subname = name + "." + subname } if _, ok := c.fields[subname]; ok { return nil, fmt.Errorf("datastore: struct tag has repeated property name: %q", subname) } c.fields[subname] = fieldCodec{ path: append([]int{i}, subfield.path...), noIndex: subfield.noIndex || opts["noindex"], omitEmpty: subfield.omitEmpty, structCodec: subfield.structCodec, } } continue } } if _, ok := c.fields[name]; ok { return nil, fmt.Errorf("datastore: struct tag has repeated property name: %q", name) } c.fields[name] = fieldCodec{ path: []int{i}, noIndex: opts["noindex"], omitEmpty: opts["omitempty"], structCodec: sub, } } c.complete = true return c, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/hook/server.go#L193-L206
func (s *Server) demuxExternal(l *logrus.Entry, externalPlugins []plugins.ExternalPlugin, payload []byte, h http.Header) { h.Set("User-Agent", "ProwHook") for _, p := range externalPlugins { s.wg.Add(1) go func(p plugins.ExternalPlugin) { defer s.wg.Done() if err := s.dispatch(p.Endpoint, payload, h); err != nil { l.WithError(err).WithField("external-plugin", p.Name).Error("Error dispatching event to external plugin.") } else { l.WithField("external-plugin", p.Name).Info("Dispatched event to external plugin") } }(p) } }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/gocontext.go#L43-L45
func StartSpanFromContext(ctx context.Context, operationName string, opts ...StartSpanOption) (Span, context.Context) { return StartSpanFromContextWithTracer(ctx, GlobalTracer(), operationName, opts...) }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/gossip.go#L232-L238
func newGossipSenders(sender protocolSender, stop <-chan struct{}) *gossipSenders { return &gossipSenders{ sender: sender, stop: stop, senders: make(map[string]*gossipSender), } }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4881-L4890
func (u LedgerUpgrade) GetNewBaseFee() (result Uint32, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "NewBaseFee" { result = *u.NewBaseFee ok = true } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L161-L195
func (t *ErrorReason) UnmarshalEasyJSON(in *jlexer.Lexer) { switch ErrorReason(in.String()) { case ErrorReasonFailed: *t = ErrorReasonFailed case ErrorReasonAborted: *t = ErrorReasonAborted case ErrorReasonTimedOut: *t = ErrorReasonTimedOut case ErrorReasonAccessDenied: *t = ErrorReasonAccessDenied case ErrorReasonConnectionClosed: *t = ErrorReasonConnectionClosed case ErrorReasonConnectionReset: *t = ErrorReasonConnectionReset case ErrorReasonConnectionRefused: *t = ErrorReasonConnectionRefused case ErrorReasonConnectionAborted: *t = ErrorReasonConnectionAborted case ErrorReasonConnectionFailed: *t = ErrorReasonConnectionFailed case ErrorReasonNameNotResolved: *t = ErrorReasonNameNotResolved case ErrorReasonInternetDisconnected: *t = ErrorReasonInternetDisconnected case ErrorReasonAddressUnreachable: *t = ErrorReasonAddressUnreachable case ErrorReasonBlockedByClient: *t = ErrorReasonBlockedByClient case ErrorReasonBlockedByResponse: *t = ErrorReasonBlockedByResponse default: in.AddError(errors.New("unknown ErrorReason value")) } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/proxy/httpproxy/proxy.go#L68-L71
func NewReadonlyHandler(hdlr http.Handler) http.Handler { readonly := readonlyHandlerFunc(hdlr) return http.HandlerFunc(readonly) }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/config/config.go#L122-L129
func (c *Config) IsValidBuildFileName(name string) bool { for _, n := range c.ValidBuildFileNames { if name == n { return true } } return false }
https://github.com/fujiwara/fluent-agent-hydra/blob/f5c1c02a0b892cf5c08918ec2ff7bbca71cc7e4f/fluent/fluent.go#L121-L125
func (f *Fluent) IsReconnecting() bool { f.mu.Lock() defer f.mu.Unlock() return f.reconnecting }
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/snowballword/snowballword.go#L306-L308
func (w *SnowballWord) FirstSuffix(suffixes ...string) (suffix string, suffixRunes []rune) { return w.FirstSuffixIfIn(0, len(w.RS), suffixes...) }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L207-L210
func txLiteral(st *State) { st.sa = st.CurrentOp().Arg() st.Advance() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/easyjson.go#L1116-L1120
func (v *EventBufferUsage) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTracing10(&r, v) return r.Error() }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/httpclient/http.go#L393-L443
func (d *dumpClient) dumpResponse(resp *http.Response, req *http.Request, reqBody []byte) { df := d.dumpFormat() if df == NoDump { return } respBody, _ := dumpRespBody(resp) if df.IsDebug() { var buffer bytes.Buffer buffer.WriteString("==> " + resp.Proto + " " + resp.Status + "\n") d.writeHeaders(&buffer, resp.Header) if respBody != nil { buffer.WriteString("\n") buffer.Write(respBody) buffer.WriteString("\n") } fmt.Fprint(OsStderr, buffer.String()) } else if df.IsJSON() { reqHeaders := make(http.Header) hh := d.hiddenHeaders() filterHeaders(df, hh, req.Header, func(name string, value []string) { reqHeaders[name] = value }) respHeaders := make(http.Header) filterHeaders(df, hh, resp.Header, func(name string, value []string) { respHeaders[name] = value }) dumped := recording.RequestResponse{ Verb: req.Method, URI: req.URL.String(), ReqHeader: reqHeaders, ReqBody: string(reqBody), Status: resp.StatusCode, RespHeader: respHeaders, RespBody: string(respBody), } b, err := json.MarshalIndent(dumped, "", " ") if err != nil { log.Error("Failed to dump request content", "error", err.Error()) return } if df.IsRecord() { f := os.NewFile(10, "fd10") _, err = f.Stat() if err == nil { // fd 10 is open, dump to it (used by recorder) fmt.Fprintf(f, "%s\n", string(b)) } } fmt.Fprint(OsStderr, string(b)) } }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/influx/writer.go#L24-L31
func newBatchPoints(bpConf influxdb.BatchPointsConfig) influxdb.BatchPoints { bp, err := influxdb.NewBatchPoints(bpConf) if err != nil { // Can only happen if there's an error in the code panic(fmt.Errorf("Invalid batch point configuration: %s", err)) } return bp }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L217-L225
func (c APIClient) FinishCommit(repoName string, commitID string) error { _, err := c.PfsAPIClient.FinishCommit( c.Ctx(), &pfs.FinishCommitRequest{ Commit: NewCommit(repoName, commitID), }, ) return grpcutil.ScrubGRPC(err) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/updateconfig/updateconfig.go#L180-L231
func FilterChanges(cfg plugins.ConfigUpdater, changes []github.PullRequestChange, log *logrus.Entry) map[ConfigMapID][]ConfigMapUpdate { toUpdate := map[ConfigMapID][]ConfigMapUpdate{} for _, change := range changes { var cm plugins.ConfigMapSpec found := false for key, configMap := range cfg.Maps { var matchErr error found, matchErr = zglob.Match(key, change.Filename) if matchErr != nil { // Should not happen, log matchErr and continue log.WithError(matchErr).Info("key matching error") continue } if found { cm = configMap break } } if !found { continue // This file does not define a configmap } // Yes, update the configmap with the contents of this file for _, ns := range append(cm.Namespaces) { id := ConfigMapID{Name: cm.Name, Namespace: ns} key := cm.Key if key == "" { key = path.Base(change.Filename) // if the key changed, we need to remove the old key if change.Status == github.PullRequestFileRenamed { oldKey := path.Base(change.PreviousFilename) // not setting the filename field will cause the key to be // deleted toUpdate[id] = append(toUpdate[id], ConfigMapUpdate{Key: oldKey}) } } if change.Status == github.PullRequestFileRemoved { toUpdate[id] = append(toUpdate[id], ConfigMapUpdate{Key: key}) } else { gzip := cfg.GZIP if cm.GZIP != nil { gzip = *cm.GZIP } toUpdate[id] = append(toUpdate[id], ConfigMapUpdate{Key: key, Filename: change.Filename, GZIP: gzip}) } } } return toUpdate }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L603-L606
func (writer *VideoWriter) WriteFrame(image *IplImage) int { rv := C.cvWriteFrame((*C.CvVideoWriter)(writer), (*C.IplImage)(image)) return int(rv) }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/storage/postgres/storage.go#L410-L414
func (s *Storage) TearDown() error { _, err := s.db.Exec(`DROP SCHEMA IF EXISTS ` + s.schema + ` CASCADE`) return err }
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/exception.go#L68-L75
func (x *Exception) SetContent(content string) error { contentRegexp, err := regexp.Compile("(?i)" + content) if err != nil { return err } x.Content = contentRegexp return nil }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/release/boshrelease.go#L43-L49
func readBoshRelease(rr io.Reader) (*BoshRelease, error) { release := &BoshRelease{ JobManifests: make(map[string]enaml.JobManifest), } err := release.readBoshRelease(rr) return release, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L115-L118
func (p CaptureScreenshotParams) WithClip(clip *Viewport) *CaptureScreenshotParams { p.Clip = clip return &p }