_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/genny/resource/resource.go#L15-L69
func New(opts *Options) (*genny.Generator, error) { g := genny.New() if err := opts.Validate(); err != nil { return g, err } if !opts.SkipTemplates { core := packr.New("github.com/gobuffalo/buffalo/genny/resource/templates/core", "../resource/templates/core") if err := g.Box(core); err != nil { return g, err } } var abox packd.Box if opts.SkipModel { abox = packr.New("github.com/gobuffalo/buffalo/genny/resource/templates/standard", "../resource/templates/standard") } else { abox = packr.New("github.com/gobuffalo/buffalo/genny/resource/templates/use_model", "../resource/templates/use_model") } if err := g.Box(abox); err != nil { return g, err } pres := presenter{ App: opts.App, Name: name.New(opts.Name), Model: name.New(opts.Model), Attrs: opts.Attrs, } x := pres.Name.Resource().File().String() folder := pres.Name.Folder().Pluralize().String() g.Transformer(genny.Replace("resource-name", x)) g.Transformer(genny.Replace("resource-use_model", x)) g.Transformer(genny.Replace("folder-name", folder)) data := map[string]interface{}{ "opts": pres, "actions": actions(opts), "folder": folder, } helpers := template.FuncMap{ "camelize": func(s string) string { return flect.Camelize(s) }, } g.Transformer(gogen.TemplateTransformer(data, helpers)) g.RunFn(installPop(opts)) g.RunFn(addResource(pres)) return g, nil }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L394-L403
func (u *UploadDataType) IsEquivalent(other DataType) bool { o, ok := other.(*UploadDataType) if !ok { return false } if o.TypeName != u.TypeName { return false } return true }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L1167-L1207
func (d *Daemon) setupRBACServer(rbacURL string, rbacKey string, rbacExpiry int64, rbacAgentURL string, rbacAgentUsername string, rbacAgentPrivateKey string, rbacAgentPublicKey string) error { if d.rbac != nil || rbacURL == "" || rbacAgentURL == "" || rbacAgentUsername == "" || rbacAgentPrivateKey == "" || rbacAgentPublicKey == "" { return nil } // Get a new server struct server, err := rbac.NewServer(rbacURL, rbacKey, rbacAgentURL, rbacAgentUsername, rbacAgentPrivateKey, rbacAgentPublicKey) if err != nil { return err } // Set projects helper server.ProjectsFunc = func() (map[int64]string, error) { var result map[int64]string err := d.cluster.Transaction(func(tx *db.ClusterTx) error { var err error result, err = tx.ProjectMap() return err }) return result, err } // Perform full sync err = server.SyncProjects() if err != nil { return err } server.StartStatusCheck() d.rbac = server // Enable candid authentication err = d.setupExternalAuthentication(fmt.Sprintf("%s/auth", rbacURL), rbacKey, rbacExpiry, "") if err != nil { return err } return nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/file_snapshot.go#L380-L430
func (s *FileSnapshotSink) Close() error { // Make sure close is idempotent if s.closed { return nil } s.closed = true // Close the open handles if err := s.finalize(); err != nil { s.logger.Printf("[ERR] snapshot: Failed to finalize snapshot: %v", err) if delErr := os.RemoveAll(s.dir); delErr != nil { s.logger.Printf("[ERR] snapshot: Failed to delete temporary snapshot directory at path %v: %v", s.dir, delErr) return delErr } return err } // Write out the meta data if err := s.writeMeta(); err != nil { s.logger.Printf("[ERR] snapshot: Failed to write metadata: %v", err) return err } // Move the directory into place newPath := strings.TrimSuffix(s.dir, tmpSuffix) if err := os.Rename(s.dir, newPath); err != nil { s.logger.Printf("[ERR] snapshot: Failed to move snapshot into place: %v", err) return err } if runtime.GOOS != "windows" { //skipping fsync for directory entry edits on Windows, only needed for *nix style file systems parentFH, err := os.Open(s.parentDir) defer parentFH.Close() if err != nil { s.logger.Printf("[ERR] snapshot: Failed to open snapshot parent directory %v, error: %v", s.parentDir, err) return err } if err = parentFH.Sync(); err != nil { s.logger.Printf("[ERR] snapshot: Failed syncing parent directory %v, error: %v", s.parentDir, err) return err } } // Reap any old snapshots if err := s.store.ReapSnapshots(); err != nil { return err } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/types.go#L277-L279
func (t *MouseType) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/storage/postgres/storage.go#L299-L358
func (s *Storage) SetValue(ctx context.Context, accessToken string, key, value string) (map[string]string, error) { span, ctx := opentracing.StartSpanFromContext(ctx, "postgres.storage.set-value") defer span.Finish() var err error if accessToken == "" { return nil, storage.ErrMissingAccessToken } entity := &sessionEntity{ AccessToken: accessToken, } selectQuery := ` SELECT bag FROM ` + s.schema + `.` + s.table + ` WHERE access_token = $1 FOR UPDATE ` updateQuery := ` UPDATE ` + s.schema + `.` + s.table + ` SET bag = $2 WHERE access_token = $1 ` tx, err := s.db.BeginTx(ctx, nil) if err != nil { tx.Rollback() return nil, err } startSelect := time.Now() err = tx.QueryRowContext(ctx, selectQuery, accessToken).Scan( &entity.Bag, ) s.incQueries(prometheus.Labels{"query": "set_value_select"}, startSelect) if err != nil { s.incError(prometheus.Labels{"query": "set_value_select"}) tx.Rollback() if err == sql.ErrNoRows { return nil, storage.ErrSessionNotFound } return nil, err } entity.Bag.Set(key, value) startUpdate := time.Now() _, err = tx.ExecContext(ctx, updateQuery, accessToken, entity.Bag) s.incQueries(prometheus.Labels{"query": "set_value_update"}, startUpdate) if err != nil { s.incError(prometheus.Labels{"query": "set_value_update"}) tx.Rollback() return nil, err } tx.Commit() return entity.Bag, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L121-L149
func (c *Cluster) ProfileGet(project, name string) (int64, *api.Profile, error) { var result *api.Profile var id int64 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" } profile, err := tx.ProfileGet(project, name) if err != nil { return err } result = ProfileToAPI(profile) id = int64(profile.ID) return nil }) if err != nil { return -1, nil, err } return id, result, nil }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/service_instance.go#L126-L194
func updateServiceInstance(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { serviceName := r.URL.Query().Get(":service") instanceName := r.URL.Query().Get(":instance") updateData := struct { Description string Plan string TeamOwner string Tags []string }{} err = ParseInput(r, &updateData) if err != nil { return err } tags, _ := InputValues(r, "tag") updateData.Tags = append(updateData.Tags, tags...) // for compatibility srv, err := getService(serviceName) if err != nil { return err } si, err := getServiceInstanceOrError(serviceName, instanceName) if err != nil { return err } var wantedPerms []*permission.PermissionScheme if updateData.Description != "" { wantedPerms = append(wantedPerms, permission.PermServiceInstanceUpdateDescription) si.Description = updateData.Description } if updateData.TeamOwner != "" { wantedPerms = append(wantedPerms, permission.PermServiceInstanceUpdateTeamowner) si.TeamOwner = updateData.TeamOwner } if updateData.Tags != nil { wantedPerms = append(wantedPerms, permission.PermServiceInstanceUpdateTags) si.Tags = updateData.Tags } if updateData.Plan != "" { wantedPerms = append(wantedPerms, permission.PermServiceInstanceUpdatePlan) si.PlanName = updateData.Plan } if len(wantedPerms) == 0 { return &tsuruErrors.HTTP{ Code: http.StatusBadRequest, Message: "Neither the description, team owner, tags or plan were set. You must define at least one.", } } for _, perm := range wantedPerms { allowed := permission.Check(t, perm, contextsForServiceInstance(si, serviceName)..., ) if !allowed { return permission.ErrUnauthorized } } evt, err := event.New(&event.Opts{ Target: serviceInstanceTarget(serviceName, instanceName), Kind: permission.PermServiceInstanceUpdate, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermServiceInstanceReadEvents, contextsForServiceInstance(si, serviceName)...), }) if err != nil { return err } defer func() { evt.Done(err) }() requestID := requestIDHeader(r) return si.Update(srv, *si, evt, requestID) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/json.go#L71-L88
func paranoidUnmarshalJSONObjectExactFields(data []byte, exactFields map[string]interface{}) error { seenKeys := map[string]struct{}{} if err := paranoidUnmarshalJSONObject(data, func(key string) interface{} { if valuePtr, ok := exactFields[key]; ok { seenKeys[key] = struct{}{} return valuePtr } return nil }); err != nil { return err } for key := range exactFields { if _, ok := seenKeys[key]; !ok { return jsonFormatError(fmt.Sprintf(`Key "%s" missing in a JSON object`, key)) } } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L4526-L4530
func (v GetBoxModelParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom51(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L1016-L1020
func (v RemoteObject) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime9(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/client.go#L507-L513
func (c *Client) DeleteProwJob(name string) error { c.log("DeleteProwJob", name) return c.request(&request{ method: http.MethodDelete, path: fmt.Sprintf("/apis/prow.k8s.io/v1/namespaces/%s/prowjobs/%s", c.namespace, name), }, nil) }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/snapshot.go#L211-L239
func (r *Raft) compactLogs(snapIdx uint64) error { defer metrics.MeasureSince([]string{"raft", "compactLogs"}, time.Now()) // Determine log ranges to compact minLog, err := r.logs.FirstIndex() if err != nil { return fmt.Errorf("failed to get first log index: %v", err) } // Check if we have enough logs to truncate lastLogIdx, _ := r.getLastLog() if lastLogIdx <= r.conf.TrailingLogs { return nil } // Truncate up to the end of the snapshot, or `TrailingLogs` // back from the head, which ever is further back. This ensures // at least `TrailingLogs` entries, but does not allow logs // after the snapshot to be removed. maxLog := min(snapIdx, lastLogIdx-r.conf.TrailingLogs) // Log this r.logger.Info(fmt.Sprintf("Compacting logs from %d to %d", minLog, maxLog)) // Compact the logs if err := r.logs.DeleteRange(minLog, maxLog); err != nil { return fmt.Errorf("log compaction failed: %v", err) } return nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L228-L236
func findInGopath(dir string, gopath []string) (string, error) { for _, v := range gopath { dst := filepath.Join(v, "src", dir) if _, err := os.Stat(dst); err == nil { return dst, nil } } return "", fmt.Errorf("unable to find package %v in gopath %v", dir, gopath) }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/imgproc.go#L35-L42
func GetPerspectiveTransform(rect, dst []CvPoint2D32f) *Mat { mat := CreateMat(3, 3, CV_64F) result := C.cvGetPerspectiveTransform( (*C.CvPoint2D32f)(&rect[0]), (*C.CvPoint2D32f)(&dst[0]), (*C.struct_CvMat)(mat)) return (*Mat)(result) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/db.go#L1336-L1373
func (db *DB) DropPrefix(prefix []byte) error { db.opt.Infof("DropPrefix called on %s. Blocking writes...", hex.Dump(prefix)) f := db.prepareToDrop() defer f() // Block all foreign interactions with memory tables. db.Lock() defer db.Unlock() db.imm = append(db.imm, db.mt) for _, memtable := range db.imm { if memtable.Empty() { memtable.DecrRef() continue } task := flushTask{ mt: memtable, // Ensure that the head of value log gets persisted to disk. vptr: db.vhead, dropPrefix: prefix, } db.opt.Debugf("Flushing memtable") if err := db.handleFlushTask(task); err != nil { db.opt.Errorf("While trying to flush memtable: %v", err) return err } memtable.DecrRef() } db.imm = db.imm[:0] db.mt = skl.NewSkiplist(arenaSize(db.opt)) // Drop prefixes from the levels. if err := db.lc.dropPrefix(prefix); err != nil { return err } db.opt.Infof("DropPrefix done") return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L242-L266
func (t *ConnectionType) UnmarshalEasyJSON(in *jlexer.Lexer) { switch ConnectionType(in.String()) { case ConnectionTypeNone: *t = ConnectionTypeNone case ConnectionTypeCellular2g: *t = ConnectionTypeCellular2g case ConnectionTypeCellular3g: *t = ConnectionTypeCellular3g case ConnectionTypeCellular4g: *t = ConnectionTypeCellular4g case ConnectionTypeBluetooth: *t = ConnectionTypeBluetooth case ConnectionTypeEthernet: *t = ConnectionTypeEthernet case ConnectionTypeWifi: *t = ConnectionTypeWifi case ConnectionTypeWimax: *t = ConnectionTypeWimax case ConnectionTypeOther: *t = ConnectionTypeOther default: in.AddError(errors.New("unknown ConnectionType value")) } }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gstruct/elements.go#L47-L55
func MatchElements(identifier Identifier, options Options, elements Elements) types.GomegaMatcher { return &ElementsMatcher{ Identifier: identifier, Elements: elements, IgnoreExtras: options&IgnoreExtras != 0, IgnoreMissing: options&IgnoreMissing != 0, AllowDuplicates: options&AllowDuplicates != 0, } }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/ostree/ostree_dest.go#L93-L98
func (d *ostreeImageDestination) Close() error { if d.repo != nil { C.g_object_unref(C.gpointer(d.repo)) } return os.RemoveAll(d.tmpDirPath) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L2362-L2366
func (v *CloseTargetParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget27(&r, v) return r.Error() }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/store.go#L70-L80
func (rp *redisProvider) refresh(rs *redisStore) error { var err error redisPool.Exec(func(c *redis.Client) { err = c.HMSet(rs.SID, rs.Values).Err() if err != nil { return } err = c.Expire(rs.SID, sessExpire).Err() }) return nil }
https://github.com/jpillora/requestlog/blob/df8817be5f8288874e4cbe58d441a01222a28a2f/writer.go#L81-L108
func (m *monitorableWriter) Log() { duration := time.Now().Sub(m.t0) if m.Code == 0 { m.Code = 200 } if m.opts.Filter != nil && !m.opts.Filter(m.r, m.Code, duration, m.Size) { return //skip } cc := m.colorCode() size := "" if m.Size > 0 { size = sizestr.ToString(m.Size) } buff := bytes.Buffer{} m.opts.formatTmpl.Execute(&buff, &struct { *Colors Timestamp, Method, Path, CodeColor string Code int Duration, Size, IP string }{ m.opts.Colors, m.t0.Format(m.opts.TimeFormat), m.method, m.path, cc, m.Code, fmtDuration(duration), size, m.ip, }) //fmt is threadsafe :) fmt.Fprint(m.opts.Writer, buff.String()) }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/cddvd.go#L153-L175
func (v *VM) RemoveAllCDDVDDrives() error { drives, err := v.CDDVDs() if err != nil { return &Error{ Operation: "vm.RemoveAllCDDVDDrives", Code: 200004, Text: fmt.Sprintf("Error listing CD/DVD Drives: %s\n", err), } } for _, d := range drives { err := v.DetachCDDVD(d) if err != nil { return &Error{ Operation: "vm.RemoveAllCDDVDDrives", Code: 200004, Text: fmt.Sprintf("Error removing CD/DVD Drive %v, error: %s\n", d, err), } } } return nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L609-L621
func (c APIClient) GetObject(hash string, writer io.Writer) error { getObjectClient, err := c.ObjectAPIClient.GetObject( c.Ctx(), &pfs.Object{Hash: hash}, ) if err != nil { return grpcutil.ScrubGRPC(err) } if err := grpcutil.WriteFromStreamingBytesClient(getObjectClient, writer); err != nil { return grpcutil.ScrubGRPC(err) } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/report/report.go#L278-L308
func createComment(reportTemplate *template.Template, pj prowapi.ProwJob, entries []string) (string, error) { plural := "" if len(entries) > 1 { plural = "s" } var b bytes.Buffer if reportTemplate != nil { if err := reportTemplate.Execute(&b, &pj); err != nil { return "", err } } lines := []string{ fmt.Sprintf("@%s: The following test%s **failed**, say `/retest` to rerun them all:", pj.Spec.Refs.Pulls[0].Author, plural), "", "Test name | Commit | Details | Rerun command", "--- | --- | --- | ---", } lines = append(lines, entries...) if reportTemplate != nil { lines = append(lines, "", b.String()) } lines = append(lines, []string{ "", "<details>", "", plugins.AboutThisBot, "</details>", commentTag, }...) return strings.Join(lines, "\n"), nil }
https://github.com/kokardy/listing/blob/795534c33c5ab6be8b85a15951664ab11fb70ea7/comb.go#L4-L26
func Combinations(list Replacer, select_num int, repeatable bool, buf int) (c chan Replacer) { c = make(chan Replacer, buf) index := make([]int, list.Len(), list.Len()) for i := 0; i < list.Len(); i++ { index[i] = i } var comb_generator func([]int, int, int) chan []int if repeatable { comb_generator = repeated_combinations } else { comb_generator = combinations } go func() { defer close(c) for comb := range comb_generator(index, select_num, buf) { c <- list.Replace(comb) } }() return }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/displayer.go#L107-L140
func (d *Displayer) Output() string { output := d.RawOutput if output == nil { return "" } if outputStr, ok := d.RawOutput.(string); ok { suffix := "" if d.prettify { suffix = "\n" } return outputStr + suffix } var out string var err error if d.prettify { var b []byte b, err = json.MarshalIndent(output, "", " ") if err == nil { out = string(b) + "\n" } } else { var b []byte b, err = json.Marshal(output) out = string(b) } if err != nil { fm := "%v" if d.prettify { fm += "\n" } return fmt.Sprintf(fm, output) } return out }
https://github.com/glycerine/rbuf/blob/75b78581bebe959bc9a3df4c5f64e82c187d7531/rbuf.go#L50-L54
func (b *FixedSizeRingBuf) ContigLen() int { extent := b.Beg + b.Readable firstContigLen := intMin(extent, b.N) - b.Beg return firstContigLen }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/dag/dag.go#L36-L43
func (d *DAG) Sorted() []string { seen := make(map[string]bool) var result []string for id := range d.parents { result = append(result, dfs(id, d.parents, seen)...) } return result }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/route_info.go#L40-L46
func (ri *RouteInfo) Alias(aliases ...string) *RouteInfo { ri.Aliases = append(ri.Aliases, aliases...) for _, a := range aliases { ri.App.router.Handle(a, ri).Methods(ri.Method) } return ri }
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L235-L250
func (f *packedFileReader) Read(p []byte) (int, error) { n, err := f.r.Read(p) // read current block data for err == io.EOF { // current block empty if n > 0 { return n, nil } if f.h == nil || f.h.last { return 0, io.EOF // last block so end of file } if err := f.nextBlockInFile(); err != nil { return 0, err } n, err = f.r.Read(p) // read new block data } return n, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/easyjson.go#L569-L573
func (v *GetApplicationCacheForFrameParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoApplicationcache6(&r, v) return r.Error() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/transport.go#L254-L266
func (t *Transport) MendPeer(id types.ID) { t.mu.RLock() p, pok := t.peers[id] g, gok := t.remotes[id] t.mu.RUnlock() if pok { p.(Pausable).Resume() } if gok { g.Resume() } }
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/normalizer.go#L210-L224
func GetBindvars(stmt Statement) map[string]struct{} { bindvars := make(map[string]struct{}) _ = Walk(func(node SQLNode) (kontinue bool, err error) { switch node := node.(type) { case *SQLVal: if node.Type == ValArg { bindvars[string(node.Val[1:])] = struct{}{} } case ListArg: bindvars[string(node[2:])] = struct{}{} } return true, nil }, stmt) return bindvars }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L261-L267
func (t *tokenAuthenticator) Sign(r *http.Request) error { r.Header.Set("Authorization", "Bearer "+t.token) if t.accountID != 0 { r.Header.Set("X-Account", strconv.Itoa(t.accountID)) } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L418-L428
func formatSQL(statement string) string { lines := strings.Split(statement, "\n") for i, line := range lines { if strings.Contains(line, "UNIQUE") { // Let UNIQUE(x, y) constraints alone. continue } lines[i] = strings.Replace(line, ", ", ",\n ", -1) } return strings.Join(lines, "\n") }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/raft.go#L259-L264
func (i *raftInstance) HandlerFunc() http.HandlerFunc { if i.handler == nil { return nil } return i.handler.ServeHTTP }
https://github.com/btcsuite/btclog/blob/84c8d2346e9fc8c7b947e243b9c24e6df9fd206a/log.go#L265-L286
func (b *Backend) print(lvl, tag string, args ...interface{}) { t := time.Now() // get as early as possible bytebuf := buffer() var file string var line int if b.flag&(Lshortfile|Llongfile) != 0 { file, line = callsite(b.flag) } formatHeader(bytebuf, t, lvl, tag, file, line) buf := bytes.NewBuffer(*bytebuf) fmt.Fprintln(buf, args...) *bytebuf = buf.Bytes() b.mu.Lock() b.w.Write(*bytebuf) b.mu.Unlock() recycleBuffer(bytebuf) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L904-L913
func (p *PushNodesByBackendIdsToFrontendParams) Do(ctx context.Context) (nodeIds []cdp.NodeID, err error) { // execute var res PushNodesByBackendIdsToFrontendReturns err = cdp.Execute(ctx, CommandPushNodesByBackendIdsToFrontend, p, &res) if err != nil { return nil, err } return res.NodeIds, nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/iterator.go#L74-L76
func (item *Item) KeyCopy(dst []byte) []byte { return y.SafeCopy(dst, item.key) }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L366-L375
func (n *NetworkTransport) AppendEntriesPipeline(id ServerID, target ServerAddress) (AppendPipeline, error) { // Get a connection conn, err := n.getConnFromAddressProvider(id, target) if err != nil { return nil, err } // Create the pipeline return newNetPipeline(n, conn), nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L794-L803
func (p *TakeCoverageDeltaParams) Do(ctx context.Context) (coverage []*RuleUsage, err error) { // execute var res TakeCoverageDeltaReturns err = cdp.Execute(ctx, CommandTakeCoverageDelta, nil, &res) if err != nil { return nil, err } return res.Coverage, nil }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/examples/increment-only-counter/peer.go#L127-L136
func (p *peer) OnGossipUnicast(src mesh.PeerName, buf []byte) error { var set map[mesh.PeerName]int if err := gob.NewDecoder(bytes.NewReader(buf)).Decode(&set); err != nil { return err } complete := p.st.mergeComplete(set) p.logger.Printf("OnGossipUnicast %s %v => complete %v", src, set, complete) return nil }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/callbacks.go#L106-L121
func BasicAuthorizer(credentials map[string]string) *Callback { return C("fire/BasicAuthorizer", All(), func(ctx *Context) error { // check for credentials user, password, ok := ctx.HTTPRequest.BasicAuth() if !ok { return ErrAccessDenied } // check if credentials match if val, ok := credentials[user]; !ok || val != password { return ErrAccessDenied } return nil }) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L5032-L5036
func (v *GetInlineStylesForNodeReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss43(&r, v) return r.Error() }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/commands.go#L498-L568
func Normalize(payload APIParams, name string, v interface{}) (APIParams, error) { var matches = nameRegex.FindStringSubmatch(name) if len(matches) == 0 { return nil, nil } var k = matches[1] if len(k) == 0 { return nil, nil } var after = matches[2] if after == "" { payload[k] = v } else if after == "[" { payload[name] = v } else if after == "[]" { if _, ok := payload[k]; !ok { payload[k] = []interface{}{} } a, ok := payload[k].([]interface{}) if !ok { return nil, fmt.Errorf("expected array for param '%s'", k) } payload[k] = append(a, v) } else { matches = childRegexp.FindStringSubmatch(after) if len(matches) == 0 { matches = childRegexp2.FindStringSubmatch(after) } if len(matches) > 0 { var childKey = matches[1] if _, ok := payload[k]; !ok { payload[k] = []interface{}{} } var array []interface{} if a, ok := payload[k].([]interface{}); ok { array = a } else { return nil, fmt.Errorf("expected array for param '%s'", k) } var handled bool if len(array) > 0 { if last, ok := array[len(array)-1].(APIParams); ok { if _, ok := last[childKey]; !ok { handled = true Normalize(last, childKey, v) } } } if !handled { var p, err = Normalize(APIParams{}, childKey, v) if err != nil { return nil, err } payload[k] = append(array, p) } } else { if payload[k] == nil { payload[k] = APIParams{} } if _, ok := payload[k].(APIParams); !ok { return nil, fmt.Errorf("expected map for param '%s'", k) } var p, err = Normalize(payload[k].(APIParams), after, v) if err != nil { return nil, err } payload[k] = p } } return payload, nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/iterator.go#L654-L677
func (it *Iterator) Seek(key []byte) { for i := it.data.pop(); i != nil; i = it.data.pop() { i.wg.Wait() it.waste.push(i) } it.lastKey = it.lastKey[:0] if len(key) == 0 { key = it.opt.Prefix } if len(key) == 0 { it.iitr.Rewind() it.prefetch() return } if !it.opt.Reverse { key = y.KeyWithTs(key, it.txn.readTs) } else { key = y.KeyWithTs(key, 0) } it.iitr.Seek(key) it.prefetch() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L587-L591
func (v *ReplaySnapshotParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoLayertree5(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/types.go#L369-L371
func (t Subtype) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L75-L83
func (o Owners) GetLeafApprovers() map[string]sets.String { ownersToApprovers := map[string]sets.String{} for fn := range o.GetOwnersSet() { ownersToApprovers[fn] = o.repo.LeafApprovers(fn) } return ownersToApprovers }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4189-L4198
func (u OperationResultTr) GetAccountMergeResult() (result AccountMergeResult, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "AccountMergeResult" { result = *u.AccountMergeResult ok = true } return }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4856-L4865
func (u LedgerUpgrade) GetNewLedgerVersion() (result Uint32, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "NewLedgerVersion" { result = *u.NewLedgerVersion ok = true } return }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/iaas/dockermachine/dockermachine.go#L215-L259
func (d *DockerMachine) RegisterMachine(opts RegisterMachineOpts) (*Machine, error) { if !d.temp { return nil, errors.New("register is only available without user defined StorePath") } if opts.Base.CustomData == nil { return nil, errors.New("custom data is required") } opts.Base.CustomData["SSHKeyPath"] = filepath.Join(d.client.GetMachinesDir(), opts.Base.Id, "id_rsa") rawDriver, err := json.Marshal(opts.Base.CustomData) if err != nil { return nil, errors.WithMessage(err, "failed to marshal driver data") } h, err := d.client.NewHost(opts.DriverName, rawDriver) if err != nil { return nil, errors.WithStack(err) } err = ioutil.WriteFile(h.Driver.GetSSHKeyPath(), opts.SSHPrivateKey, 0700) if err != nil { return nil, errors.WithStack(err) } err = ioutil.WriteFile(h.AuthOptions().CaCertPath, opts.Base.CaCert, 0700) if err != nil { return nil, errors.WithStack(err) } err = ioutil.WriteFile(h.AuthOptions().ClientCertPath, opts.Base.ClientCert, 0700) if err != nil { return nil, errors.WithStack(err) } err = ioutil.WriteFile(h.AuthOptions().ClientKeyPath, opts.Base.ClientKey, 0700) if err != nil { return nil, errors.WithStack(err) } err = d.client.Save(h) if err != nil { return nil, errors.WithStack(err) } savedHost, err := d.client.Load(h.Name) if err != nil { return nil, errors.WithStack(err) } return &Machine{ Base: opts.Base, Host: savedHost, }, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/pretty/pretty.go#L21-L27
func Ago(timestamp *types.Timestamp) string { t, _ := types.TimestampFromProto(timestamp) if t.Equal(time.Time{}) { return "" } return fmt.Sprintf("%s ago", units.HumanDuration(time.Since(t))) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L139-L143
func (v *TypeProfileEntry) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler(&r, v) return r.Error() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/artifact-uploader/controller.go#L147-L184
func (c *Controller) processNextItem() bool { key, quit := c.queue.Get() if quit { return false } defer c.queue.Done(key) workItem := key.(item) prowJob, err := c.prowJobClient.GetProwJob(workItem.prowJobId) if err != nil { c.handleErr(err, workItem) return true } spec := downwardapi.NewJobSpec(prowJob.Spec, prowJob.Status.BuildID, prowJob.Name) result := c.client.Pods(workItem.namespace).GetLogs(workItem.podName, &api.PodLogOptions{Container: workItem.containerName}).Do() if err := result.Error(); err != nil { c.handleErr(err, workItem) return true } // error is checked above log, _ := result.Raw() var target string if workItem.podName == workItem.prowJobId { target = path.Join(ContainerLogDir, fmt.Sprintf("%s.txt", workItem.containerName)) } else { target = path.Join(ContainerLogDir, workItem.podName, fmt.Sprintf("%s.txt", workItem.containerName)) } data := gcs.DataUpload(bytes.NewReader(log)) if err := c.gcsConfig.Run(&spec, map[string]gcs.UploadFunc{target: data}); err != nil { c.handleErr(err, workItem) return true } c.queue.Forget(key) return true }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/backup.go#L140-L226
func (db *DB) Load(r io.Reader) error { br := bufio.NewReaderSize(r, 16<<10) unmarshalBuf := make([]byte, 1<<10) var entries []*Entry var wg sync.WaitGroup errChan := make(chan error, 1) // func to check for pending error before sending off a batch for writing batchSetAsyncIfNoErr := func(entries []*Entry) error { select { case err := <-errChan: return err default: wg.Add(1) return db.batchSetAsync(entries, func(err error) { defer wg.Done() if err != nil { select { case errChan <- err: default: } } }) } } for { var sz uint64 err := binary.Read(br, binary.LittleEndian, &sz) if err == io.EOF { break } else if err != nil { return err } if cap(unmarshalBuf) < int(sz) { unmarshalBuf = make([]byte, sz) } e := &pb.KV{} if _, err = io.ReadFull(br, unmarshalBuf[:sz]); err != nil { return err } if err = e.Unmarshal(unmarshalBuf[:sz]); err != nil { return err } var userMeta byte if len(e.UserMeta) > 0 { userMeta = e.UserMeta[0] } entries = append(entries, &Entry{ Key: y.KeyWithTs(e.Key, e.Version), Value: e.Value, UserMeta: userMeta, ExpiresAt: e.ExpiresAt, meta: e.Meta[0], }) // Update nextTxnTs, memtable stores this timestamp in badger head // when flushed. if e.Version >= db.orc.nextTxnTs { db.orc.nextTxnTs = e.Version + 1 } if len(entries) == 1000 { if err := batchSetAsyncIfNoErr(entries); err != nil { return err } entries = make([]*Entry, 0, 1000) } } if len(entries) > 0 { if err := batchSetAsyncIfNoErr(entries); err != nil { return err } } wg.Wait() select { case err := <-errChan: return err default: // Mark all versions done up until nextTxnTs. db.orc.txnMark.Done(db.orc.nextTxnTs - 1) return nil } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L431-L440
func (p *GetNavigationHistoryParams) Do(ctx context.Context) (currentIndex int64, entries []*NavigationEntry, err error) { // execute var res GetNavigationHistoryReturns err = cdp.Execute(ctx, CommandGetNavigationHistory, nil, &res) if err != nil { return 0, nil, err } return res.CurrentIndex, res.Entries, nil }
https://github.com/sayanarijit/gopassgen/blob/cf555de90ad6031f567a55be7d7c90f2fbe8389a/gopassgen.go#L49-L63
func NewPolicy() Policy { p := Policy{ MinLength: 6, MaxLength: 16, MinLowers: 0, MinUppers: 0, MinDigits: 0, MinSpclChars: 0, LowerPool: "abcdefghijklmnopqrstuvwxyz", UpperPool: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", DigitPool: "0123456789", SpclCharPool: "!@#$%^&*()-_=+,.?/:;{}[]~", } return p }
https://github.com/blacklabeldata/namedtuple/blob/c341f1db44f30b8164294aa8605ede42be604aba/schema/lexer.go#L291-L316
func lexComment(l *Lexer) stateFn { l.skipWhitespace() // if strings.HasPrefix(l.remaining(), comment) { // skip comment // l.Pos += len(comment) // find next new line and add location to pos which // advances the scanner if index := strings.Index(l.remaining(), "\n"); index > 0 { l.Pos += index } else { l.Pos += len(l.remaining()) // l.emit(TokenComment) // break } // emit the comment string l.emit(TokenComment) l.skipWhitespace() // } // continue on scanner return lexText }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_lxc.go#L521-L540
func containerLXCInstantiate(s *state.State, args db.ContainerArgs) *containerLXC { return &containerLXC{ state: s, id: args.ID, project: args.Project, name: args.Name, description: args.Description, ephemeral: args.Ephemeral, architecture: args.Architecture, cType: args.Ctype, creationDate: args.CreationDate, lastUsedDate: args.LastUsedDate, profiles: args.Profiles, localConfig: args.Config, localDevices: args.Devices, stateful: args.Stateful, node: args.Node, expiryDate: args.ExpiryDate, } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/tackle/main.go#L287-L300
func contextConfig() (clientcmd.ClientConfigLoader, *clientcmdapi.Config, error) { if err := ensureKubectl(); err != nil { fmt.Println("Prow's tackler requires kubectl, please install:") fmt.Println(" *", err) if gerr := ensureGcloud(); gerr != nil { fmt.Println(" *", gerr) } return nil, nil, errors.New("missing kubectl") } l := clientcmd.NewDefaultClientConfigLoadingRules() c, err := l.Load() return l, c, err }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/wal/file_pipeline.go#L58-L64
func (fp *filePipeline) Open() (f *fileutil.LockedFile, err error) { select { case f = <-fp.filec: case err = <-fp.errc: } return f, err }
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/filehandler.go#L33-L35
func (h *FileHandler) Write(b []byte) (n int, err error) { return h.fd.Write(b) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/emulation.go#L242-L245
func (p SetDeviceMetricsOverrideParams) WithPositionY(positionY int64) *SetDeviceMetricsOverrideParams { p.PositionY = positionY return &p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/easyjson.go#L279-L283
func (v *Error) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdproto2(&r, v) return r.Error() }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L642-L649
func StoragePoolConfigClear(tx *sql.Tx, poolID, nodeID int64) error { _, err := tx.Exec("DELETE FROM storage_pools_config WHERE storage_pool_id=? AND (node_id=? OR node_id IS NULL)", poolID, nodeID) if err != nil { return err } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L509-L511
func (p *SetAutoAttachParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetAutoAttach, p, nil) }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dbase/text.go#L66-L73
func (g *Glyph) Fill(gc draw2d.GraphicContext, x, y float64) float64 { gc.Save() gc.BeginPath() gc.Translate(x, y) gc.Fill(g.Path) gc.Restore() return g.Width }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L4198-L4202
func (v FrameTree) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage45(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/agent/agent.go#L117-L119
func (k *Keyring) RemoveKey(key ssh.PublicKey) error { return k.Agent.Remove(key) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/managed_db.go#L63-L68
func (db *DB) SetDiscardTs(ts uint64) { if !db.opt.managedTxns { panic("Cannot use SetDiscardTs with managedDB=false.") } db.orc.setDiscardTs(ts) }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/module/module.go#L77-L85
func DefaultVersion(c context.Context, module string) (string, error) { req := &pb.GetDefaultVersionRequest{} if module != "" { req.Module = &module } res := &pb.GetDefaultVersionResponse{} err := internal.Call(c, "modules", "GetDefaultVersion", req, res) return res.GetVersion(), err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L562-L565
func (p GlobalLexicalScopeNamesParams) WithExecutionContextID(executionContextID ExecutionContextID) *GlobalLexicalScopeNamesParams { p.ExecutionContextID = executionContextID return &p }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/docker.go#L26-L65
func VerifyDockerManifestSignature(unverifiedSignature, unverifiedManifest []byte, expectedDockerReference string, mech SigningMechanism, expectedKeyIdentity string) (*Signature, error) { expectedRef, err := reference.ParseNormalizedNamed(expectedDockerReference) if err != nil { return nil, err } sig, err := verifyAndExtractSignature(mech, unverifiedSignature, signatureAcceptanceRules{ validateKeyIdentity: func(keyIdentity string) error { if keyIdentity != expectedKeyIdentity { return InvalidSignatureError{msg: fmt.Sprintf("Signature by %s does not match expected fingerprint %s", keyIdentity, expectedKeyIdentity)} } return nil }, validateSignedDockerReference: func(signedDockerReference string) error { signedRef, err := reference.ParseNormalizedNamed(signedDockerReference) if err != nil { return InvalidSignatureError{msg: fmt.Sprintf("Invalid docker reference %s in signature", signedDockerReference)} } if signedRef.String() != expectedRef.String() { return InvalidSignatureError{msg: fmt.Sprintf("Docker reference %s does not match %s", signedDockerReference, expectedDockerReference)} } return nil }, validateSignedDockerManifestDigest: func(signedDockerManifestDigest digest.Digest) error { matches, err := manifest.MatchesDigest(unverifiedManifest, signedDockerManifestDigest) if err != nil { return err } if !matches { return InvalidSignatureError{msg: fmt.Sprintf("Signature for docker digest %q does not match", signedDockerManifestDigest)} } return nil }, }) if err != nil { return nil, err } return sig, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/domdebugger.go#L152-L154
func (p *RemoveInstrumentationBreakpointParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandRemoveInstrumentationBreakpoint, p, nil) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/volume.go#L222-L247
func volumeDelete(w http.ResponseWriter, r *http.Request, t auth.Token) error { volumeName := r.URL.Query().Get(":name") dbVolume, err := volume.Load(volumeName) if err != nil { if err == volume.ErrVolumeNotFound { return &errors.HTTP{Code: http.StatusNotFound, Message: err.Error()} } return err } canDelete := permission.Check(t, permission.PermVolumeDelete, contextsForVolume(dbVolume)...) if !canDelete { return permission.ErrUnauthorized } evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypeVolume, Value: volumeName}, Kind: permission.PermVolumeDelete, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermVolumeReadEvents, contextsForVolume(dbVolume)...), }) if err != nil { return err } defer func() { evt.Done(err) }() return dbVolume.Delete() }
https://github.com/manifoldco/go-base32/blob/47b2838451516c36d06986c7b85bf1355522ecbb/base32.go#L20-L32
func DecodeString(raw string) ([]byte, error) { pad := 8 - (len(raw) % 8) nb := []byte(raw) if pad != 8 { nb = make([]byte, len(raw)+pad) copy(nb, raw) for i := 0; i < pad; i++ { nb[len(raw)+i] = '=' } } return lowerBase32.DecodeString(string(nb)) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L130-L134
func (v StickyPositionConstraint) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoLayertree(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/hooklift/govix/blob/063702285520a992b920fc1575e305dc9ffd6ffe/vmx.go#L27-L43
func (vmxfile *VMXFile) Read() error { data, err := ioutil.ReadFile(vmxfile.path) if err != nil { return err } model := new(vmx.VirtualMachine) err = vmx.Unmarshal(data, model) if err != nil { return err } vmxfile.model = model return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L4542-L4546
func (v FrameResource) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage47(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kokardy/listing/blob/795534c33c5ab6be8b85a15951664ab11fb70ea7/perm.go#L35-L63
func permutations(list []int, select_num, buf int) (c chan []int) { c = make(chan []int, buf) go func() { defer close(c) switch select_num { case 1: for _, v := range list { c <- []int{v} } return case 0: return case len(list): for i := 0; i < len(list); i++ { top, sub_list := pop(list, i) for perm := range permutations(sub_list, select_num-1, buf) { c <- append([]int{top}, perm...) } } default: for comb := range combinations(list, select_num, buf) { for perm := range permutations(comb, select_num, buf) { c <- perm } } } }() return }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/ranch/storage.go#L195-L212
func ParseConfig(configPath string) ([]common.Resource, error) { file, err := ioutil.ReadFile(configPath) if err != nil { return nil, err } var data common.BoskosConfig err = yaml.Unmarshal(file, &data) if err != nil { return nil, err } var resources []common.Resource for _, entry := range data.Resources { resources = append(resources, common.NewResourcesFromConfig(entry)...) } return resources, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/resources_config_crd.go#L116-L121
func (in *ResourcesConfigObject) FromItem(i common.Item) { c, err := common.ItemToResourcesConfig(i) if err == nil { in.fromConfig(c) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/types.go#L217-L219
func (t *Timestamp) UnmarshalJSON(buf []byte) error { return easyjson.Unmarshal(buf, t) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L378-L381
func (e *SourceUploadDataType) IsEquivalent(other DataType) bool { _, ok := other.(*SourceUploadDataType) return ok }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cmdutil/exec.go#L25-L27
func RunStdin(stdin io.Reader, args ...string) error { return RunIO(IO{Stdin: stdin}, args...) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/team_token.go#L28-L39
func tokenList(w http.ResponseWriter, r *http.Request, t auth.Token) error { tokens, err := servicemanager.TeamToken.FindByUserToken(t) if err != nil { return err } if len(tokens) == 0 { w.WriteHeader(http.StatusNoContent) return nil } w.Header().Set("Content-Type", "application/json") return json.NewEncoder(w).Encode(tokens) }
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/tracked_buffer.go#L42-L47
func NewTrackedBuffer(nodeFormatter NodeFormatter) *TrackedBuffer { return &TrackedBuffer{ Buffer: new(bytes.Buffer), nodeFormatter: nodeFormatter, } }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/internal/stack/stack.go#L102-L108
func (s *Stack) Push(v interface{}) { if len(*s) >= s.BufferSize() { s.Resize(calcNewSize(cap(*s))) } *s = append(*s, v) }
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmlnode/xmlnode.go#L18-L24
func (a XMLNode) GetToken() xml.Token { if a.NodeType == tree.NtAttr { ret := a.Token.(*xml.Attr) return *ret } return a.Token }
https://github.com/achiku/soapc/blob/cfbdfe6e4caffe57a9cba89996e8b1cedb512be0/client.go#L50-L56
func NewClient(url string, tls bool, header interface{}) *Client { return &Client{ url: url, tls: tls, header: header, } }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L2090-L2153
func (loc *PatternLocator) Create(months string, name string, operation string, type_ string, value float64, years string, options rsapi.APIParams) (*PatternLocator, error) { var res *PatternLocator if months == "" { return res, fmt.Errorf("months is required") } if name == "" { return res, fmt.Errorf("name is required") } if operation == "" { return res, fmt.Errorf("operation is required") } if type_ == "" { return res, fmt.Errorf("type_ is required") } if years == "" { return res, fmt.Errorf("years is required") } var params rsapi.APIParams params = rsapi.APIParams{} var viewOpt = options["view"] if viewOpt != nil { params["view"] = viewOpt } var p rsapi.APIParams p = rsapi.APIParams{ "months": months, "name": name, "operation": operation, "type": type_, "value": value, "years": years, } var summaryOpt = options["summary"] if summaryOpt != nil { p["summary"] = summaryOpt } uri, err := loc.ActionPath("Pattern", "create") if err != nil { return res, err } req, err := loc.api.BuildHTTPRequest(uri.HTTPMethod, uri.Path, APIVersion, params, p) if err != nil { return res, err } resp, err := loc.api.PerformRequest(req) if err != nil { return res, err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { respBody, _ := ioutil.ReadAll(resp.Body) sr := string(respBody) if sr != "" { sr = ": " + sr } return res, fmt.Errorf("invalid response %s%s", resp.Status, sr) } location := resp.Header.Get("Location") if len(location) == 0 { return res, fmt.Errorf("Missing location header in response") } else { return &PatternLocator{Href(location), loc.api}, nil } }
https://github.com/solher/snakepit/blob/bc2b6bc4ed85156fe5f715b058a30048c62f7ad5/request_id.go#L26-L41
func GetRequestID(ctx context.Context) (string, error) { if ctx == nil { return "", errors.New("nil context") } reqID, ok := ctx.Value(contextRequestID).(string) if !ok { return "", errors.New("unexpected type") } if len(reqID) == 0 { return "", errors.New("empty value in context") } return reqID, nil }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/header.go#L452-L476
func fixUnquotedSpecials(s string) string { idx := strings.IndexByte(s, ';') if idx < 0 || idx == len(s) { // No parameters return s } clean := strings.Builder{} clean.WriteString(s[:idx+1]) s = s[idx+1:] for len(s) > 0 { var consumed string consumed, s = consumeParam(s) if len(consumed) == 0 { clean.WriteString(s) return clean.String() } clean.WriteString(consumed) } return clean.String() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/config.go#L726-L742
func (c *Config) validateComponentConfig() error { if c.Plank.JobURLPrefix != "" && c.Plank.JobURLPrefixConfig["*"] != "" { return errors.New(`Planks job_url_prefix must be unset when job_url_prefix_config["*"] is set. The former is deprecated, use the latter`) } for k, v := range c.Plank.JobURLPrefixConfig { if _, err := url.Parse(v); err != nil { return fmt.Errorf(`Invalid value for Planks job_url_prefix_config["%s"]: %v`, k, err) } } if c.SlackReporter != nil { if err := c.SlackReporter.DefaultAndValidate(); err != nil { return fmt.Errorf("failed to validate slackreporter config: %v", err) } } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L1368-L1370
func (p *WaitForDebuggerParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandWaitForDebugger, nil, nil) }
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L581-L591
func (v Value) Float64() float64 { x, ok := v.data.(float64) if !ok { x, ok := v.data.(int64) if ok { return float64(x) } return 0 } return x }
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dgl/gc.go#L312-L315
func (gc *GraphicContext) SetFontSize(fontSize float64) { gc.Current.FontSize = fontSize gc.recalc() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L4408-L4412
func (v *GetRequestPostDataReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork32(&r, v) return r.Error() }