_id
stringlengths 86
170
| text
stringlengths 54
39.3k
|
|---|---|
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/objutil/tag.go#L19-L41
|
func ParseTag(s string) Tag {
var name string
var omitzero bool
var omitempty bool
name, s = parseNextTagToken(s)
for len(s) != 0 {
var token string
switch token, s = parseNextTagToken(s); token {
case "omitempty":
omitempty = true
case "omitzero":
omitzero = true
}
}
return Tag{
Name: name,
Omitempty: omitempty,
Omitzero: omitzero,
}
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/rand/cryptorand.go#L48-L58
|
func GenerateRandomInt64(min, max int64) int64 {
upper := max - min
nBig, err := rand.Int(rand.Reader, big.NewInt(upper))
if err != nil {
panic(err)
}
return nBig.Int64() + min
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssm/codegen_client.go#L120-L122
|
func (api *API) ExecutionLocator(href string) *ExecutionLocator {
return &ExecutionLocator{Href(href), api}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/browser/browser.go#L276-L285
|
func (p *GetHistogramParams) Do(ctx context.Context) (histogram *Histogram, err error) {
// execute
var res GetHistogramReturns
err = cdp.Execute(ctx, CommandGetHistogram, p, &res)
if err != nil {
return nil, err
}
return res.Histogram, nil
}
|
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/google/compute/resources/instancegroup.go#L338-L371
|
func (r *InstanceGroup) Delete(actual cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {
logger.Debug("instanceGroup.Delete")
deleteResource := actual.(*InstanceGroup)
if deleteResource.Name == "" {
return nil, nil, fmt.Errorf("Unable to delete instance resource without Name [%s]", deleteResource.Name)
}
logger.Success("Deleting InstanceGroup manager [%s]", r.ServerPool.Name)
_, err := Sdk.Service.InstanceGroupManagers.Get(immutable.ProviderConfig().CloudId, immutable.ProviderConfig().Location, strings.ToLower(r.ServerPool.Name)).Do()
if err == nil {
_, err := Sdk.Service.InstanceGroupManagers.Delete(immutable.ProviderConfig().CloudId, immutable.ProviderConfig().Location, strings.ToLower(r.ServerPool.Name)).Do()
if err != nil {
return nil, nil, err
}
}
_, err = Sdk.Service.InstanceTemplates.Get(immutable.ProviderConfig().CloudId, strings.ToLower(r.ServerPool.Name)).Do()
if err == nil {
err := r.retryDeleteInstanceTemplate(immutable)
if err != nil {
return nil, nil, err
}
}
// Kubernetes API
providerConfig := immutable.ProviderConfig()
providerConfig.KubernetesAPI.Endpoint = ""
immutable.SetProviderConfig(providerConfig)
renderedCluster, err := r.immutableRender(actual, immutable)
if err != nil {
return nil, nil, err
}
return renderedCluster, actual, nil
}
|
https://github.com/naoina/genmai/blob/78583835e1e41e3938e1ddfffd7101f8ad27fae0/genmai.go#L896-L910
|
func (db *DB) defaultFromTag(field *reflect.StructField) (string, error) {
def := field.Tag.Get(dbDefaultTag)
if def == "" {
return "", nil
}
switch field.Type.Kind() {
case reflect.Bool:
b, err := strconv.ParseBool(def)
if err != nil {
return "", err
}
return fmt.Sprintf("DEFAULT %v", db.dialect.FormatBool(b)), nil
}
return fmt.Sprintf("DEFAULT %v", def), nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/kube/client.go#L557-L567
|
func (c *Client) GetLogTail(pod, container string, n int64) ([]byte, error) {
c.log("GetLogTail", pod, n)
return c.requestRetry(&request{
path: fmt.Sprintf("/api/v1/namespaces/%s/pods/%s/log", c.namespace, pod),
query: map[string]string{ // Because we want last n bytes, we fetch all lines and then limit to n bytes
"tailLines": "-1",
"container": container,
"limitBytes": strconv.FormatInt(n, 10),
},
})
}
|
https://github.com/nicholasjackson/bench/blob/2df9635f0ad020b2e82616b0fd87130aaa1ee12e/example/main.go#L27-L41
|
func AmazonRequest() error {
resp, err := http.Get("http://www.amazon.co.uk/")
defer func(response *http.Response) {
if response != nil && response.Body != nil {
response.Body.Close()
}
}(resp)
if err != nil || resp.StatusCode != 200 {
return err
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/easyjson.go#L1052-L1056
|
func (v *ApplicationCache) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoApplicationcache11(&r, v)
return r.Error()
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/tnet/listener.go#L77-L81
|
func (s *listener) Accept() (net.Conn, error) {
s.incRef()
defer s.decRef()
return s.Listener.Accept()
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L396-L407
|
func (s *FileSequence) frameInt(frame int) string {
var zframe string
if s.frameSet != nil {
zframe = zfillInt(frame, s.zfill)
}
var buf strings.Builder
buf.WriteString(s.dir)
buf.WriteString(s.basename)
buf.WriteString(zframe)
buf.WriteString(s.ext)
return buf.String()
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/boltdb/boltdb.go#L172-L181
|
func (bdc *cache) UncompressedDigest(anyDigest digest.Digest) digest.Digest {
var res digest.Digest
if err := bdc.view(func(tx *bolt.Tx) error {
res = bdc.uncompressedDigest(tx, anyDigest)
return nil
}); err != nil { // Including os.IsNotExist(err)
return "" // FIXME? Log err (but throttle the log volume on repeated accesses)?
}
return res
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/query/config.go#L16-L47
|
func SelectConfig(tx *sql.Tx, table string, where string, args ...interface{}) (map[string]string, error) {
query := fmt.Sprintf("SELECT key, value FROM %s", table)
if where != "" {
query += fmt.Sprintf(" WHERE %s", where)
}
rows, err := tx.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
values := map[string]string{}
for rows.Next() {
var key string
var value string
err := rows.Scan(&key, &value)
if err != nil {
return nil, err
}
values[key] = value
}
err = rows.Err()
if err != nil {
return nil, err
}
return values, nil
}
|
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/errors.go#L63-L68
|
func (e *BusinessError) New(errno int, message string) *BusinessError {
e.HTTPCode = http.StatusBadRequest
e.Errno = errno
e.Message = message
return e
}
|
https://github.com/janos/web/blob/0fb0203103deb84424510a8d5166ac00700f2b0e/maintenance/maintenance.go#L296-L309
|
func (s Service) OnHandler(w http.ResponseWriter, r *http.Request) {
changed, err := s.store.On()
if err != nil {
s.logger.Errorf("maintenance on: %s", err)
jsonInternalServerErrorResponse(w)
return
}
if changed {
s.logger.Infof("maintenance on")
jsonCreatedResponse(w)
return
}
jsonOKResponse(w)
}
|
https://github.com/marcuswestin/go-errs/blob/b09b17aacd5a8213690bc30f9ccfe7400be7b380/errs.go#L154-L159
|
func (e *err) Info(key string) interface{} {
if e.info == nil {
return nil
}
return e.info[key]
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/easyjson.go#L3836-L3840
|
func (v EventConsoleAPICalled) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoRuntime35(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/approve/approvers/owners.go#L334-L336
|
func (ap *Approvers) RemoveApprover(login string) {
delete(ap.approvers, strings.ToLower(login))
}
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L494-L499
|
func FileSequence_SetDirname(id FileSeqId, dir *C.char) {
if fs, ok := sFileSeqs.Get(id); ok {
str := C.GoString(dir)
fs.SetDirname(str)
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/golint/golint.go#L91-L117
|
func modifiedGoFiles(ghc githubClient, org, repo string, number int, sha string) (map[string]string, error) {
changes, err := ghc.GetPullRequestChanges(org, repo, number)
if err != nil {
return nil, err
}
gfg, err := genfiles.NewGroup(ghc, org, repo, sha)
if err != nil {
return nil, err
}
modifiedFiles := make(map[string]string)
for _, change := range changes {
switch {
case strings.HasPrefix(change.Filename, "vendor/"):
continue
case filepath.Ext(change.Filename) != ".go":
continue
case gfg.Match(change.Filename):
continue
case change.Status == github.PullRequestFileRemoved || change.Status == github.PullRequestFileRenamed:
continue
}
modifiedFiles[change.Filename] = change.Patch
}
return modifiedFiles, nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/buffalo/cmd/fix/npm.go#L19-L87
|
func PackageJSONCheck(r *Runner) error {
fmt.Println("~~~ Checking package.json ~~~")
if !r.App.WithWebpack {
return nil
}
box := webpack.Templates
f, err := box.FindString("package.json.tmpl")
if err != nil {
return err
}
tmpl, err := template.New("package.json").Parse(f)
if err != nil {
return err
}
bb := &bytes.Buffer{}
err = tmpl.Execute(bb, map[string]interface{}{
"opts": &webpack.Options{
App: r.App,
},
})
if err != nil {
return err
}
b, err := ioutil.ReadFile("package.json")
if err != nil {
return err
}
if string(b) == bb.String() {
return nil
}
if !ask("Your package.json file is different from the latest Buffalo template.\nWould you like to REPLACE yours with the latest template?") {
fmt.Println("\tskipping package.json")
return nil
}
pf, err := os.Create("package.json")
if err != nil {
return err
}
_, err = pf.Write(bb.Bytes())
if err != nil {
return err
}
err = pf.Close()
if err != nil {
return err
}
os.RemoveAll(filepath.Join(r.App.Root, "node_modules"))
var cmd *exec.Cmd
if r.App.WithYarn {
cmd = exec.Command("yarnpkg", "install")
} else {
cmd = exec.Command("npm", "install")
}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L5660-L5664
|
func (v *EventChildNodeRemoved) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom63(&r, v)
return r.Error()
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/robots/issue-creator/sources/flakyjob-reporter.go#L256-L282
|
func ReadHTTP(url string) ([]byte, error) {
var err error
retryDelay := time.Duration(2) * time.Second
for retryCount := 0; retryCount < 5; retryCount++ {
if retryCount > 0 {
time.Sleep(retryDelay)
retryDelay *= time.Duration(2)
}
resp, err := http.Get(url)
if resp != nil && resp.StatusCode >= 500 {
// Retry on this type of error.
continue
}
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
continue
}
return body, nil
}
return nil, fmt.Errorf("ran out of retries reading from '%s'. Last error was %v", url, err)
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/profitbricks.go#L37-L39
|
func (c *Client) SetDepth(depth int) {
c.client.depth = strconv.Itoa(depth)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/types/set.go#L101-L108
|
func (us *unsafeSet) Copy() Set {
cp := NewUnsafeSet()
for val := range us.d {
cp.Add(val)
}
return cp
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/provision/kubernetes/pkg/apis/tsuru/v1/zz_generated.deepcopy.go#L35-L40
|
func (in *App) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
|
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/log/namespaced/namespaced.go#L71-L77
|
func (n *Namespaced) WithFields(fields log.Fields) log.Interface {
return &Namespaced{
Interface: n.Interface.WithFields(fields),
namespaces: n.namespaces,
namespace: n.namespace,
}
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L128-L134
|
func (x *Index) Put(c context.Context, id string, src interface{}) (string, error) {
ids, err := x.PutMulti(c, []string{id}, []interface{}{src})
if err != nil {
return "", err
}
return ids[0], nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/tide.go#L517-L532
|
func (cp *TideContextPolicy) IsOptional(c string) bool {
if sets.NewString(cp.OptionalContexts...).Has(c) {
return true
}
if sets.NewString(cp.RequiredContexts...).Has(c) {
return false
}
// assume if we're asking that the context is present on the PR
if sets.NewString(cp.RequiredIfPresentContexts...).Has(c) {
return false
}
if cp.SkipUnknownContexts != nil && *cp.SkipUnknownContexts {
return true
}
return false
}
|
https://github.com/stvp/pager/blob/17442a04891b757880b72d926848df3e3af06c15/pager.go#L56-L58
|
func TriggerIncidentKeyWithDetails(description string, key string, details map[string]interface{}) (incidentKey string, err error) {
return trigger(description, key, details)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/serviceworker/easyjson.go#L681-L685
|
func (v SetForceUpdateOnPageLoadParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoServiceworker7(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/config.go#L102-L146
|
func (c *Config) Validate() error {
if c.Group.Heartbeat.Interval%time.Millisecond != 0 {
sarama.Logger.Println("Group.Heartbeat.Interval only supports millisecond precision; nanoseconds will be truncated.")
}
if c.Group.Session.Timeout%time.Millisecond != 0 {
sarama.Logger.Println("Group.Session.Timeout only supports millisecond precision; nanoseconds will be truncated.")
}
if c.Group.PartitionStrategy != StrategyRange && c.Group.PartitionStrategy != StrategyRoundRobin {
sarama.Logger.Println("Group.PartitionStrategy is not supported; range will be assumed.")
}
if !c.Version.IsAtLeast(minVersion) {
sarama.Logger.Println("Version is not supported; 0.9. will be assumed.")
c.Version = minVersion
}
if err := c.Config.Validate(); err != nil {
return err
}
// validate the Group values
switch {
case c.Group.Offsets.Retry.Max < 0:
return sarama.ConfigurationError("Group.Offsets.Retry.Max must be >= 0")
case c.Group.Offsets.Synchronization.DwellTime <= 0:
return sarama.ConfigurationError("Group.Offsets.Synchronization.DwellTime must be > 0")
case c.Group.Offsets.Synchronization.DwellTime > 10*time.Minute:
return sarama.ConfigurationError("Group.Offsets.Synchronization.DwellTime must be <= 10m")
case c.Group.Heartbeat.Interval <= 0:
return sarama.ConfigurationError("Group.Heartbeat.Interval must be > 0")
case c.Group.Session.Timeout <= 0:
return sarama.ConfigurationError("Group.Session.Timeout must be > 0")
case !c.Metadata.Full && c.Group.Topics.Whitelist != nil:
return sarama.ConfigurationError("Metadata.Full must be enabled when Group.Topics.Whitelist is used")
case !c.Metadata.Full && c.Group.Topics.Blacklist != nil:
return sarama.ConfigurationError("Metadata.Full must be enabled when Group.Topics.Blacklist is used")
}
// ensure offset is correct
switch c.Consumer.Offsets.Initial {
case sarama.OffsetOldest, sarama.OffsetNewest:
default:
return sarama.ConfigurationError("Consumer.Offsets.Initial must be either OffsetOldest or OffsetNewest")
}
return nil
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/reqres.go#L139-L158
|
func (w *reqResWriter) flushFragment(fragment *writableFragment) error {
if w.err != nil {
return w.err
}
frame := fragment.frame.(*Frame)
frame.Header.SetPayloadSize(uint16(fragment.contents.BytesWritten()))
if err := w.mex.checkError(); err != nil {
return w.failed(err)
}
select {
case <-w.mex.ctx.Done():
return w.failed(GetContextError(w.mex.ctx.Err()))
case <-w.mex.errCh.c:
return w.failed(w.mex.errCh.err)
case w.conn.sendCh <- frame:
return nil
}
}
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/metadata.go#L18-L40
|
func NewMetadataWriter() (*MetadataWriter, error) {
funcMap := template.FuncMap{
"comment": comment,
"join": strings.Join,
"commandLine": commandLine,
"toStringArray": toStringArray,
"flagType": flagType,
"location": location,
"escapeBackticks": escapeBackticks,
}
headerT, err := template.New("header-metadata").Funcs(funcMap).Parse(headerMetadataTmpl)
if err != nil {
return nil, err
}
resourceT, err := template.New("resource-metadata").Funcs(funcMap).Parse(resourceMetadataTmpl)
if err != nil {
return nil, err
}
return &MetadataWriter{
headerTmpl: headerT,
resourceTmpl: resourceT,
}, nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/mail/internal/mail/message.go#L34-L50
|
func NewMessage(settings ...MessageSetting) *Message {
m := &Message{
header: make(header),
charset: "UTF-8",
encoding: QuotedPrintable,
}
m.applySettings(settings)
if m.encoding == Base64 {
m.hEncoder = bEncoding
} else {
m.hEncoder = qEncoding
}
return m
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/hashtree/db.go#L1157-L1160
|
func PathToTree(path string, numTrees int64) uint64 {
path = clean(path)
return pathToTree(b(path), numTrees)
}
|
https://github.com/profitbricks/profitbricks-sdk-go/blob/1d2db5f00bf5dd0b6c29273541c71c60cdf4d4d4/server.go#L75-L80
|
func (c *Client) GetServer(dcid, srvid string) (*Server, error) {
url := serverPath(dcid, srvid) + `?depth=` + c.client.depth + `&pretty=` + strconv.FormatBool(c.client.pretty)
ret := &Server{}
err := c.client.Get(url, ret, http.StatusOK)
return ret, err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/logger/log.go#L90-L94
|
func Errorf(format string, args ...interface{}) {
if Log != nil {
Log.Error(fmt.Sprintf(format, args...))
}
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/debugger/debugger.go#L446-L448
|
func (p *ResumeParams) Do(ctx context.Context) (err error) {
return cdp.Execute(ctx, CommandResume, nil, nil)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/indexeddb/easyjson.go#L78-L82
|
func (v RequestDatabaseReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoIndexeddb(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/config/jobs.go#L360-L362
|
func (ps Presubmit) TriggerMatches(body string) bool {
return ps.Trigger != "" && ps.re.MatchString(body)
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/webaudio/easyjson.go#L598-L602
|
func (v *ContextRealtimeData) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoWebaudio7(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/agent/server.go#L129-L169
|
func (srv *Server) Transport(stream rpcpb.Transport_TransportServer) (err error) {
errc := make(chan error)
go func() {
for {
var req *rpcpb.Request
req, err = stream.Recv()
if err != nil {
errc <- err
// TODO: handle error and retry
return
}
if req.Member != nil {
srv.Member = req.Member
}
if req.Tester != nil {
srv.Tester = req.Tester
}
var resp *rpcpb.Response
resp, err = srv.handleTesterRequest(req)
if err != nil {
errc <- err
// TODO: handle error and retry
return
}
if err = stream.Send(resp); err != nil {
errc <- err
// TODO: handle error and retry
return
}
}
}()
select {
case err = <-errc:
case <-stream.Context().Done():
err = stream.Context().Err()
}
return err
}
|
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/rule/rule.go#L732-L734
|
func (r *Rule) SetPrivateAttr(key string, value interface{}) {
r.private[key] = value
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L4990-L4994
|
func (v *EventScreencastVisibilityChanged) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoPage51(&r, v)
return r.Error()
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L2236-L2240
|
func (v PrintToPDFParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage23(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/log/log.go#L145-L152
|
func (t *Target) GetStdLogger() *log.Logger {
t.mut.RLock()
defer t.mut.RUnlock()
if t.logger != nil {
return t.logger.GetStdLogger()
}
return nil
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/applicationcache/easyjson.go#L235-L239
|
func (v GetManifestForFrameParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoApplicationcache2(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcnotify/tcnotify.go#L113-L117
|
func (notify *Notify) Email(payload *SendEmailRequest) error {
cd := tcclient.Client(*notify)
_, _, err := (&cd).APICall(payload, "POST", "/email", nil, nil)
return err
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/cluster/gateway.go#L113-L244
|
func (g *Gateway) HandlerFuncs() map[string]http.HandlerFunc {
database := func(w http.ResponseWriter, r *http.Request) {
if !tlsCheckCert(r, g.cert) {
http.Error(w, "403 invalid client certificate", http.StatusForbidden)
return
}
// Handle heatbeats.
if r.Method == "PUT" {
var nodes []db.RaftNode
err := shared.ReadToJSON(r.Body, &nodes)
if err != nil {
http.Error(w, "400 invalid raft nodes payload", http.StatusBadRequest)
return
}
logger.Debugf("Replace current raft nodes with %+v", nodes)
err = g.db.Transaction(func(tx *db.NodeTx) error {
return tx.RaftNodesReplace(nodes)
})
if err != nil {
http.Error(w, "500 failed to update raft nodes", http.StatusInternalServerError)
return
}
return
}
// From here on we require that this node is part of the raft cluster.
if g.server == nil || g.memoryDial != nil {
http.NotFound(w, r)
return
}
// Handle database upgrade notifications.
if r.Method == "PATCH" {
select {
case g.upgradeCh <- struct{}{}:
default:
}
return
}
// Before actually establishing the gRPC SQL connection, our
// dialer probes the node to see if it's currently the leader
// (otherwise it tries with another node or retry later).
if r.Method == "HEAD" {
if g.raft.Raft().State() != raft.Leader {
http.Error(w, "503 not leader", http.StatusServiceUnavailable)
return
}
return
}
// Handle leader address requests.
if r.Method == "GET" {
leader, err := g.LeaderAddress()
if err != nil {
http.Error(w, "500 no elected leader", http.StatusInternalServerError)
return
}
util.WriteJSON(w, map[string]string{"leader": leader}, false)
return
}
if r.Header.Get("Upgrade") != "dqlite" {
http.Error(w, "Missing or invalid upgrade header", http.StatusBadRequest)
return
}
hijacker, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Webserver doesn't support hijacking", http.StatusInternalServerError)
return
}
conn, _, err := hijacker.Hijack()
if err != nil {
message := errors.Wrap(err, "Failed to hijack connection").Error()
http.Error(w, message, http.StatusInternalServerError)
return
}
// Write the status line and upgrade header by hand since w.WriteHeader()
// would fail after Hijack()
data := []byte("HTTP/1.1 101 Switching Protocols\r\nUpgrade: dqlite\r\n\r\n")
if n, err := conn.Write(data); err != nil || n != len(data) {
conn.Close()
return
}
g.acceptCh <- conn
}
raft := func(w http.ResponseWriter, r *http.Request) {
// If we are not part of the raft cluster, reply with a
// redirect to one of the raft nodes that we know about.
if g.raft == nil {
var address string
err := g.db.Transaction(func(tx *db.NodeTx) error {
nodes, err := tx.RaftNodes()
if err != nil {
return err
}
address = nodes[0].Address
return nil
})
if err != nil {
http.Error(w, "500 failed to fetch raft nodes", http.StatusInternalServerError)
return
}
url := &url.URL{
Scheme: "http",
Path: r.URL.Path,
RawQuery: r.URL.RawQuery,
Host: address,
}
http.Redirect(w, r, url.String(), http.StatusPermanentRedirect)
return
}
// If this node is not clustered return a 404.
if g.raft.HandlerFunc() == nil {
http.NotFound(w, r)
return
}
g.raft.HandlerFunc()(w, r)
}
return map[string]http.HandlerFunc{
databaseEndpoint: database,
raftEndpoint: raft,
}
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/build/controller.go#L271-L281
|
func (c *controller) enqueueKey(ctx string, obj interface{}) {
switch o := obj.(type) {
case *prowjobv1.ProwJob:
c.workqueue.AddRateLimited(toKey(ctx, o.Spec.Namespace, o.Name))
case *buildv1alpha1.Build:
c.workqueue.AddRateLimited(toKey(ctx, o.Namespace, o.Name))
default:
logrus.Warnf("cannot enqueue unknown type %T: %v", o, obj)
return
}
}
|
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/api_classic.go#L33-L39
|
func ClassicContextFromContext(ctx netcontext.Context) (appengine.Context, error) {
c := fromContext(ctx)
if c == nil {
return nil, errNotAppEngineContext
}
return c, nil
}
|
https://github.com/tehnerd/gnl2go/blob/101b5c6e2d44eb00fbfe85917ffc0bf95249977b/gnl2go.go#L387-L390
|
func CreateAttrListDefinition(listName string, atl []AttrTuple) []AttrTuple {
ATLName2ATL[listName] = atl
return atl
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/input.go#L418-L421
|
func (p SynthesizePinchGestureParams) WithGestureSourceType(gestureSourceType GestureType) *SynthesizePinchGestureParams {
p.GestureSourceType = gestureSourceType
return &p
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/heapprofiler/easyjson.go#L1319-L1323
|
func (v EventResetProfiles) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoHeapprofiler15(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/urandom/handler/blob/61508044a5569d1609521d81e81f6737567fd104/encoding/gzip.go#L33-L73
|
func Gzip(h http.Handler, opts ...Option) http.Handler {
o := options{logger: handler.OutLogger()}
o.apply(opts)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
h.ServeHTTP(w, r)
return
}
wrapper := handler.NewResponseWrapper(w)
h.ServeHTTP(wrapper, r)
for k, v := range wrapper.Header() {
w.Header()[k] = v
}
w.Header().Set("Vary", "Accept-Encoding")
w.Header().Set("Content-Encoding", "gzip")
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", http.DetectContentType(wrapper.Body.Bytes()))
}
w.Header().Del("Content-Length")
if wrapper.Code != http.StatusOK {
w.WriteHeader(wrapper.Code)
}
gz := gzip.NewWriter(w)
gz.Flush()
if _, err := gz.Write(wrapper.Body.Bytes()); err != nil {
o.logger.Print("gzip handler: " + err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
gz.Close()
})
}
|
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/multi.go#L58-L65
|
func (b *multiLogger) IsEnabledFor(level Level, module string) bool {
for _, backend := range b.backends {
if backend.IsEnabledFor(level, module) {
return true
}
}
return false
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/easyjson.go#L307-L311
|
func (v SetDOMBreakpointParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDomdebugger3(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/node/config.go#L69-L76
|
func (c *Config) Patch(patch map[string]interface{}) (map[string]string, error) {
values := c.Dump() // Use current values as defaults
for name, value := range patch {
values[name] = value
}
return c.update(values)
}
|
https://github.com/google/acme/blob/7c6dfc908d68ed254a16c126f6770f4d9d9352da/config.go#L127-L142
|
func writeKey(path string, k *ecdsa.PrivateKey) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
bytes, err := x509.MarshalECPrivateKey(k)
if err != nil {
return err
}
b := &pem.Block{Type: ecPrivateKey, Bytes: bytes}
if err := pem.Encode(f, b); err != nil {
f.Close()
return err
}
return f.Close()
}
|
https://github.com/qor/render/blob/63566e46f01b134ae9882a59a06518e82a903231/render.go#L108-L114
|
func (render *Render) SetAssetFS(assetFS assetfs.Interface) {
for _, viewPath := range render.ViewPaths {
assetFS.RegisterPath(viewPath)
}
render.AssetFileSystem = assetFS
}
|
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/inbound.go#L132-L138
|
func (c *Connection) handleCallReqContinue(frame *Frame) bool {
if err := c.inbound.forwardPeerFrame(frame); err != nil {
// If forward fails, it's due to a timeout. We can free this frame.
return true
}
return false
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/input/easyjson.go#L724-L728
|
func (v InsertTextParams) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoInput5(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/domdebugger/domdebugger.go#L122-L125
|
func (p RemoveEventListenerBreakpointParams) WithTargetName(targetName string) *RemoveEventListenerBreakpointParams {
p.TargetName = targetName
return &p
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/obj/obj.go#L581-L585
|
func (b *BackoffReadCloser) Close() error {
span, _ := tracing.AddSpanToAnyExisting(b.ctx, "obj/BackoffReadCloser.Close")
defer tracing.FinishAnySpan(span)
return b.reader.Close()
}
|
https://github.com/tendermint/go-amino/blob/dc14acf9ef15f85828bfbc561ed9dd9d2a284885/amino.go#L403-L409
|
func (cdc *Codec) MustMarshalJSON(o interface{}) []byte {
bz, err := cdc.MarshalJSON(o)
if err != nil {
panic(err)
}
return bz
}
|
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/iterator.go#L456-L461
|
func (it *Iterator) Valid() bool {
if it.item == nil {
return false
}
return bytes.HasPrefix(it.item.key, it.opt.Prefix)
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L58-L66
|
func Merge(imgBlue, imgGreen, imgRed, imgAlpha, dst *IplImage) {
C.cvMerge(
unsafe.Pointer(imgBlue),
unsafe.Pointer(imgGreen),
unsafe.Pointer(imgRed),
unsafe.Pointer(imgAlpha),
unsafe.Pointer(dst),
)
}
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_properties.go#L90-L92
|
func (s *Selection) Selected() (bool, error) {
return s.hasState(element.Element.IsSelected, "selected")
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L293-L295
|
func (rn *RawNode) ReadIndex(rctx []byte) {
_ = rn.raft.Step(pb.Message{Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: rctx}}})
}
|
https://github.com/pivotal-pez/pezdispenser/blob/768e2777520868857916b66cfd4cfb7149383ca5/innkeeperclient/fake/ik_client.go#L43-L51
|
func (s *IKClient) GetStatus(requestID string) (resp *innkeeperclient.GetStatusResponse, err error) {
resp = new(innkeeperclient.GetStatusResponse)
atomic.AddInt64(s.SpyStatusCallCount, 1)
if atomic.LoadInt64(s.SpyStatusCallCount) > s.StatusCallCountForComplete {
resp.Status = taskmanager.AgentTaskStatusComplete
resp.Data.Status = taskmanager.AgentTaskStatusComplete
}
return
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L887-L891
|
func (v *SetAttributesAsTextParams) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom8(&r, v)
return r.Error()
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v2store/store.go#L334-L393
|
func (s *store) Delete(nodePath string, dir, recursive bool) (*Event, error) {
var err *v2error.Error
s.worldLock.Lock()
defer s.worldLock.Unlock()
defer func() {
if err == nil {
s.Stats.Inc(DeleteSuccess)
reportWriteSuccess(Delete)
return
}
s.Stats.Inc(DeleteFail)
reportWriteFailure(Delete)
}()
nodePath = path.Clean(path.Join("/", nodePath))
// we do not allow the user to change "/"
if s.readonlySet.Contains(nodePath) {
return nil, v2error.NewError(v2error.EcodeRootROnly, "/", s.CurrentIndex)
}
// recursive implies dir
if recursive {
dir = true
}
n, err := s.internalGet(nodePath)
if err != nil { // if the node does not exist, return error
return nil, err
}
nextIndex := s.CurrentIndex + 1
e := newEvent(Delete, nodePath, nextIndex, n.CreatedIndex)
e.EtcdIndex = nextIndex
e.PrevNode = n.Repr(false, false, s.clock)
eNode := e.Node
if n.IsDir() {
eNode.Dir = true
}
callback := func(path string) { // notify function
// notify the watchers with deleted set true
s.WatcherHub.notifyWatchers(e, path, true)
}
err = n.Remove(dir, recursive, callback)
if err != nil {
return nil, err
}
// update etcd index
s.CurrentIndex++
s.WatcherHub.notify(e)
return e, nil
}
|
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/base.go#L423-L425
|
func (b *Base) Infom(m *Attrs, msg string, a ...interface{}) error {
return b.Log(LevelInfo, m, msg, a...)
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L699-L707
|
func (r *ProtocolLXD) DeleteImageAlias(name string) error {
// Send the request
_, _, err := r.query("DELETE", fmt.Sprintf("/images/aliases/%s", url.QueryEscape(name)), nil, "")
if err != nil {
return err
}
return nil
}
|
https://github.com/malice-plugins/go-plugin-utils/blob/9ee76663c3b0a531b8c529f03f12a5a84ff9b61b/clitable/table.go#L113-L143
|
func (t *Table) Print() {
if len(t.Rows) == 0 && t.Footer == nil {
return
}
t.calculateSizes(t.Footer)
if !t.Markdown {
t.printDash()
}
if !t.HideHead {
fmt.Println(t.getHead())
t.printTableDash()
}
for _, r := range t.Rows {
fmt.Println(t.rowString(r))
if !t.Markdown {
t.printDash()
}
}
if t.Footer != nil {
t.printTableDash()
fmt.Println(t.rowString(t.Footer))
if !t.Markdown {
t.printTableDash()
}
}
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/client/pps.go#L545-L554
|
func (c APIClient) ListPipeline() ([]*pps.PipelineInfo, error) {
pipelineInfos, err := c.PpsAPIClient.ListPipeline(
c.Ctx(),
&pps.ListPipelineRequest{},
)
if err != nil {
return nil, grpcutil.ScrubGRPC(err)
}
return pipelineInfos.PipelineInfo, nil
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/idmap/idmapset_linux.go#L637-L682
|
func getFromShadow(fname string, username string) ([][]int64, error) {
entries := [][]int64{}
f, err := os.Open(fname)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
// Skip comments
s := strings.Split(scanner.Text(), "#")
if len(s[0]) == 0 {
continue
}
// Validate format
s = strings.Split(s[0], ":")
if len(s) < 3 {
return nil, fmt.Errorf("Unexpected values in %q: %q", fname, s)
}
if strings.EqualFold(s[0], username) {
// Get range start
entryStart, err := strconv.ParseUint(s[1], 10, 32)
if err != nil {
continue
}
// Get range size
entrySize, err := strconv.ParseUint(s[2], 10, 32)
if err != nil {
continue
}
entries = append(entries, []int64{int64(entryStart), int64(entrySize)})
}
}
if len(entries) == 0 {
return nil, fmt.Errorf("User %q has no %ss", username, path.Base(fname))
}
return entries, nil
}
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/types/repository.go#L10-L15
|
func (u *UserRepository) ByUsername(username string) (*User, error) {
if user, ok := u.Users[username]; ok {
return user, nil
}
return nil, ErrNotFound
}
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/cmpopts/ignore.go#L32-L35
|
func IgnoreTypes(typs ...interface{}) cmp.Option {
tf := newTypeFilter(typs...)
return cmp.FilterPath(tf.filter, cmp.Ignore())
}
|
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/api.go#L580-L590
|
func (r *Raft) BootstrapCluster(configuration Configuration) Future {
bootstrapReq := &bootstrapFuture{}
bootstrapReq.init()
bootstrapReq.configuration = configuration
select {
case <-r.shutdownCh:
return errorFuture{ErrRaftShutdown}
case r.bootstrapCh <- bootstrapReq:
return bootstrapReq
}
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/log15/stack/stack.go#L185-L190
|
func (pcs Trace) TrimBelowName(name string) Trace {
for len(pcs) > 0 && pcs[0].name() != name {
pcs = pcs[1:]
}
return pcs
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/gocv/gocv_calib3d.go#L13-L39
|
func GcvInitCameraMatrix2D(objPts, imgPts *mat64.Dense, dims [2]int,
aspectRatio float64) (camMat *mat64.Dense) {
objDim, nObjPts := objPts.Dims()
imgDim, nImgPts := imgPts.Dims()
if objDim != 3 || imgDim != 2 || nObjPts != nImgPts {
panic("Invalid dimensions for objPts and imgPts")
}
objPtsVec := NewGcvPoint3f32Vector(int64(nObjPts))
imgPtsVec := NewGcvPoint2f32Vector(int64(nObjPts))
for j := 0; j < nObjPts; j++ {
objPtsVec.Set(j, NewGcvPoint3f32(mat64.Col(nil, j, objPts)...))
}
for j := 0; j < nObjPts; j++ {
imgPtsVec.Set(j, NewGcvPoint2f32(mat64.Col(nil, j, imgPts)...))
}
_imgSize := NewGcvSize2i(dims[0], dims[1])
camMat = GcvMatToMat64(GcvInitCameraMatrix2D_(
objPtsVec, imgPtsVec, _imgSize, aspectRatio))
return camMat
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/memory/easyjson.go#L592-L596
|
func (v *SamplingProfile) UnmarshalJSON(data []byte) error {
r := jlexer.Lexer{Data: data}
easyjsonC5a4559bDecodeGithubComChromedpCdprotoMemory5(&r, v)
return r.Error()
}
|
https://github.com/Diggs/go-backoff/blob/f7b9f7e6b83be485b2e1b3eebba36652c6c4cd8a/backoff.go#L44-L49
|
func (b *Backoff) Backoff() {
time.Sleep(b.NextDuration)
b.count++
b.LastDuration = b.NextDuration
b.NextDuration = b.getNextDuration()
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L416-L430
|
func EncodeImage(ext string, image unsafe.Pointer, params []int) *Mat {
var firstParam *C.int
if len(params) > 0 {
var params_c []C.int
for _, param := range params {
params_c = append(params_c, C.int(param))
}
firstParam = ¶ms_c[0]
}
ext_c := C.CString(ext)
defer C.free(unsafe.Pointer(ext_c))
rv := C.cvEncodeImage(ext_c, (image), firstParam)
return (*Mat)(rv)
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/raft/rawnode.go#L72-L116
|
func NewRawNode(config *Config, peers []Peer) (*RawNode, error) {
if config.ID == 0 {
panic("config.ID must not be zero")
}
r := newRaft(config)
rn := &RawNode{
raft: r,
}
lastIndex, err := config.Storage.LastIndex()
if err != nil {
panic(err) // TODO(bdarnell)
}
// If the log is empty, this is a new RawNode (like StartNode); otherwise it's
// restoring an existing RawNode (like RestartNode).
// TODO(bdarnell): rethink RawNode initialization and whether the application needs
// to be able to tell us when it expects the RawNode to exist.
if lastIndex == 0 {
r.becomeFollower(1, None)
ents := make([]pb.Entry, len(peers))
for i, peer := range peers {
cc := pb.ConfChange{Type: pb.ConfChangeAddNode, NodeID: peer.ID, Context: peer.Context}
data, err := cc.Marshal()
if err != nil {
panic("unexpected marshal error")
}
ents[i] = pb.Entry{Type: pb.EntryConfChange, Term: 1, Index: uint64(i + 1), Data: data}
}
r.raftLog.append(ents...)
r.raftLog.committed = uint64(len(ents))
for _, peer := range peers {
r.addNode(peer.ID)
}
}
// Set the initial hard and soft states after performing all initialization.
rn.prevSoftSt = r.softState()
if lastIndex == 0 {
rn.prevHardSt = emptyState
} else {
rn.prevHardSt = r.hardState()
}
return rn, nil
}
|
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/pretty/pretty.go#L46-L72
|
func PrintJobInfo(w io.Writer, jobInfo *ppsclient.JobInfo, fullTimestamps bool) {
fmt.Fprintf(w, "%s\t", jobInfo.Job.ID)
fmt.Fprintf(w, "%s\t", jobInfo.Pipeline.Name)
if fullTimestamps {
fmt.Fprintf(w, "%s\t", jobInfo.Started.String())
} else {
fmt.Fprintf(w, "%s\t", pretty.Ago(jobInfo.Started))
}
if jobInfo.Finished != nil {
fmt.Fprintf(w, "%s\t", pretty.TimeDifference(jobInfo.Started, jobInfo.Finished))
} else {
fmt.Fprintf(w, "-\t")
}
fmt.Fprintf(w, "%d\t", jobInfo.Restart)
if jobInfo.DataRecovered != 0 {
fmt.Fprintf(w, "%d + %d + %d / %d\t", jobInfo.DataProcessed, jobInfo.DataSkipped, jobInfo.DataRecovered, jobInfo.DataTotal)
} else {
fmt.Fprintf(w, "%d + %d / %d\t", jobInfo.DataProcessed, jobInfo.DataSkipped, jobInfo.DataTotal)
}
fmt.Fprintf(w, "%s\t", pretty.Size(jobInfo.Stats.DownloadBytes))
fmt.Fprintf(w, "%s\t", pretty.Size(jobInfo.Stats.UploadBytes))
if jobInfo.State == ppsclient.JobState_JOB_FAILURE {
fmt.Fprintf(w, "%s: %s\t\n", jobState(jobInfo.State), safeTrim(jobInfo.Reason, jobReasonLen))
} else {
fmt.Fprintf(w, "%s\t\n", jobState(jobInfo.State))
}
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/platform.go#L240-L285
|
func platformRollback(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
name := r.URL.Query().Get(":name")
image := InputValue(r, "image")
if image == "" {
return &tErrors.HTTP{
Code: http.StatusBadRequest,
Message: "you cannot rollback without an image name",
}
}
canUpdatePlatform := permission.Check(t, permission.PermPlatformUpdate)
if !canUpdatePlatform {
return permission.ErrUnauthorized
}
w.Header().Set("Content-Type", "application/x-json-stream")
keepAliveWriter := io.NewKeepAliveWriter(w, 30*time.Second, "")
defer keepAliveWriter.Stop()
writer := &io.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypePlatform, Value: name},
Kind: permission.PermPlatformUpdate,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermPlatformReadEvents),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
evt.SetLogWriter(writer)
ctx, cancel := evt.CancelableContext(context.Background())
err = servicemanager.Platform.Rollback(appTypes.PlatformOptions{
Name: name,
ImageName: image,
Output: evt,
Ctx: ctx,
})
cancel()
if err == appTypes.ErrPlatformNotFound {
return &tErrors.HTTP{Code: http.StatusNotFound, Message: err.Error()}
}
if err != nil {
return err
}
writer.Write([]byte("Platform successfully updated!\n"))
return nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/github/types.go#L529-L536
|
func (i Issue) IsAssignee(login string) bool {
for _, assignee := range i.Assignees {
if NormLogin(login) == NormLogin(assignee.Login) {
return true
}
}
return false
}
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistriesv2/system_registries_v2.go#L253-L263
|
func getConfigPath(ctx *types.SystemContext) string {
confPath := systemRegistriesConfPath
if ctx != nil {
if ctx.SystemRegistriesConfPath != "" {
confPath = ctx.SystemRegistriesConfPath
} else if ctx.RootForImplicitAbsolutePaths != "" {
confPath = filepath.Join(ctx.RootForImplicitAbsolutePaths, systemRegistriesConfPath)
}
}
return confPath
}
|
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L2326-L2330
|
func (v PushNodeByPathToFrontendReturns) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom25(&w, v)
return w.Buffer.BuildBytes(), w.Error
}
|
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/api/permission.go#L517-L564
|
func addDefaultRole(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
if !permission.Check(t, permission.PermRoleDefaultCreate) {
return permission.ErrUnauthorized
}
rolesMap := map[string][]string{}
for evtName := range permTypes.RoleEventMap {
roles, _ := InputValues(r, evtName)
for _, roleName := range roles {
rolesMap[roleName] = append(rolesMap[roleName], evtName)
}
}
for roleName, evts := range rolesMap {
evt, err := event.New(&event.Opts{
Target: event.Target{Type: event.TargetTypeRole, Value: roleName},
Kind: permission.PermRoleDefaultCreate,
Owner: t,
CustomData: event.FormToCustomData(InputFields(r)),
Allowed: event.Allowed(permission.PermRoleReadEvents),
})
if err != nil {
return err
}
defer func() { evt.Done(err) }()
role, err := permission.FindRole(roleName)
if err != nil {
if err == permTypes.ErrRoleNotFound {
return &errors.HTTP{
Code: http.StatusBadRequest,
Message: err.Error(),
}
}
return err
}
for _, evtName := range evts {
err = role.AddEvent(evtName)
if err != nil {
if _, ok := err.(permTypes.ErrRoleEventWrongContext); ok {
return &errors.HTTP{
Code: http.StatusBadRequest,
Message: err.Error(),
}
}
return err
}
}
}
return nil
}
|
https://github.com/iron-io/functions_go/blob/91b84f5bbb17095bf1c7028ec6e70a3dc06a5893/client/apps/get_apps_app_parameters.go#L88-L91
|
func (o *GetAppsAppParams) WithContext(ctx context.Context) *GetAppsAppParams {
o.SetContext(ctx)
return o
}
|
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/shared/cert.go#L182-L211
|
func mynames() ([]string, error) {
h, err := os.Hostname()
if err != nil {
return nil, err
}
ret := []string{h}
ifs, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, iface := range ifs {
if IsLoopback(&iface) {
continue
}
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
ret = append(ret, addr.String())
}
}
return ret, nil
}
|
https://github.com/gobuffalo/buffalo/blob/7f360181f4ccd79dcc9dcea2c904a4801f194f04/middleware.go#L61-L64
|
func (ms *MiddlewareStack) Clear() {
ms.stack = []MiddlewareFunc{}
ms.skips = map[string]bool{}
}
|
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/compare.go#L100-L105
|
func (cmp *Cmp) ValueBytes() []byte {
if tu, ok := cmp.TargetUnion.(*pb.Compare_Value); ok {
return tu.Value
}
return nil
}
|
https://github.com/geoffgarside/ber/blob/27a1aff36ce64dbe5d93c08cc5f161983134ddc5/ber.go#L330-L335
|
func parseUTF8String(bytes []byte) (ret string, err error) {
if !utf8.Valid(bytes) {
return "", errors.New("asn1: invalid UTF-8 string")
}
return string(bytes), nil
}
|
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/githuboauth/githuboauth.go#L227-L231
|
func (ga *Agent) serverError(w http.ResponseWriter, action string, err error) {
ga.logger.WithError(err).Errorf("Error %s.", action)
msg := fmt.Sprintf("500 Internal server error %s: %v", action, err)
http.Error(w, msg, http.StatusInternalServerError)
}
|
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/cxcore.go#L576-L583
|
func AndScalarWithMask(src *IplImage, value Scalar, dst, mask *IplImage) {
C.cvAndS(
unsafe.Pointer(src),
(C.CvScalar)(value),
unsafe.Pointer(dst),
unsafe.Pointer(mask),
)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.