_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/qor/action_bar/blob/136e5e2c5b8c50976dc39edddf523fcaab0a73b8/action_bar.go#L82-L84
func (bar *ActionBar) EditMode(w http.ResponseWriter, r *http.Request) bool { return isEditMode(bar.Admin.NewContext(w, r)) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/fetch/fetch.go#L65-L68
func (p EnableParams) WithHandleAuthRequests(handleAuthRequests bool) *EnableParams { p.HandleAuthRequests = handleAuthRequests return &p }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/asset.go#L45-L52
func (a *Asset) SetNative() error { newa, err := NewAsset(AssetTypeAssetTypeNative, nil) if err != nil { return err } *a = newa return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/plugins.go#L74-L77
func RegisterIssueCommentHandler(name string, fn IssueCommentHandler, help HelpProvider) { pluginHelp[name] = help issueCommentHandlers[name] = fn }
https://github.com/ianschenck/envflag/blob/9111d830d133f952887a936367fb0211c3134f0d/envflag.go#L102-L104
func Uint(name string, value uint, usage string) *uint { return EnvironmentFlags.Uint(name, value, usage) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_ceph_utils.go#L69-L81
func cephRBDVolumeCreate(clusterName string, poolName string, volumeName string, volumeType string, size string, userName string) error { _, err := shared.RunCommand( "rbd", "--id", userName, "--image-feature", "layering,", "--cluster", clusterName, "--pool", poolName, "--size", size, "create", fmt.Sprintf("%s_%s", volumeType, volumeName)) return err }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/channel/channel.go#L62-L68
func SendJSON(c context.Context, clientID string, value interface{}) error { m, err := json.Marshal(value) if err != nil { return err } return Send(c, clientID, string(m)) }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/protocol.go#L163-L212
func (res *protocolIntroResults) doIntroV1(params protocolIntroParams, pubKey, privKey *[32]byte) error { features := filterV1Features(params.Features) if pubKey != nil { features["PublicKey"] = hex.EncodeToString(pubKey[:]) } enc := gob.NewEncoder(params.Conn) dec := gob.NewDecoder(params.Conn) // Encode in a separate goroutine to avoid the possibility of // deadlock. The result channel is of size 1 so that the // goroutine does not linger even if we encounter an error on // the read side. encodeDone := make(chan error, 1) go func() { encodeDone <- enc.Encode(features) }() if err := dec.Decode(&res.Features); err != nil { return err } if err := <-encodeDone; err != nil { return err } res.Sender = newGobTCPSender(enc) res.Receiver = newGobTCPReceiver(dec) if pubKey == nil { if _, present := res.Features["PublicKey"]; present { return errExpectedNoCrypto } } else { remotePubKeyStr, ok := res.Features["PublicKey"] if !ok { return errExpectedCrypto } remotePubKey, err := hex.DecodeString(remotePubKeyStr) if err != nil { return err } res.setupCrypto(params, remotePubKey, privKey) } res.Features = filterV1Features(res.Features) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/tracing/types.go#L201-L211
func (t *TransferMode) UnmarshalEasyJSON(in *jlexer.Lexer) { switch TransferMode(in.String()) { case TransferModeReportEvents: *t = TransferModeReportEvents case TransferModeReturnAsStream: *t = TransferModeReturnAsStream default: in.AddError(errors.New("unknown TransferMode value")) } }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/memcache/memcache.go#L345-L347
func CompareAndSwap(c context.Context, item *Item) error { return singleError(set(c, []*Item{item}, nil, pb.MemcacheSetRequest_CAS)) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/hyperbahn/client.go#L158-L161
func addPeer(ch *tchannel.Channel, hostPort string) { peers := ch.GetSubChannel(hyperbahnServiceName).Peers() peers.Add(hostPort) }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/app.go#L1429-L1468
func sleep(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) { process := InputValue(r, "process") appName := r.URL.Query().Get(":app") a, err := getAppFromContext(appName, r) if err != nil { return err } proxy := InputValue(r, "proxy") if proxy == "" { return &errors.HTTP{Code: http.StatusBadRequest, Message: "Empty proxy URL"} } proxyURL, err := url.Parse(proxy) if err != nil { log.Errorf("Invalid url for proxy param: %v", proxy) return err } allowed := permission.Check(t, permission.PermAppUpdateSleep, contextsForApp(&a)..., ) if !allowed { return permission.ErrUnauthorized } evt, err := event.New(&event.Opts{ Target: appTarget(appName), Kind: permission.PermAppUpdateSleep, Owner: t, CustomData: event.FormToCustomData(InputFields(r)), Allowed: event.Allowed(permission.PermAppReadEvents, contextsForApp(&a)...), }) if err != nil { return err } defer func() { evt.Done(err) }() w.Header().Set("Content-Type", "application/x-json-stream") keepAliveWriter := tsuruIo.NewKeepAliveWriter(w, 30*time.Second, "") defer keepAliveWriter.Stop() writer := &tsuruIo.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)} evt.SetLogWriter(writer) return a.Sleep(evt, process, proxyURL) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/patches.go#L96-L102
func patchesGetNames() []string { names := make([]string, len(patches)) for i, patch := range patches { names[i] = patch.name } return names }
https://github.com/rsc/pdf/blob/c47d69cf462f804ff58ca63c61a8fb2aed76587e/read.go#L655-L665
func (v Value) Key(key string) Value { x, ok := v.data.(dict) if !ok { strm, ok := v.data.(stream) if !ok { return Value{} } x = strm.hdr } return v.r.resolve(v.ptr, x[name(key)]) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/operations.go#L284-L300
func (c *ClusterTx) OperationAdd(project, uuid string, typ OperationType) (int64, error) { var projectID interface{} if project != "" { var err error projectID, err = c.ProjectID(project) if err != nil { return -1, errors.Wrap(err, "Fetch project ID") } } else { projectID = nil } columns := []string{"uuid", "node_id", "type", "project_id"} values := []interface{}{uuid, c.nodeID, typ, projectID} return query.UpsertObject(c.tx, "operations", columns, values) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/runner/election_command.go#L28-L36
func NewElectionCommand() *cobra.Command { cmd := &cobra.Command{ Use: "election [election name (defaults to 'elector')]", Short: "Performs election operation", Run: runElectionFunc, } cmd.Flags().IntVar(&totalClientConnections, "total-client-connections", 10, "total number of client connections") return cmd }
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/tree/xmltree/xmlele/xmlele.go#L29-L59
func (x *XMLEle) CreateNode(opts *xmlbuilder.BuilderOpts) xmlbuilder.XMLBuilder { if opts.NodeType == tree.NtElem { ele := &XMLEle{ StartElement: opts.Tok.(xml.StartElement), NSBuilder: tree.NSBuilder{NS: opts.NS}, Attrs: make([]tree.Node, len(opts.Attrs)), Parent: x, NodePos: tree.NodePos(opts.NodePos), NodeType: opts.NodeType, } for i := range opts.Attrs { ele.Attrs[i] = xmlnode.XMLNode{ Token: opts.Attrs[i], NodePos: tree.NodePos(opts.AttrStartPos + i), NodeType: tree.NtAttr, Parent: ele, } } x.Children = append(x.Children, ele) return ele } node := xmlnode.XMLNode{ Token: opts.Tok, NodePos: tree.NodePos(opts.NodePos), NodeType: opts.NodeType, Parent: x, } x.Children = append(x.Children, node) return x }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/css.go#L367-L376
func (p *GetMatchedStylesForNodeParams) Do(ctx context.Context) (inlineStyle *Style, attributesStyle *Style, matchedCSSRules []*RuleMatch, pseudoElements []*PseudoElementMatches, inherited []*InheritedStyleEntry, cssKeyframesRules []*KeyframesRule, err error) { // execute var res GetMatchedStylesForNodeReturns err = cdp.Execute(ctx, CommandGetMatchedStylesForNode, p, &res) if err != nil { return nil, nil, nil, nil, nil, nil, err } return res.InlineStyle, res.AttributesStyle, res.MatchedCSSRules, res.PseudoElements, res.Inherited, res.CSSKeyframesRules, nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/deviceorientation/easyjson.go#L164-L168
func (v *ClearDeviceOrientationOverrideParams) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDeviceorientation1(&r, v) return r.Error() }
https://github.com/Financial-Times/neo-model-utils-go/blob/aea1e95c83055aaed6761c5e546400dd383fb220/mapper/uri_utils.go#L39-L58
func APIURL(uuid string, labels []string, env string) string { base := "http://api.ft.com/" if env == "test" { base = "http://test.api.ft.com/" } path := "" mostSpecific, err := MostSpecificType(labels) if err == nil { for t := mostSpecific; t != "" && path == ""; t = ParentType(t) { path = apiPaths[t] } } if path == "" { // TODO: I don't thing we should default to this, but I kept it // for compatability and because this function can't return an error path = "things" } return base + path + "/" + uuid }
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/util.go#L37-L39
func IsUnexportedField(field reflect.StructField) bool { return !(field.PkgPath == "" && unicode.IsUpper(rune(field.Name[0]))) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L1395-L1399
func (v *GetMetadataReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoIndexeddb11(&r, v) return r.Error() }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/client/verification_service.go#L25-L33
func (v *VerificationService) NewService(args []string) Service { log.Printf("[DEBUG] starting verification service with args: %v\n", args) v.Args = args v.Cmd = getVerifierCommandPath() v.Env = append(os.Environ(), `PACT_INTERACTION_RERUN_COMMAND="To re-run this specific test, set the following environment variables and run your test again: PACT_DESCRIPTION=\"<PACT_DESCRIPTION>\" PACT_PROVIDER_STATE=\"<PACT_PROVIDER_STATE>\""`) return v }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/client/http/http_client.go#L137-L147
func (o Options) MarshalJSON() ([]byte, error) { return json.Marshal(optionsJSON{ Timeout: marshal.Duration(o.Timeout), KeepAlive: marshal.Duration(o.KeepAlive), TLSHandshakeTimeout: marshal.Duration(o.TLSHandshakeTimeout), TLSSkipVerify: o.TLSSkipVerify, RetryTimeMax: marshal.Duration(o.RetryTimeMax), RetrySleepMax: marshal.Duration(o.RetrySleepMax), RetrySleepBase: marshal.Duration(o.RetrySleepBase), }) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/client.go#L196-L222
func (c *Client) requestRetry(r *request) ([]byte, error) { if c.fake && r.deckPath == "" { return []byte("{}"), nil } resp, err := c.retry(r) if err != nil { return nil, err } defer resp.Body.Close() rb, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } if resp.StatusCode == 404 { return nil, NewNotFoundError(fmt.Errorf("body: %s", string(rb))) } else if resp.StatusCode == 409 { return nil, NewConflictError(fmt.Errorf("body: %s", string(rb))) } else if resp.StatusCode == 422 { return nil, NewUnprocessableEntityError(fmt.Errorf("body: %s", string(rb))) } else if resp.StatusCode == 404 { return nil, NewNotFoundError(fmt.Errorf("body: %s", string(rb))) } else if resp.StatusCode < 200 || resp.StatusCode > 299 { return nil, fmt.Errorf("response has status \"%s\" and body \"%s\"", resp.Status, string(rb)) } return rb, nil }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L308-L313
func (p *Page) CancelPopup() error { if err := p.session.DismissAlert(); err != nil { return fmt.Errorf("failed to cancel popup: %s", err) } return nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/api.go#L171-L214
func BootstrapCluster(conf *Config, logs LogStore, stable StableStore, snaps SnapshotStore, trans Transport, configuration Configuration) error { // Validate the Raft server config. if err := ValidateConfig(conf); err != nil { return err } // Sanity check the Raft peer configuration. if err := checkConfiguration(configuration); err != nil { return err } // Make sure the cluster is in a clean state. hasState, err := HasExistingState(logs, stable, snaps) if err != nil { return fmt.Errorf("failed to check for existing state: %v", err) } if hasState { return ErrCantBootstrap } // Set current term to 1. if err := stable.SetUint64(keyCurrentTerm, 1); err != nil { return fmt.Errorf("failed to save current term: %v", err) } // Append configuration entry to log. entry := &Log{ Index: 1, Term: 1, } if conf.ProtocolVersion < 3 { entry.Type = LogRemovePeerDeprecated entry.Data = encodePeers(configuration, trans) } else { entry.Type = LogConfiguration entry.Data = encodeConfiguration(configuration) } if err := logs.StoreLog(entry); err != nil { return fmt.Errorf("failed to append configuration entry to log: %v", err) } return nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/retry.go#L37-L60
func IsRetriableError(err error) bool { err = errors.Cause(err) if err == nil { return false } if err == sqlite3.ErrLocked || err == sqlite3.ErrBusy { return true } if strings.Contains(err.Error(), "database is locked") { return true } if strings.Contains(err.Error(), "bad connection") { return true } // Despite the description this is usually a lost leadership error. if strings.Contains(err.Error(), "disk I/O error") { return true } return false }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/file_snapshot.go#L349-L365
func (f *FileSnapshotStore) ReapSnapshots() error { snapshots, err := f.getSnapshots() if err != nil { f.logger.Printf("[ERR] snapshot: Failed to get snapshots: %v", err) return err } for i := f.retain; i < len(snapshots); i++ { path := filepath.Join(f.path, snapshots[i].ID) f.logger.Printf("[INFO] snapshot: reaping snapshot %v", path) if err := os.RemoveAll(path); err != nil { f.logger.Printf("[ERR] snapshot: Failed to reap snapshot %v: %v", path, err) return err } } return nil }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/local_peer.go#L50-L55
func (peer *localPeer) ConnectionTo(name PeerName) (Connection, bool) { peer.RLock() defer peer.RUnlock() conn, found := peer.connections[name] return conn, found // yes, you really can't inline that. FFS. }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/util.go#L912-L918
func RemoveDuplicatesFromString(s string, sep string) string { dup := sep + sep for s = strings.Replace(s, dup, sep, -1); strings.Contains(s, dup); s = strings.Replace(s, dup, sep, -1) { } return s }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/velodrome/transform/plugins/states.go#L101-L108
func (m *MultiState) Active() bool { for _, state := range m.states { if !state.Active() { return false } } return true }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L1149-L1153
func (v SignedExchangeHeader) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork7(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/boskos/crds/client.go#L75-L93
func (o *KubernetesClientOptions) newCRDClient(t Type) (*Client, error) { config, scheme, err := createRESTConfig(o.kubeConfig, t) if err != nil { return nil, err } if err = registerResource(config, t); err != nil { return nil, err } // creates the client var restClient *rest.RESTClient restClient, err = rest.RESTClientFor(config) if err != nil { return nil, err } rc := Client{cl: restClient, ns: o.namespace, t: t, codec: runtime.NewParameterCodec(scheme)} return &rc, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/issue-creator/creator/creator.go#L218-L276
func (c *IssueCreator) loadCache() error { user, err := c.client.GetUser("") if err != nil { return fmt.Errorf("failed to fetch the User struct for the current authenticated user. errmsg: %v", err) } if user == nil { return fmt.Errorf("received a nil User struct pointer when trying to look up the currently authenticated user") } if user.Login == nil { return fmt.Errorf("the user struct for the currently authenticated user does not specify a login") } c.authorName = *user.Login // Try to get the list of valid labels for the repo. if validLabels, err := c.client.GetRepoLabels(c.org, c.project); err != nil { c.validLabels = nil glog.Errorf("Failed to retrieve the list of valid labels for repo '%s/%s'. Allowing all labels. errmsg: %v\n", c.org, c.project, err) } else { c.validLabels = make([]string, 0, len(validLabels)) for _, label := range validLabels { if label.Name != nil && *label.Name != "" { c.validLabels = append(c.validLabels, *label.Name) } } } // Try to get the valid collaborators for the repo. if collaborators, err := c.client.GetCollaborators(c.org, c.project); err != nil { c.Collaborators = nil glog.Errorf("Failed to retrieve the list of valid collaborators for repo '%s/%s'. Allowing all assignees. errmsg: %v\n", c.org, c.project, err) } else { c.Collaborators = make([]string, 0, len(collaborators)) for _, user := range collaborators { if user.Login != nil && *user.Login != "" { c.Collaborators = append(c.Collaborators, strings.ToLower(*user.Login)) } } } // Populate the issue cache (allIssues). issues, err := c.client.GetIssues( c.org, c.project, &github.IssueListByRepoOptions{ State: "all", Creator: c.authorName, }, ) if err != nil { return fmt.Errorf("failed to refresh the list of all issues created by %s in repo '%s/%s'. errmsg: %v", c.authorName, c.org, c.project, err) } if len(issues) == 0 { glog.Warningf("IssueCreator found no issues in the repo '%s/%s' authored by '%s'.\n", c.org, c.project, c.authorName) } c.allIssues = make(map[int]*github.Issue) for _, i := range issues { c.allIssues[*i.Number] = i } return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L526-L530
func (v GrantPermissionsParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser4(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/emulation/easyjson.go#L980-L984
func (v SetDocumentCookieDisabledParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoEmulation11(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/options.go#L116-L124
func FilterPath(f func(Path) bool, opt Option) Option { if f == nil { panic("invalid path filter function") } if opt := normalizeOption(opt); opt != nil { return &pathFilter{fnc: f, opt: opt} } return nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/blockers/blockers.go#L61-L70
func (b Blockers) GetApplicable(org, repo, branch string) []Blocker { var res []Blocker res = append(res, b.Repo[orgRepo{org: org, repo: repo}]...) res = append(res, b.Branch[orgRepoBranch{org: org, repo: repo, branch: branch}]...) sort.Slice(res, func(i, j int) bool { return res[i].Number < res[j].Number }) return res }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/y/iterator.go#L210-L238
func (s *MergeIterator) Next() { if len(s.h) == 0 { return } smallest := s.h[0].itr smallest.Next() for len(s.h) > 0 { smallest = s.h[0].itr if !smallest.Valid() { heap.Pop(&s.h) continue } heap.Fix(&s.h, 0) smallest = s.h[0].itr if smallest.Valid() { if !bytes.Equal(smallest.Key(), s.curKey) { break } smallest.Next() } } if !smallest.Valid() { return } s.storeKey(smallest) }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/peersjson.go#L64-L98
func ReadConfigJSON(path string) (Configuration, error) { // Read in the file. buf, err := ioutil.ReadFile(path) if err != nil { return Configuration{}, err } // Parse it as JSON. var peers []configEntry dec := json.NewDecoder(bytes.NewReader(buf)) if err := dec.Decode(&peers); err != nil { return Configuration{}, err } // Map it into the new-style configuration structure. var configuration Configuration for _, peer := range peers { suffrage := Voter if peer.NonVoter { suffrage = Nonvoter } server := Server{ Suffrage: suffrage, ID: peer.ID, Address: peer.Address, } configuration.Servers = append(configuration.Servers, server) } // We should only ingest valid configurations. if err := checkConfiguration(configuration); err != nil { return Configuration{}, err } return configuration, nil }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/file-server/server.go#L140-L154
func (s *Server) HashedPath(p string) (string, error) { if s.Hasher == nil { return path.Join(s.root, p), nil } h, cont, err := s.hash(p) if err != nil { if cont { h, _, err = s.hashFromFilename(p) } if err != nil { return "", err } } return path.Join(s.root, s.hashedPath(p, h)), nil }
https://github.com/wawandco/fako/blob/c36a0bc97398c9100daa83ebef1c4e7af32c7654/fakers.go#L123-L134
func findFakeFunctionFor(fako string) func() string { result := func() string { return "" } for kind, function := range allGenerators() { if fako == kind { result = function break } } return result }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/mex.go#L451-L462
func (mexset *messageExchangeSet) copyExchanges() (shutdown bool, exchanges map[uint32]*messageExchange) { if mexset.shutdown { return true, nil } exchangesCopy := make(map[uint32]*messageExchange, len(mexset.exchanges)) for k, mex := range mexset.exchanges { exchangesCopy[k] = mex } return false, exchangesCopy }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L951-L955
func (v HighlightQuadParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoOverlay10(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/contention/contention.go#L44-L49
func (td *TimeoutDetector) Reset() { td.mu.Lock() defer td.mu.Unlock() td.records = make(map[uint64]time.Time) }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_slices.go#L62-L210
func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { assert(opts.DiffMode == diffUnknown) t, vx, vy := v.Type, v.ValueX, v.ValueY // Auto-detect the type of the data. var isLinedText, isText, isBinary bool var sx, sy string switch { case t.Kind() == reflect.String: sx, sy = vx.String(), vy.String() isText = true // Initial estimate, verify later case t.Kind() == reflect.Slice && t.Elem() == reflect.TypeOf(byte(0)): sx, sy = string(vx.Bytes()), string(vy.Bytes()) isBinary = true // Initial estimate, verify later case t.Kind() == reflect.Array: // Arrays need to be addressable for slice operations to work. vx2, vy2 := reflect.New(t).Elem(), reflect.New(t).Elem() vx2.Set(vx) vy2.Set(vy) vx, vy = vx2, vy2 } if isText || isBinary { var numLines, lastLineIdx, maxLineLen int isBinary = false for i, r := range sx + sy { if !(unicode.IsPrint(r) || unicode.IsSpace(r)) || r == utf8.RuneError { isBinary = true break } if r == '\n' { if maxLineLen < i-lastLineIdx { lastLineIdx = i - lastLineIdx } lastLineIdx = i + 1 numLines++ } } isText = !isBinary isLinedText = isText && numLines >= 4 && maxLineLen <= 256 } // Format the string into printable records. var list textList var delim string switch { // If the text appears to be multi-lined text, // then perform differencing across individual lines. case isLinedText: ssx := strings.Split(sx, "\n") ssy := strings.Split(sy, "\n") list = opts.formatDiffSlice( reflect.ValueOf(ssx), reflect.ValueOf(ssy), 1, "line", func(v reflect.Value, d diffMode) textRecord { s := formatString(v.Index(0).String()) return textRecord{Diff: d, Value: textLine(s)} }, ) delim = "\n" // If the text appears to be single-lined text, // then perform differencing in approximately fixed-sized chunks. // The output is printed as quoted strings. case isText: list = opts.formatDiffSlice( reflect.ValueOf(sx), reflect.ValueOf(sy), 64, "byte", func(v reflect.Value, d diffMode) textRecord { s := formatString(v.String()) return textRecord{Diff: d, Value: textLine(s)} }, ) delim = "" // If the text appears to be binary data, // then perform differencing in approximately fixed-sized chunks. // The output is inspired by hexdump. case isBinary: list = opts.formatDiffSlice( reflect.ValueOf(sx), reflect.ValueOf(sy), 16, "byte", func(v reflect.Value, d diffMode) textRecord { var ss []string for i := 0; i < v.Len(); i++ { ss = append(ss, formatHex(v.Index(i).Uint())) } s := strings.Join(ss, ", ") comment := commentString(fmt.Sprintf("%c|%v|", d, formatASCII(v.String()))) return textRecord{Diff: d, Value: textLine(s), Comment: comment} }, ) // For all other slices of primitive types, // then perform differencing in approximately fixed-sized chunks. // The size of each chunk depends on the width of the element kind. default: var chunkSize int if t.Elem().Kind() == reflect.Bool { chunkSize = 16 } else { switch t.Elem().Bits() { case 8: chunkSize = 16 case 16: chunkSize = 12 case 32: chunkSize = 8 default: chunkSize = 8 } } list = opts.formatDiffSlice( vx, vy, chunkSize, t.Elem().Kind().String(), func(v reflect.Value, d diffMode) textRecord { var ss []string for i := 0; i < v.Len(); i++ { switch t.Elem().Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: ss = append(ss, fmt.Sprint(v.Index(i).Int())) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: ss = append(ss, formatHex(v.Index(i).Uint())) case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: ss = append(ss, fmt.Sprint(v.Index(i).Interface())) } } s := strings.Join(ss, ", ") return textRecord{Diff: d, Value: textLine(s)} }, ) } // Wrap the output with appropriate type information. var out textNode = textWrap{"{", list, "}"} if !isText { // The "{...}" byte-sequence literal is not valid Go syntax for strings. // Emit the type for extra clarity (e.g. "string{...}"). if t.Kind() == reflect.String { opts = opts.WithTypeMode(emitType) } return opts.FormatType(t, out) } switch t.Kind() { case reflect.String: out = textWrap{"strings.Join(", out, fmt.Sprintf(", %q)", delim)} if t != reflect.TypeOf(string("")) { out = opts.FormatType(t, out) } case reflect.Slice: out = textWrap{"bytes.Join(", out, fmt.Sprintf(", %q)", delim)} if t != reflect.TypeOf([]byte(nil)) { out = opts.FormatType(t, out) } } return out }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_dest.go#L198-L219
func (d *dockerImageDestination) blobExists(ctx context.Context, repo reference.Named, digest digest.Digest, extraScope *authScope) (bool, int64, error) { checkPath := fmt.Sprintf(blobsPath, reference.Path(repo), digest.String()) logrus.Debugf("Checking %s", checkPath) res, err := d.c.makeRequest(ctx, "HEAD", checkPath, nil, nil, v2Auth, extraScope) if err != nil { return false, -1, err } defer res.Body.Close() switch res.StatusCode { case http.StatusOK: logrus.Debugf("... already exists") return true, getBlobSize(res), nil case http.StatusUnauthorized: logrus.Debugf("... not authorized") return false, -1, errors.Wrapf(client.HandleErrorResponse(res), "Error checking whether a blob %s exists in %s", digest, repo.Name()) case http.StatusNotFound: logrus.Debugf("... not present") return false, -1, nil default: return false, -1, errors.Errorf("failed to read from destination repository %s: %d (%s)", reference.Path(d.ref.ref), res.StatusCode, http.StatusText(res.StatusCode)) } }
https://github.com/qor/roles/blob/d6375609fe3e5da46ad3a574fae244fb633e79c1/role.go#L27-L37
func (role *Role) Register(name string, fc Checker) { if role.definitions == nil { role.definitions = map[string]Checker{} } definition := role.definitions[name] if definition != nil { fmt.Printf("Role `%v` already defined, overwrited it!\n", name) } role.definitions[name] = fc }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/version/client.go#L37-L43
func PrettyPrintVersion(version *pb.Version) string { result := PrettyPrintVersionNoAdditional(version) if version.Additional != "" { result += fmt.Sprintf("%s", version.Additional) } return result }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/jenkins/jenkins.go#L745-L759
func (c *Client) Abort(job string, build *Build) error { c.logger.Debugf("Abort(%v %v)", job, build.Number) if c.dryRun { return nil } resp, err := c.request(http.MethodPost, fmt.Sprintf("/job/%s/%d/stop", job, build.Number), nil, false) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { return fmt.Errorf("response not 2XX: %s", resp.Status) } return nil }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/internal/stringutil/addr.go#L9-L21
func JoinAddress(addrs []mail.Address) string { if len(addrs) == 0 { return "" } buf := &bytes.Buffer{} for i, a := range addrs { if i > 0 { _, _ = buf.WriteString(", ") } _, _ = buf.WriteString(a.String()) } return buf.String() }
https://github.com/alexflint/go-arg/blob/fb1ae1c3e0bd00d45333c3d51384afc05846f7a0/usage.go#L73-L117
func (p *Parser) WriteHelp(w io.Writer) { var positionals, options []*spec for _, spec := range p.specs { if spec.positional { positionals = append(positionals, spec) } else { options = append(options, spec) } } if p.description != "" { fmt.Fprintln(w, p.description) } p.WriteUsage(w) // write the list of positionals if len(positionals) > 0 { fmt.Fprint(w, "\nPositional arguments:\n") for _, spec := range positionals { left := " " + strings.ToUpper(spec.long) fmt.Fprint(w, left) if spec.help != "" { if len(left)+2 < colWidth { fmt.Fprint(w, strings.Repeat(" ", colWidth-len(left))) } else { fmt.Fprint(w, "\n"+strings.Repeat(" ", colWidth)) } fmt.Fprint(w, spec.help) } fmt.Fprint(w, "\n") } } // write the list of options fmt.Fprint(w, "\nOptions:\n") for _, spec := range options { printOption(w, spec) } // write the list of built in options printOption(w, &spec{boolean: true, long: "help", short: "h", help: "display this help and exit"}) if p.version != "" { printOption(w, &spec{boolean: true, long: "version", help: "display version and exit"}) } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/slices.go#L126-L145
func scanSingleColumn(tx *sql.Tx, query string, args []interface{}, typeName string, scan scanFunc) error { rows, err := tx.Query(query, args...) if err != nil { return err } defer rows.Close() for rows.Next() { err := scan(rows) if err != nil { return err } } err = rows.Err() if err != nil { return err } return nil }
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/models/app.go#L43-L48
func (m *App) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/auth.go#L163-L166
func (s *cookieSigner) CanAuthenticate(host string) error { _, instance := s.builder.(*instanceLoginRequestBuilder) return testAuth(s, s.client, host, instance) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/generate/file/path.go#L12-L28
func absPath(path string) string { // We expect to be called by code within the lxd package itself. _, filename, _, _ := runtime.Caller(1) elems := strings.Split(filename, string(filepath.Separator)) for i := len(elems) - 1; i >= 0; i-- { if elems[i] == "lxd" { elems = append([]string{string(filepath.Separator)}, elems[:i]...) elems = append(elems, path) return filepath.Join(elems...) } } log.Fatalf("Could not found root dir of LXD tree source tree") return "" }
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L1355-L1360
func (o *ListFloat32Option) Set(value string) error { val := Float32Option{} val.Set(value) *o = append(*o, val) return nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/easyjson.go#L1360-L1364
func (v *SetBreakpointByURLReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDebugger14(&r, v) return r.Error() }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcauth/tcauth.go#L671-L674
func (auth *Auth) SentryDSN_SignedURL(project string, duration time.Duration) (*url.URL, error) { cd := tcclient.Client(*auth) return (&cd).SignedURL("/sentry/"+url.QueryEscape(project)+"/dsn", nil, duration) }
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/servers/grpc/grpc.go#L35-L37
func (s *Server) ServeTCP(ln net.Listener) (err error) { return s.Server.Serve(ln) }
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/usermanagment.go#L214-L219
func (c *Client) GetShare(groupid string, resourceid string) (*Share, error) { url := umGroupSharePath(groupid, resourceid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty) ret := &Share{} err := c.client.Get(url, ret, http.StatusOK) return ret, err }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/cmd/utils.go#L143-L186
func FormatPart(w io.Writer, p *enmime.Part, indent string) { if p == nil { return } sibling := p.NextSibling child := p.FirstChild // Compute indent strings myindent := indent + "`-- " childindent := indent + " " if sibling != nil { myindent = indent + "|-- " childindent = indent + "| " } if p.Parent == nil { // Root shouldn't be decorated, has no siblings myindent = indent childindent = indent } // Format and print this node ctype := "MISSING TYPE" if p.ContentType != "" { ctype = p.ContentType } disposition := "" if p.Disposition != "" { disposition = fmt.Sprintf(", disposition: %s", p.Disposition) } filename := "" if p.FileName != "" { filename = fmt.Sprintf(", filename: %q", p.FileName) } errors := "" if len(p.Errors) > 0 { errors = fmt.Sprintf(" (errors: %v)", len(p.Errors)) } fmt.Fprintf(w, "%s%s%s%s%s\n", myindent, ctype, disposition, filename, errors) // Recurse FormatPart(w, child, childindent) FormatPart(w, sibling, indent) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/profiler/easyjson.go#L1869-L1873
func (v PositionTickInfo) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoProfiler18(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/generate.go#L299-L331
func selectPackage(c *config.Config, dir string, packageMap map[string]*goPackage) (*goPackage, error) { buildablePackages := make(map[string]*goPackage) for name, pkg := range packageMap { if pkg.isBuildable(c) { buildablePackages[name] = pkg } } if len(buildablePackages) == 0 { return nil, &build.NoGoError{Dir: dir} } if len(buildablePackages) == 1 { for _, pkg := range buildablePackages { return pkg, nil } } if pkg, ok := buildablePackages[defaultPackageName(c, dir)]; ok { return pkg, nil } err := &build.MultiplePackageError{Dir: dir} for name, pkg := range buildablePackages { // Add the first file for each package for the error message. // Error() method expects these lists to be the same length. File // lists must be non-empty. These lists are only created by // buildPackage for packages with .go files present. err.Packages = append(err.Packages, name) err.Files = append(err.Files, pkg.firstGoFile()) } return nil, err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L743-L746
func (p RunScriptParams) WithIncludeCommandLineAPI(includeCommandLineAPI bool) *RunScriptParams { p.IncludeCommandLineAPI = includeCommandLineAPI return &p }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L840-L842
func (p *SetReturnValueParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetReturnValue, p, nil) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/pipeline/controller.go#L218-L234
func (c *controller) runWorker() { for { key, shutdown := c.workqueue.Get() if shutdown { return } func() { defer c.workqueue.Done(key) if err := reconcile(c, key.(string)); err != nil { runtime.HandleError(fmt.Errorf("failed to reconcile %s: %v", key, err)) return // Do not forget so we retry later. } c.workqueue.Forget(key) }() } }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/flame/models.go#L63-L71
func (t *Token) SetTokenData(typ TokenType, scope []string, expiresAt time.Time, client Client, resourceOwner ResourceOwner) { t.Type = typ t.Scope = scope t.ExpiresAt = expiresAt t.Application = client.ID() if resourceOwner != nil { t.User = coal.P(resourceOwner.ID()) } }
https://github.com/pandemicsyn/oort/blob/fca1d3baddc1d944387cc8bbe8b21f911ec9091b/api/groupstore_GEN_.go#L52-L127
func NewGroupStore(addr string, concurrency int, ftlsConfig *ftls.Config, opts ...grpc.DialOption) (store.GroupStore, error) { stor := &groupStore{ addr: addr, ftlsc: ftlsConfig, opts: opts, handlersDoneChan: make(chan struct{}), } stor.pendingLookupReqChan = make(chan *asyncGroupLookupRequest, concurrency) stor.freeLookupReqChan = make(chan *asyncGroupLookupRequest, concurrency) stor.freeLookupResChan = make(chan *asyncGroupLookupResponse, concurrency) for i := 0; i < cap(stor.freeLookupReqChan); i++ { stor.freeLookupReqChan <- &asyncGroupLookupRequest{resChan: make(chan *asyncGroupLookupResponse, 1)} } for i := 0; i < cap(stor.freeLookupResChan); i++ { stor.freeLookupResChan <- &asyncGroupLookupResponse{} } go stor.handleLookupStream() stor.pendingReadReqChan = make(chan *asyncGroupReadRequest, concurrency) stor.freeReadReqChan = make(chan *asyncGroupReadRequest, concurrency) stor.freeReadResChan = make(chan *asyncGroupReadResponse, concurrency) for i := 0; i < cap(stor.freeReadReqChan); i++ { stor.freeReadReqChan <- &asyncGroupReadRequest{resChan: make(chan *asyncGroupReadResponse, 1)} } for i := 0; i < cap(stor.freeReadResChan); i++ { stor.freeReadResChan <- &asyncGroupReadResponse{} } go stor.handleReadStream() stor.pendingWriteReqChan = make(chan *asyncGroupWriteRequest, concurrency) stor.freeWriteReqChan = make(chan *asyncGroupWriteRequest, concurrency) stor.freeWriteResChan = make(chan *asyncGroupWriteResponse, concurrency) for i := 0; i < cap(stor.freeWriteReqChan); i++ { stor.freeWriteReqChan <- &asyncGroupWriteRequest{resChan: make(chan *asyncGroupWriteResponse, 1)} } for i := 0; i < cap(stor.freeWriteResChan); i++ { stor.freeWriteResChan <- &asyncGroupWriteResponse{} } go stor.handleWriteStream() stor.pendingDeleteReqChan = make(chan *asyncGroupDeleteRequest, concurrency) stor.freeDeleteReqChan = make(chan *asyncGroupDeleteRequest, concurrency) stor.freeDeleteResChan = make(chan *asyncGroupDeleteResponse, concurrency) for i := 0; i < cap(stor.freeDeleteReqChan); i++ { stor.freeDeleteReqChan <- &asyncGroupDeleteRequest{resChan: make(chan *asyncGroupDeleteResponse, 1)} } for i := 0; i < cap(stor.freeDeleteResChan); i++ { stor.freeDeleteResChan <- &asyncGroupDeleteResponse{} } go stor.handleDeleteStream() stor.pendingLookupGroupReqChan = make(chan *asyncGroupLookupGroupRequest, concurrency) stor.freeLookupGroupReqChan = make(chan *asyncGroupLookupGroupRequest, concurrency) stor.freeLookupGroupResChan = make(chan *asyncGroupLookupGroupResponse, concurrency) for i := 0; i < cap(stor.freeLookupGroupReqChan); i++ { stor.freeLookupGroupReqChan <- &asyncGroupLookupGroupRequest{resChan: make(chan *asyncGroupLookupGroupResponse, 1)} } for i := 0; i < cap(stor.freeLookupGroupResChan); i++ { stor.freeLookupGroupResChan <- &asyncGroupLookupGroupResponse{} } go stor.handleLookupGroupStream() stor.pendingReadGroupReqChan = make(chan *asyncGroupReadGroupRequest, concurrency) stor.freeReadGroupReqChan = make(chan *asyncGroupReadGroupRequest, concurrency) stor.freeReadGroupResChan = make(chan *asyncGroupReadGroupResponse, concurrency) for i := 0; i < cap(stor.freeReadGroupReqChan); i++ { stor.freeReadGroupReqChan <- &asyncGroupReadGroupRequest{resChan: make(chan *asyncGroupReadGroupResponse, 1)} } for i := 0; i < cap(stor.freeReadGroupResChan); i++ { stor.freeReadGroupResChan <- &asyncGroupReadGroupResponse{} } go stor.handleReadGroupStream() return stor, nil }
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/zero/time.go#L69-L74
func (t Time) MarshalJSON() ([]byte, error) { if !t.Valid { return (time.Time{}).MarshalJSON() } return t.Time.MarshalJSON() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L65-L74
func (p *AwaitPromiseParams) Do(ctx context.Context) (result *RemoteObject, exceptionDetails *ExceptionDetails, err error) { // execute var res AwaitPromiseReturns err = cdp.Execute(ctx, CommandAwaitPromise, p, &res) if err != nil { return nil, nil, err } return res.Result, res.ExceptionDetails, nil }
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/lang/i18n.go#L35-L39
func Session(s handler.Session) Option { return Option{func(o *options) { o.session = s }} }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L301-L378
func (p *Pact) VerifyProviderRaw(request types.VerifyRequest) (types.ProviderVerifierResponse, error) { p.Setup(false) var res types.ProviderVerifierResponse u, err := url.Parse(request.ProviderBaseURL) if err != nil { return res, err } m := []proxy.Middleware{} if request.BeforeEach != nil { m = append(m, BeforeEachMiddleware(request.BeforeEach)) } if request.AfterEach != nil { m = append(m, AfterEachMiddleware(request.AfterEach)) } if len(request.StateHandlers) > 0 { m = append(m, stateHandlerMiddleware(request.StateHandlers)) } if request.RequestFilter != nil { m = append(m, request.RequestFilter) } // Configure HTTP Verification Proxy opts := proxy.Options{ TargetAddress: fmt.Sprintf("%s:%s", u.Hostname(), u.Port()), TargetScheme: u.Scheme, Middleware: m, } // Starts the message wrapper API with hooks back to the state handlers // This maps the 'description' field of a message pact, to a function handler // that will implement the message producer. This function must return an object and optionally // and error. The object will be marshalled to JSON for comparison. port, err := proxy.HTTPReverseProxy(opts) // Backwards compatibility, setup old provider states URL if given // Otherwise point to proxy setupURL := request.ProviderStatesSetupURL if request.ProviderStatesSetupURL == "" { setupURL = fmt.Sprintf("%s://localhost:%d/__setup", u.Scheme, port) } // Construct verifier request verificationRequest := types.VerifyRequest{ ProviderBaseURL: fmt.Sprintf("%s://localhost:%d", u.Scheme, port), // PactURLs: request.PactURLs, BrokerURL: request.BrokerURL, Tags: request.Tags, BrokerUsername: request.BrokerUsername, BrokerPassword: request.BrokerPassword, BrokerToken: request.BrokerToken, PublishVerificationResults: request.PublishVerificationResults, ProviderVersion: request.ProviderVersion, ProviderStatesSetupURL: setupURL, } if request.Provider == "" { verificationRequest.Provider = p.Provider } portErr := waitForPort(port, "tcp", "localhost", p.ClientTimeout, fmt.Sprintf(`Timed out waiting for http verification proxy on port %d - check for errors`, port)) if portErr != nil { log.Fatal("Error:", err) return res, portErr } log.Println("[DEBUG] pact provider verification") return p.pactClient.VerifyProvider(verificationRequest) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/audits/audits.go#L37-L42
func GetEncodedResponse(requestID network.RequestID, encoding GetEncodedResponseEncoding) *GetEncodedResponseParams { return &GetEncodedResponseParams{ RequestID: requestID, Encoding: encoding, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/types.go#L306-L330
func (t *Type) UnmarshalEasyJSON(in *jlexer.Lexer) { switch Type(in.String()) { case TypeObject: *t = TypeObject case TypeFunction: *t = TypeFunction case TypeUndefined: *t = TypeUndefined case TypeString: *t = TypeString case TypeNumber: *t = TypeNumber case TypeBoolean: *t = TypeBoolean case TypeSymbol: *t = TypeSymbol case TypeBigint: *t = TypeBigint case TypeAccessor: *t = TypeAccessor default: in.AddError(errors.New("unknown Type value")) } }
https://github.com/Unknwon/goconfig/blob/3dba17dd7b9ec8509b3621a73a30a4b333eb28da/write.go#L28-L103
func SaveConfigData(c *ConfigFile, out io.Writer) (err error) { equalSign := "=" if PrettyFormat { equalSign = " = " } buf := bytes.NewBuffer(nil) for _, section := range c.sectionList { // Write section comments. if len(c.GetSectionComments(section)) > 0 { if _, err = buf.WriteString(c.GetSectionComments(section) + LineBreak); err != nil { return err } } if section != DEFAULT_SECTION { // Write section name. if _, err = buf.WriteString("[" + section + "]" + LineBreak); err != nil { return err } } for _, key := range c.keyList[section] { if key != " " { // Write key comments. if len(c.GetKeyComments(section, key)) > 0 { if _, err = buf.WriteString(c.GetKeyComments(section, key) + LineBreak); err != nil { return err } } keyName := key // Check if it's auto increment. if keyName[0] == '#' { keyName = "-" } //[SWH|+]:支持键名包含等号和冒号 if strings.Contains(keyName, `=`) || strings.Contains(keyName, `:`) { if strings.Contains(keyName, "`") { if strings.Contains(keyName, `"`) { keyName = `"""` + keyName + `"""` } else { keyName = `"` + keyName + `"` } } else { keyName = "`" + keyName + "`" } } value := c.data[section][key] // In case key value contains "`" or "\"". if strings.Contains(value, "`") { if strings.Contains(value, `"`) { value = `"""` + value + `"""` } else { value = `"` + value + `"` } } // Write key and value. if _, err = buf.WriteString(keyName + equalSign + value + LineBreak); err != nil { return err } } } // Put a line between sections. if _, err = buf.WriteString(LineBreak); err != nil { return err } } if _, err := buf.WriteTo(out); err != nil { return err } return nil }
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/route_mappings.go#L81-L85
func (a *App) Mount(p string, h http.Handler) { prefix := path.Join(a.Prefix, p) path := path.Join(p, "{path:.+}") a.ANY(path, WrapHandler(http.StripPrefix(prefix, h))) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L528-L532
func (v *SamplingHeapProfileSample) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoHeapprofiler6(&r, v) return r.Error() }
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L128-L131
func (render *Render) Execute(name string, context interface{}, request *http.Request, writer http.ResponseWriter) error { tmpl := &Template{render: render, usingDefaultLayout: true} return tmpl.Execute(name, context, request, writer) }
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/database/elasticsearch/elasticsearch.go#L194-L243
func (db *Database) StoreFileInfo(sample map[string]interface{}) (elastic.IndexResponse, error) { if len(db.Plugins) == 0 { return elastic.IndexResponse{}, errors.New("Database.Plugins is empty (you must set this field to use this function)") } // Test connection to ElasticSearch err := db.TestConnection() if err != nil { return elastic.IndexResponse{}, errors.Wrap(err, "failed to connect to database") } client, err := elastic.NewSimpleClient( elastic.SetURL(db.URL), elastic.SetBasicAuth( utils.Getopts(db.Username, "MALICE_ELASTICSEARCH_USERNAME", ""), utils.Getopts(db.Password, "MALICE_ELASTICSEARCH_PASSWORD", ""), ), ) if err != nil { return elastic.IndexResponse{}, errors.Wrap(err, "failed to create elasticsearch simple client") } // NOTE: I am not setting ID because I want to be able to re-scan files with updated signatures in the future fInfo := map[string]interface{}{ // "id": sample.SHA256, "file": sample, "plugins": db.Plugins, "scan_date": time.Now().Format(time.RFC3339Nano), } newScan, err := client.Index(). Index(db.Index). Type(db.Type). OpType("index"). // Id("1"). BodyJson(fInfo). Do(context.Background()) if err != nil { return elastic.IndexResponse{}, errors.Wrap(err, "failed to index file info") } log.WithFields(log.Fields{ "id": newScan.Id, "index": newScan.Index, "type": newScan.Type, }).Debug("indexed sample") return *newScan, nil }
https://github.com/pandemicsyn/oort/blob/fca1d3baddc1d944387cc8bbe8b21f911ec9091b/oort/config.go#L148-L155
func GenServiceID(service, name, proto string) (string, error) { h, _ := os.Hostname() d := strings.SplitN(h, ".", 2) if len(d) != 2 { return "", fmt.Errorf("Unable to determine FQDN, only got short name.") } return fmt.Sprintf("_%s-%s._%s.%s", service, name, proto, d[1]), nil }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/fuzzy/apply_src.go#L45-L49
func (a *applySource) apply(t *testing.T, c *cluster, n uint) *clusterApplier { ap := &clusterApplier{stopCh: make(chan bool), src: a} go ap.apply(t, c, n) return ap }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/thrift/meta.go#L71-L77
func (h *metaHandler) Health(ctx Context, req *meta.HealthRequest) (*meta.HealthStatus, error) { ok, message := h.healthFn(ctx, metaReqToReq(req)) if message == "" { return &meta.HealthStatus{Ok: ok}, nil } return &meta.HealthStatus{Ok: ok, Message: &message}, nil }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/balancer/balancer.go#L174-L225
func (bb *baseBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { bb.mu.Lock() defer bb.mu.Unlock() old, ok := bb.scToSt[sc] if !ok { bb.lg.Warn( "state change for an unknown subconn", zap.String("balancer-id", bb.id), zap.String("subconn", scToString(sc)), zap.String("state", s.String()), ) return } bb.lg.Info( "state changed", zap.String("balancer-id", bb.id), zap.Bool("connected", s == connectivity.Ready), zap.String("subconn", scToString(sc)), zap.String("address", bb.scToAddr[sc].Addr), zap.String("old-state", old.String()), zap.String("new-state", s.String()), ) bb.scToSt[sc] = s switch s { case connectivity.Idle: sc.Connect() case connectivity.Shutdown: // When an address was removed by resolver, b called RemoveSubConn but // kept the sc's state in scToSt. Remove state for this sc here. delete(bb.scToAddr, sc) delete(bb.scToSt, sc) } oldAggrState := bb.currentState bb.currentState = bb.csEvltr.recordTransition(old, s) // Regenerate picker when one of the following happens: // - this sc became ready from not-ready // - this sc became not-ready from ready // - the aggregated state of balancer became TransientFailure from non-TransientFailure // - the aggregated state of balancer became non-TransientFailure from TransientFailure if (s == connectivity.Ready) != (old == connectivity.Ready) || (bb.currentState == connectivity.TransientFailure) != (oldAggrState == connectivity.TransientFailure) { bb.regeneratePicker() } bb.currentConn.UpdateBalancerState(bb.currentState, bb.Picker) return }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fileinfo.go#L518-L556
func readTags(path string) ([]tagLine, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() scanner := bufio.NewScanner(f) // Pass 1: Identify leading run of // comments and blank lines, // which must be followed by a blank line. var lines []string end := 0 for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) if line == "" { end = len(lines) continue } if strings.HasPrefix(line, "//") { lines = append(lines, line[len("//"):]) continue } break } if err := scanner.Err(); err != nil { return nil, err } lines = lines[:end] // Pass 2: Process each line in the run. var tagLines []tagLine for _, line := range lines { fields := strings.Fields(line) if len(fields) > 0 && fields[0] == "+build" { tagLines = append(tagLines, parseTagsInGroups(fields[1:])) } } return tagLines, nil }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L196-L201
func (img *IplImage) GetMat() *Mat { var null C.int tmp := CreateMat(img.Height(), img.Width(), CV_32S) m := C.cvGetMat(unsafe.Pointer(img), (*C.CvMat)(tmp), &null, C.int(0)) return (*Mat)(m) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/archive/oci_dest.go#L93-L95
func (d *ociArchiveImageDestination) PutBlob(ctx context.Context, stream io.Reader, inputInfo types.BlobInfo, cache types.BlobInfoCache, isConfig bool) (types.BlobInfo, error) { return d.unpackedDest.PutBlob(ctx, stream, inputInfo, cache, isConfig) }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/http.go#L85-L102
func setURL(client *Client, route string, query url.Values) (u *url.URL, err error) { URL := client.BaseURL // See https://bugzil.la/1484702 // Avoid double separator; routes must start with `/`, so baseURL shouldn't // end with `/`. if strings.HasSuffix(URL, "/") { URL = URL[:len(URL)-1] } URL += route u, err = url.Parse(URL) if err != nil { return nil, fmt.Errorf("Cannot parse url: '%v', is BaseURL (%v) set correctly?\n%v\n", URL, client.BaseURL, err) } if query != nil { u.RawQuery = query.Encode() } return }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L158-L169
func (h *dbHashTree) Get(path string) (*NodeProto, error) { path = clean(path) var node *NodeProto if err := h.View(func(tx *bolt.Tx) error { var err error node, err = get(tx, path) return err }); err != nil { return nil, err } return node, nil }
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L275-L280
func (c *Client) Close() error { if c.conn != (*tls.Conn)(nil) { return c.conn.Close() } return nil }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L487-L489
func (b *Base) Error(msg string) error { return b.Log(LevelError, nil, msg) }
https://github.com/antlinker/go-dirtyfilter/blob/533f538ffaa112776b1258c3db63e6f55648e18b/store/memory.go#L99-L108
func (ms *MemoryStore) Remove(words ...string) error { if len(words) == 0 { return nil } for i, l := 0, len(words); i < l; i++ { ms.dataStore.Remove(words[i]) } atomic.AddUint64(&ms.version, 1) return nil }
https://github.com/nwaples/rardecode/blob/197ef08ef68c4454ae5970a9c2692d6056ceb8d7/reader.go#L282-L325
func (r *Reader) Next() (*FileHeader, error) { if r.solidr != nil { // solid files must be read fully to update decoder information if _, err := io.Copy(ioutil.Discard, r.solidr); err != nil { return nil, err } } h, err := r.pr.next() // skip to next file if err != nil { return nil, err } r.solidr = nil br := byteReader(&r.pr) // start with packed file reader // check for encryption if len(h.key) > 0 && len(h.iv) > 0 { br = newAesDecryptReader(br, h.key, h.iv) // decrypt } r.r = br // check for compression if h.decoder != nil { err = r.dr.init(br, h.decoder, h.winSize, !h.solid) if err != nil { return nil, err } r.r = &r.dr if r.pr.r.isSolid() { r.solidr = r.r } } if h.UnPackedSize >= 0 && !h.UnKnownSize { // Limit reading to UnPackedSize as there may be padding r.r = &limitedReader{r.r, h.UnPackedSize, errShortFile} } r.cksum = h.cksum if r.cksum != nil { r.r = io.TeeReader(r.r, h.cksum) // write file data to checksum as it is read } fh := new(FileHeader) *fh = h.FileHeader return fh, nil }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L651-L653
func Add(src1, src2, dst *IplImage) { AddWithMask(src1, src2, dst, nil) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/dom.go#L1441-L1443
func (p *SetNodeValueParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandSetNodeValue, p, nil) }
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_reflect.go#L274-L279
func (m visitedPointers) Visit(v reflect.Value) bool { p := value.PointerOf(v) _, visited := m[p] m[p] = struct{}{} return visited }
https://github.com/gopistolet/gospf/blob/a58dd1fcbf509d558a6809c54defbce6872c40c5/spf.go#L440-L446
func (s *SPF) incDNSLookupCount(amt int) error { s.dnsLookupCount = s.dnsLookupCount + amt if s.dnsLookupCount > DNSLookupLimit { return &PermError{fmt.Sprintf("Domain %v exceeds max amount of dns queries: %v", s.Domain, DNSLookupLimit)} } return nil }
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/capabilities.go#L86-L89
func (c Capabilities) JSON() (string, error) { capabilitiesJSON, err := json.Marshal(c) return string(capabilitiesJSON), err }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L401-L407
func SynthesizePinchGesture(x float64, y float64, scaleFactor float64) *SynthesizePinchGestureParams { return &SynthesizePinchGestureParams{ X: x, Y: y, ScaleFactor: scaleFactor, } }