input
stringlengths
24
2.11k
output
stringlengths
7
948
package addrmgr import ( "time" "github.com/abcsuite/abcd/wire" ) func TstKnownAddressIsBad(ka *KnownAddress) bool { return ka.isBad() } func TstNewKnownAddress(na *wire.NetAddress, attempts int, lastattempt, lastsuccess time.Time, tried bool, refs int) *KnownAddress { return &KnownAddress{na: na, attempts: attempts, lastattempt: lastattempt, lastsuccess: lastsuccess, tried: tried, refs: refs} } func TstKnownAddressChance(ka *KnownAddress) float64
{ return ka.chance() }
package unibyte import "unicode" func IsLower(b byte) bool { return b >= 'a' && b <= 'z' } func IsLetter(b byte) bool { return IsLower(b) || IsUpper(b) } func IsSpaceQuote(b byte) bool { return IsSpace(b) || b == '"' || b == '\'' } func IsSpace(b byte) bool { return unicode.IsSpace(rune(b)) } func ToLower(b byte) byte { if IsUpper(b) { b = b - 'A' + 'a' } return b } func ToUpper(b byte) byte { if IsLower(b) { b = b - 'a' + 'A' } return b } func ToLowerString(b byte) string { if IsUpper(b) { b = b - 'A' + 'a' } return string(b) } func ToUpperString(b byte) string { if IsLower(b) { b = b - 'a' + 'A' } return string(b) } func IsUpper(b byte) bool
{ return b >= 'A' && b <= 'Z' }
package wire_test import ( "bytes" "io" ) type fixedWriter struct { b []byte pos int } func (w *fixedWriter) Write(p []byte) (n int, err error) { lenp := len(p) if w.pos+lenp > cap(w.b) { return 0, io.ErrShortWrite } n = lenp w.pos += copy(w.b[w.pos:], p) return } func (w *fixedWriter) Bytes() []byte { return w.b } func newFixedWriter(max int) io.Writer { b := make([]byte, max, max) fw := fixedWriter{b, 0} return &fw } type fixedReader struct { buf []byte pos int iobuf *bytes.Buffer } func (fr *fixedReader) Read(p []byte) (n int, err error) { n, err = fr.iobuf.Read(p) fr.pos += n return } func newFixedReader(max int, buf []byte) io.Reader
{ b := make([]byte, max, max) if buf != nil { copy(b[:], buf) } iobuf := bytes.NewBuffer(b) fr := fixedReader{b, 0, iobuf} return &fr }
package collector import ( "testing" "time" "github.com/google/cadvisor/info/v1" "github.com/stretchr/testify/assert" ) type fakeCollector struct { nextCollectionTime time.Time err error collectedFrom int } func (fc *fakeCollector) Name() string { return "fake-collector" } func (fc *fakeCollector) GetSpec() []v1.MetricSpec { return []v1.MetricSpec{} } func TestCollect(t *testing.T) { cm := &GenericCollectorManager{} firstTime := time.Now().Add(-time.Hour) secondTime := time.Now().Add(time.Hour) f1 := &fakeCollector{ nextCollectionTime: firstTime, } f2 := &fakeCollector{ nextCollectionTime: secondTime, } assert := assert.New(t) assert.NoError(cm.RegisterCollector(f1)) assert.NoError(cm.RegisterCollector(f2)) nextTime, _, err := cm.Collect() assert.Equal(firstTime, nextTime) assert.NoError(err) assert.Equal(1, f1.collectedFrom) assert.Equal(1, f2.collectedFrom) f1.nextCollectionTime = time.Now().Add(2 * time.Hour) nextTime, _, err = cm.Collect() assert.Equal(secondTime, nextTime) assert.NoError(err) assert.Equal(2, f1.collectedFrom) assert.Equal(1, f2.collectedFrom) } func (fc *fakeCollector) Collect(metric map[string]v1.MetricVal) (time.Time, map[string]v1.MetricVal, error)
{ fc.collectedFrom++ return fc.nextCollectionTime, metric, fc.err }
package auth import ( "sync" "github.com/google/martian/session" ) const key = "auth.Context" type Context struct { mu sync.RWMutex id string err error } func FromContext(ctx *session.Context) *Context { if v, ok := ctx.GetSession().Get(key); ok { return v.(*Context) } actx := &Context{} ctx.GetSession().Set(key, actx) return actx } func (ctx *Context) SetID(id string) { ctx.mu.Lock() ctx.mu.Unlock() ctx.err = nil if id == "" { return } ctx.id = id } func (ctx *Context) SetError(err error) { ctx.mu.Lock() defer ctx.mu.Unlock() ctx.id = "" ctx.err = err } func (ctx *Context) Error() error { ctx.mu.RLock() defer ctx.mu.RUnlock() return ctx.err } func (ctx *Context) ID() string
{ ctx.mu.RLock() ctx.mu.RUnlock() return ctx.id }
package main import ( "fmt" ) func main() { methods() interfaces() typeAssertions() } func interfaces() { fmt.Println("Interfaces") fmt.Println("==========") person := Person{ Phrase: "Hello", Thought: "Cogito ergo sum", } dog := Dog{} var sentient Sentient sentient = person fmt.Printf("sentient says '%s' and thinks '%s'\n", sentient.Speak(), sentient.Reason()) var speaker Speaker speaker = sentient fmt.Printf("sentient speaker says '%s'\n", speaker.Speak()) speaker = dog fmt.Printf("non-sentient speaker says '%s'\n", speaker.Speak()) speaker.Speak() fmt.Println() } func typeAssertions() { fmt.Println("Type assertions") fmt.Println("===============") var i interface{} = "All types match the empty interface" f, ok := i.(float64) fmt.Printf("Type assertion results for float64 -> f = %f, ok = %t\n", f, ok) s, ok := i.(string) fmt.Printf("Type assertion results for string -> s = %s, ok = %t\n", s, ok) switch i.(type) { case int: fmt.Println("It's an int") case string: fmt.Println("It's a string") default: fmt.Println("Hell if I know") } fmt.Println() } func methods()
{ fmt.Println("Methods") fmt.Println("=======") swedishChef := Person{ Phrase: "Bork bork bork!", } fmt.Printf("swedishChef says '%s'\n", swedishChef.Speak()) myFloat := MyFloat(16.0) myFloat.Square() fmt.Printf("myFloat -> value = %f, squared = %f\n", myFloat, myFloat.Square()) fmt.Println() }
package influxdb import ( "fmt" "log" "net/url" "testing" "time" "github.com/fractalplatform/fractal/metrics" client "github.com/influxdata/influxdb1-client" ) const ( dburl = "http://localhost:8086" testdb = "testmetrics" username = "" password = "" namespace = "test/" prefix = "test" table = namespace + prefix + ".timer" ) func TestQuery(t *testing.T) { host, err := url.Parse(dburl) if err != nil { log.Fatal(err) } con, err := client.NewClient(client.Config{URL: *host}) if err != nil { log.Fatal(err) } q := client.Query{ Command: fmt.Sprintf(`select * from "%s"`, table), Database: testdb, } if response, err := con.Query(q); err == nil && response.Error() == nil { log.Println(response.Results) } } func TestWrite(t *testing.T)
{ go InfluxDBWithTags(metrics.DefaultRegistry, 1*time.Second, dburl, testdb, "", "", namespace, make(map[string]string)) tm := metrics.NewRegisteredTimer(prefix, nil) for i := 0; i < 5; i++ { tm.Update(100 * time.Second) } time.Sleep(time.Duration(10) * time.Second) }
package main import ( "fmt" "net/http" rice "github.com/GeertJohan/go.rice" "git.timschuster.info/rls.moe/catgi/logger" ) type handlerServeResources struct { rice *rice.Box } func newHandlerServeResources() http.Handler { return &handlerServeResources{ rice: (&rice.Config{ LocateOrder: []rice.LocateMethod{ rice.LocateWorkingDirectory, rice.LocateFS, rice.LocateEmbedded, }, }).MustFindBox("./resources"), } } func (h *handlerServeResources) ServeHTTP(rw http.ResponseWriter, r *http.Request)
{ log := logger.LogFromCtx("serverIndex", r.Context()) log.Info("Loading file from disk: ", r.RequestURI) dat, err := h.rice.Bytes(r.URL.String()) if err != nil { log.Error("Could not load file from disk: ", err) rw.WriteHeader(404) fmt.Fprint(rw, "index.html not found") return } rw.WriteHeader(200) rw.Header().Add("Content-Type", "application/html") rw.Write(dat) }
package logutils import ( "github.com/stretchr/testify/mock" ) type MockLog struct { mock.Mock } func NewMockLog() *MockLog { return &MockLog{} } func (m *MockLog) Fatalf(format string, args ...interface{}) { mArgs := []interface{}{format} m.Called(append(mArgs, args...)...) } func (m *MockLog) Panicf(format string, args ...interface{}) { mArgs := []interface{}{format} m.Called(append(mArgs, args...)...) } func (m *MockLog) Errorf(format string, args ...interface{}) { mArgs := []interface{}{format} m.Called(append(mArgs, args...)...) } func (m *MockLog) Warnf(format string, args ...interface{}) { mArgs := []interface{}{format} m.Called(append(mArgs, args...)...) } func (m *MockLog) Infof(format string, args ...interface{}) { mArgs := []interface{}{format} m.Called(append(mArgs, args...)...) } func (m *MockLog) Child(name string) Log { m.Called(name) return m } func (m *MockLog) SetLevel(level LogLevel)
{ m.Called(level) }
package lock import ( "testing" . "gopkg.in/check.v1" ) func Test(t *testing.T) { TestingT(t) } type LockSuite struct{} var _ = Suite(&LockSuite{}) func (s *LockSuite) TestDebugLock(c *C) { var lock1 RWMutexDebug lock1.Lock() lock1.Unlock() lock1.RLock() lock1.RLock() lock1.RUnlock() lock1.RUnlock() var lock2 MutexDebug lock2.Lock() lock2.Unlock() } func (s *LockSuite) TestLock(c *C)
{ var lock1 RWMutex lock1.Lock() lock1.Unlock() lock1.RLock() lock1.RLock() lock1.RUnlock() lock1.RUnlock() var lock2 Mutex lock2.Lock() lock2.Unlock() }
package models import "testing" func TestGetEntityName(t *testing.T) { _, err := GetEntityName(2) if err != nil { t.Error(err) return } } func TestGetTypeName(t *testing.T) { _, err := GetTypeName(2) if err != nil { t.Error(err) return } } func TestGetCelestialName(t *testing.T) { _, err := GetCelestialName(30000001) if err != nil { t.Error(err) return } } func TestGetSystemName(t *testing.T)
{ _, err := GetSystemName(30000001) if err != nil { t.Error(err) return } }
package codegen import ( "os" "testing" "goa.design/goa/v3/codegen/service" "goa.design/goa/v3/expr" ) func makeGolden(t *testing.T, p string) *os.File { t.Helper() if os.Getenv("GOLDEN") == "" { return nil } f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY, 0600) if err != nil { t.Fatal(err) } return f } func RunHTTPDSL(t *testing.T, dsl func()) *expr.RootExpr
{ service.Services = make(service.ServicesData) HTTPServices = make(ServicesData) return expr.RunDSL(t, dsl) }
package rorm type rorm struct { redisQuerier *RedisQuerier } func NewROrm() ROrmer { return new(rorm).Using("default") } func (r *rorm) QueryHash(key string) HashQuerySeter { return &hashQuerySet{ querySet: &querySet{ rorm: r, key: key, }, } } func (r *rorm) QueryKeys(key string) KeysQuerySeter { return &keysQuerySet{ querySet: &querySet{ rorm: r, key: key, }, } } func (r *rorm) QueryString(key string) StringQuerySeter { return &stringQuerySet{ querySet: &querySet{ rorm: r, key: key, }, } } func (r *rorm) QueryZSet(key string) ZSetQuerySeter { return &zsetQuerySet{ querySet: &querySet{ rorm: r, key: key, }, } } func (r rorm) Using(alias string) ROrmer { client, ok := redisRegistry[alias] if !ok { panic("using reids '" + alias + "' not exist.") } r.redisQuerier = &RedisQuerier{ Client: client, } return &r } func (r *rorm) Querier() Querier { return r.redisQuerier } func (r *rorm) QuerySet(key string) SetQuerySeter
{ return &setQuerySet{ querySet: &querySet{ rorm: r, key: key, }, } }
package data_table import ( "bytes" "encoding/json" "fmt" "github.com/julienschmidt/httprouter" "net/http" "net/url" ) func TreePostFormValues(values url.Values) map[string]interface{} { res := make(map[string]interface{}) var currValue map[string]interface{} for rawKey, value := range values { if vs := value; len(vs) > 0 { currValue = res keyPath := ParseKey(rawKey) lastIndex := len(keyPath) - 1 for index, key := range keyPath { if index == lastIndex { currValue[key] = vs[0] } else { if _, ok := currValue[key]; !ok { currValue[key] = make(map[string]interface{}) } currValue = currValue[key].(map[string]interface{}) } } } } return res } func ParseKey(key string) []string { res := make([]string, 0) var currKey bytes.Buffer for _, char := range key { if char == '[' || char == ']' { if currKey.Len() > 0 { res = append(res, currKey.String()) currKey.Reset() } } else { currKey.WriteRune(char) } } if currKey.Len() > 0 { res = append(res, currKey.String()) } return res } func DataStoreHandler(tableStore TableStore) func(http.ResponseWriter, *http.Request, httprouter.Params)
{ return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { request := newSearchRequest(r, ps) result := tableStore.QueryData(request) jsonBytes, _ := json.Marshal(result) fmt.Fprint(w, string(jsonBytes)) } }
package sharpen import ( "hawx.me/code/img/blur" "hawx.me/code/img/utils" "image" "image/color" "math" ) func UnsharpMask(in image.Image, radius int, sigma, amount, threshold float64) image.Image { blurred := blur.Gaussian(in, radius, sigma, blur.IGNORE) bounds := in.Bounds() out := image.NewRGBA(bounds) diff := func(a, b float64) float64 { if a > b { return a - b } return b - a } for y := bounds.Min.Y; y < bounds.Max.Y; y++ { for x := bounds.Min.X; x < bounds.Max.X; x++ { ar, ag, ab, aa := utils.RatioRGBA(in.At(x, y)) br, bg, bb, _ := utils.RatioRGBA(blurred.At(x, y)) if diff(ar, br) >= threshold { ar = amount*(ar-br) + ar } if diff(ag, bg) >= threshold { ag = amount*(ag-bg) + ag } if diff(ab, bb) >= threshold { ab = amount*(ab-bb) + ab } out.Set(x, y, color.NRGBA{ uint8(utils.Truncatef(ar * 255)), uint8(utils.Truncatef(ag * 255)), uint8(utils.Truncatef(ab * 255)), uint8(aa * 255), }) } } return out } func Sharpen(in image.Image, radius int, sigma float64) image.Image
{ normalize := 0.0 f := func(u, v int) float64 { usq := float64(u * u) vsq := float64(v * v) val := -math.Exp(-(usq+vsq)/(2.0*sigma*sigma)) / (2.0 * math.Pi * sigma * sigma) normalize += val return val } k := blur.NewKernel(radius*2+1, radius*2+1, f) k[radius+1][radius+1] = -2.0 * normalize return blur.Convolve(in, k, blur.CLAMP) }
package main import ( "crypto/tls" "crypto/x509" log "github.com/Sirupsen/logrus" "io" "io/ioutil" "time" ) type TLSConnection struct { host string certPool *x509.CertPool conn *tls.Conn } func (c *TLSConnection) Connect() (err error) { c.conn, err = tls.Dial("tcp", c.host, &tls.Config{ RootCAs: c.certPool, }) if err != nil { return } c.conn.SetWriteDeadline(time.Time{}) return } func (c *TLSConnection) WriteString(s string) (n int, err error) { return io.WriteString(c.conn, s) } func (c *TLSConnection) Write(p []byte) (n int, err error) { return c.conn.Write(p) } func (c *TLSConnection) Close() error { return c.conn.Close() } func (c *TLSConnection) getCerts() { c.certPool = x509.NewCertPool() cert, err := ioutil.ReadFile(certsPemFile) if err != nil { log.Fatal(err) } if !c.certPool.AppendCertsFromPEM(cert) { log.Fatal("Failed parsing root certificate") } } func NewTLSConnection(host string) (*TLSConnection, error)
{ c := &TLSConnection{} c.host = host c.getCerts() err := c.Connect() return c, err }
package pml_test import ( "encoding/xml" "testing" "baliance.com/gooxml/schema/soo/pml" ) func TestEG_TopLevelSlideConstructor(t *testing.T) { v := pml.NewEG_TopLevelSlide() if v == nil { t.Errorf("pml.NewEG_TopLevelSlide must return a non-nil value") } if err := v.Validate(); err != nil { t.Errorf("newly constructed pml.EG_TopLevelSlide should validate: %s", err) } } func TestEG_TopLevelSlideMarshalUnmarshal(t *testing.T)
{ v := pml.NewEG_TopLevelSlide() buf, _ := xml.Marshal(v) v2 := pml.NewEG_TopLevelSlide() xml.Unmarshal(buf, v2) }
package testing import ( "github.com/markdaws/gohome/pkg/cmd" "github.com/markdaws/gohome/pkg/gohome" ) type extension struct { gohome.NullExtension } func (e *extension) Name() string { return "testing" } func (e *extension) NetworkForDevice(sys *gohome.System, d *gohome.Device) gohome.Network { return nil } func (e *extension) EventsForDevice(sys *gohome.System, d *gohome.Device) *gohome.ExtEvents { switch d.ModelNumber { case "testing.hardware": evts := &gohome.ExtEvents{} evts.Producer = &producer{ Device: d, System: sys, } evts.Consumer = &consumer{ Device: d, System: sys, } return evts default: return nil } } func (e *extension) Discovery(sys *gohome.System) gohome.Discovery { return &discovery{} } func NewExtension() *extension { return &extension{} } func (e *extension) BuilderForDevice(sys *gohome.System, d *gohome.Device) cmd.Builder
{ switch d.ModelNumber { case "testing.hardware": return &cmdBuilder{ModelNumber: d.ModelNumber, Device: d} default: return nil } }
package hawkular import ( "net/url" "sync" "github.com/adfin/statster/metrics/core" hawkular "github.com/hawkular/hawkular-client-go/metrics" ) type Filter func(ms *core.MetricSet, metricName string) bool type FilterType int const ( Label FilterType = iota Name Unknown ) type hawkularSink struct { client *hawkular.Client models map[string]*hawkular.MetricDefinition regLock sync.RWMutex reg map[string]*hawkular.MetricDefinition uri *url.URL labelTenant string labelNodeId string labelTagPrefix string modifiers []hawkular.Modifier filters []Filter disablePreCaching bool batchSize int } func heapsterTypeToHawkularType(t core.MetricType) hawkular.MetricType { switch t { case core.MetricCumulative: return hawkular.Counter case core.MetricGauge: return hawkular.Gauge default: return hawkular.Gauge } } func (f FilterType) From(s string) FilterType
{ switch s { case "label": return Label case "name": return Name default: return Unknown } }
package distsql import ( "errors" "runtime" "testing" "time" . "github.com/pingcap/check" "github.com/pingcap/tidb/model" "github.com/pingcap/tidb/mysql" "github.com/pingcap/tidb/util/testleak" "github.com/pingcap/tidb/util/types" "github.com/pingcap/tipb/go-tipb" goctx "golang.org/x/net/context" ) func TestT(t *testing.T) { CustomVerboseFlag = true TestingT(t) } var _ = Suite(&testTableCodecSuite{}) type testTableCodecSuite struct{} func (s *testTableCodecSuite) TestColumnToProto(c *C) { defer testleak.AfterTest(c)() tp := types.NewFieldType(mysql.TypeLong) tp.Flag = 10 col := &model.ColumnInfo{ FieldType: *tp, } pc := columnToProto(col) c.Assert(pc.GetFlag(), Equals, int32(10)) } type mockResponse struct { count int } func (resp *mockResponse) Next() ([]byte, error) { resp.count++ if resp.count == 100 { return nil, errors.New("error happend") } return mockSubresult(), nil } func (resp *mockResponse) Close() error { return nil } func mockSubresult() []byte { resp := new(tipb.SelectResponse) b, err := resp.Marshal() if err != nil { panic(err) } return b } func (s *testTableCodecSuite) TestGoroutineLeak(c *C)
{ var sr SelectResult countBefore := runtime.NumGoroutine() sr = &selectResult{ resp: &mockResponse{}, results: make(chan resultWithErr, 5), closed: make(chan struct{}), } go sr.Fetch(goctx.TODO()) for { _, err := sr.Next() if err != nil { sr.Close() break } } tick := 10 * time.Millisecond totalSleep := time.Duration(0) for totalSleep < 3*time.Second { time.Sleep(tick) totalSleep += tick countAfter := runtime.NumGoroutine() if countAfter-countBefore < 5 { return } } c.Error("distsql goroutine leak!") }
package http import ( "strconv" "go-common/app/service/main/archive/api" "go-common/library/ecode" bm "go-common/library/net/http/blademaster" ) func pageList(c *bm.Context) { var ( aid int64 err error pages []*api.Page ) aidStr := c.Request.Form.Get("aid") if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil || aid <= 0 { c.JSON(nil, ecode.RequestErr) return } if pages, err = playSvr.PageList(c, aid); err != nil { c.JSON(nil, err) return } if len(pages) == 0 { c.JSON(nil, ecode.NothingFound) return } c.JSON(pages, nil) } func playURLToken(c *bm.Context) { var ( aid, cid, mid int64 err error ) params := c.Request.Form aidStr := params.Get("aid") if aid, err = strconv.ParseInt(aidStr, 10, 64); err != nil { c.JSON(nil, ecode.RequestErr) return } cid, _ = strconv.ParseInt(params.Get("cid"), 10, 64) midStr, _ := c.Get("mid") mid = midStr.(int64) c.JSON(playSvr.PlayURLToken(c, mid, aid, cid)) } func videoShot(c *bm.Context)
{ v := new(struct { Aid int64 `form:"aid" validate:"min=1"` Cid int64 `form:"cid"` Index bool `form:"index"` }) if err := c.Bind(v); err != nil { return } c.JSON(playSvr.VideoShot(c, v.Aid, v.Cid, v.Index)) }
package internal import ( "fmt" "log" "os" "gopkg.in/reform.v1" ) type Logger struct { printf reform.Printf debug bool } func NewLogger(prefix string, debug bool) *Logger { var flags int if debug { flags = log.Ldate | log.Lmicroseconds | log.Lshortfile } l := log.New(os.Stderr, prefix, flags) return &Logger{ printf: func(format string, args ...interface{}) { l.Output(3, fmt.Sprintf(format, args...)) }, debug: debug, } } func (l *Logger) Debugf(format string, args ...interface{}) { if l.debug { l.printf(format, args...) } } func (l *Logger) Printf(format string, args ...interface{}) { l.printf(format, args...) } func (l *Logger) Fatalf(format string, args ...interface{})
{ l.printf(format, args...) if l.debug { panic(fmt.Sprintf(format, args...)) } os.Exit(1) }
package timekeeper import "time" type TimeKeeper interface { After(d time.Duration) <-chan time.Time Sleep(d time.Duration) Now() time.Time } type realTime struct{} var rt realTime func (t *realTime) After(d time.Duration) <-chan time.Time { return time.After(d) } func (t *realTime) Sleep(d time.Duration) { time.Sleep(d) } func RealTime() TimeKeeper { return &rt } func (t *realTime) Now() time.Time
{ return time.Now() }
package client import ( "fmt" "strings" "google.golang.org/grpc/status" "google.golang.org/protobuf/encoding/prototext" "google.golang.org/protobuf/proto" _ "google.golang.org/genproto/googleapis/rpc/errdetails" ) type StatusError struct { st *status.Status details string } func (e *StatusError) Error() string { msg := fmt.Sprintf("rpc error: code = %s desc = %s", e.st.Code(), e.st.Message()) if e.details != "" { msg += " details = " + e.details } return msg } func (e *StatusError) GRPCStatus() *status.Status { return e.st } func (e *StatusError) Is(target error) bool { if tse, ok := target.(*StatusError); ok { return proto.Equal(e.st.Proto(), tse.st.Proto()) } if tst, ok := status.FromError(target); ok { return proto.Equal(e.st.Proto(), tst.Proto()) } return false } func StatusDetailedError(st *status.Status) *StatusError
{ var details []string for _, d := range st.Details() { s := fmt.Sprintf("%+v", d) if pb, ok := d.(proto.Message); ok { s = prototext.Format(pb) } details = append(details, s) } return &StatusError{st, strings.Join(details, "; ")} }
package cache import ( "context" "io" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/platform" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/tag" ) type BuildAndTestFn func(context.Context, io.Writer, tag.ImageTags, []*latestV1.Artifact, platform.Resolver) ([]graph.Artifact, error) type Cache interface { Build(context.Context, io.Writer, tag.ImageTags, []*latestV1.Artifact, platform.Resolver, BuildAndTestFn) ([]graph.Artifact, error) } type noCache struct{} func (n *noCache) Build(ctx context.Context, out io.Writer, tags tag.ImageTags, artifacts []*latestV1.Artifact, platforms platform.Resolver, buildAndTest BuildAndTestFn) ([]graph.Artifact, error)
{ return buildAndTest(ctx, out, tags, artifacts, platforms) }
package http import ( "net/http" "reflect" ) type JSONErrorBuilder interface { Build() JSONError CustomError(code int, errorType, msg string) JSONErrorBuilder FromError(e error) JSONErrorBuilder Message(string) JSONErrorBuilder Status(int) JSONErrorBuilder URL(string) JSONErrorBuilder } type jsonErrorBuilder struct { instance JSONError } func NewJSONError() JSONErrorBuilder { return &jsonErrorBuilder{JSONError{ Status: http.StatusInternalServerError, }} } func (b *jsonErrorBuilder) Build() JSONError { return b.instance } func (b *jsonErrorBuilder) CustomError( code int, errorType, msg string, ) JSONErrorBuilder { b.instance.Code = code b.instance.Type = errorType b.instance.Message = msg return b } func (b *jsonErrorBuilder) FromError(e error) JSONErrorBuilder { errType := reflect.TypeOf(e) var typeName string if errType.Kind() == reflect.Ptr { typeName = errType.Elem().Name() } else { typeName = errType.Name() } b.instance.Type = typeName b.instance.Message = e.Error() return b } func (b *jsonErrorBuilder) Status(status int) JSONErrorBuilder { b.instance.Status = status return b } func (b *jsonErrorBuilder) URL(url string) JSONErrorBuilder { b.instance.MoreInfo = url return b } var _ JSONErrorBuilder = (*jsonErrorBuilder)(nil) func (b *jsonErrorBuilder) Message(msg string) JSONErrorBuilder
{ b.instance.Message = msg return b }
package models import ( "context" "encoding/json" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/validate" ) type RdmaProtocol string const ( RdmaProtocolRoce RdmaProtocol = "roce" ) var rdmaProtocolEnum []interface{} func init() { var res []RdmaProtocol if err := json.Unmarshal([]byte(`["roce"]`), &res); err != nil { panic(err) } for _, v := range res { rdmaProtocolEnum = append(rdmaProtocolEnum, v) } } func (m RdmaProtocol) validateRdmaProtocolEnum(path, location string, value RdmaProtocol) error { if err := validate.EnumCase(path, location, value, rdmaProtocolEnum, true); err != nil { return err } return nil } func (m RdmaProtocol) Validate(formats strfmt.Registry) error { var res []error if err := m.validateRdmaProtocolEnum("", "body", m); err != nil { return err } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m RdmaProtocol) ContextValidate(ctx context.Context, formats strfmt.Registry) error
{ return nil }
package db import ( "time" "github.com/jinzhu/gorm" _"github.com/mattn/go-sqlite3" ) var ( DB gorm.DB ) type User struct { Id int `json:"id"` Username string `json:"username"; unique` Password string `json:"password"` Created time.Time `json:"created_at"` } type Device struct { Id int `json:"id"` Wifimode string `json:"wifimode"` Wifissid string `json:"wifissid"` Wifipwd string `json:"wifipwd"` Wifiip string `json:"wifiip"` Wifinetmask string `json:"wifinetmask"` Wifigateway string `json:"gateway"` Device string `json:"device"` Land string `json:"land"` Serial string `json:"serial"` Mac string `json:"mac"` Ip string `json:"ip"` Landhq string `json:"landhq"` Swstate string `json:"swstate"` Created time.Time `json:"created_at"` } func Init(dbname *string) error
{ var err error DB, err = gorm.Open("sqlite3", *dbname) if err != nil { return err } DB.AutoMigrate(&User{}, &Device{}) return nil }
package com import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func TestIsFile(t *testing.T) { if !IsFile("file.go") { t.Errorf("IsExist:\n Expect => %v\n Got => %v\n", true, false) } if IsFile("testdata") { t.Errorf("IsExist:\n Expect => %v\n Got => %v\n", false, true) } if IsFile("files.go") { t.Errorf("IsExist:\n Expect => %v\n Got => %v\n", false, true) } } func TestIsExist(t *testing.T) { Convey("Check if file or directory exists", t, func() { Convey("Pass a file name that exists", func() { So(IsExist("file.go"), ShouldEqual, true) }) Convey("Pass a directory name that exists", func() { So(IsExist("testdata"), ShouldEqual, true) }) Convey("Pass a directory name that does not exist", func() { So(IsExist(".hg"), ShouldEqual, false) }) }) } func BenchmarkIsExist(b *testing.B) { for i := 0; i < b.N; i++ { IsExist("file.go") } } func BenchmarkIsFile(b *testing.B)
{ for i := 0; i < b.N; i++ { IsFile("file.go") } }
package gtk import "C" import ( "unsafe" ) func (v *Menu) PopupAtMouseCursor(parentMenuShell IMenu, parentMenuItem IMenuItem, button int, activateTime uint32) { wshell := nullableWidget(parentMenuShell) witem := nullableWidget(parentMenuItem) C.gtk_menu_popup(v.native(), wshell, witem, nil, nil, C.guint(button), C.guint32(activateTime)) } func (v *SizeGroup) GetIgnoreHidden() bool { c := C.gtk_size_group_get_ignore_hidden(v.native()) return gobool(c) } func (v *Window) SetWMClass(name, class string) { cName := C.CString(name) defer C.free(unsafe.Pointer(cName)) cClass := C.CString(class) defer C.free(unsafe.Pointer(cClass)) C.gtk_window_set_wmclass(v.native(), (*C.gchar)(cName), (*C.gchar)(cClass)) } func (v *SizeGroup) SetIgnoreHidden(ignoreHidden bool) { C.gtk_size_group_set_ignore_hidden(v.native(), gbool(ignoreHidden)) } func (v *FontButton) SetFontName(fontname string) bool { cstr := C.CString(fontname) defer C.free(unsafe.Pointer(cstr)) c := C.gtk_font_button_set_font_name(v.native(), (*C.gchar)(cstr)) return gobool(c) } func (v *FontButton) GetFontName() string
{ c := C.gtk_font_button_get_font_name(v.native()) return goString(c) }
package leafnodes_test import ( . "github.com/sinbad/git-lfs-ssh-serve/Godeps/_workspace/src/github.com/onsi/ginkgo" . "github.com/sinbad/git-lfs-ssh-serve/Godeps/_workspace/src/github.com/onsi/gomega" "testing" ) func TestLeafNode(t *testing.T)
{ RegisterFailHandler(Fail) RunSpecs(t, "LeafNode Suite") }
package timeutil import ( "time" ) func SetTimeout(t time.Duration, callback func()) { go func() { time.Sleep(t) callback() }() } func SetInterval(t time.Duration, callback func() bool) { go func() { for { time.Sleep(t) if !callback() { break } } }() } func Nanosecond() int64 { return time.Now().UnixNano() } func Microsecond() int64 { return time.Now().UnixNano() / 1e3 } func Millisecond() int64 { return time.Now().UnixNano() / 1e6 } func Second() int64 { return time.Now().UnixNano() / 1e9 } func Date() string { return time.Now().Format("2006-01-02") } func Format(format string, timestamps ...int64) string { timestamp := Second() if len(timestamps) > 0 { timestamp = timestamps[0] } return time.Unix(timestamp, 0).Format(format) } func StrToTime(format string, timestr string) (int64, error) { t, err := time.Parse(format, timestr) if err != nil { return 0, err } return t.Unix(), nil } func Datetime() string
{ return time.Now().Format("2006-01-02 15:04:05") }
package iso20022 type PartyIdentificationAndAccount77 struct { Identification *PartyIdentification32Choice `xml:"Id"` AlternateIdentification *AlternatePartyIdentification5 `xml:"AltrnId,omitempty"` SafekeepingAccount *Max35Text `xml:"SfkpgAcct,omitempty"` ProcessingIdentification *Max35Text `xml:"PrcgId,omitempty"` AdditionalInformation *PartyTextInformation1 `xml:"AddtlInf,omitempty"` } func (p *PartyIdentificationAndAccount77) AddIdentification() *PartyIdentification32Choice { p.Identification = new(PartyIdentification32Choice) return p.Identification } func (p *PartyIdentificationAndAccount77) AddAlternateIdentification() *AlternatePartyIdentification5 { p.AlternateIdentification = new(AlternatePartyIdentification5) return p.AlternateIdentification } func (p *PartyIdentificationAndAccount77) SetSafekeepingAccount(value string) { p.SafekeepingAccount = (*Max35Text)(&value) } func (p *PartyIdentificationAndAccount77) SetProcessingIdentification(value string) { p.ProcessingIdentification = (*Max35Text)(&value) } func (p *PartyIdentificationAndAccount77) AddAdditionalInformation() *PartyTextInformation1
{ p.AdditionalInformation = new(PartyTextInformation1) return p.AdditionalInformation }
package armrecoveryservicesbackup_test import ( "context" "log" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/recoveryservices/armrecoveryservicesbackup" ) func ExampleBackupEnginesClient_Get() { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armrecoveryservicesbackup.NewBackupEnginesClient("<subscription-id>", cred, nil) res, err := client.Get(ctx, "<vault-name>", "<resource-group-name>", "<backup-engine-name>", &armrecoveryservicesbackup.BackupEnginesClientGetOptions{Filter: nil, SkipToken: nil, }) if err != nil { log.Fatal(err) } log.Printf("Response result: %#v\n", res.BackupEnginesClientGetResult) } func ExampleBackupEnginesClient_List()
{ cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armrecoveryservicesbackup.NewBackupEnginesClient("<subscription-id>", cred, nil) pager := client.List("<vault-name>", "<resource-group-name>", &armrecoveryservicesbackup.BackupEnginesClientListOptions{Filter: nil, SkipToken: nil, }) for { nextResult := pager.NextPage(ctx) if err := pager.Err(); err != nil { log.Fatalf("failed to advance page: %v", err) } if !nextResult { break } for _, v := range pager.PageResponse().Value { log.Printf("Pager result: %#v\n", v) } } }
package replicationcontroller import ( "github.com/kubernetes/dashboard/src/app/backend/resource/common" "github.com/kubernetes/dashboard/src/app/backend/resource/dataselect" "github.com/kubernetes/dashboard/src/app/backend/resource/service" metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1" client "k8s.io/client-go/kubernetes" ) func GetReplicationControllerServices(client client.Interface, dsQuery *dataselect.DataSelectQuery, namespace, rcName string) (*service.ServiceList, error)
{ replicationController, err := client.CoreV1().ReplicationControllers(namespace).Get(rcName, metaV1.GetOptions{}) if err != nil { return nil, err } channels := &common.ResourceChannels{ ServiceList: common.GetServiceListChannel(client, common.NewSameNamespaceQuery(namespace), 1), } services := <-channels.ServiceList.List if err := <-channels.ServiceList.Error; err != nil { return nil, err } matchingServices := common.FilterNamespacedServicesBySelector(services.Items, namespace, replicationController.Spec.Selector) return service.CreateServiceList(matchingServices, dsQuery), nil }
package nodos import ( "unsafe" ) func progressPrintCallBack(totalL, totalH, transferL, transferH, c1, c2, d1, d2, e, f, g, h, this uintptr) uintptr
{ progressPrint(uint64(totalL)|(uint64(totalH)<<32), uint64(transferL)|(uint64(transferH)<<32), (*progressCopy)(unsafe.Pointer(this))) return 0 }
package engine import ( "time" "github.com/aws/amazon-ecs-agent/agent/api" ) type impossibleTransitionError struct { state api.ContainerStatus } func (err *impossibleTransitionError) Error() string { return "Cannot transition to " + err.state.String() } func (err *impossibleTransitionError) ErrorName() string { return "ImpossibleStateTransitionError" } type DockerTimeoutError struct { duration time.Duration transition string } func (err *DockerTimeoutError) Error() string { return "Could not transition to " + err.transition + "; timed out after waiting " + err.duration.String() } func (err *DockerTimeoutError) ErrorName() string { return "DockerTimeoutError" } type ContainerVanishedError struct{} func (err ContainerVanishedError) Error() string { return "No container matching saved ID found" } func (err ContainerVanishedError) ErrorName() string { return "ContainerVanishedError" } type CannotXContainerError struct { transition string msg string } func (err CannotXContainerError) Error() string { return err.msg } func (err CannotXContainerError) ErrorName() string { return "Cannot" + err.transition + "ContainerError" } type OutOfMemoryError struct{} func (err OutOfMemoryError) Error() string { return "Container killed due to memory usage" } type DockerStateError struct { dockerError string name string } func NewDockerStateError(err string) DockerStateError { return DockerStateError{ dockerError: err, name: "DockerStateError", } } func (err DockerStateError) Error() string { return err.dockerError } func (err DockerStateError) ErrorName() string { return err.name } func (err OutOfMemoryError) ErrorName() string
{ return "OutOfMemoryError" }
package vision import ( "golang.org/x/net/context" "google.golang.org/grpc/metadata" ) func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) out = out.Copy() for _, md := range mds { for k, v := range md { out[k] = append(out[k], v...) } } return metadata.NewOutgoingContext(ctx, out) } func DefaultAuthScopes() []string
{ return []string{ "https:www.googleapis.com/auth/cloud-platform", "https:www.googleapis.com/auth/cloud-vision", } }
package msd import ( "encoding/base64" "github.com/bluefw/blued/discoverd/api" "github.com/gin-gonic/gin" "log" "net/http" ) type ServiceResource struct { repo *DiscoverdRepo logger *log.Logger } func (sr *ServiceResource) RegMicroApp(c *gin.Context) { var as api.MicroApp if err := c.Bind(&as); err != nil { c.JSON(http.StatusBadRequest, api.NewError("problem decoding body")) return } sr.repo.Register(&as) c.JSON(http.StatusCreated, nil) } func (sr *ServiceResource) GetRouterTable(c *gin.Context) { addr, err := base64.StdEncoding.DecodeString(c.Params.ByName("addr")) if err != nil { c.JSON(http.StatusBadRequest, api.NewError("error decoding addr")) return } rt := sr.repo.GetRouterTable(string(addr)) c.JSON(http.StatusOK, rt) } func (sr *ServiceResource) Refresh(c *gin.Context) { addr, err := base64.StdEncoding.DecodeString(c.Params.ByName("addr")) if err != nil { c.JSON(http.StatusBadRequest, api.NewError("error decoding addr")) return } appStatus := sr.repo.Refresh(string(addr)) c.JSON(http.StatusAccepted, appStatus) } func NewServiceResource(dr *DiscoverdRepo, l *log.Logger) *ServiceResource
{ return &ServiceResource{ repo: dr, logger: l, } }
package main import ( "io" "os" "text/template" ) func copyFile(dst, src string) (int64, error) { sf, err := os.Open(src) if err != nil { return 0, err } defer sf.Close() df, err := os.Create(dst) if err != nil { return 0, err } defer df.Close() return io.Copy(df, sf) } func writeTemplateToFile(path string, t *template.Template, data interface{}) (string, error)
{ f, e := os.Create(path) if e != nil { return "", e } defer f.Close() e = t.Execute(f, data) if e != nil { return "", e } return f.Name(), nil }
package api import ( "fmt" "net/http" "github.com/NebulousLabs/Sia/build" "github.com/NebulousLabs/Sia/types" ) type ConsensusGET struct { Height types.BlockHeight `json:"height"` CurrentBlock types.BlockID `json:"currentblock"` Target types.Target `json:"target"` } func (srv *Server) consensusHandler(w http.ResponseWriter, req *http.Request) { if req.Method == "" || req.Method == "GET" { srv.consensusHandlerGET(w, req) return } writeError(w, "unrecognized method when calling /consensus", http.StatusBadRequest) } func (srv *Server) consensusHandlerGET(w http.ResponseWriter, req *http.Request)
{ id := srv.mu.RLock() defer srv.mu.RUnlock(id) curblockID := srv.currentBlock.ID() currentTarget, exists := srv.cs.ChildTarget(curblockID) if build.DEBUG { if !exists { fmt.Printf("Could not find block %s\n", curblockID) panic("server has nonexistent current block") } } writeJSON(w, ConsensusGET{ Height: types.BlockHeight(srv.blockchainHeight), CurrentBlock: srv.currentBlock.ID(), Target: currentTarget, }) }
package triton import ( "context" "encoding/json" "fmt" "net/http" "github.com/hashicorp/errwrap" ) type ConfigClient struct { *Client } func (c *Client) Config() *ConfigClient { return &ConfigClient{c} } type Config struct { DefaultNetwork string `json:"default_network"` } type GetConfigInput struct{} func (client *ConfigClient) GetConfig(ctx context.Context, input *GetConfigInput) (*Config, error) { path := fmt.Sprintf("/%s/config", client.accountName) respReader, err := client.executeRequest(ctx, http.MethodGet, path, nil) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errwrap.Wrapf("Error executing GetConfig request: {{err}}", err) } var result *Config decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errwrap.Wrapf("Error decoding GetConfig response: {{err}}", err) } return result, nil } type UpdateConfigInput struct { DefaultNetwork string `json:"default_network"` } func (client *ConfigClient) UpdateConfig(ctx context.Context, input *UpdateConfigInput) (*Config, error)
{ path := fmt.Sprintf("/%s/config", client.accountName) respReader, err := client.executeRequest(ctx, http.MethodPut, path, input) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errwrap.Wrapf("Error executing UpdateConfig request: {{err}}", err) } var result *Config decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errwrap.Wrapf("Error decoding UpdateConfig response: {{err}}", err) } return result, nil }
package xy type Group []Geometric func (g *Group) Add(shape Geometric) { *g = append(*g, shape) } func (g Group) Accept(visitor Visitor)
{ visitor.VisitGroup(g) }
package server import ( "fmt" "net/http" "github.com/localhots/shezmu/stats" ) type Server struct { port int ss *stats.Server mux *http.ServeMux } func (s *Server) Start() { addr := fmt.Sprintf(":%d", s.port) s.mux.HandleFunc("/stats.json", s.ss.History) go http.ListenAndServe(addr, s.mux) } func New(port int, ss *stats.Server) *Server
{ return &Server{ port: port, ss: ss, mux: http.NewServeMux(), } }
package goapp import( "github.com/xaevman/goat/mod/log" ) import( "testing" "time" ) func waitForShutdown() { <-time.After(10 * time.Second) Stop() } func TestDefaultApp(t *testing.T)
{ log.DebugLogs = true SetHeartbeat(1 * 1000) go waitForShutdown() stopChan := Start("DefaultApp") <-stopChan }
package kasper import ( "testing" "github.com/stretchr/testify/assert" ) func TestTopicProcessorConfig_kafkaConsumerGroup(t *testing.T) { c := &Config{ TopicProcessorName: "hari-seldon", } assert.Equal(t, "kasper-topic-processor-hari-seldon", c.kafkaConsumerGroup()) } func TestTopicProcessorConfig_producerClientID(t *testing.T)
{ c := &Config{ TopicProcessorName: "ford-prefect", } assert.Equal(t, "kasper-topic-processor-ford-prefect", c.producerClientID()) }
package util import "fmt" func PanicOnError(err error, message string) { if err != nil { panic(fmt.Sprintf("%s: %s", message, err.Error())) } } func PanicIfNil(check interface{}, message string)
{ if check == nil { panic(message) } }
package client import ( "fmt" "strings" "google.golang.org/grpc/status" "google.golang.org/protobuf/encoding/prototext" "google.golang.org/protobuf/proto" _ "google.golang.org/genproto/googleapis/rpc/errdetails" ) type StatusError struct { st *status.Status details string } func StatusDetailedError(st *status.Status) *StatusError { var details []string for _, d := range st.Details() { s := fmt.Sprintf("%+v", d) if pb, ok := d.(proto.Message); ok { s = prototext.Format(pb) } details = append(details, s) } return &StatusError{st, strings.Join(details, "; ")} } func (e *StatusError) GRPCStatus() *status.Status { return e.st } func (e *StatusError) Is(target error) bool { if tse, ok := target.(*StatusError); ok { return proto.Equal(e.st.Proto(), tse.st.Proto()) } if tst, ok := status.FromError(target); ok { return proto.Equal(e.st.Proto(), tst.Proto()) } return false } func (e *StatusError) Error() string
{ msg := fmt.Sprintf("rpc error: code = %s desc = %s", e.st.Code(), e.st.Message()) if e.details != "" { msg += " details = " + e.details } return msg }
package lints import ( "github.com/zmap/zcrypto/x509" "github.com/zmap/zlint/util" ) type caKeyCertSignNotSet struct{} func (l *caKeyCertSignNotSet) Initialize() error { return nil } func (l *caKeyCertSignNotSet) Execute(c *x509.Certificate) *LintResult { if c.KeyUsage&x509.KeyUsageCertSign != 0 { return &LintResult{Status: Pass} } else { return &LintResult{Status: Error} } } func init() { RegisterLint(&Lint{ Name: "e_ca_key_cert_sign_not_set", Description: "Root CA Certificate: Bit positions for keyCertSign and cRLSign MUST be set.", Citation: "BRs: 7.1.2.1", Source: CABFBaselineRequirements, EffectiveDate: util.CABEffectiveDate, Lint: &caKeyCertSignNotSet{}, }) } func (l *caKeyCertSignNotSet) CheckApplies(c *x509.Certificate) bool
{ return c.IsCA && util.IsExtInCert(c, util.KeyUsageOID) }
package transporttest import ( "context" "fmt" "testing" "time" ) type ContextMatcher struct { t *testing.T ttl time.Duration TTLDelta time.Duration } type ContextMatcherOption interface { run(*ContextMatcher) } type ContextTTL time.Duration func (ttl ContextTTL) run(c *ContextMatcher) { c.ttl = time.Duration(ttl) } func NewContextMatcher(t *testing.T, options ...ContextMatcherOption) *ContextMatcher { matcher := &ContextMatcher{t: t, TTLDelta: DefaultTTLDelta} for _, opt := range options { opt.run(matcher) } return matcher } func (c *ContextMatcher) Matches(got interface{}) bool { ctx, ok := got.(context.Context) if !ok { c.t.Logf("expected a Context but got a %T: %v", got, got) return false } if c.ttl != 0 { d, ok := ctx.Deadline() if !ok { c.t.Logf( "expected Context to have a TTL of %v but it has no deadline", c.ttl) return false } ttl := time.Until(d) maxTTL := c.ttl + c.TTLDelta minTTL := c.ttl - c.TTLDelta if ttl > maxTTL || ttl < minTTL { c.t.Logf("TTL out of expected bounds: %v < %v < %v", minTTL, ttl, maxTTL) return false } } return true } func (c *ContextMatcher) String() string
{ return fmt.Sprintf("ContextMatcher(TTL:%v±%v)", c.ttl, c.TTLDelta) }
package identitymapper import ( "fmt" "k8s.io/klog" "k8s.io/apiserver/pkg/authentication/authenticator" "github.com/openshift/origin/pkg/oauthserver/api" ) func logf(format string, args ...interface{}) { if klog.V(4) { klog.InfoDepth(2, fmt.Sprintf("identitymapper: "+format, args...)) } } func ResponseFor(mapper api.UserIdentityMapper, identity api.UserIdentityInfo) (*authenticator.Response, bool, error)
{ user, err := mapper.UserFor(identity) if err != nil { logf("error creating or updating mapping for: %#v due to %v", identity, err) return nil, false, err } logf("got userIdentityMapping: %#v", user) return &authenticator.Response{User: user}, true, nil }
package collector import ( "errors" "fmt" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/log" ) import "C" type loadavgCollector struct { metric prometheus.Gauge } func init() { Factories["loadavg"] = NewLoadavgCollector } func (c *loadavgCollector) Update(ch chan<- prometheus.Metric) (err error) { load, err := getLoad1() if err != nil { return fmt.Errorf("Couldn't get load: %s", err) } log.Debugf("Set node_load: %f", load) c.metric.Set(load) c.metric.Collect(ch) return err } func getLoad1() (float64, error) { var loadavg [1]C.double samples := C.getloadavg(&loadavg[0], 1) if samples > 0 { return float64(loadavg[0]), nil } else { return 0, errors.New("failed to get load average") } } func NewLoadavgCollector() (Collector, error)
{ return &loadavgCollector{ metric: prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: Namespace, Name: "load1", Help: "1m load average.", }), }, nil }
package library import ( "context" "flag" "fmt" "github.com/vmware/govmomi/govc/cli" "github.com/vmware/govmomi/govc/flags" "github.com/vmware/govmomi/vapi/library" "github.com/vmware/govmomi/vapi/rest" ) type rm struct { *flags.ClientFlag force bool } func (cmd *rm) Register(ctx context.Context, f *flag.FlagSet) { cmd.ClientFlag, ctx = flags.NewClientFlag(ctx) cmd.ClientFlag.Register(ctx, f) } func (cmd *rm) Usage() string { return "NAME" } func (cmd *rm) Description() string { return `Delete library or item NAME. Examples: govc library.rm /library_name govc library.rm library_id # Use library id if multiple libraries have the same name govc library.rm /library_name/item_name` } func (cmd *rm) Run(ctx context.Context, f *flag.FlagSet) error { return cmd.WithRestClient(ctx, func(c *rest.Client) error { m := library.NewManager(c) res, err := flags.ContentLibraryResult(ctx, c, "", f.Arg(0)) if err != nil { return err } switch t := res.GetResult().(type) { case library.Library: return m.DeleteLibrary(ctx, &t) case library.Item: return m.DeleteLibraryItem(ctx, &t) default: return fmt.Errorf("%q is a %T", f.Arg(0), t) } }) } func init()
{ cli.Register("library.rm", &rm{}) }
package topovalidator import ( "fmt" "golang.org/x/net/context" "vitess.io/vitess/go/vt/topo" topodatapb "vitess.io/vitess/go/vt/proto/topodata" ) type KeyspaceValidator struct{} func (kv *KeyspaceValidator) Audit(ctx context.Context, ts *topo.Server, w *Workflow) error { keyspaces, err := ts.GetKeyspaces(ctx) if err != nil { return err } for _, keyspace := range keyspaces { _, err := ts.GetKeyspace(ctx, keyspace) if err != nil { w.AddFixer(keyspace, fmt.Sprintf("Error: %v", err), &KeyspaceFixer{ ts: ts, keyspace: keyspace, }, []string{"Create", "Delete"}) } } return nil } type KeyspaceFixer struct { ts *topo.Server keyspace string } func (kf *KeyspaceFixer) Action(ctx context.Context, name string) error { if name == "Create" { return kf.ts.CreateKeyspace(ctx, kf.keyspace, &topodatapb.Keyspace{}) } if name == "Delete" { return kf.ts.DeleteKeyspace(ctx, kf.keyspace) } return fmt.Errorf("unknown KeyspaceFixer action: %v", name) } func RegisterKeyspaceValidator()
{ RegisterValidator("Keyspace Validator", &KeyspaceValidator{}) }
package graphdriver import "C" import ( "path/filepath" "unsafe" "github.com/docker/docker/pkg/mount" "github.com/sirupsen/logrus" ) const ( FsMagicZfs = FsMagic(0x2fc12fc1) ) var ( priority = []string{ "zfs", } FsNames = map[FsMagic]string{ FsMagicZfs: "zfs", } ) func GetFSMagic(rootpath string) (FsMagic, error) { return 0, nil } type fsChecker struct { t FsMagic } func (c *fsChecker) IsMounted(path string) bool { m, _ := Mounted(c.t, path) return m } func NewFsChecker(t FsMagic) Checker { return &fsChecker{ t: t, } } func NewDefaultChecker() Checker { return &defaultChecker{} } type defaultChecker struct { } func (c *defaultChecker) IsMounted(path string) bool { m, _ := mount.Mounted(path) return m } func Mounted(fsType FsMagic, mountPath string) (bool, error)
{ cs := C.CString(filepath.Dir(mountPath)) defer C.free(unsafe.Pointer(cs)) buf := C.getstatfs(cs) defer C.free(unsafe.Pointer(buf)) if (buf.f_basetype[0] != 122) || (buf.f_basetype[1] != 102) || (buf.f_basetype[2] != 115) || (buf.f_basetype[3] != 0) { logrus.Debugf("[zfs] no zfs dataset found for rootdir '%s'", mountPath) return false, ErrPrerequisites } return true, nil }
package blobstoredbstatesnapshotio import ( "fmt" "golang.org/x/net/context" "github.com/nyaxt/otaru/metadata" ) func generateBlobpath() string { return fmt.Sprintf("%s_SimpleSSLocator", metadata.INodeDBSnapshotBlobpathPrefix) } var simplesslocatorTxID int64 type SimpleSSLocator struct{} func (SimpleSSLocator) Locate(history int) (string, int64, error) { return generateBlobpath(), simplesslocatorTxID, nil } func (SimpleSSLocator) GenerateBlobpath() string { return generateBlobpath() } func (SimpleSSLocator) Put(blobpath string, txid int64) error { simplesslocatorTxID = txid return nil } func (SimpleSSLocator) DeleteOld(ctx context.Context, threshold int, dryRun bool) ([]string, error)
{ return []string{}, nil }
package header import "github.com/google/netstack/tcpip" type NDPNeighborSolicit []byte const ( NDPNSMinimumSize = 20 ndpNSTargetAddessOffset = 4 ndpNSOptionsOffset = ndpNSTargetAddessOffset + IPv6AddressSize ) func (b NDPNeighborSolicit) SetTargetAddress(addr tcpip.Address) { copy(b[ndpNSTargetAddessOffset:][:IPv6AddressSize], addr) } func (b NDPNeighborSolicit) Options() NDPOptions { return NDPOptions(b[ndpNSOptionsOffset:]) } func (b NDPNeighborSolicit) TargetAddress() tcpip.Address
{ return tcpip.Address(b[ndpNSTargetAddessOffset:][:IPv6AddressSize]) }
package format import ( "github.com/trivago/gollum/core" "os" ) type Hostname struct { core.SimpleFormatter `gollumdoc:"embed_type"` separator []byte `config:"Separator" default:":"` } func init() { core.TypeRegistry.Register(Hostname{}) } func (format *Hostname) Configure(conf core.PluginConfigReader) { } func (format *Hostname) ApplyFormatter(msg *core.Message) error { content := format.getFinalContent(format.GetAppliedContent(msg)) format.SetAppliedContent(msg, content) return nil } func (format *Hostname) getFinalContent(content []byte) []byte
{ hostname, err := os.Hostname() if err != nil { format.Logger.Error(err) hostname = "unknown host" } dataSize := len(hostname) + len(format.separator) + len(content) payload := core.MessageDataPool.Get(dataSize) offset := copy(payload, []byte(hostname)) offset += copy(payload[offset:], format.separator) copy(payload[offset:], content) return payload }
package lifegame type Universe struct { aliveCells []Cell } type Cell struct{} func NewUniverse() *Universe { return &Universe{} } func (u *Universe) HasAliveCell() bool { return len(u.AliveCells()) != 0 } func (u *Universe) AliveCells() []Cell { return u.aliveCells } func (u *Universe) NextGeneration() { u.aliveCells = []Cell{} } func (u *Universe) BornCellAtLocation(x, y int) { u.aliveCells = append(u.aliveCells, Cell{}) } func (c *Cell) Location() (int, int)
{ return 0, 0 }
package backend import ( "sync" "github.com/docker/infrakit/pkg/run/scope" "github.com/spf13/cobra" "github.com/spf13/pflag" ) type ExecFunc func(script string, cmd *cobra.Command, args []string) error type FlagsFunc func(*pflag.FlagSet) type TemplateFunc func(scope scope.Scope, trial bool, opt ...interface{}) (ExecFunc, error) var ( backends = map[string]TemplateFunc{} flags = map[string]FlagsFunc{} lock = sync.Mutex{} ) func Visit(visitor func(funcName string, backend TemplateFunc)) { lock.Lock() defer lock.Unlock() for funcName, backend := range backends { visitor(funcName, backend) } } func VisitFlags(visitor func(string, FlagsFunc)) { lock.Lock() defer lock.Unlock() for funcName, f := range flags { visitor(funcName, f) } } func Register(funcName string, backend TemplateFunc, buildFlags FlagsFunc)
{ lock.Lock() defer lock.Unlock() backends[funcName] = backend flags[funcName] = buildFlags }
package server import ( "net/http" "github.com/fnproject/fn/api" "github.com/gin-gonic/gin" ) func (s *Server) handleAppGet(c *gin.Context)
{ ctx := c.Request.Context() appId := c.Param(api.AppID) app, err := s.datastore.GetAppByID(ctx, appId) if err != nil { handleErrorResponse(c, err) return } c.JSON(http.StatusOK, app) }
package restic import "syscall" func (node Node) restoreSymlinkTimestamps(path string, utimes [2]syscall.Timespec) error { return nil } func (node Node) device() int { return int(node.Device) } func (s statUnix) atim() syscall.Timespec { return s.Atimespec } func (s statUnix) mtim() syscall.Timespec { return s.Mtimespec } func (s statUnix) ctim() syscall.Timespec { return s.Ctimespec } func Getxattr(path, name string) ([]byte, error) { return nil, nil } func Setxattr(path, name string, data []byte) error { return nil } func Listxattr(path string) ([]string, error)
{ return nil, nil }
package post import "github.com/barnex/bruteray/imagef" type Params struct { Gaussian BloomParams Airy BloomParams Star BloomParams } type BloomParams struct { Radius float64 Amplitude float64 Threshold float64 } func (p *Params) ApplyTo(img imagef.Image, pixelSize float64) imagef.Image { if b := p.Gaussian; b.Radius != 0 { img = ApplyGaussianBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold) } if b := p.Airy; b.Radius != 0 { img = ApplyAiryBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold) } if b := p.Star; b.Radius != 0 { img = ApplyStarBloom(img, pixelSize, b.Radius, b.Amplitude, b.Threshold) } return img } func ApplyGaussianBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image { widthPix := radius / pixelSize numPix := int(5*widthPix) + 1 K := Gaussian(numPix, widthPix) img2 := img.Copy() AddConvolution(img2, img, K, amplitude, threshold) return img2 } func ApplyAiryBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image { widthPix := radius / pixelSize numPix := int(8*widthPix) + 1 K := Airy(numPix, widthPix) img2 := img.Copy() AddConvolution(img2, img, K, amplitude, threshold) return img2 } func ApplyStarBloom(img imagef.Image, pixelSize, radius, amplitude, threshold float64) imagef.Image
{ widthPix := radius / pixelSize numPix := int(widthPix) K := starKernel(numPix) img2 := img.Copy() AddConvolution(img2, img, K, amplitude, threshold) return img2 }
package byteorder import ( "encoding/binary" "net" "testing" . "gopkg.in/check.v1" ) func Test(t *testing.T) { TestingT(t) } type ByteorderSuite struct{} var _ = Suite(&ByteorderSuite{}) func (b *ByteorderSuite) TestNativeIsInitialized(c *C) { c.Assert(Native, NotNil) } func (b *ByteorderSuite) TestHostToNetwork(c *C) { switch Native { case binary.LittleEndian: c.Assert(HostToNetwork16(0xAABB), Equals, uint16(0xBBAA)) c.Assert(HostToNetwork32(0xAABBCCDD), Equals, uint32(0xDDCCBBAA)) case binary.BigEndian: c.Assert(HostToNetwork16(0xAABB), Equals, uint16(0xAABB)) c.Assert(HostToNetwork32(0xAABBCCDD), Equals, uint32(0xAABBCCDD)) } } func (b *ByteorderSuite) TestNetIPv4ToHost32(c *C)
{ switch Native { case binary.LittleEndian: c.Assert(NetIPv4ToHost32(net.ParseIP("10.11.129.91")), Equals, uint32(0x5b810b0a)) c.Assert(NetIPv4ToHost32(net.ParseIP("10.11.138.214")), Equals, uint32(0xd68a0b0a)) case binary.BigEndian: c.Assert(NetIPv4ToHost32(net.ParseIP("10.11.129.91")), Equals, uint32(0x0a0b815b)) c.Assert(NetIPv4ToHost32(net.ParseIP("10.11.138.214")), Equals, uint32(0x0a0b8ad6)) } }
package vm import ( "github.com/expanse-org/go-expanse/common" "github.com/expanse-org/go-expanse/common/math" "github.com/holiman/uint256" ) func calcMemSize64WithUint(off *uint256.Int, length64 uint64) (uint64, bool) { if length64 == 0 { return 0, false } offset64, overflow := off.Uint64WithOverflow() if overflow { return 0, true } val := offset64 + length64 return val, val < offset64 } func getData(data []byte, start uint64, size uint64) []byte { length := uint64(len(data)) if start > length { start = length } end := start + size if end > length { end = length } return common.RightPadBytes(data[start:end], int(size)) } func toWordSize(size uint64) uint64 { if size > math.MaxUint64-31 { return math.MaxUint64/32 + 1 } return (size + 31) / 32 } func allZero(b []byte) bool { for _, byte := range b { if byte != 0 { return false } } return true } func calcMemSize64(off, l *uint256.Int) (uint64, bool)
{ if !l.IsUint64() { return 0, true } return calcMemSize64WithUint(off, l.Uint64()) }
package metrics_test import ( "github.com/stripe/veneur/v14/ssf" "github.com/stripe/veneur/v14/trace" "github.com/stripe/veneur/v14/trace/metrics" ) func ExampleReportAsync()
{ samples := []*ssf.SSFSample{} samples = append(samples, ssf.Count("a.counter", 2, nil)) samples = append(samples, ssf.Gauge("a.gauge", 420, nil)) done := make(chan error) metrics.ReportAsync(trace.DefaultClient, samples, done) <-done }
package cluster import ( "common" "testing" . "launchpad.net/gocheck" ) type UserSuite struct{} var _ = Suite(&UserSuite{}) var root common.User func Test(t *testing.T) { TestingT(t) } func (self *UserSuite) TestProperties(c *C) { u := ClusterAdmin{CommonUser{Name: "root"}} c.Assert(u.IsClusterAdmin(), Equals, true) c.Assert(u.GetName(), Equals, "root") hash, err := HashPassword("foobar") c.Assert(err, IsNil) c.Assert(u.ChangePassword(string(hash)), IsNil) c.Assert(u.isValidPwd("foobar"), Equals, true) c.Assert(u.isValidPwd("password"), Equals, false) dbUser := DbUser{CommonUser{Name: "db_user"}, "db", nil, nil, true} c.Assert(dbUser.IsClusterAdmin(), Equals, false) c.Assert(dbUser.IsDbAdmin("db"), Equals, true) c.Assert(dbUser.GetName(), Equals, "db_user") hash, err = HashPassword("password") c.Assert(err, IsNil) c.Assert(dbUser.ChangePassword(string(hash)), IsNil) c.Assert(dbUser.isValidPwd("password"), Equals, true) c.Assert(dbUser.isValidPwd("password1"), Equals, false) } func (self *UserSuite) SetUpSuite(c *C)
{ user := &ClusterAdmin{CommonUser{"root", "", false, "root"}} c.Assert(user.ChangePassword("password"), IsNil) root = user }
package common import ( "strconv" "time" ) type ConversionResult struct { DateAsString string DateAsInt int Date time.Time } func ConvertIntToDisplay(dateAsInt int) string { dayAsString := strconv.Itoa(dateAsInt) return dayAsString } func ConvertStringToDates(dateAsString string) (ConversionResult, error) { result := ConversionResult{} result.DateAsString = dateAsString dateAsInt, err := strconv.Atoi(dateAsString) if err != nil { return result, nil } result.DateAsInt = dateAsInt date, err := time.Parse("20060102", dateAsString) if err != nil { return result, nil } result.Date = date return result, nil } func (d *ConversionResult) Yesterday() (ConversionResult, error) { return ConvertStringToDates(d.Date.AddDate(0, 0, -1).Format("20060102")) } func (d *ConversionResult) Tomorrow() (ConversionResult, error)
{ return ConvertStringToDates(d.Date.AddDate(0, 0, 1).Format("20060102")) }
package core import ( "github.com/oracle/oci-go-sdk/v46/common" "net/http" ) type CopyVolumeGroupBackupRequest struct { VolumeGroupBackupId *string `mandatory:"true" contributesTo:"path" name:"volumeGroupBackupId"` CopyVolumeGroupBackupDetails `contributesTo:"body"` OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"` OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"` RequestMetadata common.RequestMetadata } func (request CopyVolumeGroupBackupRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) { return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders) } func (request CopyVolumeGroupBackupRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) { return nil, false } func (request CopyVolumeGroupBackupRequest) RetryPolicy() *common.RetryPolicy { return request.RequestMetadata.RetryPolicy } type CopyVolumeGroupBackupResponse struct { RawResponse *http.Response VolumeGroupBackup `presentIn:"body"` Etag *string `presentIn:"header" name:"etag"` OpcRequestId *string `presentIn:"header" name:"opc-request-id"` } func (response CopyVolumeGroupBackupResponse) String() string { return common.PointerString(response) } func (response CopyVolumeGroupBackupResponse) HTTPResponse() *http.Response { return response.RawResponse } func (request CopyVolumeGroupBackupRequest) String() string
{ return common.PointerString(request) }
package handler import ( "net/http" "github.com/cosiner/zerver" ) type MethodHandler interface { Get(zerver.Request, zerver.Response) Post(zerver.Request, zerver.Response) Delete(zerver.Request, zerver.Response) Put(zerver.Request, zerver.Response) Patch(zerver.Request, zerver.Response) } type methodHandler struct { zerver.Component MethodHandler } func WrapMethodHandler(m MethodHandler) zerver.Handler { return &methodHandler{ Component: zerver.NopComponent{}, MethodHandler: m, } } func (s methodHandler) Handler(method string) zerver.HandleFunc { switch method { case zerver.METHOD_GET: return s.Get case zerver.METHOD_POST: return s.Post case zerver.METHOD_DELETE: return s.Delete case zerver.METHOD_PUT: return s.Put case zerver.METHOD_PATCH: return s.Patch } return nil } type NopMethodHandler struct{} func (NopMethodHandler) Get(_ zerver.Request, resp zerver.Response) { resp.StatusCode(http.StatusMethodNotAllowed) } func (NopMethodHandler) Post(_ zerver.Request, resp zerver.Response) { resp.StatusCode(http.StatusMethodNotAllowed) } func (NopMethodHandler) Delete(_ zerver.Request, resp zerver.Response) { resp.StatusCode(http.StatusMethodNotAllowed) } func (NopMethodHandler) Patch(_ zerver.Request, resp zerver.Response) { resp.StatusCode(http.StatusMethodNotAllowed) } func (NopMethodHandler) Put(_ zerver.Request, resp zerver.Response)
{ resp.StatusCode(http.StatusMethodNotAllowed) }
package main import ( "bytes" "github.com/bitly/go-nsq" ) type BackendQueue interface { Put([]byte) error ReadChan() chan []byte Close() error Delete() error Depth() int64 Empty() error } type DummyBackendQueue struct { readChan chan []byte } func NewDummyBackendQueue() BackendQueue { return &DummyBackendQueue{readChan: make(chan []byte)} } func (d *DummyBackendQueue) Put([]byte) error { return nil } func (d *DummyBackendQueue) Close() error { return nil } func (d *DummyBackendQueue) Delete() error { return nil } func (d *DummyBackendQueue) Depth() int64 { return int64(0) } func (d *DummyBackendQueue) Empty() error { return nil } func WriteMessageToBackend(buf *bytes.Buffer, msg *nsq.Message, bq BackendQueue) error { buf.Reset() err := msg.Write(buf) if err != nil { return err } err = bq.Put(buf.Bytes()) if err != nil { return err } return nil } func (d *DummyBackendQueue) ReadChan() chan []byte
{ return d.readChan }
package land import ( "context" "os" "code.cloudfoundry.org/lager" "code.cloudfoundry.org/lager/lagerctx" "github.com/concourse/concourse/atc" "github.com/concourse/concourse/worker" ) type LandWorkerCommand struct { TSA worker.TSAConfig `group:"TSA Configuration" namespace:"tsa" required:"true"` WorkerName string `long:"name" required:"true" description:"The name of the worker you wish to land."` } func (cmd *LandWorkerCommand) Execute(args []string) error
{ logger := lager.NewLogger("land-worker") logger.RegisterSink(lager.NewPrettySink(os.Stdout, lager.DEBUG)) client := cmd.TSA.Client(atc.Worker{ Name: cmd.WorkerName, }) return client.Land(lagerctx.NewContext(context.Background(), logger)) }
package main import ( "github.com/gossamer-irc/lib" "strings" ) type PendingClient struct { Ircd *Ircd Conn *IrcConnection Subnet *lib.Subnet Nick string Ident string Gecos string Host string } func NewPendingClient(ircd *Ircd, conn *IrcConnection, subnet *lib.Subnet, host string) *PendingClient { return &PendingClient{ Ircd: ircd, Subnet: subnet, Conn: conn, Host: host, } } func (pc *PendingClient) Handle(raw IrcClientMessage) { switch msg := raw.(type) { case *InvalidIrcClientMessage: break case *NickIrcClientMessage: lnick := strings.ToLower(msg.Nick) _, found := pc.Subnet.Client[lnick] if found { pc.Conn.Send(&IrcNickInUse{msg.Nick}) return } pc.Nick = msg.Nick pc.CheckReady() break case *UserIrcClientMessage: pc.Ident = msg.Ident pc.Gecos = msg.Gecos pc.CheckReady() break } } func (pc *PendingClient) CheckReady()
{ if pc.Nick == "" || pc.Ident == "" || pc.Gecos == "" { return } lnick := strings.ToLower(pc.Nick) _, found := pc.Subnet.Client[lnick] if found { pc.Conn.Send(&IrcNickInUse{pc.Nick}) pc.Nick = "" return } pc.Ircd.AcceptPendingClient(pc) }
package like import ( "context" "fmt" "go-common/app/interface/main/activity/model/like" "go-common/library/cache/memcache" "go-common/library/log" ) const ( _prefixInfo = "m_" ) func (dao *Dao) SetInfoCache(c context.Context, v *like.Subject, sid int64) (err error) { if v == nil { v = &like.Subject{} } var ( conn = dao.mc.Get(c) mckey = keyInfo(sid) ) defer conn.Close() if err = conn.Set(&memcache.Item{Key: mckey, Object: v, Flags: memcache.FlagGOB, Expiration: dao.mcLikeExpire}); err != nil { log.Error("conn.Set error(%v)", err) return } return } func (dao *Dao) InfoCache(c context.Context, sid int64) (v *like.Subject, err error) { var ( mckey = keyInfo(sid) conn = dao.mc.Get(c) item *memcache.Item ) defer conn.Close() if item, err = conn.Get(mckey); err != nil { if err == memcache.ErrNotFound { err = nil v = nil } else { log.Error("conn.Get error(%v)", err) } return } if err = conn.Scan(item, &v); err != nil { log.Error("item.Scan error(%v)", err) return } return } func keyInfo(sid int64) string
{ return fmt.Sprintf("%s%d", _prefixInfo, sid) }
package character type Histogram struct { counts [256]uint16 } func StringHistogram(text string) *Histogram { histogram := &Histogram{} for i := 0; i < len(text); i++ { histogram.Add(Char(text[i])) } return histogram } func (h *Histogram) Add(char Char) { h.counts[char]++ } func (h *Histogram) Count(char Char) int
{ return int(h.counts[char]) }
package dhcpv6 import ( "fmt" "github.com/u-root/uio/uio" ) type optRelayPort struct { DownstreamSourcePort uint16 } func (op *optRelayPort) Code() OptionCode { return OptionRelayPort } func (op *optRelayPort) ToBytes() []byte { buf := uio.NewBigEndianBuffer(nil) buf.Write16(op.DownstreamSourcePort) return buf.Data() } func (op *optRelayPort) String() string { return fmt.Sprintf("RelayPort: %d", op.DownstreamSourcePort) } func parseOptRelayPort(data []byte) (*optRelayPort, error) { var opt optRelayPort buf := uio.NewBigEndianBuffer(data) opt.DownstreamSourcePort = buf.Read16() return &opt, buf.FinError() } func OptRelayPort(port uint16) Option
{ return &optRelayPort{DownstreamSourcePort: port} }
package lib func cacheHintTagList(repository string) string { return "pull:" + repository } func cacheHintTagDetails(repository string) string { return "pull:" + repository } func cacheHintRegistryList() string
{ return "catalog:" }
package vpki import ( "crypto/tls" "sync" "time" ) type certCache struct { m map[string]*tls.Certificate mut *sync.RWMutex crt Certifier ttl time.Duration } func newCertCache(crt Certifier) *certCache { return &certCache{ m: map[string]*tls.Certificate{}, mut: &sync.RWMutex{}, crt: crt, ttl: DefaultTTL, } } func (cc *certCache) add(name string) (*tls.Certificate, error) { crt, err := cc.crt.Cert(name) if err != nil { return nil, err } cc.mut.Lock() cc.m[name] = crt cc.mut.Unlock() return crt, nil } func (cc *certCache) get(name string) (*tls.Certificate, error)
{ lkr := cc.mut.RLocker() lkr.Lock() if c, ok := cc.m[name]; ok { n := time.Now() if n.After(c.Leaf.NotBefore) && n.Before(c.Leaf.NotAfter) { lkr.Unlock() return c, nil } } lkr.Unlock() return cc.add(name) }
package fake_cmdpreparer import ( "os/exec" "sync" "code.cloudfoundry.org/garden" "code.cloudfoundry.org/garden-linux/container_daemon" ) type FakeCmdPreparer struct { PrepareCmdStub func(garden.ProcessSpec) (*exec.Cmd, error) prepareCmdMutex sync.RWMutex prepareCmdArgsForCall []struct { arg1 garden.ProcessSpec } prepareCmdReturns struct { result1 *exec.Cmd result2 error } } func (fake *FakeCmdPreparer) PrepareCmd(arg1 garden.ProcessSpec) (*exec.Cmd, error) { fake.prepareCmdMutex.Lock() fake.prepareCmdArgsForCall = append(fake.prepareCmdArgsForCall, struct { arg1 garden.ProcessSpec }{arg1}) fake.prepareCmdMutex.Unlock() if fake.PrepareCmdStub != nil { return fake.PrepareCmdStub(arg1) } else { return fake.prepareCmdReturns.result1, fake.prepareCmdReturns.result2 } } func (fake *FakeCmdPreparer) PrepareCmdCallCount() int { fake.prepareCmdMutex.RLock() defer fake.prepareCmdMutex.RUnlock() return len(fake.prepareCmdArgsForCall) } func (fake *FakeCmdPreparer) PrepareCmdReturns(result1 *exec.Cmd, result2 error) { fake.PrepareCmdStub = nil fake.prepareCmdReturns = struct { result1 *exec.Cmd result2 error }{result1, result2} } var _ container_daemon.CmdPreparer = new(FakeCmdPreparer) func (fake *FakeCmdPreparer) PrepareCmdArgsForCall(i int) garden.ProcessSpec
{ fake.prepareCmdMutex.RLock() defer fake.prepareCmdMutex.RUnlock() return fake.prepareCmdArgsForCall[i].arg1 }
package aviasales type Alliance struct { Name string `json:"name" bson:"name"` Airlines []string `json:"alias" bson:"alias"` } func (a *AviasalesApi) DataAirlinesAlliances() (airlinesAlliances []Alliance, err error)
{ err = a.getJson("data/airlines_alliances.json", map[string]string{}, &airlinesAlliances) return }
package v1 import ( "github.com/ertgl/croncache" ) func init()
{ err := croncache.TaskManagerRepository().Register(MODULE_NAME, Generator) if err != nil { croncache.HandleFatalError(err) } }
package cgotest import "C" import "testing" import "time" func test6997(t *testing.T)
{ r := C.StartThread() if r != 0 { t.Error("pthread_create failed") } c := make(chan C.int) go func() { time.Sleep(500 * time.Millisecond) c <- C.CancelThread() }() select { case r = <-c: if r == 0 { t.Error("pthread finished but wasn't cancelled??") } case <-time.After(30 * time.Second): t.Error("hung in pthread_cancel/pthread_join") } }
package watch type FilterFunc func(in Event) (out Event, keep bool) type filteredWatch struct { incoming Interface result chan Event f FilterFunc } func (fw *filteredWatch) ResultChan() <-chan Event { return fw.result } func (fw *filteredWatch) Stop() { fw.incoming.Stop() } func (fw *filteredWatch) loop() { defer close(fw.result) for { event, ok := <-fw.incoming.ResultChan() if !ok { break } filtered, keep := fw.f(event) if keep { fw.result <- filtered } } } func Filter(w Interface, f FilterFunc) Interface
{ fw := &filteredWatch{ incoming: w, result: make(chan Event), f: f, } go fw.loop() return fw }
package sql import ( "fmt" "github.com/cockroachdb/cockroach/sql/parser" ) func (p *planner) Values(n parser.Values) (planNode, error) { v := &valuesNode{ rows: make([]parser.DTuple, 0, len(n)), } for _, tuple := range n { data, err := parser.EvalExpr(tuple, nil) if err != nil { return nil, err } vals, ok := data.(parser.DTuple) if !ok { return nil, fmt.Errorf("expected a tuple, but found %T", data) } v.rows = append(v.rows, vals) } return v, nil } type valuesNode struct { columns []string rows []parser.DTuple nextRow int } func (n *valuesNode) Columns() []string { return n.columns } func (n *valuesNode) Values() parser.DTuple { return n.rows[n.nextRow-1] } func (*valuesNode) Err() error { return nil } func (n *valuesNode) Next() bool
{ if n.nextRow >= len(n.rows) { return false } n.nextRow++ return true }
package v1 import ( dataService "github.com/tidepool-org/platform/data/service" "github.com/tidepool-org/platform/request" "github.com/tidepool-org/platform/service" ) func Authenticate(handler dataService.HandlerFunc) dataService.HandlerFunc
{ return func(context dataService.Context) { if details := request.DetailsFromContext(context.Request().Context()); details == nil { context.RespondWithError(service.ErrorUnauthenticated()) return } handler(context) } }
package testing import "k8s.io/kubernetes/pkg/util/iptables" type fake struct{} func NewFake() *fake { return &fake{} } func (*fake) EnsureChain(table iptables.Table, chain iptables.Chain) (bool, error) { return true, nil } func (*fake) FlushChain(table iptables.Table, chain iptables.Chain) error { return nil } func (*fake) DeleteChain(table iptables.Table, chain iptables.Chain) error { return nil } func (*fake) EnsureRule(position iptables.RulePosition, table iptables.Table, chain iptables.Chain, args ...string) (bool, error) { return true, nil } func (*fake) DeleteRule(table iptables.Table, chain iptables.Chain, args ...string) error { return nil } func (*fake) IsIpv6() bool { return false } func (*fake) SaveAll() ([]byte, error) { return make([]byte, 0), nil } func (*fake) Restore(table iptables.Table, data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error { return nil } func (*fake) RestoreAll(data []byte, flush iptables.FlushFlag, counters iptables.RestoreCountersFlag) error { return nil } func (*fake) AddReloadFunc(reloadFunc func()) {} func (*fake) Destroy() {} var _ = iptables.Interface(&fake{}) func (*fake) Save(table iptables.Table) ([]byte, error)
{ return make([]byte, 0), nil }
package process import ( "net" "strconv" ) const ( MIN_PORT = 50000 MAX_PORT = 60000 INVALID_PORT = -1 ) func GetAvailablePort() (int, bool) { for port := MIN_PORT; port <= MAX_PORT; port++ { if !isPortUsed(port) { return port, true } } return INVALID_PORT, false } func isPortUsed(port int) bool
{ conn, err := net.Dial("tcp", net.JoinHostPort("localhost", strconv.Itoa(port))) if err != nil { return false } defer conn.Close() return true }
package lrucache import ( "testing" "time" "github.com/stretchr/testify/assert" ) func TestListMap_PushBack(t *testing.T) { m := NewListMap() t1 := time.Now().Nanosecond() t2 := time.Now().Nanosecond() m.PushBack(1, t1) m.PushFront(2, t2) v, _ := m.Get(1) assert.Equal(t, t1, v) v1, _ := m.Back() v2, _ := m.Front() assert.Equal(t, t1, v1) assert.Equal(t, t2, v2) assert.Equal(t, 2, m.Len()) } func TestListMap_PopFront(t *testing.T) { m := NewListMap() t1 := time.Now().Nanosecond() t2 := time.Now().Nanosecond() m.PushBack(1, t1) m.PushFront(2, t2) v, _ := m.PopFront() assert.Equal(t, t2, v) v, _ = m.Front() assert.Equal(t, t1, v) assert.Equal(t, 1, m.Len()) m.PopFront() m.PopFront() assert.Equal(t, 0, m.Len()) } func TestListMap_MoveToFront(t *testing.T)
{ m := NewListMap() t1 := time.Now().Nanosecond() t2 := time.Now().Nanosecond() m.PushBack(1, t1) m.PushFront(2, t2) m.MoveToFront(1) v1, _ := m.Back() v2, _ := m.Front() assert.Equal(t, t2, v1) assert.Equal(t, t1, v2) }
package storage import ( "fmt" "github.com/apigee-labs/transicator/common" "strings" ) const ( EntryComparatorName = "transicator-entries-v1" SequenceComparatorName = "transicator-sequence-v1" ) var entryComparator = new(entryCmp) var sequenceComparator = new(sequenceCmp) type entryCmp struct { } func (c entryCmp) Name() string { return EntryComparatorName } type sequenceCmp struct { } func (s sequenceCmp) Compare(a, b []byte) int { s1, err := common.ParseSequenceBytes(a) if err != nil { panic(fmt.Sprintf("Error parsing sequence: %s", err)) } s2, err := common.ParseSequenceBytes(b) if err != nil { panic(fmt.Sprintf("Error parsing sequence: %s", err)) } return s1.Compare(s2) } func (s sequenceCmp) Name() string { return SequenceComparatorName } func (c entryCmp) Compare(a, b []byte) int
{ aScope, aLsn, aIndex, err := keyToLsnAndOffset(a) if err != nil { panic(fmt.Sprintf("Error parsing database key: %s", err)) } bScope, bLsn, bIndex, err := keyToLsnAndOffset(b) if err != nil { panic(fmt.Sprintf("Error parsing database key: %s", err)) } scopeCmp := strings.Compare(aScope, bScope) if scopeCmp == 0 { if aLsn < bLsn { return -1 } else if aLsn > bLsn { return 1 } if aIndex < bIndex { return -1 } else if aIndex > bIndex { return 1 } return 0 } return scopeCmp }
package merkledag import ( "context" cid "gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid" ipld "gx/ipfs/QmR7TcHkR9nxkUorfi8XMTAMLUK7GiP64TWWBzY3aacc1o/go-ipld-format" ) type ErrorService struct { Err error } var _ ipld.DAGService = (*ErrorService)(nil) func (cs *ErrorService) Add(ctx context.Context, nd ipld.Node) error { return cs.Err } func (cs *ErrorService) AddMany(ctx context.Context, nds []ipld.Node) error { return cs.Err } func (cs *ErrorService) Get(ctx context.Context, c cid.Cid) (ipld.Node, error) { return nil, cs.Err } func (cs *ErrorService) Remove(ctx context.Context, c cid.Cid) error { return cs.Err } func (cs *ErrorService) RemoveMany(ctx context.Context, cids []cid.Cid) error { return cs.Err } func (cs *ErrorService) GetMany(ctx context.Context, cids []cid.Cid) <-chan *ipld.NodeOption
{ ch := make(chan *ipld.NodeOption) close(ch) return ch }
package models import ( "database/sql" "github.com/BrandonRomano/serf" db "github.com/carrot/burrow/db/postgres" "time" ) type Topic struct { serf.Worker `json:"-"` Id int64 `json:"id"` Name string `json:"name"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } func NewTopic() *Topic { topic := new(Topic) return topic.Prep() } func AllTopics(limit int64, offset int64) ([]Topic, error) { database := db.Get() rows, err := database.Query("SELECT * FROM topics ORDER BY created_at LIMIT $1 OFFSET $2", limit, offset) if err != nil { return nil, err } defer rows.Close() var topics []Topic = []Topic{} for rows.Next() { t := new(Topic) err = t.consumeNextRow(rows) if err != nil { return nil, err } topics = append(topics, *t) } err = rows.Err() if err != nil { return nil, err } return topics, nil } func (t *Topic) consumeNextRow(rows *sql.Rows) error { return rows.Scan( &t.Id, &t.Name, &t.CreatedAt, &t.UpdatedAt, ) } func (t *Topic) Prep() *Topic
{ t.Worker = &serf.PqWorker{ Database: db.Get(), Config: serf.Configuration{ TableName: "topics", Fields: []serf.Field{ serf.Field{Pointer: &t.Id, Name: "id", UniqueIdentifier: true, IsSet: func(pointer interface{}) bool { pointerInt := *pointer.(*int64) return pointerInt != 0 }, }, serf.Field{Pointer: &t.Name, Name: "name", Insertable: true, Updatable: true}, serf.Field{Pointer: &t.CreatedAt, Name: "created_at"}, serf.Field{Pointer: &t.UpdatedAt, Name: "updated_at"}, }, }, } return t }
package main import ( "bytes" "io/ioutil" "os" "path/filepath" "testing" . "gopkg.in/check.v1" ) func Test(t *testing.T) { TestingT(t) } type CommonTests struct { out *bytes.Buffer d *Dispatcher } var _ = Suite(&CommonTests{}) func (t *CommonTests) SetUpTest(c *C) { t.out = new(bytes.Buffer) t.d = &Dispatcher{stderr: t.out} } func removeFilesInDir(dir string) error
{ files, err := ioutil.ReadDir(dir) if err != nil { return err } for _, file := range files { path := filepath.Join(dir, file.Name()) err = os.Remove(path) if err != nil { return err } } return nil }
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { sc := bufio.NewScanner(os.Stdin) sc.Split(bufio.ScanWords) n := nextInt(sc) a := nextInt(sc) b := nextInt(sc) answer := 0 for i := 1; i <= n; i++ { sum := 0 for _, s := range fmt.Sprintf("%d", i) { x, _ := strconv.Atoi(string(s)) sum = sum + x } if a <= sum && sum <= b { answer = answer + i } } fmt.Println(answer) } func nextString(sc *bufio.Scanner) string { sc.Scan() return sc.Text() } func nextNumber(sc *bufio.Scanner) float64 { sc.Scan() f, err := strconv.ParseFloat(sc.Text(), 32) if err != nil { panic(err) } return f } func nextInt(sc *bufio.Scanner) int { sc.Scan() n, err := strconv.Atoi(sc.Text()) if err != nil { panic(err) } return n } func printArray(xs []int) { fmt.Println(strings.Trim(fmt.Sprint(xs), "[]")) } func debugPrintf(format string, a ...interface{})
{ fmt.Fprintf(os.Stderr, format, a...) }
package models import ( "sync" "github.com/eaciit/orm" ) type FuelTransport struct { sync.RWMutex orm.ModelBase `bson:"-" json:"-"` Plant string `bson:"Plant" json:"Plant"` Year int `bson:"Year" json:"Year"` TransportCost float64 `bson:"TransportCost" json:"TransportCost"` } func (m *FuelTransport) TableName() string
{ return "FuelTransport" }
package models import ( "crawshaw.io/sqlite" "xorm.io/builder" itchio "github.com/itchio/go-itchio" "github.com/itchio/hades" ) type ProfileGame struct { GameID int64 `json:"gameId" hades:"primary_key"` Game *itchio.Game `json:"game,omitempty"` ProfileID int64 `json:"profileId" hades:"primary_key"` Profile *Profile `json:"profile,omitempty"` Position int64 `json:"position"` ViewsCount int64 `json:"viewsCount"` DownloadsCount int64 `json:"downloadsCount"` PurchasesCount int64 `json:"purchasesCount"` Published bool `json:"published"` } func ProfileGamesByGameID(conn *sqlite.Conn, gameID int64) []*ProfileGame
{ var pgs []*ProfileGame MustSelect(conn, &pgs, builder.Eq{"game_id": gameID}, hades.Search{}) return pgs }
package kernel import ( "fmt" "os/exec" "strings" ) func GetKernelVersion() (*VersionInfo, error) { osName, err := getSPSoftwareDataType() if err != nil { return nil, err } release, err := getRelease(osName) if err != nil { return nil, err } return ParseRelease(release) } func getSPSoftwareDataType() (string, error) { cmd := exec.Command("system_profiler", "SPSoftwareDataType") osName, err := cmd.Output() if err != nil { return "", err } return string(osName), nil } func getRelease(osName string) (string, error)
{ var release string data := strings.Split(osName, "\n") for _, line := range data { if !strings.Contains(line, "Kernel Version") { continue } content := strings.SplitN(line, ":", 2) if len(content) != 2 { return "", fmt.Errorf("Kernel Version is invalid") } prettyNames := strings.SplitN(strings.TrimSpace(content[1]), " ", 2) if len(prettyNames) != 2 { return "", fmt.Errorf("Kernel Version needs to be 'Darwin x.x.x' ") } release = prettyNames[1] } return release, nil }
package util import ( "fmt" "os" "os/user" "strconv" ) func mkdir(paths []string) error { for _, path := range paths { err := os.MkdirAll(path, os.ModePerm) if err != nil { fmt.Printf("Make directory failed: %s\n", err) return err } } return nil } func chown(paths []string, userName string, groupName string) error { userId, err := GetUserId(userName) if err != nil { return err } groupId, err := getGroupId(groupName) if err != nil { return err } for _, path := range paths { err := os.Chown(path, userId, groupId) if err != nil { fmt.Printf("Chown failed: %s\n", err) } } return nil } func GetUserId(userName string) (int, error) { u, err := user.Lookup(userName) if err != nil { fmt.Printf("Failed to obtain UID: %s\n", err) return -1, err } userId, _ := strconv.Atoi(u.Uid) return userId, nil } func getGroupId(groupName string) (int, error) { g, err := user.LookupGroup(groupName) if err != nil { fmt.Printf("Failed to obtain GID: %s\n", err) return -1, err } groupId, _ := strconv.Atoi(g.Gid) return groupId, nil } func CreateVcapDirs(paths []string, userName string, groupName string) error
{ err := mkdir(paths) if err != nil { return err } err = chown(paths, userName, groupName) if err != nil { return err } return nil }
package models import ( strfmt "github.com/go-openapi/strfmt" "github.com/go-openapi/errors" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) type SendPhotoLinkBody struct { Caption string `json:"caption,omitempty"` ChatID interface{} `json:"chat_id"` DisableNotification bool `json:"disable_notification,omitempty"` Photo *string `json:"photo"` ReplyMarkup interface{} `json:"reply_markup,omitempty"` ReplyToMessageID int64 `json:"reply_to_message_id,omitempty"` } func (m *SendPhotoLinkBody) Validate(formats strfmt.Registry) error { var res []error if err := m.validateChatID(formats); err != nil { res = append(res, err) } if err := m.validatePhoto(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *SendPhotoLinkBody) validateChatID(formats strfmt.Registry) error { return nil } func (m *SendPhotoLinkBody) validatePhoto(formats strfmt.Registry) error { if err := validate.Required("photo", "body", m.Photo); err != nil { return err } return nil } func (m *SendPhotoLinkBody) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } func (m *SendPhotoLinkBody) UnmarshalBinary(b []byte) error
{ var res SendPhotoLinkBody if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
package main import ( "fmt" "reflect" ) type User struct{ Id int Name string Age int } func (u User) Hello(){ fmt.Println("Hello World.") } func main(){ var u User u = User{1, "ok", 12} info(u) } func info(o interface{})
{ t := reflect.TypeOf(o) fmt.Println("Type:", t.Name()) v := reflect.ValueOf(o) fmt.Println("Fields:") for i:= 0; i < t.NumField(); i++{ f := t.Field(i) val := v.Field(i).Interface() fmt.Printf("%6s: %v = %v\n", f.Name, f.Type, val) } for i:= 0; i < t.NumMethod(); i++{ m := t.Method(i) fmt.Printf("%6s: %v\n", m.Name) } }
package utils import ( "runtime" "strings" ) func GetTraceback() string
{ tb := make([]byte, 4096) stb := string(tb[:runtime.Stack(tb, false)]) lines := strings.Split(stb, "\n") for i := range lines { if strings.Contains(lines[i], "ServeHTTP") { return strings.Join(lines[4:i], "\n") } } return stb }