_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/log_nix.go#L54-L56
|
func NewLogBackend(out io.Writer, prefix string, flag int) *LogBackend {
return &LogBackend{Logger: log.New(out, prefix, flag)}
}
|
https://github.com/faiface/mainthread/blob/8b78f0a41ae388189090ac4506612659fa53082b/mainthread.go#L32-L49
|
func Run(run func()) {
callQueue = make(chan func(), CallQueueCap)
done := make(chan struct{})
go func() {
run()
done <- struct{}{}
}()
for {
select {
case f := <-callQueue:
f()
case <-done:
return
}
}
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/meta/bundle.go#L18-L34
|
func (b *Bundle) InitialState(key xdr.LedgerKey) (*xdr.LedgerEntry, error) {
all := b.Changes(key)
if len(all) == 0 {
return nil, ErrMetaNotFound
}
first := all[0]
if first.Type != xdr.LedgerEntryChangeTypeLedgerEntryState {
return nil, nil
}
result := first.MustState()
return &result, nil
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/http.go#L108-L172
|
func (client *Client) Request(rawPayload []byte, method, route string, query url.Values) (*CallSummary, error) {
callSummary := new(CallSummary)
callSummary.HTTPRequestBody = string(rawPayload)
// function to perform http request - we call this using backoff library to
// have exponential backoff in case of intermittent failures (e.g. network
// blips or HTTP 5xx errors)
httpCall := func() (*http.Response, error, error) {
var ioReader io.Reader
ioReader = bytes.NewReader(rawPayload)
u, err := setURL(client, route, query)
if err != nil {
return nil, nil, fmt.Errorf("apiCall url cannot be parsed:\n%v\n", err)
}
callSummary.HTTPRequest, err = http.NewRequest(method, u.String(), ioReader)
if err != nil {
return nil, nil, fmt.Errorf("Internal error: apiCall url cannot be parsed although thought to be valid: '%v', is the BaseURL (%v) set correctly?\n%v\n", u.String(), client.BaseURL, err)
}
if len(rawPayload) > 0 {
callSummary.HTTPRequest.Header.Set("Content-Type", "application/json")
}
// Refresh Authorization header with each call...
// Only authenticate if client library user wishes to.
if client.Authenticate {
err = client.Credentials.SignRequest(callSummary.HTTPRequest)
if err != nil {
return nil, nil, err
}
}
// Set context if one is given
if client.Context != nil {
callSummary.HTTPRequest = callSummary.HTTPRequest.WithContext(client.Context)
}
var resp *http.Response
if client.HTTPClient != nil {
resp, err = client.HTTPClient.Do(callSummary.HTTPRequest)
} else {
resp, err = defaultHTTPClient.Do(callSummary.HTTPRequest)
}
// return cancelled error, if context was cancelled
if client.Context != nil && client.Context.Err() != nil {
return nil, nil, client.Context.Err()
}
// b, e := httputil.DumpResponse(resp, true)
// if e == nil {
// fmt.Println(string(b))
// }
return resp, err, nil
}
// Make HTTP API calls using an exponential backoff algorithm...
var err error
callSummary.HTTPResponse, callSummary.Attempts, err = httpbackoff.Retry(httpCall)
// read response into memory, so that we can return the body
if callSummary.HTTPResponse != nil {
body, err2 := ioutil.ReadAll(callSummary.HTTPResponse.Body)
if err2 == nil {
callSummary.HTTPResponseBody = string(body)
}
}
return callSummary, err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L125-L129
|
func (v *SetRemoteLocationsParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoTarget(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L436-L440
|
func (v WebSocketFrame) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork2(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L702-L704
|
func (h *dbHashTree) PutFile(path string, objects []*pfs.Object, size int64) error {
return h.putFile(path, objects, nil, size, false)
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/client/clientset/versioned/fake/clientset_generated.go#L59-L61
|
func (c *Clientset) Tsuru() tsuruv1.TsuruV1Interface {
return &faketsuruv1.FakeTsuruV1{Fake: &c.Fake}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/tracing.go#L229-L260
|
func ExtractInboundSpan(ctx context.Context, call *InboundCall, headers map[string]string, tracer opentracing.Tracer) context.Context {
var span = call.Response().span
if span != nil {
if headers != nil {
// extract SpanContext from headers, but do not start another span with it,
// just get the baggage and copy to the already created span
carrier := tracingHeadersCarrier(headers)
if sc, err := tracer.Extract(opentracing.TextMap, carrier); err == nil {
sc.ForeachBaggageItem(func(k, v string) bool {
span.SetBaggageItem(k, v)
return true
})
}
carrier.RemoveTracingKeys()
}
} else {
var parent opentracing.SpanContext
if headers != nil {
carrier := tracingHeadersCarrier(headers)
if p, err := tracer.Extract(opentracing.TextMap, carrier); err == nil {
parent = p
}
carrier.RemoveTracingKeys()
}
span = tracer.StartSpan(call.MethodString(), ext.RPCServerOption(parent))
ext.PeerService.Set(span, call.CallerName())
span.SetTag("as", string(call.Format()))
call.conn.setPeerHostPort(span)
call.Response().span = span
}
return opentracing.ContextWithSpan(ctx, span)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L591-L605
|
func storagePoolDriverGet(tx *sql.Tx, id int64) (string, error) {
stmt := "SELECT driver FROM storage_pools WHERE id=?"
drivers, err := query.SelectStrings(tx, stmt, id)
if err != nil {
return "", err
}
switch len(drivers) {
case 0:
return "", ErrNoSuchObject
case 1:
return drivers[0], nil
default:
return "", fmt.Errorf("more than one pool has the given ID")
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/client.go#L2454-L2475
|
func (c *Client) ListIssueEvents(org, repo string, num int) ([]ListedIssueEvent, error) {
c.log("ListIssueEvents", org, repo, num)
if c.fake {
return nil, nil
}
path := fmt.Sprintf("/repos/%s/%s/issues/%d/events", org, repo, num)
var events []ListedIssueEvent
err := c.readPaginatedResults(
path,
acceptNone,
func() interface{} {
return &[]ListedIssueEvent{}
},
func(obj interface{}) {
events = append(events, *(obj.(*[]ListedIssueEvent))...)
},
)
if err != nil {
return nil, err
}
return events, nil
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/net_transport.go#L452-L455
|
func (n *NetworkTransport) EncodePeer(id ServerID, p ServerAddress) []byte {
address := n.getProviderAddressOrFallback(id, p)
return []byte(address)
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/plugins.go#L288-L300
|
func (pa *ConfigAgent) IssueCommentHandlers(owner, repo string) map[string]IssueCommentHandler {
pa.mut.Lock()
defer pa.mut.Unlock()
hs := map[string]IssueCommentHandler{}
for _, p := range pa.getPlugins(owner, repo) {
if h, ok := issueCommentHandlers[p]; ok {
hs[p] = h
}
}
return hs
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/integration/cluster.go#L786-L952
|
func (m *member) Launch() error {
lg.Info(
"launching a member",
zap.String("name", m.Name),
zap.Strings("advertise-peer-urls", m.PeerURLs.StringSlice()),
zap.Strings("listen-client-urls", m.ClientURLs.StringSlice()),
zap.String("grpc-address", m.grpcAddr),
)
var err error
if m.s, err = etcdserver.NewServer(m.ServerConfig); err != nil {
return fmt.Errorf("failed to initialize the etcd server: %v", err)
}
m.s.SyncTicker = time.NewTicker(500 * time.Millisecond)
m.s.Start()
var peerTLScfg *tls.Config
if m.PeerTLSInfo != nil && !m.PeerTLSInfo.Empty() {
if peerTLScfg, err = m.PeerTLSInfo.ServerConfig(); err != nil {
return err
}
}
if m.grpcListener != nil {
var (
tlscfg *tls.Config
)
if m.ClientTLSInfo != nil && !m.ClientTLSInfo.Empty() {
tlscfg, err = m.ClientTLSInfo.ServerConfig()
if err != nil {
return err
}
}
m.grpcServer = v3rpc.Server(m.s, tlscfg, m.grpcServerOpts...)
m.grpcServerPeer = v3rpc.Server(m.s, peerTLScfg)
m.serverClient = v3client.New(m.s)
lockpb.RegisterLockServer(m.grpcServer, v3lock.NewLockServer(m.serverClient))
epb.RegisterElectionServer(m.grpcServer, v3election.NewElectionServer(m.serverClient))
go m.grpcServer.Serve(m.grpcListener)
}
m.raftHandler = &testutil.PauseableHandler{Next: etcdhttp.NewPeerHandler(m.Logger, m.s)}
h := (http.Handler)(m.raftHandler)
if m.grpcListener != nil {
h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
m.grpcServerPeer.ServeHTTP(w, r)
} else {
m.raftHandler.ServeHTTP(w, r)
}
})
}
for _, ln := range m.PeerListeners {
cm := cmux.New(ln)
// don't hang on matcher after closing listener
cm.SetReadTimeout(time.Second)
if m.grpcServer != nil {
grpcl := cm.Match(cmux.HTTP2())
go m.grpcServerPeer.Serve(grpcl)
}
// serve http1/http2 rafthttp/grpc
ll := cm.Match(cmux.Any())
if peerTLScfg != nil {
if ll, err = transport.NewTLSListener(ll, m.PeerTLSInfo); err != nil {
return err
}
}
hs := &httptest.Server{
Listener: ll,
Config: &http.Server{
Handler: h,
TLSConfig: peerTLScfg,
ErrorLog: log.New(ioutil.Discard, "net/http", 0),
},
TLS: peerTLScfg,
}
hs.Start()
donec := make(chan struct{})
go func() {
defer close(donec)
cm.Serve()
}()
closer := func() {
ll.Close()
hs.CloseClientConnections()
hs.Close()
<-donec
}
m.serverClosers = append(m.serverClosers, closer)
}
for _, ln := range m.ClientListeners {
hs := &httptest.Server{
Listener: ln,
Config: &http.Server{
Handler: v2http.NewClientHandler(
m.Logger,
m.s,
m.ServerConfig.ReqTimeout(),
),
ErrorLog: log.New(ioutil.Discard, "net/http", 0),
},
}
if m.ClientTLSInfo == nil {
hs.Start()
} else {
info := m.ClientTLSInfo
hs.TLS, err = info.ServerConfig()
if err != nil {
return err
}
// baseConfig is called on initial TLS handshake start.
//
// Previously,
// 1. Server has non-empty (*tls.Config).Certificates on client hello
// 2. Server calls (*tls.Config).GetCertificate iff:
// - Server's (*tls.Config).Certificates is not empty, or
// - Client supplies SNI; non-empty (*tls.ClientHelloInfo).ServerName
//
// When (*tls.Config).Certificates is always populated on initial handshake,
// client is expected to provide a valid matching SNI to pass the TLS
// verification, thus trigger server (*tls.Config).GetCertificate to reload
// TLS assets. However, a cert whose SAN field does not include domain names
// but only IP addresses, has empty (*tls.ClientHelloInfo).ServerName, thus
// it was never able to trigger TLS reload on initial handshake; first
// ceritifcate object was being used, never being updated.
//
// Now, (*tls.Config).Certificates is created empty on initial TLS client
// handshake, in order to trigger (*tls.Config).GetCertificate and populate
// rest of the certificates on every new TLS connection, even when client
// SNI is empty (e.g. cert only includes IPs).
//
// This introduces another problem with "httptest.Server":
// when server initial certificates are empty, certificates
// are overwritten by Go's internal test certs, which have
// different SAN fields (e.g. example.com). To work around,
// re-overwrite (*tls.Config).Certificates before starting
// test server.
tlsCert, err := tlsutil.NewCert(info.CertFile, info.KeyFile, nil)
if err != nil {
return err
}
hs.TLS.Certificates = []tls.Certificate{*tlsCert}
hs.StartTLS()
}
closer := func() {
ln.Close()
hs.CloseClientConnections()
hs.Close()
}
m.serverClosers = append(m.serverClosers, closer)
}
lg.Info(
"launched a member",
zap.String("name", m.Name),
zap.Strings("advertise-peer-urls", m.PeerURLs.StringSlice()),
zap.Strings("listen-client-urls", m.ClientURLs.StringSlice()),
zap.String("grpc-address", m.grpcAddr),
)
return nil
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/response.go#L118-L121
|
func (w *responseWriter) CloseNotify() <-chan bool {
notifier := w.ResponseWriter.(http.CloseNotifier)
return notifier.CloseNotify()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L160-L163
|
func (p EvaluateOnCallFrameParams) WithReturnByValue(returnByValue bool) *EvaluateOnCallFrameParams {
p.ReturnByValue = returnByValue
return &p
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/message.go#L69-L72
|
func (p *Message) ExpectsToReceive(description string) *Message {
p.Description = description
return p
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/ostree/ostree_transport.go#L89-L127
|
func NewReference(image string, repo string) (types.ImageReference, error) {
// image is not _really_ in a containers/image/docker/reference format;
// as far as the libOSTree ociimage/* namespace is concerned, it is more or
// less an arbitrary string with an implied tag.
// Parse the image using reference.ParseNormalizedNamed so that we can
// check whether the images has a tag specified and we can add ":latest" if needed
ostreeImage, err := reference.ParseNormalizedNamed(image)
if err != nil {
return nil, err
}
if reference.IsNameOnly(ostreeImage) {
image = image + ":latest"
}
resolved, err := explicitfilepath.ResolvePathToFullyExplicit(repo)
if err != nil {
// With os.IsNotExist(err), the parent directory of repo is also not existent;
// that should ordinarily not happen, but it would be a bit weird to reject
// references which do not specify a repo just because the implicit defaultOSTreeRepo
// does not exist.
if os.IsNotExist(err) && repo == defaultOSTreeRepo {
resolved = repo
} else {
return nil, err
}
}
// This is necessary to prevent directory paths returned by PolicyConfigurationNamespaces
// from being ambiguous with values of PolicyConfigurationIdentity.
if strings.Contains(resolved, ":") {
return nil, errors.Errorf("Invalid OSTree reference %s@%s: path %s contains a colon", image, repo, resolved)
}
return ostreeReference{
image: image,
branchName: encodeOStreeRef(image),
repo: resolved,
}, nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/systeminfo/easyjson.go#L634-L638
|
func (v *GPUInfo) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoSysteminfo5(&r, v)
return r.Error()
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/cluster/cluster.go#L124-L131
|
func (c *Cluster) ExternalNodes() (res []*Node) {
for _, n := range c.nodes {
if n.Addr != c.listen {
res = append(res, n)
}
}
return
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/angular.go#L51-L58
|
func mandatory(a gen.Action, param string) bool {
for _, p := range a.Params {
if p.Name == param {
return p.Mandatory
}
}
panic("praxisgen bug: Unknown param " + param + " for action " + a.Name)
}
|
https://github.com/r3labs/sse/blob/2f90368216802092e9ed520c43e974e11d50438d/client.go#L96-L168
|
func (c *Client) SubscribeChan(stream string, ch chan *Event) error {
var connected bool
errch := make(chan error)
c.mu.Lock()
c.subscribed[ch] = make(chan bool)
c.mu.Unlock()
go func() {
operation := func() error {
resp, err := c.request(stream)
if err != nil {
c.cleanup(resp, ch)
return err
}
if resp.StatusCode != 200 {
c.cleanup(resp, ch)
return errors.New("could not connect to stream")
}
if !connected {
errch <- nil
connected = true
}
reader := NewEventStreamReader(resp.Body)
for {
// Read each new line and process the type of event
event, err := reader.ReadEvent()
if err != nil {
if err == io.EOF {
c.cleanup(resp, ch)
return nil
}
// run user specified disconnect function
if c.disconnectcb != nil {
c.disconnectcb(c)
}
return err
}
// If we get an error, ignore it.
if msg, err := c.processEvent(event); err == nil {
if len(msg.ID) > 0 {
c.EventID = string(msg.ID)
} else {
msg.ID = []byte(c.EventID)
}
select {
case <-c.subscribed[ch]:
c.cleanup(resp, ch)
return nil
case ch <- msg:
// message sent
}
}
}
}
err := backoff.Retry(operation, backoff.NewExponentialBackOff())
if err != nil && !connected {
errch <- err
}
}()
err := <-errch
close(errch)
return err
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L296-L299
|
func (m Sequence) MutateTransaction(o *TransactionBuilder) error {
o.TX.SeqNum = xdr.SequenceNumber(m.Sequence)
return nil
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/proxy/grpcproxy/health.go#L28-L30
|
func HandleHealth(mux *http.ServeMux, c *clientv3.Client) {
mux.Handle(etcdhttp.PathHealth, etcdhttp.NewHealthHandler(func() etcdhttp.Health { return checkHealth(c) }))
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L148-L201
|
func (x *Index) PutMulti(c context.Context, ids []string, srcs []interface{}) ([]string, error) {
if len(ids) != 0 && len(srcs) != len(ids) {
return nil, fmt.Errorf("search: PutMulti expects ids and srcs slices of the same length")
}
if len(srcs) > maxDocumentsPerPutDelete {
return nil, ErrTooManyDocuments
}
docs := make([]*pb.Document, len(srcs))
for i, s := range srcs {
var err error
docs[i], err = saveDoc(s)
if err != nil {
return nil, err
}
if len(ids) != 0 && ids[i] != "" {
if !validIndexNameOrDocID(ids[i]) {
return nil, fmt.Errorf("search: invalid ID %q", ids[i])
}
docs[i].Id = proto.String(ids[i])
}
}
// spec is modified by Call when applying the current Namespace, so copy it to
// avoid retaining the namespace beyond the scope of the Call.
spec := x.spec
req := &pb.IndexDocumentRequest{
Params: &pb.IndexDocumentParams{
Document: docs,
IndexSpec: &spec,
},
}
res := &pb.IndexDocumentResponse{}
if err := internal.Call(c, "search", "IndexDocument", req, res); err != nil {
return nil, err
}
multiErr, hasErr := make(appengine.MultiError, len(res.Status)), false
for i, s := range res.Status {
if s.GetCode() != pb.SearchServiceError_OK {
multiErr[i] = fmt.Errorf("search: %s: %s", s.GetCode(), s.GetErrorDetail())
hasErr = true
}
}
if hasErr {
return res.DocId, multiErr
}
if len(res.Status) != len(docs) || len(res.DocId) != len(docs) {
return nil, fmt.Errorf("search: internal error: wrong number of results (%d Statuses, %d DocIDs, expected %d)",
len(res.Status), len(res.DocId), len(docs))
}
return res.DocId, nil
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/draw2dgl/gc.go#L297-L299
|
func (gc *GraphicContext) recalc() {
gc.Current.Scale = gc.Current.FontSize * float64(gc.DPI) * (64.0 / 72.0)
}
|
https://github.com/piotrkowalczuk/mnemosyne/blob/66d59c3c5b886e8e869915bb76257bcba4a47250/internal/cluster/cluster.go#L145-L161
|
func (c *Cluster) GetOther(accessToken string) (*Node, bool) {
if c == nil {
return nil, false
}
if c.Len() == 1 {
return nil, false
}
if node, ok := c.Get(jump.HashString(accessToken, c.Len())); ok {
if node.Addr != c.listen {
if node.Client != nil {
return node, true
}
}
}
return nil, false
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L647-L653
|
func (h *dbHashTree) Destroy() error {
path := h.Path()
if err := h.Close(); err != nil {
return err
}
return os.Remove(path)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L8565-L8569
|
func (v *AuthChallengeResponse) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork67(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/plugins.go#L389-L416
|
func EventsForPlugin(name string) []string {
var events []string
if _, ok := issueHandlers[name]; ok {
events = append(events, "issue")
}
if _, ok := issueCommentHandlers[name]; ok {
events = append(events, "issue_comment")
}
if _, ok := pullRequestHandlers[name]; ok {
events = append(events, "pull_request")
}
if _, ok := pushEventHandlers[name]; ok {
events = append(events, "push")
}
if _, ok := reviewEventHandlers[name]; ok {
events = append(events, "pull_request_review")
}
if _, ok := reviewCommentEventHandlers[name]; ok {
events = append(events, "pull_request_review_comment")
}
if _, ok := statusEventHandlers[name]; ok {
events = append(events, "status")
}
if _, ok := genericCommentHandlers[name]; ok {
events = append(events, "GenericCommentEvent (any event for user text)")
}
return events
}
|
https://github.com/ikawaha/kagome.ipadic/blob/fe03f87a0c7c32945d956fcfc934c3e11d5eb182/cmd/kagome/tokenize/cmd.go#L54-L67
|
func newOption(w io.Writer, eh flag.ErrorHandling) (o *option) {
o = &option{
flagSet: flag.NewFlagSet(CommandName, eh),
}
// option settings
o.flagSet.SetOutput(w)
o.flagSet.StringVar(&o.file, "file", "", "input file")
o.flagSet.StringVar(&o.dic, "dic", "", "dic")
o.flagSet.StringVar(&o.udic, "udic", "", "user dic")
o.flagSet.StringVar(&o.sysdic, "sysdic", "normal", "system dic type (normal|simple)")
o.flagSet.StringVar(&o.mode, "mode", "normal", "tokenize mode (normal|search|extended)")
return
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/amount/main.go#L25-L31
|
func MustParse(v string) xdr.Int64 {
ret, err := Parse(v)
if err != nil {
panic(err)
}
return ret
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/image/docker_schema1.go#L76-L92
|
func (m *manifestSchema1) EmbeddedDockerReferenceConflicts(ref reference.Named) bool {
// This is a bit convoluted: We can’t just have a "get embedded docker reference" method
// and have the “does it conflict” logic in the generic copy code, because the manifest does not actually
// embed a full docker/distribution reference, but only the repo name and tag (without the host name).
// So we would have to provide a “return repo without host name, and tag” getter for the generic code,
// which would be very awkward. Instead, we do the matching here in schema1-specific code, and all the
// generic copy code needs to know about is reference.Named and that a manifest may need updating
// for some destinations.
name := reference.Path(ref)
var tag string
if tagged, isTagged := ref.(reference.NamedTagged); isTagged {
tag = tagged.Tag()
} else {
tag = ""
}
return m.m.Name != name || m.m.Tag != tag
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/css/easyjson.go#L5812-L5816
|
func (v EventStyleSheetRemoved) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoCss51(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/util/http.go#L80-L121
|
func HTTPClient(certificate string, proxy proxyFunc) (*http.Client, error) {
var err error
var cert *x509.Certificate
if certificate != "" {
certBlock, _ := pem.Decode([]byte(certificate))
if certBlock == nil {
return nil, fmt.Errorf("Invalid certificate")
}
cert, err = x509.ParseCertificate(certBlock.Bytes)
if err != nil {
return nil, err
}
}
tlsConfig, err := shared.GetTLSConfig("", "", "", cert)
if err != nil {
return nil, err
}
tr := &http.Transport{
TLSClientConfig: tlsConfig,
Dial: shared.RFC3493Dialer,
Proxy: proxy,
DisableKeepAlives: true,
}
myhttp := http.Client{
Transport: tr,
}
// Setup redirect policy
myhttp.CheckRedirect = func(req *http.Request, via []*http.Request) error {
// Replicate the headers
req.Header = via[len(via)-1].Header
return nil
}
return &myhttp, nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/request_logger.go#L20-L56
|
func RequestLoggerFunc(h Handler) Handler {
return func(c Context) error {
var irid interface{}
if irid = c.Session().Get("requestor_id"); irid == nil {
irid = randx.String(10)
c.Session().Set("requestor_id", irid)
c.Session().Save()
}
rid := irid.(string) + "-" + randx.String(10)
c.Set("request_id", rid)
c.LogField("request_id", rid)
start := time.Now()
defer func() {
ws, ok := c.Response().(*Response)
if !ok {
ws = &Response{ResponseWriter: c.Response()}
ws.Status = 200
}
req := c.Request()
ct := httpx.ContentType(req)
if ct != "" {
c.LogField("content_type", ct)
}
c.LogFields(map[string]interface{}{
"method": req.Method,
"path": req.URL.String(),
"duration": time.Since(start),
"size": ws.Size,
"human_size": humanize.Bytes(uint64(ws.Size)),
"status": ws.Status,
})
c.Logger().Info(req.URL.String())
}()
return h(c)
}
}
|
https://github.com/tylerb/gls/blob/e606233f194d6c314156dc6a35f21a42a470c6f6/gls.go#L80-L85
|
func Cleanup() {
gid := curGoroutineID()
dataLock.Lock()
delete(data, gid)
dataLock.Unlock()
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4152-L4160
|
func (u OperationResultTr) MustAllowTrustResult() AllowTrustResult {
val, ok := u.GetAllowTrustResult()
if !ok {
panic("arm AllowTrustResult is not set")
}
return val
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/easyjson.go#L399-L403
|
func (v Histogram) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoBrowser3(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L36-L53
|
func (r *ProtocolLXD) GetImageFingerprints() ([]string, error) {
urls := []string{}
// Fetch the raw value
_, err := r.queryStruct("GET", "/images", nil, "", &urls)
if err != nil {
return nil, err
}
// Parse it
fingerprints := []string{}
for _, url := range urls {
fields := strings.Split(url, "/images/")
fingerprints = append(fingerprints, fields[len(fields)-1])
}
return fingerprints, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/tide.go#L930-L988
|
func tryMerge(mergeFunc func() error) (bool, error) {
var err error
const maxRetries = 3
backoff := time.Second * 4
for retry := 0; retry < maxRetries; retry++ {
if err = mergeFunc(); err == nil {
// Successful merge!
return true, nil
}
// TODO: Add a config option to abort batches if a PR in the batch
// cannot be merged for any reason. This would skip merging
// not just the changed PR, but also the other PRs in the batch.
// This shouldn't be the default behavior as merging batches is high
// priority and this is unlikely to be problematic.
// Note: We would also need to be able to roll back any merges for the
// batch that were already successfully completed before the failure.
// Ref: https://github.com/kubernetes/test-infra/issues/10621
if _, ok := err.(github.ModifiedHeadError); ok {
// This is a possible source of incorrect behavior. If someone
// modifies their PR as we try to merge it in a batch then we
// end up in an untested state. This is unlikely to cause any
// real problems.
return true, fmt.Errorf("PR was modified: %v", err)
} else if _, ok = err.(github.UnmergablePRBaseChangedError); ok {
// complained that the base branch was modified. This is a
// strange error because the API doesn't even allow the request to
// specify the base branch sha, only the head sha.
// We suspect that github is complaining because we are making the
// merge requests too rapidly and it cannot recompute mergability
// in time. https://github.com/kubernetes/test-infra/issues/5171
// We handle this by sleeping for a few seconds before trying to
// merge again.
err = fmt.Errorf("base branch was modified: %v", err)
if retry+1 < maxRetries {
sleep(backoff)
backoff *= 2
}
} else if _, ok = err.(github.UnauthorizedToPushError); ok {
// GitHub let us know that the token used cannot push to the branch.
// Even if the robot is set up to have write access to the repo, an
// overzealous branch protection setting will not allow the robot to
// push to a specific branch.
// We won't be able to merge the other PRs.
return false, fmt.Errorf("branch needs to be configured to allow this robot to push: %v", err)
} else if _, ok = err.(github.MergeCommitsForbiddenError); ok {
// GitHub let us know that the merge method configured for this repo
// is not allowed by other repo settings, so we should let the admins
// know that the configuration needs to be updated.
// We won't be able to merge the other PRs.
return false, fmt.Errorf("Tide needs to be configured to use the 'rebase' merge method for this repo or the repo needs to allow merge commits: %v", err)
} else if _, ok = err.(github.UnmergablePRError); ok {
return true, fmt.Errorf("PR is unmergable. Do the Tide merge requirements match the GitHub settings for the repo? %v", err)
} else {
return true, err
}
}
// We ran out of retries. Return the last transient error.
return true, err
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/reflect.go#L195-L227
|
func typeToTyp3(rt reflect.Type, opts FieldOptions) Typ3 {
switch rt.Kind() {
case reflect.Interface:
return Typ3_ByteLength
case reflect.Array, reflect.Slice:
return Typ3_ByteLength
case reflect.String:
return Typ3_ByteLength
case reflect.Struct, reflect.Map:
return Typ3_ByteLength
case reflect.Int64, reflect.Uint64:
if opts.BinFixed64 {
return Typ3_8Byte
} else {
return Typ3_Varint
}
case reflect.Int32, reflect.Uint32:
if opts.BinFixed32 {
return Typ3_4Byte
} else {
return Typ3_Varint
}
case reflect.Int16, reflect.Int8, reflect.Int,
reflect.Uint16, reflect.Uint8, reflect.Uint, reflect.Bool:
return Typ3_Varint
case reflect.Float64:
return Typ3_8Byte
case reflect.Float32:
return Typ3_4Byte
default:
panic(fmt.Sprintf("unsupported field type %v", rt))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L1926-L1930
|
func (v ReloadParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage21(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L564-L567
|
func (e ThresholdIndexes) ValidEnum(v int32) bool {
_, ok := thresholdIndexesMap[v]
return ok
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/types.go#L376-L392
|
func (t *ResourcePriority) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch ResourcePriority(in.String()) {
case ResourcePriorityVeryLow:
*t = ResourcePriorityVeryLow
case ResourcePriorityLow:
*t = ResourcePriorityLow
case ResourcePriorityMedium:
*t = ResourcePriorityMedium
case ResourcePriorityHigh:
*t = ResourcePriorityHigh
case ResourcePriorityVeryHigh:
*t = ResourcePriorityVeryHigh
default:
in.AddError(errors.New("unknown ResourcePriority value"))
}
}
|
https://github.com/kljensen/snowball/blob/115fa8f6419dcfb9ec4653997b1c6803a5eff962/snowballword/snowballword.go#L109-L122
|
func (w *SnowballWord) slice(start, stop int) []rune {
startMin := 0
if start < startMin {
start = startMin
}
max := len(w.RS) - 1
if start > max {
start = max
}
if stop > max {
stop = max
}
return w.RS[start:stop]
}
|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/json/decode.go#L12-L14
|
func NewDecoder(r io.Reader) *objconv.Decoder {
return objconv.NewDecoder(NewParser(r))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/database/database.go#L63-L68
|
func ExecuteSQL(databaseID ID, query string) *ExecuteSQLParams {
return &ExecuteSQLParams{
DatabaseID: databaseID,
Query: query,
}
}
|
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L177-L179
|
func (c *Client) Query(dataset, project, queryStr string) ([][]interface{}, []string, error) {
return c.pagedQuery(defaultPageSize, dataset, project, queryStr, nil)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/containers.mapper.go#L564-L658
|
func (c *ClusterTx) ContainerConfigRef(filter ContainerFilter) (map[string]map[string]map[string]string, error) {
// Result slice.
objects := make([]struct {
Project string
Name string
Key string
Value string
}, 0)
// Check which filter criteria are active.
criteria := map[string]interface{}{}
if filter.Project != "" {
criteria["Project"] = filter.Project
}
if filter.Name != "" {
criteria["Name"] = filter.Name
}
if filter.Parent != "" {
criteria["Parent"] = filter.Parent
}
// Pick the prepared statement and arguments to use based on active criteria.
var stmt *sql.Stmt
var args []interface{}
if criteria["Project"] != nil && criteria["Name"] != nil {
stmt = c.stmt(containerConfigRefByProjectAndName)
args = []interface{}{
filter.Project,
filter.Name,
}
} else if criteria["Project"] != nil && criteria["Node"] != nil {
stmt = c.stmt(containerConfigRefByProjectAndNode)
args = []interface{}{
filter.Project,
filter.Node,
}
} else if criteria["Node"] != nil {
stmt = c.stmt(containerConfigRefByNode)
args = []interface{}{
filter.Node,
}
} else if criteria["Project"] != nil {
stmt = c.stmt(containerConfigRefByProject)
args = []interface{}{
filter.Project,
}
} else {
stmt = c.stmt(containerConfigRef)
args = []interface{}{}
}
// Dest function for scanning a row.
dest := func(i int) []interface{} {
objects = append(objects, struct {
Project string
Name string
Key string
Value string
}{})
return []interface{}{
&objects[i].Project,
&objects[i].Name,
&objects[i].Key,
&objects[i].Value,
}
}
// Select.
err := query.SelectObjects(stmt, dest, args...)
if err != nil {
return nil, errors.Wrap(err, "Failed to fetch ref for containers")
}
// Build index by primary name.
index := map[string]map[string]map[string]string{}
for _, object := range objects {
_, ok := index[object.Project]
if !ok {
subIndex := map[string]map[string]string{}
index[object.Project] = subIndex
}
item, ok := index[object.Project][object.Name]
if !ok {
item = map[string]string{}
}
index[object.Project][object.Name] = item
item[object.Key] = object.Value
}
return index, nil
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L303-L305
|
func (m SourceAccount) MutateTransaction(o *TransactionBuilder) error {
return setAccountId(m.AddressOrSeed, &o.TX.SourceAccount)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/networks.go#L264-L288
|
func (c *Cluster) networks(where string, args ...interface{}) ([]string, error) {
q := "SELECT name FROM networks"
inargs := []interface{}{}
if where != "" {
q += fmt.Sprintf(" WHERE %s", where)
for _, arg := range args {
inargs = append(inargs, arg)
}
}
var name string
outfmt := []interface{}{name}
result, err := queryScan(c.db, q, inargs, outfmt)
if err != nil {
return []string{}, err
}
response := []string{}
for _, r := range result {
response = append(response, r[0].(string))
}
return response, nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/external-plugins/cherrypicker/server.go#L508-L514
|
func releaseNoteFromParentPR(body string) string {
potentialMatch := releaseNoteRe.FindStringSubmatch(body)
if potentialMatch == nil {
return ""
}
return fmt.Sprintf("```release-note\n%s\n```", strings.TrimSpace(potentialMatch[1]))
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/security/types.go#L42-L44
|
func (t MixedContentType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/controller.go#L135-L151
|
func (c *Controller) IntRangeZoom(fieldName string, p interface{}, n int, m int, zoom int) int {
if p == nil {
p = 0
}
value, ok := c.toNumber(p)
if ok == false {
panic((&ValidationError{}).New(fieldName + "必须是数字"))
}
b := c.Validate.Range(value, n, m)
if b == false {
fN := fmt.Sprintf("%.2f", float64(n)/float64(zoom))
fM := fmt.Sprintf("%.2f", float64(m)/float64(zoom))
panic((&ValidationError{}).New(fieldName + "值的范围应该从 " + fN + " 到 " + fM))
}
return value
}
|
https://github.com/coryb/figtree/blob/e5fa026ccd54e0a6a99b6d81f73bfcc8e6fe6a6b/gen-rawoption.go#L4151-L4156
|
func (o *ListUint64Option) Set(value string) error {
val := Uint64Option{}
val.Set(value)
*o = append(*o, val)
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domstorage/easyjson.go#L796-L800
|
func (v EventDomStorageItemRemoved) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomstorage7(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L69-L72
|
func (p ResetPermissionsParams) WithBrowserContextID(browserContextID target.BrowserContextID) *ResetPermissionsParams {
p.BrowserContextID = browserContextID
return &p
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/inmem_transport.go#L175-L177
|
func (i *InmemTransport) EncodePeer(id ServerID, p ServerAddress) []byte {
return []byte(p)
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/task/task.go#L30-L56
|
func RunAnnotated(task Task, description string, symbol string, options ...interface{}) error {
doneCh := make(chan bool)
errCh := make(chan error)
l := logger.Log
t := DefaultTicker
for _, o := range options {
if value, ok := o.(logger.Logger); ok {
l = value
} else if value, ok := o.(*time.Ticker); ok {
t = value
}
}
go func() {
errCh <- task()
}()
l(description)
logActivity(symbol, l, t, doneCh)
err := <-errCh
doneCh <- true
return err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/accessibility/easyjson.go#L1229-L1233
|
func (v GetFullAXTreeReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoAccessibility7(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L747-L750
|
func (p PrintToPDFParams) WithPageRanges(pageRanges string) *PrintToPDFParams {
p.PageRanges = pageRanges
return &p
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/node.go#L42-L46
|
func (n Node) Size() int {
return int(unsafe.Sizeof(n) +
uintptr(n.level+1)*(unsafe.Sizeof(unsafe.Pointer(nil))+
unsafe.Sizeof(NodeRef{})))
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/api.go#L113-L119
|
func projectParam(request *http.Request) string {
project := queryParam(request, "project")
if project == "" {
project = "default"
}
return project
}
|
https://github.com/qor/roles/blob/d6375609fe3e5da46ad3a574fae244fb633e79c1/permissioner.go#L22-L30
|
func (ps permissioners) HasPermission(mode PermissionMode, roles ...interface{}) bool {
for _, p := range ps {
if p != nil && !p.HasPermission(mode, roles) {
return false
}
}
return true
}
|
https://github.com/mgutz/str/blob/968bf66e3da857419e4f6e71b2d5c9ae95682dc4/funcsAO.go#L156-L163
|
func Dasherize(s string) string {
s = strings.TrimSpace(s)
s = spaceUnderscoreRe.ReplaceAllString(s, "-")
s = capitalsRe.ReplaceAllString(s, "-$1")
s = dashesRe.ReplaceAllString(s, "-")
s = strings.ToLower(s)
return s
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L314-L316
|
func (w *WriteBuffer) DeferBytes(n int) BytesRef {
return BytesRef(w.deferred(n))
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/codegen_client.go#L1768-L1770
|
func (r *ServerArray) Locator(api *API) *ServerArrayLocator {
return api.ServerArrayLocator(r.Href)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/client.go#L334-L339
|
func (c *Client) dialWithBalancer(ep string, dopts ...grpc.DialOption) (*grpc.ClientConn, error) {
_, host, _ := endpoint.ParseEndpoint(ep)
target := c.resolverGroup.Target(host)
creds := c.dialWithBalancerCreds(ep)
return c.dial(target, creds, dopts...)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L6965-L6969
|
func (v *ClearCompilationCacheParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage76(&r, v)
return r.Error()
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/cookies.go#L25-L33
|
func (c *Cookies) Set(name, value string, maxAge time.Duration) {
ck := http.Cookie{
Name: name,
Value: value,
MaxAge: int(maxAge.Seconds()),
}
http.SetCookie(c.res, &ck)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L222-L225
|
func (p DispatchMouseEventParams) WithClickCount(clickCount int64) *DispatchMouseEventParams {
p.ClickCount = clickCount
return &p
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/matcher.go#L291-L324
|
func match(srcType reflect.Type, params params) Matcher {
switch kind := srcType.Kind(); kind {
case reflect.Ptr:
return match(srcType.Elem(), params)
case reflect.Slice, reflect.Array:
return EachLike(match(srcType.Elem(), getDefaults()), params.slice.min)
case reflect.Struct:
result := StructMatcher{}
for i := 0; i < srcType.NumField(); i++ {
field := srcType.Field(i)
result[field.Tag.Get("json")] = match(field.Type, pluckParams(field.Type, field.Tag.Get("pact")))
}
return result
case reflect.String:
if params.str.regEx != "" {
return Term(params.str.example, params.str.regEx)
}
if params.str.example != "" {
return Like(params.str.example)
}
return Like("string")
case reflect.Bool:
return Like(true)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return Like(1)
case reflect.Float32, reflect.Float64:
return Like(1.1)
default:
panic(fmt.Sprintf("match: unhandled type: %v", srcType))
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/branchprotector/protect.go#L267-L291
|
func (p *protector) UpdateBranch(orgName, repo string, branchName string, branch config.Branch, protected bool) error {
bp, err := p.cfg.GetPolicy(orgName, repo, branchName, branch)
if err != nil {
return fmt.Errorf("get policy: %v", err)
}
if bp == nil || bp.Protect == nil {
return nil
}
if !protected && !*bp.Protect {
logrus.Infof("%s/%s=%s: already unprotected", orgName, repo, branchName)
return nil
}
var req *github.BranchProtectionRequest
if *bp.Protect {
r := makeRequest(*bp)
req = &r
}
p.updates <- requirements{
Org: orgName,
Repo: repo,
Branch: branchName,
Request: req,
}
return nil
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/managed_db.go#L48-L58
|
func (txn *Txn) CommitAt(commitTs uint64, callback func(error)) error {
if !txn.db.opt.managedTxns {
panic("Cannot use CommitAt with managedDB=false. Use Commit instead.")
}
txn.commitTs = commitTs
if callback == nil {
return txn.Commit()
}
txn.CommitWith(callback)
return nil
}
|
https://github.com/google/shlex/blob/c34317bd91bf98fab745d77b03933cf8769299fe/shlex.go#L176-L182
|
func NewTokenizer(r io.Reader) *Tokenizer {
input := bufio.NewReader(r)
classifier := newDefaultClassifier()
return &Tokenizer{
input: *input,
classifier: classifier}
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/page.go#L292-L297
|
func (p *Page) EnterPopupText(text string) error {
if err := p.session.SetAlertText(text); err != nil {
return fmt.Errorf("failed to enter popup text: %s", err)
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L294-L298
|
func (v *SetPressureNotificationsSuppressedParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoMemory3(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/lease_command.go#L88-L101
|
func leaseRevokeCommandFunc(cmd *cobra.Command, args []string) {
if len(args) != 1 {
ExitWithError(ExitBadArgs, fmt.Errorf("lease revoke command needs 1 argument"))
}
id := leaseFromArgs(args[0])
ctx, cancel := commandCtx(cmd)
resp, err := mustClientFromCmd(cmd).Revoke(ctx, id)
cancel()
if err != nil {
ExitWithError(ExitError, fmt.Errorf("failed to revoke lease (%v)", err))
}
display.Revoke(id, *resp)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L369-L373
|
func (v *SetShowFPSCounterParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoOverlay4(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/lgtm/lgtm.go#L518-L524
|
func loadReviewers(ro repoowners.RepoOwner, filenames []string) sets.String {
reviewers := sets.String{}
for _, filename := range filenames {
reviewers = reviewers.Union(ro.Approvers(filename)).Union(ro.Reviewers(filename))
}
return reviewers
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/daemon.go#L143-L147
|
func DefaultDaemon() *Daemon {
config := DefaultDaemonConfig()
os := sys.DefaultOS()
return NewDaemon(config, os)
}
|
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/auth/jwt.go#L106-L110
|
func Extractor(e request.Extractor) TokenOpt {
return TokenOpt{func(o *options) {
o.extractor = e
}}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/backoff/exponential.go#L176-L183
|
func (b *ExponentialBackOff) NextBackOff() time.Duration {
// Make sure we have not gone over the maximum elapsed time.
if b.MaxElapsedTime != 0 && b.GetElapsedTime() > b.MaxElapsedTime {
return Stop
}
defer b.incrementCurrentInterval()
return getRandomValueFromInterval(b.RandomizationFactor, rand.Float64(), b.currentInterval)
}
|
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2016-L2025
|
func (u OperationBody) GetAllowTrustOp() (result AllowTrustOp, ok bool) {
armName, _ := u.ArmForSwitch(int32(u.Type))
if armName == "AllowTrustOp" {
result = *u.AllowTrustOp
ok = true
}
return
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/logger.go#L119-L121
|
func NewLogger(writer io.Writer, fields ...LogField) Logger {
return &writerLogger{writer, fields}
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/introspection.go#L207-L241
|
func (ch *Channel) IntrospectState(opts *IntrospectionOptions) *RuntimeState {
if opts == nil {
opts = &IntrospectionOptions{}
}
ch.mutable.RLock()
state := ch.mutable.state
numConns := len(ch.mutable.conns)
inactiveConns := make([]*Connection, 0, numConns)
connIDs := make([]uint32, 0, numConns)
for id, conn := range ch.mutable.conns {
connIDs = append(connIDs, id)
if !conn.IsActive() {
inactiveConns = append(inactiveConns, conn)
}
}
ch.mutable.RUnlock()
ch.State()
return &RuntimeState{
ID: ch.chID,
ChannelState: state.String(),
CreatedStack: ch.createdStack,
LocalPeer: ch.PeerInfo(),
SubChannels: ch.subChannels.IntrospectState(opts),
RootPeers: ch.RootPeers().IntrospectState(opts),
Peers: ch.Peers().IntrospectList(opts),
NumConnections: numConns,
Connections: connIDs,
InactiveConnections: getConnectionRuntimeState(inactiveConns, opts),
OtherChannels: ch.IntrospectOthers(opts),
RuntimeVersion: introspectRuntimeVersion(),
}
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L69-L77
|
func Split(src, imgBlue, imgGreen, imgRed, imgAlpha *IplImage) {
C.cvSplit(
unsafe.Pointer(src),
unsafe.Pointer(imgBlue),
unsafe.Pointer(imgGreen),
unsafe.Pointer(imgRed),
unsafe.Pointer(imgAlpha),
)
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/rpcerror/grpc.go#L37-L42
|
func StreamClientInterceptor(fn ConvertFunc) grpc.StreamClientInterceptor {
return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (stream grpc.ClientStream, err error) {
stream, err = streamer(ctx, desc, cc, method, opts...)
return stream, fn(err)
}
}
|
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/route.go#L42-L48
|
func Head(pathExp string, handlerFunc HandlerFunc) *Route {
return &Route{
HttpMethod: "HEAD",
PathExp: pathExp,
Func: handlerFunc,
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/deck/badge.go#L55-L84
|
func makeShield(subject, status, color string) []byte {
// TODO(rmmh): Use better font-size metrics for prettier badges-- estimating
// character widths as 6px isn't very accurate.
// See also: https://github.com/badges/shields/blob/master/measure-text.js
p := struct {
Width, RightStart, RightWidth int
XposLeft, XposRight float64
Subject, Status string
Color string
}{
Subject: subject,
Status: status,
RightStart: 13 + 6*len(subject),
RightWidth: 13 + 6*len(status),
}
p.Width = p.RightStart + p.RightWidth
p.XposLeft = float64(p.RightStart) * 0.5
p.XposRight = float64(p.RightStart) + float64(p.RightWidth-2)*0.5
switch color {
case "brightgreen":
p.Color = "#4c1"
case "red":
p.Color = "#e05d44"
default:
p.Color = color
}
var buf bytes.Buffer
svgTemplate.Execute(&buf, p)
return buf.Bytes()
}
|
https://github.com/dailyburn/bigquery/blob/b6f18972580ed8882d195da0e9b7c9b94902a1ea/client/client.go#L519-L529
|
func (c *Client) Count(dataset, project, datasetTable string) int64 {
qstr := fmt.Sprintf("select count(*) from [%s]", datasetTable)
res, err := c.SyncQuery(dataset, project, qstr, 1)
if err == nil {
if len(res) > 0 {
val, _ := strconv.ParseInt(res[0][0].(string), 10, 64)
return val
}
}
return 0
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/skiplist/builder.go#L79-L112
|
func (b *Builder) Assemble(segments ...*Segment) *Skiplist {
tail := make([]*Node, MaxLevel+1)
head := make([]*Node, MaxLevel+1)
for _, seg := range segments {
for l := 0; l <= MaxLevel; l++ {
if tail[l] != nil && seg.head[l] != nil {
tail[l].setNext(l, seg.head[l], false)
} else if head[l] == nil && seg.head[l] != nil {
head[l] = seg.head[l]
}
if seg.tail[l] != nil {
tail[l] = seg.tail[l]
}
}
}
for l := 0; l <= MaxLevel; l++ {
if head[l] != nil {
b.store.head.setNext(l, head[l], false)
}
if tail[l] != nil {
tail[l].setNext(l, b.store.tail, false)
}
}
for _, seg := range segments {
b.store.Stats.Merge(&seg.sts)
}
return b.store
}
|
https://github.com/t3rm1n4l/nitro/blob/937fe99f63a01a8bea7661c49e2f3f8af6541d7c/nodetable/table.go#L273-L283
|
func (nt *NodeTable) Close() {
nt.fastHTCount = 0
nt.slowHTCount = 0
nt.conflicts = 0
nt.fastHT = make(map[uint32]uint64)
nt.slowHT = make(map[uint32][]uint64)
buf := dbInstances.MakeBuf()
defer dbInstances.FreeBuf(buf)
dbInstances.Delete(unsafe.Pointer(nt), CompareNodeTable, buf, &dbInstances.Stats)
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/writeto.go#L15-L19
|
func (m *Message) WriteTo(w io.Writer) (int64, error) {
mw := &messageWriter{w: w}
mw.writeMessage(m)
return mw.n, mw.err
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L3297-L3301
|
func (v EventExecutionContextsCleared) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime30(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/llgcode/draw2d/blob/f52c8a71aff06ab8df41843d33ab167b36c971cd/font.go#L172-L178
|
func NewSyncFolderFontCache(folder string) *SyncFolderFontCache {
return &SyncFolderFontCache{
fonts: make(map[string]*truetype.Font),
folder: folder,
namer: FontFileName,
}
}
|
https://github.com/qor/roles/blob/d6375609fe3e5da46ad3a574fae244fb633e79c1/permission.go#L77-L87
|
func (permission *Permission) Allow(mode PermissionMode, roles ...string) *Permission {
if mode == CRUD {
return permission.Allow(Create, roles...).Allow(Update, roles...).Allow(Read, roles...).Allow(Delete, roles...)
}
if permission.AllowedRoles[mode] == nil {
permission.AllowedRoles[mode] = []string{}
}
permission.AllowedRoles[mode] = append(permission.AllowedRoles[mode], roles...)
return permission
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/errors/http.go#L63-L90
|
func HTTPStatusToType(status int) Type {
switch status {
case http.StatusBadRequest:
return InvalidArgument
case http.StatusNotFound:
return NotFound
case http.StatusConflict:
return Conflict
case http.StatusUnauthorized:
return Unauthorized
case http.StatusForbidden:
return PermissionDenied
case http.StatusRequestTimeout:
return Timeout
case http.StatusNotImplemented:
return NotImplemented
case http.StatusBadGateway:
case http.StatusServiceUnavailable:
return TemporarilyUnavailable
case http.StatusGone:
return PermanentlyUnavailable
case http.StatusTooManyRequests:
return ResourceExhausted
case http.StatusInternalServerError:
return Unknown
}
return Unknown
}
|
https://github.com/apparentlymart/go-rundeck-api/blob/2c962acae81080a937c350a5bea054c239f27a81/rundeck/job.go#L343-L345
|
func (c *Client) CreateOrUpdateJob(job *JobDetail) (*JobSummary, error) {
return c.importJob(job, "update")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.