_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/storage/easyjson.go#L93-L97
func (v *UsageForType) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoStorage(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/animation/animation.go#L197-L199
func (p *SeekAnimationsParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSeekAnimations, p, nil) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/cache.go#L21-L23
func parseBICLocationReference(lr types.BICLocationReference) (reference.Named, error) { return reference.ParseNormalizedNamed(lr.Opaque) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L670-L676
func (c APIClient) ReadObjects(hashes []string, offset uint64, size uint64) ([]byte, error) { var buffer bytes.Buffer if err := c.GetObjects(hashes, offset, size, 0, &buffer); err != nil { return nil, err } return buffer.Bytes(), nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/easyjson.go#L720-L724
func (v FailRequestParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoFetch7(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/policy/auth.go#L35-L41
func fromAPI(api *rsapi.API) *API { api.FileEncoding = rsapi.FileEncodingJSON api.Host = HostFromLogin(api.Host) api.Metadata = GenMetadata api.VersionHeader = "Api-Version" return &API{api} }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L13220-L13227
func (r *SshKey) Locator(api *API) *SshKeyLocator { for _, l := range r.Links { if l["rel"] == "self" { return api.SshKeyLocator(l["href"]) } } return nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/file_snapshot.go#L274-L293
func (f *FileSnapshotStore) readMeta(name string) (*fileSnapshotMeta, error) { // Open the meta file metaPath := filepath.Join(f.path, name, metaFilePath) fh, err := os.Open(metaPath) if err != nil { return nil, err } defer fh.Close() // Buffer the file IO buffered := bufio.NewReader(fh) // Read in the JSON meta := &fileSnapshotMeta{} dec := json.NewDecoder(buffered) if err := dec.Decode(meta); err != nil { return nil, err } return meta, nil }
https://github.com/alternaDev/go-avatar-gen/blob/b5ca997c0389dc8ce22e1a95087647aa4bb25b57/generator.go#L40-L86
func GenerateAvatar(input string, blockSize int, borderSize int) *image.RGBA { hash := hashMd5(input) pic := [size][size]bool{} for i := size - 4; i >= 0; i-- { for j := size - 1; j >= 0; j-- { if strings.Contains(low, string(hash[size-1*i+j])) { pic[j][i] = true pic[j][size-1-i] = true } } } for i := size - 1; i >= 0; i-- { if strings.Contains(low, string(hash[i])) { pic[i][int(math.Ceil(size/2))] = true } } avatar := image.NewRGBA(image.Rect(0, 0, blockSize*size+borderSize*2, blockSize*size+borderSize*2)) bgColor := calcBgColor() for x := 0; x < avatar.Bounds().Dx(); x++ { for y := 0; y < avatar.Bounds().Dy(); y++ { avatar.SetRGBA(x, y, bgColor) } } color := calcPixelColor(input) for x := 0; x < len(pic); x++ { for y := 0; y < len(pic[x]); y++ { if pic[x][y] { for i := 0; i < blockSize; i++ { for j := 0; j < blockSize; j++ { avatar.SetRGBA(borderSize+x*blockSize+i, borderSize+y*blockSize+j, color) } } } } } return avatar }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L152-L160
func (f *FakeClient) CreateReview(org, repo string, number int, r github.DraftReview) error { f.Reviews[number] = append(f.Reviews[number], github.Review{ ID: f.ReviewID, User: github.User{Login: botName}, Body: r.Body, }) f.ReviewID++ return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/decorate/podspec.go#L145-L185
func ProwJobToPod(pj prowapi.ProwJob, buildID string) (*coreapi.Pod, error) { if pj.Spec.PodSpec == nil { return nil, fmt.Errorf("prowjob %q lacks a pod spec", pj.Name) } rawEnv, err := downwardapi.EnvForSpec(downwardapi.NewJobSpec(pj.Spec, buildID, pj.Name)) if err != nil { return nil, err } spec := pj.Spec.PodSpec.DeepCopy() spec.RestartPolicy = "Never" spec.Containers[0].Name = kube.TestContainerName // if the user has not provided a serviceaccount to use or explicitly // requested mounting the default token, we treat the unset value as // false, while kubernetes treats it as true if it is unset because // it was added in v1.6 if spec.AutomountServiceAccountToken == nil && spec.ServiceAccountName == "" { myFalse := false spec.AutomountServiceAccountToken = &myFalse } if pj.Spec.DecorationConfig == nil { spec.Containers[0].Env = append(spec.Containers[0].Env, kubeEnv(rawEnv)...) } else { if err := decorate(spec, &pj, rawEnv); err != nil { return nil, fmt.Errorf("error decorating podspec: %v", err) } } podLabels, annotations := LabelsAndAnnotationsForJob(pj) return &coreapi.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: pj.ObjectMeta.Name, Labels: podLabels, Annotations: annotations, }, Spec: *spec, }, nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2150-L2153
func (e MemoType) ValidEnum(v int32) bool { _, ok := memoTypeMap[v] return ok }
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/requestbuilder.go#L35-L37
func (r *RequestBuilder) BodyBytes(body []byte) *RequestBuilder { return r.Body(bytes.NewReader(body)) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L1827-L1831
func (v *EventNodeHighlightRequested) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoOverlay18(&r, v) return r.Error() }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L991-L1005
func txFunCallOmni(st *State) { t := reflect.ValueOf(st.sa) switch t.Kind() { case reflect.Int: // If it's an int, assume that it's a MACRO, which points to // the location in the bytecode that contains the macro code txMacroCall(st) case reflect.Func: txFunCall(st) default: st.Warnf("Unknown variable as function call: %s\n", st.sa) st.sa = nil st.Advance() } }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/auth.go#L64-L88
func (h AuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { valid, entity, err := h.authenticate(r) if err != nil { h.error(w, r, err) return } if h.PostAuthFunc != nil { rr, err := h.PostAuthFunc(w, r, valid, entity) if err != nil { h.error(w, r, err) return } if rr != nil { r = rr } } if !valid { h.unauthorized(w, r) return } if h.Handler != nil { h.Handler.ServeHTTP(w, r) } }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/mnemosyned/daemon.go#L293-L312
func (d *Daemon) Close() (err error) { d.done <- struct{}{} d.server.GracefulStop() if d.postgres != nil { if err = d.postgres.Close(); err != nil { return } } if d.debugListener != nil { if err = d.debugListener.Close(); err != nil { return } } if d.tracerCloser != nil { if err = d.tracerCloser.Close(); err != nil { return } } return nil }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fileinfo.go#L610-L623
func checkConstraints(c *config.Config, os, arch, osSuffix, archSuffix string, fileTags []tagLine, cgoTags tagLine) bool { if osSuffix != "" && osSuffix != os || archSuffix != "" && archSuffix != arch { return false } for _, l := range fileTags { if !l.check(c, os, arch) { return false } } if len(cgoTags) > 0 && !cgoTags.check(c, os, arch) { return false } return true }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/codegen_client.go#L306-L308
func (api *API) EnvLocator(href string) *EnvLocator { return &EnvLocator{Href(href), api} }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/state.go#L79-L94
func (st *state) mergeReceived(set map[mesh.PeerName]int) (received mesh.GossipData) { st.mtx.Lock() defer st.mtx.Unlock() for peer, v := range set { if v <= st.set[peer] { delete(set, peer) // optimization: make the forwarded data smaller continue } st.set[peer] = v } return &state{ set: set, // all remaining elements were novel to us } }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/account_id.go#L56-L76
func (aid *AccountId) SetAddress(address string) error { if aid == nil { return nil } raw, err := strkey.Decode(strkey.VersionByteAccountID, address) if err != nil { return err } if len(raw) != 32 { return errors.New("invalid address") } var ui Uint256 copy(ui[:], raw) *aid, err = NewAccountId(CryptoKeyTypeKeyTypeEd25519, ui) return err }
https://github.com/insionng/martini/blob/2d0ba5dc75fe9549c10e2f71927803a11e5e4957/render.go#L305-L317
func (r *Render) HTML(status int, name string, binding interface{}, htmlOpt ...HTMLRenderOptions) { out, err := r.renderBytes(name, binding, htmlOpt...) if err != nil { http.Error(r, err.Error(), http.StatusInternalServerError) return } r.Header().Set(ContentType, r.opt.HTMLContentType+r.compiledCharset) r.WriteHeader(status) io.Copy(r, out) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L279-L283
func (v SetAutoAttachParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/certificates.go#L87-L113
func (c *Cluster) CertSave(cert *CertInfo) error { err := c.Transaction(func(tx *ClusterTx) error { stmt, err := tx.tx.Prepare(` INSERT INTO certificates ( fingerprint, type, name, certificate ) VALUES (?, ?, ?, ?)`, ) if err != nil { return err } defer stmt.Close() _, err = stmt.Exec( cert.Fingerprint, cert.Type, cert.Name, cert.Certificate, ) if err != nil { return err } return nil }) return err }
https://github.com/antlinker/go-dirtyfilter/blob/533f538ffaa112776b1258c3db63e6f55648e18b/manager.go#L59-L64
func (dm *DirtyManager) Filter() DirtyFilter { dm.filterMux.RLock() filter := dm.filter dm.filterMux.RUnlock() return filter }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/ext/tags.go#L196-L198
func (tag boolTagName) Set(span opentracing.Span, value bool) { span.SetTag(string(tag), value) }
https://github.com/google/shlex/blob/c34317bd91bf98fab745d77b03933cf8769299fe/shlex.go#L186-L395
func (t *Tokenizer) scanStream() (*Token, error) { state := startState var tokenType TokenType var value []rune var nextRune rune var nextRuneType runeTokenClass var err error for { nextRune, _, err = t.input.ReadRune() nextRuneType = t.classifier.ClassifyRune(nextRune) if err == io.EOF { nextRuneType = eofRuneClass err = nil } else if err != nil { return nil, err } switch state { case startState: // no runes read yet { switch nextRuneType { case eofRuneClass: { return nil, io.EOF } case spaceRuneClass: { } case escapingQuoteRuneClass: { tokenType = WordToken state = quotingEscapingState } case nonEscapingQuoteRuneClass: { tokenType = WordToken state = quotingState } case escapeRuneClass: { tokenType = WordToken state = escapingState } case commentRuneClass: { tokenType = CommentToken state = commentState } default: { tokenType = WordToken value = append(value, nextRune) state = inWordState } } } case inWordState: // in a regular word { switch nextRuneType { case eofRuneClass: { token := &Token{ tokenType: tokenType, value: string(value)} return token, err } case spaceRuneClass: { token := &Token{ tokenType: tokenType, value: string(value)} return token, err } case escapingQuoteRuneClass: { state = quotingEscapingState } case nonEscapingQuoteRuneClass: { state = quotingState } case escapeRuneClass: { state = escapingState } default: { value = append(value, nextRune) } } } case escapingState: // the rune after an escape character { switch nextRuneType { case eofRuneClass: { err = fmt.Errorf("EOF found after escape character") token := &Token{ tokenType: tokenType, value: string(value)} return token, err } default: { state = inWordState value = append(value, nextRune) } } } case escapingQuotedState: // the next rune after an escape character, in double quotes { switch nextRuneType { case eofRuneClass: { err = fmt.Errorf("EOF found after escape character") token := &Token{ tokenType: tokenType, value: string(value)} return token, err } default: { state = quotingEscapingState value = append(value, nextRune) } } } case quotingEscapingState: // in escaping double quotes { switch nextRuneType { case eofRuneClass: { err = fmt.Errorf("EOF found when expecting closing quote") token := &Token{ tokenType: tokenType, value: string(value)} return token, err } case escapingQuoteRuneClass: { state = inWordState } case escapeRuneClass: { state = escapingQuotedState } default: { value = append(value, nextRune) } } } case quotingState: // in non-escaping single quotes { switch nextRuneType { case eofRuneClass: { err = fmt.Errorf("EOF found when expecting closing quote") token := &Token{ tokenType: tokenType, value: string(value)} return token, err } case nonEscapingQuoteRuneClass: { state = inWordState } default: { value = append(value, nextRune) } } } case commentState: // in a comment { switch nextRuneType { case eofRuneClass: { token := &Token{ tokenType: tokenType, value: string(value)} return token, err } case spaceRuneClass: { if nextRune == '\n' { state = startState token := &Token{ tokenType: tokenType, value: string(value)} return token, err } else { value = append(value, nextRune) } } default: { value = append(value, nextRune) } } } default: { return nil, fmt.Errorf("Unexpected state: %v", state) } } } }
https://github.com/imdario/mergo/blob/45df20b7fcedb0ff48e461334a1f0aafcc3892e3/map.go#L132-L134
func Map(dst, src interface{}, opts ...func(*Config)) error { return _map(dst, src, opts...) }
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/archive50.go#L426-L456
func (a *archive50) next() (*fileBlockHeader, error) { for { h, err := a.readBlockHeader() if err != nil { return nil, err } a.byteReader = limitByteReader(a.v, h.dataSize) switch h.htype { case block5File: return a.parseFileHeader(h) case block5Arc: flags := h.data.uvarint() a.multi = flags&arc5MultiVol > 0 a.solid = flags&arc5Solid > 0 case block5Encrypt: err = a.parseEncryptionBlock(h.data) case block5End: flags := h.data.uvarint() if flags&endArc5NotLast == 0 || !a.multi { return nil, errArchiveEnd } return nil, errArchiveContinues default: // discard block data _, err = io.Copy(ioutil.Discard, a.byteReader) } if err != nil { return nil, err } } }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/server.go#L101-L108
func (a *App) Stop(err error) error { a.cancel() if err != nil && errors.Cause(err) != context.Canceled { a.Logger.Error(err) return err } return nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/channel.go#L780-L786
func (ch *Channel) State() ChannelState { ch.mutable.RLock() state := ch.mutable.state ch.mutable.RUnlock() return state }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/ppsutil/util.go#L172-L189
func GetPipelineInfo(pachClient *client.APIClient, ptr *pps.EtcdPipelineInfo, full bool) (*pps.PipelineInfo, error) { result := &pps.PipelineInfo{} if full { buf := bytes.Buffer{} if err := pachClient.GetFile(ppsconsts.SpecRepo, ptr.SpecCommit.ID, ppsconsts.SpecFile, 0, 0, &buf); err != nil { return nil, fmt.Errorf("could not read existing PipelineInfo from PFS: %v", err) } if err := result.Unmarshal(buf.Bytes()); err != nil { return nil, fmt.Errorf("could not unmarshal PipelineInfo bytes from PFS: %v", err) } } result.State = ptr.State result.Reason = ptr.Reason result.JobCounts = ptr.JobCounts result.LastJobState = ptr.LastJobState result.SpecCommit = ptr.SpecCommit return result, nil }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L1533-L1542
func (o *MapFloat64Option) Set(value string) error { parts := stringMapRegex.Split(value, 2) if len(parts) != 2 { return fmt.Errorf("expected KEY=VALUE got '%s'", value) } val := Float64Option{} val.Set(parts[1]) (*o)[parts[0]] = val return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L59-L63
func (v UndoParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/giantswarm/certctl/blob/2a6615f61499cd09a8d5ced9a5fade322d2de254/service/role/error.go#L21-L29
func IsNoVaultHandlerDefined(err error) bool { cause := microerror.Cause(err) if cause != nil && strings.Contains(cause.Error(), "no handler for route") { return true } return false }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/model.go#L25-L27
func (m *Model) Err(errno int, message string) error { return validationError.New(message) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/config.go#L1306-L1328
func ValidateController(c *Controller) error { urlTmpl, err := template.New("JobURL").Parse(c.JobURLTemplateString) if err != nil { return fmt.Errorf("parsing template: %v", err) } c.JobURLTemplate = urlTmpl reportTmpl, err := template.New("Report").Parse(c.ReportTemplateString) if err != nil { return fmt.Errorf("parsing template: %v", err) } c.ReportTemplate = reportTmpl if c.MaxConcurrency < 0 { return fmt.Errorf("controller has invalid max_concurrency (%d), it needs to be a non-negative number", c.MaxConcurrency) } if c.MaxGoroutines == 0 { c.MaxGoroutines = 20 } if c.MaxGoroutines <= 0 { return fmt.Errorf("controller has invalid max_goroutines (%d), it needs to be a positive number", c.MaxGoroutines) } return nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L102-L107
func singleError(err error) error { if me, ok := err.(appengine.MultiError); ok { return me[0] } return err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/client.go#L357-L382
func ClientMapFromFile(clustersPath, namespace string) (map[string]*Client, error) { data, err := ioutil.ReadFile(clustersPath) if err != nil { return nil, fmt.Errorf("read error: %v", err) } raw, err := UnmarshalClusterMap(data) if err != nil { return nil, fmt.Errorf("unmarshal error: %v", err) } foundDefault := false result := map[string]*Client{} for alias, config := range raw { client, err := newClient(&config, namespace) if err != nil { return nil, fmt.Errorf("failed to load config for build cluster alias %q in file %q: %v", alias, clustersPath, err) } result[alias] = client if alias == DefaultClusterAlias { foundDefault = true } } if !foundDefault { return nil, fmt.Errorf("failed to find the required %q alias in build cluster config %q", DefaultClusterAlias, clustersPath) } return result, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L228-L234
func (ws writeSet) cmps(rev int64) []v3.Cmp { cmps := make([]v3.Cmp, 0, len(ws)) for key := range ws { cmps = append(cmps, v3.Compare(v3.ModRevision(key), "<", rev)) } return cmps }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/ae.go#L175-L185
func insertContext(f *ast.File, call *ast.CallExpr, ctx *ast.Ident) { if ctx == nil { // context is unknown, so use a plain "ctx". ctx = ast.NewIdent("ctx") } else { // Create a fresh *ast.Ident so we drop the position information. ctx = ast.NewIdent(ctx.Name) } call.Args = append([]ast.Expr{ctx}, call.Args...) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/external-plugins/needs-rebase/main.go#L138-L150
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // TODO: Move webhook handling logic out of hook binary so that we don't have to import all // plugins just to validate the webhook. eventType, eventGUID, payload, ok, _ := github.ValidateWebhook(w, r, s.tokenGenerator()) if !ok { return } fmt.Fprint(w, "Event received. Have a nice day.") if err := s.handleEvent(eventType, eventGUID, payload); err != nil { logrus.WithError(err).Error("Error parsing event.") } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/param_analyzer.go#L236-L240
func appendSorted(params []*gen.ActionParam, param *gen.ActionParam) []*gen.ActionParam { params = append(params, param) sort.Sort(gen.ByName(params)) return params }
https://github.com/google/acme/blob/7c6dfc908d68ed254a16c126f6770f4d9d9352da/config.go#L163-L165
func sameDir(existing, filename string) string { return filepath.Join(filepath.Dir(existing), filename) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L150-L162
func (in *ProwJobList) DeepCopyInto(out *ProwJobList) { *out = *in out.TypeMeta = in.TypeMeta out.ListMeta = in.ListMeta if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]ProwJob, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/deck/main.go#L625-L647
func handleRequestJobViews(sg *spyglass.Spyglass, cfg config.Getter, o options) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { start := time.Now() setHeadersNoCaching(w) src := strings.TrimPrefix(r.URL.Path, "/view/") page, err := renderSpyglass(sg, cfg, src, o) if err != nil { logrus.WithError(err).Error("error rendering spyglass page") message := fmt.Sprintf("error rendering spyglass page: %v", err) http.Error(w, message, http.StatusInternalServerError) return } fmt.Fprint(w, page) elapsed := time.Since(start) logrus.WithFields(logrus.Fields{ "duration": elapsed.String(), "endpoint": r.URL.Path, "source": src, }).Info("Loading view completed.") } }
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/tuple.go#L30-L32
func (t *Tuple) Is(tupleType TupleType) bool { return t.Header.Hash == tupleType.Hash && t.Header.NamespaceHash == tupleType.NamespaceHash }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/gocore/region.go#L80-L85
func (r region) Int32() int32 { if r.typ.Kind != KindInt || r.typ.Size != 4 { panic("bad int32 type " + r.typ.Name) } return r.p.proc.ReadInt32(r.a) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/pprof.go#L49-L55
func profileHandler(w http.ResponseWriter, r *http.Request, t auth.Token) error { if !permission.Check(t, permission.PermDebug) { return permission.ErrUnauthorized } pprof.Profile(w, r) return nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/archive/oci_transport.go#L177-L192
func createUntarTempDir(ref ociArchiveReference) (tempDirOCIRef, error) { tempDirRef, err := createOCIRef(ref.image) if err != nil { return tempDirOCIRef{}, errors.Wrap(err, "error creating oci reference") } src := ref.resolvedFile dst := tempDirRef.tempDirectory // TODO: This can take quite some time, and should ideally be cancellable using a context.Context. if err := archive.UntarPath(src, dst); err != nil { if err := tempDirRef.deleteTempDir(); err != nil { return tempDirOCIRef{}, errors.Wrapf(err, "error deleting temp directory %q", tempDirRef.tempDirectory) } return tempDirOCIRef{}, errors.Wrapf(err, "error untarring file %q", tempDirRef.tempDirectory) } return tempDirRef, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph.go#L1980-L2052
func (s *storageCeph) ContainerBackupLoad(info backupInfo, data io.ReadSeeker, tarArgs []string) error { // create the main container err := s.doContainerCreate(info.Project, info.Name, info.Privileged) if err != nil { return err } // mount container _, err = s.doContainerMount(info.Project, info.Name) if err != nil { return err } containerMntPoint := getContainerMountPoint(info.Project, s.pool.Name, info.Name) // Extract container for _, snap := range info.Snapshots { cur := fmt.Sprintf("backup/snapshots/%s", snap) // Prepare tar arguments args := append(tarArgs, []string{ "-", "--recursive-unlink", "--strip-components=3", "--xattrs-include=*", "-C", containerMntPoint, cur, }...) // Extract snapshots data.Seek(0, 0) err = shared.RunCommandWithFds(data, nil, "tar", args...) if err != nil { logger.Errorf("Failed to untar \"%s\" into \"%s\": %s", cur, containerMntPoint, err) return err } // This is costly but we need to ensure that all cached data has // been committed to disk. If we don't then the rbd snapshot of // the underlying filesystem can be inconsistent or - worst case // - empty. syscall.Sync() msg, fsFreezeErr := shared.TryRunCommand("fsfreeze", "--freeze", containerMntPoint) logger.Debugf("Trying to freeze the filesystem: %s: %s", msg, fsFreezeErr) // create snapshot err = s.doContainerSnapshotCreate(info.Project, fmt.Sprintf("%s/%s", info.Name, snap), info.Name) if fsFreezeErr == nil { msg, fsFreezeErr := shared.TryRunCommand("fsfreeze", "--unfreeze", containerMntPoint) logger.Debugf("Trying to unfreeze the filesystem: %s: %s", msg, fsFreezeErr) } if err != nil { return err } } // Prepare tar arguments args := append(tarArgs, []string{ "-", "--strip-components=2", "--xattrs-include=*", "-C", containerMntPoint, "backup/container", }...) // Extract container data.Seek(0, 0) err = shared.RunCommandWithFds(data, nil, "tar", args...) if err != nil { logger.Errorf("Failed to untar \"backup/container\" into \"%s\": %s", containerMntPoint, err) return err } return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/storage.go#L192-L211
func (ms *MemoryStorage) CreateSnapshot(i uint64, cs *pb.ConfState, data []byte) (pb.Snapshot, error) { ms.Lock() defer ms.Unlock() if i <= ms.snapshot.Metadata.Index { return pb.Snapshot{}, ErrSnapOutOfDate } offset := ms.ents[0].Index if i > ms.lastIndex() { raftLogger.Panicf("snapshot %d is out of bound lastindex(%d)", i, ms.lastIndex()) } ms.snapshot.Metadata.Index = i ms.snapshot.Metadata.Term = ms.ents[i-offset].Term if cs != nil { ms.snapshot.Metadata.ConfState = *cs } ms.snapshot.Data = data return ms.snapshot, nil }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/json/decode.go#L17-L19
func NewStreamDecoder(r io.Reader) *objconv.StreamDecoder { return objconv.NewStreamDecoder(NewParser(r)) }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L257-L307
func (p *Part) decodeContent(r io.Reader) error { // contentReader will point to the end of the content decoding pipeline. contentReader := r // b64cleaner aggregates errors, must maintain a reference to it to get them later. var b64cleaner *coding.Base64Cleaner // Build content decoding reader. encoding := p.Header.Get(hnContentEncoding) validEncoding := true switch strings.ToLower(encoding) { case cteQuotedPrintable: contentReader = coding.NewQPCleaner(contentReader) contentReader = quotedprintable.NewReader(contentReader) case cteBase64: b64cleaner = coding.NewBase64Cleaner(contentReader) contentReader = base64.NewDecoder(base64.RawStdEncoding, b64cleaner) case cte8Bit, cte7Bit, cteBinary, "": // No decoding required. default: // Unknown encoding. validEncoding = false p.addWarning( ErrorContentEncoding, "Unrecognized Content-Transfer-Encoding type %q", encoding) } // Build charset decoding reader. if validEncoding && strings.HasPrefix(p.ContentType, "text/") { var err error contentReader, err = p.convertFromDetectedCharset(contentReader) if err != nil { return err } } // Decode and store content. content, err := ioutil.ReadAll(contentReader) if err != nil { return errors.WithStack(err) } p.Content = content // Collect base64 errors. if b64cleaner != nil { for _, err := range b64cleaner.Errors { p.Errors = append(p.Errors, &Error{ Name: ErrorMalformedBase64, Detail: err.Error(), Severe: false, }) } } return nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/typecheck.go#L633-L668
func split(s string) []string { out := []string{} i := 0 // current type being scanned is s[i:j]. nparen := 0 for j := 0; j < len(s); j++ { switch s[j] { case ' ': if i == j { i++ } case '(': nparen++ case ')': nparen-- if nparen < 0 { // probably can't happen return nil } case ',': if nparen == 0 { if i < j { out = append(out, s[i:j]) } i = j + 1 } } } if nparen != 0 { // probably can't happen return nil } if i < len(s) { out = append(out, s[i:]) } return out }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L875-L879
func (v SetAttributesAsTextParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom8(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L26-L34
func Load(schema Schema, values map[string]string) (Map, error) { m := Map{ schema: schema, } // Populate the initial values. _, err := m.update(values) return m, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L1345-L1348
func (p GenerateTestReportParams) WithGroup(group string) *GenerateTestReportParams { p.Group = group return &p }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/client.go#L345-L410
func NewOnUserMachine(reportMetrics bool, portForward bool, prefix string, options ...Option) (*APIClient, error) { cfg, err := config.Read() if err != nil { // metrics errors are non fatal log.Warningf("error loading user config from ~/.pachyderm/config: %v", err) } // create new pachctl client var fw *PortForwarder addr, cfgOptions, err := getUserMachineAddrAndOpts(cfg) if err != nil { return nil, err } if addr == "" { addr = fmt.Sprintf("0.0.0.0:%s", DefaultPachdNodePort) if portForward { fw = portForwarder() } } client, err := NewFromAddress(addr, append(options, cfgOptions...)...) if err != nil { if strings.Contains(err.Error(), "context deadline exceeded") { // port always starts after last colon, but net.SplitHostPort returns an // error on a hostport without a colon, which this might be port := "" if colonIdx := strings.LastIndexByte(addr, ':'); colonIdx >= 0 { port = addr[colonIdx+1:] } // Check for errors in approximate order of helpfulness if port != "" && port != DefaultPachdPort && port != DefaultPachdNodePort { return nil, fmt.Errorf("could not connect (note: port is usually "+ "%s or %s, but is currently set to %q--is this right?): %v", DefaultPachdNodePort, DefaultPachdPort, port, err) } if strings.HasPrefix(addr, "0.0.0.0") || strings.HasPrefix(addr, "127.0.0.1") || strings.HasPrefix(addr, "[::1]") || strings.HasPrefix(addr, "localhost") { return nil, fmt.Errorf("could not connect (note: address %q looks "+ "like loopback, check that 'pachctl port-forward' is running): %v", addr, err) } if port == "" { return nil, fmt.Errorf("could not connect (note: address %q does not "+ "seem to be host:port): %v", addr, err) } } return nil, fmt.Errorf("could not connect to pachd at %q: %v", addr, err) } // Add metrics info & authentication token client.metricsPrefix = prefix if cfg != nil && cfg.UserID != "" && reportMetrics { client.metricsUserID = cfg.UserID } if cfg != nil && cfg.V1 != nil && cfg.V1.SessionToken != "" { client.authenticationToken = cfg.V1.SessionToken } // Add port forwarding. This will set it to nil if port forwarding is // disabled, or an address is explicitly set. client.portForwarder = fw return client, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/client.go#L156-L161
func (c *Client) SetEndpoints(eps ...string) { c.mu.Lock() defer c.mu.Unlock() c.cfg.Endpoints = eps c.resolverGroup.SetEndpoints(eps) }
https://github.com/akutz/gotil/blob/6fa2e80bd3ac40f15788cfc3d12ebba49a0add92/gotil.go#L165-L168
func FileExistsInPath(fileName string) bool { _, err := exec.LookPath(fileName) return err == nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/proxy/grpcproxy/leader.go#L109-L113
func (l *leader) lostNotify() <-chan struct{} { l.mu.RLock() defer l.mu.RUnlock() return l.leaderc }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/artifact-uploader/controller.go#L187-L196
func (c *Controller) handleErr(err error, key item) { if c.queue.NumRequeues(key) < 5 { glog.Infof("Error uploading logs for container %v in pod %v: %v", key.containerName, key.podName, err) c.queue.AddRateLimited(key) return } c.queue.Forget(key) glog.Infof("Giving up on upload of logs for container %v in pod %v: %v", key.containerName, key.podName, err) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/logexporter/cmd/main.go#L134-L152
func createSystemdLogfiles(outputDir string) { services := append(systemdServices, nodeSystemdServices...) for _, service := range services { if err := createSystemdLogfile(service, "cat", outputDir); err != nil { glog.Warningf("Failed to record journalctl logs: %v", err) } } // Service logs specific to VM setup. for _, service := range systemdSetupServices { if err := createSystemdLogfile(service, "short-precise", outputDir); err != nil { glog.Warningf("Failed to record journalctl logs: %v", err) } } if *dumpSystemdJournal { if err := createFullSystemdLogfile(outputDir); err != nil { glog.Warningf("Failed to record journalctl logs: %v", err) } } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/profiles_utils.go#L152-L185
func doProfileUpdateCluster(d *Daemon, project, name string, old api.ProfilePut) error { nodeName := "" err := d.cluster.Transaction(func(tx *db.ClusterTx) error { var err error nodeName, err = tx.NodeName() return err }) if err != nil { return errors.Wrap(err, "failed to query local node name") } containers, err := getProfileContainersInfo(d.cluster, project, name) if err != nil { return errors.Wrapf(err, "failed to query containers associated with profile '%s'", name) } failures := map[string]error{} for _, args := range containers { err := doProfileUpdateContainer(d, name, old, nodeName, args) if err != nil { failures[args.Name] = err } } if len(failures) != 0 { msg := "The following containers failed to update (profile change still saved):\n" for cname, err := range failures { msg += fmt.Sprintf(" - %s: %s\n", cname, err) } return fmt.Errorf("%s", msg) } return nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pkg/tracing/tracing.go#L173-L176
func UnaryServerInterceptor() grpc.UnaryServerInterceptor { return otgrpc.OpenTracingServerInterceptor(opentracing.GlobalTracer(), otgrpc.IncludingSpans(addTraceIfTracingEnabled)) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/proxy/grpcproxy/metrics.go#L71-L98
func HandleMetrics(mux *http.ServeMux, c *http.Client, eps []string) { // random shuffle endpoints r := rand.New(rand.NewSource(int64(time.Now().Nanosecond()))) if len(eps) > 1 { eps = shuffleEndpoints(r, eps) } pathMetrics := etcdhttp.PathMetrics mux.HandleFunc(pathMetrics, func(w http.ResponseWriter, r *http.Request) { target := fmt.Sprintf("%s%s", eps[0], pathMetrics) if !strings.HasPrefix(target, "http") { scheme := "http" if r.TLS != nil { scheme = "https" } target = fmt.Sprintf("%s://%s", scheme, target) } resp, err := c.Get(target) if err != nil { http.Error(w, "Internal server error", http.StatusInternalServerError) } defer resp.Body.Close() w.Header().Set("Content-Type", "text/plain; version=0.0.4") body, _ := ioutil.ReadAll(resp.Body) fmt.Fprintf(w, "%s", body) }) }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection.go#L106-L117
func (s *Selection) MouseToElement() error { selectedElement, err := s.elements.GetExactlyOne() if err != nil { return fmt.Errorf("failed to select element from %s: %s", s, err) } if err := s.session.MoveTo(selectedElement.(*api.Element), nil); err != nil { return fmt.Errorf("failed to move mouse to element for %s: %s", s, err) } return nil }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/peer_name_hash.go#L34-L39
func PeerNameFromString(nameStr string) (PeerName, error) { if _, err := hex.DecodeString(nameStr); err != nil { return UnknownPeerName, err } return PeerName(nameStr), nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L129-L143
func (m AutoSequence) MutateTransaction(o *TransactionBuilder) error { source := o.TX.SourceAccount if source == (xdr.AccountId{}) { return errors.New("auto sequence used prior to setting source account") } seq, err := m.SequenceForAccount(source.Address()) if err != nil { return err } o.TX.SeqNum = seq + 1 return nil }
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/reply.go#L28-L36
func ReplyJSON(w http.ResponseWriter, code int, obj interface{}) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) out, err := json.Marshal(obj) if err != nil { out = []byte(`{"msg": "internal marshal error"}`) } w.Write(out) }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/post_apps_responses.go#L25-L59
func (o *PostAppsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewPostAppsOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 400: result := NewPostAppsBadRequest() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 409: result := NewPostAppsConflict() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: result := NewPostAppsDefault(response.Code()) if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } if response.Code()/100 == 2 { return result, nil } return nil, result } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L170-L174
func (r *ReadBuffer) Wrap(b []byte) { r.buffer = b r.remaining = b r.err = nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L7696-L7700
func (v *AddCompilationCacheParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage85(&r, v) return r.Error() }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/default.go#L166-L168
func Warningm(m *Attrs, msg string, a ...interface{}) error { return curDefault.Warningm(m, msg, a...) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/selective_string.go#L77-L88
func (ss *SelectiveStringsValue) Set(s string) error { vs := strings.Split(s, ",") for i := range vs { if _, ok := ss.valids[vs[i]]; ok { ss.vs = append(ss.vs, vs[i]) } else { return fmt.Errorf("invalid value %q", vs[i]) } } sort.Strings(ss.vs) return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/fakegithub/fakegithub.go#L140-L149
func (f *FakeClient) CreateComment(owner, repo string, number int, comment string) error { f.IssueCommentsAdded = append(f.IssueCommentsAdded, fmt.Sprintf("%s/%s#%d:%s", owner, repo, number, comment)) f.IssueComments[number] = append(f.IssueComments[number], github.IssueComment{ ID: f.IssueCommentID, Body: comment, User: github.User{Login: botName}, }) f.IssueCommentID++ return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L797-L808
func (c *Client) HasPermission(org, repo, user string, roles ...string) (bool, error) { perm, err := c.GetUserPermission(org, repo, user) if err != nil { return false, err } for _, r := range roles { if r == perm { return true, nil } } return false, nil }
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L656-L670
func (c *Client) Send(chat Chat) (n int, err error) { var subtext = `` var thdtext = `` if chat.Subject != `` { subtext = `<subject>` + xmlEscape(chat.Subject) + `</subject>` } if chat.Thread != `` { thdtext = `<thread>` + xmlEscape(chat.Thread) + `</thread>` } stanza := "<message to='%s' type='%s' id='%s' xml:lang='en'>" + subtext + "<body>%s</body>" + thdtext + "</message>" return fmt.Fprintf(c.conn, stanza, xmlEscape(chat.Remote), xmlEscape(chat.Type), cnonce(), xmlEscape(chat.Text)) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L1748-L1825
func NewOperationBody(aType OperationType, value interface{}) (result OperationBody, err error) { result.Type = aType switch OperationType(aType) { case OperationTypeCreateAccount: tv, ok := value.(CreateAccountOp) if !ok { err = fmt.Errorf("invalid value, must be CreateAccountOp") return } result.CreateAccountOp = &tv case OperationTypePayment: tv, ok := value.(PaymentOp) if !ok { err = fmt.Errorf("invalid value, must be PaymentOp") return } result.PaymentOp = &tv case OperationTypePathPayment: tv, ok := value.(PathPaymentOp) if !ok { err = fmt.Errorf("invalid value, must be PathPaymentOp") return } result.PathPaymentOp = &tv case OperationTypeManageOffer: tv, ok := value.(ManageOfferOp) if !ok { err = fmt.Errorf("invalid value, must be ManageOfferOp") return } result.ManageOfferOp = &tv case OperationTypeCreatePassiveOffer: tv, ok := value.(CreatePassiveOfferOp) if !ok { err = fmt.Errorf("invalid value, must be CreatePassiveOfferOp") return } result.CreatePassiveOfferOp = &tv case OperationTypeSetOptions: tv, ok := value.(SetOptionsOp) if !ok { err = fmt.Errorf("invalid value, must be SetOptionsOp") return } result.SetOptionsOp = &tv case OperationTypeChangeTrust: tv, ok := value.(ChangeTrustOp) if !ok { err = fmt.Errorf("invalid value, must be ChangeTrustOp") return } result.ChangeTrustOp = &tv case OperationTypeAllowTrust: tv, ok := value.(AllowTrustOp) if !ok { err = fmt.Errorf("invalid value, must be AllowTrustOp") return } result.AllowTrustOp = &tv case OperationTypeAccountMerge: tv, ok := value.(AccountId) if !ok { err = fmt.Errorf("invalid value, must be AccountId") return } result.Destination = &tv case OperationTypeInflation: // void case OperationTypeManageData: tv, ok := value.(ManageDataOp) if !ok { err = fmt.Errorf("invalid value, must be ManageDataOp") return } result.ManageDataOp = &tv } return }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/root.go#L10-L23
func newRoot() *cobra.Command { cmd := &cobra.Command{ Use: "lxd-generate", Short: "Code generation tool for LXD development", Long: `This is the entry point for all "go:generate" directives used in LXD's source code.`, RunE: func(cmd *cobra.Command, args []string) error { return fmt.Errorf("Not implemented") }, } cmd.AddCommand(newDb()) return cmd }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L202-L206
func (v TakeCoverageDeltaReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss1(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/database/rethinkdb/rethinkdb.go#L23-L58
func WritePluginResultsToDatabase(results map[string]interface{}) { // connect to RethinkDB session, err := r.Connect(r.ConnectOpts{ Address: fmt.Sprintf("%s:28015", utils.Getopt("MALICE_RETHINKDB", "rethink")), Timeout: 5 * time.Second, Database: "malice", }) if err != nil { log.Debug(err) return } defer session.Close() res, err := r.Table("samples").Get(results["ID"]).Run(session) utils.Assert(err) defer res.Close() if res.IsNil() { // upsert into RethinkDB resp, err := r.Table("samples").Insert(results, r.InsertOpts{Conflict: "replace"}).RunWrite(session) utils.Assert(err) log.Debug(resp) } else { resp, err := r.Table("samples").Get(results["ID"]).Update(map[string]interface{}{ "plugins": map[string]interface{}{ category: map[string]interface{}{ name: results["Data"], }, }, }).RunWrite(session) utils.Assert(err) log.Debug(resp) } }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/matcher.go#L245-L258
func (m *MapMatcher) UnmarshalJSON(bytes []byte) (err error) { sk := make(map[string]string) err = json.Unmarshal(bytes, &sk) if err != nil { return } *m = make(map[string]Matcher) for k, v := range sk { (*m)[k] = String(v) } return }
https://github.com/michaelbironneau/garbler/blob/2018e2dc9c1173564cc1352ccb90bdc0ac29c12f/lib/garbler.go#L249-L255
func randInt(max int) int { i, err := crypto.Int(crypto.Reader, big.NewInt(int64(max))) if err == nil { return int(i.Int64()) } return rand.Intn(max) }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L131-L134
func (win *Window) ShowImage(image *IplImage) { win.image = image C.cvShowImage(win.name_c, unsafe.Pointer(image)) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/directory/directory_transport.go#L142-L145
func (ref dirReference) NewImage(ctx context.Context, sys *types.SystemContext) (types.ImageCloser, error) { src := newImageSource(ref) return image.FromSource(ctx, sys, src) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/raft.go#L572-L580
func (r *raft) bcastAppend() { r.forEachProgress(func(id uint64, _ *Progress) { if id == r.id { return } r.sendAppend(id) }) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/gopherage/pkg/util/util.go#L51-L69
func LoadProfile(origin string) ([]*cover.Profile, error) { filename := origin if origin == "-" { // Annoyingly, ParseProfiles only accepts a filename, so we have to write the bytes to disk // so it can read them back. // We could probably also just give it /dev/stdin, but that'll break on Windows. tf, err := ioutil.TempFile("", "") if err != nil { return nil, fmt.Errorf("failed to create temp file: %v", err) } defer tf.Close() defer os.Remove(tf.Name()) if _, err := io.Copy(tf, os.Stdin); err != nil { return nil, fmt.Errorf("failed to copy stdin to temp file: %v", err) } filename = tf.Name() } return cover.ParseProfiles(filename) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L165-L168
func (p HighlightNodeParams) WithNodeID(nodeID cdp.NodeID) *HighlightNodeParams { p.NodeID = nodeID return &p }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/key.go#L50-L65
func waitDeletes(ctx context.Context, client *v3.Client, pfx string, maxCreateRev int64) (*pb.ResponseHeader, error) { getOpts := append(v3.WithLastCreate(), v3.WithMaxCreateRev(maxCreateRev)) for { resp, err := client.Get(ctx, pfx, getOpts...) if err != nil { return nil, err } if len(resp.Kvs) == 0 { return resp.Header, nil } lastKey := string(resp.Kvs[0].Key) if err = waitDelete(ctx, client, lastKey, resp.Header.Revision); err != nil { return nil, err } } }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tchooks/tchooks.go#L183-L187
func (hooks *Hooks) RemoveHook(hookGroupId, hookId string) error { cd := tcclient.Client(*hooks) _, _, err := (&cd).APICall(nil, "DELETE", "/hooks/"+url.QueryEscape(hookGroupId)+"/"+url.QueryEscape(hookId), nil, nil) return err }
https://github.com/mastahyeti/fakeca/blob/c1d84b1b473e99212130da7b311dd0605de5ed0a/configuration.go#L215-L219
func IssuingCertificateURL(value ...string) Option { return func(c *configuration) { c.issuingCertificateURL = append(c.issuingCertificateURL, value...) } }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_dest.go#L439-L484
func (d *dockerImageDestination) putSignaturesToLookaside(signatures [][]byte) error { // FIXME? This overwrites files one at a time, definitely not atomic. // A failure when updating signatures with a reordered copy could lose some of them. // Skip dealing with the manifest digest if not necessary. if len(signatures) == 0 { return nil } if d.manifestDigest.String() == "" { // This shouldn’t happen, ImageDestination users are required to call PutManifest before PutSignatures return errors.Errorf("Unknown manifest digest, can't add signatures") } // NOTE: Keep this in sync with docs/signature-protocols.md! for i, signature := range signatures { url := signatureStorageURL(d.c.signatureBase, d.manifestDigest, i) if url == nil { return errors.Errorf("Internal error: signatureStorageURL with non-nil base returned nil") } err := d.putOneSignature(url, signature) if err != nil { return err } } // Remove any other signatures, if present. // We stop at the first missing signature; if a previous deleting loop aborted // prematurely, this may not clean up all of them, but one missing signature // is enough for dockerImageSource to stop looking for other signatures, so that // is sufficient. for i := len(signatures); ; i++ { url := signatureStorageURL(d.c.signatureBase, d.manifestDigest, i) if url == nil { return errors.Errorf("Internal error: signatureStorageURL with non-nil base returned nil") } missing, err := d.c.deleteOneSignature(url) if err != nil { return err } if missing { break } } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util.go#L276-L288
func RandomCryptoString() (string, error) { buf := make([]byte, 32) n, err := rand.Read(buf) if err != nil { return "", err } if n != len(buf) { return "", fmt.Errorf("not enough random bytes read") } return hex.EncodeToString(buf), nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/config/map.go#L95-L110
func (m *Map) Dump() map[string]interface{} { values := map[string]interface{}{} for name, key := range m.schema { value := m.GetRaw(name) if value != key.Default { if key.Hidden { values[name] = true } else { values[name] = value } } } return values }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L798-L800
func Successf(format string, val ...interface{}) error { return glg.out(OK, format, val...) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L3209-L3213
func (v *PlatformFontUsage) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss28(&r, v) return r.Error() }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2977-L2980
func (e ManageOfferEffect) ValidEnum(v int32) bool { _, ok := manageOfferEffectMap[v] return ok }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/form.go#L45-L49
func NewError(e string) FormErrors { errors := FormErrors{} errors.AddError(e) return errors }