input
stringlengths
24
2.11k
output
stringlengths
7
948
package flags import ( "fmt" "io" "os" ) type IniError struct { Message string File string LineNumber uint } func (x *IniError) Error() string { return fmt.Sprintf("%s:%d: %s", x.File, x.LineNumber, x.Message) } type IniOptions uint const ( IniNone IniOptions = 0 IniIncludeDefaults = 1 << iota IniCommentDefaults IniIncludeComments IniDefault = IniIncludeComments ) type IniParser struct { parser *Parser } func NewIniParser(p *Parser) *IniParser { return &IniParser{ parser: p, } } func IniParse(filename string, data interface{}) error { p := NewParser(data, Default) return NewIniParser(p).ParseFile(filename) } func (i *IniParser) Parse(reader io.Reader) error { i.parser.storeDefaults() ini, err := readIni(reader, "") if err != nil { return err } return i.parse(ini) } func (i *IniParser) WriteFile(filename string, options IniOptions) error { file, err := os.Create(filename) if err != nil { return err } defer file.Close() i.Write(file, options) return nil } func (i *IniParser) Write(writer io.Writer, options IniOptions) { writeIni(i, writer, options) } func (i *IniParser) ParseFile(filename string) error
{ i.parser.storeDefaults() ini, err := readIniFromFile(filename) if err != nil { return err } return i.parse(ini) }
package global import ( "context" "sync" "go.opentelemetry.io/otel/propagation" ) type textMapPropagator struct { mtx sync.Mutex once sync.Once delegate propagation.TextMapPropagator noop propagation.TextMapPropagator } var _ propagation.TextMapPropagator = (*textMapPropagator)(nil) func newTextMapPropagator() *textMapPropagator { return &textMapPropagator{ noop: propagation.NewCompositeTextMapPropagator(), } } func (p *textMapPropagator) SetDelegate(delegate propagation.TextMapPropagator) { if delegate == nil { return } p.mtx.Lock() p.once.Do(func() { p.delegate = delegate }) p.mtx.Unlock() } func (p *textMapPropagator) effectiveDelegate() propagation.TextMapPropagator { p.mtx.Lock() defer p.mtx.Unlock() if p.delegate != nil { return p.delegate } return p.noop } func (p *textMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) { p.effectiveDelegate().Inject(ctx, carrier) } func (p *textMapPropagator) Fields() []string { return p.effectiveDelegate().Fields() } func (p *textMapPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context
{ return p.effectiveDelegate().Extract(ctx, carrier) }
package main import ( "net" "strconv" ) import ( "cfg" . "helper" "misc/packet" . "types" ) type Buffer struct { ctrl chan bool pending chan []byte max int conn net.Conn sess *Session } func (buf *Buffer) Send(data []byte) (err error) { defer func() { if x := recover(); x != nil { WARN("buffer.Send failed", x) } }() if buf.sess.Flag&SESS_ENCRYPT != 0 { buf.sess.Encoder.Codec(data) } else if buf.sess.Flag&SESS_KEYEXCG != 0 { buf.sess.Flag &= ^SESS_KEYEXCG buf.sess.Flag |= SESS_ENCRYPT } buf.pending <- data return nil } func (buf *Buffer) raw_send(data []byte) { writer := packet.Writer() writer.WriteU16(uint16(len(data))) writer.WriteRawBytes(data) n, err := buf.conn.Write(writer.Data()) if err != nil { ERR("Error send reply, bytes:", n, "reason:", err) return } } func NewBuffer(sess *Session, conn net.Conn, ctrl chan bool) *Buffer { config := cfg.Get() max, err := strconv.Atoi(config["outqueue_size"]) if err != nil { max = DEFAULT_OUTQUEUE_SIZE WARN("cannot parse outqueue_size from config", err, "using default:", max) } buf := Buffer{conn: conn} buf.sess = sess buf.pending = make(chan []byte, max) buf.ctrl = ctrl buf.max = max return &buf } func (buf *Buffer) Start()
{ defer func() { if x := recover(); x != nil { ERR("caught panic in buffer goroutine", x) } }() for { select { case data := <-buf.pending: buf.raw_send(data) case <-buf.ctrl: close(buf.pending) for data := range buf.pending { buf.raw_send(data) } buf.conn.Close() return } } }
package dexcom import ( "math" ) func marshalInt16(n int16) []byte { return marshalUint16(uint16(n)) } func marshalUint32(n uint32) []byte { return append(marshalUint16(uint16(n&0xFFFF)), marshalUint16(uint16(n>>16))...) } func marshalInt32(n int32) []byte { return marshalUint32(uint32(n)) } func unmarshalUint16(v []byte) uint16 { return uint16(v[0]) | uint16(v[1])<<8 } func unmarshalInt16(v []byte) int16 { return int16(unmarshalUint16(v)) } func unmarshalUint32(v []byte) uint32 { return uint32(unmarshalUint16(v[0:2])) | uint32(unmarshalUint16(v[2:4]))<<16 } func unmarshalInt32(v []byte) int32 { return int32(unmarshalUint32(v)) } func unmarshalUint64(v []byte) uint64 { return uint64(unmarshalUint32(v[0:4])) | uint64(unmarshalUint32(v[4:8]))<<32 } func unmarshalFloat64(v []byte) float64 { return math.Float64frombits(unmarshalUint64(v)) } func marshalUint16(n uint16) []byte
{ return []byte{byte(n & 0xFF), byte(n >> 8)} }
package fenwick import "testing" func TestNewFenwickTree(t *testing.T)
{ f := []int{2,4,5,5,6,6,6,7,7,8,9} fw := NewFenwickTree(10) for i := 0; i < 11; i++ { fw.adjust(f[i],1) } if fw.rsq(1,1) != 0 { t.Errorf("expect 0") } if fw.rsq(1,2) != 1 { t.Errorf("expect 1") } if fw.rsq(1,10) != 11 { t.Errorf("expect 11") } if fw.rsq(3,6) != 6 { t.Errorf("expect 6") } }
package utils import ( "github.com/scionproto/scion/go/lib/ctrl/seg" "github.com/scionproto/scion/go/lib/scrypto/signed" "github.com/scionproto/scion/go/lib/serrors" ) func ExtractLastHopVersion(ps *seg.PathSegment) (int64, error)
{ ases := ps.ASEntries if len(ases) == 0 { return 0, serrors.New("segment without AS Entries") } sign := ases[len(ases)-1].Signed hdr, err := signed.ExtractUnverifiedHeader(sign) if err != nil { return 0, err } return hdr.Timestamp.UnixNano(), nil }
package strings import ( "strings" ) func RemoveSpace(s string) (d string) { if IsBlank(s) { return } d = s sps := [...]string{"\t", "\n", "\v", "\f", "\r", " "} for _, sp := range sps { d = strings.Replace(d, sp, "", -1) } return } func RemoveBlank(s string) (d string) { if IsBlank(s) { return } d = strings.TrimSpace(s) sps := [...]string{"\t", "\n", "\v", "\f", "\r", " "} for _, sp := range sps { d = strings.Replace(d, sp, "", -1) } return } func RemoveEnd(s, remove string) string { if IsBlank(s) || IsBlank(remove) { return s } if strings.HasSuffix(s, remove) { return s[0 : len(s)-len(remove)] } return s } func Remove(s, remove string) string { if IsBlank(s) || IsBlank(remove) { return s } return strings.Replace(s, remove, "", -1) } func RemoveStart(s, remove string) string
{ if IsBlank(s) || IsBlank(remove) { return s } if strings.HasPrefix(s, remove) { return s[len(remove):] } return s }
package db_models import "time" import "github.com/go-xorm/xorm" type UriFilteringTelemetryPreMitigation struct { Id int64 `xorm:"'id' pk autoincr"` CustomerId int `xorm:"'customer_id' not null"` Cuid string `xorm:"'cuid' not null"` Cdid string `xorm:"'cdid'"` Tmid int `xorm:"'tmid' not null"` TargetPrefix string `xorm:"target_prefix"` LowerPort int `xorm:"lower_port"` UpperPort int `xorm:"upper_port"` TargetProtocol int `xorm:"target_protocol"` TargetFqdn string `xorm:"target_fqdn"` AliasName string `xorm:"alias_name"` Created time.Time `xorm:"created"` Updated time.Time `xorm:"updated"` } func GetUriFilteringTelemetryPreMitigationByCuid(engine *xorm.Engine, customerId int, cuid string) ([]UriFilteringTelemetryPreMitigation, error) { telePreMitigation := []UriFilteringTelemetryPreMitigation{} err := engine.Where("customer_id = ? AND cuid = ?", customerId, cuid).Find(&telePreMitigation) return telePreMitigation, err } func DeleteUriFilteringTelemetryPreMitigationByTmid(session *xorm.Session, tmid int) (err error) { _, err = session.Delete(&UriFilteringTelemetryPreMitigation{Tmid: tmid}) return } func GetUriFilteringTelemetryPreMitigationByTmid(engine *xorm.Engine, customerId int, cuid string, tmid int) ([]UriFilteringTelemetryPreMitigation, error)
{ telePreMitigation := []UriFilteringTelemetryPreMitigation{} err := engine.Where("customer_id = ? AND cuid = ? AND tmid = ?", customerId, cuid, tmid).Find(&telePreMitigation) return telePreMitigation, err }
package upside_down import ( "bytes" "fmt" "github.com/blevesearch/bleve/index" "github.com/blevesearch/bleve/index/store" ) type UpsideDownCouchFieldDict struct { indexReader *IndexReader iterator store.KVIterator endKey []byte field uint16 } func newUpsideDownCouchFieldDict(indexReader *IndexReader, field uint16, startTerm, endTerm []byte) (*UpsideDownCouchFieldDict, error) { startKey := NewDictionaryRow(startTerm, field, 0).Key() if endTerm == nil { endTerm = []byte{ByteSeparator} } endKey := NewDictionaryRow(endTerm, field, 0).Key() it := indexReader.kvreader.Iterator(startKey) return &UpsideDownCouchFieldDict{ indexReader: indexReader, iterator: it, field: field, endKey: endKey, }, nil } func (r *UpsideDownCouchFieldDict) Next() (*index.DictEntry, error) { key, val, valid := r.iterator.Current() if !valid { return nil, nil } if bytes.Compare(key, r.endKey) > 0 { return nil, nil } currRow, err := NewDictionaryRowKV(key, val) if err != nil { return nil, fmt.Errorf("unexpected error parsing dictionary row kv: %v", err) } rv := index.DictEntry{ Term: string(currRow.term), Count: currRow.count, } r.iterator.Next() return &rv, nil } func (r *UpsideDownCouchFieldDict) Close() error { return r.iterator.Close() } func incrementBytes(in []byte) []byte
{ rv := make([]byte, len(in)) copy(rv, in) for i := len(rv) - 1; i >= 0; i-- { rv[i] = rv[i] + 1 if rv[i] != 0 { break } } return rv }
package tc import ( "encoding/json" ) type CRStates struct { Caches map[CacheName]IsAvailable `json:"caches"` DeliveryService map[DeliveryServiceName]CRStatesDeliveryService `json:"deliveryServices"` } type CRStatesDeliveryService struct { DisabledLocations []CacheGroupName `json:"disabledLocations"` IsAvailable bool `json:"isAvailable"` } type IsAvailable struct { IsAvailable bool `json:"isAvailable"` } func NewCRStates() CRStates { return CRStates{ Caches: map[CacheName]IsAvailable{}, DeliveryService: map[DeliveryServiceName]CRStatesDeliveryService{}, } } func (a CRStates) CopyDeliveryServices() map[DeliveryServiceName]CRStatesDeliveryService { b := map[DeliveryServiceName]CRStatesDeliveryService{} for k, v := range a.DeliveryService { b[k] = v } return b } func (a CRStates) CopyCaches() map[CacheName]IsAvailable { b := map[CacheName]IsAvailable{} for k, v := range a.Caches { b[k] = v } return b } func CRStatesMarshall(states CRStates) ([]byte, error) { return json.Marshal(states) } func CRStatesUnMarshall(body []byte) (CRStates, error) { var crStates CRStates err := json.Unmarshal(body, &crStates) return crStates, err } func (a CRStates) Copy() CRStates
{ b := NewCRStates() for k, v := range a.Caches { b.Caches[k] = v } for k, v := range a.DeliveryService { b.DeliveryService[k] = v } return b }
package outbarriers import ( "log" "time" ) type User struct { Id int64 Email string Password string } type Session struct { Id int64 UserId int64 Token string `sql:"unique; not null"` CreatedAt time.Time } func (ctx *Context) AuthUser(email, password string) *User { var user User ctx.DB.Where("email = ? and password = ?", email, password).First(&user) return &user } func (ctx *Context) CheckAdmin() { var user User ctx.DB.Where(User{Email: ADMIN_EMAIL, Password: ADMIN_PASSWORD}).FirstOrInit(&user) if ctx.DB.NewRecord(user) { log.Printf("Admin user not exists, creating...") ctx.DB.Create(&user) } } func (ctx *Context) GetSessionByToken(token string) *Session { var session Session ctx.DB.Where("token = ?", token).First(&session) if session.Id == 0 { return nil } return &session } func (ctx *Context) LoginUser(user *User) string
{ token := RandomString(64) session := &Session{UserId: user.Id, Token: token, CreatedAt: time.Now()} ctx.DB.Create(session) return token }
package utils import "time" func GetUnixEpochFrom(now time.Time) int64 { return now.UnixNano() } func GetUnixEpoch() int64
{ return GetUnixEpochFrom(time.Now()) }
package config import ( cb "github.com/hyperledger/fabric/protos/common" ab "github.com/hyperledger/fabric/protos/orderer" "github.com/hyperledger/fabric/protos/utils" ) func ordererConfigGroup(key string, value []byte) *cb.ConfigGroup { result := cb.NewConfigGroup() result.Groups[OrdererGroupKey] = cb.NewConfigGroup() result.Groups[OrdererGroupKey].Values[key] = &cb.ConfigValue{ Value: value, } return result } func TemplateConsensusType(typeValue string) *cb.ConfigGroup { return ordererConfigGroup(ConsensusTypeKey, utils.MarshalOrPanic(&ab.ConsensusType{Type: typeValue})) } func TemplateBatchSize(batchSize *ab.BatchSize) *cb.ConfigGroup { return ordererConfigGroup(BatchSizeKey, utils.MarshalOrPanic(batchSize)) } func TemplateBatchTimeout(batchTimeout string) *cb.ConfigGroup { return ordererConfigGroup(BatchTimeoutKey, utils.MarshalOrPanic(&ab.BatchTimeout{Timeout: batchTimeout})) } func TemplateKafkaBrokers(brokers []string) *cb.ConfigGroup { return ordererConfigGroup(KafkaBrokersKey, utils.MarshalOrPanic(&ab.KafkaBrokers{Brokers: brokers})) } func TemplateChannelRestrictions(maxChannels uint64) *cb.ConfigGroup
{ return ordererConfigGroup(ChannelRestrictionsKey, utils.MarshalOrPanic(&ab.ChannelRestrictions{MaxCount: maxChannels})) }
package virtcontainers type mockAddr struct { network string ipAddr string } func (m mockAddr) Network() string { return m.network } func (m mockAddr) String() string
{ return m.ipAddr }
package seccomp import ( seccomp_compiler "github.com/snapcore/snapd/sandbox/seccomp" ) func MockKernelFeatures(f func() []string) (resture func()) { old := kernelFeatures kernelFeatures = f return func() { kernelFeatures = old } } func MockRequiresSocketcall(f func(string) bool) (restore func()) { old := requiresSocketcall requiresSocketcall = f return func() { requiresSocketcall = old } } func MockDpkgKernelArchitecture(f func() string) (restore func()) { old := dpkgKernelArchitecture dpkgKernelArchitecture = f return func() { dpkgKernelArchitecture = old } } func MockReleaseInfoId(s string) (restore func()) { old := releaseInfoId releaseInfoId = s return func() { releaseInfoId = old } } func MockReleaseInfoVersionId(s string) (restore func()) { old := releaseInfoVersionId releaseInfoVersionId = s return func() { releaseInfoVersionId = old } } func MockSeccompCompilerLookup(f func(string) (string, error)) (restore func()) { old := seccompCompilerLookup seccompCompilerLookup = f return func() { seccompCompilerLookup = old } } func (b *Backend) VersionInfo() seccomp_compiler.VersionInfo { return b.versionInfo } var ( RequiresSocketcall = requiresSocketcall GlobalProfileLE = globalProfileLE GlobalProfileBE = globalProfileBE IsBigEndian = isBigEndian ) func MockTemplate(fakeTemplate []byte) (restore func())
{ orig := defaultTemplate origBarePrivDropSyscalls := barePrivDropSyscalls defaultTemplate = fakeTemplate barePrivDropSyscalls = "" return func() { defaultTemplate = orig barePrivDropSyscalls = origBarePrivDropSyscalls } }
package context import ( "os" "path/filepath" jujuos "github.com/juju/utils/os" ) func OSDependentEnvVars(paths Paths) []string { switch jujuos.HostOS() { case jujuos.Windows: return windowsEnv(paths) case jujuos.Ubuntu: return ubuntuEnv(paths) case jujuos.CentOS: return centosEnv(paths) } return nil } func appendPath(paths Paths) []string { return []string{ "PATH=" + paths.GetToolsDir() + ":" + os.Getenv("PATH"), } } func centosEnv(paths Paths) []string { return appendPath(paths) } func windowsEnv(paths Paths) []string { charmDir := paths.GetCharmDir() charmModules := filepath.Join(charmDir, "lib", "Modules") return []string{ "Path=" + paths.GetToolsDir() + ";" + os.Getenv("Path"), "PSModulePath=" + os.Getenv("PSModulePath") + ";" + charmModules, } } func ubuntuEnv(paths Paths) []string
{ path := appendPath(paths) env := []string{ "APT_LISTCHANGES_FRONTEND=none", "DEBIAN_FRONTEND=noninteractive", } env = append(env, path...) return env }
package i3ipc import ( "encoding/json" ) type I3Node struct { ID int64 Name string Type string Border string CurrentBorderWidth int32 `json:"current_border_width"` Layout string Orientation string Percent float64 Rect Rect WindowRect Rect DecoRect Rect `json:"deco_rect"` Geometry Rect Window int32 Urgent bool Focused bool Floating_Nodes []I3Node Nodes []I3Node Parent *I3Node Window_Properties struct { Title string Instance string Class string } Sticky bool Floating string Last_Split_Layout string Fullscreen_Mode int32 Scratchpad_State string Workspace_Layout string } func setParent(node, parent *I3Node) { node.Parent = parent for i := range node.Nodes { setParent(&node.Nodes[i], node) } for i := range node.Floating_Nodes { setParent(&node.Floating_Nodes[i], node) } } func (socket *IPCSocket) GetTree() (root I3Node, err error)
{ jsonReply, err := socket.Raw(I3GetTree, "") if err != nil { return } defer setParent(&root, nil) err = json.Unmarshal(jsonReply, &root) if err == nil { return } if _, ok := err.(*json.UnmarshalTypeError); ok { err = nil } return }
package turtle import ( "strings" ) type DataSet struct { triplecount int nscount int Namespaces map[string]string Triples []Triple } func newDataSet() *DataSet { return &DataSet{ triplecount: 0, nscount: 0, Namespaces: make(map[string]string), Triples: []Triple{}, } } func (d *DataSet) AddTripleStrings(subject, predicate, object string) { d.triplecount += 1 d.Triples = append(d.Triples, MakeTriple(subject, predicate, object)) } func (d *DataSet) AddTripleURIs(subject, predicate, object URI) { d.triplecount += 1 d.Triples = append(d.Triples, Triple{subject, predicate, object}) } func (d *DataSet) addNamespace(prefix, namespace string) { d.nscount += 1 namespace = strings.TrimRight(namespace, "#") d.Namespaces[prefix] = namespace } func (d *DataSet) NumNamespaces() int { return d.nscount } func (d *DataSet) NumTriples() int
{ return d.triplecount }
package utilmocks import ( context "context" gomock "github.com/golang/mock/gomock" exec "os/exec" reflect "reflect" ) type MockCommandRunner struct { ctrl *gomock.Controller recorder *MockCommandRunnerMockRecorder } type MockCommandRunnerMockRecorder struct { mock *MockCommandRunner } func NewMockCommandRunner(ctrl *gomock.Controller) *MockCommandRunner { mock := &MockCommandRunner{ctrl: ctrl} mock.recorder = &MockCommandRunnerMockRecorder{mock} return mock } func (m *MockCommandRunner) EXPECT() *MockCommandRunnerMockRecorder { return m.recorder } func (mr *MockCommandRunnerMockRecorder) Run(ctx, command interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Run", reflect.TypeOf((*MockCommandRunner)(nil).Run), ctx, command) } func (m *MockCommandRunner) Run(ctx context.Context, command *exec.Cmd) ([]byte, []byte, error)
{ m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Run", ctx, command) ret0, _ := ret[0].([]byte) ret1, _ := ret[1].([]byte) ret2, _ := ret[2].(error) return ret0, ret1, ret2 }
package testclient import ( kapi "k8s.io/kubernetes/pkg/api" ktestclient "k8s.io/kubernetes/pkg/client/unversioned/testclient" "github.com/openshift/origin/pkg/client" imageapi "github.com/openshift/origin/pkg/image/api" ) type FakeImages struct { Fake *Fake } var _ client.ImageInterface = &FakeImages{} func (c *FakeImages) Get(name string) (*imageapi.Image, error) { obj, err := c.Fake.Invokes(ktestclient.NewRootGetAction("images", name), &imageapi.Image{}) if obj == nil { return nil, err } return obj.(*imageapi.Image), err } func (c *FakeImages) List(opts kapi.ListOptions) (*imageapi.ImageList, error) { obj, err := c.Fake.Invokes(ktestclient.NewRootListAction("images", opts), &imageapi.ImageList{}) if obj == nil { return nil, err } return obj.(*imageapi.ImageList), err } func (c *FakeImages) Create(inObj *imageapi.Image) (*imageapi.Image, error) { obj, err := c.Fake.Invokes(ktestclient.NewRootCreateAction("images", inObj), inObj) if obj == nil { return nil, err } return obj.(*imageapi.Image), err } func (c *FakeImages) Delete(name string) error
{ _, err := c.Fake.Invokes(ktestclient.NewRootDeleteAction("images", name), &imageapi.Image{}) return err }
package chipmunk import ( "github.com/Dethrail/chipmunk/transform" "github.com/Dethrail/chipmunk/vect" "math" ) const ( RadianConst = math.Pi / 180 DegreeConst = 180 / math.Pi ) type Group int type Layer int type Shape struct { DefaultHash ShapeClass Body *Body BB AABB IsSensor bool e vect.Float u vect.Float Surface_v vect.Vect UserData interface{} Group Group Layer Layer space *Space velocityIndexed bool } func newShape() *Shape { return &Shape{velocityIndexed: true, e: 0.5, u: 0.5, Layer: -1} } func (shape *Shape) Velocity() (vect.Vect, bool) { return shape.Body.v, shape.velocityIndexed } func (shape *Shape) SetFriction(friction vect.Float) { shape.u = friction } func (shape *Shape) SetElasticity(e vect.Float) { shape.e = e } func (shape *Shape) Shape() *Shape { return shape } func (shape *Shape) AABB() AABB { return shape.BB } func (shape *Shape) Clone() *Shape { clone := *shape cc := &clone cc.space = nil cc.DefaultHash.Reset() cc.Body = nil cc.ShapeClass = cc.ShapeClass.Clone(cc) return cc } func (shape *Shape) Update()
{ shape.BB = shape.ShapeClass.update(transform.NewTransform(shape.Body.p, shape.Body.a)) }
package protocol import ( "io" "sync/atomic" ) type countingReader struct { io.Reader tot uint64 } var ( totalIncoming uint64 totalOutgoing uint64 ) func (c *countingReader) Tot() uint64 { return atomic.LoadUint64(&c.tot) } type countingWriter struct { io.Writer tot uint64 } func (c *countingWriter) Write(bs []byte) (int, error) { n, err := c.Writer.Write(bs) atomic.AddUint64(&c.tot, uint64(n)) atomic.AddUint64(&totalOutgoing, uint64(n)) return n, err } func (c *countingWriter) Tot() uint64 { return atomic.LoadUint64(&c.tot) } func TotalInOut() (uint64, uint64) { return atomic.LoadUint64(&totalIncoming), atomic.LoadUint64(&totalOutgoing) } func (c *countingReader) Read(bs []byte) (int, error)
{ n, err := c.Reader.Read(bs) atomic.AddUint64(&c.tot, uint64(n)) atomic.AddUint64(&totalIncoming, uint64(n)) return n, err }
package datastore import ( "testing" "github.com/hellodudu/Ultimate/iface" "github.com/hellodudu/Ultimate/utils/global" ) var ds iface.IDatastore func TestNewDatastore(t *testing.T) { var err error ds, err = NewDatastore() if err != nil { t.Error("NewDatastore error:", err) } } func TestTableGlobal(t *testing.T) { tbl := ds.TableGlobal() if tbl == nil { t.Error("Init table global error") } if tbl.Id != 110 { t.Error("Init table global ultimate_id error") } } func init()
{ global.Debugging = false global.MysqlUser = "root" global.MysqlPwd = "" global.MysqlAddr = "127.0.0.1" global.MysqlPort = "3306" global.MysqlDB = "db_ultimate" global.UltimateID = 110 }
package queue type LazyQueue struct { qChan chan interface{} DequeueMethod DequeueMethod } type DequeueMethod func(interface{}) func NewLazyQueue(qsize int, dequeueMethod DequeueMethod, grcount int) *LazyQueue { qInstance := &LazyQueue{} qInstance.qChan = make(chan interface{}, qsize) qInstance.DequeueMethod = dequeueMethod if grcount <= 0 { grcount = 1 } for i := 0; i < grcount; i++ { go qInstance.startDequeue() } return qInstance } func (lq *LazyQueue) Enqueue(qinfo interface{}) { lq.qChan <- qinfo } func (lq *LazyQueue) startDequeue()
{ for { select { case bm := <-lq.qChan: lq.DequeueMethod(bm) } } }
package archive import ( "syscall" "time" ) func timeToTimespec(time time.Time) (ts syscall.Timespec)
{ if time.IsZero() { ts.Sec = 0 ts.Nsec = ((1 << 30) - 2) return } return syscall.NsecToTimespec(time.UnixNano()) }
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) ErrorName() string { return "OutOfMemoryError" } 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) Error() string
{ return "Container killed due to memory usage" }
package unitassigner import ( "github.com/juju/errors" "github.com/juju/worker/v2" "github.com/juju/worker/v2/dependency" "github.com/juju/juju/api/base" "github.com/juju/juju/api/unitassigner" "github.com/juju/juju/cmd/jujud/agent/engine" ) type Logger interface { Tracef(string, ...interface{}) } type ManifoldConfig struct { APICallerName string Logger Logger } func (c *ManifoldConfig) start(apiCaller base.APICaller) (worker.Worker, error) { facade := unitassigner.New(apiCaller) worker, err := New(facade, c.Logger) if err != nil { return nil, errors.Trace(err) } return worker, nil } func Manifold(config ManifoldConfig) dependency.Manifold
{ return engine.APIManifold( engine.APIManifoldConfig{ APICallerName: config.APICallerName, }, config.start, ) }
package blanket_emulator import ( "fmt" ) type Event interface { Hash() uint64 Inspect() string } type ReturnEvent uint64 type ReadEvent uint64 type WriteEvent struct { Addr uint64 Value uint64 } type SyscallEvent uint64 type InvalidInstructionEvent uint64 func (addr ReadEvent) Hash() uint64 { return ReadEventHash(uint64(addr)) } func (s WriteEvent) Hash() uint64 { return WriteEventHash(s.Addr, s.Value) } func (s SyscallEvent) Hash() uint64 { return SysEventHash(uint64(s)) } func (s ReturnEvent) Hash() uint64 { return ReturnEventHash(uint64(s)) } func (s InvalidInstructionEvent) Hash() uint64 { return InvalidInstructionEventHash(uint64(s)) } func (addr ReadEvent) Inspect() string { return fmt.Sprintf("Read([%x])", addr) } func (addr ReturnEvent) Inspect() string { return fmt.Sprintf("Return([%x])", addr) } func (s SyscallEvent) Inspect() string { return fmt.Sprintf("Sys(%x)", s) } func (s InvalidInstructionEvent) Inspect() string { return fmt.Sprintf("InvalidOpcode([%x])", s) } func (s WriteEvent) Inspect() string
{ return fmt.Sprintf("Write([%x]=%x)", s.Addr, s.Value) }
package global import ( "context" "sync" "go.opentelemetry.io/otel/propagation" ) type textMapPropagator struct { mtx sync.Mutex once sync.Once delegate propagation.TextMapPropagator noop propagation.TextMapPropagator } var _ propagation.TextMapPropagator = (*textMapPropagator)(nil) func newTextMapPropagator() *textMapPropagator { return &textMapPropagator{ noop: propagation.NewCompositeTextMapPropagator(), } } func (p *textMapPropagator) SetDelegate(delegate propagation.TextMapPropagator) { if delegate == nil { return } p.mtx.Lock() p.once.Do(func() { p.delegate = delegate }) p.mtx.Unlock() } func (p *textMapPropagator) effectiveDelegate() propagation.TextMapPropagator { p.mtx.Lock() defer p.mtx.Unlock() if p.delegate != nil { return p.delegate } return p.noop } func (p *textMapPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context { return p.effectiveDelegate().Extract(ctx, carrier) } func (p *textMapPropagator) Fields() []string { return p.effectiveDelegate().Fields() } func (p *textMapPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier)
{ p.effectiveDelegate().Inject(ctx, carrier) }
package main import ( "fmt" "os" "os/exec" "github.com/rjeczalik/which" ) const usage = `NAME: gowhich - shows the import path of Go executables USAGE: gowhich name|path EXAMPLES: gowhich godoc gowhich ~/bin/godoc` func ishelp(s string) bool { return s == "-h" || s == "-help" || s == "help" || s == "--help" || s == "/?" } func main() { if len(os.Args) != 2 { die(usage) } if ishelp(os.Args[1]) { fmt.Println(usage) return } path, err := exec.LookPath(os.Args[1]) if err != nil { die(err) } pkg, err := which.Import(path) if err != nil { die(err) } fmt.Println(pkg) } func die(v interface{})
{ fmt.Fprintln(os.Stderr, v) os.Exit(1) }
package influxdb import ( "io" "io/ioutil" "net/http" "testing" "time" "go.k6.io/k6/stats" ) func benchmarkInfluxdb(b *testing.B, t time.Duration) { testOutputCycle(b, func(rw http.ResponseWriter, r *http.Request) { for { time.Sleep(t) m, _ := io.CopyN(ioutil.Discard, r.Body, 1<<18) if m == 0 { break } } rw.WriteHeader(204) }, func(tb testing.TB, c *Output) { b = tb.(*testing.B) b.ResetTimer() samples := make(stats.Samples, 10) for i := 0; i < len(samples); i++ { samples[i] = stats.Sample{ Metric: stats.New("testGauge", stats.Gauge), Time: time.Now(), Tags: stats.NewSampleTags(map[string]string{ "something": "else", "VU": "21", "else": "something", }), Value: 2.0, } } b.ResetTimer() for i := 0; i < b.N; i++ { c.AddMetricSamples([]stats.SampleContainer{samples}) time.Sleep(time.Nanosecond * 20) } }) } func BenchmarkInfluxdb1Second(b *testing.B) { benchmarkInfluxdb(b, time.Second) } func BenchmarkInfluxdb100Milliseconds(b *testing.B) { benchmarkInfluxdb(b, 100*time.Millisecond) } func BenchmarkInfluxdb2Second(b *testing.B)
{ benchmarkInfluxdb(b, 2*time.Second) }
package daemon import ( "log" "time" "github.com/Cloakaac/cloak/models" ) type RecordDaemon struct{} func (r *RecordDaemon) tick()
{ total := models.GetOnlineCount() err := models.AddOnlineRecord(total, time.Now().Unix()) if err != nil { log.Fatal(err) } }
package remotecache import ( "context" "time" "github.com/bradfitz/gomemcache/memcache" "github.com/grafana/grafana/pkg/setting" ) const memcachedCacheType = "memcached" type memcachedStorage struct { c *memcache.Client } func newMemcachedStorage(opts *setting.RemoteCacheOptions) *memcachedStorage { return &memcachedStorage{ c: memcache.New(opts.ConnStr), } } func (s *memcachedStorage) Set(ctx context.Context, key string, val interface{}, expires time.Duration) error { item := &cachedItem{Val: val} bytes, err := encodeGob(item) if err != nil { return err } var expiresInSeconds int64 if expires != 0 { expiresInSeconds = int64(expires) / int64(time.Second) } memcachedItem := newItem(key, bytes, int32(expiresInSeconds)) return s.c.Set(memcachedItem) } func (s *memcachedStorage) Get(ctx context.Context, key string) (interface{}, error) { memcachedItem, err := s.c.Get(key) if err != nil && err.Error() == "memcache: cache miss" { return nil, ErrCacheItemNotFound } if err != nil { return nil, err } item := &cachedItem{} err = decodeGob(memcachedItem.Value, item) if err != nil { return nil, err } return item.Val, nil } func (s *memcachedStorage) Delete(ctx context.Context, key string) error { return s.c.Delete(key) } func newItem(sid string, data []byte, expire int32) *memcache.Item
{ return &memcache.Item{ Key: sid, Value: data, Expiration: expire, } }
package cmac import ( "log" "unsafe" ) func xorBlock( dstPtr unsafe.Pointer, aPtr unsafe.Pointer, bPtr unsafe.Pointer)
{ const wordSize = unsafe.Sizeof(uintptr(0)) if blockSize != 2*wordSize { log.Panicf("%d %d", blockSize, wordSize) } a := (*[2]uintptr)(aPtr) b := (*[2]uintptr)(bPtr) dst := (*[2]uintptr)(dstPtr) dst[0] = a[0] ^ b[0] dst[1] = a[1] ^ b[1] }
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) ReadChan() chan []byte { return d.readChan } func (d *DummyBackendQueue) Close() error { return nil } func (d *DummyBackendQueue) Delete() error { return nil } 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) Depth() int64
{ return int64(0) }
package iso20022 type AcquirerProtocolParameters5 struct { FinancialCapture *FinancialCapture1Code `xml:"FinCaptr"` BatchTransfer *ExchangeConfiguration4 `xml:"BtchTrf,omitempty"` CompletionExchange *ExchangeConfiguration5 `xml:"CmpltnXchg,omitempty"` CancellationExchange *CancellationProcess1Code `xml:"CxlXchg,omitempty"` } func (a *AcquirerProtocolParameters5) SetFinancialCapture(value string) { a.FinancialCapture = (*FinancialCapture1Code)(&value) } func (a *AcquirerProtocolParameters5) AddBatchTransfer() *ExchangeConfiguration4 { a.BatchTransfer = new(ExchangeConfiguration4) return a.BatchTransfer } func (a *AcquirerProtocolParameters5) SetCancellationExchange(value string) { a.CancellationExchange = (*CancellationProcess1Code)(&value) } func (a *AcquirerProtocolParameters5) AddCompletionExchange() *ExchangeConfiguration5
{ a.CompletionExchange = new(ExchangeConfiguration5) return a.CompletionExchange }
package backingstore import ( "github.com/gostor/gotgt/pkg/api" "github.com/gostor/gotgt/pkg/scsi" ) func init() { scsi.RegisterBackingStore("null", newNull) } type NullBackingStore struct { scsi.BaseBackingStore } func newNull() (api.BackingStore, error) { return &NullBackingStore{ BaseBackingStore: scsi.BaseBackingStore{ Name: "null", DataSize: 0, OflagsSupported: 0, }, }, nil } func (bs *NullBackingStore) Open(dev *api.SCSILu, path string) error { return nil } func (bs *NullBackingStore) Close(dev *api.SCSILu) error { return nil } func (bs *NullBackingStore) Init(dev *api.SCSILu, Opts string) error { return nil } func (bs *NullBackingStore) Exit(dev *api.SCSILu) error { return nil } func (bs *NullBackingStore) Read(offset, tl int64) ([]byte, error) { return nil, nil } func (bs *NullBackingStore) Write(wbuf []byte, offset int64) error { return nil } func (bs *NullBackingStore) DataSync(offset, tl int64) error { return nil } func (bs *NullBackingStore) DataAdvise(offset, length int64, advise uint32) error { return nil } func (bs *NullBackingStore) Unmap([]api.UnmapBlockDescriptor) error { return nil } func (bs *NullBackingStore) Size(dev *api.SCSILu) uint64
{ return 0 }
package query import ( "encoding/json" "reflect" ) func wrapper(name string, v interface{}) map[string]interface{} { query := map[string]interface{}{ name: v, } return query } func convert(value reflect.Value) interface{} { switch value.Kind() { case reflect.Slice: var res []interface{} for i := 0; i < value.Len(); i++ { res = append(res, convert(value.Index(i))) } return res case reflect.Ptr: if !value.IsNil() { return convert(value.Elem()) } case reflect.String: return value.String() case reflect.Float64: return value.Float() case reflect.Int: return value.Int() case reflect.Bool: return value.Bool() } return value.Interface() } func convertable(value reflect.Value) bool { switch value.Kind() { case reflect.Slice: return value.Len() > 0 case reflect.Ptr: return !value.IsNil() } return true } func convertStruct(x interface{}) interface{} { query := make(map[string]interface{}) t := reflect.ValueOf(x).Type() v := reflect.ValueOf(x) for i := 0; i < t.NumField(); i++ { field := t.Field(i) value := v.FieldByName(field.Name) tag := field.Tag.Get("json") if tag == "-" { continue } if convertable(value) { query[tag] = convert(value) } } return query } func toJson(v interface{}) ([]byte, error)
{ return json.Marshal(v) }
package armpeering_test import ( "context" "log" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/peering/armpeering" ) func ExampleLegacyPeeringsClient_List()
{ cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } ctx := context.Background() client := armpeering.NewLegacyPeeringsClient("<subscription-id>", cred, nil) pager := client.List("<peering-location>", armpeering.LegacyPeeringsKind("Exchange"), &armpeering.LegacyPeeringsClientListOptions{Asn: 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 jmespath import "strconv" type JMESPath struct { ast ASTNode intr *treeInterpreter } func Compile(expression string) (*JMESPath, error) { parser := NewParser() ast, err := parser.Parse(expression) if err != nil { return nil, err } jmespath := &JMESPath{ast: ast, intr: newInterpreter()} return jmespath, nil } func MustCompile(expression string) *JMESPath { jmespath, err := Compile(expression) if err != nil { panic(`jmespath: Compile(` + strconv.Quote(expression) + `): ` + err.Error()) } return jmespath } func Search(expression string, data interface{}) (interface{}, error) { intr := newInterpreter() parser := NewParser() ast, err := parser.Parse(expression) if err != nil { return nil, err } return intr.Execute(ast, data) } func (jp *JMESPath) Search(data interface{}) (interface{}, error)
{ return jp.intr.Execute(jp.ast, data) }
package main import ( "go/build" "io/ioutil" "os" "path/filepath" "strings" "github.com/posener/complete" ) func predictPackages(a complete.Args) (prediction []string) { prediction = []string{a.Last} lastPrediction := "" for len(prediction) == 1 && (lastPrediction == "" || lastPrediction != prediction[0]) { lastPrediction = prediction[0] a.Last = prediction[0] prediction = predictLocalAndSystem(a) } return } func predictLocalAndSystem(a complete.Args) []string { localDirs := complete.PredictFilesSet(listPackages(a.Directory())).Predict(a) s := systemDirs(a.Last) sysDirs := complete.PredictSet(s...).Predict(a) return append(localDirs, sysDirs...) } func listPackages(dir string) (directories []string) { files, err := ioutil.ReadDir(dir) if err != nil { complete.Log("failed reading directory %s: %s", dir, err) return } paths := make([]string, 0, len(files)+1) for _, f := range files { if f.IsDir() { paths = append(paths, filepath.Join(dir, f.Name())) } } paths = append(paths, dir) for _, p := range paths { pkg, err := build.ImportDir(p, 0) if err != nil { complete.Log("failed importing directory %s: %s", p, err) continue } directories = append(directories, pkg.Dir) } return } func systemDirs(dir string) (directories []string)
{ paths := strings.Split(os.Getenv("GOPATH"), ":") for i := range paths { paths[i] = filepath.Join(paths[i], "src") } if !strings.HasSuffix(dir, "/") { dir = filepath.Dir(dir) } for _, basePath := range paths { path := filepath.Join(basePath, dir) files, err := ioutil.ReadDir(path) if err != nil { continue } switch dir { case "", ".", "/", "./": default: directories = append(directories, dir) } for _, f := range files { if !f.IsDir() { continue } directories = append(directories, filepath.Join(dir, f.Name())+"/") } } return }
package serverrpc import ( "github.com/hyperhq/hyperd/types" "golang.org/x/net/context" ) func (s *ServerRPC) TTYResize(c context.Context, req *types.TTYResizeRequest) (*types.TTYResizeResponse, error)
{ err := s.daemon.TtyResize(req.ContainerID, req.ExecID, int(req.Height), int(req.Width)) if err != nil { return nil, err } return &types.TTYResizeResponse{}, nil }
package tests import ( log "github.com/janekolszak/revfluent" "github.com/revel/revel/testing" ) type AppTest struct { testing.TestSuite } func (t *AppTest) TestError() { data := map[string]string{"message": "Error"} log.Error(data) } func (t *AppTest) TestDebug() { data := map[string]string{"message": "Debug"} log.Debug(data) } func (t *AppTest) TestLog() { data := map[string]string{"message": "Log"} log.Log("tag", data) } func (t *AppTest) TestLogger() { data := map[string]string{"message": "Logger"} log.Logger.Post("tag", data) } func (t *AppTest) TestInfo()
{ data := map[string]string{"message": "Info"} log.Info(data) }
package main import ( "bufio" "fmt" "os" "sort" "strconv" "strings" ) func main() { scanner := bufio.NewScanner(os.Stdin) scanner.Scan() testCases, _ := strconv.Atoi(scanner.Text()) for i := 0; i < testCases; i++ { fmt.Printf("Case #%v: %v\n", i+1, solve(parseTestCase(scanner))) } } func solve(us int, others []int) int { cnt := 0 fmt.Println(us, others) probs := make([]int, len(others)) if us > others[0] { probs[0] = us } for i := 1; i < len(others); i++ { if probs[i-1]+others[i-1] > others[i] { probs[i] = probs[i-1] + others[i-1] } } for i := 0; i < len(probs); i++ { if probs[i] <= others[i] { cnt++ } } return cnt } func parseTestCase(scanner *bufio.Scanner) (int, []int)
{ scanner.Scan() pair := strings.Split(scanner.Text(), " ") us, _ := strconv.Atoi(pair[0]) scanner.Scan() others := []int{} for _, m := range strings.Split(scanner.Text(), " ") { mote, _ := strconv.Atoi(m) others = append(others, mote) } sort.Ints(others) return us, others }
package resources import "github.com/awslabs/goformation/cloudformation/policies" type AWSGameLiftBuild_S3Location struct { Bucket string `json:"Bucket,omitempty"` Key string `json:"Key,omitempty"` RoleArn string `json:"RoleArn,omitempty"` _deletionPolicy policies.DeletionPolicy _dependsOn []string _metadata map[string]interface{} } func (r *AWSGameLiftBuild_S3Location) AWSCloudFormationType() string { return "AWS::GameLift::Build.S3Location" } func (r *AWSGameLiftBuild_S3Location) DependsOn() []string { return r._dependsOn } func (r *AWSGameLiftBuild_S3Location) SetDependsOn(dependencies []string) { r._dependsOn = dependencies } func (r *AWSGameLiftBuild_S3Location) Metadata() map[string]interface{} { return r._metadata } func (r *AWSGameLiftBuild_S3Location) SetDeletionPolicy(policy policies.DeletionPolicy) { r._deletionPolicy = policy } func (r *AWSGameLiftBuild_S3Location) SetMetadata(metadata map[string]interface{})
{ r._metadata = metadata }
package kubernetes import ( "fmt" "k8s.io/api/apps/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "github.com/weaveworks/scope/report" ) type StatefulSet interface { Meta Selector() (labels.Selector, error) GetNode(probeID string) report.Node } type statefulSet struct { *v1beta1.StatefulSet Meta } func (s *statefulSet) Selector() (labels.Selector, error) { selector, err := metav1.LabelSelectorAsSelector(s.Spec.Selector) if err != nil { return nil, err } return selector, nil } func (s *statefulSet) GetNode(probeID string) report.Node { desiredReplicas := 1 if s.Spec.Replicas != nil { desiredReplicas = int(*s.Spec.Replicas) } latests := map[string]string{ NodeType: "StatefulSet", DesiredReplicas: fmt.Sprint(desiredReplicas), Replicas: fmt.Sprint(s.Status.Replicas), report.ControlProbeID: probeID, } if s.Status.ObservedGeneration != nil { latests[ObservedGeneration] = fmt.Sprint(*s.Status.ObservedGeneration) } return s.MetaNode(report.MakeStatefulSetNodeID(s.UID())).WithLatests(latests) } func NewStatefulSet(s *v1beta1.StatefulSet) StatefulSet
{ return &statefulSet{ StatefulSet: s, Meta: meta{s.ObjectMeta}, } }
package examples import ( "github.com/orfjackal/gospec/src/gospec" "testing" ) func TestAllSpecs(t *testing.T)
{ r := gospec.NewRunner() r.AddSpec(ExecutionModelSpec) r.AddSpec(ExpectationSyntaxSpec) r.AddSpec(FibSpec) r.AddSpec(StackSpec) gospec.MainGoTest(r, t) }
package esicache import ( "context" "sync" "time" "github.com/corestoreio/errors" ) type Cacher interface { Set(key string, value []byte, expiration time.Duration) error Get(key string) ([]byte, error) } func NewCacher(url string) (Cacher, error) { return nil, nil } type Caches []Cacher func (c Caches) Set(key string, value []byte, expiration time.Duration) error { return nil } func (c Caches) Get(key string) ([]byte, error) { return nil, nil } var MainRegistry = &registry{ caches: make(map[string]Caches), } type registry struct { mu sync.RWMutex caches map[string]Caches } func (r *registry) Get(ctx context.Context, scope, alias, key string) error { return errors.New("TODO IMPLEMENT") } func (r *registry) Len(scope string) int { r.mu.RLock() defer r.mu.RUnlock() return len(r.caches[scope]) } func (r *registry) Clear() { r.mu.Lock() defer r.mu.Unlock() r.caches = make(map[string]Caches) } func (r *registry) Register(scope, url string) error
{ r.mu.Lock() defer r.mu.Unlock() c, err := NewCacher(url) if err != nil { return errors.Wrapf(err, "[esikv] NewCacher URL %q", url) } if _, ok := r.caches[scope]; !ok { r.caches[scope] = make(Caches, 0, 2) } r.caches[scope] = append(r.caches[scope], c) return nil }
package rng import ( "fmt" "math" ) type CauchyGenerator struct { uniform *UniformGenerator } func NewCauchyGenerator(seed int64) *CauchyGenerator { urng := NewUniformGenerator(seed) return &CauchyGenerator{urng} } func (crng CauchyGenerator) Cauchy(x0, gamma float64) float64 { if !(gamma > 0.0) { panic(fmt.Sprintf("Invalid parameter gamma: %.2f", gamma)) } return crng.cauchy(x0, gamma) } func (crng CauchyGenerator) StandardCauchy() float64 { return crng.cauchy(0.0, 1.0) } func (crng CauchyGenerator) cauchy(x0, gamma float64) float64
{ return x0 + gamma*math.Tan(math.Pi*(crng.uniform.Float64()-0.5)) }
package lapack import ( "fmt" "github.com/hrautila/linalg" "github.com/hrautila/matrix" ) func Potrf(A matrix.Matrix, opts ...linalg.Option) error { switch A.(type) { case *matrix.FloatMatrix: return PotrfFloat(A.(*matrix.FloatMatrix), opts...) case *matrix.ComplexMatrix: return onError("Potrf: complex not implemented yet") } return onError("Potrf unknown types") } func PotrfFloat(A *matrix.FloatMatrix, opts ...linalg.Option) error { pars, err := linalg.GetParameters(opts...) if err != nil { return err } ind := linalg.GetIndexOpts(opts...) err = checkPotrf(ind, A) if ind.N == 0 { return nil } Aa := A.FloatArray() uplo := linalg.ParamString(pars.Uplo) info := dpotrf(uplo, ind.N, Aa[ind.OffsetA:], ind.LDa) if info != 0 { return onError(fmt.Sprintf("Potrf: lapack error %d", info)) } return nil } func checkPotrf(ind *linalg.IndexOpts, A matrix.Matrix) error
{ arows := ind.LDa if ind.N < 0 { ind.N = A.Rows() if ind.N != A.Cols() { return onError("Potrf: not square") } } if ind.N == 0 { return nil } if ind.LDa == 0 { ind.LDa = max(1, A.LeadingIndex()) arows = max(1, A.Rows()) } if ind.LDa < max(1, ind.N) { return onError("Potrf: lda") } if ind.OffsetA < 0 { return onError("Potrf: offsetA") } if A.NumElements() < ind.OffsetA+(ind.N-1)*arows+ind.N { return onError("Potrf: sizeA") } return nil }
package configmap import ( "sync" corev1 "k8s.io/api/core/v1" ) type ManualWatcher struct { Namespace string sync.RWMutex observers map[string][]Observer } var _ Watcher = (*ManualWatcher)(nil) func (w *ManualWatcher) ForEach(f func(string, []Observer) error) error { for k, v := range w.observers { if err := f(k, v); err != nil { return err } } return nil } func (w *ManualWatcher) Start(<-chan struct{}) error { return nil } func (w *ManualWatcher) OnChange(configMap *corev1.ConfigMap) { if configMap.Namespace != w.Namespace { return } w.RLock() defer w.RUnlock() for _, o := range w.observers[configMap.Name] { o(configMap) } } func (w *ManualWatcher) Watch(name string, o ...Observer)
{ w.Lock() defer w.Unlock() if w.observers == nil { w.observers = make(map[string][]Observer, 1) } w.observers[name] = append(w.observers[name], o...) }
package gridq type byColRow []*WriteResponse func (p byColRow) Len() int { return len(p) } func (p byColRow) Swap(i, j int) { p[i], p[j] = p[j], p[i] } type byRowTimestamp []*ReadResponse func (p byRowTimestamp) Len() int { return len(p) } func (p byRowTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p byRowTimestamp) Less(i, j int) bool { if p[i].Row < p[j].Row { return true } else if p[i].Row > p[j].Row { return false } else { return p[i].State.Timestamp > p[j].State.Timestamp } } type byTimestamp []*ReadResponse func (p byTimestamp) Len() int { return len(p) } func (p byTimestamp) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p byTimestamp) Less(i, j int) bool { return p[i].State.Timestamp < p[j].State.Timestamp } func (p byColRow) Less(i, j int) bool
{ if p[i].Col < p[j].Col { return true } else if p[i].Col > p[j].Col { return false } else { return p[i].Row < p[j].Row } }
package naivecheap import "github.com/ffloyd/evergrid-go/global/types" type byPriceAsc []types.WorkerInfo func (sw byPriceAsc) Len() int { return len(sw) } func (sw byPriceAsc) Swap(i, j int) { sw[i], sw[j] = sw[j], sw[i] } type byQueueAsc []types.WorkerInfo func (sw byQueueAsc) Len() int { return len(sw) } func (sw byQueueAsc) Swap(i, j int) { sw[i], sw[j] = sw[j], sw[i] } func (sw byQueueAsc) Less(i, j int) bool { return sw[i].QueueLength < sw[j].QueueLength } func (sw byPriceAsc) Less(i, j int) bool
{ return sw[i].PricePerTick < sw[j].PricePerTick }
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 *FontButton) GetFontName() string { c := C.gtk_font_button_get_font_name(v.native()) return goString(c) } 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 *SizeGroup) SetIgnoreHidden(ignoreHidden bool)
{ C.gtk_size_group_set_ignore_hidden(v.native(), gbool(ignoreHidden)) }
package models import ( "crypto/md5" "encoding/hex" ) func Hash(s string) string
{ hash := md5.New() hash.Write([]byte(s)) return hex.EncodeToString(hash.Sum(nil)) }
package credit_card_utils import ( "testing" "github.com/stretchr/testify/assert" ) func TestDisplayNumber(t *testing.T)
{ maskedNumber := MaskNumber("42224242422222") assert.Equal(t, "XXXX-XXXX-XXXX-2222", maskedNumber) }
package stick import ( "encoding/json" "fmt" "reflect" "strings" "go.mongodb.org/mongo-driver/bson" ) type Coding string const ( JSON Coding = "json" BSON Coding = "bson" ) func (c Coding) Unmarshal(in []byte, out interface{}) error { switch c { case JSON: return json.Unmarshal(in, out) case BSON: return bson.Unmarshal(in, out) default: panic(fmt.Sprintf("coal: unknown coding %q", c)) } } func (c Coding) Transfer(in, out interface{}) error { bytes, err := c.Marshal(in) if err != nil { return err } err = c.Unmarshal(bytes, out) if err != nil { return err } return nil } func GetJSONKey(field *reflect.StructField) string { tag := field.Tag.Get("json") if tag == "-" { return "" } values := strings.Split(tag, ",") if len(values) > 0 && len(values[0]) > 0 { return values[0] } return field.Name } func GetBSONKey(field *reflect.StructField) string { tag := field.Tag.Get("bson") if tag == "-" { return "" } values := strings.Split(tag, ",") if len(values) > 0 && len(values[0]) > 0 { return values[0] } return strings.ToLower(field.Name) } func (c Coding) Marshal(in interface{}) ([]byte, error)
{ switch c { case JSON: return json.Marshal(in) case BSON: return bson.Marshal(in) default: panic(fmt.Sprintf("coal: unknown coding %q", c)) } }
package migrations import "github.com/BurntSushi/migration" func ReplaceStepLocationWithPlanID(tx migration.LimitedTx) error
{ _, err := tx.Exec(` ALTER TABLE containers DROP COLUMN step_location; `) if err != nil { return err } _, err = tx.Exec(` ALTER TABLE containers ADD COLUMN plan_id text; `) return err }
package c3 type whereIterable struct { items Iterable where Predicate } func (i *whereIterable) Iterator() Iterator
{ return &whereIterator{i.items.Iterator(), i.where} }
package internalversion import ( "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" core "k8s.io/kubernetes/pkg/apis/core" ) type ComponentStatusLister interface { List(selector labels.Selector) (ret []*core.ComponentStatus, err error) Get(name string) (*core.ComponentStatus, error) ComponentStatusListerExpansion } type componentStatusLister struct { indexer cache.Indexer } func NewComponentStatusLister(indexer cache.Indexer) ComponentStatusLister { return &componentStatusLister{indexer: indexer} } func (s *componentStatusLister) Get(name string) (*core.ComponentStatus, error) { obj, exists, err := s.indexer.GetByKey(name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(core.Resource("componentstatus"), name) } return obj.(*core.ComponentStatus), nil } func (s *componentStatusLister) List(selector labels.Selector) (ret []*core.ComponentStatus, err error)
{ err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*core.ComponentStatus)) }) return ret, err }
package common import "strings" func TransformToAuthProvider(authConfig map[string]interface{}) map[string]interface{}
{ result := map[string]interface{}{} if m, ok := authConfig["metadata"].(map[string]interface{}); ok { result["id"] = m["name"] } if t, ok := authConfig["type"].(string); ok && t != "" { result["type"] = strings.Replace(t, "Config", "Provider", -1) } return result }
package main import ( "log" "net" "golang.org/x/net/context" "google.golang.org/grpc" "github.com/go-svc/svc/examples/grpc-lb/pb" "github.com/go-svc/svc/sd/consul" "github.com/go-svc/svc/sd/lb" "github.com/hashicorp/consul/api" ) type server struct { db pb.TodoClient } func (s *server) Add(ctx context.Context, in *pb.Task) (*pb.Task, error) { s.db.Add(context.Background(), in) return in, nil } func (s *server) List(ctx context.Context, in *pb.Void) (*pb.Tasks, error) { tasks, _ := s.db.List(context.Background(), in) return tasks, nil } func main() { lis, err := net.Listen("tcp", ":50051") if err != nil { log.Fatalf("無法監聽該埠口:%v", err) } s := grpc.NewServer() pb.RegisterTodoServer(s, &server{ db: newDB(), }) if err := s.Serve(lis); err != nil { log.Fatalf("無法提供服務:%v", err) } } func newDB() pb.TodoClient
{ sd, _ := consul.NewClient(api.DefaultConfig()) balancer := lb.NewBalancer(lb.ConsulOption{ Name: "Database", Mode: lb.RoundRobin, Tag: "", Client: sd, }) conn, err := grpc.Dial("localhost:50050", grpc.WithInsecure(), grpc.WithBalancer(balancer)) if err != nil { log.Fatalf("連線失敗:%v", err) } return pb.NewTodoClient(conn) }
package vmware func (v VMWare) IsAvailable() bool { return false } func NewDatasource(fileName string) *VMWare
{ return &VMWare{} }
package util import ( "fmt" "os" ) func Example_noTrailingNewline() { ld := NewLineDelimiter(os.Stdout, "|") defer ld.Flush() fmt.Fprint(ld, " Hello \n World ") } func Example_trailingNewline()
{ ld := NewLineDelimiter(os.Stdout, "|") defer ld.Flush() fmt.Fprint(ld, " Hello \n World \n") }
package goque import ( "bytes" "encoding/binary" "encoding/gob" ) type Item struct { ID uint64 Key []byte Value []byte } func (i *Item) ToString() string { return string(i.Value) } func (i *Item) ToObject(value interface{}) error { buffer := bytes.NewBuffer(i.Value) dec := gob.NewDecoder(buffer) return dec.Decode(value) } type PriorityItem struct { ID uint64 Priority uint8 Key []byte Value []byte } func (pi *PriorityItem) ToString() string { return string(pi.Value) } func idToKey(id uint64) []byte { key := make([]byte, 8) binary.BigEndian.PutUint64(key, id) return key } func keyToID(key []byte) uint64 { return binary.BigEndian.Uint64(key) } func (pi *PriorityItem) ToObject(value interface{}) error
{ buffer := bytes.NewBuffer(pi.Value) dec := gob.NewDecoder(buffer) return dec.Decode(value) }
package model import ( "encoding/json" "io" ) const ( SYSTEM_DIAGNOSTIC_ID = "DiagnosticId" SYSTEM_RAN_UNIT_TESTS = "RanUnitTests" SYSTEM_LAST_SECURITY_TIME = "LastSecurityTime" ) type System struct { Name string `json:"name"` Value string `json:"value"` } func SystemFromJson(data io.Reader) *System { decoder := json.NewDecoder(data) var o System err := decoder.Decode(&o) if err == nil { return &o } else { return nil } } func (o *System) ToJson() string
{ b, err := json.Marshal(o) if err != nil { return "" } else { return string(b) } }
package model import ( "encoding/json" "fmt" "log" "net/http" "strings" ) type Response struct { Status string `json:"status"` ErrorText string `json:"errorText,omitempty"` Address string `json:"address,omitempty"` StatusCode int `json:"statusCode,omitempty"` Version string `json:"version,omitempty"` } type Responses struct { Responses []Response `json:"responses"` } func (r *Response) Fill(outStr string, err error) { if err != nil { r.Status = "ERR" r.ErrorText = strings.TrimSpace(outStr + " " + err.Error()) } else { r.Status = "OK" } } func (r Response) String() string { j, _ := json.Marshal(r) return fmt.Sprintf("Response: %s", string(j)) } func (r Response) WriteHttp(w http.ResponseWriter) (resp Response) { if r.StatusCode == 0 { r.StatusCode = 200 } w.WriteHeader(r.StatusCode) return EncodeJson(r, w) } func (r Response) WriteBadRequestHttp(w http.ResponseWriter) (resp Response) { w.WriteHeader(http.StatusBadRequest) r.StatusCode = http.StatusBadRequest return EncodeJson(r, w) } func (r Response) WriteInternalServerErrorHttp(w http.ResponseWriter) (resp Response) { w.WriteHeader(http.StatusInternalServerError) r.StatusCode = http.StatusInternalServerError return EncodeJson(r, w) } func EncodeJson(r Response, w http.ResponseWriter) (resp Response) { err := json.NewEncoder(w).Encode(r) if err != nil { log.Printf("[writehttp] failed to create json from model: %s", err.Error()) } return r } func (r Responses) String() string
{ j, _ := json.Marshal(r) return fmt.Sprintf("Responses: %s", string(j)) }
package logger import ( "testing" "github.com/golib/assert" ) func Test_Level_String(t *testing.T) { assertion := assert.New(t) for level, s := range levels { assertion.Equal(s, level.String()) } assertion.Equal("UNKNOWN", lmin.String()) assertion.Equal("UNKNOWN", lmax.String()) } func Test_Level_ResolveLevelByName(t *testing.T)
{ assertion := assert.New(t) for level, name := range levels { assertion.Equal(level, ResolveLevelByName(name)) } assertion.Equal(lmin, ResolveLevelByName("UNKNOWN")) }
package gitlab import ( "fmt" "strings" "testing" "github.com/nlamirault/guzuta/utils" ) var ( namespace = "nicolas-lamirault" name = "scame" description = "An Emacs configuration" ) func TestRetrieveGitLabProjects(t *testing.T) { client := getGitlabClient() projects, _ := client.GetProjects() for _, project := range *projects { path := fmt.Sprintf("%s/%s", namespace, project.Path) if !strings.HasPrefix(project.PathWithNamespace, path) { t.Fatalf("Invalid project name : %s %s", project.PathWithNamespace, path) } } } func TestRetrieveGitlabUnknownProject(t *testing.T) { client := getGitlabClient() _, err := client.GetProject(namespace, "aaaaaaaaaa") if err == nil { t.Fatalf("No error with unknown username") } } func getGitlabClient() *Client
{ return NewClient(utils.Getenv("GUZUTA_GITLAB_TOKEN")) }
package event import ( "fmt" "sync/atomic" "time" ) type Increment struct { Name string Value int64 } func (e *Increment) StatClass() string { return "counter" } func (e *Increment) Update(e2 Event) error { if e.Type() != e2.Type() { return fmt.Errorf("statsd event type conflict: %s vs %s ", e.String(), e2.String()) } atomic.AddInt64(&e.Value, e2.Payload().(int64)) return nil } func (e *Increment) Reset() { e.Value = 0 } func (e Increment) Payload() interface{} { return e.Value } func (e Increment) Key() string { return e.Name } func (e *Increment) SetKey(key string) { e.Name = key } func (e Increment) Type() int { return EventIncr } func (e Increment) TypeString() string { return "Increment" } func (e Increment) String() string { return fmt.Sprintf("{Type: %s, Key: %s, Value: %d}", e.TypeString(), e.Name, e.Value) } func (e Increment) Stats(tick time.Duration) []string
{ return []string{fmt.Sprintf("%s:%d|c", e.Name, e.Value)} }
package paths import ( "fmt" "os" "path/filepath" ) type Path struct { Home string Config string Data string Logs string } type FileType string const ( Home FileType = "home" Config FileType = "config" Data FileType = "data" Logs FileType = "logs" ) var Paths = New() func New() *Path { return &Path{} } func (paths *Path) InitPaths(cfg *Path) error { err := paths.initPaths(cfg) if err != nil { return err } err = os.MkdirAll(paths.Data, 0755) if err != nil { return fmt.Errorf("Failed to create data path %s: %v", paths.Data, err) } return nil } func InitPaths(cfg *Path) error { return Paths.InitPaths(cfg) } func (paths *Path) initPaths(cfg *Path) error { *paths = *cfg if paths.Config == "" { paths.Config = paths.Home } if paths.Data == "" { paths.Data = filepath.Join(paths.Home, "data") } if paths.Logs == "" { paths.Logs = filepath.Join(paths.Home, "logs") } return nil } func Resolve(fileType FileType, path string) string { return Paths.Resolve(fileType, path) } func (paths *Path) String() string { return fmt.Sprintf("Home path: [%s] Config path: [%s] Data path: [%s] Logs path: [%s]", paths.Home, paths.Config, paths.Data, paths.Logs) } func (paths *Path) Resolve(fileType FileType, path string) string
{ if filepath.IsAbs(path) { return path } switch fileType { case Home: return filepath.Join(paths.Home, path) case Config: return filepath.Join(paths.Config, path) case Data: return filepath.Join(paths.Data, path) case Logs: return filepath.Join(paths.Logs, path) default: panic(fmt.Sprintf("Unknown file type: %s", fileType)) } }
package e2e import ( "testing" "flag" "github.com/kubernetes-incubator/service-catalog/test/e2e/framework" ) var brokerImageFlag string func init() { flag.StringVar(&brokerImageFlag, "broker-image", "quay.io/kubernetes-service-catalog/user-broker:latest", "The container image for the broker to test against") framework.RegisterParseFlags() } func TestE2E(t *testing.T)
{ RunE2ETests(t) }
package main import ( "testing" ) func Benchmark_numberOfWaysToMake2Pounds(b *testing.B) { for i := 0; i < b.N; i++ { numberOfWaysToMake2Pounds() } } func Benchmark_numberOfWaysToMakeX2(b *testing.B) { for i := 0; i < b.N; i++ { numberOfWaysToMakeX2(200) } } func Benchmark_numberOfWaysToMakeX1(b *testing.B)
{ for i := 0; i < b.N; i++ { numberOfWaysToMakeX1(200) } }
package api import ( "net/http" "github.com/pivotal-golang/lager" "github.com/tedsuo/rata" "github.com/concourse/turbine" "github.com/concourse/turbine/api/abort" "github.com/concourse/turbine/api/check" "github.com/concourse/turbine/api/deletebuild" "github.com/concourse/turbine/api/events" "github.com/concourse/turbine/api/execute" "github.com/concourse/turbine/api/hijack" "github.com/concourse/turbine/resource" "github.com/concourse/turbine/scheduler" ) func New( logger lager.Logger, scheduler scheduler.Scheduler, tracker resource.Tracker, turbineEndpoint string, drain <-chan struct{}, ) (http.Handler, error)
{ checkHandler := check.NewHandler(logger, tracker, drain) handlers := map[string]http.Handler{ turbine.ExecuteBuild: execute.NewHandler(logger, scheduler, turbineEndpoint), turbine.DeleteBuild: deletebuild.NewHandler(logger, scheduler), turbine.AbortBuild: abort.NewHandler(logger, scheduler), turbine.HijackBuild: hijack.NewHandler(logger, scheduler), turbine.GetBuildEvents: events.NewHandler(logger, scheduler), turbine.CheckInput: checkHandler, turbine.CheckInputStream: http.HandlerFunc(checkHandler.Stream), } return rata.NewRouter(turbine.Routes, handlers) }
package metrics_test import ( "net/http" "net/http/httptest" "testing" "github.com/gkarlik/quark-go" "github.com/gkarlik/quark-go/metrics/prometheus" "github.com/gkarlik/quark-go/middleware/metrics" tr "github.com/gkarlik/quark-go/service/trace/noop" "github.com/stretchr/testify/assert" ) type TestService struct { *quark.ServiceBase } type TestHttpHandler struct{} func (h *TestHttpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write([]byte("OK")) } func TestMetricsMiddlewareWithNext(t *testing.T) { a, _ := quark.GetHostAddress(1234) ts := &TestService{ ServiceBase: quark.NewService( quark.Name("TestService"), quark.Version("1.0"), quark.Address(a), quark.Metrics(prometheus.NewMetricsExposer()), quark.Tracer(tr.NewTracer())), } defer ts.Dispose() mm := metrics.NewRequestMetricsMiddleware(ts) r, _ := http.NewRequest(http.MethodGet, "/test", nil) w := httptest.NewRecorder() th := &TestHttpHandler{} mm.HandleWithNext(w, r, th.ServeHTTP) assert.Equal(t, http.StatusOK, w.Code) } func TestMetricsMiddleware(t *testing.T)
{ a, _ := quark.GetHostAddress(1234) ts := &TestService{ ServiceBase: quark.NewService( quark.Name("TestService"), quark.Version("1.0"), quark.Address(a), quark.Metrics(prometheus.NewMetricsExposer()), quark.Tracer(tr.NewTracer())), } defer ts.Dispose() mm := metrics.NewRequestMetricsMiddleware(ts) r, _ := http.NewRequest(http.MethodGet, "/test", nil) w := httptest.NewRecorder() h := mm.Handle(&TestHttpHandler{}) h.ServeHTTP(w, r) assert.Equal(t, http.StatusOK, w.Code) }
package bigquery import ( "fmt" "github.com/viant/endly" "github.com/viant/endly/system/cloud/gcp" "google.golang.org/api/bigquery/v2" ) var clientKey = (*CtxClient)(nil) type CtxClient struct { *gcp.AbstractClient service *bigquery.Service } func (s *CtxClient) SetService(service interface{}) error { var ok bool s.service, ok = service.(*bigquery.Service) if !ok { return fmt.Errorf("unable to set service: %T", service) } return nil } func InitRequest(context *endly.Context, rawRequest map[string]interface{}) error { config, err := gcp.InitCredentials(context, rawRequest) if err != nil { return err } client, err := getClient(context) if err != nil { return err } gcp.UpdateActionRequest(rawRequest, config, client) return nil } func getClient(context *endly.Context) (gcp.CtxClient, error) { return GetClient(context) } func GetClient(context *endly.Context) (*CtxClient, error) { client := &CtxClient{ AbstractClient: &gcp.AbstractClient{}, } err := gcp.GetClient(context, bigquery.New, clientKey, &client, bigquery.CloudPlatformScope, bigquery.BigqueryScope, bigquery.BigqueryInsertdataScope) return client, err } func (s *CtxClient) Service() interface{}
{ return s.service }
package main import ( "io" "sync" "time" "github.com/google/uuid" "github.com/gorilla/websocket" ) type Client struct { hub *Hub ws *websocket.Conn otherSide *Client channelID uuid.UUID remoteType string params map[string][]string wmu sync.Mutex rmu sync.Mutex } func (c *Client) WriteMessage(msgType int, message []byte) (err error) { c.wmu.Lock() err = c.ws.WriteMessage(msgType, message) c.wmu.Unlock() return } func (c *Client) NextWriter(msgType int) (w io.WriteCloser, err error) { c.wmu.Lock() w, err = c.ws.NextWriter(msgType) c.wmu.Unlock() return } func (c *Client) NextReader() (msgType int, r io.Reader, err error) { c.rmu.Lock() msgType, r, err = c.ws.NextReader() c.rmu.Unlock() return } func (c *Client) SetWriteDeadline(t time.Time) (err error) { c.wmu.Lock() err = c.ws.SetWriteDeadline(t) c.wmu.Unlock() return } func (c *Client) SetReadDeadline(t time.Time) (err error) { c.rmu.Lock() err = c.ws.SetReadDeadline(t) c.rmu.Unlock() return } func (c *Client) ReadMessage() (msgType int, message []byte, err error)
{ c.rmu.Lock() msgType, message, err = c.ws.ReadMessage() c.rmu.Unlock() return }
package google import ( "errors" "fmt" "strconv" "testing" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func testAccCheckGoogleComputeZonesMeta(n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Can't find zones data source: %s", n) } if rs.Primary.ID == "" { return errors.New("zones data source ID not set.") } count, ok := rs.Primary.Attributes["names.#"] if !ok { return errors.New("can't find 'names' attribute") } noOfNames, err := strconv.Atoi(count) if err != nil { return errors.New("failed to read number of zones") } if noOfNames < 2 { return fmt.Errorf("expected at least 2 zones, received %d, this is most likely a bug", noOfNames) } for i := 0; i < noOfNames; i++ { idx := "names." + strconv.Itoa(i) v, ok := rs.Primary.Attributes[idx] if !ok { return fmt.Errorf("zone list is corrupt (%q not found), this is definitely a bug", idx) } if len(v) < 1 { return fmt.Errorf("Empty zone name (%q), this is definitely a bug", idx) } } return nil } } var testAccCheckGoogleComputeZonesConfig = ` data "google_compute_zones" "available" {} ` func TestAccComputeZones_basic(t *testing.T)
{ t.Parallel() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { Config: testAccCheckGoogleComputeZonesConfig, Check: resource.ComposeTestCheckFunc( testAccCheckGoogleComputeZonesMeta("data.google_compute_zones.available"), ), }, }, }) }
package memberlist import ( "fmt" "net" "time" ) type Packet struct { Buf []byte From net.Addr Timestamp time.Time } type Transport interface { FinalAdvertiseAddr(ip string, port int) (net.IP, int, error) WriteTo(b []byte, addr string) (time.Time, error) PacketCh() <-chan *Packet DialTimeout(addr string, timeout time.Duration) (net.Conn, error) StreamCh() <-chan net.Conn Shutdown() error } type Address struct { Addr string Name string } func (a *Address) String() string { if a.Name != "" { return fmt.Sprintf("%s (%s)", a.Name, a.Addr) } return a.Addr } type IngestionAwareTransport interface { IngestPacket(conn net.Conn, addr net.Addr, now time.Time, shouldClose bool) error IngestStream(conn net.Conn) error } type NodeAwareTransport interface { Transport WriteToAddress(b []byte, addr Address) (time.Time, error) DialAddressTimeout(addr Address, timeout time.Duration) (net.Conn, error) } type shimNodeAwareTransport struct { Transport } var _ NodeAwareTransport = (*shimNodeAwareTransport)(nil) func (t *shimNodeAwareTransport) DialAddressTimeout(addr Address, timeout time.Duration) (net.Conn, error) { return t.DialTimeout(addr.Addr, timeout) } func (t *shimNodeAwareTransport) WriteToAddress(b []byte, addr Address) (time.Time, error)
{ return t.WriteTo(b, addr.Addr) }
package k8sclient import ( "bytes" "encoding/gob" "hash/fnv" "math/rand" "sync" "github.com/golang/glog" "github.com/google/uuid" ) var ( seedOnce sync.Once uuidMutex sync.Mutex ) func GenerateUUID(seed string) string { var stringUUID string uuidMutex.Lock() uuid.SetRand(rand.New(rand.NewSource(int64(hash(seed))))) stringUUID = uuid.New().String() uuidMutex.Unlock() return stringUUID } func hash(valueOne interface{}) uint64 { newHash := fnv.New64() newHash.Write(getBytes(valueOne)) return newHash.Sum64() } func HashCombine(valueOne, valueTwo interface{}) uint64 { newHash := fnv.New64() valueOneBytes := getBytes(valueOne) valueTwoBytes := getBytes(valueTwo) newHash.Write(append(valueOneBytes, valueTwoBytes...)) return newHash.Sum64() } func getBytes(value interface{}) []byte
{ var byteBuffer bytes.Buffer gobEncoder := gob.NewEncoder(&byteBuffer) if err := gobEncoder.Encode(value); err != nil { glog.Fatalln("Failed to encode value") return nil } return byteBuffer.Bytes() }
package mock_concurrent import ( reflect "reflect" gomock "github.com/golang/mock/gomock" ) type MockMath struct { ctrl *gomock.Controller recorder *MockMathMockRecorder } type MockMathMockRecorder struct { mock *MockMath } func NewMockMath(ctrl *gomock.Controller) *MockMath { mock := &MockMath{ctrl: ctrl} mock.recorder = &MockMathMockRecorder{mock} return mock } func (m *MockMath) Sum(arg0, arg1 int) int { ret := m.ctrl.Call(m, "Sum", arg0, arg1) ret0, _ := ret[0].(int) return ret0 } func (mr *MockMathMockRecorder) Sum(arg0, arg1 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sum", reflect.TypeOf((*MockMath)(nil).Sum), arg0, arg1) } func (m *MockMath) EXPECT() *MockMathMockRecorder
{ return m.recorder }
package types import "testing" func TestGzipText(t *testing.T) { g := GzippedText("Hello, world") v, err := g.Value() if err != nil { t.Errorf("Was not expecting an error") } err = (&g).Scan(v) if err != nil { t.Errorf("Was not expecting an error") } if string(g) != "Hello, world" { t.Errorf("Was expecting the string we sent in (Hello World), got %s", string(g)) } } func TestJSONText(t *testing.T) { j := JSONText(`{"foo": 1, "bar": 2}`) v, err := j.Value() if err != nil { t.Errorf("Was not expecting an error") } err = (&j).Scan(v) if err != nil { t.Errorf("Was not expecting an error") } m := map[string]interface{}{} j.Unmarshal(&m) if m["foo"].(float64) != 1 || m["bar"].(float64) != 2 { t.Errorf("Expected valid json but got some garbage instead? %#v", m) } j = JSONText(`{"foo": 1, invalid, false}`) v, err = j.Value() if err == nil { t.Errorf("Was expecting invalid json to fail!") } } func TestBitBool(t *testing.T)
{ var b BitBool = true v, err := b.Value() if err != nil { t.Errorf("Cannot return error") } err = (&b).Scan(v) if err != nil { t.Errorf("Was not expecting an error") } if !b { t.Errorf("Was expecting the bool we sent in (true), got %b", b) } b = false v, err = b.Value() if err != nil { t.Errorf("Cannot return error") } err = (&b).Scan(v) if err != nil { t.Errorf("Was not expecting an error") } if b { t.Errorf("Was expecting the bool we sent in (false), got %b", b) } }
package tasks import ( "net/http" "github.com/go-openapi/errors" "github.com/go-openapi/runtime/middleware" "github.com/go-openapi/swag" strfmt "github.com/go-openapi/strfmt" ) func NewDeleteTaskParams() DeleteTaskParams { var () return DeleteTaskParams{} } type DeleteTaskParams struct { HTTPRequest *http.Request ID int64 } func (o *DeleteTaskParams) bindID(rawData []string, hasKey bool, formats strfmt.Registry) error { var raw string if len(rawData) > 0 { raw = rawData[len(rawData)-1] } value, err := swag.ConvertInt64(raw) if err != nil { return errors.InvalidType("id", "path", "int64", raw) } o.ID = value return nil } func (o *DeleteTaskParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error
{ var res []error o.HTTPRequest = r rID, rhkID, _ := route.Params.GetOK("id") if err := o.bindID(rID, rhkID, route.Formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
package permutation import "C" import ( "github.com/dtromb/gogsl" "reflect" "unsafe" ) func (p *GslPermutation) Len() int { return int(C.get_permutation_size((*C.gsl_permutation)(unsafe.Pointer(p.Ptr())))) } func (p *GslPermutation) Slice_() interface{}
{ baseType := gogsl.GOGSL_SIZE_T_TYPE sliceType := reflect.SliceOf(baseType) size := p.Len() hdr := &reflect.SliceHeader{Len: size, Cap: size, Data: uintptr(C.get_permutation_data((*C.gsl_permutation)(unsafe.Pointer(p.Ptr()))))} return reflect.NewAt(sliceType, unsafe.Pointer(hdr)).Elem().Interface() }
package trace import ( "github.com/golang/groupcache/lru" ) type lruMap struct { cacheKeys map[lru.Key]bool cache *lru.Cache droppedCount int } func newLruMap(size int) *lruMap { lm := &lruMap{ cacheKeys: make(map[lru.Key]bool), cache: lru.New(size), droppedCount: 0, } lm.cache.OnEvicted = func(key lru.Key, value interface{}) { delete(lm.cacheKeys, key) lm.droppedCount++ } return lm } func (lm lruMap) len() int { return lm.cache.Len() } func (lm *lruMap) add(key, value interface{}) { lm.cacheKeys[lru.Key(key)] = true lm.cache.Add(lru.Key(key), value) } func (lm *lruMap) get(key interface{}) (interface{}, bool) { return lm.cache.Get(key) } func (lm lruMap) keys() []interface{}
{ keys := []interface{}{} for k := range lm.cacheKeys { keys = append(keys, k) } return keys }
package matchers import ( "github.com/nttlabs/cli/cf/errors" testcmd "github.com/nttlabs/cli/testhelpers/commands" "github.com/onsi/gomega" ) type havePassedRequirementsMatcher struct{} func (matcher havePassedRequirementsMatcher) Match(actual interface{}) (bool, error) { switch actual.(type) { case bool: asBool := actual.(bool) return asBool == true, nil case testcmd.RunCommandResult: result := actual.(testcmd.RunCommandResult) return result == testcmd.RunCommandResultSuccess, nil default: return false, errors.NewWithFmt("Expected actual value to be a bool or enum, but it was a %T", actual) } } func (matcher havePassedRequirementsMatcher) FailureMessage(_ interface{}) string { return "Expected command to pass requirements but it did not" } func (matcher havePassedRequirementsMatcher) NegatedFailureMessage(_ interface{}) string { return "Expected command to have not passed requirements but it did" } func HavePassedRequirements() gomega.OmegaMatcher
{ return havePassedRequirementsMatcher{} }
package utils import ( "bytes" "strings" "testing" "github.com/stretchr/testify/assert" irc "gopkg.in/irc.v3" ) type TestClientServer struct { client *bytes.Buffer server *bytes.Buffer } func NewTestClientServer() *TestClientServer { return &TestClientServer{ client: &bytes.Buffer{}, server: &bytes.Buffer{}, } } func (cs *TestClientServer) Read(p []byte) (int, error) { return cs.server.Read(p) } func (cs *TestClientServer) SendServerLines(lines []string) { w := irc.NewWriter(cs.server) for _, line := range lines { w.WriteMessage(irc.MustParseMessage(line)) } } func (cs *TestClientServer) CheckLines(t *testing.T, expected []string) bool { ok := true lines := strings.Split(cs.client.String(), "\r\n") var line, clientLine string for len(expected) > 0 && len(lines) > 0 { line, expected = expected[0], expected[1:] clientLine, lines = lines[0], lines[1:] ok = ok && assert.Equal(t, line, clientLine) } ok = ok && assert.Equal(t, 0, len(expected), "Not enough lines: %s", strings.Join(expected, ", ")) ok = ok && assert.Equal(t, 0, len(lines), "Extra non-empty lines: %s", strings.Join(lines, ", ")) return ok } func (cs *TestClientServer) Reset() { cs.client.Reset() cs.server.Reset() } func (cs *TestClientServer) Write(p []byte) (int, error)
{ return cs.client.Write(p) }
package main import ( "fmt" ) var ( cmdAuth = &Command{ Name: "auth", Run: RunAuth, Short: "auth LOGIN", Description: "authenticate user", Enabled: false, } ) func RunAuth(args []string) error
{ fmt.Println("hello from auth command") return nil }
package api import ( "encoding/json" "fmt" "os" "path/filepath" ) func Load(api, docs, paginators, waiters string) *API { a := API{} a.Attach(api) a.Attach(docs) a.Attach(paginators) a.Attach(waiters) a.Setup() return &a } func (a *API) AttachString(str string) { json.Unmarshal([]byte(str), a) if !a.initialized { a.Setup() } } func (a *API) Setup() { a.unrecognizedNames = map[string]string{} a.writeShapeNames() a.resolveReferences() a.fixStutterNames() a.renameExportable() a.renameToplevelShapes() a.updateTopLevelShapeReferences() a.createInputOutputShapes() a.customizationPasses() if !a.NoRemoveUnusedShapes { a.removeUnusedShapes() } if len(a.unrecognizedNames) > 0 { msg := []string{ "Unrecognized inflections for the following export names:", "(Add these to inflections.csv with any inflections added after the ':')", } fmt.Fprintf(os.Stderr, "%s\n%s\n\n", msg[0], msg[1]) for n, m := range a.unrecognizedNames { if n == m { m = "" } fmt.Fprintf(os.Stderr, "%s:%s\n", n, m) } os.Stderr.WriteString("\n\n") panic("Found unrecognized exported names in API " + a.PackageName()) } a.initialized = true } func (a *API) Attach(filename string)
{ a.path = filepath.Dir(filename) f, err := os.Open(filename) defer f.Close() if err != nil { panic(err) } json.NewDecoder(f).Decode(a) }
package smartest import ( "testing" "os" ) func TestCheckCleanTest(t *testing.T)
{ if _, err := os.Stat("1.log"); err == nil { t.Error("dirty test") } if _, err := os.Stat("2.log"); err == nil { t.Error("dirty test") } if _, err := os.Stat("hello"); err == nil { t.Error("dirty test") } if _, err := os.Stat("main.o"); err == nil { t.Error("dirty test") } if _, err := os.Stat("src/foo.o"); err == nil { t.Error("dirty test") } if _, err := os.Stat("src/bar.o"); err == nil { t.Error("dirty test") } if _, err := os.Stat("src/baz.o"); err == nil { t.Error("dirty test") } }
package redis import ( "github.com/Azure/go-autorest/autorest" ) const ( DefaultBaseURI = "https:management.azure.com" ) type BaseClient struct { autorest.Client BaseURI string SubscriptionID string } func New(subscriptionID string) BaseClient { return NewWithBaseURI(DefaultBaseURI, subscriptionID) } func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient
{ return BaseClient{ Client: autorest.NewClientWithUserAgent(UserAgent()), BaseURI: baseURI, SubscriptionID: subscriptionID, } }
package disk import ( "context" "flag" "fmt" "github.com/vmware/govmomi/govc/cli" "github.com/vmware/govmomi/govc/flags" "github.com/vmware/govmomi/vslm" ) type register struct { *flags.DatastoreFlag } func (cmd *register) Register(ctx context.Context, f *flag.FlagSet) { cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx) cmd.DatastoreFlag.Register(ctx, f) } func (cmd *register) Usage() string { return "PATH [NAME]" } func (cmd *register) Description() string { return `Register existing disk on DS. Examples: govc disk.register disks/disk1.vmdk my-disk` } func (cmd *register) Run(ctx context.Context, f *flag.FlagSet) error { ds, err := cmd.Datastore() if err != nil { return err } m := vslm.NewObjectManager(ds.Client()) path := ds.NewURL(f.Arg(0)).String() obj, err := m.RegisterDisk(ctx, path, f.Arg(1)) if err != nil { return err } fmt.Println(obj.Config.Id.Id) return nil } func init()
{ cli.Register("disk.register", &register{}) }
package connectivity import ( "fmt" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" "github.com/denverdino/aliyungo/common" ) type Config struct { AccessKey string SecretKey string Region common.Region RegionId string SecurityToken string OtsInstanceName string LogEndpoint string AccountId string FcEndpoint string MNSEndpoint string } func (c *Config) loadAndValidate() error { err := c.validateRegion() if err != nil { return err } return nil } func (c *Config) getAuthCredential(stsSupported bool) auth.Credential { if stsSupported { return credentials.NewStsTokenCredential(c.AccessKey, c.SecretKey, c.SecurityToken) } return credentials.NewAccessKeyCredential(c.AccessKey, c.SecretKey) } func (c *Config) validateRegion() error
{ for _, valid := range common.ValidRegions { if c.Region == valid { return nil } } return fmt.Errorf("Not a valid region: %s", c.Region) }
package operations import ( "github.com/denkhaus/bitshares/types" "github.com/denkhaus/bitshares/util" "github.com/juju/errors" ) type TransferFromBlindOperation struct { types.OperationFee Amount types.AssetAmount `json:"amount"` To types.AccountID `json:"to"` BlindFactor types.FixedBuffer `json:"blinding_factor"` BlindInputs types.BlindInputs `json:"inputs"` } func (p TransferFromBlindOperation) Type() types.OperationType { return types.OperationTypeTransferFromBlind } func (p TransferFromBlindOperation) Marshal(enc *util.TypeEncoder) error { if err := enc.Encode(int8(p.Type())); err != nil { return errors.Annotate(err, "encode OperationType") } if err := enc.Encode(p.Fee); err != nil { return errors.Annotate(err, "encode Fee") } if err := enc.Encode(p.Amount); err != nil { return errors.Annotate(err, "encode Amount") } if err := enc.Encode(p.To); err != nil { return errors.Annotate(err, "encode To") } if err := enc.Encode(p.BlindFactor); err != nil { return errors.Annotate(err, "encode BlindFactor") } if err := enc.Encode(p.BlindInputs); err != nil { return errors.Annotate(err, "encode BlindInputs") } return nil } func init()
{ types.OperationMap[types.OperationTypeTransferFromBlind] = func() types.Operation { op := &TransferFromBlindOperation{} return op } }
package session import ( "github.com/wpxiong/beargo/log" "sync" ) type SessionProvider interface { InitProvider(SessionLifeTime int64) CreateSession(sessionId string) (Session, error) DeleteSession(sessionId string) error FindSessionById(sessionId string) bool LoadSessionById(sessionId string) (Session ,error) SerializeSession() DeserializeSession() ClearSession(sessionAccess *sync.Mutex) DeseriazeObject (valueId string,bytearray []byte, obj interface{},sess *Session) bool } func init()
{ log.InitLog() }
package transformers import ( "errors" "fmt" "sigs.k8s.io/kustomize/pkg/resmap" "sigs.k8s.io/kustomize/pkg/transformers/config" ) type mapTransformer struct { m map[string]string fieldSpecs []config.FieldSpec } var _ Transformer = &mapTransformer{} func NewLabelsMapTransformer( m map[string]string, fs []config.FieldSpec) (Transformer, error) { return NewMapTransformer(fs, m) } func NewAnnotationsMapTransformer( m map[string]string, fs []config.FieldSpec) (Transformer, error) { return NewMapTransformer(fs, m) } func NewMapTransformer( pc []config.FieldSpec, m map[string]string) (Transformer, error) { if m == nil { return NewNoOpTransformer(), nil } if pc == nil { return nil, errors.New("fieldSpecs is not expected to be nil") } return &mapTransformer{fieldSpecs: pc, m: m}, nil } func (o *mapTransformer) addMap(in interface{}) (interface{}, error) { m, ok := in.(map[string]interface{}) if !ok { return nil, fmt.Errorf("%#v is expected to be %T", in, m) } for k, v := range o.m { m[k] = v } return m, nil } func (o *mapTransformer) Transform(m resmap.ResMap) error
{ for id := range m { objMap := m[id].Map() for _, path := range o.fieldSpecs { if !id.Gvk().IsSelected(&path.Gvk) { continue } err := mutateField(objMap, path.PathSlice(), path.CreateIfNotPresent, o.addMap) if err != nil { return err } } } return nil }
package godo import ( "encoding/json" "fmt" "net/http" "reflect" "testing" ) func TestImageActions_ImageActionsServiceOpImplementsImageActionsService(t *testing.T) { if !Implements((*ImageActionsService)(nil), new(ImageActionsServiceOp)) { t.Error("ImageActionsServiceOp does not implement ImageActionsService") } } func TestImageActions_Transfer(t *testing.T) { setup() defer teardown() transferRequest := &ActionRequest{} mux.HandleFunc("/v2/images/12345/actions", func(w http.ResponseWriter, r *http.Request) { v := new(ActionRequest) json.NewDecoder(r.Body).Decode(v) testMethod(t, r, "POST") if !reflect.DeepEqual(v, transferRequest) { t.Errorf("Request body = %+v, expected %+v", v, transferRequest) } fmt.Fprintf(w, `{"action":{"status":"in-progress"}}`) }) transfer, _, err := client.ImageActions.Transfer(12345, transferRequest) if err != nil { t.Errorf("ImageActions.Transfer returned error: %v", err) } expected := &Action{Status: "in-progress"} if !reflect.DeepEqual(transfer, expected) { t.Errorf("ImageActions.Transfer returned %+v, expected %+v", transfer, expected) } } func TestImageActions_Get(t *testing.T)
{ setup() defer teardown() mux.HandleFunc("/v2/images/123/actions/456", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") fmt.Fprintf(w, `{"action":{"status":"in-progress"}}`) }) action, _, err := client.ImageActions.Get(123, 456) if err != nil { t.Errorf("ImageActions.Get returned error: %v", err) } expected := &Action{Status: "in-progress"} if !reflect.DeepEqual(action, expected) { t.Errorf("ImageActions.Get returned %+v, expected %+v", action, expected) } }
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) String() string { return common.PointerString(request) } 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) HTTPResponse() *http.Response { return response.RawResponse } func (response CopyVolumeGroupBackupResponse) String() string
{ return common.PointerString(response) }
package policy import ( "testing" ) func TestEffectIsAllowed(t *testing.T) { testCases := []struct { effect Effect check bool expectedResult bool }{ {Allow, false, false}, {Allow, true, true}, {Deny, false, true}, {Deny, true, false}, } for i, testCase := range testCases { result := testCase.effect.IsAllowed(testCase.check) if result != testCase.expectedResult { t.Fatalf("case %v: expected: %v, got: %v\n", i+1, testCase.expectedResult, result) } } } func TestEffectIsValid(t *testing.T)
{ testCases := []struct { effect Effect expectedResult bool }{ {Allow, true}, {Deny, true}, {Effect(""), false}, {Effect("foo"), false}, } for i, testCase := range testCases { result := testCase.effect.IsValid() if result != testCase.expectedResult { t.Fatalf("case %v: expected: %v, got: %v\n", i+1, testCase.expectedResult, result) } } }
package dao import ( "context" "testing" "github.com/smartystreets/goconvey/convey" ) func TestDaotypesURI(t *testing.T) { convey.Convey("typesURI", t, func(ctx convey.C) { ctx.Convey("When everything gose positive", func(ctx convey.C) { p1 := testDao.typesURI() ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) { ctx.So(p1, convey.ShouldNotBeNil) }) }) }) } func TestDaoTypeMapping(t *testing.T)
{ convey.Convey("TypeMapping", t, func(ctx convey.C) { var ( c = context.Background() ) ctx.Convey("When everything gose positive", func(ctx convey.C) { rmap, err := testDao.TypeMapping(c) ctx.Convey("Then err should be nil.rmap should not be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) ctx.So(rmap, convey.ShouldNotBeNil) }) }) }) }