_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/metadata/resource.go#L71-L81
func (r *Resource) findMatches(href string) []*PathPattern { var matches []*PathPattern for _, action := range r.Actions { for _, pattern := range action.PathPatterns { if pattern.Regexp.MatchString(href) || pattern.Regexp.MatchString(href+"/") { matches = append(matches, pattern) } } } return matches }
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/template.go#L47-L134
func (tmpl *Template) Render(templateName string, obj interface{}, request *http.Request, writer http.ResponseWriter) (template.HTML, error) { var ( content []byte t *template.Template err error funcMap = tmpl.funcMapMaker(request, writer) render = func(name string, objs ...interface{}) (template.HTML, error) { var ( err error renderObj interface{} renderContent []byte ) if len(objs) == 0 { // default obj renderObj = obj } else { // overwrite obj for _, o := range objs { renderObj = o break } } if renderContent, err = tmpl.findTemplate(name); err == nil { var partialTemplate *template.Template result := bytes.NewBufferString("") if partialTemplate, err = template.New(filepath.Base(name)).Funcs(funcMap).Parse(string(renderContent)); err == nil { if err = partialTemplate.Execute(result, renderObj); err == nil { return template.HTML(result.String()), err } } } else { err = fmt.Errorf("failed to find template: %v", name) } if err != nil { fmt.Println(err) } return "", err } ) // funcMaps funcMap["render"] = render funcMap["yield"] = func() (template.HTML, error) { return render(templateName) } layout := tmpl.layout usingDefaultLayout := false if layout == "" && tmpl.usingDefaultLayout { usingDefaultLayout = true layout = tmpl.render.DefaultLayout } if layout != "" { content, err = tmpl.findTemplate(filepath.Join("layouts", layout)) if err == nil { if t, err = template.New("").Funcs(funcMap).Parse(string(content)); err == nil { var tpl bytes.Buffer if err = t.Execute(&tpl, obj); err == nil { return template.HTML(tpl.String()), nil } } } else if !usingDefaultLayout { err = fmt.Errorf("Failed to render layout: '%v.tmpl', got error: %v", filepath.Join("layouts", tmpl.layout), err) fmt.Println(err) return template.HTML(""), err } } if content, err = tmpl.findTemplate(templateName); err == nil { if t, err = template.New("").Funcs(funcMap).Parse(string(content)); err == nil { var tpl bytes.Buffer if err = t.Execute(&tpl, obj); err == nil { return template.HTML(tpl.String()), nil } } } else { err = fmt.Errorf("failed to find template: %v", templateName) } if err != nil { fmt.Println(err) } return template.HTML(""), err }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/new_task.go#L58-L63
func (m *NewTask) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L3636-L3638
func (api *API) ImageLocator(href string) *ImageLocator { return &ImageLocator{Href(href), api} }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/coding/idheader.go#L24-L27
func ToIDHeader(v string) string { v = url.QueryEscape(v) return "<" + strings.Replace(v, "%40", "@", -1) + ">" }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/headlessexperimental/headlessexperimental.go#L46-L49
func (p BeginFrameParams) WithFrameTimeTicks(frameTimeTicks float64) *BeginFrameParams { p.FrameTimeTicks = frameTimeTicks return &p }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L1554-L1590
func (c *Client) RemoveLabel(org, repo string, number int, label string) error { c.log("RemoveLabel", org, repo, number, label) code, body, err := c.requestRaw(&request{ method: http.MethodDelete, path: fmt.Sprintf("/repos/%s/%s/issues/%d/labels/%s", org, repo, number, label), // GitHub sometimes returns 200 for this call, which is a bug on their end. // Do not expect a 404 exit code and handle it separately because we need // to introspect the request's response body. exitCodes: []int{200, 204}, }) switch { case code == 200 || code == 204: // If our code was 200 or 204, no error info. return nil case code == 404: // continue case err != nil: return err default: return fmt.Errorf("unexpected status code: %v", code) } ge := &githubError{} if err := json.Unmarshal(body, ge); err != nil { return err } // If the error was because the label was not found, we don't really // care since the label won't exist anyway. if ge.Message == "Label does not exist" { return nil } // Otherwise we got some other 404 error. return fmt.Errorf("deleting label 404: %s", ge.Message) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/auditail/main.go#L98-L101
func formatTime(tm time.Time) string { year, month, date := tm.Date() return time.Date(year, month, date, 0, 0, 0, 0, time.UTC).Format("2006/01/02 15:04:05 -0700") }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L129-L141
func (wb *WriteBatch) commit() error { if wb.err != nil { return wb.err } // Get a new txn before we commit this one. So, the new txn doesn't need // to wait for this one to commit. wb.wg.Add(1) wb.txn.CommitWith(wb.callback) wb.txn = wb.db.newTransaction(true, true) // See comment about readTs in NewWriteBatch. wb.txn.readTs = wb.db.orc.readMark.DoneUntil() return wb.err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/tide.go#L249-L256
func byRepoAndNumber(prs []PullRequest) map[string]PullRequest { m := make(map[string]PullRequest) for _, pr := range prs { key := prKey(&pr) m[key] = pr } return m }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/validation/validation.go#L29-L38
func ValidateLength(value string, min, max int) bool { l := len(value) if min > 0 && l < min { return false } if max > 0 && l > max { return false } return true }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/fetcher/client.go#L177-L184
func hasID(events []*github.IssueEvent, id int) bool { for _, event := range events { if *event.ID == int64(id) { return true } } return false }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/stringutil/uuid.go#L14-L24
func UUID() string { uuid := make([]byte, 16) uuidMutex.Lock() _, _ = uuidRand.Read(uuid) uuidMutex.Unlock() // variant bits; see section 4.1.1 uuid[8] = uuid[8]&^0xc0 | 0x80 // version 4 (pseudo-random); see section 4.1.3 uuid[6] = uuid[6]&^0xf0 | 0x40 return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]) }
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/shell.go#L129-L139
func (s *Shell) Cat(path string) (io.ReadCloser, error) { resp, err := s.Request("cat", path).Send(context.Background()) if err != nil { return nil, err } if resp.Error != nil { return nil, resp.Error } return resp.Output, nil }
https://github.com/ip2location/ip2location-go/blob/a417f19539fd2a0eb0adf273b4190241cacc0499/ip2location.go#L389-L411
func loadmessage (mesg string) IP2Locationrecord { var x IP2Locationrecord x.Country_short = mesg x.Country_long = mesg x.Region = mesg x.City = mesg x.Isp = mesg x.Domain = mesg x.Zipcode = mesg x.Timezone = mesg x.Netspeed = mesg x.Iddcode = mesg x.Areacode = mesg x.Weatherstationcode = mesg x.Weatherstationname = mesg x.Mcc = mesg x.Mnc = mesg x.Mobilebrand = mesg x.Usagetype = mesg return x }
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/goxpath.go#L34-L40
func MustParse(xp string) XPathExec { ret, err := Parse(xp) if err != nil { panic(err) } return ret }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/expect/expect.go#L47-L50
func NewExpect(name string, arg ...string) (ep *ExpectProcess, err error) { // if env[] is nil, use current system env return NewExpectWithEnv(name, arg, nil) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/mason/storage.go#L43-L45
func (s *Storage) AddConfig(conf common.ResourcesConfig) error { return s.configs.Add(conf) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L265-L270
func DispatchTouchEvent(typeVal TouchType, touchPoints []*TouchPoint) *DispatchTouchEventParams { return &DispatchTouchEventParams{ Type: typeVal, TouchPoints: touchPoints, } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/node.go#L70-L80
func newDir(store *store, nodePath string, createdIndex uint64, parent *node, expireTime time.Time) *node { return &node{ Path: nodePath, CreatedIndex: createdIndex, ModifiedIndex: createdIndex, Parent: parent, ExpireTime: expireTime, Children: make(map[string]*node), store: store, } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps.go#L300-L308
func (c APIClient) DeleteJob(jobID string) error { _, err := c.PpsAPIClient.DeleteJob( c.Ctx(), &pps.DeleteJobRequest{ Job: NewJob(jobID), }, ) return grpcutil.ScrubGRPC(err) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4127-L4135
func (u OperationResultTr) MustChangeTrustResult() ChangeTrustResult { val, ok := u.GetChangeTrustResult() if !ok { panic("arm ChangeTrustResult is not set") } return val }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L2512-L2516
func (v *RuleUsage) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoCss23(&r, v) return r.Error() }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L125-L128
func (img *IplImage) GetCOI() int { coi := C.cvGetImageCOI((*C.IplImage)(img)) return int(coi) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/container_metadata.go#L206-L263
func containerMetadataTemplatesPostPut(d *Daemon, r *http.Request) Response { project := projectParam(r) name := mux.Vars(r)["name"] // Handle requests targeted to a container on a different node response, err := ForwardedResponseIfContainerIsRemote(d, r, project, name) if err != nil { return SmartError(err) } if response != nil { return response } // Load the container c, err := containerLoadByProjectAndName(d.State(), project, name) if err != nil { return SmartError(err) } // Start the storage if needed ourStart, err := c.StorageStart() if err != nil { return SmartError(err) } if ourStart { defer c.StorageStop() } // Look at the request templateName := r.FormValue("path") if templateName == "" { return BadRequest(fmt.Errorf("missing path argument")) } // Check if the template already exists templatePath, err := getContainerTemplatePath(c, templateName) if err != nil { return SmartError(err) } if r.Method == "POST" && shared.PathExists(templatePath) { return BadRequest(fmt.Errorf("Template already exists")) } // Write the new template template, err := os.OpenFile(templatePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { return SmartError(err) } defer template.Close() _, err = io.Copy(template, r.Body) if err != nil { return InternalError(err) } return EmptySyncResponse }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L969-L973
func (v *GetVersionReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoBrowser9(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps.go#L649-L655
func (c APIClient) GarbageCollect(memoryBytes int64) error { _, err := c.PpsAPIClient.GarbageCollect( c.Ctx(), &pps.GarbageCollectRequest{MemoryBytes: memoryBytes}, ) return grpcutil.ScrubGRPC(err) }
https://github.com/enaml-ops/enaml/blob/4f847ee10b41afca41fe09fa839cb2f6ade06fb5/run/diffcmd.go#L29-L40
func (s *DiffCmd) All(w io.Writer) error { differ, err := diff.New(s.releaseRepo, s.release1, s.release2) if err != nil { return err } d, err := differ.Diff() if err != nil { return err } s.printDiffResult(w, d) return nil }
https://github.com/libp2p/go-libp2p-net/blob/a60cde50df6872512892ca85019341d281f72a42/notifiee.go#L59-L63
func (nb *NotifyBundle) ClosedStream(n Network, s Stream) { if nb.ClosedStreamF != nil { nb.ClosedStreamF(n, s) } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pfs.go#L1129-L1138
func (c APIClient) ListFileHistory(repoName string, commitID string, path string, history int64) ([]*pfs.FileInfo, error) { var result []*pfs.FileInfo if err := c.ListFileF(repoName, commitID, path, history, func(fi *pfs.FileInfo) error { result = append(result, fi) return nil }); err != nil { return nil, err } return result, nil }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/httputil/response.go#L35-L37
func ResponseStatus(w http.ResponseWriter) int { return int(httpResponseStruct(reflect.ValueOf(w)).FieldByName("status").Int()) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/schema/schema.go#L55-L79
func NewFromMap(versionsToUpdates map[int]Update) *Schema { // Collect all version keys. versions := []int{} for version := range versionsToUpdates { versions = append(versions, version) } // Sort the versions, sort.Sort(sort.IntSlice(versions)) // Build the updates slice. updates := []Update{} for i, version := range versions { // Assert that we start from 1 and there are no gaps. if version != i+1 { panic(fmt.Sprintf("updates map misses version %d", i+1)) } updates = append(updates, versionsToUpdates[version]) } return &Schema{ updates: updates, } }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/part.go#L91-L98
func (p *Part) TextContent() bool { if p.ContentType == "" { // RFC 2045: no CT is equivalent to "text/plain; charset=us-ascii" return true } return strings.HasPrefix(p.ContentType, "text/") || strings.HasPrefix(p.ContentType, ctMultipartPrefix) }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selectable.go#L172-L174
func (s *selectable) AllByName(name string) *MultiSelection { return newMultiSelection(s.session, s.selectors.Append(target.Name, name)) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/storage/chunk/writer.go#L99-L118
func (w *Writer) Write(data []byte) (int, error) { offset := 0 size := w.buf.Len() for i, b := range data { size++ w.hash.Roll(b) if w.hash.Sum64()&w.splitMask == 0 { w.buf.Write(data[offset : i+1]) if err := w.put(); err != nil { return 0, err } w.buf.Reset() offset = i + 1 size = 0 } } w.buf.Write(data[offset:]) w.rangeSize += int64(len(data)) return len(data), nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2844-L2853
func (u PathPaymentResult) GetSuccess() (result PathPaymentResultSuccess, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Code)) if armName == "Success" { result = *u.Success ok = true } return }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L3039-L3043
func (v GetResourceContentReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage32(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pubsub/subscriber/subscriber.go#L56-L68
func (pe *PeriodicProwJobEvent) ToMessage() (*pubsub.Message, error) { data, err := json.Marshal(pe) if err != nil { return nil, err } message := pubsub.Message{ Data: data, Attributes: map[string]string{ prowEventType: periodicProwJobEvent, }, } return &message, nil }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/worker/worker.go#L12-L29
func MatchDatum(filter []string, data []*pps.InputFile) bool { // All paths in request.DataFilters must appear somewhere in the log // line's inputs, or it's filtered matchesData := true dataFilters: for _, dataFilter := range filter { for _, datum := range data { if dataFilter == datum.Path || dataFilter == base64.StdEncoding.EncodeToString(datum.Hash) || dataFilter == hex.EncodeToString(datum.Hash) { continue dataFilters // Found, move to next filter } } matchesData = false break } return matchesData }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/install.go#L27-L60
func installHostAdd(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { allowed := permission.Check(t, permission.PermInstallManage) if !allowed { return permission.ErrUnauthorized } var host *install.Host err = ParseInput(r, &host) if err != nil { return err } evt, err := event.New(&event.Opts{ Target: event.Target{Type: event.TargetTypeInstallHost, Value: host.Name}, Kind: permission.PermInstallManage, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermInstallManage), }) if err != nil { return err } defer func() { evt.Done(err) }() var rawDriver map[string]interface{} err = json.Unmarshal([]byte(r.Form.Get("driver")), &rawDriver) if err != nil { return err } host.Driver = rawDriver err = install.AddHost(host) if err != nil { return err } w.WriteHeader(http.StatusCreated) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/layertree/easyjson.go#L1773-L1777
func (v *EventLayerTreeDidChange) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoLayertree15(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/database/easyjson.go#L99-L103
func (v GetDatabaseTableNamesReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDatabase(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/db.go#L357-L362
func (c *Cluster) Close() error { for _, stmt := range c.stmts { stmt.Close() } return c.db.Close() }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/retry.go#L103-L107
func RetryKVClient(c *Client) pb.KVClient { return &retryKVClient{ kc: pb.NewKVClient(c.conn), } }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/flash.go#L24-L26
func (f Flash) Set(key string, values []string) { f.data[key] = values }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/configuration.go#L158-L185
func checkConfiguration(configuration Configuration) error { idSet := make(map[ServerID]bool) addressSet := make(map[ServerAddress]bool) var voters int for _, server := range configuration.Servers { if server.ID == "" { return fmt.Errorf("Empty ID in configuration: %v", configuration) } if server.Address == "" { return fmt.Errorf("Empty address in configuration: %v", server) } if idSet[server.ID] { return fmt.Errorf("Found duplicate ID in configuration: %v", server.ID) } idSet[server.ID] = true if addressSet[server.Address] { return fmt.Errorf("Found duplicate address in configuration: %v", server.Address) } addressSet[server.Address] = true if server.Suffrage == Voter { voters++ } } if voters == 0 { return fmt.Errorf("Need at least one voter in configuration: %v", configuration) } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domsnapshot/easyjson.go#L574-L578
func (v *RareIntegerData) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDomsnapshot2(&r, v) return r.Error() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L4337-L4341
func (v *GetResponseBodyForInterceptionParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork31(&r, v) return r.Error() }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L5378-L5385
func (r *MultiCloudImage) Locator(api *API) *MultiCloudImageLocator { for _, l := range r.Links { if l["rel"] == "self" { return api.MultiCloudImageLocator(l["href"]) } } return nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/listener.go#L333-L357
func (info TLSInfo) ServerConfig() (*tls.Config, error) { cfg, err := info.baseConfig() if err != nil { return nil, err } cfg.ClientAuth = tls.NoClientCert if info.TrustedCAFile != "" || info.ClientCertAuth { cfg.ClientAuth = tls.RequireAndVerifyClientCert } cs := info.cafiles() if len(cs) > 0 { cp, err := tlsutil.NewCertPool(cs) if err != nil { return nil, err } cfg.ClientCAs = cp } // "h2" NextProtos is necessary for enabling HTTP2 for go's HTTP server cfg.NextProtos = []string{"h2"} return cfg, nil }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/usermanagment.go#L166-L171
func (c *Client) ListGroups() (*Groups, error) { url := umGroups() + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &Groups{} err := c.client.Get(url, ret, http.StatusOK) return ret, err }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistriesv2/system_registries_v2.go#L381-L402
func FindRegistry(ctx *types.SystemContext, ref string) (*Registry, error) { registries, err := GetRegistries(ctx) if err != nil { return nil, err } reg := Registry{} prefixLen := 0 for _, r := range registries { if refMatchesPrefix(ref, r.Prefix) { length := len(r.Prefix) if length > prefixLen { reg = r prefixLen = length } } } if prefixLen != 0 { return &reg, nil } return nil, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L136-L139
func (p DescribeNodeParams) WithNodeID(nodeID cdp.NodeID) *DescribeNodeParams { p.NodeID = nodeID return &p }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/cmd_registrar.go#L29-L107
func (r *Registrar) RegisterActionCommands(apiName string, res map[string]*metadata.Resource, cmds ActionCommands) { // Add special "actions" action _, ok := cmds[fmt.Sprintf("%s %s", r.APICmd.FullCommand(), "actions")] if !ok { pattern := "List all %s actions and associated hrefs. If a resource href is provided only list actions for that resource." description := fmt.Sprintf(pattern, apiName) actionsCmd := r.APICmd.Command("actions", description) actionsCmdValue := ActionCommand{} hrefMsg := "Href of resource to show actions for." actionsCmd.Arg("href", hrefMsg).StringVar(&actionsCmdValue.Href) cmds[actionsCmd.FullCommand()] = &actionsCmdValue } // Add resource actions var actionNames []string for _, r := range res { for _, a := range r.Actions { name := a.Name exists := false for _, e := range actionNames { if e == name { exists = true break } } if !exists { actionNames = append(actionNames, name) } } } sort.Strings(actionNames) for _, action := range actionNames { if _, ok := cmds[fmt.Sprintf("%s %s", r.APICmd.FullCommand(), action)]; ok { continue // Already registered - can happen with SS where multiple APIs are registered under the same command } resources := []string{} var description string for name, resource := range res { for _, a := range resource.Actions { if a.Name == action { if description == "" { description = a.Description } resources = append(resources, name) } } } if len(resources) > 1 || description == "" { switch action { case "show": description = "Show information about a single resource." case "index": description = "Lists all resources of given type in account." case "create": description = "Create new resource." case "update": description = "Update existing resource." case "destroy": description = "Destroy a single resource." default: if len(resources) > 1 { description = "Action of resources " + strings.Join(resources[:len(resources)-1], ", ") + " and " + resources[len(resources)-1] } else { description = "<no description provided>" } } } actionCmd := r.APICmd.Command(action, description) actionCmdValue := ActionCommand{} hrefMsg := "API Resource or resource collection href on which to act, e.g. '/api/servers'" paramsMsg := "Action parameters in the form QUERY=VALUE, e.g. 'server[name]=server42'" actionCmd.Arg("href", hrefMsg).Required().StringVar(&actionCmdValue.Href) actionCmd.Arg("params", paramsMsg).StringsVar(&actionCmdValue.Params) cmds[actionCmd.FullCommand()] = &actionCmdValue } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/types.go#L191-L193
func (t TransferMode) MarshalEasyJSON(out *jwriter.Writer) { out.String(string(t)) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L668-L686
func (c *Cluster) StoragePoolVolumesGetNames(poolID int64) ([]string, error) { var volumeName string query := "SELECT name FROM storage_volumes WHERE storage_pool_id=? AND node_id=?" inargs := []interface{}{poolID, c.nodeID} outargs := []interface{}{volumeName} result, err := queryScan(c.db, query, inargs, outargs) if err != nil { return []string{}, err } var out []string for _, r := range result { out = append(out, r[0].(string)) } return out, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/pjutil/tot.go#L80-L114
func GetBuildID(name, totURL string) (string, error) { if totURL == "" { return node.Generate().String(), nil } var err error url, err := url.Parse(totURL) if err != nil { return "", fmt.Errorf("invalid tot url: %v", err) } url.Path = path.Join(url.Path, "vend", name) sleepDuration := 100 * time.Millisecond for retries := 0; retries < 10; retries++ { if retries > 0 { sleep(sleepDuration) sleepDuration = sleepDuration * 2 } var resp *http.Response resp, err = http.Get(url.String()) if err != nil { continue } defer resp.Body.Close() if resp.StatusCode != 200 { err = fmt.Errorf("got unexpected response from tot: %v", resp.Status) continue } var buf []byte buf, err = ioutil.ReadAll(resp.Body) if err == nil { return string(buf), nil } return "", err } return "", err }
https://github.com/ipfs/go-ipfs-api/blob/a1b28da48b3763f67654ec4cfcba5fcbfb3dfb32/unixfs.go#L27-L38
func (s *Shell) FileList(path string) (*UnixLsObject, error) { var out lsOutput if err := s.Request("file/ls", path).Exec(context.Background(), &out); err != nil { return nil, err } for _, object := range out.Objects { return object, nil } return nil, fmt.Errorf("no object in results") }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/dag/dag.go#L11-L21
func NewDAG(nodes map[string][]string) *DAG { result := &DAG{ parents: make(map[string][]string), children: make(map[string][]string), leaves: make(map[string]bool), } for id, parents := range nodes { result.NewNode(id, parents) } return result }
https://github.com/btcsuite/btclog/blob/84c8d2346e9fc8c7b947e243b9c24e6df9fd206a/log.go#L344-L349
func (l *slog) Tracef(format string, args ...interface{}) { lvl := l.Level() if lvl <= LevelTrace { l.b.printf("TRC", l.tag, format, args...) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/webaudio/easyjson.go#L737-L741
func (v BaseAudioContext) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoWebaudio8(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L613-L617
func (v *StopTypeProfileParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoProfiler6(&r, v) return r.Error() }
https://github.com/onsi/gomega/blob/f0e010e04c08c48a875f83d17df37b04eb3a985b/gomega_dsl.go#L163-L168
func ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) Assertion { if globalFailWrapper == nil { panic(nilFailHandlerPanic) } return assertion.New(actual, globalFailWrapper, offset, extra...) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L393-L397
func (ref Uint16Ref) Update(n uint16) { if ref != nil { binary.BigEndian.PutUint16(ref, n) } }
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/web/server.go#L122-L131
func (s *Server) Stop() { if s.isStarted && s.quit != nil { log.Info("Lunarc is stopping...") s.quit <- true } else { log.Info("Lunarc is not running") s.Error <- errors.New("Lunarc is not running") s.Done <- false } }
https://github.com/armon/go-radix/blob/1a2de0c21c94309923825da3df33a4381872c795/radix.go#L237-L290
func (t *Tree) Delete(s string) (interface{}, bool) { var parent *node var label byte n := t.root search := s for { // Check for key exhaution if len(search) == 0 { if !n.isLeaf() { break } goto DELETE } // Look for an edge parent = n label = search[0] n = n.getEdge(label) if n == nil { break } // Consume the search prefix if strings.HasPrefix(search, n.prefix) { search = search[len(n.prefix):] } else { break } } return nil, false DELETE: // Delete the leaf leaf := n.leaf n.leaf = nil t.size-- // Check if we should delete this node from the parent if parent != nil && len(n.edges) == 0 { parent.delEdge(label) } // Check if we should merge this node if n != t.root && len(n.edges) == 1 { n.mergeChild() } // Check if we should merge the parent's other child if parent != nil && parent != t.root && len(parent.edges) == 1 && !parent.isLeaf() { parent.mergeChild() } return leaf.val, true }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/reporter/reporter.go#L40-L46
func NewReporter(gc report.GitHubClient, cfg config.Getter, reportAgent v1.ProwJobAgent) *Client { return &Client{ gc: gc, config: cfg, reportAgent: reportAgent, } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/crossdock/client/client.go#L54-L68
func (c *Client) listen() error { c.setDefaultPort(&c.ClientHostPort, ":"+common.DefaultClientPortHTTP) c.setDefaultPort(&c.ServerPort, common.DefaultServerPort) c.mux = http.NewServeMux() // Using default mux creates problem in unit tests c.mux.Handle("/", crossdock.Handler(c.Behaviors, true)) listener, err := net.Listen("tcp", c.ClientHostPort) if err != nil { return err } c.listener = listener c.ClientHostPort = listener.Addr().String() // override in case it was ":0" return nil }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L144-L149
func NewMergeIterator(iters []Iterator, reversed bool) *MergeIterator { m := &MergeIterator{all: iters, reversed: reversed} m.h = make(elemHeap, 0, len(iters)) m.initHeap() return m }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/coal/indexer.go#L63-L68
func (i *Indexer) AddRaw(coll string, idx mgo.Index) { i.indexes = append(i.indexes, index{ coll: coll, index: idx, }) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/cmd/worker/main.go#L104-L125
func getPipelineInfo(pachClient *client.APIClient, env *serviceenv.ServiceEnv) (*pps.PipelineInfo, error) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() resp, err := env.GetEtcdClient().Get(ctx, path.Join(env.PPSEtcdPrefix, "pipelines", env.PPSPipelineName)) if err != nil { return nil, err } if len(resp.Kvs) != 1 { return nil, fmt.Errorf("expected to find 1 pipeline (%s), got %d: %v", env.PPSPipelineName, len(resp.Kvs), resp) } var pipelinePtr pps.EtcdPipelineInfo if err := pipelinePtr.Unmarshal(resp.Kvs[0].Value); err != nil { return nil, err } pachClient.SetAuthToken(pipelinePtr.AuthToken) // Notice we use the SpecCommitID from our env, not from etcd. This is // because the value in etcd might get updated while the worker pod is // being created and we don't want to run the transform of one version of // the pipeline in the image of a different verison. pipelinePtr.SpecCommit.ID = env.PPSSpecCommitID return ppsutil.GetPipelineInfo(pachClient, &pipelinePtr, true) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/raft.go#L685-L734
func createConfigChangeEnts(lg *zap.Logger, ids []uint64, self uint64, term, index uint64) []raftpb.Entry { ents := make([]raftpb.Entry, 0) next := index + 1 found := false for _, id := range ids { if id == self { found = true continue } cc := &raftpb.ConfChange{ Type: raftpb.ConfChangeRemoveNode, NodeID: id, } e := raftpb.Entry{ Type: raftpb.EntryConfChange, Data: pbutil.MustMarshal(cc), Term: term, Index: next, } ents = append(ents, e) next++ } if !found { m := membership.Member{ ID: types.ID(self), RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://localhost:2380"}}, } ctx, err := json.Marshal(m) if err != nil { if lg != nil { lg.Panic("failed to marshal member", zap.Error(err)) } else { plog.Panicf("marshal member should never fail: %v", err) } } cc := &raftpb.ConfChange{ Type: raftpb.ConfChangeAddNode, NodeID: self, Context: ctx, } e := raftpb.Entry{ Type: raftpb.EntryConfChange, Data: pbutil.MustMarshal(cc), Term: term, Index: next, } ents = append(ents, e) } return ents }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/context_builder.go#L164-L167
func (cb *ContextBuilder) SetRetryOptions(retryOptions *RetryOptions) *ContextBuilder { cb.RetryOptions = retryOptions return cb }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/fetcher/client.go#L99-L118
func (client *Client) limitsCheckAndWait() { var sleep time.Duration githubClient, err := client.getGitHubClient() if err != nil { glog.Error("Failed to get RateLimits: ", err) sleep = time.Minute } else { limits, _, err := githubClient.RateLimits(context.Background()) if err != nil { glog.Error("Failed to get RateLimits:", err) sleep = time.Minute } if limits != nil && limits.Core != nil && limits.Core.Remaining < tokenLimit { sleep = limits.Core.Reset.Sub(time.Now()) glog.Warning("RateLimits: reached. Sleeping for ", sleep) } } time.Sleep(sleep) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/client.go#L321-L331
func NewClientFromFile(clusterPath, namespace string) (*Client, error) { data, err := ioutil.ReadFile(clusterPath) if err != nil { return nil, err } var c Cluster if err := yaml.Unmarshal(data, &c); err != nil { return nil, err } return NewClient(&c, namespace) }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/skus/m1small/m1small.go#L26-L39
func (s *SkuM1Small) StartPoller(requestID string, task *taskmanager.Task) (err error) { var ( clnt innkeeperclient.InnkeeperClient resp innkeeperclient.GetStatusResponse ) if clnt, err = s.GetInnkeeperClient(); err == nil { if resp, err = s.waitForStatusComplete(requestID, clnt); err == nil { s.updateTaskForStatusComplete(task, resp) } } return }
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/skus/m1small/types.go#L31-L35
func Init() { s := new(SkuM1SmallBuilder) s.Client, _ = new(SkuM1Small).GetInnkeeperClient() skurepo.Register(SkuName, s) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L6261-L6264
func (e MessageType) ValidEnum(v int32) bool { _, ok := messageTypeMap[v] return ok }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L2652-L2656
func (v GetIsolateIDReturns) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime23(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/tracing.go#L172-L195
func InjectOutboundSpan(response *OutboundCallResponse, headers map[string]string) map[string]string { span := response.span if span == nil { return headers } newHeaders := make(map[string]string) carrier := tracingHeadersCarrier(newHeaders) if err := span.Tracer().Inject(span.Context(), opentracing.TextMap, carrier); err != nil { // Something had to go seriously wrong for Inject to fail, usually a setup problem. // A good Tracer implementation may also emit a metric. response.log.WithFields(ErrField(err)).Error("Failed to inject tracing span.") } if len(newHeaders) == 0 { return headers // Tracer did not add any tracing headers, so return the original map } for k, v := range headers { // Some applications propagate all inbound application headers to outbound calls (issue #682). // If those headers include tracing headers we want to make sure to keep the new tracing headers. if _, ok := newHeaders[k]; !ok { newHeaders[k] = v } } return newHeaders }
https://github.com/codegangsta/martini-contrib/blob/8ce6181c2609699e4c7cd30994b76a850a9cdadc/render/render.go#L107-L119
func Renderer(options ...Options) martini.Handler { opt := prepareOptions(options) cs := prepareCharset(opt.Charset) t := compile(opt) return func(res http.ResponseWriter, req *http.Request, c martini.Context) { // recompile for easy development if martini.Env == martini.Dev { t = compile(opt) } tc, _ := t.Clone() c.MapTo(&renderer{res, req, tc, opt, cs}, (*Render)(nil)) } }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/access_barrier.go#L141-L155
func (ab *AccessBarrier) Acquire() *BarrierSession { if ab.active { retry: bs := (*BarrierSession)(atomic.LoadPointer(&ab.session)) liveCount := atomic.AddInt32(bs.liveCount, 1) if liveCount > barrierFlushOffset { ab.Release(bs) goto retry } return bs } return nil }
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/decoder.go#L183-L193
func DecodeFloat64(bz []byte) (f float64, n int, err error) { const size int = 8 if len(bz) < size { err = errors.New("EOF decoding float64") return } i := binary.LittleEndian.Uint64(bz[:size]) f = math.Float64frombits(i) n = size return }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L693-L711
func (m *member) listenGRPC() error { // prefix with localhost so cert has right domain m.grpcAddr = "localhost:" + m.Name if m.useIP { // for IP-only TLS certs m.grpcAddr = "127.0.0.1:" + m.Name } l, err := transport.NewUnixListener(m.grpcAddr) if err != nil { return fmt.Errorf("listen failed on grpc socket %s (%v)", m.grpcAddr, err) } m.grpcBridge, err = newBridge(m.grpcAddr) if err != nil { l.Close() return err } m.grpcAddr = schemeFromTLSInfo(m.ClientTLSInfo) + "://" + m.grpcBridge.inaddr m.grpcListener = l return nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/configuration.go#L137-L143
func (c *configurations) Clone() (copy configurations) { copy.committed = c.committed.Clone() copy.committedIndex = c.committedIndex copy.latest = c.latest.Clone() copy.latestIndex = c.latestIndex return }
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/node_alloc_amd64.go#L276-L285
func debugMarkFree(n *Node) { var block []byte l := int(nodeTypes[n.level].Size()) sh := (*reflect.SliceHeader)(unsafe.Pointer(&block)) sh.Data = uintptr(unsafe.Pointer(n)) sh.Len = l sh.Cap = l copy(block, freeBlockContent) }
https://github.com/adamzy/cedar-go/blob/80a9c64b256db37ac20aff007907c649afb714f1/io.go#L41-L51
func (da *Cedar) Load(in io.Reader, dataType string) error { switch dataType { case "gob", "GOB": dataDecoder := gob.NewDecoder(in) return dataDecoder.Decode(da.cedar) case "json", "JSON": dataDecoder := json.NewDecoder(in) return dataDecoder.Decode(da.cedar) } return ErrInvalidDataType }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/registry.go#L114-L121
func GetAttributes(err error) Attributes { e, ok := err.(Error) if ok { return e.Attributes() } return Attributes{} }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/codegen_client.go#L839-L846
func (r *AuditEntry) Locator(api *API) *AuditEntryLocator { for _, l := range r.Links { if l["rel"] == "self" { return api.AuditEntryLocator(l["href"]) } } return nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/api.go#L938-L996
func (r *Raft) Stats() map[string]string { toString := func(v uint64) string { return strconv.FormatUint(v, 10) } lastLogIndex, lastLogTerm := r.getLastLog() lastSnapIndex, lastSnapTerm := r.getLastSnapshot() s := map[string]string{ "state": r.getState().String(), "term": toString(r.getCurrentTerm()), "last_log_index": toString(lastLogIndex), "last_log_term": toString(lastLogTerm), "commit_index": toString(r.getCommitIndex()), "applied_index": toString(r.getLastApplied()), "fsm_pending": toString(uint64(len(r.fsmMutateCh))), "last_snapshot_index": toString(lastSnapIndex), "last_snapshot_term": toString(lastSnapTerm), "protocol_version": toString(uint64(r.protocolVersion)), "protocol_version_min": toString(uint64(ProtocolVersionMin)), "protocol_version_max": toString(uint64(ProtocolVersionMax)), "snapshot_version_min": toString(uint64(SnapshotVersionMin)), "snapshot_version_max": toString(uint64(SnapshotVersionMax)), } future := r.GetConfiguration() if err := future.Error(); err != nil { r.logger.Warn(fmt.Sprintf("could not get configuration for Stats: %v", err)) } else { configuration := future.Configuration() s["latest_configuration_index"] = toString(future.Index()) s["latest_configuration"] = fmt.Sprintf("%+v", configuration.Servers) // This is a legacy metric that we've seen people use in the wild. hasUs := false numPeers := 0 for _, server := range configuration.Servers { if server.Suffrage == Voter { if server.ID == r.localID { hasUs = true } else { numPeers++ } } } if !hasUs { numPeers = 0 } s["num_peers"] = toString(uint64(numPeers)) } last := r.LastContact() if r.getState() == Leader { s["last_contact"] = "0" } else if last.IsZero() { s["last_contact"] = "never" } else { s["last_contact"] = fmt.Sprintf("%v", time.Now().Sub(last)) } return s }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/client.go#L271-L282
func (p *PactClient) PublishPacts(request types.PublishRequest) error { svc := p.publishSvcManager.NewService(request.Args) log.Println("[DEBUG] about to publish pacts") cmd := svc.Start() log.Println("[DEBUG] waiting for response") err := cmd.Wait() log.Println("[DEBUG] response from publish", err) return err }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/codegen_client.go#L1323-L1325
func (r *NetworkInterface) Locator(api *API) *NetworkInterfaceLocator { return api.NetworkInterfaceLocator(r.Href) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L1806-L1810
func (v Bucket) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser20(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/apply_v2.go#L116-L134
func (s *EtcdServer) applyV2Request(r *RequestV2) Response { defer warnOfExpensiveRequest(s.getLogger(), time.Now(), r, nil, nil) switch r.Method { case "POST": return s.applyV2.Post(r) case "PUT": return s.applyV2.Put(r) case "DELETE": return s.applyV2.Delete(r) case "QGET": return s.applyV2.QGet(r) case "SYNC": return s.applyV2.Sync(r) default: // This should never be reached, but just in case: return Response{Err: ErrUnknownMethod} } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/listener.go#L237-L321
func (info TLSInfo) baseConfig() (*tls.Config, error) { if info.KeyFile == "" || info.CertFile == "" { return nil, fmt.Errorf("KeyFile and CertFile must both be present[key: %v, cert: %v]", info.KeyFile, info.CertFile) } if info.Logger == nil { info.Logger = zap.NewNop() } _, err := tlsutil.NewCert(info.CertFile, info.KeyFile, info.parseFunc) if err != nil { return nil, err } cfg := &tls.Config{ MinVersion: tls.VersionTLS12, ServerName: info.ServerName, } if len(info.CipherSuites) > 0 { cfg.CipherSuites = info.CipherSuites } if info.AllowedCN != "" { cfg.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { for _, chains := range verifiedChains { if len(chains) != 0 { if info.AllowedCN == chains[0].Subject.CommonName { return nil } } } return errors.New("CommonName authentication failed") } } // this only reloads certs when there's a client request // TODO: support server-side refresh (e.g. inotify, SIGHUP), caching cfg.GetCertificate = func(clientHello *tls.ClientHelloInfo) (cert *tls.Certificate, err error) { cert, err = tlsutil.NewCert(info.CertFile, info.KeyFile, info.parseFunc) if os.IsNotExist(err) { if info.Logger != nil { info.Logger.Warn( "failed to find peer cert files", zap.String("cert-file", info.CertFile), zap.String("key-file", info.KeyFile), zap.Error(err), ) } } else if err != nil { if info.Logger != nil { info.Logger.Warn( "failed to create peer certificate", zap.String("cert-file", info.CertFile), zap.String("key-file", info.KeyFile), zap.Error(err), ) } } return cert, err } cfg.GetClientCertificate = func(unused *tls.CertificateRequestInfo) (cert *tls.Certificate, err error) { cert, err = tlsutil.NewCert(info.CertFile, info.KeyFile, info.parseFunc) if os.IsNotExist(err) { if info.Logger != nil { info.Logger.Warn( "failed to find client cert files", zap.String("cert-file", info.CertFile), zap.String("key-file", info.KeyFile), zap.Error(err), ) } } else if err != nil { if info.Logger != nil { info.Logger.Warn( "failed to create client certificate", zap.String("cert-file", info.CertFile), zap.String("key-file", info.KeyFile), zap.Error(err), ) } } return cert, err } return cfg, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/apis/prowjobs/v1/zz_generated.deepcopy.go#L64-L71
func (in *DecorationConfig) DeepCopy() *DecorationConfig { if in == nil { return nil } out := new(DecorationConfig) in.DeepCopyInto(out) return out }
https://github.com/giantswarm/certctl/blob/2a6615f61499cd09a8d5ced9a5fade322d2de254/service/role/service.go#L55-L71
func (s *service) Create(params CreateParams) error { logicalStore := s.vaultClient.Logical() data := map[string]interface{}{ "allowed_domains": params.AllowedDomains, "allow_subdomains": params.AllowSubdomains, "ttl": params.TTL, "allow_bare_domains": params.AllowBareDomains, "organization": params.Organizations, } _, err := logicalStore.Write(fmt.Sprintf("%s/roles/%s", s.pkiMountpoint, params.Name), data) if err != nil { return microerror.Mask(err) } return nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/snapshot.go#L122-L207
func (r *Raft) takeSnapshot() (string, error) { defer metrics.MeasureSince([]string{"raft", "snapshot", "takeSnapshot"}, time.Now()) // Create a request for the FSM to perform a snapshot. snapReq := &reqSnapshotFuture{} snapReq.init() // Wait for dispatch or shutdown. select { case r.fsmSnapshotCh <- snapReq: case <-r.shutdownCh: return "", ErrRaftShutdown } // Wait until we get a response if err := snapReq.Error(); err != nil { if err != ErrNothingNewToSnapshot { err = fmt.Errorf("failed to start snapshot: %v", err) } return "", err } defer snapReq.snapshot.Release() // Make a request for the configurations and extract the committed info. // We have to use the future here to safely get this information since // it is owned by the main thread. configReq := &configurationsFuture{} configReq.init() select { case r.configurationsCh <- configReq: case <-r.shutdownCh: return "", ErrRaftShutdown } if err := configReq.Error(); err != nil { return "", err } committed := configReq.configurations.committed committedIndex := configReq.configurations.committedIndex // We don't support snapshots while there's a config change outstanding // since the snapshot doesn't have a means to represent this state. This // is a little weird because we need the FSM to apply an index that's // past the configuration change, even though the FSM itself doesn't see // the configuration changes. It should be ok in practice with normal // application traffic flowing through the FSM. If there's none of that // then it's not crucial that we snapshot, since there's not much going // on Raft-wise. if snapReq.index < committedIndex { return "", fmt.Errorf("cannot take snapshot now, wait until the configuration entry at %v has been applied (have applied %v)", committedIndex, snapReq.index) } // Create a new snapshot. r.logger.Info(fmt.Sprintf("Starting snapshot up to %d", snapReq.index)) start := time.Now() version := getSnapshotVersion(r.protocolVersion) sink, err := r.snapshots.Create(version, snapReq.index, snapReq.term, committed, committedIndex, r.trans) if err != nil { return "", fmt.Errorf("failed to create snapshot: %v", err) } metrics.MeasureSince([]string{"raft", "snapshot", "create"}, start) // Try to persist the snapshot. start = time.Now() if err := snapReq.snapshot.Persist(sink); err != nil { sink.Cancel() return "", fmt.Errorf("failed to persist snapshot: %v", err) } metrics.MeasureSince([]string{"raft", "snapshot", "persist"}, start) // Close and check for error. if err := sink.Close(); err != nil { return "", fmt.Errorf("failed to close snapshot: %v", err) } // Update the last stable snapshot info. r.setLastSnapshot(snapReq.index, snapReq.term) // Compact the logs. if err := r.compactLogs(snapReq.index); err != nil { return "", err } r.logger.Info(fmt.Sprintf("Snapshot to %d complete", snapReq.index)) return sink.ID(), nil }
https://github.com/golang/debug/blob/19561fee47cf8cd0400d1b094c5898002f97cf90/internal/core/read.go#L33-L39
func (p *Process) ReadUint8(a Address) uint8 { m := p.findMapping(a) if m == nil { panic(fmt.Errorf("address %x is not mapped in the core file", a)) } return m.contents[a.Sub(m.min)] }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/limit_listen.go#L32-L34
func LimitListener(l net.Listener, n int) net.Listener { return &limitListener{l, make(chan struct{}, n)} }