utils

package
v0.2.28 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2025 License: AGPL-3.0 Imports: 70 Imported by: 4

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoNegativeResults is returned when no negative results are allowed
	ErrNoNegativeResults = errors.New("cannot calculate with no negative values")
)

Functions

func ArgSortDesc added in v0.2.16

func ArgSortDesc[T cmp.Ordered](values []T) []int

ArgSortDesc 返回float64切片降序排序后对应的原始索引

func ArrToMap

func ArrToMap[T1 comparable, T2 any](arr []T2, doMap func(T2) T1) map[T1][]T2

func ArrToStr added in v0.2.0

func ArrToStr[T any](arr []T, precFlt int) string

func AutoCorrPenalty

func AutoCorrPenalty(returns []float64) float64

AutoCorrPenalty Metric to account for auto correlation

func BuildOHLCV

func BuildOHLCV(arr []*banexg.Kline, toTFMSecs int64, preFire float64, resOHLCV []*banexg.Kline, fromTFMS, offMS int64, infoBy string) ([]*banexg.Kline, bool)

BuildOHLCV Build or update coarser grained OHLC arrays from transactions or sub OHLC arrays. Arr: List of sub OHLC. ToTFSecs: Specify the time granularity to be built, in milliseconds PreFire: The rate at which builds are triggered ahead of schedule; ResOHLCV: Existing array to be updated From TFSets: The interval between the arr subarrays passed in, calculated when not provided, in milliseconds OffMS: offset of alignment time 从交易或子OHLC数组中,构建或更新更粗粒度OHLC数组。 arr: 子OHLC列表。 toTFSecs: 指定要构建的时间粒度,单位:毫秒 preFire: 提前触发构建完成的比率; resOHLCV: 已有的待更新数组 fromTFSecs: 传入的arr子数组间隔,未提供时计算,单位:毫秒 offMS: 对齐时间的偏移

func CalcAssetActivityScore added in v0.2.22

func CalcAssetActivityScore(data []float64) float64

CalcAssetActivityScore 计算活跃度分数,订单太少,或者长时间无订单的得分低

func CalcAssetDrawDownScore added in v0.2.22

func CalcAssetDrawDownScore(values []float64) float64

CalcAssetDrawDownScore 计算资产净值曲线稳定性分数;返回[-1,1],1表示一路向上,-1表示一路向下

func CalcAssetLinearScore added in v0.2.22

func CalcAssetLinearScore(values []float64) float64

CalcAssetLinearScore 计算线性回归稳定性分数[-1~1],0表示无效

func CalcAssetStabilityScore added in v0.2.22

func CalcAssetStabilityScore(values []float64, method int) float64

CalcAssetStabilityScore 计算稳定性分数[-1~1],method=0自动,1仅回撤,2仅线性拟合

func CalcAssetStabilityScore32 added in v0.2.22

func CalcAssetStabilityScore32(values []float32, method int) float64

func CalcCorrMat

func CalcCorrMat(arrLen int, dataArr [][]float64, useChgRate bool) (*mat.SymDense, []float64, error)

CalcCorrMat calculate Correlation Matrix for given data

func CalcDrawDown added in v0.2.16

func CalcDrawDown(reals []float64, viewNum int) (float64, float64)

CalcDrawDown calculate drawDownRate & drawDownVal for input real assets

func CalcEnvsCorr added in v0.1.7

func CalcEnvsCorr(envs []*ta.BarEnv, hisNum int) (*mat.SymDense, []float64, error)

func CalcExpectancy

func CalcExpectancy(profits []float64) (float64, float64)

CalcExpectancy Calculate expected returns and risk return ratio 计算收益期望、风险回报率

func CalcMaxDrawDown

func CalcMaxDrawDown(profits []float64, initBalance float64) (float64, float64, int, int, float64, float64)

CalcMaxDrawDown Calculate maximum drawdown Calculate the maximum drawdown percentage position when initBalance is provided; No location provided for calculating the maximum loss Return: Maximum drawdown percentage, maximum drawdown amount, maximum value index, minimum value index, maximum value, minimum value 计算最大回撤 initBalance 提供时计算最大回撤百分比位置;未提供计算亏损最多时位置 返回:最大回撤百分比、最大回撤额、最大值索引、最小值索引、最大值、最小值

func Check

func Check(err error)

func ConvertArr

func ConvertArr[T1, T2 any](arr []T1, doMap func(T1) T2) []T2

func ConvertFloat64

func ConvertFloat64(i interface{}) float64

func ConvertInt64

func ConvertInt64(i interface{}) int64

func Copy

func Copy(srcFile, dstFile string) error

func CopyDir

func CopyDir(src, dst string) error
func CopySymLink(source, dest string) error

func CreateNumFile added in v0.1.24

func CreateNumFile(outDir string, prefix string, ext string) (*os.File, error)

func CronAlign added in v0.2.24

func CronAlign(scd cron.Schedule, stamp time.Time) time.Time

func CutMap

func CutMap[M ~map[K]V, K comparable, V any](m M, keys ...K) M

func DecArithMean

func DecArithMean(values []decimal.Decimal) (decimal.Decimal, error)

DecArithMean is the basic form of calculating an average. Divide the sum of all values by the length of values

func DecArrToFloats

func DecArrToFloats(arr []decimal.Decimal) []float64

func DecFinaGeomMean

func DecFinaGeomMean(values []decimal.Decimal) (decimal.Decimal, error)

DecFinaGeomMean is a modified geometric average to assess the negative returns of investments. It accepts It adds +1 to each This does impact the final figures as it is modifying values It is still ultimately calculating a geometric average which should only be compared to other financial geometric averages

func DecPow

func DecPow(x, y decimal.Decimal) decimal.Decimal

DecPow is lovely because shopspring decimal cannot handle ^0.x and instead returns 1

func DecSharpeRatio

func DecSharpeRatio(moReturns []decimal.Decimal, riskFree decimal.Decimal) (decimal.Decimal, error)

DecSharpeRatio use 252 as default periods to calculate annualize

func DecSharpeRatioAdv

func DecSharpeRatioAdv(moReturns []decimal.Decimal, riskFree decimal.Decimal, periods int, annualize, smart bool) (decimal.Decimal, error)

DecSharpeRatioAdv 计算夏普比率

moReturns 固定周期的收益率,一般用日收益率 riskFree 年华无风险收益率,不为0时periods必填 periods 一年中moReturns所用的周期总数量,对日收益率,股票市场一般252 smart true时启用相关性惩罚

func DecSharpeRatioBy

func DecSharpeRatioBy(moReturns []decimal.Decimal, riskFree decimal.Decimal, periods int, annualize bool) (decimal.Decimal, error)

func DecSharpeRatioSmart

func DecSharpeRatioSmart(moReturns []decimal.Decimal, riskFree decimal.Decimal, periods int, annualize bool) (decimal.Decimal, error)

func DecSortinoRatio

func DecSortinoRatio(moReturns []decimal.Decimal, riskFree decimal.Decimal) (decimal.Decimal, error)

func DecSortinoRatioAdv

func DecSortinoRatioAdv(moReturns []decimal.Decimal, riskFree decimal.Decimal, periods int, annualize, smart bool) (decimal.Decimal, error)

DecSortinoRatioAdv returns sortino ratio of backtest compared to risk-free

func DecSortinoRatioBy

func DecSortinoRatioBy(moReturns []decimal.Decimal, riskFree decimal.Decimal, periods int, annualize bool) (decimal.Decimal, error)

func DecSortinoRatioSmart

func DecSortinoRatioSmart(moReturns []decimal.Decimal, riskFree decimal.Decimal, periods int, annualize bool) (decimal.Decimal, error)

func DecStdDev

func DecStdDev(values []decimal.Decimal) (decimal.Decimal, error)

DecStdDev calculates standard deviation using population based calculation

func DecodeGobFile added in v0.1.31

func DecodeGobFile(path string, data any) *errs.Error

func DecryptData added in v0.2.22

func DecryptData(data []byte, keyStr string) ([]byte, error)

DecryptData decrypts data using AES-GCM with the provided key Key should be 16, 24 or 32 bytes for AES-128, AES-192 or AES-256

func DeepCopyMap

func DeepCopyMap(dst, src map[string]interface{})

func DelNetLock

func DelNetLock(key string, lockVal int32) *errs.Error

func DoHttp

func DoHttp(client *http.Client, req *http.Request) *banexg.HttpRes

func EncodeGob added in v0.1.31

func EncodeGob(path string, data any) *errs.Error

func EncryptData added in v0.2.22

func EncryptData(data []byte, keyStr string) ([]byte, error)

EncryptData encrypts data using AES-GCM with the provided key Key should be 16, 24 or 32 bytes for AES-128, AES-192 or AES-256

func EnsureDir

func EnsureDir(dir string, perm os.FileMode) error

func EqualIn

func EqualIn(a, b, thres float64) bool

EqualIn Determine whether two floats are approximately equal within a certain range 判断两个float是否在一定范围内近似相等

func EqualNearly

func EqualNearly(a, b float64) bool

EqualNearly Determine whether two floats are approximately equal and solve the problem of inequality caused by floating-point close reading 判断两个float是否近似相等,解决浮点精读导致不等

func Exists

func Exists(filePath string) bool

func FillOHLCVLacks added in v0.1.31

func FillOHLCVLacks(bars []*banexg.Kline, startMS, endMS, tfMSecs int64) ([]*banexg.Kline, int)

func FindSubPath added in v0.1.12

func FindSubPath(parDir, tgtName string, maxDepth int) (string, error)

FindSubPath searches for the first occurrence of a directory named tgtName within the specified workDir and its subdirectories up to two levels deep.

func FloatsToDecArr

func FloatsToDecArr(arr []float64) []decimal.Decimal

func FormatWithMap

func FormatWithMap(text string, args map[string]interface{}) string

func GcdInts

func GcdInts(numbers []int) int

GcdMultiple Calculate the greatest common divisor of all elements in a slice 计算一个切片中所有元素的最大公约数

func GenCorrImg

func GenCorrImg(m *mat.SymDense, title string, names []string, fontName string, fontSize float64) ([]byte, error)

func GetAddsRemoves added in v0.2.16

func GetAddsRemoves[T comparable](news, olds []T) ([]T, []T)

func GetFilesWithPrefix added in v0.1.7

func GetFilesWithPrefix(filePath string) ([]string, error)

func GetFontData

func GetFontData(name string) ([]byte, error)

func GetNetLock

func GetNetLock(key string, timeout int) (int32, *errs.Error)

func GetOpenFont

func GetOpenFont(name string) (*opentype.Font, error)

func GetServerData

func GetServerData(key string) (string, *errs.Error)

func GetSystemLanguage added in v0.1.25

func GetSystemLanguage() string

GetSystemLanguage returns the current system language code. Possible return values (ISO 639-1 with optional ISO 3166-1 country code): - en-US: English - zh-CN: Chinese (Simplified) ...

func HasBanConn added in v0.2.0

func HasBanConn() bool

func IntToBytes added in v0.1.24

func IntToBytes(n uint32) ([]byte, error)

IntToBytes convert uint32 to [4]byte

func IsDocker added in v0.1.14

func IsDocker() bool

func IsTextContent added in v0.1.12

func IsTextContent(data []byte) bool

IsTextContent 检查字节数组是否可能是文本内容 返回 true 表示可能是文本内容,false 表示可能是二进制内容

func KeysOfMap

func KeysOfMap[M ~map[K]V, K comparable, V any](m M) []K

func KlineToStr

func KlineToStr(klines []*banexg.Kline, loc *time.Location) [][]string

func MD5 added in v0.1.7

func MD5(data []byte) string

func MapToStr

func MapToStr[T any](m map[string]T, value bool, precFlt int) string

func MaskDBUrl added in v0.2.0

func MaskDBUrl(url string) string

MaskDBUrl 将数据库连接字符串中的敏感信息(用户名和密码)替换为***

func MergeYamlStr added in v0.1.12

func MergeYamlStr(paths []string, skips ...string) (string, error)

MergeYamlStr 合并多个yaml文件内容,保持键的顺序

func MovePath added in v0.1.12

func MovePath(src, tgt string) error

func NanInfTo added in v0.1.12

func NanInfTo(v, to float64) float64

func NearScore

func NearScore(x, mid, rate float64) float64

NearScore Formula: y=e ^ - abs (x-a) At the given maxAt, i.e. a, y takes its maximum value of 1, x moves towards both sides, y gradually approaches 0, and the slope decreases from large to small The default rate is 1, and when x is offset by 40, it decays by 70%; When rate>1, attenuation accelerates 公式:y=e^-abs(x-a) 在给定的maxAt即a处,y取最大值1,x向两侧移动,y逐渐趋近于0,斜率由大变小 rate默认1,x偏移40时,衰减70%;rate>1时,衰减加速

func NewCronScheduler added in v0.2.1

func NewCronScheduler(exp string) (cron.Schedule, error)

func NormalizeFloat64 added in v0.2.22

func NormalizeFloat64(values []float64, minBtm float64) []float64

NormalizeFloat64 归一化到minBtm-1范围

func NumSign

func NumSign(obj interface{}) int

NumSign Obtain the direction of numbers; 1, -1 or 0 获取数字的方向;1,-1或0

func OpenBrowser added in v0.1.22

func OpenBrowser(url string) error

func OpenBrowserDelay added in v0.1.22

func OpenBrowserDelay(url string, delayMS int)

func PadCenter

func PadCenter(s string, width int, padText string) string

func ParallelRun

func ParallelRun[T any](items []T, concurNum int, handle func(int, T) *errs.Error) *errs.Error

func PrintErr

func PrintErr(e error) string

func RandomStr added in v0.1.8

func RandomStr(length int) string

func ReadCSV

func ReadCSV(path string) ([][]string, *errs.Error)

func ReadChanBatch added in v0.2.17

func ReadChanBatch[T comparable](c chan T, withNil bool) []T

func ReadConfirm

func ReadConfirm(tips []string, ok, fail string, exitAny bool) bool

func ReadFileObjRange added in v0.2.11

func ReadFileObjRange(file *os.File, size int64, offset int64) ([]byte, int64, error)

func ReadFileRange added in v0.2.11

func ReadFileRange(filePath string, size int64, offset int64) ([]byte, int64, error)

func ReadFileTail added in v0.2.11

func ReadFileTail(filePath string, size int64, end int64) ([]byte, int64, error)

ReadFileTail 从文件尾部或指定位置从后向前读取

func ReadInput

func ReadInput(tips []string) (string, error)

func ReadScanner added in v0.2.18

func ReadScanner(out io.ReadCloser) *bufio.Scanner

func ReadTextFile added in v0.1.12

func ReadTextFile(path string) (string, *errs.Error)

func ReadXlsx

func ReadXlsx(path, sheet string) ([][]string, *errs.Error)

ReadXlsx use first if `sheet` is empty

func RemoveFromArr

func RemoveFromArr[T comparable](arr []T, it T, num int) []T

func RemovePath added in v0.2.17

func RemovePath(path string, recursive bool) error

func ReverseArr

func ReverseArr[T any](s []T)

func RoundSecsTF added in v0.1.33

func RoundSecsTF(secs int) string

func SecsToTfNum added in v0.2.0

func SecsToTfNum(secs int) (string, int)

func SendEmail added in v0.2.24

func SendEmail(task *EmailTask) error

SendEmail sends an email with attachments

func SendEmailTo added in v0.2.24

func SendEmailTo(subject, body string, toList ...string) error

SendEmailTo sends an email to a single recipient

func SetMailSender added in v0.2.18

func SetMailSender(host string, port int, username, password string)

func SetServerData

func SetServerData(args *KeyValExpire) *errs.Error

func Setup added in v0.2.12

func Setup() *errs.Error

func SharpeRatio

func SharpeRatio(moReturns []float64, riskFree float64) (float64, error)

func SharpeRatioAdv

func SharpeRatioAdv(moReturns []float64, riskFree float64, periods int, annualize, smart bool) (float64, error)

SharpeRatioAdv 计算夏普比率

moReturns 固定周期的收益率,一般用日收益率 riskFree 年华无风险收益率,不为0时periods必填 periods 一年中moReturns所用的周期总数量,对日收益率,股票市场一般252 smart true时启用相关性惩罚

func SharpeRatioBy

func SharpeRatioBy(moReturns []float64, riskFree float64, periods int, annualize bool) (float64, error)

func SharpeRatioSmart

func SharpeRatioSmart(moReturns []float64, riskFree float64, periods int, annualize bool) (float64, error)

func SnakeToCamel

func SnakeToCamel(input string) string

func SortinoRatio

func SortinoRatio(moReturns []float64, riskFree float64) (float64, error)

func SortinoRatioAdv

func SortinoRatioAdv(moReturns []float64, riskFree float64, periods int, annualize, smart bool) (float64, error)

func SortinoRatioBy

func SortinoRatioBy(moReturns []float64, riskFree float64, periods int, annualize bool) (float64, error)

func SortinoRatioSmart

func SortinoRatioSmart(moReturns []float64, riskFree float64, periods int, annualize bool) (float64, error)

func SplitLines added in v0.1.23

func SplitLines(text string) []string

func SplitSolid

func SplitSolid(text string, sep string, unique bool) []string

SplitSolid String segmentation, ignore empty strings in the return result 字符串分割,忽略返回结果中的空字符串

func SplitToMap added in v0.1.33

func SplitToMap(text string, sep string) map[string]bool

func StartCpuProfile added in v0.1.31

func StartCpuProfile(path string, port int) *errs.Error

func StartEmailWorker added in v0.2.18

func StartEmailWorker(queueSize int)

StartEmailWorker 启动邮件发送worker

func StdDevVolatility

func StdDevVolatility(data []float64, rate float64) float64

StdDevVolatility Calculate the standard deviation of K-line volatility Data: It should be a set of numbers with a slight fluctuation above and below the mean of 1 Rate: default 1. If you need to enlarge the difference, pass in a value between 1-1000 计算K线的波动性标准差

data: 应该是均值为1的上下轻微浮动的一组数
rate: 默认1,如需要放大差异,则传入1~1000之间的值

func UnionArr

func UnionArr[T comparable](arrs ...[]T) []T

func UniqueItems

func UniqueItems[T comparable](arr []T) ([]T, []T)

func ValsOfMap

func ValsOfMap[M ~map[K]V, K comparable, V any](m M) []V

func WriteCsvFile

func WriteCsvFile(path string, rows [][]string, compress bool) *errs.Error

func WriteFile

func WriteFile(path string, data []byte) *errs.Error

Types

type Attachment added in v0.2.24

type Attachment struct {
	// Filename 附件文件名(必填)
	Filename string
	// Content 附件内容(二选一:Content 或 FilePath)
	Content []byte
	// FilePath 附件文件路径(二选一:Content 或 FilePath)
	FilePath string
	// ContentType MIME类型,如果为空则自动检测
	ContentType string
}

Attachment 表示邮件附件

type BanConn

type BanConn struct {
	Conn    net.Conn               // Original socket connection 原始的socket连接
	Data    map[string]interface{} // Message subscription list 消息订阅列表
	Remote  string                 // Remote Name 远端名称
	Listens map[string]ConnCB      // Message processing function 消息处理函数

	RefreshMS int64 // Connection ready timestamp 连接就绪的时间戳
	Ready     bool
	IsReading bool

	DoConnect  func(conn *BanConn) // Reconnect function, no attempt to reconnect provided 重新连接函数,未提供不尝试重新连接
	ReInitConn func()              // Initialize callback function after successful reconnection 重新连接成功后初始化回调函数
	Fallback   ConnCB
	BadMsgCB   func(err *errs.Error)
	// contains filtered or unexported fields
}

func (*BanConn) Close added in v0.2.23

func (c *BanConn) Close() *errs.Error

func (*BanConn) CloseWaitChan added in v0.2.22

func (c *BanConn) CloseWaitChan(key string)

func (*BanConn) DeleteData added in v0.2.22

func (c *BanConn) DeleteData(tags ...string)

func (*BanConn) GetAesKey added in v0.2.23

func (c *BanConn) GetAesKey() string

func (*BanConn) GetData added in v0.2.22

func (c *BanConn) GetData(key string) (interface{}, bool)

func (*BanConn) GetRemote

func (c *BanConn) GetRemote() string

func (*BanConn) GetRemoteHost added in v0.2.22

func (c *BanConn) GetRemoteHost() string

func (*BanConn) GetWaitChan added in v0.2.22

func (c *BanConn) GetWaitChan(key string) (chan []byte, bool)

GetWaitChan get chan for key to wait or set

func (*BanConn) IsClosed

func (c *BanConn) IsClosed() bool

func (*BanConn) LoopPing added in v0.1.12

func (c *BanConn) LoopPing(intvSecs int)

LoopPing should be called from client

func (*BanConn) PopData added in v0.2.23

func (c *BanConn) PopData(key string) (interface{}, bool)

func (*BanConn) Read

func (c *BanConn) Read() ([]byte, *errs.Error)

func (*BanConn) ReadMsg

func (c *BanConn) ReadMsg() (*IOMsgRaw, *errs.Error)

func (*BanConn) RunForever

func (c *BanConn) RunForever() *errs.Error

RunForever Monitor the information sent by the connection and process it. According to the action of the message: Call the corresponding member function for processing; Directly input msd_data Or find the corresponding processing function from listeners. If there is an exact match, pass msd_data. Otherwise, pass action and msd_data Both the server-side and client-side will call this method 监听连接发送的信息并处理。 根据消息的action:

调用对应成员函数处理;直接传入msg_data
或从listens中找对应的处理函数,如果精确匹配,传入msg_data,否则传入action, msg_data

服务器端和客户端都会调用此方法

func (*BanConn) SendWaitRes added in v0.2.22

func (c *BanConn) SendWaitRes(key string, data interface{}) *errs.Error

func (*BanConn) SetAesKey added in v0.2.23

func (c *BanConn) SetAesKey(aesKey string)

func (*BanConn) SetData added in v0.2.22

func (c *BanConn) SetData(val interface{}, tags ...string)

func (*BanConn) SetWait added in v0.2.22

func (c *BanConn) SetWait(key string, size int) string

SetWait set chan for key to wait async

func (*BanConn) SetWaitResult added in v0.2.22

func (c *BanConn) SetWaitResult(key string, data []byte) error

SetWaitResult set result for key

func (*BanConn) WaitResult added in v0.2.22

func (c *BanConn) WaitResult(ctx context.Context, key string, timeout time.Duration) ([]byte, *errs.Error)

WaitResult wait result for key with specified timeout; wait __res__[key] to be trigger

func (*BanConn) Write

func (c *BanConn) Write(msg *IOMsgRaw) *errs.Error

func (*BanConn) WriteMsg

func (c *BanConn) WriteMsg(msg *IOMsg) *errs.Error

type ClientIO

type ClientIO struct {
	BanConn
	Addr string
}

func NewClientIO

func NewClientIO(addr, aesKey string) (*ClientIO, *errs.Error)

NewClientIO should call LoopPing & RunForever later

func (*ClientIO) GetVal

func (c *ClientIO) GetVal(key string, timeout int) (string, *errs.Error)

func (*ClientIO) SetVal

func (c *ClientIO) SetVal(args *KeyValExpire) *errs.Error

type Cluster

type Cluster struct {
	Center float64
	Items  []float64
}

type ClusterRes

type ClusterRes struct {
	Clusters []*Cluster
	RowGIds  []int
}

func KMeansVals

func KMeansVals(vals []float64, num int) *ClusterRes

type ConnCB

type ConnCB = func(msg *IOMsgRaw)

type EmailTask added in v0.2.18

type EmailTask struct {
	From    string
	To      []string // 支持多个收件人
	Subject string
	Body    string
	// Attachments 附件列表(可选)
	Attachments []Attachment
	// IsHTML 是否为HTML格式邮件(默认false为纯文本)
	IsHTML bool
}

EmailTask 表示一个邮件发送任务

func (*EmailTask) AttachFile added in v0.2.24

func (t *EmailTask) AttachFile(filePath string) error

func (*EmailTask) AttachFileBy added in v0.2.24

func (t *EmailTask) AttachFileBy(filename string, content []byte, contentType string)

type FnTaskPrg added in v0.1.21

type FnTaskPrg = func(task string, rate float64)

type IBanConn

type IBanConn interface {
	WriteMsg(msg *IOMsg) *errs.Error
	Write(msg *IOMsgRaw) *errs.Error
	ReadMsg() (*IOMsgRaw, *errs.Error)

	SetData(val interface{}, tags ...string)
	GetData(key string) (interface{}, bool)
	PopData(key string) (interface{}, bool)
	DeleteData(tags ...string)
	SetAesKey(aesKey string)
	GetAesKey() string

	SetWait(key string, size int) string
	GetWaitChan(key string) (chan []byte, bool)
	CloseWaitChan(key string)
	SendWaitRes(key string, data interface{}) *errs.Error
	WaitResult(ctx context.Context, key string, timeout time.Duration) ([]byte, *errs.Error)

	GetRemote() string
	GetRemoteHost() string
	IsClosed() bool
	RunForever() *errs.Error
	Close() *errs.Error
}

type IOKeyVal

type IOKeyVal struct {
	Key string `json:"key"`
	Val string `json:"val"`
}

type IOMsg

type IOMsg struct {
	Action    string      `json:"action"`
	Data      interface{} `json:"data"`
	NoEncrypt bool        `json:"no_encrypt"`
}

func (*IOMsg) Marshal added in v0.2.22

func (msg *IOMsg) Marshal(aesKey string) (*IOMsgRaw, *errs.Error)

type IOMsgRaw added in v0.1.12

type IOMsgRaw struct {
	Action    string `json:"action"`
	Data      []byte `json:"data"`
	NoEncrypt bool   `json:"no_encrypt"`
}

type KeyValExpire

type KeyValExpire struct {
	Key        string
	Val        string
	ExpireSecs int `json:"expireSecs"`
}

type MailSender added in v0.2.18

type MailSender struct {
	// contains filtered or unexported fields
}

func NewMailSender added in v0.2.18

func NewMailSender(host string, port int, username, password string) *MailSender

func (*MailSender) SendMail added in v0.2.18

func (ms *MailSender) SendMail(from string, to []string, subject, body string, attachments []Attachment, isHTML bool) error

type PrgBar

type PrgBar struct {
	DoneNum  int
	TotalNum int
	Last     int64 // for outer usage
	PrgCbs   []PrgCB
	// contains filtered or unexported fields
}

func NewPrgBar

func NewPrgBar(totalNum int, title string) *PrgBar

func (*PrgBar) Add

func (p *PrgBar) Add(num int)

func (*PrgBar) Close

func (p *PrgBar) Close()

func (*PrgBar) NewJob

func (p *PrgBar) NewJob(num int) *PrgBarJob

type PrgBarJob

type PrgBarJob struct {
	*PrgBar
	// contains filtered or unexported fields
}

func (*PrgBarJob) Add

func (j *PrgBarJob) Add(num int)

func (*PrgBarJob) Done

func (j *PrgBarJob) Done()

type PrgCB added in v0.1.12

type PrgCB = func(done int, total int)

type PrgTask added in v0.1.21

type PrgTask struct {
	ID       int
	Name     string
	Progress float64
	Weight   float64
}

type ServerIO

type ServerIO struct {
	Addr string

	Conns      []IBanConn
	Data       map[string]string // Cache data available for remote access 缓存的数据,可供远程端访问
	DataExp    map[string]int64  // Cache data expiration timestamp, 13 bits 缓存数据的过期时间戳,13位
	InitConn   func(*BanConn)
	OnConnExit func(*BanConn, *errs.Error)
	// contains filtered or unexported fields
}

func NewBanServer

func NewBanServer(addr, aesKey string) *ServerIO

func (*ServerIO) Broadcast

func (s *ServerIO) Broadcast(msg *IOMsg) *errs.Error

func (*ServerIO) GetVal

func (s *ServerIO) GetVal(key string) string

func (*ServerIO) RunForever

func (s *ServerIO) RunForever(intvSecs, timeoutSecs int) *errs.Error

func (*ServerIO) SetVal

func (s *ServerIO) SetVal(args *KeyValExpire)

func (*ServerIO) WrapConn

func (s *ServerIO) WrapConn(conn net.Conn) *BanConn

type StagedPrg added in v0.1.21

type StagedPrg struct {
	Progress float64 // [0,1]
	// contains filtered or unexported fields
}

func NewStagedPrg added in v0.1.21

func NewStagedPrg(tasks []string, weights []float64) *StagedPrg

NewStagedPrg 创建多任务复合进度提示器 tasks: 子任务代码列表,按执行顺序,不可重复 weights: 各个子任务权重,>0,内部会自动归一化

func (*StagedPrg) AddTrigger added in v0.1.21

func (p *StagedPrg) AddTrigger(name string, cb FnTaskPrg)

func (*StagedPrg) DelTrigger added in v0.1.21

func (p *StagedPrg) DelTrigger(name string)

func (*StagedPrg) SetMinInterval added in v0.1.21

func (p *StagedPrg) SetMinInterval(intvMSecs int)

func (*StagedPrg) SetProgress added in v0.1.21

func (p *StagedPrg) SetProgress(task string, progress float64)

type ValIdx added in v0.2.16

type ValIdx[T cmp.Ordered] struct {
	Val T
	Idx int
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL