_id
stringlengths
86
170
text
stringlengths
54
39.3k
https://github.com/r3labs/sse/blob/2f90368216802092e9ed520c43e974e11d50438d/server.go#L82-L87
func (s *Server) StreamExists(id string) bool { s.mu.Lock() defer s.mu.Unlock() return s.Streams[id] != nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L224-L228
func (v WebSocketResponse) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoNetwork(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift_transport.go#L44-L49
func (t openshiftTransport) ValidatePolicyConfigurationScope(scope string) error { if scopeRegexp.FindStringIndex(scope) == nil { return errors.Errorf("Invalid scope name %s", scope) } return nil }
https://github.com/gravitational/roundtrip/blob/e1e0cd6b05a6bb1791b262e63160038828fd7b3a/client.go#L429-L445
func (c *Client) OpenFile(ctx context.Context, endpoint string, params url.Values) (ReadSeekCloser, error) { // If the sanitizer is enabled, make sure the requested path is safe. if c.sanitizerEnabled { err := isPathSafe(endpoint) if err != nil { return nil, err } } u, err := url.Parse(endpoint) if err != nil { return nil, err } u.RawQuery = params.Encode() return newSeeker(c, ctx, u.String()) }
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/main.go#L126-L128
func MustParse(strs ...string) time.Time { return New(time.Now()).MustParse(strs...) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L716-L765
func (c *Cluster) ImageUpdate(id int, fname string, sz int64, public bool, autoUpdate bool, architecture string, createdAt time.Time, expiresAt time.Time, properties map[string]string) error { arch, err := osarch.ArchitectureId(architecture) if err != nil { arch = 0 } err = c.Transaction(func(tx *ClusterTx) error { publicInt := 0 if public { publicInt = 1 } autoUpdateInt := 0 if autoUpdate { autoUpdateInt = 1 } stmt, err := tx.tx.Prepare(`UPDATE images SET filename=?, size=?, public=?, auto_update=?, architecture=?, creation_date=?, expiry_date=? WHERE id=?`) if err != nil { return err } defer stmt.Close() _, err = stmt.Exec(fname, sz, publicInt, autoUpdateInt, arch, createdAt, expiresAt, id) if err != nil { return err } _, err = tx.tx.Exec(`DELETE FROM images_properties WHERE image_id=?`, id) if err != nil { return err } stmt2, err := tx.tx.Prepare(`INSERT INTO images_properties (image_id, type, key, value) VALUES (?, ?, ?, ?)`) if err != nil { return err } defer stmt2.Close() for key, value := range properties { _, err = stmt2.Exec(id, 0, key, value) if err != nil { return err } } return nil }) return err }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/db/storage.go#L159-L164
func (s *LogStorage) AppLogCollection(appName string) *storage.Collection { if appName == "" { return nil } return s.Collection("logs_" + appName) }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_dest.go#L297-L306
func indexExists(ref ociReference) bool { _, err := os.Stat(ref.indexPath()) if err == nil { return true } if os.IsNotExist(err) { return false } return true }
https://github.com/256dpi/fire/blob/fa66e74352b30b9a4c730f7b8dc773302941b0fb/callbacks.go#L450-L516
func MatchingReferencesValidator(reference string, target coal.Model, matcher map[string]string) *Callback { return C("fire/MatchingReferencesValidator", Only(Create, Update), func(ctx *Context) error { // prepare ids var ids []bson.ObjectId // get reference ref := ctx.Model.MustGet(reference) // handle to-one reference if id, ok := ref.(bson.ObjectId); ok { ids = []bson.ObjectId{id} } // handle optional to-one reference if oid, ok := ref.(*bson.ObjectId); ok { // return immediately if not set if oid == nil { return nil } // set id ids = []bson.ObjectId{*oid} } // handle to-many reference if list, ok := ref.([]bson.ObjectId); ok { // return immediately if empty if len(list) == 0 { return nil } // set list ids = list } // ensure list is unique ids = coal.Unique(ids) // prepare query query := bson.M{ "_id": bson.M{ "$in": ids, }, } // add matchers for sourceField, targetField := range matcher { query[coal.F(target, targetField)] = ctx.Model.MustGet(sourceField) } // find matching documents ctx.Tracer.Push("mgo/Query.Count") ctx.Tracer.Tag("query", query) n, err := ctx.Store.DB().C(coal.C(target)).Find(query).Count() if err != nil { return err } ctx.Tracer.Pop() // return error if a document is missing (does not match) if n != len(ids) { return E("references do not match") } return nil }) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/easyjson.go#L4794-L4798
func (v *GetCertificateReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoNetwork36(&r, v) return r.Error() }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/tide/status.go#L223-L237
func expectedStatus(queryMap *config.QueryMap, pr *PullRequest, pool map[string]PullRequest, cc contextChecker) (string, string) { if _, ok := pool[prKey(pr)]; !ok { minDiffCount := -1 var minDiff string for _, q := range queryMap.ForRepo(string(pr.Repository.Owner.Login), string(pr.Repository.Name)) { diff, diffCount := requirementDiff(pr, &q, cc) if minDiffCount == -1 || diffCount < minDiffCount { minDiffCount = diffCount minDiff = diff } } return github.StatusPending, fmt.Sprintf(statusNotInPool, minDiff) } return github.StatusSuccess, statusInPool }
https://github.com/ccding/go-config-reader/blob/8b6c2b50197f20da3b1c5944c274c173634dc056/config/config.go#L106-L112
func (c *Config) Get(section string, key string) string { value, ok := c.config[section][key] if !ok { return "" } return value }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/clonerefs/options.go#L145-L156
func (o *Options) AddFlags(fs *flag.FlagSet) { fs.StringVar(&o.SrcRoot, "src-root", "", "Where to root source checkouts") fs.StringVar(&o.Log, "log", "", "Where to write logs") fs.StringVar(&o.GitUserName, "git-user-name", DefaultGitUserName, "Username to set in git config") fs.StringVar(&o.GitUserEmail, "git-user-email", DefaultGitUserEmail, "Email to set in git config") fs.Var(&o.refs, "repo", "Mapping of Git URI to refs to check out, can be provided more than once") fs.Var(&o.keys, "ssh-key", "Path to SSH key to enable during cloning, can be provided more than once") fs.Var(&o.clonePath, "clone-alias", "Format string for the path to clone to") fs.Var(&o.cloneURI, "uri-prefix", "Format string for the URI prefix to clone from") fs.IntVar(&o.MaxParallelWorkers, "max-workers", 0, "Maximum number of parallel workers, unset for unlimited.") fs.StringVar(&o.CookiePath, "cookiefile", "", "Path to git http.cookiefile") }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdctl/ctlv3/command/user_command.go#L123-L158
func userAddCommandFunc(cmd *cobra.Command, args []string) { if len(args) != 1 { ExitWithError(ExitBadArgs, fmt.Errorf("user add command requires user name as its argument")) } var password string var user string if passwordFromFlag != "" { user = args[0] password = passwordFromFlag } else { splitted := strings.SplitN(args[0], ":", 2) if len(splitted) < 2 { user = args[0] if !passwordInteractive { fmt.Scanf("%s", &password) } else { password = readPasswordInteractive(args[0]) } } else { user = splitted[0] password = splitted[1] if len(user) == 0 { ExitWithError(ExitBadArgs, fmt.Errorf("empty user name is not allowed")) } } } resp, err := mustClientFromCmd(cmd).Auth.UserAdd(context.TODO(), user, password) if err != nil { ExitWithError(ExitError, err) } display.UserAdd(user, *resp) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/dir_unix.go#L83-L97
func (guard *directoryLockGuard) release() error { var err error if !guard.readOnly { // It's important that we remove the pid file first. err = os.Remove(guard.path) } if closeErr := guard.f.Close(); err == nil { err = closeErr } guard.path = "" guard.f = nil return err }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/entrypoint/run.go#L93-L192
func (o Options) ExecuteProcess() (int, error) { if o.ArtifactDir != "" { if err := os.MkdirAll(o.ArtifactDir, os.ModePerm); err != nil { return InternalErrorCode, fmt.Errorf("could not create artifact directory(%s): %v", o.ArtifactDir, err) } } processLogFile, err := os.Create(o.ProcessLog) if err != nil { return InternalErrorCode, fmt.Errorf("could not create process logfile(%s): %v", o.ProcessLog, err) } defer processLogFile.Close() output := io.MultiWriter(os.Stdout, processLogFile) logrus.SetOutput(output) defer logrus.SetOutput(os.Stdout) // if we get asked to terminate we need to forward // that to the wrapped process as if it timed out interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM) if o.PreviousMarker != "" { ctx, cancel := context.WithCancel(context.Background()) go func() { select { case s := <-interrupt: logrus.Errorf("Received interrupt %s, cancelling...", s) cancel() case <-ctx.Done(): } }() code, err := wrapper.WaitForMarker(ctx, o.PreviousMarker) cancel() // end previous go-routine when not interrupted if err != nil { return InternalErrorCode, fmt.Errorf("wait for previous marker %s: %v", o.PreviousMarker, err) } if code != 0 { logrus.Infof("Skipping as previous step exited %d", code) return PreviousErrorCode, nil } } executable := o.Args[0] var arguments []string if len(o.Args) > 1 { arguments = o.Args[1:] } command := exec.Command(executable, arguments...) command.Stderr = output command.Stdout = output if err := command.Start(); err != nil { return InternalErrorCode, fmt.Errorf("could not start the process: %v", err) } timeout := optionOrDefault(o.Timeout, DefaultTimeout) gracePeriod := optionOrDefault(o.GracePeriod, DefaultGracePeriod) var commandErr error cancelled, aborted := false, false done := make(chan error) go func() { done <- command.Wait() }() select { case err := <-done: commandErr = err case <-time.After(timeout): logrus.Errorf("Process did not finish before %s timeout", timeout) cancelled = true gracefullyTerminate(command, done, gracePeriod) case s := <-interrupt: logrus.Errorf("Entrypoint received interrupt: %v", s) cancelled = true aborted = true gracefullyTerminate(command, done, gracePeriod) } var returnCode int if cancelled { if aborted { commandErr = errAborted returnCode = AbortedErrorCode } else { commandErr = errTimedOut returnCode = InternalErrorCode } } else { if status, ok := command.ProcessState.Sys().(syscall.WaitStatus); ok { returnCode = status.ExitStatus() } else if commandErr == nil { returnCode = 0 } else { returnCode = 1 } if returnCode != 0 { commandErr = fmt.Errorf("wrapped process failed: %v", commandErr) } } return returnCode, commandErr }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/util.go#L176-L188
func setQueryParam(uri, param, value string) (string, error) { fields, err := url.Parse(uri) if err != nil { return "", err } values := fields.Query() values.Set(param, url.QueryEscape(value)) fields.RawQuery = values.Encode() return fields.String(), nil }
https://github.com/libp2p/go-libp2p-pubsub/blob/9db3dbdde90f44d1c420192c5cefd60682fbdbb9/pubsub.go#L226-L239
func WithMessageSigning(enabled bool) Option { return func(p *PubSub) error { if enabled { p.signKey = p.host.Peerstore().PrivKey(p.signID) if p.signKey == nil { return fmt.Errorf("can't sign for peer %s: no private key", p.signID) } } else { p.signKey = nil p.signStrict = false } return nil } }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/v3compactor/revision.go#L64-L124
func (rc *Revision) Run() { prev := int64(0) go func() { for { select { case <-rc.ctx.Done(): return case <-rc.clock.After(revInterval): rc.mu.Lock() p := rc.paused rc.mu.Unlock() if p { continue } } rev := rc.rg.Rev() - rc.retention if rev <= 0 || rev == prev { continue } now := time.Now() if rc.lg != nil { rc.lg.Info( "starting auto revision compaction", zap.Int64("revision", rev), zap.Int64("revision-compaction-retention", rc.retention), ) } else { plog.Noticef("Starting auto-compaction at revision %d (retention: %d revisions)", rev, rc.retention) } _, err := rc.c.Compact(rc.ctx, &pb.CompactionRequest{Revision: rev}) if err == nil || err == mvcc.ErrCompacted { prev = rev if rc.lg != nil { rc.lg.Info( "completed auto revision compaction", zap.Int64("revision", rev), zap.Int64("revision-compaction-retention", rc.retention), zap.Duration("took", time.Since(now)), ) } else { plog.Noticef("Finished auto-compaction at revision %d", rev) } } else { if rc.lg != nil { rc.lg.Warn( "failed auto revision compaction", zap.Int64("revision", rev), zap.Int64("revision-compaction-retention", rc.retention), zap.Duration("retry-interval", revInterval), zap.Error(err), ) } else { plog.Noticef("Failed auto-compaction at revision %d (%v)", rev, err) plog.Noticef("Retry after %v", revInterval) } } } }() }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/overlay/easyjson.go#L1957-L1961
func (v *EventInspectModeCanceled) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoOverlay20(&r, v) return r.Error() }
https://github.com/bazelbuild/bazel-gazelle/blob/e3805aaca69a9deb949b47bfc45b9b1870712f4f/language/go/fix.go#L236-L245
func removeLegacyGazelle(c *config.Config, f *rule.File) { for _, l := range f.Loads { if l.Name() == "@io_bazel_rules_go//go:def.bzl" && l.Has("gazelle") { l.Remove("gazelle") if l.IsEmpty() { l.Delete() } } } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L4443-L4447
func (v *GetBoxModelReturns) UnmarshalJSON(data []byte) error { r := jlexer.Lexer{Data: data} easyjsonC5a4559bDecodeGithubComChromedpCdprotoDom50(&r, v) return r.Error() }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/deploy/assets/assets.go#L1190-L1207
func MinioSecret(bucket string, id string, secret string, endpoint string, secure, isS3V2 bool) map[string][]byte { secureV := "0" if secure { secureV = "1" } s3V2 := "0" if isS3V2 { s3V2 = "1" } return map[string][]byte{ "minio-bucket": []byte(bucket), "minio-id": []byte(id), "minio-secret": []byte(secret), "minio-endpoint": []byte(endpoint), "minio-secure": []byte(secureV), "minio-signature": []byte(s3V2), } }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/gerrit/adapter/adapter.go#L122-L147
func (c *Controller) SaveLastSync(lastSync time.Time) error { if c.lastSyncFallback == "" { return nil } lastSyncUnix := strconv.FormatInt(lastSync.Unix(), 10) logrus.Infof("Writing last sync: %s", lastSyncUnix) tempFile, err := ioutil.TempFile(filepath.Dir(c.lastSyncFallback), "temp") if err != nil { return err } defer os.Remove(tempFile.Name()) err = ioutil.WriteFile(tempFile.Name(), []byte(lastSyncUnix), 0644) if err != nil { return err } err = os.Rename(tempFile.Name(), c.lastSyncFallback) if err != nil { logrus.WithError(err).Info("Rename failed, fallback to copyfile") return copyFile(tempFile.Name(), c.lastSyncFallback) } return nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L2249-L2257
func (u Memo) MustText() string { val, ok := u.GetText() if !ok { panic("arm Text is not set") } return val }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/rsssh/main.go#L129-L136
func getInstanceNumber(name string) string { re, _ := regexp.Compile(`#\d+$`) matches := re.FindStringSubmatch(name) if len(matches) == 0 { return "" } return matches[len(matches)-1] }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/page.go#L794-L809
func (p *PrintToPDFParams) Do(ctx context.Context) (data []byte, err error) { // execute var res PrintToPDFReturns err = cdp.Execute(ctx, CommandPrintToPDF, p, &res) if err != nil { return nil, err } // decode var dec []byte dec, err = base64.StdEncoding.DecodeString(res.Data) if err != nil { return nil, err } return dec, nil }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/tackle/main.go#L68-L74
func output(args ...string) (string, error) { cmd := exec.Command(args[0], args[1:]...) cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin b, err := cmd.Output() return strings.TrimSpace(string(b)), err }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/globaltracer.go#L30-L32
func StartSpan(operationName string, opts ...StartSpanOption) Span { return globalTracer.tracer.StartSpan(operationName, opts...) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/client/clientset/versioned/typed/prowjobs/v1/fake/fake_prowjob.go#L93-L101
func (c *FakeProwJobs) Update(prowJob *prowjobsv1.ProwJob) (result *prowjobsv1.ProwJob, err error) { obj, err := c.Fake. Invokes(testing.NewUpdateAction(prowjobsResource, c.ns, prowJob), &prowjobsv1.ProwJob{}) if obj == nil { return nil, err } return obj.(*prowjobsv1.ProwJob), err }
https://github.com/fcavani/text/blob/023e76809b57fc8cfc80c855ba59537720821cb5/validation.go#L193-L206
func CleanUrl(rawurl string, min, max int) (string, error) { err := CheckUrl(rawurl, min, max) if err != nil { return "", e.Forward(err) } u, err := url.Parse(rawurl) if err != nil { return "", e.Push(e.New(ErrInvUrl), err) } if u.Scheme == "" { return u.String(), e.New(ErrNoScheme) } return u.String(), nil }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/systeminfo/systeminfo.go#L73-L82
func (p *GetProcessInfoParams) Do(ctx context.Context) (processInfo []*ProcessInfo, err error) { // execute var res GetProcessInfoReturns err = cdp.Execute(ctx, CommandGetProcessInfo, nil, &res) if err != nil { return nil, err } return res.ProcessInfo, nil }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/lxd_images.go#L61-L63
func (r *ProtocolLXD) GetImageFile(fingerprint string, req ImageFileRequest) (*ImageFileResponse, error) { return r.GetPrivateImageFile(fingerprint, "", req) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L5294-L5303
func (u BucketEntry) GetDeadEntry() (result LedgerKey, ok bool) { armName, _ := u.ArmForSwitch(int32(u.Type)) if armName == "DeadEntry" { result = *u.DeadEntry ok = true } return }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/storage_pools.go#L933-L957
func storagePoolVolumeReplicateIfCeph(tx *sql.Tx, volumeID int64, project, volumeName string, volumeType int, poolID int64, f func(int64) error) error { driver, err := storagePoolDriverGet(tx, poolID) if err != nil { return err } volumeIDs := []int64{volumeID} // If this is a ceph volume, we want to duplicate the change across the // the rows for all other nodes. if driver == "ceph" { volumeIDs, err = storageVolumeIDsGet(tx, project, volumeName, volumeType, poolID) if err != nil { return err } } for _, volumeID := range volumeIDs { err := f(volumeID) if err != nil { return err } } return nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/crossdock/behavior/trace/behavior.go#L66-L119
func (b *Behavior) Run(t crossdock.T) { logParams(t) sampled, err := strconv.ParseBool(t.Param(sampledParam)) if err != nil { t.Fatalf("Malformed param %s: %s", sampledParam, err) } baggage := randomBaggage() level1 := &Request{ ServerRole: RoleS1, } server1 := t.Param(server1NameParam) level2 := &Downstream{ ServiceName: t.Param(server2NameParam), ServerRole: RoleS2, HostPort: fmt.Sprintf("%s:%s", b.serviceToHost(t.Param(server2NameParam)), b.ServerPort, ), Encoding: t.Param(server2EncodingParam), } level1.Downstream = level2 level3 := &Downstream{ ServiceName: t.Param(server3NameParam), ServerRole: RoleS3, HostPort: fmt.Sprintf("%s:%s", b.serviceToHost(t.Param(server3NameParam)), b.ServerPort, ), Encoding: t.Param(server3EncodingParam), } level2.Downstream = level3 resp, err := b.startTrace(t, level1, sampled, baggage) if err != nil { t.Errorf("Failed to startTrace in S1(%s): %s", server1, err.Error()) return } log.Printf("Response: span=%+v, downstream=%+v", resp.Span, resp.Downstream) traceID := resp.Span.TraceID require := crossdock.Require(t) require.NotEmpty(traceID, "Trace ID should not be empty in S1(%s)", server1) if validateTrace(t, level1.Downstream, resp, server1, 1, traceID, sampled, baggage) { t.Successf("trace checks out") log.Println("PASS") } else { log.Println("FAIL") } }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L405-L412
func FileSequence_InvertedFrameRangePadded(id FileSeqId) *C.char { fs, ok := sFileSeqs.Get(id) // caller must free string if !ok { return C.CString("") } return C.CString(fs.InvertedFrameRangePadded()) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/cmd/admission/admission.go#L83-L92
func handle(w http.ResponseWriter, r *http.Request) { req, err := readRequest(r.Body, r.Header.Get("Content-Type")) if err != nil { logrus.WithError(err).Error("read") } if err := writeResponse(*req, w, onlyUpdateStatus); err != nil { logrus.WithError(err).Error("write") } }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/cli/env.go#L45-L55
func BoolEnvDef(env string, def bool) bool { val := os.Getenv(env) if val == "" { return def } b, err := strconv.ParseBool(val) if err != nil { return def } return b }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/etcdserver/api/rafthttp/http.go#L200-L339
func (h *snapshotHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { start := time.Now() if r.Method != "POST" { w.Header().Set("Allow", "POST") http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed) snapshotReceiveFailures.WithLabelValues(unknownSnapshotSender).Inc() return } w.Header().Set("X-Etcd-Cluster-ID", h.cid.String()) if err := checkClusterCompatibilityFromHeader(h.lg, h.localID, r.Header, h.cid); err != nil { http.Error(w, err.Error(), http.StatusPreconditionFailed) snapshotReceiveFailures.WithLabelValues(unknownSnapshotSender).Inc() return } addRemoteFromRequest(h.tr, r) dec := &messageDecoder{r: r.Body} // let snapshots be very large since they can exceed 512MB for large installations m, err := dec.decodeLimit(uint64(1 << 63)) from := types.ID(m.From).String() if err != nil { msg := fmt.Sprintf("failed to decode raft message (%v)", err) if h.lg != nil { h.lg.Warn( "failed to decode Raft message", zap.String("local-member-id", h.localID.String()), zap.String("remote-snapshot-sender-id", from), zap.Error(err), ) } else { plog.Error(msg) } http.Error(w, msg, http.StatusBadRequest) recvFailures.WithLabelValues(r.RemoteAddr).Inc() snapshotReceiveFailures.WithLabelValues(from).Inc() return } msgSize := m.Size() receivedBytes.WithLabelValues(from).Add(float64(msgSize)) if m.Type != raftpb.MsgSnap { if h.lg != nil { h.lg.Warn( "unexpected Raft message type", zap.String("local-member-id", h.localID.String()), zap.String("remote-snapshot-sender-id", from), zap.String("message-type", m.Type.String()), ) } else { plog.Errorf("unexpected raft message type %s on snapshot path", m.Type) } http.Error(w, "wrong raft message type", http.StatusBadRequest) snapshotReceiveFailures.WithLabelValues(from).Inc() return } if h.lg != nil { h.lg.Info( "receiving database snapshot", zap.String("local-member-id", h.localID.String()), zap.String("remote-snapshot-sender-id", from), zap.Uint64("incoming-snapshot-index", m.Snapshot.Metadata.Index), zap.Int("incoming-snapshot-message-size-bytes", msgSize), zap.String("incoming-snapshot-message-size", humanize.Bytes(uint64(msgSize))), ) } else { plog.Infof("receiving database snapshot [index:%d, from %s] ...", m.Snapshot.Metadata.Index, types.ID(m.From)) } // save incoming database snapshot. n, err := h.snapshotter.SaveDBFrom(r.Body, m.Snapshot.Metadata.Index) if err != nil { msg := fmt.Sprintf("failed to save KV snapshot (%v)", err) if h.lg != nil { h.lg.Warn( "failed to save incoming database snapshot", zap.String("local-member-id", h.localID.String()), zap.String("remote-snapshot-sender-id", from), zap.Uint64("incoming-snapshot-index", m.Snapshot.Metadata.Index), zap.Error(err), ) } else { plog.Error(msg) } http.Error(w, msg, http.StatusInternalServerError) snapshotReceiveFailures.WithLabelValues(from).Inc() return } receivedBytes.WithLabelValues(from).Add(float64(n)) if h.lg != nil { h.lg.Info( "received and saved database snapshot", zap.String("local-member-id", h.localID.String()), zap.String("remote-snapshot-sender-id", from), zap.Uint64("incoming-snapshot-index", m.Snapshot.Metadata.Index), zap.Int64("incoming-snapshot-size-bytes", n), zap.String("incoming-snapshot-size", humanize.Bytes(uint64(n))), ) } else { plog.Infof("received and saved database snapshot [index: %d, from: %s] successfully", m.Snapshot.Metadata.Index, types.ID(m.From)) } if err := h.r.Process(context.TODO(), m); err != nil { switch v := err.(type) { // Process may return writerToResponse error when doing some // additional checks before calling raft.Node.Step. case writerToResponse: v.WriteTo(w) default: msg := fmt.Sprintf("failed to process raft message (%v)", err) if h.lg != nil { h.lg.Warn( "failed to process Raft message", zap.String("local-member-id", h.localID.String()), zap.String("remote-snapshot-sender-id", from), zap.Error(err), ) } else { plog.Error(msg) } http.Error(w, msg, http.StatusInternalServerError) snapshotReceiveFailures.WithLabelValues(from).Inc() } return } // Write StatusNoContent header after the message has been processed by // raft, which facilitates the client to report MsgSnap status. w.WriteHeader(http.StatusNoContent) snapshotReceive.WithLabelValues(from).Inc() snapshotReceiveSeconds.WithLabelValues(from).Observe(time.Since(start).Seconds()) }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/json/encode.go#L22-L24
func NewPrettyEncoder(w io.Writer) *objconv.Encoder { return objconv.NewEncoder(NewPrettyEmitter(w)) }
https://github.com/segmentio/objconv/blob/7a1d7b8e6f3551b30751e6b2ea6bae500883870e/value.go#L156-L160
func NewValueParser(v interface{}) *ValueParser { return &ValueParser{ stack: []reflect.Value{reflect.ValueOf(v)}, } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L914-L916
func (p *RemoveBindingParams) Do(ctx context.Context) (err error) { return cdp.Execute(ctx, CommandRemoveBinding, p, nil) }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/images.go#L845-L862
func (c *Cluster) ImageGetPools(imageFingerprint string) ([]int64, error) { poolID := int64(-1) query := "SELECT storage_pool_id FROM storage_volumes WHERE node_id=? AND name=? AND type=?" inargs := []interface{}{c.nodeID, imageFingerprint, StoragePoolVolumeTypeImage} outargs := []interface{}{poolID} result, err := queryScan(c.db, query, inargs, outargs) if err != nil { return []int64{}, err } poolIDs := []int64{} for _, r := range result { poolIDs = append(poolIDs, r[0].(int64)) } return poolIDs, nil }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L3049-L3057
func (u ManageOfferSuccessResultOffer) MustOffer() OfferEntry { val, ok := u.GetOffer() if !ok { panic("arm Offer is not set") } return val }
https://github.com/lestrrat-go/xslate/blob/6a6eb0fce8ab7407a3e0460af60758e5d6f2b9f8/vm/ops.go#L214-L224
func txFetchSymbol(st *State) { // Need to handle local vars? key := st.CurrentOp().Arg() vars := st.Vars() if v, ok := vars.Get(key); ok { st.sa = v } else { st.sa = nil } st.Advance() }
https://github.com/Knetic/govaluate/blob/9aa49832a739dcd78a5542ff189fb82c3e423116/stagePlanner.go#L460-L550
func findTypeChecks(symbol OperatorSymbol) typeChecks { switch symbol { case GT: fallthrough case LT: fallthrough case GTE: fallthrough case LTE: return typeChecks{ combined: comparatorTypeCheck, } case REQ: fallthrough case NREQ: return typeChecks{ left: isString, right: isRegexOrString, } case AND: fallthrough case OR: return typeChecks{ left: isBool, right: isBool, } case IN: return typeChecks{ right: isArray, } case BITWISE_LSHIFT: fallthrough case BITWISE_RSHIFT: fallthrough case BITWISE_OR: fallthrough case BITWISE_AND: fallthrough case BITWISE_XOR: return typeChecks{ left: isFloat64, right: isFloat64, } case PLUS: return typeChecks{ combined: additionTypeCheck, } case MINUS: fallthrough case MULTIPLY: fallthrough case DIVIDE: fallthrough case MODULUS: fallthrough case EXPONENT: return typeChecks{ left: isFloat64, right: isFloat64, } case NEGATE: return typeChecks{ right: isFloat64, } case INVERT: return typeChecks{ right: isBool, } case BITWISE_NOT: return typeChecks{ right: isFloat64, } case TERNARY_TRUE: return typeChecks{ left: isBool, } // unchecked cases case EQ: fallthrough case NEQ: return typeChecks{} case TERNARY_FALSE: fallthrough case COALESCE: fallthrough default: return typeChecks{} } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/page/easyjson.go#L643-L647
func (v SetWebLifecycleStateParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoPage6(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/future.go#L249-L268
func (v *verifyFuture) vote(leader bool) { v.voteLock.Lock() defer v.voteLock.Unlock() // Guard against having notified already if v.notifyCh == nil { return } if leader { v.votes++ if v.votes >= v.quorumSize { v.notifyCh <- v v.notifyCh = nil } } else { v.notifyCh <- v v.notifyCh = nil } }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/cert/logging_conn.go#L193-L201
func (l *TestListener) Close() error { l.connMu.Lock() defer l.connMu.Unlock() c := <-l.connCh if c != nil { close(l.connCh) } return nil }
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L167-L280
func ParseUpload(req *http.Request) (blobs map[string][]*BlobInfo, other url.Values, err error) { _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) if err != nil { return nil, nil, err } boundary := params["boundary"] if boundary == "" { return nil, nil, errorf("did not find MIME multipart boundary") } blobs = make(map[string][]*BlobInfo) other = make(url.Values) mreader := multipart.NewReader(io.MultiReader(req.Body, strings.NewReader("\r\n\r\n")), boundary) for { part, perr := mreader.NextPart() if perr == io.EOF { break } if perr != nil { return nil, nil, errorf("error reading next mime part with boundary %q (len=%d): %v", boundary, len(boundary), perr) } bi := &BlobInfo{} ctype, params, err := mime.ParseMediaType(part.Header.Get("Content-Disposition")) if err != nil { return nil, nil, err } bi.Filename = params["filename"] formKey := params["name"] ctype, params, err = mime.ParseMediaType(part.Header.Get("Content-Type")) if err != nil { return nil, nil, err } bi.BlobKey = appengine.BlobKey(params["blob-key"]) charset := params["charset"] if ctype != "message/external-body" || bi.BlobKey == "" { if formKey != "" { slurp, serr := ioutil.ReadAll(part) if serr != nil { return nil, nil, errorf("error reading %q MIME part", formKey) } // Handle base64 content transfer encoding. multipart.Part transparently // handles quoted-printable, and no special handling is required for // 7bit, 8bit, or binary. ctype, params, err = mime.ParseMediaType(part.Header.Get("Content-Transfer-Encoding")) if err == nil && ctype == "base64" { slurp, serr = ioutil.ReadAll(base64.NewDecoder( base64.StdEncoding, bytes.NewReader(slurp))) if serr != nil { return nil, nil, errorf("error %s decoding %q MIME part", ctype, formKey) } } // Handle charset if charset != "" { encoding, err := htmlindex.Get(charset) if err != nil { return nil, nil, errorf("error getting decoder for charset %q", charset) } slurp, err = encoding.NewDecoder().Bytes(slurp) if err != nil { return nil, nil, errorf("error decoding from charset %q", charset) } } other[formKey] = append(other[formKey], string(slurp)) } continue } // App Engine sends a MIME header as the body of each MIME part. tp := textproto.NewReader(bufio.NewReader(part)) header, mimeerr := tp.ReadMIMEHeader() if mimeerr != nil { return nil, nil, mimeerr } bi.Size, err = strconv.ParseInt(header.Get("Content-Length"), 10, 64) if err != nil { return nil, nil, err } bi.ContentType = header.Get("Content-Type") // Parse the time from the MIME header like: // X-AppEngine-Upload-Creation: 2011-03-15 21:38:34.712136 createDate := header.Get("X-AppEngine-Upload-Creation") if createDate == "" { return nil, nil, errorf("expected to find an X-AppEngine-Upload-Creation header") } bi.CreationTime, err = time.Parse("2006-01-02 15:04:05.000000", createDate) if err != nil { return nil, nil, errorf("error parsing X-AppEngine-Upload-Creation: %s", err) } if hdr := header.Get("Content-MD5"); hdr != "" { md5, err := base64.URLEncoding.DecodeString(hdr) if err != nil { return nil, nil, errorf("bad Content-MD5 %q: %v", hdr, err) } bi.MD5 = string(md5) } // If the GCS object name was provided, record it. bi.ObjectName = header.Get("X-AppEngine-Cloud-Storage-Object") blobs[formKey] = append(blobs[formKey], bi) } return }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/log/field.go#L237-L264
func (lf Field) Value() interface{} { switch lf.fieldType { case stringType: return lf.stringVal case boolType: return lf.numericVal != 0 case intType: return int(lf.numericVal) case int32Type: return int32(lf.numericVal) case int64Type: return int64(lf.numericVal) case uint32Type: return uint32(lf.numericVal) case uint64Type: return uint64(lf.numericVal) case float32Type: return math.Float32frombits(uint32(lf.numericVal)) case float64Type: return math.Float64frombits(uint64(lf.numericVal)) case errorType, objectType, lazyLoggerType: return lf.interfaceVal case noopType: return nil default: return nil } }
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L200-L228
func (d *Document) Expanded(options ...*spec.ExpandOptions) (*Document, error) { swspec := new(spec.Swagger) if err := json.Unmarshal(d.raw, swspec); err != nil { return nil, err } var expandOptions *spec.ExpandOptions if len(options) > 0 { expandOptions = options[0] } else { expandOptions = &spec.ExpandOptions{ RelativeBase: d.specFilePath, } } if err := spec.ExpandSpec(swspec, expandOptions); err != nil { return nil, err } dd := &Document{ Analyzer: analysis.New(swspec), spec: swspec, specFilePath: d.specFilePath, schema: spec.MustLoadSwagger20Schema(), raw: d.raw, origSpec: d.origSpec, } return dd, nil }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L148-L151
func (r *ReadBuffer) ReadLen16String() string { n := r.ReadUint16() return r.ReadString(int(n)) }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/network/network.go#L102-L105
func (p ContinueInterceptedRequestParams) WithURL(url string) *ContinueInterceptedRequestParams { p.URL = url return &p }
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/gof3r/main.go#L89-L101
func getAWSKeys() (keys s3gof3r.Keys, err error) { keys, err = s3gof3r.EnvKeys() if err == nil { return } keys, err = s3gof3r.InstanceKeys() if err == nil { return } err = errors.New("no AWS keys found") return }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/db/profiles.go#L270-L290
func ProfileConfigAdd(tx *sql.Tx, id int64, config map[string]string) error { str := fmt.Sprintf("INSERT INTO profiles_config (profile_id, key, value) VALUES(?, ?, ?)") stmt, err := tx.Prepare(str) defer stmt.Close() if err != nil { return err } for k, v := range config { if v == "" { continue } _, err = stmt.Exec(id, k, v) if err != nil { return err } } return nil }
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/exp/cpp/export/export.go#L328-L334
func FileSequence_Start(id FileSeqId) C.int { fs, ok := sFileSeqs.Get(id) if !ok { return 0 } return C.int(fs.Start()) }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/build/transaction.go#L187-L195
func (m InflationBuilder) MutateTransaction(o *TransactionBuilder) error { if m.Err != nil { return m.Err } m.O.Body, m.Err = xdr.NewOperationBody(xdr.OperationTypeInflation, nil) o.TX.Operations = append(o.TX.Operations, m.O) return m.Err }
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L368-L370
func (d *Destination) sendBytes(path string, b []byte) error { return d.sendFile(path, int64(len(b)), bytes.NewReader(b)) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/pkg/transport/listener.go#L40-L45
func NewListener(addr, scheme string, tlsinfo *TLSInfo) (l net.Listener, err error) { if l, err = newListener(addr, scheme); err != nil { return nil, err } return wrapTLS(scheme, tlsinfo, l) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/functional/rpcpb/member.go#L220-L232
func (m *Member) IsLeader() (bool, error) { cli, err := m.CreateEtcdClient() if err != nil { return false, fmt.Errorf("%v (%q)", err, m.EtcdClientEndpoint) } defer cli.Close() resp, err := cli.Status(context.Background(), m.EtcdClientEndpoint) if err != nil { return false, err } return resp.Header.MemberId == resp.Leader, nil }
https://github.com/go-opencv/go-opencv/blob/a4fe8ec027ccc9eb8b7d0797db7c76e61083f1db/opencv/highgui.go#L546-L551
func (capture *Capture) GetProperty(property_id int) float64 { rv := C.cvGetCaptureProperty((*C.CvCapture)(capture), C.int(property_id), ) return float64(rv) }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/logger.go#L42-L47
func (opt *Options) Infof(format string, v ...interface{}) { if opt.Logger == nil { return } opt.Logger.Infof(format, v...) }
https://github.com/weaveworks/mesh/blob/512bdb7b3cb7b2c939fcd0ee434d48b6732ecc39/local_peer.go#L237-L245
func (peer *localPeer) broadcastPeerUpdate(peers ...*Peer) { // Some tests run without a router. This should be fixed so // that the relevant part of Router can be easily run in the // context of a test, but that will involve significant // reworking of tests. if peer.router != nil { peer.router.broadcastTopologyUpdate(append(peers, peer.Peer)) } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/runtime/runtime.go#L49-L52
func (p AwaitPromiseParams) WithGeneratePreview(generatePreview bool) *AwaitPromiseParams { p.GeneratePreview = generatePreview return &p }
https://github.com/stellar/go-stellar-base/blob/79c570612c0b461db178aa8949d9f13cafc2a7c9/xdr/xdr_generated.go#L4451-L4472
func NewTransactionResultResult(code TransactionResultCode, value interface{}) (result TransactionResultResult, err error) { result.Code = code switch TransactionResultCode(code) { case TransactionResultCodeTxSuccess: tv, ok := value.([]OperationResult) if !ok { err = fmt.Errorf("invalid value, must be []OperationResult") return } result.Results = &tv case TransactionResultCodeTxFailed: tv, ok := value.([]OperationResult) if !ok { err = fmt.Errorf("invalid value, must be []OperationResult") return } result.Results = &tv default: // void } return }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/rsync.go#L218-L277
func RsyncRecv(path string, conn *websocket.Conn, writeWrapper func(io.WriteCloser) io.WriteCloser, features []string) error { args := []string{ "--server", "-vlogDtpre.iLsfx", "--numeric-ids", "--devices", "--partial", "--sparse", } if features != nil && len(features) > 0 { args = append(args, rsyncFeatureArgs(features)...) } args = append(args, []string{".", path}...) cmd := exec.Command("rsync", args...) stdin, err := cmd.StdinPipe() if err != nil { return err } stdout, err := cmd.StdoutPipe() if err != nil { return err } stderr, err := cmd.StderrPipe() if err != nil { return err } if err := cmd.Start(); err != nil { return err } writePipe := io.WriteCloser(stdin) if writeWrapper != nil { writePipe = writeWrapper(stdin) } readDone, writeDone := shared.WebsocketMirror(conn, writePipe, stdout, nil, nil) output, err := ioutil.ReadAll(stderr) if err != nil { cmd.Process.Kill() cmd.Wait() return err } err = cmd.Wait() if err != nil { logger.Errorf("Rsync receive failed: %s: %s: %s", path, err, string(output)) } <-readDone <-writeDone return err }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/client/connection.go#L61-L68
func ConnectLXD(url string, args *ConnectionArgs) (ContainerServer, error) { logger.Debugf("Connecting to a remote LXD over HTTPs") // Cleanup URL url = strings.TrimSuffix(url, "/") return httpsLXD(url, args) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pkg/collection/collection.go#L219-L223
func (c *readWriteCollection) getIndexPath(val interface{}, index *Index, key string) string { reflVal := reflect.ValueOf(val) field := reflect.Indirect(reflVal).FieldByName(index.Field).Interface() return c.indexPath(index, field, key) }
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/tracer.go#L302-L304
func (t Tag) Set(s Span) { s.SetTag(t.Key, t.Value) }
https://github.com/etcd-io/etcd/blob/616592d9ba993e3fe9798eef581316016df98906/clientv3/op.go#L345-L357
func WithSort(target SortTarget, order SortOrder) OpOption { return func(op *Op) { if target == SortByKey && order == SortAscend { // If order != SortNone, server fetches the entire key-space, // and then applies the sort and limit, if provided. // Since by default the server returns results sorted by keys // in lexicographically ascending order, the client should ignore // SortOrder if the target is SortByKey. order = SortNone } op.sort = &SortOption{target, order} } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/dom/easyjson.go#L3820-L3824
func (v GetFlattenedDocumentParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoDom43(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/TheThingsNetwork/go-utils/blob/aa2a11bd59104d2a8609328c2b2b55da61826470/grpc/rpcerror/grpc.go#L30-L34
func UnaryClientInterceptor(fn ConvertFunc) grpc.UnaryClientInterceptor { return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) (err error) { return fn(invoker(ctx, method, req, reply, cc, opts...)) } }
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/google/compute/resources/instancegroup.go#L121-L335
func (r *InstanceGroup) Apply(actual, expected cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("instanceGroup.Apply") applyResource := expected.(*InstanceGroup) isEqual, err := compare.IsEqual(actual.(*InstanceGroup), expected.(*InstanceGroup)) if err != nil { return nil, nil, err } if isEqual { return immutable, applyResource, nil } masterIPPrivate := "" masterIPPublic := "" if r.ServerPool.Type == cluster.ServerPoolTypeNode { found := false for i := 0; i < MasterIPAttempts; i++ { masterTag := "" machineConfigs := immutable.MachineProviderConfigs() for _, machineConfig := range machineConfigs { serverPool := machineConfig.ServerPool if serverPool.Type == cluster.ServerPoolTypeMaster { masterTag = serverPool.Name } } if masterTag == "" { return nil, nil, fmt.Errorf("Unable to find master tag") } instanceGroupManager, err := Sdk.Service.InstanceGroupManagers.ListManagedInstances(immutable.ProviderConfig().CloudId, expected.(*InstanceGroup).Location, strings.ToLower(masterTag)).Do() if err != nil { return nil, nil, err } if err != nil || len(instanceGroupManager.ManagedInstances) == 0 { logger.Debug("Hanging for master IP.. (%v)", err) time.Sleep(time.Duration(MasterIPSleepSecondsPerAttempt) * time.Second) continue } parts := strings.Split(instanceGroupManager.ManagedInstances[0].Instance, "/") instance, err := Sdk.Service.Instances.Get(immutable.ProviderConfig().CloudId, expected.(*InstanceGroup).Location, parts[len(parts)-1]).Do() if err != nil { logger.Debug("Hanging for master IP.. (%v)", err) time.Sleep(time.Duration(MasterIPSleepSecondsPerAttempt) * time.Second) continue } for _, networkInterface := range instance.NetworkInterfaces { if networkInterface.Name == "nic0" { masterIPPrivate = networkInterface.NetworkIP for _, accessConfigs := range networkInterface.AccessConfigs { masterIPPublic = accessConfigs.NatIP } } } if masterIPPublic == "" { logger.Debug("Hanging for master IP..") time.Sleep(time.Duration(MasterIPSleepSecondsPerAttempt) * time.Second) continue } found = true providerConfig := immutable.ProviderConfig() providerConfig.Values.ItemMap["INJECTEDMASTER"] = fmt.Sprintf("%s:%s", masterIPPrivate, immutable.ProviderConfig().KubernetesAPI.Port) immutable.SetProviderConfig(providerConfig) break } if !found { return nil, nil, fmt.Errorf("Unable to find Master IP after defined wait") } } providerConfig := immutable.ProviderConfig() providerConfig.Values.ItemMap["INJECTEDPORT"] = immutable.ProviderConfig().KubernetesAPI.Port immutable.SetProviderConfig(providerConfig) scripts, err := script.BuildBootstrapScript(r.ServerPool.BootstrapScripts, immutable) if err != nil { return nil, nil, err } finalScripts := string(scripts) if err != nil { return nil, nil, err } tags := []string{} if r.ServerPool.Type == cluster.ServerPoolTypeMaster { if immutable.ProviderConfig().KubernetesAPI.Port == "443" { tags = append(tags, "https-server") } if immutable.ProviderConfig().KubernetesAPI.Port == "80" { tags = append(tags, "http-server") } tags = append(tags, "kubicorn-master") } if r.ServerPool.Type == cluster.ServerPoolTypeNode { tags = append(tags, "kubicorn-node") } prefix := "https://www.googleapis.com/compute/v1/projects/" + immutable.ProviderConfig().CloudId imageURL := "https://www.googleapis.com/compute/v1/projects/ubuntu-os-cloud/global/images/" + expected.(*InstanceGroup).Image templateInstance, err := Sdk.Service.InstanceTemplates.Get(immutable.ProviderConfig().CloudId, strings.ToLower(expected.(*InstanceGroup).Name)).Do() if err != nil { sshPublicKeyValue := fmt.Sprintf("%s:%s", immutable.ProviderConfig().SSH.User, string(immutable.ProviderConfig().SSH.PublicKeyData)) templateInstance = &compute.InstanceTemplate{ Name: strings.ToLower(expected.(*InstanceGroup).Name), Properties: &compute.InstanceProperties{ MachineType: expected.(*InstanceGroup).Size, Disks: []*compute.AttachedDisk{ { AutoDelete: true, Boot: true, Type: "PERSISTENT", InitializeParams: &compute.AttachedDiskInitializeParams{ SourceImage: imageURL, }, }, }, NetworkInterfaces: []*compute.NetworkInterface{ { AccessConfigs: []*compute.AccessConfig{ { Type: "ONE_TO_ONE_NAT", Name: "External NAT", }, }, Network: prefix + "/global/networks/default", }, }, ServiceAccounts: []*compute.ServiceAccount{ { Email: "default", Scopes: []string{ compute.DevstorageFullControlScope, compute.ComputeScope, }, }, }, Metadata: &compute.Metadata{ Kind: "compute#metadata", Items: []*compute.MetadataItems{ { Key: "ssh-keys", Value: &sshPublicKeyValue, }, { Key: "startup-script", Value: &finalScripts, }, }, }, Tags: &compute.Tags{ Items: tags, }, }, } _, err = Sdk.Service.InstanceTemplates.Insert(immutable.ProviderConfig().CloudId, templateInstance).Do() if err != nil { return nil, nil, err } } _, err = Sdk.Service.InstanceGroupManagers.Get(immutable.ProviderConfig().CloudId, expected.(*InstanceGroup).Location, strings.ToLower(expected.(*InstanceGroup).Name)).Do() if err != nil { instanceGroupManager := &compute.InstanceGroupManager{ Name: templateInstance.Name, BaseInstanceName: templateInstance.Name, InstanceTemplate: prefix + "/global/instanceTemplates/" + templateInstance.Name, TargetSize: int64(expected.(*InstanceGroup).Count), } for i := 0; i < MasterIPAttempts; i++ { logger.Debug("Creating instance group manager") _, err = Sdk.Service.InstanceGroupManagers.Insert(immutable.ProviderConfig().CloudId, expected.(*InstanceGroup).Location, instanceGroupManager).Do() if err == nil { break } logger.Debug("Waiting for instance template to be ready.") time.Sleep(time.Duration(MasterIPSleepSecondsPerAttempt) * time.Second) } logger.Success("Created instance group manager [%s]", templateInstance.Name) } newResource := &InstanceGroup{ Shared: Shared{ Name: r.ServerPool.Name, //CloudID: id, }, Image: expected.(*InstanceGroup).Image, Size: expected.(*InstanceGroup).Size, Location: expected.(*InstanceGroup).Location, Count: expected.(*InstanceGroup).Count, BootstrapScripts: expected.(*InstanceGroup).BootstrapScripts, } providerConfig = immutable.ProviderConfig() providerConfig.KubernetesAPI.Endpoint = masterIPPublic immutable.SetProviderConfig(providerConfig) renderedCluster, err := r.immutableRender(newResource, immutable) if err != nil { return nil, nil, err } return renderedCluster, newResource, nil }
https://github.com/jhillyerd/enmime/blob/874cc30e023f36bd1df525716196887b0f04851b/encode.go#L186-L208
func selectTransferEncoding(content []byte, quoteLineBreaks bool) transferEncoding { if len(content) == 0 { return te7Bit } // Binary chars remaining before we choose b64 encoding. threshold := b64Percent * len(content) / 100 bincount := 0 for _, b := range content { if (b < ' ' || '~' < b) && b != '\t' { if !quoteLineBreaks && (b == '\r' || b == '\n') { continue } bincount++ if bincount >= threshold { return teBase64 } } } if bincount == 0 { return te7Bit } return teQuoted }
https://github.com/btcsuite/btclog/blob/84c8d2346e9fc8c7b947e243b9c24e6df9fd206a/log.go#L366-L371
func (l *slog) Debugf(format string, args ...interface{}) { lvl := l.Level() if lvl <= LevelDebug { l.b.printf("DBG", l.tag, format, args...) } }
https://github.com/lxc/lxd/blob/7a41d14e4c1a6bc25918aca91004d594774dcdd3/lxd/storage_zfs_utils.go#L93-L107
func zfsPoolVolumeExists(dataset string) (bool, error) { output, err := shared.RunCommand( "zfs", "list", "-Ho", "name") if err != nil { return false, err } for _, name := range strings.Split(output, "\n") { if name == dataset { return true, nil } } return false, nil }
https://github.com/ChrisTrenkamp/goxpath/blob/c385f95c6022e7756e91beac5f5510872f7dcb7d/internal/execxp/findutil/findUtil.go#L34-L46
func Find(x tree.Node, p pathexpr.PathExpr) []tree.Node { ret := []tree.Node{} if p.Axis == "" { findChild(x, &p, &ret) return ret } f := findMap[p.Axis] f(x, &p, &ret) return ret }
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssd/codegen_client.go#L36-L56
func (r *Href) ActionPath(rName, aName string) (*metadata.ActionPath, error) { res, ok := GenMetadata[rName] if !ok { return nil, fmt.Errorf("No resource with name '%s'", rName) } var action *metadata.Action for _, a := range res.Actions { if a.Name == aName { action = a break } } if action == nil { return nil, fmt.Errorf("No action with name '%s' on %s", aName, rName) } vars, err := res.ExtractVariables(string(*r)) if err != nil { return nil, err } return action.URL(vars) }
https://github.com/pachyderm/pachyderm/blob/94fb2d536cb6852a77a49e8f777dc9c1bde2c723/src/server/pps/server/server.go#L66-L91
func NewSidecarAPIServer( env *serviceenv.ServiceEnv, etcdPrefix string, iamRole string, reporter *metrics.Reporter, workerGrpcPort uint16, pprofPort uint16, httpPort uint16, peerPort uint16, ) (ppsclient.APIServer, error) { apiServer := &apiServer{ Logger: log.NewLogger("pps.API"), env: env, etcdPrefix: etcdPrefix, iamRole: iamRole, reporter: reporter, workerUsesRoot: true, pipelines: ppsdb.Pipelines(env.GetEtcdClient(), etcdPrefix), jobs: ppsdb.Jobs(env.GetEtcdClient(), etcdPrefix), workerGrpcPort: workerGrpcPort, pprofPort: pprofPort, httpPort: httpPort, peerPort: peerPort, } return apiServer, nil }
https://github.com/jmank88/nuts/blob/8b28145dffc87104e66d074f62ea8080edfad7c8/paths.go#L49-L146
func SeekPathMatch(c *bolt.Cursor, path []byte) ([]byte, []byte) { // Validation if len(path) == 0 { return nil, nil } if path[0] != '/' { return nil, nil } // Exact match fast-path if k, v := c.Seek(path); bytes.Equal(k, path) { return k, v } // Prefix scan prefixBuf := bytes.NewBuffer(make([]byte, 0, len(path))) for { // Match slash prefixBuf.WriteByte('/') prefix := prefixBuf.Bytes() k, v := c.Seek(prefix) if !bytes.HasPrefix(k, prefix) { return nil, nil } // Advance past '/' path = path[1:] // Exact match required for trailing slash. if len(path) == 0 { if len(k) == len(prefix) { return k, v } return nil, nil } // Advance cursor past exact match to first prefix match. if len(k) == len(prefix) { k, v = c.Next() if !bytes.HasPrefix(k, prefix) { return nil, nil } } // Find end of element. i := bytes.IndexByte(path, '/') last := i < 0 switch k[len(prefix)] { case '*': return k, v case ':': // Append variable path element to prefix ki := bytes.IndexByte(k[len(prefix):], '/') if ki < 0 { prefixBuf.Write(k[len(prefix):]) } else { prefixBuf.Write(k[len(prefix) : len(prefix)+ki]) } if last { // Exact match required for last element. prefix = prefixBuf.Bytes() if k, v = c.Seek(prefix); bytes.Equal(k, prefix) { return k, v } return nil, nil } default: // Append path component to prefix. if last { prefixBuf.Write(path) } else { prefixBuf.Write(path[:i]) } prefix = prefixBuf.Bytes() k, v = c.Seek(prefix) if last { // Exact match required for last element. if bytes.Equal(k, prefix) { return k, v } return nil, nil } // Prefix match required for other elements. if !bytes.HasPrefix(k, prefix) { return nil, nil } } // Advance past element. path = path[i:] } }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L1307-L1311
func (v EventTargetDestroyed) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget14(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/target.go#L292-L295
func (p CreateTargetParams) WithBrowserContextID(browserContextID BrowserContextID) *CreateTargetParams { p.BrowserContextID = browserContextID return &p }
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/mux/provider/user_service.go#L79-L95
func GetUser(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("X-Api-Correlation-Id", "1234") // Get username from path a := strings.Split(r.URL.Path, "/") id, _ := strconv.Atoi(a[len(a)-1]) user, err := userRepository.ByID(id) if err != nil { w.WriteHeader(http.StatusNotFound) } else { w.WriteHeader(http.StatusOK) resBody, _ := json.Marshal(user) w.Write(resBody) } }
https://github.com/DamienFontaine/lunarc/blob/2e7332a51f554794a549a313430eaa7dec8d13cc/config/utils.go#L27-L48
func Get(source interface{}, environment string, configEnv Environment) (conf interface{}, err error) { if filename, ok := source.(string); ok { source, err = ioutil.ReadFile(filename) if err != nil { log.Printf("Fatal: %v", err) return } } err = yaml.Unmarshal(source.([]byte), configEnv) if err != nil { log.Printf("Fatal: bad config : %v", err) return } conf = configEnv.GetEnvironment(environment) if conf == nil { err = errors.New("No configuration") return } return }
https://github.com/mattn/go-xmpp/blob/6093f50721ed2204a87a81109ca5a466a5bec6c1/xmpp.go#L673-L675
func (c *Client) SendOrg(org string) (n int, err error) { return fmt.Fprint(c.conn, org) }
https://github.com/kubernetes/test-infra/blob/8125fbda10178887be5dff9e901d6a0a519b67bc/prow/plugins/golint/golint.go#L121-L140
func newProblems(cs []github.ReviewComment, ps map[string]map[int]lint.Problem) map[string]map[int]lint.Problem { // Make a copy, then remove the old elements. res := make(map[string]map[int]lint.Problem) for f, ls := range ps { res[f] = make(map[int]lint.Problem) for l, p := range ls { res[f][l] = p } } for _, c := range cs { if c.Position == nil { continue } if !strings.Contains(c.Body, commentTag) { continue } delete(res[c.Path], *c.Position) } return res }
https://github.com/tsuru/tsuru/blob/2f7fd515c5dc25a58aec80f0e497c49e49581b3e/auth/native/native.go#L112-L135
func (s NativeScheme) ResetPassword(user *auth.User, resetToken string) error { if resetToken == "" { return auth.ErrInvalidToken } conn, err := db.Conn() if err != nil { return err } defer conn.Close() passToken, err := getPasswordToken(resetToken) if err != nil { return err } if passToken.UserEmail != user.Email { return auth.ErrInvalidToken } password := generatePassword(12) user.Password = password hashPassword(user) go sendNewPassword(user, password) passToken.Used = true conn.PasswordTokens().UpdateId(passToken.Token, passToken) return user.Update() }
https://github.com/hashicorp/raft/blob/773bcaa2009bf059c5c06457b9fccd156d5e91e7/replication.go#L84-L95
func (s *followerReplication) notifyAll(leader bool) { // Clear the waiting notifies minimizing lock time s.notifyLock.Lock() n := s.notify s.notify = make(map[*verifyFuture]struct{}) s.notifyLock.Unlock() // Submit our votes for v, _ := range n { v.vote(leader) } }
https://github.com/aphistic/gomol/blob/1546845ba714699f76f484ad3af64cf0503064d1/log_adapter.go#L272-L276
func (la *LogAdapter) Die(exitCode int, msg string) { la.Log(LevelFatal, nil, msg) la.base.ShutdownLoggers() curExiter.Exit(exitCode) }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/reqres.go#L211-L223
func (r *reqResReader) argReader(last bool, inState reqResReaderState, outState reqResReaderState) (ArgReader, error) { if r.state != inState { return nil, r.failed(errReqResReaderStateMismatch{state: r.state, expectedState: inState}) } argReader, err := r.contents.ArgReader(last) if err != nil { return nil, r.failed(err) } r.state = outState return argReader, nil }
https://github.com/xwb1989/sqlparser/blob/120387863bf27d04bc07db8015110a6e96d0146c/dependency/hack/hack.go#L64-L73
func String(b []byte) (s string) { if len(b) == 0 { return "" } pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) pstring.Data = pbytes.Data pstring.Len = pbytes.Len return }
https://github.com/ant0ine/go-json-rest/blob/ebb33769ae013bd5f518a8bac348c310dea768b8/rest/access_log_apache.go#L71-L94
func (mw *AccessLogApacheMiddleware) MiddlewareFunc(h HandlerFunc) HandlerFunc { // set the default Logger if mw.Logger == nil { mw.Logger = log.New(os.Stderr, "", 0) } // set default format if mw.Format == "" { mw.Format = DefaultLogFormat } mw.convertFormat() return func(w ResponseWriter, r *Request) { // call the handler h(w, r) util := &accessLogUtil{w, r} mw.Logger.Print(mw.executeTextTemplate(util)) } }
https://github.com/uber/tchannel-go/blob/3c9ced6d946fe2fec6c915703a533e966c09e07a/typed/buffer.go#L136-L139
func (r *ReadBuffer) ReadUvarint() uint64 { v, _ := binary.ReadUvarint(r) return v }
https://github.com/taskcluster/taskcluster-client-go/blob/ef6acd428ae5844a933792ed6479d0e7dca61ef8/tcpurgecache/tcpurgecache.go#L98-L102
func (purgeCache *PurgeCache) Ping() error { cd := tcclient.Client(*purgeCache) _, _, err := (&cd).APICall(nil, "GET", "/ping", nil, nil) return err }
https://github.com/dgraph-io/badger/blob/6b796b3ebec3ff006fcb1b425836cd784651e9fd/batch.go#L111-L126
func (wb *WriteBatch) Delete(k []byte) error { wb.Lock() defer wb.Unlock() if err := wb.txn.Delete(k); err != ErrTxnTooBig { return err } if err := wb.commit(); err != nil { return err } if err := wb.txn.Delete(k); err != nil { wb.err = err return err } return nil }
https://github.com/libp2p/go-libp2p-crypto/blob/9d2fed53443f745e6dc4d02bdcc94d9742a0ca84/ecdsa.go#L119-L126
func (ePriv *ECDSAPrivateKey) Equals(o Key) bool { oPriv, ok := o.(*ECDSAPrivateKey) if !ok { return false } return ePriv.priv.D.Cmp(oPriv.priv.D) == 0 }
https://github.com/chromedp/cdproto/blob/d40c70bcdf242660a32f2eadf323662dd75378b5/target/easyjson.go#L2350-L2354
func (v CloseTargetParams) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} easyjsonC5a4559bEncodeGithubComChromedpCdprotoTarget27(&w, v) return w.Buffer.BuildBytes(), w.Error }
https://github.com/HiLittleCat/core/blob/ae2101184ecd36354d3fcff0ea69d67d3fdbe156/log.go#L17-L53
func SetLog(logPath string, logFileName string) { if Log != nil { return } Log = logrus.New() maxAge := time.Hour * 24 * 10 rotationTime := time.Hour * 24 //info用于记录http状态等一般日期 infoLogPaht := path.Join(logPath, logFileName+"_info") infoWriter, err := rotatelogs.New( infoLogPaht+".%Y%m%d", rotatelogs.WithLinkName(infoLogPaht), // 生成软链,指向最新日志文件 rotatelogs.WithMaxAge(maxAge), // 文件最大保存时间 rotatelogs.WithRotationTime(rotationTime), // 日志切割时间间隔 ) //error记录告警和错误信息 errorLogPaht := path.Join(logPath, logFileName+"_error") errorWriter, err := rotatelogs.New( errorLogPaht+".%Y%m%d", rotatelogs.WithLinkName(errorLogPaht), // 生成软链,指向最新日志文件 rotatelogs.WithMaxAge(maxAge), // 文件最大保存时间 rotatelogs.WithRotationTime(rotationTime), // 日志切割时间间隔 ) if err != nil { logrus.Errorf("config local file system logger error. %+v", errors.WithStack(err)) } // 为不同级别设置不同的输出文件 lfHook := lfshook.NewHook(lfshook.WriterMap{ logrus.InfoLevel: infoWriter, logrus.WarnLevel: errorWriter, logrus.ErrorLevel: errorWriter, }, &logrus.TextFormatter{ TimestampFormat: "2006-01-02 15:04:05.000", }) Log.AddHook(lfHook) }