text stringlengths 14 100k | source stringclasses 1
value | repo stringclasses 810
values | language stringclasses 13
values |
|---|---|---|---|
<|fim_suffix|>a = epsilon
}
entropy -= proba * math.Log2(proba)
}
return entropy / math.Log2(float64(len(m)))
}
<|fim_prefix|>package mathx
import "math"
const epsilon = 1e-6
// CalcEntropy calculates the entropy of m.
func Calc<|fim_middle|>Entropy(m map[any]int) float64 {
if len(m) == 0 || len(m) == 1 {
... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mathx
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCalcEntropy(t *testing.T) {
const total = 1000
const count = 10<|fim_suffix|> TestCalcEmptyEntropy(t *testing.T) {
m := make(map[any]int)
assert.Equal(t, float64(1), CalcEntropy(m))
}
func TestCalcDiffEntropy(t *tes... | fim | zeromicro/go-zero | go |
<|fim_suffix|>precated: use builtin min instead.
func MinInt(a, b int) int {
return min(a, b)
}
<|fim_prefix|>package mathx
// MaxInt returns the larger one of a and b.
// Deprecated: use<|fim_middle|> builtin max instead.
func MaxInt(a, b int) int {
return max(a, b)
}
// MinInt returns the smaller one of a and b.
... | fim | zeromicro/go-zero | go |
<|fim_suffix|>t *testing.T) {
cases := []struct {
a int
b int
expect int
}{
{
a: 0,
b: 1,
expect: 0,
},
{
a: 0,
b: -1,
expect: -1,
},
{
a: 1,
b: 1,
expect: 1,
},
}
for _, each := range cases {
t.Run(stringx.Rand(), func(t *testi... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mathx
import (
"math/rand"
"sync"
"time"
)
// A Proba is used to test if true on given probability.
type Proba struct {
// rand.New(...) returns a non thread safe object
<|fim_suffix|>n &Proba{
r: rand.New(rand.NewSource(time.Now().UnixNano())),
}
}
// TrueOnProba checks if true on give... | fim | zeromicro/go-zero | go |
<|fim_suffix|>sert"
)
func TestTrueOnProba(t *testing.T) {
const proba = math.Pi / 10
const total = 100000
const epsilon = 0.05
var count int
p := NewProba()
for i := 0; i < total; i++ {
if p.TrueOnProba(proba) {
count++
}
}
ratio := float64(count) / float64(total)
assert.InEpsilon(t, proba, ratio, ep... | fim | zeromicro/go-zero | go |
<|fim_suffix|>pper
}
return x
}
<|fim_prefix|>package mathx
// Numerical is a constraint that permits any numeric type.
type Numerical interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64
}
// AtLeast returns the greater of x or lower.
func At... | fim | zeromicro/go-zero | go |
package mathx
import "testing"
func TestAtLeast(t *testing.T) {
t.Run("test int", func(t *testing.T) {
if got := AtLeast(10, 5); got != 10 {
t.Errorf("AtLeast() = %v, want 10", got)
}
if got := AtLeast(3, 5); got != 5 {
t.Errorf("AtLeast() = %v, want 5", got)
}
if got := AtLeast(5, 5); got != 5 {
... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mathx
import (
"math<|fim_suffix|>eviation - 2*u.deviation*u.r.Float64()) * float64(base))
u.lock.Unlock()
return val
}
// AroundInt returns a random int64 with given base and deviation.
func (u Unstable) AroundInt(base int64) int64 {
u.lock.Lock()
val := int64((1 + u.deviation - 2*u.deviat... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mathx
import (<|fim_suffix|>ing.T) {
const target = 10000
unstable := NewUnstable(0.05)
for i := 0; i < 1000; i++ {
val := unstable.AroundInt(target)
assert.True(t, float64(target)*0.95 <= float64(val))
assert.True(t, float64(val) <= float64(target)*1.05)
}
}
func TestUnstable_AroundIn... | fim | zeromicro/go-zero | go |
<|fim_suffix|>unterVec.
func NewCounterVec(cfg *CounterVecOpts) CounterVec {
if cfg == nil {
return nil
}
vec := prom.NewCounterVec(prom.CounterOpts{
Namespace: cfg.Namespace,
Subsystem: cfg.Subsystem,
Name: cfg.Name,
Help: cfg.Help,
}, cfg.Labels)
prom.MustRegister(vec)
cv := &promCounterVec... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ounterVec)
cv.Add(11, "/Users", "500")
cv.Add(22, "/Users", "500")
r := testutil.ToFloat64(cv.counter)
assert.Equal(t, float64(33), r)
}
func startAgent() {
prometheus.StartAgent(prometheus.Config{
Host: "127.0.0.1",
Port: 9101,
Path: "/metrics",
})
}
<|fim_prefix|>package metric
import (
"... | fim | zeromicro/go-zero | go |
<|fim_suffix|>v := &promGaugeVec{
gauge: vec,
}
proc.AddShutdownListener(func() {
gv.close()
})
return gv
}
func (gv *promGaugeVec) Add(v float64, labels ...string) {
update(func() {
gv.gauge.WithLabelValues(labels...).Add(v)
})
}
func (gv *promGaugeVec) Dec(labels ...string) {
update(func() {
gv.gaug... | fim | zeromicro/go-zero | go |
<|fim_suffix|>t, float64(666), r)
}
<|fim_prefix|>package metric
import (
"testing"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/proc"
)
func TestNewGaugeVec(t *testing.T) {
gaugeVec := NewGaugeVec(&GaugeVecOpts{
Namespace: "... | fim | zeromicro/go-zero | go |
<|fim_suffix|>l
}
vec := prom.NewHistogramVec(prom.HistogramOpts{
Namespace: cfg.Namespace,
Subsystem: cfg.Subsystem,
Name: cfg.Name,
Help: cfg.Help,
Buckets: cfg.Buckets,
ConstLabels: cfg.ConstLabels,
}, cfg.Labels)
prom.MustRegister(vec)
hv := &promHistogramVec{
histogram: ve... | fim | zeromicro/go-zero | go |
<|fim_suffix|>c.(*promHistogramVec).close()
hv, _ := histogramVec.(*promHistogramVec)
hv.Observe(2, "/Users")
hv.ObserveFloat(1.1, "/Users")
metadata := `
# HELP counts rpc server requests duration(ms).
# TYPE counts histogram
`
val := `
counts_bucket{method="/Users",le="1"} 0
counts_bucket{method="... | fim | zeromicro/go-zero | go |
<|fim_suffix|>
func update(fn func()) {
if !prometheus.Enabled() {
return
}
fn()
}
<|fim_prefix|>package metric
import "github.com/zeromicro/go-zero/core/prometheus"
// A VectorOpts is a general configuration.
type VectorOpts struct {
Namespace<|fim_middle|> string
Subsystem string
Name string
Help ... | fim | zeromicro/go-zero | go |
<|fim_suffix|> cfg.VecOpt.Labels,
)
prom.MustRegister(vec)
sv := &promSummaryVec{
summary: vec,
}
proc.AddShutdownListener(func() {
sv.close()
})
return sv
}
func (sv *promSummaryVec) Observe(v float64, labels ...string) {
update(func() {
sv.summary.WithLabelValues(labels...).Observe(v)
})
}
func (sv... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package metric
import (
"strings"
"testing"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/proc"
)
func TestNewSummaryVec(t *testing.T) {
summaryVec := NewSummaryVec(&SummaryVecOpts{
VecOpt<|fim_suffix|>rOpts{
... | fim | zeromicro/go-zero | go |
<|fim_suffix|>
}()
mCtx.mapper(item, writer)
}()
}
}
}
// mapReduceWithPanicChan maps all elements from source, and reduce the output elements with given reducer.
func mapReduceWithPanicChan[T, U, V any](source <-chan T, panicChan *onceChan, mapper MapperFunc[T, U],
reducer ReducerFunc[U, V], opts ...O... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mr
import (
"fmt"
"math/rand"
"runtime"
"strings"
"testing"
"ti<|fim_suffix|> writer.Write(total)
}, WithWorkers(workers%50+runtime.NumCPU()))
}
if genPanic || mapperPanic || reducerPanic {
var buf strings.Builder
buf.WriteString(fmt.Sprintf("n: %d", n))
buf.WriteString(f... | fim | zeromicro/go-zero | go |
//go:build fuzz
package mr
import (
"fmt"
"math/rand"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/threading"
"gopkg.in/cheggaaa/pb.v1"
)
// If Fuzz stuck, we don't know why, because it only returns hung or unexpected,
// so... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package mr
import (
"context"
"errors"
"fmt"
"runtime"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"go.uber.org/goleak"
)
var errDummy = errors.New("dummy")
func TestFinish(t *testing.T) {
defer goleak.VerifyNone(t)
var total uint32
err := Finish(func() error {
... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ce wraps the method Name.
type Namer interface {
Name() string
}
<|fim_prefix|>package naming
// Namer in<|fim_middle|>terfa<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_prefix|>package netx
import "net"
// InternalIp returns an internal ip.
func InternalIp() string {
infs, err := net.Interfaces()
if err <|fim_suffix|> return ipnet.IP.String()
}
}
}
}
return ""
}
func isEthDown(f net.Flags) bool {
return f&net.FlagUp != net.FlagUp
}
func isLoopback(f net.Fl... | fim | zeromicro/go-zero | go |
<|fim_suffix|>func TestInternalIp(t *testing.T) {
assert.True(t, len(InternalIp()) > 0)
}
<|fim_prefix|>package netx
import (
"testing"
"gi<|fim_middle|>thub.com/stretchr/testify/assert"
)
<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_suffix|> if ok {
return val
}
val = os.Getenv(name)
envLock.Lock()
envs[name] = val
envLock.Unlock()
return val
}
// EnvInt returns an int value of the given environment variable.
func EnvInt(name string) (int, bool) {
val := Env(name)
if len(val) == 0 {
return 0, false
}
n, err := strconv.Atoi(... | fim | zeromicro/go-zero | go |
<|fim_suffix|>t", "10")
val, ok = EnvInt("anyInt")
assert.Equal(t, 10, val)
assert.True(t, ok)
t.Setenv("anyString", "a")
val, ok = EnvInt("anyString")
assert.Equal(t, 0, val)
assert.False(t, ok)
}
<|fim_prefix|>package proc
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestEnv(t *testing.T... | fim | zeromicro/go-zero | go |
<|fim_prefix|>//go:build linux || darwin || freebsd
package proc
import (
"fmt"
"os"
"path"
"runtime/pprof"
"syscall"
"time"
"github.com/zeromicro/go-zero/core/logx"
)
const (
goroutineProfile = "goroutine"
debugLevel = 2
)
type creator interface {
Create(name string) (file *os.File, err error)
}
... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ns(buf.String(), ".dump"))
})
t.Run("fake file", func(t *testing.T) {
const msg = "any message"
buf := logtest.NewCollector(t)
err := errors.New(msg)
dumpGoroutines(fakeCreator{
file: &os.File{},
err: err,
})
assert.True(t, strings.Contains(buf.String(), msg))
})
}
type fakeCreator... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package proc
import (
"os"
"path/filepath"
)
var (
procName string
pid int
)
func init() {
procName = filepath.Base(os.Args[0])
pid = os.Getpid()
}
// Pid returns pid of current process.
func Pid() int {
return pid
}
// ProcessName returns the processname, s<|fim_suffix|>me.
func ProcessN... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package proc
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestProcessName(t *testing.T) {
assert.True(t, len(Pro<|fim_suffix|>e(t, Pid() > 0)
}
<|fim_middle|>cessName()) > 0)
}
func TestPid(t *testing.T) {
assert.Tru<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_suffix|>
<|fim_prefix|>//go:build windows
package proc
func StartProfile() Stopper {
return noopStopper<|fim_middle|>
}<|endoftext|> | fim | zeromicro/go-zero | go |
//go:build linux || darwin || freebsd
package proc
import (
"fmt"
"os"
"os/signal"
"path"
"runtime"
"runtime/pprof"
"runtime/trace"
"sync/atomic"
"syscall"
"time"
"github.com/zeromicro/go-zero/core/logx"
)
// DefaultMemProfileRate is the default memory profiling rate.
// See also http://golang.org/pkg/ru... | fim | zeromicro/go-zero | go |
<|fim_suffix|>.NotNil(t, StartProfile())
profiler.Stop()
// stop twice
profiler.Stop()
assert.True(t, strings.Contains(c.String(), ".pprof"))
}
<|fim_prefix|>package proc
import (
"strings"
"testing"
"github.co<|fim_middle|>m/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx/logtest"
)
func Te... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ws, lets callers call fn on their own.
func AddWrapUpListener(fn func()) func() {
return fn
}
// SetTimeToForceQuit does nothing on windows.
func SetTimeToForceQuit(duration time.Duration) {
}
// Setup does nothing on windows.
func Setup(conf ShutdownConf) {
}
// Shutdown does nothing on windows.
func... | fim | zeromicro/go-zero | go |
<|fim_suffix|>..", waitTime)
_ = syscall.Kill(syscall.Getpid(), sig)
}
type listenerManager struct {
lock sync.Mutex
waitGroup sync.WaitGroup
listeners []func()
}
func (lm *listenerManager) addListener(fn func()) (waitForCalled func()) {
lm.waitGroup.Add(1)
lm.lock.Lock()
lm.listeners = append(lm.listene... | fim | zeromicro/go-zero | go |
<|fim_suffix|> })
shutdownLock.Lock()
assert.Equal(t, time.Second*2, wrapUpTime)
assert.Equal(t, time.Second*30, waitTime)
shutdownLock.Unlock()
})
t.Run("valid time", func(t *testing.T) {
defer restoreSettings()
Setup(ShutdownConf{})
shutdownLock.Lock()
assert.Equal(t, defaultWrapUpTime, wrapUpTi... | fim | zeromicro/go-zero | go |
<|fim_prefix|>//go:build windows
package proc
import "context"
func Done() <-chan struct{} {
return con<|fim_suffix|>ne()
}
<|fim_middle|>text.Background().Do<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_suffix|>s the process quitting.
func Done() <-chan struct{} {
return done
}
func stopOnSignal() {
select {
case <-done:
// already closed
default:
close(done)
}
}
<|fim_prefix|>//go:build linux || darwin || freebsd
package proc
import (
"os"
"os/signal"
"syscall"
"time"
"github.com/zeromicro/go-... | fim | zeromicro/go-zero | go |
<|fim_suffix|>otNil(t, Done())
}
<|fim_prefix|>//go:build linux || darwin || freebsd
package proc
import (
"testing"
"github<|fim_middle|>.com/stretchr/testify/assert"
)
func TestDone(t *testing.T) {
select {
case <-Done():
assert.Fail(t, "should run")
default:
}
assert.N<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_prefix|>package pr<|fim_suffix|>() {
}
<|fim_middle|>oc
var noopStopper nilStopper
type (
// Stopper interface wraps the method Stop.
Stopper interface {
Stop()
}
nilStopper struct{}
)
func (ns nilStopper) Stop<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_suffix|>g"
func TestNopStopper(t *testing.T) {
// no panic
noopStopper.Stop()
}
<|fim_prefix|>package proc
im<|fim_middle|>port "testin<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_prefix|>package prof
import (
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/threading"
)
type (
profileSlot struct {
lifecount int64
lastcount int64
lifecycle int64
lastcycle int64
}
profileCenter struct {
lock sync... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package prof
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestReport(t *testing.T) {
assert.NotContains(t, gen<|fim_suffix|>s(t, generateReport(), "foo")
report("foo", time.Second)
}
<|fim_middle|>erateReport(), "foo")
report("foo", time.Second)
assert.Contain<|endoftext... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ProfilePoint{}
}
func (np *nullProfiler) Report(string, ProfilePoint) {
}
<|fim_prefix|>package prof
import "github.com/zeromicro/go-zero/core/utils"
type (
// A ProfilePoint is a profile time point.
ProfilePoint struct {
*utils.ElapsedTimer
}
// A Profiler interface represents a profiler that u... | fim | zeromicro/go-zero | go |
<|fim_suffix|>
p := newNullProfiler()
p.Start()
p.Report("foo", ProfilePoint{
ElapsedTimer: utils.NewElapsedTimer(),
})
}
<|fim_prefix|>package prof
import (
"testing"
"github.com/zeromicro/go-zero/core/utils"
)
func TestProfiler(t *testing.T) {
EnableProfiling()
Start()
Report("foo", Pro<|fim_middle|>fil... | fim | zeromicro/go-zero | go |
<|fim_suffix|>..time.Duration) {
displayStatsWithWriter(os.Stdout, interval...)
}
func displayStatsWithWriter(writer io.Writer, interval ...time.Duration) {
duration := defaultInterval
for _, val := range interval {
duration = val
}
go func() {
ticker := time.NewTicker(duration)
defer ticker.Stop()
for r... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package prof
import (
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestDisplayStats(t *testing.T) {
writer := &threadSafeBuffer{
buf: strings.Builder{},
}
<|fim_suffix|>byte) (n int, err error) {
b.lock.Lock()
defer b.lock.Unlock()
return b.buf.Write(p)
}
<|... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package prometheus
import (
"fmt"
"net/http"
"sync"
"github.com/prometheus/client_golang/<|fim_suffix|>tf("%s:%d", c.Host, c.Port)
logx.Infof("Starting prometheus agent at %s", addr)
if err := http.ListenAndServe(addr, nil); err != nil {
logx.Error(err)
}
})
})
}
<|fim_middle|>promet... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package<|fim_suffix|>// A Config is a prometheus config.
type Config struct {
Host string `json:",optional"`
Port int `json:",default=9101"`
Path string `json:",default=/metrics"`
}
<|fim_middle|> prometheus
<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_suffix|>++ {
index := atomic.AddUint64(&pusher.index, 1) % uint64(size)
target := pusher.pushers[index]
if err := target.Push(message); err != nil {
logx.Error(err)
} else {
return nil
}
}
return ErrNoAvailablePusher
}
<|fim_prefix|>package queue
import (
"errors"
"sync/atomic"
"github<|f... | fim | zeromicro/go-zero | go |
<|fim_suffix|>rt.Equal(t, ErrNoAvailablePusher, pusher.Push("item"))
}
<|fim_prefix|>package queue
import (
"fmt"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
)
func TestBalancedQueuePusher(t *testing.T) {
const numPushers = 100
var pushers []Pusher
var mockedPushers []*mockedPusher
for i := 0; i... | fim | zeromicro/go-zero | go |
<|fim_suffix|>es.
Consumer interface {
Consume(string) error
OnEvent(event any)
}
// ConsumerFactory defines the factory to generate consumers.
ConsumerFactory func() (Consumer, error)
)
<|fim_prefix|>package qu<|fim_middle|>eue
type (
// A Consumer interface represents a consumer that can consume string mes... | fim | zeromicro/go-zero | go |
<|fim_suffix|>sageQueue interface {
Start()
Stop()
}
<|fim_prefix|>package queue
<|fim_middle|>
// A MessageQueue interface represents a message queue.
type Mes<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_suffix|>tiPusher is a pusher that can push messages to multiple underlying pushers.
type MultiPusher struct {
name string
pushers []Pusher
}
// NewMultiPusher returns a MultiPusher.
func NewMultiPusher(pushers []Pusher) Pusher {
return &MultiPusher{
name: generateName(pushers),
pushers: pushers,
}
... | fim | zeromicro/go-zero | go |
package queue
import (
"fmt"
"math"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
)
func TestMultiQueuePusher(t *testing.T) {
const numPushers = 100
var pushers []Pusher
var mockedPushers []*mockedPusher
for i := 0; i < numPushers; i++ {
p := &mockedPusher{
name: "pusher:" + strconv.Itoa(i),... | fim | zeromicro/go-zero | go |
<|fim_suffix|>() (Producer, error)
)
<|fim_prefix|>package queue
type (
// A Producer interface represents a producer that produces messages.
Producer interface {
AddListener(listener ProduceListene<|fim_middle|>r)
Produce() (string, bool)
}
// A ProduceListener interface represents a produce listener.
Produ... | fim | zeromicro/go-zero | go |
package queue
import (
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/rescue"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/core/threading"
"github.com/zeromicro/go-zero/core/timex"
)
const queueName = "queue"
type ... | fim | zeromicro/go-zero | go |
<|fim_suffix|>.SetNumProducer(1)
q.pause()
q.resume()
go func() {
producer.wait.Wait()
q.Stop()
}()
q.Start()
assert.Equal(t, int32(rounds), atomic.LoadInt32(&consumer.count))
}
func TestQueue_Broadcast(t *testing.T) {
producer := newMockedProducer(math.MaxInt32)
consumer := newMockedConsumer()
consumer.w... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package queue
import "strings"
func generateName(pushers []Pusher<|fim_suffix|>tring {
names := make([]string, len(pushers))
for i, pusher := range pushers {
names[i] = pusher.Name()
}
return strings.Join(names, ",")
}
<|fim_middle|>) s<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_suffix|>
return result / float64(len(vals))
}
func calcVariance(mean float64, vals []int) float64 {
if len(vals) == 0 {
return 0
}
var result float64
for _, val := range vals {
result += math.Pow(float64(val)-mean, 2)
}
return result / float64(len(vals))
}
type mockedPusher struct {
name string
c... | fim | zeromicro/go-zero | go |
<|fim_suffix|>\n%s", p, debug.Stack())
}
}
<|fim_prefix|>package rescue
import (
"context"
"runtime/debug"
"github.com/zeromicro/go-zero/core/logx"
)
// Recover is used with defer to do cleanup on panics.
// Use it like:
//
// defer Recover(func() {})
func Recover(cleanups ...func()) {
for _, cleanup := range c... | fim | zeromicro/go-zero | go |
<|fim_suffix|>T) {
var count int32
assert.NotPanics(t, func() {
defer RecoverCtx(context.Background(), func() {
atomic.AddInt32(&count, 2)
}, func() {
atomic.AddInt32(&count, 3)
})
panic("hello")
})
assert.Equal(t, int32(5), atomic.LoadInt32(&count))
}
<|fim_prefix|>p<|fim_middle|>ackage rescue
impo... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ring) map[string]*node {
if len(route) > 0 && route[0] == colon {
return nd.children[1]
}
return nd.children[0]
}
func add(nd *node, route string, item any) error {
if len(route) == 0 {
if nd.item != nil {
return errDupItem
}
nd.item = item
return nil
}
if route[0] == slash {
retu... | fim | zeromicro/go-zero | go |
<|fim_prefix|>//go:build debug
package search
import "fmt"
func (t *Tree) Print() {
if t.root.item == nil {
fmt.Println("/")
} else {
fmt.Printf("/:%#v\n", t.root.item)
}
printNode(t.root, 1)
}
f<|fim_suffix|>v\n", string(indent), k, v.item)
}
printNode(v, depth+1)
}
}
}
<|fim_middle|>unc printNode... | fim | zeromicro/go-zero | go |
<|fim_suffix|>s)
assert.Equal(t, test.expect, actual)
}
})
}
}
func TestStrictSearch(t *testing.T) {
routes := []mockedRoute{
{"/api/users", 1},
{"/api/:layer", 2},
}
query := "/api/users"
tree := NewTree()
for _, r := range routes {
tree.Add(r.route, r.value)
}
for i := 0; i < 1000; i++ {
r... | fim | zeromicro/go-zero | go |
<|fim_suffix|>{
trace.StopAgent()
})
if len(sc.MetricsUrl) > 0 {
stat.SetReportWriter(stat.NewRemoteWriter(sc.MetricsUrl))
}
devserver.StartAgent(sc.DevServer)
profiling.Start(sc.Profiling)
return nil
}
func (sc ServiceConf) initMode() {
switch sc.Mode {
case DevMode, TestMode, RtMode, PreMode:
load.D... | fim | zeromicro/go-zero | go |
<|fim_suffix|>localhost:8080",
}
assert.NoError(t, c.SetUp())
}
<|fim_prefix|>package service
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/internal/devserver"
)
func <|fim_middle|>TestServiceConf(t *testing.T) {
c := ServiceConf... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package service
import (
"sync"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/threading"
)
type (
// Starter is the interface wraps the Start method.
Starter interface {
Start()
}
// Stopper is the interface wraps the Sto... | fim | zeromicro/go-zero | go |
<|fim_suffix|>Group
var lock sync.Mutex
wait.Add(len(multipliers))
group := NewServiceGroup()
for _, multiplier := range multipliers {
mul := multiplier
group.Add(WithStarter(mockedStarter{
fn: func() {
lock.Lock()
want *= mul
lock.Unlock()
wait.Done()
},
}))
}
go group.Start()
wait.... | fim | zeromicro/go-zero | go |
<|fim_suffix|>g) {
}
// SetReporter sets the given reporter.
func SetReporter(func(string)) {
}
<|fim_prefix|>//go:build !l<|fim_middle|>inux
package stat
// Report reports given message.
func Report(strin<|endoftext|> | fim | zeromicro/go-zero | go |
//go:build linux
package stat
import (
"flag"
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/executors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/sysx"
)
const (
clusterNameKey = "CLUSTER_NAME"
tes... | fim | zeromicro/go-zero | go |
<|fim_suffix|> count)
}
<|fim_prefix|>//go:build linux
package stat
import (
"strconv"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
)
func TestReport(t *testing.T) {
t.Setenv(clusterNameKey, "test-cluster")
var count int32
SetReporter(func(s string) {
atomic.AddInt32(&count, 1)
})
for i ... | fim | zeromicro/go-zero | go |
package internal
import (
"bufio"
"errors"
"fmt"
"math"
"os"
"path"
"strconv"
"strings"
"sync"
"time"
"github.com/zeromicro/go-zero/core/iox"
"github.com/zeromicro/go-zero/core/lang"
"golang.org/x/sys/unix"
)
const (
cgroupDir = "/sys/fs/cgroup"
cpuMaxFile = cgroupDir + "/cpu.max"
cpuStatFile = cg... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package internal
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRunningInUserNS(t *testing.T) {
// should be false in docker
assert.False(t, runningInUserNS())
}
func TestCgroups(t *testing.T) {
// test cgroup legacy(v1) & hybrid
if !isCgroup2UnifiedMode() {
cg, err ... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package internal
import (
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/zeromicro/go-zero/core/iox"
"github.com/zeromicro/go-zero/core/logx"
)
const (
cpuTicks = 100
cpuFields = 8
cpuMax = 1000
statFile = "/proc/stat"
)
var (
preSystem uint64
preTotal u<|fim_suffix|>err
}
pr... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package internal
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestRefreshCpu(t *testing.T) {
a<|fim_suffix|>eshCpu(b *testing.B) {
for i := 0; i < b.N; i++ {
RefreshCpu()
}
}
<|fim_middle|>ssert.NotPanics(t, func() {
RefreshCpu()
})
}
func BenchmarkRefr<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_suffix|>n linux.
func RefreshCpu() uint64 {
return 0
}
<|fim_prefix|>//go:build !linux
package internal
// RefreshCpu returns cpu usage, always returns 0 on systems other <|fim_middle|>tha<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_suffix|>
report.Median = float32(medianTask.Duration) / float32(time.Millisecond)
tenPercent := fiftyPercent / 5
if tenPercent > 0 {
top10pTasks := topK(top50pTasks, tenPercent)
task90th := top10pTasks[0]
report.Top90th = float32(task90th.Duration) / float32(time.Millisecond)
onePercent :... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package stat
import (
"errors"
"strconv"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/logx/logtest"
)
func TestMetrics(t *testing.T) {
DisableLog()
defer logEnabled.Set(true)
counts := []int{1, 5, 10, 100, 1000, 1000}
for _, count := range counts {... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package stat
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"time"
"github.com/zeromicro/go-zero/core/logx"
)
const (
httpTimeout = time.Second * 5
jsonContentType = "application/json; charset=utf-8"
)
// ErrWriteFailed is an error that indicates failed to submit a StatReport.
var Er... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package stat
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
"gopkg.in/h2non/gock.v1"
)
func TestRemoteWriter(t *testing.T) {
defer gock.Off()
gock.New("http://foo.com").Reply(200).BodyString("foo")
writer := NewRemoteWriter("http://foo.com")
err := writer.Write(&StatReport{
... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package stat
import "time"
<|fim_suffix|>// A Task is a task reported to Metrics.
type Task struct {
Drop bool
Duration time.Duration
Description string
}
<|fim_middle|>
<|endoftext|> | fim | zeromicro/go-zero | go |
package stat
import "container/heap"
type taskHeap []Task
func (h *taskHeap) Len() int {
return len(*h)
}
func (h *taskHeap) Less(i, j int) bool {
return (*h)[i].Duration < (*h)[j].Duration
}
func (h *taskHeap) Swap(i, j int) {
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
}
func (h *taskHeap) Push(x any) {
*h = append... | fim | zeromicro/go-zero | go |
<|fim_suffix|>ples = append(samples, task)
}
}
func TestTopK(t *testing.T) {
tasks := []Task{
{false, 1, "a"},
{false, 4, "a"},
{false, 2, "a"},
{false, 5, "a"},
{false, 9, "a"},
{false, 10, "a"},
{false, 12, "a"},
{false, 3, "a"},
{false, 6, "a"},
{false, 11, "a"},
{false, 8, "a"},
}
result... | fim | zeromicro/go-zero | go |
<|fim_suffix|>4(curUsage)*(1-beta))
atomic.StoreInt64(&cpuUsage, usage)
})
case <-allTicker.C:
if logEnabled.True() {
printUsage()
}
}
}
}()
}
// CpuUsage returns current cpu usage.
func CpuUsage() int64 {
return atomic.LoadInt64(&cpuUsage)
}
func bToMb(b uint64) float32 {
return floa... | fim | zeromicro/go-zero | go |
<|fim_suffix|>t := c.String()
assert.Contains(t, output, "CPU:")
assert.Contains(t, output, "MEMORY:")
assert.Contains(t, output, "Alloc=")
assert.Contains(t, output, "TotalAlloc=")
assert.Contains(t, output, "Sys=")
assert.Contains(t, output, "NumGC=")
lines := strings.Split(output, "\n")
assert.Len(t, lines,... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package builder
import (
"fmt"
"reflect"
"strings"
)
const dbTag = "db"
// RawFieldNames converts golang struct field into slice string.
func RawFieldNames(in any, postgreSql ...bool) []string {
out := make([]string, 0)
v := reflect.ValueOf(in)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
var... | fim | zeromicro/go-zero | go |
<|fim_suffix|>Tag struct {
ID string `db:"id" json:"id,omitempty"`
UserName string `db:"user_name" json:"userName,omitempty"`
Mobile string `db:"-" json:"mobile,omitempty"`
}
func TestFieldNamesWithDashTag(t *testing.T) {
t.Run("new", func(t *testing.T) {
var u mockedUserWithDashTag
out := RawFieldName... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package cache
import (
"context"
"errors"
"fmt"
"log"
"time"
"github.com/zeromicro/go-zero/core/errorx"
"github.com/zeromicro/go-zero/core/hash"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/syncx"
)
type (
// Cache interface is used to define the cache i... | fim | zeromicro/go-zero | go |
<|fim_suffix|>}
assert.Nil(t, c.Del())
for i := 0; i < total; i++ {
assert.Nil(t, c.Del(fmt.Sprintf("key/%d", i)))
}
for i := 0; i < total; i++ {
var val int
assert.True(t, c.IsNotFound(c.Get(fmt.Sprintf("key/%d", i), &val)))
assert.Equal(t, 0, val)
}
}
func TestCache_Balance(t *testing.T) {
const (
nu... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package cache
// CacheConf is an alias of ClusterConf.<|fim_suffix|>ype CacheConf = ClusterConf
<|fim_middle|>
t<|endoftext|> | fim | zeromicro/go-zero | go |
<|fim_prefix|>package cache
import (
"context"
"errors"
"fmt"
"math"
"math/rand"
"sync"
"time"
"github.com/zeromicro/go-zero/core/jsonx"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/mathx"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/core/stores/red... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package cache
import (
"errors"
"fmt"
"math/rand"
"runtime"
"strconv"
"sync"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/stretchr/testify/assert"
"github.com/zeromicro/go-zero/core/collection"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/ma... | fim | zeromicro/go-zero | go |
package cache
import "time"
const (
defaultExpiry = time.Hour * 24 * 7
defaultNotFoundExpiry = time.Minute
)
type (
// Options is used to store the cache options.
Options struct {
Expiry time.Duration
NotFoundExpiry time.Duration
}
// Option defines the method to customize an Options.
Opt... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package cache
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestCacheOptions(t *testing.T) {
t.Run("default options", func<|fim_suffix|>otFoundExpiry)
})
}
<|fim_middle|>(t *testing.T) {
o := newOptions()
assert.Equal(t, defaultExpiry, o.Expiry)
assert.Equal(t, defaul... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package cache
import (
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/ti<|fim_suffix|>it tests working,
// reside in internal package, doesn't matter.
Total uint64
Hit uint64
Miss uint64
DbFails uint64
}
// NewStat returns a Stat.
func... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package cache
import (
"testing"
"github.com/zeromicro/go-zero/core/timex"
)
func TestCacheStat_statLoop(t *testing.T) {
t.Run("stat loop total 0", func(t *testing.T) {
var stat Stat
ticker := timex.NewFakeTicker()
go stat.statLoop(ticker)
ticker.Tick()
ticker.Tick()
ticker.Stop()
}<|fi... | fim | zeromicro/go-zero | go |
<|fim_prefix|>package cache
import (
"fmt"
"sync/atomic"
"time"
"github.com/zeromicro/go-zero/core/collection"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/stat"
"github.com/zeromicro/go-zero/core/stringx"
"github.com/zeromicro/go-zero/c... | fim | zeromicro/go-zero | go |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.