_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/heapprofiler.go#L51-L53
func (p *CollectGarbageParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandCollectGarbage, nil, nil) }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/snapshot.go#L25-L44
func (s *Snapshot) Name() (string, error) { var err C.VixError = C.VIX_OK var name *C.char err = C.get_property(s.handle, C.VIX_PROPERTY_SNAPSHOT_DISPLAYNAME, unsafe.Pointer(&name)) defer C.Vix_FreeBuffer(unsafe.Pointer(name)) if C.VIX_OK != err { return "", &Error{ Operation: "snapshot.Name", Code: int(err & 0xFFFF), Text: C.GoString(C.Vix_GetErrorText(err, nil)), } } return C.GoString(name), nil }
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L73-L76
func (now *Now) EndOfDay() time.Time { y, m, d := now.Date() return time.Date(y, m, d, 23, 59, 59, int(time.Second-time.Nanosecond), now.Location()) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/node.go#L200-L235
func StartNode(c *Config, peers []Peer) Node { r := newRaft(c) // become the follower at term 1 and apply initial configuration // entries of term 1 r.becomeFollower(1, None) for _, peer := range peers { cc := pb.ConfChange{Type: pb.ConfChangeAddNode, NodeID: peer.ID, Context: peer.Context} d, err := cc.Marshal() if err != nil { panic("unexpected marshal error") } e := pb.Entry{Type: pb.EntryConfChange, Term: 1, Index: r.raftLog.lastIndex() + 1, Data: d} r.raftLog.append(e) } // Mark these initial entries as committed. // TODO(bdarnell): These entries are still unstable; do we need to preserve // the invariant that committed < unstable? r.raftLog.committed = r.raftLog.lastIndex() // Now apply them, mainly so that the application can call Campaign // immediately after StartNode in tests. Note that these nodes will // be added to raft twice: here and when the application's Ready // loop calls ApplyConfChange. The calls to addNode must come after // all calls to raftLog.append so progress.next is set after these // bootstrapping entries (it is an error if we try to append these // entries since they have already been committed). // We do not set raftLog.applied so the application will be able // to observe all conf changes via Ready.CommittedEntries. for _, peer := range peers { r.addNode(peer.ID) } n := newNode() n.logger = c.Logger go n.run(r) return &n }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L526-L540
func (prm *prmMatchExact) UnmarshalJSON(data []byte) error { *prm = prmMatchExact{} var tmp prmMatchExact if err := paranoidUnmarshalJSONObjectExactFields(data, map[string]interface{}{ "type": &tmp.Type, }); err != nil { return err } if tmp.Type != prmTypeMatchExact { return InvalidPolicyFormatError(fmt.Sprintf("Unexpected policy requirement type \"%s\"", tmp.Type)) } *prm = *newPRMMatchExact() return nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L255-L302
func GetMulti(c context.Context, key []*Key, dst interface{}) error { v := reflect.ValueOf(dst) multiArgType, _ := checkMultiArg(v) if multiArgType == multiArgTypeInvalid { return errors.New("datastore: dst has invalid type") } if len(key) != v.Len() { return errors.New("datastore: key and dst slices have different length") } if len(key) == 0 { return nil } if err := multiValid(key); err != nil { return err } req := &pb.GetRequest{ Key: multiKeyToProto(internal.FullyQualifiedAppID(c), key), } res := &pb.GetResponse{} if err := internal.Call(c, "datastore_v3", "Get", req, res); err != nil { return err } if len(key) != len(res.Entity) { return errors.New("datastore: internal error: server returned the wrong number of entities") } multiErr, any := make(appengine.MultiError, len(key)), false for i, e := range res.Entity { if e.Entity == nil { multiErr[i] = ErrNoSuchEntity } else { elem := v.Index(i) if multiArgType == multiArgTypePropertyLoadSaver || multiArgType == multiArgTypeStruct { elem = elem.Addr() } if multiArgType == multiArgTypeStructPtr && elem.IsNil() { elem.Set(reflect.New(elem.Type().Elem())) } multiErr[i] = loadEntity(elem.Interface(), e.Entity) } if multiErr[i] != nil { any = true } } if any { return multiErr } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/easyjson.go#L756-L760
func (v *ClearEventsParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoBackgroundservice7(&r, v) return r.Error() }
https://github.com/ccding/go-config-reader/blob/8b6c2b50197f20da3b1c5944c274c173634dc056/config/config.go#L126-L128
func (c *Config) Add(section string, key string, value string) { c.Set(section, key, value) }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/font.go#L159-L161
func (cache *FolderFontCache) Store(fontData FontData, font *truetype.Font) { cache.fonts[cache.namer(fontData)] = font }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/node/config.go#L19-L32
func ConfigLoad(tx *db.NodeTx) (*Config, error) { // Load current raw values from the database, any error is fatal. values, err := tx.Config() if err != nil { return nil, fmt.Errorf("cannot fetch node config from database: %v", err) } m, err := config.SafeLoad(ConfigSchema, values) if err != nil { return nil, fmt.Errorf("failed to load node config: %v", err) } return &Config{tx: tx, m: m}, nil }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L289-L296
func (it *inclusiveRangeIt) Next() int { val, err := it.ptr.Value(it.pos) it.pos++ if err != nil { return it.ptr.End() } return val }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/database/easyjson.go#L416-L420
func (v ExecuteSQLParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDatabase3(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/types.go#L336-L338
func (t ExceptionsState) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cmd/ask.go#L18-L30
func AskBool(question string, defaultAnswer string) bool { for { answer := askQuestion(question, defaultAnswer) if shared.StringInSlice(strings.ToLower(answer), []string{"yes", "y"}) { return true } else if shared.StringInSlice(strings.ToLower(answer), []string{"no", "n"}) { return false } invalidInput() } }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/callbacks.go#L532-L584
func UniqueFieldValidator(field string, zero interface{}, filters ...string) *Callback { return C("fire/UniqueFieldValidator", Only(Create, Update), func(ctx *Context) error { // check if field has changed if ctx.Operation == Update { // get original model original, err := ctx.Original() if err != nil { return err } // return if field has not been changed if reflect.DeepEqual(ctx.Model.MustGet(field), original.MustGet(field)) { return nil } } // get value value := ctx.Model.MustGet(field) // return if value is the zero value if value != NoZero && reflect.DeepEqual(value, zero) { return nil } // prepare query query := bson.M{ coal.F(ctx.Model, field): value, } // add filters for _, field := range filters { query[coal.F(ctx.Model, field)] = ctx.Model.MustGet(field) } // exclude soft deleted documents if supported if sdm := coal.L(ctx.Model, "fire-soft-delete", false); sdm != "" { query[coal.F(ctx.Model, sdm)] = nil } // count ctx.Tracer.Push("mgo/Query.Count") ctx.Tracer.Tag("query", query) n, err := ctx.Store.C(ctx.Model).Find(query).Limit(1).Count() if err != nil { return err } else if n != 0 { return E("attribute %s is not unique", field) } ctx.Tracer.Pop() return nil }) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/build.go#L34-L98
func build(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { tag := InputValue(r, "tag") if tag == "" { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: "you must specify the image tag.", } } opts, err := prepareToBuild(r) if err != nil { return err } if opts.File != nil { defer opts.File.Close() } w.Header().Set("Content-Type", "text") appName := r.URL.Query().Get(":appname") var userName string if t.IsAppToken() { if t.GetAppName() != appName && t.GetAppName() != app.InternalAppName { return &tsuruErrors.HTTP{Code: http.StatusUnauthorized, Message: "invalid app token"} } userName = InputValue(r, "user") } else { userName = t.GetUserName() } instance, err := app.GetByName(appName) if err != nil { return &tsuruErrors.HTTP{Code: http.StatusNotFound, Message: err.Error()} } opts.App = instance opts.BuildTag = tag opts.User = userName opts.GetKind() if t.GetAppName() != app.InternalAppName { canBuild := permission.Check(t, permission.PermAppBuild, contextsForApp(instance)...) if !canBuild { return &tsuruErrors.HTTP{Code: http.StatusForbidden, Message: "User does not have permission to do this action in this app"} } } evt, err := event.New(&event.Opts{ Target: appTarget(appName), Kind: permission.PermAppBuild, RawOwner: event.Owner{Type: event.OwnerTypeUser, Name: userName}, CustomData: opts, Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(instance)...), AllowedCancel: event.Allowed(permission.PermAppUpdateEvents, contextsForApp(instance)...), Cancelable: true, }) if err != nil { return err } var imageID string defer func() { evt.DoneCustomData(err, map[string]string{"image": imageID}) }() opts.Event = evt writer := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "please wait...") defer writer.Stop() opts.OutputStream = writer imageID, err = app.Build(opts) if err == nil { fmt.Fprintln(w, imageID) fmt.Fprintln(w, "OK") } return err }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/clientset/versioned/clientset.go#L73-L79
func NewForConfigOrDie(c *rest.Config) *Clientset { var cs Clientset cs.tsuruV1 = tsuruv1.NewForConfigOrDie(c) cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) return &cs }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/decorate/podspec.go#L135-L142
func LabelsAndAnnotationsForJob(pj prowapi.ProwJob) (map[string]string, map[string]string) { var extraLabels map[string]string if extraLabels = pj.ObjectMeta.Labels; extraLabels == nil { extraLabels = map[string]string{} } extraLabels[kube.ProwJobIDLabel] = pj.ObjectMeta.Name return LabelsAndAnnotationsForSpec(pj.Spec, extraLabels, nil) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/systeminfo/easyjson.go#L105-L109
func (v *ProcessInfo) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoSysteminfo(&r, v) return r.Error() }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/node.go#L559-L635
func rebalanceNodesHandler(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { var params provision.RebalanceNodesOptions err = ParseInput(r, &params) if err != nil { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: err.Error(), } } params.Force = true var permContexts []permTypes.PermissionContext var ok bool evtTarget := event.Target{Type: event.TargetTypeGlobal} params.Pool, ok = params.MetadataFilter[provision.PoolMetadataName] if ok { delete(params.MetadataFilter, provision.PoolMetadataName) permContexts = append(permContexts, permission.Context(permTypes.CtxPool, params.Pool)) evtTarget = event.Target{Type: event.TargetTypePool, Value: params.Pool} } if !permission.Check(t, permission.PermNodeUpdateRebalance, permContexts...) { return permission.ErrUnauthorized } evt, err := event.New(&event.Opts{ Target: evtTarget, Kind: permission.PermNodeUpdateRebalance, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), DisableLock: true, Allowed: event.Allowed(permission.PermPoolReadEvents, permContexts...), Cancelable: true, AllowedCancel: event.Allowed(permission.PermAppUpdateEvents, permContexts...), }) if err != nil { return err } defer func() { evt.Done(err) }() w.Header().Set("Content-Type", "application/x-json-stream") keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 15*time.Second, "") defer keepAliveWriter.Stop() writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)} evt.SetLogWriter(writer) params.Event = evt var provs []provision.Provisioner if params.Pool != "" { var p *pool.Pool var prov provision.Provisioner p, err = pool.GetPoolByName(params.Pool) if err != nil { return err } prov, err = p.GetProvisioner() if err != nil { return err } if _, ok := prov.(provision.NodeRebalanceProvisioner); !ok { return provision.ProvisionerNotSupported{Prov: prov, Action: "node rebalance operations"} } provs = append(provs, prov) } else { provs, err = provision.Registry() if err != nil { return err } } for _, prov := range provs { rebalanceProv, ok := prov.(provision.NodeRebalanceProvisioner) if !ok { continue } _, err = rebalanceProv.RebalanceNodes(params) if err != nil { return errors.Wrap(err, "Error trying to rebalance units in nodes") } } fmt.Fprintf(writer, "Units successfully rebalanced!\n") return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/types.go#L465-L470
func (j *ProwJob) ClusterAlias() string { if j.Spec.Cluster == "" { return DefaultClusterAlias } return j.Spec.Cluster }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/contrib/recipes/key.go#L62-L73
func putNewKV(kv v3.KV, key, val string, leaseID v3.LeaseID) (int64, error) { cmp := v3.Compare(v3.Version(key), "=", 0) req := v3.OpPut(key, val, v3.WithLease(leaseID)) txnresp, err := kv.Txn(context.TODO()).If(cmp).Then(req).Commit() if err != nil { return 0, err } if !txnresp.Succeeded { return 0, ErrKeyExists } return txnresp.Header.Revision, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L5037-L5041
func (v *GetAllCookiesParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork39(&r, v) return r.Error() }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L316-L324
func GetCols(arr Arr, submat *Mat, start_col, end_col int) *Mat { mat_new := C.cvGetCols( unsafe.Pointer(arr), (*C.CvMat)(submat), C.int(start_col), C.int(end_col), ) return (*Mat)(mat_new) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/reqres.go#L111-L136
func (w *reqResWriter) newFragment(initial bool, checksum Checksum) (*writableFragment, error) { if err := w.mex.checkError(); err != nil { return nil, w.failed(err) } message := w.messageForFragment(initial) // Create the frame frame := w.conn.opts.FramePool.Get() frame.Header.ID = w.mex.msgID frame.Header.messageType = message.messageType() // Write the message into the fragment, reserving flags and checksum bytes wbuf := typed.NewWriteBuffer(frame.Payload[:]) fragment := new(writableFragment) fragment.frame = frame fragment.flagsRef = wbuf.DeferByte() if err := message.write(wbuf); err != nil { return nil, err } wbuf.WriteSingleByte(byte(checksum.TypeCode())) fragment.checksumRef = wbuf.DeferBytes(checksum.Size()) fragment.checksum = checksum fragment.contents = wbuf return fragment, wbuf.Err() }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/daemon/daemon_transport.go#L63-L86
func ParseReference(refString string) (types.ImageReference, error) { // This is intended to be compatible with reference.ParseAnyReference, but more strict about refusing some of the ambiguous cases. // In particular, this rejects unprefixed digest values (64 hex chars), and sha256 digest prefixes (sha256:fewer-than-64-hex-chars). // digest:hexstring is structurally the same as a reponame:tag (meaning docker.io/library/reponame:tag). // reference.ParseAnyReference interprets such strings as digests. if dgst, err := digest.Parse(refString); err == nil { // The daemon explicitly refuses to tag images with a reponame equal to digest.Canonical - but _only_ this digest name. // Other digest references are ambiguous, so refuse them. if dgst.Algorithm() != digest.Canonical { return nil, errors.Errorf("Invalid docker-daemon: reference %s: only digest algorithm %s accepted", refString, digest.Canonical) } return NewReference(dgst, nil) } ref, err := reference.ParseNormalizedNamed(refString) // This also rejects unprefixed digest values if err != nil { return nil, err } if reference.FamiliarName(ref) == digest.Canonical.String() { return nil, errors.Errorf("Invalid docker-daemon: reference %s: The %s repository name is reserved for (non-shortened) digest references", refString, digest.Canonical) } return NewReference("", ref) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tethering/easyjson.go#L152-L156
func (v EventAccepted) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTethering1(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/types.go#L57-L59
func (t *ServiceName) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/jstemmer/go-junit-report/blob/af01ea7f8024089b458d804d5cdf190f962a9a0c/parser/parser.go#L76-L260
func Parse(r io.Reader, pkgName string) (*Report, error) { reader := bufio.NewReader(r) report := &Report{make([]Package, 0)} // keep track of tests we find var tests []*Test // keep track of benchmarks we find var benchmarks []*Benchmark // sum of tests' time, use this if current test has no result line (when it is compiled test) var testsTime time.Duration // current test var cur string // keep track if we've already seen a summary for the current test var seenSummary bool // coverage percentage report for current package var coveragePct string // stores mapping between package name and output of build failures var packageCaptures = map[string][]string{} // the name of the package which it's build failure output is being captured var capturedPackage string // capture any non-test output var buffers = map[string][]string{} // parse lines for { l, _, err := reader.ReadLine() if err != nil && err == io.EOF { break } else if err != nil { return nil, err } line := string(l) if strings.HasPrefix(line, "=== RUN ") { // new test cur = strings.TrimSpace(line[8:]) tests = append(tests, &Test{ Name: cur, Result: FAIL, Output: make([]string, 0), }) // clear the current build package, so output lines won't be added to that build capturedPackage = "" seenSummary = false } else if matches := regexBenchmark.FindStringSubmatch(line); len(matches) == 6 { bytes, _ := strconv.Atoi(matches[4]) allocs, _ := strconv.Atoi(matches[5]) benchmarks = append(benchmarks, &Benchmark{ Name: matches[1], Duration: parseNanoseconds(matches[3]), Bytes: bytes, Allocs: allocs, }) } else if strings.HasPrefix(line, "=== PAUSE ") { continue } else if strings.HasPrefix(line, "=== CONT ") { cur = strings.TrimSpace(line[8:]) continue } else if matches := regexResult.FindStringSubmatch(line); len(matches) == 6 { if matches[5] != "" { coveragePct = matches[5] } if strings.HasSuffix(matches[4], "failed]") { // the build of the package failed, inject a dummy test into the package // which indicate about the failure and contain the failure description. tests = append(tests, &Test{ Name: matches[4], Result: FAIL, Output: packageCaptures[matches[2]], }) } else if matches[1] == "FAIL" && len(tests) == 0 && len(buffers[cur]) > 0 { // This package didn't have any tests, but it failed with some // output. Create a dummy test with the output. tests = append(tests, &Test{ Name: "Failure", Result: FAIL, Output: buffers[cur], }) buffers[cur] = buffers[cur][0:0] } // all tests in this package are finished report.Packages = append(report.Packages, Package{ Name: matches[2], Duration: parseSeconds(matches[3]), Tests: tests, Benchmarks: benchmarks, CoveragePct: coveragePct, Time: int(parseSeconds(matches[3]) / time.Millisecond), // deprecated }) buffers[cur] = buffers[cur][0:0] tests = make([]*Test, 0) benchmarks = make([]*Benchmark, 0) coveragePct = "" cur = "" testsTime = 0 } else if matches := regexStatus.FindStringSubmatch(line); len(matches) == 4 { cur = matches[2] test := findTest(tests, cur) if test == nil { continue } // test status if matches[1] == "PASS" { test.Result = PASS } else if matches[1] == "SKIP" { test.Result = SKIP } else { test.Result = FAIL } if matches := regexIndent.FindStringSubmatch(line); len(matches) == 2 { test.SubtestIndent = matches[1] } test.Output = buffers[cur] test.Name = matches[2] test.Duration = parseSeconds(matches[3]) testsTime += test.Duration test.Time = int(test.Duration / time.Millisecond) // deprecated } else if matches := regexCoverage.FindStringSubmatch(line); len(matches) == 2 { coveragePct = matches[1] } else if matches := regexOutput.FindStringSubmatch(line); capturedPackage == "" && len(matches) == 3 { // Sub-tests start with one or more series of 4-space indents, followed by a hard tab, // followed by the test output // Top-level tests start with a hard tab. test := findTest(tests, cur) if test == nil { continue } test.Output = append(test.Output, matches[2]) } else if strings.HasPrefix(line, "# ") { // indicates a capture of build output of a package. set the current build package. capturedPackage = line[2:] } else if capturedPackage != "" { // current line is build failure capture for the current built package packageCaptures[capturedPackage] = append(packageCaptures[capturedPackage], line) } else if regexSummary.MatchString(line) { // don't store any output after the summary seenSummary = true } else if !seenSummary { // buffer anything else that we didn't recognize buffers[cur] = append(buffers[cur], line) // if we have a current test, also append to its output test := findTest(tests, cur) if test != nil { if strings.HasPrefix(line, test.SubtestIndent+" ") { test.Output = append(test.Output, strings.TrimPrefix(line, test.SubtestIndent+" ")) } } } } if len(tests) > 0 { // no result line found report.Packages = append(report.Packages, Package{ Name: pkgName, Duration: testsTime, Time: int(testsTime / time.Millisecond), Tests: tests, Benchmarks: benchmarks, CoveragePct: coveragePct, }) } return report, nil }
https://github.com/mrd0ll4r/tbotapi/blob/edc257282178bb5cebbfcc41260ec04c1ec7ac19/api.go#L93-L137
func NewWithWebhook(apiKey, webhookURL, certificate string) (*TelegramBotAPI, http.HandlerFunc, error) { toReturn := TelegramBotAPI{ Updates: make(chan BotUpdate), baseURIs: createEndpoints(fmt.Sprintf(apiBaseURI, apiKey)), closed: make(chan struct{}), c: newClient(fmt.Sprintf(apiBaseURI, apiKey)), updateC: newClient(fmt.Sprintf(apiBaseURI, apiKey)), } user, err := toReturn.GetMe() if err != nil { return nil, nil, err } toReturn.ID = user.User.ID toReturn.Name = user.User.FirstName toReturn.Username = *user.User.Username file, err := os.Open(certificate) if err != nil { return nil, nil, err } err = toReturn.setWebhook(webhookURL, certificate, file) if err != nil { return nil, nil, err } updateFunc := func(w http.ResponseWriter, r *http.Request) { bytes, err := ioutil.ReadAll(r.Body) if err != nil { toReturn.Updates <- BotUpdate{err: err} return } update := &Update{} err = json.Unmarshal(bytes, update) if err != nil { toReturn.Updates <- BotUpdate{err: err} return } toReturn.Updates <- BotUpdate{update: *update} } return &toReturn, updateFunc, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/storage.go#L142-L146
func (ms *MemoryStorage) LastIndex() (uint64, error) { ms.Lock() defer ms.Unlock() return ms.lastIndex(), nil }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/proto/fileinfo.go#L98-L113
func buildProtoRegexp() *regexp.Regexp { hexEscape := `\\[xX][0-9a-fA-f]{2}` octEscape := `\\[0-7]{3}` charEscape := `\\[abfnrtv'"\\]` charValue := strings.Join([]string{hexEscape, octEscape, charEscape, "[^\x00\\'\\\"\\\\]"}, "|") strLit := `'(?:` + charValue + `|")*'|"(?:` + charValue + `|')*"` ident := `[A-Za-z][A-Za-z0-9_]*` fullIdent := ident + `(?:\.` + ident + `)*` importStmt := `\bimport\s*(?:public|weak)?\s*(?P<import>` + strLit + `)\s*;` packageStmt := `\bpackage\s*(?P<package>` + fullIdent + `)\s*;` optionStmt := `\boption\s*(?P<optkey>` + fullIdent + `)\s*=\s*(?P<optval>` + strLit + `)\s*;` serviceStmt := `(?P<service>service)` comment := `//[^\n]*` protoReSrc := strings.Join([]string{importStmt, packageStmt, optionStmt, serviceStmt, comment}, "|") return regexp.MustCompile(protoReSrc) }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcec2manager/tcec2manager.go#L62-L68
func New(credentials *tcclient.Credentials) *EC2Manager { return &EC2Manager{ Credentials: credentials, BaseURL: DefaultBaseURL, Authenticate: credentials != nil, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/easyjson.go#L71-L75
func (v TakeResponseBodyAsStreamReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoFetch(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/docker_schema1.go#L309-L315
func (m *Schema1) ImageID(diffIDs []digest.Digest) (string, error) { image, err := m.ToSchema2Config(diffIDs) if err != nil { return "", err } return digest.FromBytes(image).Hex(), nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/resources_config_crd.go#L124-L130
func (in *ResourcesConfigCollection) GetItems() []Object { var items []Object for _, i := range in.Items { items = append(items, i) } return items }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/docker_schema1.go#L170-L202
func (m *Schema1) fixManifestLayers() error { // m.initialize() has verified that len(m.FSLayers) == len(m.History) for _, compat := range m.ExtractedV1Compatibility { if err := validateV1ID(compat.ID); err != nil { return err } } if m.ExtractedV1Compatibility[len(m.ExtractedV1Compatibility)-1].Parent != "" { return errors.New("Invalid parent ID in the base layer of the image") } // check general duplicates to error instead of a deadlock idmap := make(map[string]struct{}) var lastID string for _, img := range m.ExtractedV1Compatibility { // skip IDs that appear after each other, we handle those later if _, exists := idmap[img.ID]; img.ID != lastID && exists { return errors.Errorf("ID %+v appears multiple times in manifest", img.ID) } lastID = img.ID idmap[lastID] = struct{}{} } // backwards loop so that we keep the remaining indexes after removing items for i := len(m.ExtractedV1Compatibility) - 2; i >= 0; i-- { if m.ExtractedV1Compatibility[i].ID == m.ExtractedV1Compatibility[i+1].ID { // repeated ID. remove and continue m.FSLayers = append(m.FSLayers[:i], m.FSLayers[i+1:]...) m.History = append(m.History[:i], m.History[i+1:]...) m.ExtractedV1Compatibility = append(m.ExtractedV1Compatibility[:i], m.ExtractedV1Compatibility[i+1:]...) } else if m.ExtractedV1Compatibility[i].Parent != m.ExtractedV1Compatibility[i+1].ID { return errors.Errorf("Invalid parent ID. Expected %v, got %v", m.ExtractedV1Compatibility[i+1].ID, m.ExtractedV1Compatibility[i].Parent) } } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_cluster.go#L97-L109
func (r *ProtocolLXD) GetClusterMember(name string) (*api.ClusterMember, string, error) { if !r.HasExtension("clustering") { return nil, "", fmt.Errorf("The server is missing the required \"clustering\" API extension") } member := api.ClusterMember{} etag, err := r.queryStruct("GET", fmt.Sprintf("/cluster/members/%s", name), nil, "", &member) if err != nil { return nil, "", err } return &member, etag, nil }
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/smtp/server.go#L36-L48
func NewSMTP(filename string, environment string) (s *SMTP, err error) { conf, err := GetSMTP(filename, environment) if err != nil { return } auth := smtp.PlainAuth("", conf.Auth.User, conf.Auth.Password, conf.Host) f := smtp.SendMail if conf.SSL { f = SendMailSSL } s = &SMTP{auth: auth, send: f, addr: fmt.Sprintf("%s:%d", conf.Host, conf.Port)} return }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_volumes.go#L325-L337
func (c *Cluster) StorageVolumeMoveToLVMThinPoolNameKey() error { err := exec(c.db, "UPDATE storage_pools_config SET key='lvm.thinpool_name' WHERE key='volume.lvm.thinpool_name';") if err != nil { return err } err = exec(c.db, "DELETE FROM storage_volumes_config WHERE key='lvm.thinpool_name';") if err != nil { return err } return nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L364-L369
func refersTo(n ast.Node, x *ast.Ident) bool { id, ok := n.(*ast.Ident) // The test of id.Name == x.Name handles top-level unresolved // identifiers, which all have Obj == nil. return ok && id.Obj == x.Obj && id.Name == x.Name }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L385-L392
func FileSequence_FrameRangePadded(id FileSeqId) *C.char { fs, ok := sFileSeqs.Get(id) // caller must free string if !ok { return C.CString("") } return C.CString(fs.FrameRangePadded()) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L269-L271
func (p *SetDeviceMetricsOverrideParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetDeviceMetricsOverride, p, nil) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/platform.go#L182-L227
func (s *platformService) Rollback(opts appTypes.PlatformOptions) error { if opts.Name == "" { return appTypes.ErrPlatformNameMissing } if opts.ImageName == "" { return appTypes.ErrPlatformImageMissing } _, err := s.FindByName(opts.Name) if err != nil { return err } image, err := servicemanager.PlatformImage.FindImage(opts.Name, opts.ImageName) if err != nil { return err } if image == "" { return fmt.Errorf("Image %s not found in platform %q", opts.ImageName, opts.Name) } opts.Data = []byte("FROM " + image) opts.ImageName, err = servicemanager.PlatformImage.NewImage(opts.Name) if err != nil { return err } err = builder.PlatformUpdate(opts) if err != nil { return err } err = servicemanager.PlatformImage.AppendImage(opts.Name, opts.ImageName) if err != nil { return err } conn, err := db.Conn() if err != nil { return err } defer conn.Close() var apps []App err = conn.Apps().Find(bson.M{"framework": opts.Name}).All(&apps) if err != nil { return err } for _, app := range apps { app.SetUpdatePlatform(true) } return nil }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/docker_schema1.go#L234-L306
func (m *Schema1) ToSchema2Config(diffIDs []digest.Digest) ([]byte, error) { // Convert the schema 1 compat info into a schema 2 config, constructing some of the fields // that aren't directly comparable using info from the manifest. if len(m.History) == 0 { return nil, errors.New("image has no layers") } s1 := Schema2V1Image{} config := []byte(m.History[0].V1Compatibility) err := json.Unmarshal(config, &s1) if err != nil { return nil, errors.Wrapf(err, "error decoding configuration") } // Images created with versions prior to 1.8.3 require us to re-encode the encoded object, // adding some fields that aren't "omitempty". if s1.DockerVersion != "" && versions.LessThan(s1.DockerVersion, "1.8.3") { config, err = json.Marshal(&s1) if err != nil { return nil, errors.Wrapf(err, "error re-encoding compat image config %#v", s1) } } // Build the history. convertedHistory := []Schema2History{} for _, compat := range m.ExtractedV1Compatibility { hitem := Schema2History{ Created: compat.Created, CreatedBy: strings.Join(compat.ContainerConfig.Cmd, " "), Author: compat.Author, Comment: compat.Comment, EmptyLayer: compat.ThrowAway, } convertedHistory = append([]Schema2History{hitem}, convertedHistory...) } // Build the rootfs information. We need the decompressed sums that we've been // calculating to fill in the DiffIDs. It's expected (but not enforced by us) // that the number of diffIDs corresponds to the number of non-EmptyLayer // entries in the history. rootFS := &Schema2RootFS{ Type: "layers", DiffIDs: diffIDs, } // And now for some raw manipulation. raw := make(map[string]*json.RawMessage) err = json.Unmarshal(config, &raw) if err != nil { return nil, errors.Wrapf(err, "error re-decoding compat image config %#v", s1) } // Drop some fields. delete(raw, "id") delete(raw, "parent") delete(raw, "parent_id") delete(raw, "layer_id") delete(raw, "throwaway") delete(raw, "Size") // Add the history and rootfs information. rootfs, err := json.Marshal(rootFS) if err != nil { return nil, errors.Errorf("error encoding rootfs information %#v: %v", rootFS, err) } rawRootfs := json.RawMessage(rootfs) raw["rootfs"] = &rawRootfs history, err := json.Marshal(convertedHistory) if err != nil { return nil, errors.Errorf("error encoding history information %#v: %v", convertedHistory, err) } rawHistory := json.RawMessage(history) raw["history"] = &rawHistory // Encode the result. config, err = json.Marshal(raw) if err != nil { return nil, errors.Errorf("error re-encoding compat image config %#v: %v", s1, err) } return config, nil }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/imgproc.go#L167-L173
func MinAreaRect(points unsafe.Pointer) Box2D { box := C.cvMinAreaRect2(points, nil) center := Point2D32f{float32(box.center.x), float32(box.center.y)} size := Size2D32f{float32(box.size.width), float32(box.size.height)} angle := float32(box.angle) return Box2D{center, size, angle} }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/file-server/server.go#L29-L42
func New(root, dir string, options *Options) *Server { if options == nil { options = &Options{} } return &Server{ Options: *options, root: root, dir: dir, hashes: map[string]string{}, mu: &sync.RWMutex{}, } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/maintenance/aws-janitor/resources/set.go#L132-L150
func (s *Set) MarkComplete() int { var gone []string for key := range s.firstSeen { if !s.marked[key] { gone = append(gone, key) } } for _, key := range gone { klog.V(1).Infof("%s: deleted since last run", key) delete(s.firstSeen, key) } if len(s.swept) > 0 { klog.Errorf("%d resources swept: %v", len(s.swept), s.swept) } return len(s.swept) }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/http.go#L298-L320
func getExtHeader(credentials *Credentials) (header string, err error) { ext := &ExtHeader{} if credentials.Certificate != "" { certObj := new(Certificate) err = json.Unmarshal([]byte(credentials.Certificate), certObj) if err != nil { return "", err } ext.Certificate = certObj } if credentials.AuthorizedScopes != nil { ext.AuthorizedScopes = &credentials.AuthorizedScopes } extJSON, err := json.Marshal(ext) if err != nil { return "", err } if string(extJSON) != "{}" { return base64.StdEncoding.EncodeToString(extJSON), nil } return "", nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L621-L625
func (v *RequestDataParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb5(&r, v) return r.Error() }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L259-L310
func (cdc *Codec) UnmarshalBinaryLengthPrefixedReader(r io.Reader, ptr interface{}, maxSize int64) (n int64, err error) { if maxSize < 0 { panic("maxSize cannot be negative.") } // Read byte-length prefix. var l int64 var buf [binary.MaxVarintLen64]byte for i := 0; i < len(buf); i++ { _, err = r.Read(buf[i : i+1]) if err != nil { return } n += 1 if buf[i]&0x80 == 0 { break } if n >= maxSize { err = fmt.Errorf("Read overflow, maxSize is %v but uvarint(length-prefix) is itself greater than maxSize.", maxSize) } } u64, _ := binary.Uvarint(buf[:]) if err != nil { return } if maxSize > 0 { if uint64(maxSize) < u64 { err = fmt.Errorf("Read overflow, maxSize is %v but this amino binary object is %v bytes.", maxSize, u64) return } if (maxSize - n) < int64(u64) { err = fmt.Errorf("Read overflow, maxSize is %v but this length-prefixed amino binary object is %v+%v bytes.", maxSize, n, u64) return } } l = int64(u64) if l < 0 { err = fmt.Errorf("Read overflow, this implementation can't read this because, why would anyone have this much data? Hello from 2018.") } // Read that many bytes. var bz = make([]byte, l, l) _, err = io.ReadFull(r, bz) if err != nil { return } n += l // Decode. err = cdc.UnmarshalBinaryBare(bz, ptr) return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/security/types.go#L67-L69
func (t *MixedContentType) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/hook/server.go#L54-L72
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { eventType, eventGUID, payload, ok, resp := github.ValidateWebhook(w, r, s.TokenGenerator()) if counter, err := s.Metrics.WebhookCounter.GetMetricWithLabelValues(strconv.Itoa(resp)); err != nil { logrus.WithFields(logrus.Fields{ "status-code": resp, }).WithError(err).Error("Failed to get metric for reporting webhook status code") } else { counter.Inc() } if !ok { return } fmt.Fprint(w, "Event received. Have a nice day.") if err := s.demuxEvent(eventType, eventGUID, payload, r.Header); err != nil { logrus.WithError(err).Error("Error parsing event.") } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L4979-L4981
func (api *API) IpAddressBindingLocator(href string) *IpAddressBindingLocator { return &IpAddressBindingLocator{Href(href), api} }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/docker/config/config.go#L89-L105
func RemoveAuthentication(sys *types.SystemContext, registry string) error { return modifyJSON(sys, func(auths *dockerConfigFile) (bool, error) { // First try cred helpers. if ch, exists := auths.CredHelpers[registry]; exists { return false, deleteAuthFromCredHelper(ch, registry) } if _, ok := auths.AuthConfigs[registry]; ok { delete(auths.AuthConfigs, registry) } else if _, ok := auths.AuthConfigs[normalizeRegistry(registry)]; ok { delete(auths.AuthConfigs, normalizeRegistry(registry)) } else { return false, ErrNotLoggedIn } return true, nil }) }
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/handler.go#L28-L30
func (h *StreamHandler) Write(b []byte) (n int, err error) { return h.w.Write(b) }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L360-L393
func (s *FileSequence) Frame(frame interface{}) (string, error) { var zframe string var isInt bool if s.frameSet != nil { switch t := frame.(type) { case int: var i int = t zframe = zfillInt(i, s.zfill) isInt = true case string: zframe = t case []byte: zframe = string(t) case fmt.Stringer: zframe = t.String() default: return zframe, fmt.Errorf("%v is not a valid int/string type", t) } // Only try and zfill the string if it was an int format if !isInt { if _, err := strconv.Atoi(zframe); err == nil { zframe = zfillString(zframe, s.zfill) } } } var buf strings.Builder buf.WriteString(s.dir) buf.WriteString(s.basename) buf.WriteString(zframe) buf.WriteString(s.ext) return buf.String(), nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L182-L239
func (c *Cluster) ProfileConfig(project, name string) (map[string]string, error) { err := c.Transaction(func(tx *ClusterTx) error { enabled, err := tx.ProjectHasProfiles(project) if err != nil { return errors.Wrap(err, "Check if project has profiles") } if !enabled { project = "default" } return nil }) if err != nil { return nil, err } var key, value string query := ` SELECT key, value FROM profiles_config JOIN profiles ON profiles_config.profile_id=profiles.id JOIN projects ON projects.id = profiles.project_id WHERE projects.name=? AND profiles.name=?` inargs := []interface{}{project, name} outfmt := []interface{}{key, value} results, err := queryScan(c.db, query, inargs, outfmt) if err != nil { return nil, errors.Wrapf(err, "Failed to get profile '%s'", name) } if len(results) == 0 { /* * If we didn't get any rows here, let's check to make sure the * profile really exists; if it doesn't, let's send back a 404. */ query := "SELECT id FROM profiles WHERE name=?" var id int results, err := queryScan(c.db, query, []interface{}{name}, []interface{}{id}) if err != nil { return nil, err } if len(results) == 0 { return nil, ErrNoSuchObject } } config := map[string]string{} for _, r := range results { key = r[0].(string) value = r[1].(string) config[key] = value } return config, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L105-L107
func (p *CrashParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandCrash, nil, nil) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/auditail/main.go#L149-L155
func fail(format string, v ...interface{}) { if !strings.HasSuffix(format, "\n") { format += "\n" } fmt.Println(fmt.Sprintf(format, v...)) os.Exit(1) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/types.go#L228-L230
func (t *ValueNativeSourceType) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/golint/golint.go#L331-L368
func AddedLines(patch string) (map[int]int, error) { result := make(map[int]int) if patch == "" { return result, nil } lines := strings.Split(patch, "\n") for i := 0; i < len(lines); i++ { // dodge the "\ No newline at end of file" line if lines[i] == "\\ No newline at end of file" { continue } _, oldLen, newLine, newLen, err := parseHunkLine(lines[i]) if err != nil { return nil, fmt.Errorf("couldn't parse hunk on line %d in patch %s: %v", i, patch, err) } oldAdd := 0 newAdd := 0 for oldAdd < oldLen || newAdd < newLen { i++ if i >= len(lines) { return nil, fmt.Errorf("invalid patch: %s", patch) } switch lines[i][0] { case ' ': oldAdd++ newAdd++ case '-': oldAdd++ case '+': result[newLine+newAdd] = i newAdd++ default: return nil, fmt.Errorf("bad prefix on line %d in patch %s", i, patch) } } } return result, nil }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L299-L301
func (m *Message) AttachReader(name string, r io.Reader, settings ...FileSetting) { m.attachments = m.appendFile(m.attachments, fileFromReader(name, r), settings) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L415-L419
func (v RareStringData) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomsnapshot1(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L5406-L5410
func (v EventWebSocketFrameSent) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork42(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/mex.go#L159-L191
func (mex *messageExchange) recvPeerFrame() (*Frame, error) { // We have to check frames/errors in a very specific order here: // 1. Timeouts/cancellation (mex.ctx errors) // 2. Any pending frames (non-blocking select over mex.recvCh) // 3. Other mex errors (mex.errCh) // Which is why we check the context error only (instead of mex.checkError)e // In the mex.errCh case, we do a non-blocking read from recvCh to prioritize it. if err := mex.ctx.Err(); err != nil { return nil, GetContextError(err) } select { case frame := <-mex.recvCh: if err := mex.checkFrame(frame); err != nil { return nil, err } return frame, nil case <-mex.ctx.Done(): return nil, GetContextError(mex.ctx.Err()) case <-mex.errCh.c: // Select will randomly choose a case, but we want to prioritize // receiving a frame over errCh. Try a non-blocking read. select { case frame := <-mex.recvCh: if err := mex.checkFrame(frame); err != nil { return nil, err } return frame, nil default: } return nil, mex.errCh.err } }
https://github.com/kpango/glg/blob/68d2670cb2dbff047331daad841149a82ac37796/glg.go#L1003-L1005
func (g *Glg) Fail(val ...interface{}) error { return g.out(FAIL, blankFormat(len(val)), val...) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/mechanism_openpgp.go#L106-L108
func (m *openpgpSigningMechanism) Sign(input []byte, keyIdentity string) ([]byte, error) { return nil, SigningNotSupportedError("signing is not supported in github.com/containers/image built with the containers_image_openpgp build tag") }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/fileutil/sync_darwin.go#L28-L34
func Fsync(f *os.File) error { _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, f.Fd(), uintptr(syscall.F_FULLFSYNC), uintptr(0)) if errno == 0 { return nil } return errno }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/app/app.go#L1294-L1303
func (app *App) Run(cmd string, w io.Writer, args provision.RunArgs) error { if !args.Isolated && !app.available() { return errors.New("App must be available to run non-isolated commands") } app.Log(fmt.Sprintf("running '%s'", cmd), "tsuru", "api") logWriter := LogWriter{App: app, Source: "app-run"} logWriter.Async() defer logWriter.Close() return app.run(cmd, io.MultiWriter(w, &logWriter), args) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L173-L176
func (p EvaluateOnCallFrameParams) WithThrowOnSideEffect(throwOnSideEffect bool) *EvaluateOnCallFrameParams { p.ThrowOnSideEffect = throwOnSideEffect return &p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L765-L768
func (p PrintToPDFParams) WithHeaderTemplate(headerTemplate string) *PrintToPDFParams { p.HeaderTemplate = headerTemplate return &p }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6573-L6581
func (u StellarMessage) MustPeers() []PeerAddress { val, ok := u.GetPeers() if !ok { panic("arm Peers is not set") } return val }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/thrift-gen/wrap.go#L201-L207
func (m *Method) ArgList() string { args := []string{"ctx " + contextType()} for _, arg := range m.Arguments() { args = append(args, arg.Declaration()) } return strings.Join(args, ", ") }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_dest.go#L123-L181
func (d *ociImageDestination) PutBlob(ctx context.Context, stream io.Reader, inputInfo types.BlobInfo, cache types.BlobInfoCache, isConfig bool) (types.BlobInfo, error) { blobFile, err := ioutil.TempFile(d.ref.dir, "oci-put-blob") if err != nil { return types.BlobInfo{}, err } succeeded := false explicitClosed := false defer func() { if !explicitClosed { blobFile.Close() } if !succeeded { os.Remove(blobFile.Name()) } }() digester := digest.Canonical.Digester() tee := io.TeeReader(stream, digester.Hash()) // TODO: This can take quite some time, and should ideally be cancellable using ctx.Done(). size, err := io.Copy(blobFile, tee) if err != nil { return types.BlobInfo{}, err } computedDigest := digester.Digest() if inputInfo.Size != -1 && size != inputInfo.Size { return types.BlobInfo{}, errors.Errorf("Size mismatch when copying %s, expected %d, got %d", computedDigest, inputInfo.Size, size) } if err := blobFile.Sync(); err != nil { return types.BlobInfo{}, err } // On POSIX systems, blobFile was created with mode 0600, so we need to make it readable. // On Windows, the “permissions of newly created files” argument to syscall.Open is // ignored and the file is already readable; besides, blobFile.Chmod, i.e. syscall.Fchmod, // always fails on Windows. if runtime.GOOS != "windows" { if err := blobFile.Chmod(0644); err != nil { return types.BlobInfo{}, err } } blobPath, err := d.ref.blobPath(computedDigest, d.sharedBlobDir) if err != nil { return types.BlobInfo{}, err } if err := ensureParentDirectoryExists(blobPath); err != nil { return types.BlobInfo{}, err } // need to explicitly close the file, since a rename won't otherwise not work on Windows blobFile.Close() explicitClosed = true if err := os.Rename(blobFile.Name(), blobPath); err != nil { return types.BlobInfo{}, err } succeeded = true return types.BlobInfo{Digest: computedDigest, Size: size}, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/git/git.go#L27-L41
func DiscoverRepositoryPath(dir string) (string, error) { _, err := os.Stat(dir) if os.IsNotExist(err) { return "", ErrRepositoryNotFound } dir = filepath.Join(dir, ".git") for dir != "/.git" { fi, err := os.Stat(dir) if err == nil && fi.IsDir() { return dir, nil } dir = filepath.Join(dir, "..", "..", ".git") } return "", ErrRepositoryNotFound }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/transform.go#L98-L138
func (config *transformConfig) run(plugin plugins.Plugin) error { if err := config.CheckRootFlags(); err != nil { return err } mysqldb, err := config.MySQLConfig.CreateDatabase() if err != nil { return err } influxdb, err := config.InfluxConfig.CreateDatabase( map[string]string{"repository": config.repository}, config.metricName) if err != nil { return err } fetcher := NewFetcher(config.repository) // Plugins constantly wait for new issues/events/comments go Dispatch(plugin, influxdb, fetcher.IssuesChannel, fetcher.EventsCommentsChannel) ticker := time.Tick(time.Hour / time.Duration(config.frequency)) for { // Fetch new events from MySQL, push it to plugins if err := fetcher.Fetch(mysqldb); err != nil { return err } if err := influxdb.PushBatchPoints(); err != nil { return err } if config.once { break } <-ticker } return nil }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/frameset.go#L198-L200
func (s *FrameSet) FrameRangePadded(pad int) string { return PadFrameRange(s.frange, pad) }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/deploymentmanifest.go#L24-L32
func NewDeploymentManifestFromFile(f *os.File) *DeploymentManifest { var b []byte fi, _ := f.Stat() if fi.Size() > 0 { b, _ = ioutil.ReadAll(f) } return NewDeploymentManifest(b) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/issue-creator/sources/triage-filer.go#L62-L78
func (f *TriageFiler) Issues(c *creator.IssueCreator) ([]creator.Issue, error) { f.creator = c rawjson, err := ReadHTTP(clusterDataURL) if err != nil { return nil, err } clusters, err := f.loadClusters(rawjson) if err != nil { return nil, err } topclusters := topClusters(clusters, f.topClustersCount) issues := make([]creator.Issue, 0, len(topclusters)) for _, clust := range topclusters { issues = append(issues, clust) } return issues, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/label_sync/main.go#L408-L411
func change(repo string, label Label) Update { logrus.WithField("repo", repo).WithField("label", label.Name).WithField("color", label.Color).Info("change") return Update{Why: "change", Current: &label, Wanted: &label, repo: repo} }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L410-L412
func (cd Codec) SetMulti(c context.Context, items []*Item) error { return cd.set(c, items, pb.MemcacheSetRequest_SET) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L358-L365
func (d *Destination) sendSymlink(path string, target string) error { hdr, err := tar.FileInfoHeader(&tarFI{path: path, size: 0, isSymlink: true}, target) if err != nil { return nil } logrus.Debugf("Sending as tar link %s -> %s", path, target) return d.tar.WriteHeader(hdr) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift-copies.go#L321-L332
func (config *directClientConfig) getContext() clientcmdContext { contexts := config.config.Contexts contextName := config.getContextName() var mergedContext clientcmdContext if configContext, exists := contexts[contextName]; exists { mergo.Merge(&mergedContext, configContext) } // REMOVED: overrides support return mergedContext }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/raft.go#L273-L299
func (i *raftInstance) Shutdown() error { logger.Debug("Stop raft instance") // Invoke raft APIs asynchronously to allow for a timeout. timeout := 10 * time.Second errCh := make(chan error) timer := time.After(timeout) go func() { errCh <- i.raft.Shutdown().Error() }() select { case err := <-errCh: if err != nil { return errors.Wrap(err, "failed to shutdown raft") } case <-timer: logger.Debug("Timeout waiting for raft to shutdown") return fmt.Errorf("raft did not shutdown within %s", timeout) } err := i.logs.Close() if err != nil { return errors.Wrap(err, "failed to close boltdb logs store") } return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/concurrency/stm.go#L84-L86
func WithPrefetch(keys ...string) stmOption { return func(so *stmOptions) { so.prefetch = append(so.prefetch, keys...) } }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/loader/http.go#L60-L83
func NewHTTPSource(r *http.Response) (*HTTPSource, error) { body, err := ioutil.ReadAll(r.Body) if err != nil { return nil, err } s := &HTTPSource{ bytes.NewBuffer(body), time.Time{}, } if lastmodStr := r.Header.Get("Last-Modified"); lastmodStr != "" { t, err := time.Parse(http.TimeFormat, lastmodStr) if err != nil { fmt.Printf("failed to parse: %s\n", err) t = time.Now() } s.LastModifiedTime = t } else { s.LastModifiedTime = time.Now() } return s, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L1211-L1224
func WriteSecret(encoder Encoder, data map[string][]byte, opts *AssetOpts) error { if opts.DashOnly { return nil } secret := &v1.Secret{ TypeMeta: metav1.TypeMeta{ Kind: "Secret", APIVersion: "v1", }, ObjectMeta: objectMeta(client.StorageSecretName, labels(client.StorageSecretName), nil, opts.Namespace), Data: data, } return encoder.Encode(secret) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/pretty/pretty.go#L309-L311
func PrintFile(w io.Writer, file *pfsclient.File) { fmt.Fprintf(w, " %s\t%s\t%s\t\n", file.Commit.Repo.Name, file.Commit.ID, file.Path) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L3066-L3070
func (v GetStackTraceParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDebugger32(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/config.go#L202-L208
func ConfigGetInt64(cluster *db.Cluster, key string) (int64, error) { config, err := configGet(cluster) if err != nil { return 0, err } return config.m.GetInt64(key), nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/repoowners/repoowners.go#L307-L320
func (a RepoAliases) ExpandAliases(logins sets.String) sets.String { if a == nil { return logins } // Make logins a copy of the original set to avoid modifying the original. logins = logins.Union(nil) for _, login := range logins.List() { if expanded := a.ExpandAlias(login); len(expanded) > 0 { logins.Delete(login) logins = logins.Union(expanded) } } return logins }
https://github.com/kelseyhightower/envconfig/blob/dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1/usage.go#L58-L107
func toTypeDescription(t reflect.Type) string { switch t.Kind() { case reflect.Array, reflect.Slice: return fmt.Sprintf("Comma-separated list of %s", toTypeDescription(t.Elem())) case reflect.Map: return fmt.Sprintf( "Comma-separated list of %s:%s pairs", toTypeDescription(t.Key()), toTypeDescription(t.Elem()), ) case reflect.Ptr: return toTypeDescription(t.Elem()) case reflect.Struct: if implementsInterface(t) && t.Name() != "" { return t.Name() } return "" case reflect.String: name := t.Name() if name != "" && name != "string" { return name } return "String" case reflect.Bool: name := t.Name() if name != "" && name != "bool" { return name } return "True or False" case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: name := t.Name() if name != "" && !strings.HasPrefix(name, "int") { return name } return "Integer" case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: name := t.Name() if name != "" && !strings.HasPrefix(name, "uint") { return name } return "Unsigned Integer" case reflect.Float32, reflect.Float64: name := t.Name() if name != "" && !strings.HasPrefix(name, "float") { return name } return "Float" } return fmt.Sprintf("%+v", t) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2255-L2259
func (v PushNodesByBackendIdsToFrontendParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom24(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/log/field.go#L117-L123
func Float64(key string, val float64) Field { return Field{ key: key, fieldType: float64Type, numericVal: int64(math.Float64bits(val)), } }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/apis/tsuru/v1/zz_generated.deepcopy.go#L106-L113
func (in *AppSpec) DeepCopy() *AppSpec { if in == nil { return nil } out := new(AppSpec) in.DeepCopyInto(out) return out }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/query.go#L138-L166
func (q *Query) Filter(filterStr string, value interface{}) *Query { q = q.clone() filterStr = strings.TrimSpace(filterStr) if len(filterStr) < 1 { q.err = errors.New("datastore: invalid filter: " + filterStr) return q } f := filter{ FieldName: strings.TrimRight(filterStr, " ><=!"), Value: value, } switch op := strings.TrimSpace(filterStr[len(f.FieldName):]); op { case "<=": f.Op = lessEq case ">=": f.Op = greaterEq case "<": f.Op = lessThan case ">": f.Op = greaterThan case "=": f.Op = equal default: q.err = fmt.Errorf("datastore: invalid operator %q in filter %q", op, filterStr) return q } q.filter = append(q.filter, f) return q }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/encoding/decode.go#L92-L196
func FromStringStringMap(tagName string, base interface{}, input map[string]string) (output interface{}, err error) { baseType := reflect.TypeOf(base) valType := baseType if baseType.Kind() == reflect.Ptr { valType = valType.Elem() } // If we get a pointer in, we'll return a pointer out valPtr := reflect.New(valType) val := valPtr.Elem() output = valPtr.Interface() defer func() { if err == nil && baseType.Kind() != reflect.Ptr { output = reflect.Indirect(reflect.ValueOf(output)).Interface() } }() for i := 0; i < valType.NumField(); i++ { field := valType.Field(i) if field.PkgPath != "" { continue } fieldName, opts := parseTag(field.Tag.Get(tagName)) squash, include := opts.Has("squash"), opts.Has("include") if !squash && (fieldName == "" || fieldName == "-") { continue } inputStr, fieldInInput := input[fieldName] fieldType := field.Type fieldKind := field.Type.Kind() isPointerField := fieldKind == reflect.Ptr if isPointerField { if inputStr == "null" { continue } fieldType = fieldType.Elem() fieldKind = fieldType.Kind() } var iface interface{} if (squash || include) && fieldKind == reflect.Struct { var subInput map[string]string if squash { subInput = input } else { subInput = make(map[string]string) for k, v := range input { if strings.HasPrefix(k, fieldName+".") { subInput[strings.TrimPrefix(k, fieldName+".")] = v } } if len(subInput) == 0 { continue } } subOutput, err := FromStringStringMap(tagName, val.Field(i).Interface(), subInput) if err != nil { return nil, err } val.Field(i).Set(reflect.ValueOf(subOutput)) continue } if !fieldInInput || inputStr == "" { continue } switch fieldKind { case reflect.Struct, reflect.Array, reflect.Interface, reflect.Slice, reflect.Map: iface, err = unmarshalToType(fieldType, inputStr) if err != nil { return nil, err } default: iface = decodeToType(fieldKind, inputStr) } if v, ok := iface.(time.Time); ok { iface = v.UTC() } fieldVal := reflect.ValueOf(iface).Convert(fieldType) if isPointerField { fieldValPtr := reflect.New(fieldType) fieldValPtr.Elem().Set(fieldVal) val.Field(i).Set(fieldValPtr) } else { val.Field(i).Set(fieldVal) } } return output, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L302-L306
func (v SnapshotCommandLogParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoLayertree2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/archive/transport.go#L136-L142
func (ref archiveReference) NewImage(ctx context.Context, sys *types.SystemContext) (types.ImageCloser, error) { src, err := newImageSource(ctx, ref) if err != nil { return nil, err } return ctrImage.FromSource(ctx, sys, src) }