_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/response.go#L520-L535
func SmartError(err error) Response { switch errors.Cause(err) { case nil: return EmptySyncResponse case os.ErrNotExist, sql.ErrNoRows, db.ErrNoSuchObject: return NotFound(nil) case os.ErrPermission: return Forbidden(nil) case db.ErrAlreadyDefined, sqlite3.ErrConstraintUnique: return Conflict(nil) case dqlite.ErrNoAvailableLeader: return Unavailable(err) default: return InternalError(err) } }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/merge.go#L44-L80
func MergeRules(src, dst *Rule, mergeable map[string]bool, filename string) { if dst.ShouldKeep() { return } // Process attributes that are in dst but not in src. for key, dstAttr := range dst.attrs { if _, ok := src.attrs[key]; ok || !mergeable[key] || ShouldKeep(dstAttr) { continue } dstValue := dstAttr.RHS if mergedValue, err := mergeExprs(nil, dstValue); err != nil { start, end := dstValue.Span() log.Printf("%s:%d.%d-%d.%d: could not merge expression", filename, start.Line, start.LineRune, end.Line, end.LineRune) } else if mergedValue == nil { dst.DelAttr(key) } else { dst.SetAttr(key, mergedValue) } } // Merge attributes from src into dst. for key, srcAttr := range src.attrs { srcValue := srcAttr.RHS if dstAttr, ok := dst.attrs[key]; !ok { dst.SetAttr(key, srcValue) } else if mergeable[key] && !ShouldKeep(dstAttr) { dstValue := dstAttr.RHS if mergedValue, err := mergeExprs(srcValue, dstValue); err != nil { start, end := dstValue.Span() log.Printf("%s:%d.%d-%d.%d: could not merge expression", filename, start.Line, start.LineRune, end.Line, end.LineRune) } else { dst.SetAttr(key, mergedValue) } } } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L262-L266
func (v RequestDatabaseNamesReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoIndexeddb2(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L775-L779
func (v SignedExchangeSignature) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork5(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/pprof.go#L21-L27
func indexHandler(w http.ResponseWriter, r *http.Request, t auth.Token) error { if !permission.Check(t, permission.PermDebug) { return permission.ErrUnauthorized } pprof.Index(w, r) return nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/file/file.go#L19-L28
func DefaultBucketName(c context.Context) (string, error) { req := &aipb.GetDefaultGcsBucketNameRequest{} res := &aipb.GetDefaultGcsBucketNameResponse{} err := internal.Call(c, "app_identity_service", "GetDefaultGcsBucketName", req, res) if err != nil { return "", fmt.Errorf("file: no default bucket name returned in RPC response: %v", res) } return res.GetDefaultGcsBucketName(), nil }
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/clitable/table.go#L248-L255
func (t *Table) stringDash() string { s := "|" for i := 0; i < t.lineLength()-2; i++ { s += "-" } s += "|" return s }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/release/pivnetrelease.go#L16-L28
func LoadPivnetRelease(releaseRepo pull.Release, path string) (release *PivnetRelease, err error) { release = &PivnetRelease{} var localPath string localPath, err = releaseRepo.Pull(path) if err != nil { return } release = &PivnetRelease{ BoshRelease: make(map[string]*BoshRelease), } err = release.readPivnetRelease(localPath) return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/admission/admission.go#L59-L80
func readRequest(r io.Reader, contentType string) (*admissionapi.AdmissionRequest, error) { if contentType != contentTypeJSON { return nil, fmt.Errorf("Content-Type=%s, expected %s", contentType, contentTypeJSON) } // Can we read the body? if r == nil { return nil, fmt.Errorf("no body") } body, err := ioutil.ReadAll(r) if err != nil { return nil, fmt.Errorf("read body: %v", err) } // Can we convert the body into an AdmissionReview? var ar admissionapi.AdmissionReview deserializer := codecs.UniversalDeserializer() if _, _, err := deserializer.Decode(body, nil, &ar); err != nil { return nil, fmt.Errorf("decode body: %v", err) } return ar.Request, nil }
https://github.com/google/acme/blob/7c6dfc908d68ed254a16c126f6770f4d9d9352da/config.go#L93-L102
func writeConfig(uc *userConfig) error { b, err := json.MarshalIndent(uc, "", " ") if err != nil { return err } if err := os.MkdirAll(configDir, 0700); err != nil { return err } return ioutil.WriteFile(filepath.Join(configDir, accountFile), b, 0600) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pfs/pretty/pretty.go#L28-L34
func PrintRepoHeader(w io.Writer, printAuth bool) { if printAuth { fmt.Fprint(w, RepoAuthHeader) return } fmt.Fprint(w, RepoHeader) }
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/parsing.go#L304-L345
func readUntilFalse(stream *lexerStream, includeWhitespace bool, breakWhitespace bool, allowEscaping bool, condition func(rune) bool) (string, bool) { var tokenBuffer bytes.Buffer var character rune var conditioned bool conditioned = false for stream.canRead() { character = stream.readCharacter() // Use backslashes to escape anything if allowEscaping && character == '\\' { character = stream.readCharacter() tokenBuffer.WriteString(string(character)) continue } if unicode.IsSpace(character) { if breakWhitespace && tokenBuffer.Len() > 0 { conditioned = true break } if !includeWhitespace { continue } } if condition(character) { tokenBuffer.WriteString(string(character)) } else { conditioned = true stream.rewind(1) break } } return tokenBuffer.String(), conditioned }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/status.go#L97-L216
func requirementDiff(pr *PullRequest, q *config.TideQuery, cc contextChecker) (string, int) { const maxLabelChars = 50 var desc string var diff int // Drops labels if needed to fit the description text area, but keep at least 1. truncate := func(labels []string) []string { i := 1 chars := len(labels[0]) for ; i < len(labels); i++ { if chars+len(labels[i]) > maxLabelChars { break } chars += len(labels[i]) + 2 // ", " } return labels[:i] } // Weight incorrect branches with very high diff so that we select the query // for the correct branch. targetBranchBlacklisted := false for _, excludedBranch := range q.ExcludedBranches { if string(pr.BaseRef.Name) == excludedBranch { targetBranchBlacklisted = true break } } // if no whitelist is configured, the target is OK by default targetBranchWhitelisted := len(q.IncludedBranches) == 0 for _, includedBranch := range q.IncludedBranches { if string(pr.BaseRef.Name) == includedBranch { targetBranchWhitelisted = true break } } if targetBranchBlacklisted || !targetBranchWhitelisted { diff += 1000 if desc == "" { desc = fmt.Sprintf(" Merging to branch %s is forbidden.", pr.BaseRef.Name) } } // Weight incorrect milestone with relatively high diff so that we select the // query for the correct milestone (but choose favor query for correct branch). if q.Milestone != "" && (pr.Milestone == nil || string(pr.Milestone.Title) != q.Milestone) { diff += 100 if desc == "" { desc = fmt.Sprintf(" Must be in milestone %s.", q.Milestone) } } // Weight incorrect labels and statues with low (normal) diff values. var missingLabels []string for _, l1 := range q.Labels { var found bool for _, l2 := range pr.Labels.Nodes { if string(l2.Name) == l1 { found = true break } } if !found { missingLabels = append(missingLabels, l1) } } diff += len(missingLabels) if desc == "" && len(missingLabels) > 0 { sort.Strings(missingLabels) trunced := truncate(missingLabels) if len(trunced) == 1 { desc = fmt.Sprintf(" Needs %s label.", trunced[0]) } else { desc = fmt.Sprintf(" Needs %s labels.", strings.Join(trunced, ", ")) } } var presentLabels []string for _, l1 := range q.MissingLabels { for _, l2 := range pr.Labels.Nodes { if string(l2.Name) == l1 { presentLabels = append(presentLabels, l1) break } } } diff += len(presentLabels) if desc == "" && len(presentLabels) > 0 { sort.Strings(presentLabels) trunced := truncate(presentLabels) if len(trunced) == 1 { desc = fmt.Sprintf(" Should not have %s label.", trunced[0]) } else { desc = fmt.Sprintf(" Should not have %s labels.", strings.Join(trunced, ", ")) } } // fixing label issues takes precedence over status contexts var contexts []string for _, commit := range pr.Commits.Nodes { if commit.Commit.OID == pr.HeadRefOID { for _, ctx := range unsuccessfulContexts(commit.Commit.Status.Contexts, cc, logrus.New().WithFields(pr.logFields())) { contexts = append(contexts, string(ctx.Context)) } } } diff += len(contexts) if desc == "" && len(contexts) > 0 { sort.Strings(contexts) trunced := truncate(contexts) if len(trunced) == 1 { desc = fmt.Sprintf(" Job %s has not succeeded.", trunced[0]) } else { desc = fmt.Sprintf(" Jobs %s have not succeeded.", strings.Join(trunced, ", ")) } } // TODO(cjwagner): List reviews (states:[APPROVED], first: 1) as part of open // PR query. return desc, diff }
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/dependency/sqltypes/value.go#L215-L224
func (v Value) EncodeSQL(b BinWriter) { switch { case v.typ == Null: b.Write(nullstr) case v.IsQuoted(): encodeBytesSQL(v.val, b) default: b.Write(v.val) } }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L232-L235
func (win *Window) GetTrackbarPos(name string) (value, max int) { rv := C.cvGetTrackbarPos(win.trackbarName[name], win.name_c) return int(rv), win.trackbarMax[name] }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/time.go#L19-L26
func (t Time) MarshalJSON() ([]byte, error) { if y := time.Time(t).Year(); y < 0 || y >= 10000 { // RFC 3339 is clear that years are 4 digits exactly. // See golang.org/issue/4556#c15 for more discussion. return nil, errors.New("queue.Time.MarshalJSON: year outside of range [0,9999]") } return []byte(`"` + t.String() + `"`), nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L192-L203
func (d *Daemon) checkTrustedClient(r *http.Request) error { trusted, _, _, err := d.Authenticate(r) if !trusted || err != nil { if err != nil { return err } return fmt.Errorf("Not authorized") } return nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/errors.go#L207-L217
func GetSystemErrorCode(err error) SystemErrCode { if err == nil { return ErrCodeInvalid } if se, ok := err.(SystemError); ok { return se.Code() } return ErrCodeUnexpected }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5257-L5265
func (u BucketEntry) MustLiveEntry() LedgerEntry { val, ok := u.GetLiveEntry() if !ok { panic("arm LiveEntry is not set") } return val }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L201-L212
func (p *Page) Size(width, height int) error { window, err := p.session.GetWindow() if err != nil { return fmt.Errorf("failed to retrieve window: %s", err) } if err := window.SetSize(width, height); err != nil { return fmt.Errorf("failed to set window size: %s", err) } return nil }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/put_apps_app_parameters.go#L82-L85
func (o *PutAppsAppParams) WithContext(ctx context.Context) *PutAppsAppParams { o.SetContext(ctx) return o }
https://github.com/fgrid/uuid/blob/6f72a2d331c927473b9b19f590d43ccb5018c844/v4.go#L6-L14
func NewV4() *UUID { buf := make([]byte, 16) rand.Read(buf) buf[6] = (buf[6] & 0x0f) | 0x40 var uuid UUID copy(uuid[:], buf[:]) uuid.variantRFC4122() return &uuid }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L820-L869
func (db *DB) handleFlushTask(ft flushTask) error { if !ft.mt.Empty() { // Store badger head even if vptr is zero, need it for readTs db.opt.Debugf("Storing value log head: %+v\n", ft.vptr) db.elog.Printf("Storing offset: %+v\n", ft.vptr) offset := make([]byte, vptrSize) ft.vptr.Encode(offset) // Pick the max commit ts, so in case of crash, our read ts would be higher than all the // commits. headTs := y.KeyWithTs(head, db.orc.nextTs()) ft.mt.Put(headTs, y.ValueStruct{Value: offset}) // Also store lfDiscardStats before flushing memtables discardStatsKey := y.KeyWithTs(lfDiscardStatsKey, 1) ft.mt.Put(discardStatsKey, y.ValueStruct{Value: db.vlog.encodedDiscardStats()}) } fileID := db.lc.reserveFileID() fd, err := y.CreateSyncedFile(table.NewFilename(fileID, db.opt.Dir), true) if err != nil { return y.Wrap(err) } // Don't block just to sync the directory entry. dirSyncCh := make(chan error) go func() { dirSyncCh <- syncDir(db.opt.Dir) }() err = writeLevel0Table(ft, fd) dirSyncErr := <-dirSyncCh if err != nil { db.elog.Errorf("ERROR while writing to level 0: %v", err) return err } if dirSyncErr != nil { // Do dir sync as best effort. No need to return due to an error there. db.elog.Errorf("ERROR while syncing level directory: %v", dirSyncErr) } tbl, err := table.OpenTable(fd, db.opt.TableLoadingMode, nil) if err != nil { db.elog.Printf("ERROR while opening table: %v", err) return err } // We own a ref on tbl. err = db.lc.addLevel0Table(tbl) // This will incrRef (if we don't error, sure) tbl.DecrRef() // Releases our ref. return err }
https://github.com/delicb/gstring/blob/77637d5e476b8e22d81f6a7bc5311a836dceb1c2/gstring.go#L12-L103
func gformat(format string, args map[string]interface{}) (string, []interface{}) { // holder for new format string - capacity as length of provided string // should be enough not to resize during appending, since expected length // of new format is smaller then provided one (names are removed) var new_format = make([]rune, 0, len(format)) // flag that indicates if current place in format string in inside { } var in_format = false // flag that indicates if current place is format string in inside { } and after : var in_args = false var previousChar rune // temp slice for holding name in current format var current_name_runes = make([]rune, 0, 10) // temp slice for holding args in current format var current_args_runes = make([]rune, 0, 10) var new_format_params []interface{} for i, ch := range format { if i > 0 { previousChar = rune(format[i-1]) } switch ch { case '{': if in_format && previousChar == '{' { in_format = false new_format = append(new_format, ch) break } in_format = true case '}': if !in_format { if previousChar == '}' { new_format = append(new_format, ch) break } // what to do if not in_format and only single } appears? break } if in_format { if len(current_args_runes) > 0 { // append formatting arguments to new_format directly new_format = append(new_format, current_args_runes...) } else { // if no arguments are supplied, use default ones new_format = append(new_format, defaultFormat...) } // reset format args for new iteration current_args_runes = current_args_runes[0:0] } var name string if len(current_name_runes) == 0 { name = "EMPTY_PLACEHOLDER" } else { name = string(current_name_runes) } // reset name runes for next iteration current_name_runes = current_name_runes[0:0] // get value from provided args and append it to new_format_args val, ok := args[name] if !ok { val = fmt.Sprintf("%%MISSING=%s", name) } new_format_params = append(new_format_params, val) // reset flags in_format = false in_args = false case ':': if in_format { in_args = true } default: if in_format { if in_args { current_args_runes = append(current_args_runes, ch) } else { current_name_runes = append(current_name_runes, ch) } } else { new_format = append(new_format, ch) } } } return string(new_format), new_format_params }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L606-L613
func OrScalarWithMask(src *IplImage, value Scalar, dst, mask *IplImage) { C.cvOrS( unsafe.Pointer(src), (C.CvScalar)(value), unsafe.Pointer(dst), unsafe.Pointer(mask), ) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/reqres.go#L161-L170
func (w *reqResWriter) failed(err error) error { w.log.Debugf("writer failed: %v existing err: %v", err, w.err) if w.err != nil { return w.err } w.mex.shutdown() w.err = err return w.err }
https://github.com/jpillora/velox/blob/42845d32322027cde41ba6b065a083ea4120238f/go/conn.go#L177-L182
func (c *conn) send(upd *update) error { c.sendingMut.Lock() defer c.sendingMut.Unlock() //send (transports responsiblity to enforce timeouts) return c.transport.send(upd) }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tchooks/tchooks.go#L95-L99
func (hooks *Hooks) Ping() error { cd := tcclient.Client(*hooks) _, _, err := (&cd).APICall(nil, "GET", "/ping", nil, nil) return err }
https://github.com/geoffgarside/ber/blob/27a1aff36ce64dbe5d93c08cc5f161983134ddc5/ber.go#L483-L804
func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error) { offset = initOffset fieldType := v.Type() // If we have run out of data, it may be that there are optional elements at the end. if offset == len(bytes) { if !setDefaultValue(v, params) { err = asn1.SyntaxError{Msg: "sequence truncated"} } return } // Deal with raw values. if fieldType == rawValueType { var t tagAndLength t, offset, err = parseTagAndLength(bytes, offset) if err != nil { return } if invalidLength(offset, t.length, len(bytes)) { err = asn1.SyntaxError{Msg: "data truncated"} return } result := asn1.RawValue{t.class, t.tag, t.isCompound, bytes[offset : offset+t.length], bytes[initOffset : offset+t.length]} offset += t.length v.Set(reflect.ValueOf(result)) return } // Deal with the ANY type. if ifaceType := fieldType; ifaceType.Kind() == reflect.Interface && ifaceType.NumMethod() == 0 { var t tagAndLength t, offset, err = parseTagAndLength(bytes, offset) if err != nil { return } if invalidLength(offset, t.length, len(bytes)) { err = asn1.SyntaxError{Msg: "data truncated"} return } var result interface{} if !t.isCompound && t.class == classUniversal { innerBytes := bytes[offset : offset+t.length] switch t.tag { case tagPrintableString: result, err = parsePrintableString(innerBytes) case tagIA5String: result, err = parseIA5String(innerBytes) case tagT61String: result, err = parseT61String(innerBytes) case tagUTF8String: result, err = parseUTF8String(innerBytes) case tagInteger: result, err = parseInt64(innerBytes) case tagBitString: result, err = parseBitString(innerBytes) case tagOID: result, err = parseObjectIdentifier(innerBytes) case tagUTCTime: result, err = parseUTCTime(innerBytes) case tagGeneralizedTime: result, err = parseGeneralizedTime(innerBytes) case tagOctetString: result = innerBytes default: // If we don't know how to handle the type, we just leave Value as nil. } } offset += t.length if err != nil { return } if result != nil { v.Set(reflect.ValueOf(result)) } return } universalTag, compoundType, ok1 := getUniversalType(fieldType) if !ok1 { err = asn1.StructuralError{Msg: fmt.Sprintf("unknown Go type: %v", fieldType)} return } t, offset, err := parseTagAndLength(bytes, offset) if err != nil { return } if params.explicit { expectedClass := classContextSpecific if params.application { expectedClass = classApplication } if offset == len(bytes) { err = asn1.StructuralError{Msg: "explicit tag has no child"} return } if t.class == expectedClass && t.tag == *params.tag && (t.length == 0 || t.isCompound) { if t.length > 0 { t, offset, err = parseTagAndLength(bytes, offset) if err != nil { return } } else { if fieldType != flagType { err = asn1.StructuralError{Msg: "zero length explicit tag was not an asn1.Flag"} return } v.SetBool(true) return } } else { // The tags didn't match, it might be an optional element. ok := setDefaultValue(v, params) if ok { offset = initOffset } else { err = asn1.StructuralError{Msg: "explicitly tagged member didn't match"} } return } } // Special case for strings: all the ASN.1 string types map to the Go // type string. getUniversalType returns the tag for PrintableString // when it sees a string, so if we see a different string type on the // wire, we change the universal type to match. if universalTag == tagPrintableString { if t.class == classUniversal { switch t.tag { case tagIA5String, tagGeneralString, tagT61String, tagUTF8String: universalTag = t.tag } } else if params.stringType != 0 { universalTag = params.stringType } } // Special case for time: UTCTime and GeneralizedTime both map to the // Go type time.Time. if universalTag == tagUTCTime && t.tag == tagGeneralizedTime && t.class == classUniversal { universalTag = tagGeneralizedTime } if params.set { universalTag = tagSet } expectedClass := classUniversal expectedTag := universalTag if !params.explicit && params.tag != nil { expectedClass = classContextSpecific expectedTag = *params.tag } if !params.explicit && params.application && params.tag != nil { expectedClass = classApplication expectedTag = *params.tag } // We have unwrapped any explicit tagging at this point. if t.class != expectedClass || t.tag != expectedTag || t.isCompound != compoundType { // Tags don't match. Again, it could be an optional element. ok := setDefaultValue(v, params) if ok { offset = initOffset } else { err = asn1.StructuralError{Msg: fmt.Sprintf("tags don't match (%d vs %+v) %+v %s @%d", expectedTag, t, params, fieldType.Name(), offset)} } return } if invalidLength(offset, t.length, len(bytes)) { err = asn1.SyntaxError{Msg: "data truncated"} return } innerBytes := bytes[offset : offset+t.length] offset += t.length // We deal with the structures defined in this package first. switch fieldType { case objectIdentifierType: newSlice, err1 := parseObjectIdentifier(innerBytes) v.Set(reflect.MakeSlice(v.Type(), len(newSlice), len(newSlice))) if err1 == nil { reflect.Copy(v, reflect.ValueOf(newSlice)) } err = err1 return case bitStringType: bs, err1 := parseBitString(innerBytes) if err1 == nil { v.Set(reflect.ValueOf(bs)) } err = err1 return case timeType: var time time.Time var err1 error if universalTag == tagUTCTime { time, err1 = parseUTCTime(innerBytes) } else { time, err1 = parseGeneralizedTime(innerBytes) } if err1 == nil { v.Set(reflect.ValueOf(time)) } err = err1 return case enumeratedType: parsedInt, err1 := parseInt32(innerBytes) if err1 == nil { v.SetInt(int64(parsedInt)) } err = err1 return case flagType: v.SetBool(true) return case bigIntType: parsedInt, err1 := parseBigInt(innerBytes) if err1 == nil { v.Set(reflect.ValueOf(parsedInt)) } err = err1 return } switch val := v; val.Kind() { case reflect.Bool: parsedBool, err1 := parseBool(innerBytes) if err1 == nil { val.SetBool(parsedBool) } err = err1 return case reflect.Int, reflect.Int32, reflect.Int64: if val.Type().Size() == 4 { parsedInt, err1 := parseInt32(innerBytes) if err1 == nil { val.SetInt(int64(parsedInt)) } err = err1 } else { parsedInt, err1 := parseInt64(innerBytes) if err1 == nil { val.SetInt(parsedInt) } err = err1 } return // TODO(dfc) Add support for the remaining integer types case reflect.Struct: structType := fieldType for i := 0; i < structType.NumField(); i++ { if structType.Field(i).PkgPath != "" { err = asn1.StructuralError{Msg: "struct contains unexported fields"} return } } if structType.NumField() > 0 && structType.Field(0).Type == rawContentsType { bytes := bytes[initOffset:offset] val.Field(0).Set(reflect.ValueOf(asn1.RawContent(bytes))) } innerOffset := 0 for i := 0; i < structType.NumField(); i++ { field := structType.Field(i) if i == 0 && field.Type == rawContentsType { continue } innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag.Get("asn1"))) if err != nil { return } } // We allow extra bytes at the end of the SEQUENCE because // adding elements to the end has been used in X.509 as the // version numbers have increased. return case reflect.Slice: sliceType := fieldType if sliceType.Elem().Kind() == reflect.Uint8 { val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes))) reflect.Copy(val, reflect.ValueOf(innerBytes)) return } newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem()) if err1 == nil { val.Set(newSlice) } err = err1 return case reflect.String: var v string switch universalTag { case tagPrintableString: v, err = parsePrintableString(innerBytes) case tagIA5String: v, err = parseIA5String(innerBytes) case tagT61String: v, err = parseT61String(innerBytes) case tagUTF8String: v, err = parseUTF8String(innerBytes) case tagGeneralString: // GeneralString is specified in ISO-2022/ECMA-35, // A brief review suggests that it includes structures // that allow the encoding to change midstring and // such. We give up and pass it as an 8-bit string. v, err = parseT61String(innerBytes) default: err = asn1.SyntaxError{Msg: fmt.Sprintf("internal error: unknown string type %d", universalTag)} } if err == nil { val.SetString(v) } return } err = asn1.StructuralError{Msg: "unsupported: " + v.Type().String()} return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/types.go#L52-L54
func (t VersionRunningStatus) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/apuigsech/seekret/blob/9b1f7ea1b3fd5bd29d93cf62102cb66e54428a49/models/exception.go#L61-L64
func (x *Exception) SetNline(nLine int) error { x.Nline = &nLine return nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/fuzzy/transport.go#L210-L212
func (t *transport) RequestVote(id raft.ServerID, target raft.ServerAddress, args *raft.RequestVoteRequest, resp *raft.RequestVoteResponse) error { return t.sendRPC(string(target), args, resp) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/overlay.go#L183-L186
func (p HighlightNodeParams) WithSelector(selector string) *HighlightNodeParams { p.Selector = selector return &p }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L1099-L1101
func (c APIClient) InspectFile(repoName string, commitID string, path string) (*pfs.FileInfo, error) { return c.inspectFile(repoName, commitID, path) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/client.go#L567-L572
func (c *APIClient) Ctx() context.Context { if c.ctx == nil { return c.AddMetadata(context.Background()) } return c.AddMetadata(c.ctx) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L1746-L1748
func (api *API) CloudLocator(href string) *CloudLocator { return &CloudLocator{Href(href), api} }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fileinfo.go#L414-L457
func splitQuoted(s string) (r []string, err error) { var args []string arg := make([]rune, len(s)) escaped := false quoted := false quote := '\x00' i := 0 for _, rune := range s { switch { case escaped: escaped = false case rune == '\\': escaped = true continue case quote != '\x00': if rune == quote { quote = '\x00' continue } case rune == '"' || rune == '\'': quoted = true quote = rune continue case unicode.IsSpace(rune): if quoted || i > 0 { quoted = false args = append(args, string(arg[:i])) i = 0 } continue } arg[i] = rune i++ } if quoted || i > 0 { args = append(args, string(arg[:i])) } if quote != 0 { err = errors.New("unclosed quote") } else if escaped { err = errors.New("unfinished escaping") } return args, err }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_containers.go#L86-L151
func (r *ProtocolLXD) CreateContainerFromBackup(args ContainerBackupArgs) (Operation, error) { if !r.HasExtension("container_backup") { return nil, fmt.Errorf("The server is missing the required \"container_backup\" API extension") } if args.PoolName == "" { // Send the request op, _, err := r.queryOperation("POST", "/containers", args.BackupFile, "") if err != nil { return nil, err } return op, nil } if !r.HasExtension("container_backup_override_pool") { return nil, fmt.Errorf("The server is missing the required \"container_backup_override_pool\" API extension") } // Prepare the HTTP request reqURL, err := r.setQueryAttributes(fmt.Sprintf("%s/1.0/containers", r.httpHost)) if err != nil { return nil, err } req, err := http.NewRequest("POST", reqURL, args.BackupFile) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/octet-stream") req.Header.Set("X-LXD-pool", args.PoolName) // Set the user agent if r.httpUserAgent != "" { req.Header.Set("User-Agent", r.httpUserAgent) } // Send the request resp, err := r.do(req) if err != nil { return nil, err } defer resp.Body.Close() // Handle errors response, _, err := lxdParseResponse(resp) if err != nil { return nil, err } // Get to the operation respOperation, err := response.MetadataAsOperation() if err != nil { return nil, err } // Setup an Operation wrapper op := operation{ Operation: *respOperation, r: r, chActive: make(chan bool), } return &op, nil }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/codec.go#L152-L201
func (cdc *Codec) RegisterInterface(ptr interface{}, iopts *InterfaceOptions) { cdc.assertNotSealed() // Get reflect.Type from ptr. rt := getTypeFromPointer(ptr) if rt.Kind() != reflect.Interface { panic(fmt.Sprintf("RegisterInterface expects an interface, got %v", rt)) } // Construct InterfaceInfo var info = cdc.newTypeInfoFromInterfaceType(rt, iopts) // Finally, check conflicts and register. func() { cdc.mtx.Lock() defer cdc.mtx.Unlock() cdc.collectImplementers_nolock(info) err := cdc.checkConflictsInPrio_nolock(info) if err != nil { panic(err) } cdc.setTypeInfo_nolock(info) }() /* NOTE: The above func block is a defensive pattern. First of all, the defer call is necessary to recover from panics, otherwise the Codec would become unusable after a single panic. This “defer-panic-unlock” pattern requires a func block to denote the boundary outside of which the defer call is guaranteed to have been called. In other words, using any other form of curly braces (e.g. in the form of a conditional or looping block) won't actually unlock when it might appear to visually. Consider: ``` var info = ... { cdc.mtx.Lock() defer cdc.mtx.Unlock() ... } // Here, cdc.mtx.Unlock() hasn't been called yet. ``` So, while the above code could be simplified, it's there for defense. */ }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L6379-L6383
func (v *DescribeNodeReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom72(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_storage_volumes.go#L89-L105
func (r *ProtocolLXD) CreateStoragePoolVolumeSnapshot(pool string, volumeType string, volumeName string, snapshot api.StorageVolumeSnapshotsPost) (Operation, error) { if !r.HasExtension("storage_api_volume_snapshots") { return nil, fmt.Errorf("The server is missing the required \"storage_api_volume_snapshots\" API extension") } // Send the request path := fmt.Sprintf("/storage-pools/%s/volumes/%s/%s/snapshots", url.QueryEscape(pool), url.QueryEscape(volumeType), url.QueryEscape(volumeName)) op, _, err := r.queryOperation("POST", path, snapshot, "") if err != nil { return nil, err } return op, nil }
https://github.com/Diggs/go-backoff/blob/f7b9f7e6b83be485b2e1b3eebba36652c6c4cd8a/backoff.go#L89-L91
func NewExponentialFullJitter(start time.Duration, limit time.Duration) *Backoff { return NewBackoff(exponentialFullJitter{limit: limit}, start, limit) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/backgroundservice/easyjson.go#L237-L241
func (v *SetRecordingParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoBackgroundservice2(&r, v) return r.Error() }
https://github.com/avast/retry-go/blob/88ef2130df9642aa2849152b2985af9ba3676ee9/retry.go#L132-L141
func (e Error) Error() string { logWithNumber := make([]string, lenWithoutNil(e)) for i, l := range e { if l != nil { logWithNumber[i] = fmt.Sprintf("#%d: %s", i+1, l.Error()) } } return fmt.Sprintf("All attempts fail:\n%s", strings.Join(logWithNumber, "\n")) }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L433-L435
func (b *Base) Warnf(msg string, a ...interface{}) error { return b.Warningf(msg, a...) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/fetch.go#L186-L189
func (p ContinueRequestParams) WithHeaders(headers []*HeaderEntry) *ContinueRequestParams { p.Headers = headers return &p }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/route_mappings.go#L278-L316
func (a *App) buildRouteName(p string) string { if p == "/" || p == "" { return "root" } resultParts := []string{} parts := strings.Split(p, "/") for index, part := range parts { if strings.Contains(part, "{") || part == "" { continue } shouldSingularize := (len(parts) > index+1) && strings.Contains(parts[index+1], "{") if shouldSingularize { part = flect.Singularize(part) } if parts[index] == "new" || parts[index] == "edit" { resultParts = append([]string{part}, resultParts...) continue } if index > 0 && strings.Contains(parts[index-1], "}") { resultParts = append(resultParts, part) continue } resultParts = append(resultParts, part) } if len(resultParts) == 0 { return "unnamed" } underscore := strings.TrimSpace(strings.Join(resultParts, "_")) return name.VarCase(underscore) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/client.go#L220-L225
func WithDialTimeout(t time.Duration) Option { return func(settings *clientSettings) error { settings.dialTimeout = t return nil } }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L2465-L2474
func (o *MapInt64Option) Set(value string) error { parts := stringMapRegex.Split(value, 2) if len(parts) != 2 { return fmt.Errorf("expected KEY=VALUE got '%s'", value) } val := Int64Option{} val.Set(parts[1]) (*o)[parts[0]] = val return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/client.go#L484-L502
func (c *Client) ListProwJobs(selector string) ([]prowapi.ProwJob, error) { c.log("ListProwJobs", selector) var jl struct { Items []prowapi.ProwJob `json:"items"` } err := c.request(&request{ path: fmt.Sprintf("/apis/prow.k8s.io/v1/namespaces/%s/prowjobs", c.namespace), deckPath: "/prowjobs.js", query: map[string]string{"labelSelector": selector}, }, &jl) if err == nil { var pjs []prowapi.ProwJob for _, pj := range jl.Items { pjs = append(pjs, pj) } jl.Items = pjs } return jl.Items, err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pod-utils/downwardapi/jobspec.go#L141-L156
func EnvForType(jobType prowapi.ProwJobType) []string { baseEnv := []string{jobNameEnv, JobSpecEnv, jobTypeEnv, prowJobIDEnv, buildIDEnv, prowBuildIDEnv} refsEnv := []string{repoOwnerEnv, repoNameEnv, pullBaseRefEnv, pullBaseShaEnv, pullRefsEnv} pullEnv := []string{pullNumberEnv, pullPullShaEnv} switch jobType { case prowapi.PeriodicJob: return baseEnv case prowapi.PostsubmitJob, prowapi.BatchJob: return append(baseEnv, refsEnv...) case prowapi.PresubmitJob: return append(append(baseEnv, refsEnv...), pullEnv...) default: return []string{} } }
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L646-L659
func (db *DB) fieldIndexByName(t reflect.Type, name string, index []int) []int { for i := 0; i < t.NumField(); i++ { field := t.Field(i) if candidate := db.columnFromTag(field); candidate == name { return append(index, i) } if field.Anonymous { if idx := db.fieldIndexByName(field.Type, name, append(index, i)); len(idx) > 0 { return append(index, idx...) } } } return nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/frame.go#L130-L150
func (f *Frame) ReadBody(header []byte, r io.Reader) error { // Copy the header into the underlying buffer so we have an assembled frame // that can be directly forwarded. copy(f.buffer, header) // Parse the header into our typed struct. if err := f.Header.read(typed.NewReadBuffer(header)); err != nil { return err } switch payloadSize := f.Header.PayloadSize(); { case payloadSize > MaxFramePayloadSize: return fmt.Errorf("invalid frame size %v", f.Header.size) case payloadSize > 0: _, err := io.ReadFull(r, f.SizedPayload()) return err default: // No payload to read return nil } }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/raft.go#L642-L664
func (r *Raft) verifyLeader(v *verifyFuture) { // Current leader always votes for self v.votes = 1 // Set the quorum size, hot-path for single node v.quorumSize = r.quorumSize() if v.quorumSize == 1 { v.respond(nil) return } // Track this request v.notifyCh = r.verifyCh r.leaderState.notify[v] = struct{}{} // Trigger immediate heartbeats for _, repl := range r.leaderState.replState { repl.notifyLock.Lock() repl.notify[v] = struct{}{} repl.notifyLock.Unlock() asyncNotifyCh(repl.notifyCh) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L728-L732
func (v ObjectStoreIndex) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoIndexeddb6(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/build/controller.go#L699-L719
func injectedSteps(encodedJobSpec string, dc prowjobv1.DecorationConfig, injectedSource bool, toolsMount coreapi.VolumeMount, entries []wrapper.Options) ([]coreapi.Container, *coreapi.Container, *coreapi.Volume, error) { gcsVol, gcsMount, gcsOptions := decorate.GCSOptions(dc) sidecar, err := decorate.Sidecar(dc.UtilityImages.Sidecar, gcsOptions, gcsMount, logMount, encodedJobSpec, decorate.RequirePassingEntries, entries...) if err != nil { return nil, nil, nil, fmt.Errorf("inject sidecar: %v", err) } var cloneLogMount *coreapi.VolumeMount if injectedSource { cloneLogMount = &logMount } initUpload, err := decorate.InitUpload(dc.UtilityImages.InitUpload, gcsOptions, gcsMount, cloneLogMount, encodedJobSpec) if err != nil { return nil, nil, nil, fmt.Errorf("inject initupload: %v", err) } placer := decorate.PlaceEntrypoint(dc.UtilityImages.Entrypoint, toolsMount) return []coreapi.Container{placer, *initUpload}, sidecar, &gcsVol, nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L104-L108
func (wb *WriteBatch) SetWithTTL(key, val []byte, dur time.Duration) error { expire := time.Now().Add(dur).Unix() e := &Entry{Key: key, Value: val, ExpiresAt: uint64(expire)} return wb.SetEntry(e) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L3902-L3904
func (api *API) UserSettingLocator(href string) *UserSettingLocator { return &UserSettingLocator{Href(href), api} }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/routes_client.go#L92-L115
func (a *Client) GetAppsAppRoutesRoute(params *GetAppsAppRoutesRouteParams) (*GetAppsAppRoutesRouteOK, error) { // TODO: Validate the params before sending if params == nil { params = NewGetAppsAppRoutesRouteParams() } result, err := a.transport.Submit(&runtime.ClientOperation{ ID: "GetAppsAppRoutesRoute", Method: "GET", PathPattern: "/apps/{app}/routes/{route}", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json"}, Schemes: []string{"http", "https"}, Params: params, Reader: &GetAppsAppRoutesRouteReader{formats: a.formats}, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return nil, err } return result.(*GetAppsAppRoutesRouteOK), nil }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/rate/rate.go#L166-L172
func NewLimiter(counter Counter, duration time.Duration, limit uint64) Limiter { return &limiter{ Counter: counter, duration: duration, limit: limit, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L410-L413
func (p SetDockTileParams) WithBadgeLabel(badgeLabel string) *SetDockTileParams { p.BadgeLabel = badgeLabel return &p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/memory.go#L197-L206
func (p *GetAllTimeSamplingProfileParams) Do(ctx context.Context) (profile *SamplingProfile, err error) { // execute var res GetAllTimeSamplingProfileReturns err = cdp.Execute(ctx, CommandGetAllTimeSamplingProfile, nil, &res) if err != nil { return nil, err } return res.Profile, nil }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/auditail/main.go#L127-L136
func getHref(entry *cm15.AuditEntry) string { var href string for _, link := range entry.Links { if link["rel"] == "self" { href = link["href"] break } } return href }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/errors.go#L221-L227
func GetSystemErrorMessage(err error) string { if se, ok := err.(SystemError); ok { return se.Message() } return err.Error() }
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/time.go#L56-L61
func TimeFromPtr(t *time.Time) Time { if t == nil { return NewTime(time.Time{}, false) } return NewTime(*t, true) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L629-L633
func (v *GetWindowForTargetReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser5(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/flags/urls.go#L31-L38
func (us *URLsValue) Set(s string) error { ss, err := types.NewURLs(strings.Split(s, ",")) if err != nil { return err } *us = URLsValue(ss) return nil }
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/header.go#L41-L96
func (t *TupleHeader) WriteTo(w io.Writer) (int64, error) { if len(t.Offsets) != int(t.FieldCount) { return 0, errors.New("Invalid Header: Field count does not equal number of field offsets") } // Encode Header dst := make([]byte, t.Size()) dst[0] = byte(t.TupleVersion) binary.LittleEndian.PutUint32(dst[1:], t.NamespaceHash) binary.LittleEndian.PutUint32(dst[5:], t.Hash) binary.LittleEndian.PutUint32(dst[9:], t.FieldCount) pos := int64(13) switch t.FieldSize { case 1: // Write field offsets for _, offset := range t.Offsets { dst[pos] = byte(offset) pos++ } case 2: // Set size enum dst[0] |= 64 // Write field offsets for _, offset := range t.Offsets { binary.LittleEndian.PutUint16(dst[pos:], uint16(offset)) pos += 2 } case 4: // Set size enum dst[0] |= 128 // Write field offsets for _, offset := range t.Offsets { binary.LittleEndian.PutUint32(dst[pos:], uint32(offset)) pos += 4 } case 8: // Set size enum dst[0] |= 192 // Write field offsets for _, offset := range t.Offsets { binary.LittleEndian.PutUint64(dst[pos:], offset) pos += 8 } default: return pos, errors.New("Invalid Header: Field size must be 1,2,4 or 8 bytes") } n, err := w.Write(dst) return int64(n), err }
https://github.com/st3v/tracerr/blob/07f754d5ee02576c14a8272df820e8947d87e723/tracerr.go#L81-L83
func (s *stackFrame) string() string { return fmt.Sprintf("%s (%s:%d)", s.function, s.file, s.line) }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L158-L161
func (img *IplImage) Get1D(x int) Scalar { ret := C.cvGet1D(unsafe.Pointer(img), C.int(x)) return Scalar(ret) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L2095-L2099
func (v *SearchInContentParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger21(&r, v) return r.Error() }
https://github.com/segmentio/nsq-go/blob/ff4eef968f46eb580d9dba4f637c5dfb1e5b2208/frame.go#L116-L128
func (f UnknownFrame) Write(w *bufio.Writer) (err error) { if err = writeFrameHeader(w, f.Type, len(f.Data)); err != nil { err = errors.WithMessage(err, "writing unknown frame") return } if _, err = w.Write(f.Data); err != nil { err = errors.Wrap(err, "writing unknown frame") return } return }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/osarch/release.go#L11-L17
func GetLSBRelease() (map[string]string, error) { osRelease, err := getLSBRelease("/etc/os-release") if os.IsNotExist(err) { return getLSBRelease("/usr/lib/os-release") } return osRelease, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/audits/audits.go#L70-L85
func (p *GetEncodedResponseParams) Do(ctx context.Context) (body []byte, originalSize int64, encodedSize int64, err error) { // execute var res GetEncodedResponseReturns err = cdp.Execute(ctx, CommandGetEncodedResponse, p, &res) if err != nil { return nil, 0, 0, err } // decode var dec []byte dec, err = base64.StdEncoding.DecodeString(res.Body) if err != nil { return nil, 0, 0, err } return dec, res.OriginalSize, res.EncodedSize, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L194-L274
func (c *ClusterTx) StoragePoolCreatePending(node, name, driver string, conf map[string]string) error { // First check if a storage pool with the given name exists, and, if // so, that it has a matching driver and it's in the pending state. pool := struct { id int64 driver string state int }{} var errConsistency error dest := func(i int) []interface{} { // Sanity check that there is at most one pool with the given name. if i != 0 { errConsistency = fmt.Errorf("more than one pool exists with the given name") } return []interface{}{&pool.id, &pool.driver, &pool.state} } stmt, err := c.tx.Prepare("SELECT id, driver, state FROM storage_pools WHERE name=?") if err != nil { return err } defer stmt.Close() err = query.SelectObjects(stmt, dest, name) if err != nil { return err } if errConsistency != nil { return errConsistency } var poolID = pool.id if poolID == 0 { // No existing pool with the given name was found, let's create // one. columns := []string{"name", "driver"} values := []interface{}{name, driver} poolID, err = query.UpsertObject(c.tx, "storage_pools", columns, values) if err != nil { return err } } else { // Check that the existing pools matches the given driver and // is in the pending state. if pool.driver != driver { return fmt.Errorf("pool already exists with a different driver") } if pool.state != storagePoolPending { return fmt.Errorf("pool is not in pending state") } } // Get the ID of the node with the given name. nodeInfo, err := c.NodeByName(node) if err != nil { return err } // Check that no storage_pool entry of this node and pool exists yet. count, err := query.Count( c.tx, "storage_pools_nodes", "storage_pool_id=? AND node_id=?", poolID, nodeInfo.ID) if err != nil { return err } if count != 0 { return ErrAlreadyDefined } // Insert the node-specific configuration. columns := []string{"storage_pool_id", "node_id"} values := []interface{}{poolID, nodeInfo.ID} _, err = query.UpsertObject(c.tx, "storage_pools_nodes", columns, values) if err != nil { return err } err = c.StoragePoolConfigAdd(poolID, nodeInfo.ID, conf) if err != nil { return err } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L3644-L3648
func (v GetInstallabilityErrorsParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage39(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L591-L598
func OrWithMask(src1, src2, dst, mask *IplImage) { C.cvOr( unsafe.Pointer(src1), unsafe.Pointer(src2), unsafe.Pointer(dst), unsafe.Pointer(mask), ) }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/ash/authorizer.go#L7-L32
func A(name string, m fire.Matcher, h Handler) *Authorizer { // panic if matcher or handler is not set if m == nil || h == nil { panic("ash: missing matcher or handler") } // construct and return authorizer return &Authorizer{ Matcher: m, Handler: func(ctx *fire.Context) ([]*Enforcer, error) { // begin trace ctx.Tracer.Push(name) // call handler enforcers, err := h(ctx) if err != nil { return nil, err } // finish trace ctx.Tracer.Pop() return enforcers, nil }, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L1227-L1231
func (v RequestNodeReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom12(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L239-L262
func copyTree(tw *tar.Writer, dstDir, srcDir string) error { entries, err := ioutil.ReadDir(srcDir) if err != nil { return fmt.Errorf("unable to read dir %v: %v", srcDir, err) } for _, entry := range entries { n := entry.Name() if skipFiles[n] { continue } s := filepath.Join(srcDir, n) d := filepath.Join(dstDir, n) if entry.IsDir() { if err := copyTree(tw, d, s); err != nil { return fmt.Errorf("unable to copy dir %v to %v: %v", s, d, err) } continue } if err := copyFile(tw, d, s); err != nil { return fmt.Errorf("unable to copy dir %v to %v: %v", s, d, err) } } return nil }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/service/logger/logger.go#L166-L179
func NewStackdriverConfig() zap.Config { return zap.Config{ Level: zap.NewAtomicLevelAt(zap.InfoLevel), Development: false, Sampling: &zap.SamplingConfig{ Initial: 100, Thereafter: 100, }, Encoding: encoderName, EncoderConfig: NewStackdriverEncoderConfig(), OutputPaths: []string{"stdout"}, ErrorOutputPaths: []string{"stdout"}, } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/client.go#L76-L78
func (c *ClientWriter) WriteResource(resource *gen.Resource, w io.Writer) error { return c.resourceTmpl.Execute(w, resource) }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/json_indent.go#L77-L80
func (w *jsonIndentResponseWriter) WriteHeader(code int) { w.ResponseWriter.WriteHeader(code) w.wroteHeader = true }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/types.go#L87-L92
func (t TimeSinceEpoch) MarshalEasyJSON(out *jwriter.Writer) { v := float64(time.Time(t).UnixNano() / int64(time.Second)) out.Buffer.EnsureSpace(20) out.Buffer.Buf = strconv.AppendFloat(out.Buffer.Buf, v, 'f', -1, 64) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L555-L557
func (t *BlockedReason) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/olorin/nagiosplugin/blob/893f9702af4ea1e2dc4cd6528cbdcdb3dc7ca064/perfdata.go#L99-L105
func (p PerfDatum) String() string { val := fmtPerfFloat(p.value) value := fmt.Sprintf("%s=%s%s", p.label, val, p.unit) value += fmt.Sprintf(";%s;%s", fmtThreshold(p.warn), fmtThreshold(p.crit)) value += fmt.Sprintf(";%s;%s", fmtThreshold(p.min), fmtThreshold(p.max)) return value }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/diff/result.go#L29-L31
func (dj *DeltaJob) AddedProperty(name string, p *enaml.JobManifestProperty) { dj.AddedProperties[name] = *p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L2161-L2165
func (v *CreateBrowserContextReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget24(&r, v) return r.Error() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1447-L1457
func (c *Client) UpdateRepoLabel(org, repo, label, newName, description, color string) error { c.log("UpdateRepoLabel", org, repo, label, newName, color) _, err := c.request(&request{ method: http.MethodPatch, path: fmt.Sprintf("/repos/%s/%s/labels/%s", org, repo, label), accept: "application/vnd.github.symmetra-preview+json", // allow the description field -- https://developer.github.com/changes/2018-02-22-label-description-search-preview/ requestBody: Label{Name: newName, Description: description, Color: color}, exitCodes: []int{200}, }, nil) return err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L653-L655
func (p *NavigateToHistoryEntryParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandNavigateToHistoryEntry, p, nil) }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dpdf/gc.go#L295-L299
func (gc *GraphicContext) SetFontSize(fontSize float64) { gc.StackGraphicContext.SetFontSize(fontSize) gc.recalc() gc.pdf.SetFontSize(fontSize * gc.Current.Scale) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L716-L719
func (p PrintToPDFParams) WithPaperHeight(paperHeight float64) *PrintToPDFParams { p.PaperHeight = paperHeight return &p }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/type_filter_wrapper.go#L64-L73
func (t *TypeFilterWrapperPlugin) ReceiveIssue(issue sql.Issue) []Point { if issue.IsPR && t.pullRequests { return nil } else if !issue.IsPR && t.issues { return nil } else { t.pass[issue.ID] = true return t.plugin.ReceiveIssue(issue) } }
https://github.com/mikespook/possum/blob/56d7ebb6470b670001632b11be7fc089038f4dd7/helper.go#L12-L22
func Method(m map[string]HandlerFunc) HandlerFunc { f := func(ctx *Context) error { h, ok := m[ctx.Request.Method] if ok { return h(ctx) } ctx.Response.Status = http.StatusMethodNotAllowed return nil } return f }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/functions/depot.go#L27-L30
func (fc *FuncDepot) Get(key string) (reflect.Value, bool) { f, ok := fc.depot[key] return f, ok }
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/ecdsa.go#L60-L66
func ECDSAKeyPairFromKey(priv *ecdsa.PrivateKey) (PrivKey, PubKey, error) { if priv == nil { return nil, nil, ErrNilPrivateKey } return &ECDSAPrivateKey{priv}, &ECDSAPublicKey{&priv.PublicKey}, nil }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/routes/patch_apps_app_routes_route_parameters.go#L111-L114
func (o *PatchAppsAppRoutesRouteParams) WithHTTPClient(client *http.Client) *PatchAppsAppRoutesRouteParams { o.SetHTTPClient(client) return o }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/render/plain.go#L9-L12
func Plain(names ...string) Renderer { e := New(Options{}) return e.Plain(names...) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/channel.go#L792-L830
func (ch *Channel) Close() { ch.Logger().Info("Channel.Close called.") var connections []*Connection var channelClosed bool func() { ch.mutable.Lock() defer ch.mutable.Unlock() if ch.mutable.state == ChannelClosed { ch.Logger().Info("Channel already closed, skipping additional Close() calls") return } if ch.mutable.l != nil { ch.mutable.l.Close() } // Stop the idle connections timer. ch.mutable.idleSweep.Stop() ch.mutable.state = ChannelStartClose if len(ch.mutable.conns) == 0 { ch.mutable.state = ChannelClosed channelClosed = true } for _, c := range ch.mutable.conns { connections = append(connections, c) } }() for _, c := range connections { c.close(LogField{"reason", "channel closing"}) } if channelClosed { ch.onClosed() } }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6485-L6494
func (u StellarMessage) GetError() (result Error, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "Error" { result = *u.Error ok = true } return }