text stringlengths 11 4.05M |
|---|
package exceltitle
import (
"bytes"
"math"
)
/*
1 A 0*26 + 1
26 Z 0*26 + 26
27 AA 1*26 + 1
52 AZ 1*26 + 26
53 BA 2*26 + 1
701 ZY 26*26 + 25
702 ZZ 26*26 + 26
703 AAA 1*678 + 1*26 + 1
*/
var placeValues = make(map[int]int)
// excelDigits finds the number of excel digits in a number
func excelDigits(n int) int {
if n < 1 {
return 0
}
aa := 1 // aa represents numbers that can be written with A's only
digits := 0
placeValue := 1
for aa <= n {
placeValues[digits] = placeValue
digits++
placeValue = int(math.Pow(26.0, float64(digits)))
aa += placeValue
}
return digits
}
func convertToTitle(n int) string {
digits := excelDigits(n)
var b bytes.Buffer
for i := digits - 1; i >= 0; i-- {
pv := placeValues[i]
val := n / pv
n -= val * pv
if i > 0 && n == 0 {
// Special case. as we want Z=26
val--
n = 26
}
r := 'A' + rune(val-1)
b.WriteRune(r)
}
return b.String()
}
|
package endpoint
import (
"errors"
"github.com/skidder/streammarker-writer/config"
"github.com/skidder/streammarker-writer/db"
"github.com/skidder/streammarker-writer/msg"
"golang.org/x/net/context"
)
// MessageWriter provides functions for writing messages to storage
type MessageWriter interface {
Run(context.Context, interface{}) (interface{}, error)
}
type messageWriter struct {
measurementWriter db.MeasurementWriter
deviceManager db.DeviceManager
}
// NewMessageWriter creates a new healthcheck
func NewMessageWriter(c *config.Configuration) MessageWriter {
return &messageWriter{c.MeasurementWriter, c.DeviceManager}
}
func (h *messageWriter) Run(ctx context.Context, i interface{}) (interface{}, error) {
request, ok := i.(*msg.SensorReadingQueueMessage)
if !ok {
return nil, errors.New("Bad cast of request value")
}
if err := h.measurementWriter.WriteSensorReading(request); err != nil {
return nil, err
}
return nil, nil
}
|
package webapp
import (
"github.com/dblokhin/config"
"context"
"errors"
)
// key is used by context.Context
type key int
const (
keyParams key = iota
keyClient
keyCSRFToken
)
var (
noClientError = errors.New("no client data")
noConfig = errors.New("error on load app config")
noInstance = errors.New("no webapp instance")
)
// Webapp main container of webapp
type Webapp struct {
context.Context
}
// New creates app context
func New() Webapp {
return Webapp{context.Background()}
}
// Config returns config data from app context
func Config(app context.Context) *config.ConfigData {
return config.Config(app)
} |
package query
import (
"encoding/json"
"net/http"
"github.com/gorilla/mux"
)
func Configure(router *mux.Router) {
router.HandleFunc("/account/{id}", getAccount).Methods("GET")
}
func handleAccountCreated(evt AccountCreated) {
writeAccount(BankAccount{
Name: evt.Name,
Balance: evt.Balance,
})
}
func getAccount(resp http.ResponseWriter, req *http.Request) {
id, _ := mux.Vars(req)["id"]
account := findAccount(id)
val, _ := json.Marshal(account)
resp.Write(val)
}
|
package game
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"sort"
"strconv"
"time"
dbfile "github.com/HanYu1983/gomod/lib/db/file"
"github.com/HanYu1983/gomod/lib/tool"
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
)
var _ = time.Millisecond
func CreateUser(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
w.Header().Set("Content-Type", "application/json; charset=utf8")
defer tool.Recover(func(err error) {
Output(w, nil, err.Error())
})
if r.Method == "GET" {
gameCtx, err := LoadGameContext(ctx)
tool.Assert(tool.IfError(err))
Output(w, gameCtx.Users, nil)
return
}
form, err := tool.ReadAjaxPost(r)
tool.Assert(tool.IfError(err))
tool.Assert(tool.ParameterIsNotExist(form, "FBID"))
fbid := form["FBID"][0]
tool.Assert(tool.ParameterIsNotExist(form, "Name"))
err = WithTransaction(ctx, 3, func(ctx context.Context) error {
gameCtx, err := LoadGameContext(ctx)
if err != nil {
return err
}
name := form["Name"][0]
user := gameCtx.User(fbid)
user.Name = name
gameCtx.EditUser(user)
err = SaveGameContext(ctx, gameCtx)
return err
})
tool.Assert(tool.IfError(err))
Output(w, nil, nil)
}
func CreateRoom(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf8")
defer tool.Recover(func(err error) {
Output(w, nil, err.Error())
})
ctx := appengine.NewContext(r)
if r.Method == "GET" {
gameCtx, err := LoadGameContext(ctx)
tool.Assert(tool.IfError(err))
Output(w, gameCtx.Rooms, nil)
return
}
form, err := tool.ReadAjaxPost(r)
tool.Assert(tool.IfError(err))
tool.Assert(tool.ParameterIsNotExist(form, "ID"))
id := form["ID"][0]
tool.Assert(tool.ParameterIsNotExist(form, "Name"))
err = WithTransaction(ctx, 3, func(ctx context.Context) error {
gameCtx, err := LoadGameContext(ctx)
if err != nil {
return err
}
name := form["Name"][0]
room := gameCtx.Room(id)
room.Name = name
gameCtx.EditRoom(room)
err = SaveGameContext(ctx, gameCtx)
return err
})
tool.Assert(tool.IfError(err))
Output(w, nil, nil)
}
func EnterRoom(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf8")
defer tool.Recover(func(err error) {
Output(w, nil, err.Error())
})
ctx := appengine.NewContext(r)
if r.Method == "GET" {
gameCtx, err := LoadGameContext(ctx)
tool.Assert(tool.IfError(err))
Output(w, gameCtx.Rooms, nil)
return
}
form, err := tool.ReadAjaxPost(r)
tool.Assert(tool.IfError(err))
tool.Assert(tool.ParameterIsNotExist(form, "FBID"))
fbid := form["FBID"][0]
tool.Assert(tool.ParameterIsNotExist(form, "Room"))
err = WithTransaction(ctx, 3, func(ctx context.Context) error {
gameCtx, err := LoadGameContext(ctx)
if err != nil {
return err
}
roomKey := form["Room"][0]
user := gameCtx.User(fbid)
room := gameCtx.Room(roomKey)
user.Room = room.Key
gameCtx.EditUser(user)
err = SaveGameContext(ctx, gameCtx)
return err
})
tool.Assert(tool.IfError(err))
Output(w, nil, nil)
}
func LeaveMessage(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf8")
defer tool.Recover(func(err error) {
Output(w, nil, err.Error())
})
ctx := appengine.NewContext(r)
if r.Method == "GET" {
gameCtx, err := LoadGameContext(ctx)
tool.Assert(tool.IfError(err))
Output(w, gameCtx.Messages, nil)
return
}
form, err := tool.ReadAjaxPost(r)
tool.Assert(tool.IfError(err))
tool.Assert(tool.ParameterIsNotExist(form, "FBID"))
tool.Assert(tool.ParameterIsNotExist(form, "TargetUser"))
tool.Assert(tool.ParameterIsNotExist(form, "Content"))
tool.Assert(tool.ParameterIsNotExist(form, "UnixTime"))
fbid := form["FBID"][0]
targetUser := form["TargetUser"][0]
content := form["Content"][0]
unixTime, err := strconv.ParseInt(form["UnixTime"][0], 10, 64)
tool.Assert(tool.IfError(err))
err = WithTransaction(ctx, 3, func(ctx context.Context) error {
gameCtx, err := LoadGameContext(ctx)
if err != nil {
return err
}
user := gameCtx.FindUser(targetUser)
if user == EmptyUser {
return errors.New(fmt.Sprintf("user not found:%v", targetUser))
}
msg := Message{
FromUser: fbid,
ToUser: targetUser,
Content: content,
Time: time.Unix(unixTime, 0),
}
gameCtx.LeaveMessage(msg)
err = SaveGameContext(ctx, gameCtx)
return err
})
tool.Assert(tool.IfError(err))
Output(w, nil, nil)
}
func Clear(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf8")
defer tool.Recover(func(err error) {
Output(w, nil, err.Error())
})
ctx := appengine.NewContext(r)
err := datastore.RunInTransaction(ctx, func(ctx context.Context) error {
gameCtx, err := LoadGameContext(ctx)
if err != nil {
return err
}
gameCtx = Context{}
err = SaveGameContext(ctx, gameCtx)
return err
}, nil)
tool.Assert(tool.IfError(err))
Output(w, nil, nil)
}
func State(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf8")
defer tool.Recover(func(err error) {
Output(w, nil, err.Error())
})
ctx := appengine.NewContext(r)
gameCtx, err := LoadGameContext(ctx)
tool.Assert(tool.IfError(err))
Output(w, gameCtx, nil)
}
func LongPollingTargetMessage(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf8")
defer tool.Recover(func(err error) {
Output(w, nil, err.Error())
})
ctx := appengine.NewContext(r)
var _ = ctx
r.ParseForm()
tool.Assert(tool.ParameterIsNotExist(r.Form, "FBID"))
tool.Assert(tool.ParameterIsNotExist(r.Form, "Maxtime"))
fbid := r.Form["FBID"][0]
// use long polling tech if maxtime > 1
maxtime, err := strconv.Atoi(r.Form["Maxtime"][0])
tool.Assert(tool.IfError(err))
retCh, errCh := make(chan []Message), make(chan error)
go func() {
defer close(retCh)
defer close(errCh)
var times int
var ok bool
for times < maxtime {
// 忽略回傳的任何錯誤,直到timeout或取得資料
datastore.RunInTransaction(ctx, func(ctx context.Context) error {
gameCtx, err := LoadGameContext(ctx)
if err != nil {
return err
}
user := gameCtx.FindUser(fbid)
if user == EmptyUser {
// user not found, ignore this case
ok = true
} else {
msgs := gameCtx.MessagesToUser(user)
if len(msgs) > 0 {
gameCtx.DeleteMessage(msgs)
err = SaveGameContext(ctx, gameCtx)
sort.Sort(ByTime(msgs))
retCh <- msgs
ok = true
}
}
return err
}, nil)
if ok == true {
break
} else {
if maxtime > 1 {
time.Sleep(1 * time.Second)
}
times += 1
}
}
if times == maxtime {
errCh <- errors.New("times out")
}
}()
select {
case err := <-errCh:
tool.Assert(tool.IfError(err))
case ret := <-retCh:
Output(w, ret, nil)
}
}
func WithTransaction(ctx context.Context, retry int, fn func(c context.Context) error) error {
var err error
var times int
for times < retry {
err = datastore.RunInTransaction(ctx, fn, nil)
if err == datastore.ErrConcurrentTransaction {
// redo RunTransaction
} else {
break
}
times += 1
}
return err
}
var gameContextPosition int64
func InitContext(gameContextPosition_ int64) {
gameContextPosition = gameContextPosition_
}
func LoadGameContext(ctx context.Context) (Context, error) {
file, err := dbfile.GetFile(ctx, gameContextPosition)
if err != nil {
return Context{}, err
}
var gameCtx Context
err = json.Unmarshal(file.Content, &gameCtx)
if err != nil {
return Context{}, err
}
return gameCtx, nil
/*
files, _, err := dbfile.QueryKeys( ctx, 0, "root" )
if err != nil {
return Context{}, err
}
if len( files ) == 0 {
return Context{}, errors.New("root dir isn't exist")
}
rootDir := files[0].Key
files, _, err = dbfile.QueryKeys( ctx, rootDir, "card" )
if err != nil {
return Context{}, err
}
if len( files ) == 0 {
return Context{}, errors.New("card dir isn't exist")
}
cardDir := files[0].Key
files, _, err = dbfile.QueryKeys( ctx, cardDir, "gameContext.json" )
if err != nil {
return Context{}, err
}
if len( files ) == 0 {
return Context{}, errors.New("root/card/gameContext.json isn't exist")
}
var gameCtx Context
err = json.Unmarshal( files[0].Content, &gameCtx )
if err != nil {
return Context{}, err
}
return gameCtx, nil
*/
}
func SaveGameContext(ctx context.Context, gameCtx Context) error {
data, err := json.Marshal(gameCtx)
if err != nil {
return err
}
file, err := dbfile.GetFile(ctx, gameContextPosition)
if err != nil {
return err
}
_, err = dbfile.MakeFile(ctx, file.Position, file.Name, []byte(data), true, "")
if err != nil {
return err
}
return nil
/*
files, _, err := dbfile.QueryKeys( ctx, 0, "root" )
if err != nil {
return err
}
if len( files ) == 0 {
return errors.New("root dir isn't exist")
}
rootDir := files[0].Key
files, _, err = dbfile.QueryKeys( ctx, rootDir, "card" )
if err != nil {
return err
}
if len( files ) == 0 {
return errors.New("card dir isn't exist")
}
cardDir := files[0].Key
data, err := json.Marshal( gameCtx )
if err != nil {
return err
}
_, err = dbfile.MakeFile( ctx, cardDir, "gameContext.json", []byte(data), true )
if err != nil {
return err
}
return nil
*/
}
type Result struct {
Info interface{}
Error interface{}
}
func Output(w http.ResponseWriter, info, err interface{}) {
ret := Result{
Info: info,
Error: err,
}
jsonstr, _ := json.Marshal(ret)
fmt.Fprintf(w, "%s", string(jsonstr))
}
|
package main
import (
"flag"
"fmt"
"github.com/shybily/beansproxy/resources"
"github.com/shybily/beansproxy/server"
"os"
)
var (
config string
)
func main() {
flag.StringVar(&config, "config", "", "config file")
flag.Parse()
if len(config) <= 0 {
flag.Usage()
os.Exit(1)
}
opt, err := server.NewYamlProxyOptions(config)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
resources.InitInstance(opt.Instances, opt.Strategy)
_ = (server.NewProxyServer(opt)).Listen()
}
|
package client
import (
"IMServer/internal/client/conf"
"io"
"net"
"gogit.oa.com/March/gopkg/protocol/bypack"
"gogit.oa.com/March/gopkg/util"
)
func Run() {
reader := SendAndRecv(buffer888())
conf.L.Info(reader.String())
}
func Send(data []byte) {
_, err := Conn().Write(data)
util.MustNil(err)
}
func SendAndRecv(data []byte) *bypack.Reader {
conn := Conn()
_, err := conn.Write(data)
util.MustNil(err)
hb := make([]byte, bypack.HeaderSize)
_, err = io.ReadFull(conn, hb)
util.MustNil(err)
header, err := bypack.NewHeader(hb)
util.MustNil(err)
body := make([]byte, header.GetSize())
n, err := io.ReadFull(conn, body)
util.MustNil(err)
return bypack.NewReader(header.GetCmd(), body[:n])
}
func Conn() net.Conn {
conn, err := net.Dial("tcp", conf.Conf.Client.Addr)
util.MustNil(err)
return conn
}
|
package main
import (
"compress/bzip2"
"io"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"github.com/cheuka/dota-parser/dota2"
"github.com/cheuka/dota-parser/getStats"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
func main() {
//demFileName := decompressBzip2ToDemFile("C:/2545299883.dem.bz2")
//textAGame(demFileName)
textAGame("C:/dota2replay/2655449401.dem")
//writeToDB("root:123456@/dota2_new_stats?charset=utf8&parseTime=True&loc=Local", "C:/TI6/")
//writeToDB("root:123456@/dota2_new_stats_for_cn?charset=utf8&parseTime=True&loc=Local", "D:/replays/")
// draw()
}
func decompressBzip2ToDemFile(bz2FileName string) string {
var demFileName string
demFileName = strings.TrimSuffix(bz2FileName, ".bz2")
bizFile, err := os.Open(bz2FileName)
if err != nil {
log.Fatalf("打开录像压缩文件失败: %s", err)
}
defer bizFile.Close()
demFile, err := os.Create(demFileName)
if err != nil {
log.Fatalf("创建录像文件失败: %s", err)
}
bzip2Reader := bzip2.NewReader(bizFile)
if err != nil {
log.Fatalf("解压录像文件失败: %s", err)
}
io.Copy(demFile, bzip2Reader)
return demFileName
}
func textAGame(fileName string) {
f, err := os.Open(fileName)
if err != nil {
log.Fatalf("打开比赛录像失败: %s", err)
}
defer f.Close()
allHeroStats, err := getStats.GetStats(f)
if err != nil {
log.Fatalf("解析录像失败: %s", err)
}
log.Printf("英雄对敌方英雄造成的伤害统计:\n")
for _, v := range allHeroStats {
log.Printf("%s(Steamid=%d)——总伤害:%d,致死伤害:%d,致死控制时间:%.2f, 单杀/被单杀/被单抓次数: %d/%d/%d, \n", v.HeroName, v.Steamid, v.CreateTotalDamages, v.CreateDeadlyDamages, v.CreateDeadlyStiffControl, v.AloneKilledNum, v.AloneBeKilledNum, v.AloneBeCatchedNum)
}
}
func writeToDB(dbPath, replayDir string) {
getStats.SetDebug(false)
db, err := gorm.Open("mysql", dbPath)
if err != nil {
log.Printf("failed to connect database\n")
}
defer db.Close()
db.AutoMigrate(&dota2.Stats{})
dir, err := ioutil.ReadDir(replayDir)
if err != nil {
log.Printf("failed to open dir\n")
}
for i, aFile := range dir {
aRepaly := replayDir + aFile.Name()
matchID, _ := strconv.ParseUint(strings.TrimSuffix(aFile.Name(), ".dem"), 10, 64)
log.Printf("正在解析第%d个录像:%d", i+1, matchID)
f, err := os.Open(aRepaly)
if err != nil {
log.Fatalf("打开比赛录像失败: %s", err)
}
defer f.Close()
allHeroStats, err := getStats.GetStats(f)
if err != nil {
log.Fatalf("解析录像失败: %s", err)
}
//写结果到数据库
for _, aHeroStats := range allHeroStats {
aHeroStats.MatchId = matchID
db.Create(aHeroStats)
}
}
}
|
package management
import (
"context"
"math/rand"
"sync/atomic"
)
const (
// Indicates how many log messages the listener will hold before dropping.
// Provides a throttling mechanism to drop latest messages if the sender
// can't keep up with the influx of log messages.
logWindow = 30
)
// session captures a streaming logs session for a connection of an actor.
type session struct {
// Indicates if the session is streaming or not. Modifying this will affect the active session.
active atomic.Bool
// Allows the session to control the context of the underlying connection to close it out when done. Mostly
// used by the LoggerListener to close out and cleanup a session.
cancel context.CancelFunc
// Actor who started the session
actor actor
// Buffered channel that holds the recent log events
listener chan *Log
// Types of log events that this session will provide through the listener
filters *StreamingFilters
// Sampling of the log events this session will send (runs after all other filters if available)
sampler *sampler
}
// NewSession creates a new session.
func newSession(size int, actor actor, cancel context.CancelFunc) *session {
s := &session{
active: atomic.Bool{},
cancel: cancel,
actor: actor,
listener: make(chan *Log, size),
filters: &StreamingFilters{},
}
return s
}
// Filters assigns the StreamingFilters to the session
func (s *session) Filters(filters *StreamingFilters) {
if filters != nil {
s.filters = filters
sampling := filters.Sampling
// clamp the sampling values between 0 and 1
if sampling < 0 {
sampling = 0
}
if sampling > 1 {
sampling = 1
}
s.filters.Sampling = sampling
if sampling > 0 && sampling < 1 {
s.sampler = &sampler{
p: int(sampling * 100),
}
}
} else {
s.filters = &StreamingFilters{}
}
}
// Insert attempts to insert the log to the session. If the log event matches the provided session filters, it
// will be applied to the listener.
func (s *session) Insert(log *Log) {
// Level filters are optional
if s.filters.Level != nil {
if *s.filters.Level > log.Level {
return
}
}
// Event filters are optional
if len(s.filters.Events) != 0 && !contains(s.filters.Events, log.Event) {
return
}
// Sampling is also optional
if s.sampler != nil && !s.sampler.Sample() {
return
}
select {
case s.listener <- log:
default:
// buffer is full, discard
}
}
// Active returns if the session is active
func (s *session) Active() bool {
return s.active.Load()
}
// Stop will halt the session
func (s *session) Stop() {
s.active.Store(false)
}
func contains(array []LogEventType, t LogEventType) bool {
for _, v := range array {
if v == t {
return true
}
}
return false
}
// sampler will send approximately every p percentage log events out of 100.
type sampler struct {
p int
}
// Sample returns true if the event should be part of the sample, false if the event should be dropped.
func (s *sampler) Sample() bool {
return rand.Intn(100) <= s.p
}
|
package backup
import (
"encoding/json"
"fp-dynamic-elements-manager-controller/api/util"
"fp-dynamic-elements-manager-controller/internal/backup"
"fp-dynamic-elements-manager-controller/internal/backup/structs"
notificationfuncs "fp-dynamic-elements-manager-controller/internal/notification"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
"net/http"
)
// Handler handles requests to the backup and restore provider, it accepts PostedCommand's
// Which contain the command to run (backup/restore) and if the command is restore,
// it expects a commit hash to restore to
func Handler(provider backup.Provider, ns notificationfuncs.Service) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodOptions:
w.Header().Set("Access-Control-Allow-Methods", "OPTIONS,GET,POST,PUT")
w.WriteHeader(http.StatusNoContent)
case http.MethodGet:
history, err := provider.List()
if err != nil {
log.Error().Err(err).Msg("error retrieving git history")
util.ReturnHTTPStatus(w, http.StatusInternalServerError, "error retrieving git history")
return
}
if len(history) > 10 {
history = history[:10]
}
sch := backup.Schedule{
DayOfWeek: viper.GetString("dayofweek"),
TimeOfDay: viper.GetString("timeofday"),
}
s := DetailResponse{
History: history,
Schedule: sch,
}
json.NewEncoder(w).Encode(s)
case http.MethodPost:
handlePOST(r, w, provider, ns)
util.ReturnHTTPStatus(w, http.StatusOK, "command executed successfully")
case http.MethodPut:
sched := backup.Schedule{}
err := json.NewDecoder(r.Body).Decode(&sched)
if err != nil {
log.Error().Err(err).Msg("error decoding schedule wrapper")
util.ReturnHTTPStatus(w, http.StatusNotAcceptable, "could not decode json into entity")
return
}
go provider.StartAutoBackup(sched)
util.ReturnHTTPStatus(w, http.StatusOK, "command executed successfully")
}
return
})
}
func handlePOST(r *http.Request, w http.ResponseWriter, provider backup.Provider, ns notificationfuncs.Service) {
item := PostedCommand{}
err := json.NewDecoder(r.Body).Decode(&item)
if err != nil {
log.Error().Err(err).Msg("error decoding details wrapper")
util.ReturnHTTPStatus(w, http.StatusNotAcceptable, "could not decode json into entity")
return
}
switch item.Cmd {
case backup.Backup:
if err := provider.Backup("Manual"); err != nil {
sendStatus(ns, notificationfuncs.Error, "Error running backup")
return
}
sendStatus(ns, notificationfuncs.Success, "Backed up successfully")
case backup.Restore:
if err := provider.Restore(item.Hash); err != nil {
sendStatus(ns, notificationfuncs.Error, "Error running restore")
return
}
sendStatus(ns, notificationfuncs.Success, "Restored successfully")
default:
util.ReturnHTTPStatus(w, http.StatusBadRequest, "command not recognised")
return
}
}
type PostedCommand struct {
Cmd backup.Command `json:"cmd"`
Hash string `json:"hash"`
}
type DetailResponse struct {
History []structs.History `json:"history"`
Schedule backup.Schedule `json:"schedule"`
}
func sendStatus(ns notificationfuncs.Service, status notificationfuncs.EventType, msg string) {
ns.Send(notificationfuncs.Event{
EventType: status,
Value: msg,
})
}
|
package main
import (
"context"
"fmt"
"os"
"encoding/csv"
"strings"
"log"
"io"
"github.com/coreos/go-semver/semver"
"github.com/google/go-github/github"
)
// LatestVersions returns a sorted slice with the highest version as its first element and the highest version of the smaller minor versions in a descending order
func LatestVersions(releases []*semver.Version, minVersion *semver.Version) []*semver.Version {
var versionSlice []*semver.Version
// sort releases in ascending order
semver.Sort(releases)
// iterate through slice backwards
for i := len(releases)-1; i >= 0; i-- {
// release > min version ?
if !releases[i].LessThan(*minVersion) {
// if first element or element has diff minor version than last item in versionSlice,
// then add to versionSlice
if i == len(releases)-1 || releases[i].Minor != versionSlice[len(versionSlice)-1].Minor {
versionSlice = append(versionSlice, releases[i])
}
}
}
return versionSlice
}
func main() {
// init Github api reqs
client := github.NewClient(nil)
ctx := context.Background()
opt := &github.ListOptions{PerPage: 10}
// get filename from cmd args
if len(os.Args) < 2 {
log.Fatal("Missing filename argument\n")
}
file, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
// ensure file is closed at end of program
defer file.Close()
// init csv reader
r := csv.NewReader(file)
// skip header line
line, err := r.Read()
for {
// read one line
line, err = r.Read()
// reached end of file ?
if err == io.EOF {
break
}
// skip entry if error found during read
if err != nil {
fmt.Printf(err.Error())
continue
}
// trim leading and trailing whitespace
line[0] = strings.TrimSpace(line[0])
line[1] = strings.TrimSpace(line[1])
// split repository field into owner and name components
repo := strings.Split(line[0],"/")
// skip repository if name is incorrectly formmated
if len(repo) < 2 {
fmt.Printf("Repository field incorrectly formatted '%s'\n", line[0])
continue
}
// retrieve releases from Github
releases, _, err := client.Repositories.ListReleases(ctx, repo[0], repo[1], opt)
// skip repository if releases could not be retrieved
if err != nil {
fmt.Printf("Could not retrieve releases for '%s'\n", line[0])
continue
}
minVersion, err := semver.NewVersion(line[1])
// skip entry if min version is not in valid format
if err != nil {
fmt.Printf("Minversion '%s' is invalid\n", line[1])
continue
}
allReleases := make([]*semver.Version, len(releases))
for i, release := range releases {
versionString := *release.TagName
// remove preceeding 'v' from version strings
if versionString[0] == 'v' {
versionString = versionString[1:]
}
// store version string as a semver struct
allReleases[i] = semver.New(versionString)
}
// get latest versions
versionSlice := LatestVersions(allReleases, minVersion)
if versionSlice != nil {
fmt.Printf("latest versions of %s: %s\n", line[0], versionSlice)
} else {
fmt.Printf("Min version is greater than latest available version\n")
}
}
}
|
package main
//接口和反射
//类型不需要显式声明它实现了某个接口:接口被隐式地实现。多个类型可以实现同一个接口。
//实现某个接口的类型(除了实现接口方法外)可以有其他的方法。
//一个类型可以实现多个接口。
//接口类型可以包含一个实例的引用, 该实例的类型实现了此接口(接口是动态类型)。
//type Shaper interface {
// Area() float32
//}
//
//type Square struct {
// side float32
//}
//
//func (sq *Square) Area() float32 {
// return sq.side * sq.side
//}
//
//type Rectangle struct {
// length, width float32
//}
//
//func (re Rectangle) Area() float32 {
// return re.length * re.width
//}
//
//func main() {
// //sq1 := new(Square)
// //sq1.side = 5
//
// //var areaIntF Shaper
// //areaIntF = sq1
// //fmt.Printf("The square has area: %f\n", areaIntF.Area())
//
// r := Rectangle{5,3} // Area() of Rectangle needs a value
// q := &Square{5} // Area() of Square needs a pointer
// // shapes := []Shaper{Shaper(r), Shaper(q)}
// // or shorter
//
// shapes := []Shaper{r, q}
// fmt.Println("Looping through shapes for area ....")
// for n, _ := range shapes {
// fmt.Println("shape details: ", shapes[n])
// fmt.Println("Are of this shape is: ", shapes[n].Area())
// }
//}
//valuable.go
//type stockPosition struct {
// ticker string
// sharePrice float32
// count float32
//}
//
////method to determine the value of a stock position
//func (s stockPosition) getValue() float32 {
// return s.sharePrice * s.count
//}
//
//type car struct {
// make string
// model string
// price float32
//}
//
//// method to determine the value of the car
//func (c car) getValue() float32 {
// return c.price
//}
//
////contract that defines different things that have value
//type valuable interface {
// getValue() float32
//}
//
//func showValue(asset valuable) {
// fmt.Printf("Value of the asset is: %f\n", asset.getValue())
//}
//
//func main() {
// var o valuable = stockPosition{"GOOG", 577.200, 4}
// showValue(o)
// o = car{"BWM", "M3", 657600}
// showValue(o)
//}
//接口嵌套接口
//比如接口 File 包含了 ReadWrite 和 Lock 的所有方法,它还额外有一个 Close() 方法。
//type ReadWrite interface {
// Read(b Buffer) bool
// Write(b Buffer) bool
//}
//
//type Lock interface {
// Lock()
// Unlock()
//}
//
//type File interface {
// ReadWrite
// Lock
// Close()
//}
//类型断言:如何检测和转换接口变量的类型
//type_interface.go
//type Square struct {
// side float32
//}
//
//type Circle struct {
// radius float32
//}
//
//type Shaper interface {
// Area() float32
//}
//
//func main() {
// var areaIntF Shaper
// sq1 := new(Square)
// sq1.side = 21
//
// areaIntF = sq1
// // is Square the type of areaIntF
// if t, ok := areaIntF.(*Square); ok {
// fmt.Printf("the type of areaIntF is: %T\n", t)
// }
// if u, ok := areaIntF.(*Circle); ok {
// fmt.Printf("the tyoe of areaIntfis: %T\n", u)
// } else {
// fmt.Println("areaIntF does not contain a variable of type Circle")
// }
//
// switch t := areaIntF.(type) {
// case *Square:
// fmt.Printf("Type Square %T with value %v\n", t, t)
// case *Circle:
// fmt.Printf("Type Circle %T with value %v\n", t, t)
// case nil:
// fmt.Printf("nil value: nothing to check?\n")
// default:
// fmt.Printf("Unexpected type %T\n", t)
// }
//}
//
//func (sq *Square) Area() float32 {
// return sq.side * sq.side
//}
//
//func (ci * Circle) Area() float32 {
// return ci.radius * ci.radius * math.Pi
//}
//实现冒泡排序
//type Sorter interface {
// Len() int
// Less(i, j int) bool
// Swap(i, j int)
//}
//
//func Sort(data Sorter) {
// for pass := 1; pass < data.Len(); pass++ {
// for i := 0; i < data.Len() - pass; i++ {
// if data.Less(i + 1, i) {
// data.Swap(i, i + 1)
// }
// }
// }
//}
//
//func IsSorted(data Sorter) bool {
// n := data.Len()
// for i := n - 1; i > 0; i-- {
// if data.Less(i, i-1) {
// return false
// }
// }
// return true
//}
//
//// Convenience type for common cases
//type IntArray []int
//
//func (p IntArray) Len() int { return len(p) }
//func (p IntArray) Less(i, j int) bool { return p[i] < p[j] }
//func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
//
//
//type StringArray []string
//
//func (p StringArray) Len() int { return len(p) }
//func (p StringArray) Less(i, j int) bool { return p[i] < p[j] }
//func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
//
//// Convenience wrappers for common cases
//func SortIntS(a []int) { Sort(IntArray(a)) }
//func SortStrings(a []string) { Sort(StringArray(a)) }
//
//func IntSAreSorted(a []int) bool { return IsSorted(IntArray(a)) }
//func StringsAreSorted(a []string) bool { return IsSorted(StringArray(a)) }
//
////sortedMain.go
//func intS() {
// data := []int{74, 59, 243, 542, -13, 9, 76, 234, 89, -234}
// a := IntArray(data)
// Sort(a)
// if !IsSorted(a) {
// panic("fails")
// }
// fmt.Printf("The sorted array is: %v\n", a)
//}
//
//func stringS() {
// data := []string{"monday", "friday", "wednesday", "sunday", "thursday", "", "saturday"}
// a := StringArray(data)
// Sort(a)
// if !IsSorted(a) {
// panic("fails")
// }
// fmt.Printf("The sorted array is: %v\n", a)
//}
//
//type day struct {
// num int
// shortName string
// longName string
//}
//
//type dayArray struct {
// data []*day
//}
//
//func (d *dayArray) Len() int { return len(d.data) }
//func (d *dayArray) Less(i, j int) bool { return d.data[i].num < d.data[j].num}
//func (d *dayArray) Swap(i, j int) { d.data[i], d.data[j] = d.data[j], d.data[i]}
//
//func dayS() {
// Sunday := day{0, "SUN", "Sunday"}
// Monday := day{1, "MON", "Monday"}
// Tuesday := day{2, "TUE", "Tuesday"}
// Wednesday := day{3, "WED", "Wednesday"}
// Thursday := day{4, "THU", "Thursday"}
// Friday := day{5, "FRI", "Friday"}
// Saturday := day{6, "SAT", "Saturday"}
//
// data := []*day{&Tuesday, &Sunday, &Saturday, &Wednesday, &Thursday, &Friday, &Monday}
// a := dayArray{data}
// Sort(&a)
// if !IsSorted(&a) {
// panic("fails")
// }
//
// fmt.Print("The sorted array is: ")
// for _, d := range data {
// fmt.Printf("%s ", d.longName)
// }
// fmt.Println()
//}
//
//func main() {
// intS()
// stringS()
// dayS()
//}
|
package types
type User struct {
Id int `gorm:"primary_key"`
Username string `sql:"unique"`
MimeType string
}
func (User) SwaggerDoc() map[string]string {
return map[string]string{
"": "A user object",
"id": "The id of the user",
"username": "The username of the user",
}
}
|
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
)
func (bot *Bot) loadConfiguration(filepath string) {
configFile, err := ioutil.ReadFile(filepath)
if err != nil {
flag.Usage()
log.Fatal(err.Error())
}
err = json.Unmarshal(configFile, &bot)
if err != nil {
log.Fatal(err.Error())
panic(err)
}
bot.Trigger = fmt.Sprintf("%s: %s", bot.Nickname, bot.Trigger)
log.Println("Configuration loaded!")
}
|
package integration
// Collection of utilities to share between our various load tests
import (
"io/ioutil"
"os"
"path/filepath"
"strconv"
"time"
"github.com/cortexproject/cortex/integration/e2e"
cortex_e2e "github.com/cortexproject/cortex/integration/e2e"
"github.com/cortexproject/cortex/pkg/util"
"github.com/pkg/errors"
)
const (
image = "tempo:latest"
azuriteImage = "mcr.microsoft.com/azure-storage/azurite"
)
func NewTempoAllInOne() *cortex_e2e.HTTPService {
args := "-config.file=" + filepath.Join(cortex_e2e.ContainerSharedDir, "config.yaml")
s := cortex_e2e.NewHTTPService(
"tempo",
image,
cortex_e2e.NewCommandWithoutEntrypoint("/tempo", args),
cortex_e2e.NewHTTPReadinessProbe(3200, "/ready", 200, 299),
3200, // http all things
14250, // jaeger grpc ingest
9411, // zipkin ingest (used by load)
)
s.SetBackoff(tempoBackoff())
return s
}
func NewAzurite() *cortex_e2e.HTTPService {
s := cortex_e2e.NewHTTPService(
"azurite",
azuriteImage, // Create the the azurite container
e2e.NewCommandWithoutEntrypoint("sh", "-c", "azurite -l /data --blobHost 0.0.0.0"),
e2e.NewHTTPReadinessProbe(10000, "/devstoreaccount1?comp=list", 403, 403), //If we get 403 the Azurite is ready
10000, // blob storage port
)
s.SetBackoff(tempoBackoff())
return s
}
func NewTempoDistributor() *cortex_e2e.HTTPService {
args := []string{"-config.file=" + filepath.Join(cortex_e2e.ContainerSharedDir, "config.yaml"), "-target=distributor"}
s := cortex_e2e.NewHTTPService(
"distributor",
image,
cortex_e2e.NewCommandWithoutEntrypoint("/tempo", args...),
cortex_e2e.NewHTTPReadinessProbe(3200, "/ready", 200, 299),
3200,
14250,
)
s.SetBackoff(tempoBackoff())
return s
}
func NewTempoIngester(replica int) *cortex_e2e.HTTPService {
args := []string{"-config.file=" + filepath.Join(cortex_e2e.ContainerSharedDir, "config.yaml"), "-target=ingester"}
s := cortex_e2e.NewHTTPService(
"ingester-"+strconv.Itoa(replica),
image,
cortex_e2e.NewCommandWithoutEntrypoint("/tempo", args...),
cortex_e2e.NewHTTPReadinessProbe(3200, "/ready", 200, 299),
3200,
)
s.SetBackoff(tempoBackoff())
return s
}
func NewTempoQueryFrontend() *cortex_e2e.HTTPService {
args := []string{"-config.file=" + filepath.Join(cortex_e2e.ContainerSharedDir, "config.yaml"), "-target=query-frontend"}
s := cortex_e2e.NewHTTPService(
"query-frontend",
image,
cortex_e2e.NewCommandWithoutEntrypoint("/tempo", args...),
cortex_e2e.NewHTTPReadinessProbe(3200, "/ready", 200, 299),
3200,
)
s.SetBackoff(tempoBackoff())
return s
}
func NewTempoQuerier() *cortex_e2e.HTTPService {
args := []string{"-config.file=" + filepath.Join(cortex_e2e.ContainerSharedDir, "config.yaml"), "-target=querier"}
s := cortex_e2e.NewHTTPService(
"querier",
image,
cortex_e2e.NewCommandWithoutEntrypoint("/tempo", args...),
cortex_e2e.NewHTTPReadinessProbe(3200, "/ready", 200, 299),
3200,
)
s.SetBackoff(tempoBackoff())
return s
}
func WriteFileToSharedDir(s *e2e.Scenario, dst string, content []byte) error {
dst = filepath.Join(s.SharedDir(), dst)
// Ensure the entire path of directories exist.
if err := os.MkdirAll(filepath.Dir(dst), os.ModePerm); err != nil {
return err
}
return ioutil.WriteFile(
dst,
content,
os.ModePerm)
}
func CopyFileToSharedDir(s *e2e.Scenario, src, dst string) error {
content, err := ioutil.ReadFile(src)
if err != nil {
return errors.Wrapf(err, "unable to read local file %s", src)
}
return WriteFileToSharedDir(s, dst, content)
}
func tempoBackoff() util.BackoffConfig {
return util.BackoffConfig{
MinBackoff: 500 * time.Millisecond,
MaxBackoff: time.Second,
MaxRetries: 300, // Sometimes the CI is slow ¯\_(ツ)_/¯
}
}
|
package roman
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestToArabicI(t *testing.T) {
assert.Equal(t, 1, ToArabic("I"))
}
func TestToArabicV(t *testing.T) {
assert.Equal(t, 5, ToArabic("V"))
}
func TestToArabicX(t *testing.T) {
assert.Equal(t, 10, ToArabic("X"))
}
func TestToArabicL(t *testing.T) {
assert.Equal(t, 50, ToArabic("L"))
}
func TestToArabicC(t *testing.T) {
assert.Equal(t, 100, ToArabic("C"))
}
func TestToArabicD(t *testing.T) {
assert.Equal(t, 500, ToArabic("D"))
}
func TestToArabicM(t *testing.T) {
assert.Equal(t, 1000, ToArabic("M"))
}
func TestToArabicML(t *testing.T) {
assert.Equal(t, 1050, ToArabic("ML"))
}
func TestToArabicIV(t *testing.T) {
assert.Equal(t, 4, ToArabic("IV"))
}
func TestFromArabic1(t *testing.T) {
assert.Equal(t, "I", FromArabic(1))
}
func TestFromArabic5(t *testing.T) {
assert.Equal(t, "V", FromArabic(5))
}
func TestFromArabic10(t *testing.T) {
assert.Equal(t, "X", FromArabic(10))
}
func TestFromArabic50(t *testing.T) {
assert.Equal(t, "L", FromArabic(50))
}
func TestFromArabic100(t *testing.T) {
assert.Equal(t, "C", FromArabic(100))
}
func TestFromArabic500(t *testing.T) {
assert.Equal(t, "D", FromArabic(500))
}
func TestFromArabic1000(t *testing.T) {
assert.Equal(t, "M", FromArabic(1000))
}
func TestFromArabic1050(t *testing.T) {
assert.Equal(t, "ML", FromArabic(1050))
}
func TestFromArabic4(t *testing.T) {
assert.Equal(t, "IV", FromArabic(4))
}
func TestFromArabic9(t *testing.T) {
assert.Equal(t, "IX", FromArabic(9))
}
func TestFromArabic40(t *testing.T) {
assert.Equal(t, "XL", FromArabic(40))
}
func TestFromArabic400(t *testing.T) {
assert.Equal(t, "CD", FromArabic(400))
}
func TestFromArabic440(t *testing.T) {
assert.Equal(t, "CDXL", FromArabic(440))
}
func TestFromArabic1947(t *testing.T) {
assert.Equal(t, "MCMXLVII", FromArabic(1947))
}
func TestFromArabic123(t *testing.T) {
assert.Equal(t, "CXXIII", FromArabic(123))
}
func TestFromArabic1979(t *testing.T) {
assert.Equal(t, "MCMLXXIX", FromArabic(1979))
}
|
package dbconfig_test
import (
"testing"
"github.com/adlerhsieh/dbconfig"
)
func TestReadFile(t *testing.T) {
config := dbconfig.ReadFile("./example/database.yml", "development")
username := "foo"
password := "bar"
if config["username"] != username {
t.Error("Expecting config username as " + username + ". Got " + config["username"])
}
if config["password"] != password {
t.Error("Expecting config username as " + password + ". Got " + config["password"])
}
}
func TestEnvironment(t *testing.T) {
config := dbconfig.ReadFile("./example/database.yml", "production")
host := "the_host"
if config["host"] != host {
t.Error("Expecting config host as " + host + ". Got " + config["host"])
}
}
|
/*
* Npcf_SMPolicyControl API
*
* Session Management Policy Control Service © 2019, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved.
*
* API version: 1.0.4
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package openapi
// QosFlowUsage - Possible values are - GENERAL: Indicate no specific QoS flow usage information is available. - IMS_SIG: Indicate that the QoS flow is used for IMS signalling only.
type QosFlowUsage struct {
}
|
package pubsub
import (
"context"
"flag"
"fmt"
"hash/fnv"
"os"
"runtime"
"sync"
"time"
"cloud.google.com/go/pubsub"
"github.com/GoogleCloudPlatform/cloud-ingest/agent/tasks/list"
"github.com/golang/glog"
)
const (
listProgressTopicID = "cloud-ingest-list-progress"
copyProgressTopicID = "cloud-ingest-copy-progress"
deleteProgressTopicID = "cloud-ingest-delete-object-progress"
pulseTopicID = "cloud-ingest-pulse"
controlTopicID = "cloud-ingest-control"
listSubscriptionID = "cloud-ingest-list"
copySubscriptionID = "cloud-ingest-copy"
deleteSubscriptionID = "cloud-ingest-delete-object"
controlSubscriptionID = "cloud-ingest-control"
)
var (
pubsubPrefix = flag.String("pubsub-prefix", "", "Prefix of Pub/Sub topics and subscriptions names.")
maxPubSubLeaseExtenstion = flag.Duration("pubsub-lease-extension", 20*time.Minute, "The max duration to extend the leases for a Pub/Sub message. If 0, will use the default Pub/Sub client value (10 mins).")
_ = flag.Int("threads", 100, "This flag is no longer used and will be soon deprecated.")
copyTasksPerCPU = flag.Int("copy-tasks-per-cpu", 2, "Copy tasks to process (per CPU) in parallel. Can be overridden by setting copy-tasks.")
copyTasks = flag.Int("copy-tasks", 0, "Copy tasks to process in parallel. If > 0 this will override copy-tasks-per-cpu.")
deleteTasks = flag.Int("delete-tasks", 10, "Max delete tasks the agent will process at any given time. If 0, will use the default Pub/Sub client value (1000).")
)
// waitOnSubscription blocks until either the PubSub subscription exists, or returns an err.
func waitOnSubscription(ctx context.Context, sub *pubsub.Subscription) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
exists, err := sub.Exists(ctx)
if err != nil {
return err
}
if exists {
fmt.Printf("PubSub subscription %q is ready.\n", sub.String())
return nil
}
fmt.Printf("Waiting for PubSub subscription %q to exist.\n", sub.String())
time.Sleep(10 * time.Second)
}
}
}
// waitOnTopic blocks until either the PubSub topic exists, or returns an err.
func waitOnTopic(ctx context.Context, topic *pubsub.Topic) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
exists, err := topic.Exists(ctx)
if err != nil {
return err
}
if exists {
fmt.Printf("PubSub topic %q is ready.\n", topic.ID())
return nil
}
fmt.Printf("Waiting for PubSub topic %q to exist.\n", topic.ID())
time.Sleep(10 * time.Second)
}
}
}
func subscribeToControlTopic(ctx context.Context, client *pubsub.Client, topic *pubsub.Topic) (*pubsub.Subscription, error) {
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
h := fnv.New64a()
h.Write([]byte(hostname))
h.Write([]byte(fmt.Sprintf("%v", os.Getpid())))
subID := fmt.Sprintf("%s%s-%d", *pubsubPrefix, controlSubscriptionID, h.Sum64())
sub := client.Subscription(subID)
exists, err := sub.Exists(ctx)
if err != nil {
return nil, err
}
if exists {
glog.Infof("PubSub subscription %q already exists, probably another agent created it before.", sub.String())
return sub, nil
}
return client.CreateSubscription(ctx, subID, pubsub.SubscriptionConfig{Topic: topic})
}
// CreatePubSubTopicsAndSubs creates all of the PubSub topics and subs necessary for the Agent. If any of them can't
// be successfully created this function will glog.Fatal and kill the Agent.
//
// Where not overridden, the DefaultReceiveSettings are:
// ReceiveSettings{
// MaxExtension: 10 * time.Minute,
// MaxOutstandingMessages: 1000,
// MaxOutstandingBytes: 1e9,
// NumGoroutines: 1,
// }
// The default settings should be safe, because of the following reasons
// * MaxExtension: DCP should not publish messages that are estimated to take more than 10 mins.
// * MaxOutstandingMessages: It's also capped by the memory, and this will speed up processing of small files.
// * MaxOutstandingBytes: 1GB memory should not be a problem for a modern machine.
// * NumGoroutines: Does not need more than 1 routine to pull Pub/Sub messages.
func CreatePubSubTopicsAndSubs(ctx context.Context, pubSubClient *pubsub.Client) (listSub, copySub, controlSub, deleteSub *pubsub.Subscription, listTopic, copyTopic, pulseTopic, deleteTopic *pubsub.Topic) {
var wg sync.WaitGroup
wg.Add(8)
go func() {
defer wg.Done()
listSub = pubSubClient.Subscription(*pubsubPrefix + listSubscriptionID)
listSub.ReceiveSettings.MaxExtension = *maxPubSubLeaseExtenstion
listSub.ReceiveSettings.MaxOutstandingMessages = *list.NumberConcurrentListTasks
listSub.ReceiveSettings.Synchronous = true
if err := waitOnSubscription(ctx, listSub); err != nil {
glog.Fatalf("Could not find list subscription %s, error %+v", listSub.String(), err)
}
}()
go func() {
defer wg.Done()
listTopic = pubSubClient.Topic(*pubsubPrefix + listProgressTopicID)
if err := waitOnTopic(ctx, listTopic); err != nil {
glog.Fatalf("Could not find list topic %s, error %+v", listTopic.ID(), err)
}
}()
go func() {
defer wg.Done()
copySub = pubSubClient.Subscription(*pubsubPrefix + copySubscriptionID)
copySub.ReceiveSettings.MaxExtension = *maxPubSubLeaseExtenstion
ct := *copyTasks
if ct <= 0 {
ct = *copyTasksPerCPU * runtime.NumCPU()
}
glog.Info("CopySub MaxoutstandingMessages:", ct)
copySub.ReceiveSettings.MaxOutstandingMessages = ct
copySub.ReceiveSettings.Synchronous = true
if err := waitOnSubscription(ctx, copySub); err != nil {
glog.Fatalf("Could not find copy subscription %s, error %+v", copySub.String(), err)
}
}()
go func() {
defer wg.Done()
copyTopic = pubSubClient.Topic(*pubsubPrefix + copyProgressTopicID)
if err := waitOnTopic(ctx, copyTopic); err != nil {
glog.Fatalf("Could not find copy topic %s, error %+v", copyTopic.ID(), err)
}
}()
go func() {
defer wg.Done()
controlTopic := pubSubClient.Topic(*pubsubPrefix + controlTopicID)
if err := waitOnTopic(ctx, controlTopic); err != nil {
glog.Fatalf("Could not get ControlTopic: %s, got err: %v ", controlTopic.ID(), err)
}
var err error
controlSub, err = subscribeToControlTopic(ctx, pubSubClient, controlTopic)
if err != nil {
glog.Fatalf("Could not create subscription to control topic %v, with err: %v", controlTopic.ID(), err)
}
controlSub.ReceiveSettings.MaxOutstandingMessages = 1
if err := waitOnSubscription(ctx, controlSub); err != nil {
glog.Fatalf("Could not find control subscription %s, error %+v", controlSub.String(), err)
}
}()
go func() {
defer wg.Done()
pulseTopic = pubSubClient.Topic(*pubsubPrefix + pulseTopicID)
if err := waitOnTopic(ctx, pulseTopic); err != nil {
glog.Fatalf("Could not get PulseTopic: %s, got err: %v ", pulseTopic.ID(), err)
}
}()
go func() {
defer wg.Done()
deleteSub = pubSubClient.Subscription(*pubsubPrefix + deleteSubscriptionID)
deleteSub.ReceiveSettings.MaxExtension = *maxPubSubLeaseExtenstion
deleteSub.ReceiveSettings.MaxOutstandingMessages = *deleteTasks
deleteSub.ReceiveSettings.Synchronous = true
if err := waitOnSubscription(ctx, deleteSub); err != nil {
glog.Fatalf("Could not find delete subscription %s, error %+v", deleteSub.String(), err)
}
}()
go func() {
defer wg.Done()
deleteTopic = pubSubClient.Topic(*pubsubPrefix + deleteProgressTopicID)
if err := waitOnTopic(ctx, deleteTopic); err != nil {
glog.Fatalf("Could not find delete topic %s, error %+v", deleteTopic.ID(), err)
}
}()
wg.Wait()
fmt.Println("All PubSub topics and subscriptions are ready.")
return listSub, copySub, controlSub, deleteSub, listTopic, copyTopic, pulseTopic, deleteTopic
}
|
package animals
func ElephpantFeed() string{
return "Grass"
} |
package streaming_transmit
import (
"net"
"testing"
"github.com/stretchr/testify/require"
"go.uber.org/goleak"
)
func TestServerShutdown(t *testing.T) {
defer goleak.VerifyNone(t)
srv := &Server{}
ln, err := net.Listen("tcp", ":0")
require.NoError(t, err)
go func() {
srv.Shutdown()
ln.Close()
}()
require.NoError(t, srv.Serve(ln))
}
|
package array
// GetMapIntKeys get map keys,return slice
func GetMapIntKeys(m map[int]interface{}) []int {
keys := make([]int, 0, len(m))
for i := range m {
keys = append(keys, i)
}
return keys
}
|
package notaryctl
import (
"context"
"github.com/operator-framework/operator-lib/status"
regv1 "github.com/tmax-cloud/registry-operator/api/v1"
"github.com/tmax-cloud/registry-operator/internal/schemes"
"github.com/tmax-cloud/registry-operator/internal/utils"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
type NotaryServerSecret struct {
secret *corev1.Secret
logger *utils.RegistryLogger
}
// Handle is to create notary server secret.
func (nt *NotaryServerSecret) Handle(c client.Client, notary *regv1.Notary, patchNotary *regv1.Notary, scheme *runtime.Scheme) error {
if err := nt.get(c, notary); err != nil {
if errors.IsNotFound(err) {
if err := nt.create(c, notary, patchNotary, scheme); err != nil {
nt.logger.Error(err, "create secret error")
return err
}
} else {
nt.logger.Error(err, "secret error")
return err
}
}
return nil
}
// Ready is to check if the secret is ready and to set the condition
func (nt *NotaryServerSecret) Ready(c client.Client, notary *regv1.Notary, patchNotary *regv1.Notary, useGet bool) error {
var err error = nil
condition := &status.Condition{
Status: corev1.ConditionFalse,
Type: regv1.ConditionTypeNotaryServerSecret,
}
defer utils.SetCondition(err, patchNotary, condition)
if useGet {
err = nt.get(c, notary)
if err != nil {
nt.logger.Error(err, "get secret error")
return err
}
}
nt.logger.Info("Ready")
condition.Status = corev1.ConditionTrue
return nil
}
func (nt *NotaryServerSecret) create(c client.Client, notary *regv1.Notary, patchNotary *regv1.Notary, scheme *runtime.Scheme) error {
var err error = nil
condition := &status.Condition{
Status: corev1.ConditionFalse,
Type: regv1.ConditionTypeNotaryServerSecret,
}
defer utils.SetCondition(err, patchNotary, condition)
if err = controllerutil.SetControllerReference(notary, nt.secret, scheme); err != nil {
nt.logger.Error(err, "SetOwnerReference Failed")
return nil
}
nt.logger.Info("Create notary server secret")
if err = c.Create(context.TODO(), nt.secret); err != nil {
nt.logger.Error(err, "Creating notary server secret is failed.")
return nil
}
return nil
}
func (nt *NotaryServerSecret) get(c client.Client, notary *regv1.Notary) error {
nt.logger = utils.NewRegistryLogger(*nt, notary.Namespace, schemes.SubresourceName(notary, schemes.SubTypeNotaryServerSecret))
secret, err := schemes.NotaryServerSecret(notary, c)
if err != nil {
nt.logger.Error(err, "create scheme failed")
return err
}
nt.secret = secret
req := types.NamespacedName{Name: nt.secret.Name, Namespace: nt.secret.Namespace}
if err := c.Get(context.TODO(), req, nt.secret); err != nil {
nt.logger.Error(err, "Get notary server secret is failed")
return err
}
return nil
}
func (nt *NotaryServerSecret) delete(c client.Client, patchNotary *regv1.Notary) error {
var err error = nil
condition := &status.Condition{
Status: corev1.ConditionFalse,
Type: regv1.ConditionTypeNotaryServerSecret,
}
defer utils.SetCondition(err, patchNotary, condition)
if err = c.Delete(context.TODO(), nt.secret); err != nil {
nt.logger.Error(err, "Unknown error delete secret")
return err
}
return nil
}
|
package game
import (
"github.com/talesmud/talesmud/pkg/entities"
"github.com/talesmud/talesmud/pkg/entities/characters"
)
// Avatar ... default active entity that moves in the world
// Avatars can be either controlled by Players/Users or be attached/belong to bots
// Once a user is logged in he automatically gets attached his last used aavatar
type Avatar struct {
ID string
User *entities.User
Character *characters.Character
}
// NewAvatar ... creates and returns a new room instance
func NewAvatar() *Avatar {
return &Avatar{}
}
|
package util
//物流
import (
"encoding/json"
"log"
"net/http"
"JsGo/JsConfig"
"JsGo/JsLogger"
"crypto/md5"
"fmt"
"io/ioutil"
"strings"
)
type ExpressFlow struct {
Time string `json:"time"` //时间,原始格式
Ftime string `json:"ftime"` //格式化后时间
Context string `json:"context"` //内容
}
type ExpressInfo struct {
Message string `json:"message"` //消息体,请忽略
ExpressNumber string `json:"nu"` //快递单号
Ischeck string `json:"ischeck"` //是否签收标记,请忽略,明细状态请参考state字段
Condition string `json:"condition"` //快递单明细状态标记,暂未实现,请忽略
ExpressName string `json:"com"` //快递公司编码,一律用小写字母
Status string `json:"status"` //通讯状态,请忽略
State string `json:"state"` //快递单当前签收状态,包括0在途中、1已揽收、2疑难、3已签收、4退签、5同城派送中、6退回、7转单等7个状态,其中4-7需要另外开通才有效
Data []ExpressFlow `json:"data"` //物流信息
}
var Express_Url string
var Express_Customer string
var Express_Key string
func init() {
var e error
Express_Url, e = JsConfig.GetConfigString([]string{"Express", "Url"})
if e != nil {
log.Fatalln(e.Error())
}
Express_Customer, e = JsConfig.GetConfigString([]string{"Express", "Customer"})
if e != nil {
log.Fatalln(e.Error())
}
Express_Key, e = JsConfig.GetConfigString([]string{"Express", "Sign"})
if e != nil {
log.Fatalln(e.Error())
}
}
//查询订单物流
func QueryExpress(Name, Number string) (*ExpressInfo, error) {
type Para struct {
Com string `json:"com"`
Num string `json:"num"`
}
st := Para{
Com: Name,
Num: Number,
}
b, e := json.Marshal(&st)
if e != nil {
return nil, e
}
para := string(b)
str := para + Express_Key + Express_Customer
has := md5.Sum([]byte(str))
Sign := fmt.Sprintf("%x", has)
Sign = strings.ToUpper(Sign)
url := Express_Url
url += "?customer="
url += Express_Customer
url += "&sign="
url += Sign
url += "¶m="
url += para
JsLogger.Error("usr=====%s", url)
resp, e := http.Get(url)
defer resp.Body.Close()
if e != nil {
JsLogger.Error(e.Error())
return nil, e
}
by, err := ioutil.ReadAll(resp.Body)
JsLogger.Error(string(by))
if err != nil {
JsLogger.Error(err.Error())
return nil, err
}
data := &ExpressInfo{}
if err := json.Unmarshal(by, data); err != nil {
JsLogger.Error(err.Error())
return nil, err
}
return data, nil
}
|
package main
import "github.com/jwt/controller"
func main() {
controller.RunController(":8080")
}
|
package basiccron
import (
"fmt"
"sync"
"testing"
"time"
)
func TestCronError(t *testing.T) {
cron := New(time.Second)
if _, err := cron.AddFunc(time.Now().Add(time.Second*2), time.Hour, func () { fmt.Println("Hello, world") }, 10); err == nil {
t.Error("This AddFunc should return Error, wrong number of args")
}
if _, err := cron.AddFunc(time.Now().Add(time.Second*2), time.Hour, nil); err == nil {
t.Error("This AddFunc should return Error, fn is nil")
}
if _, err := cron.AddFunc(time.Now().Add(time.Second*2), time.Hour, 0); err == nil {
t.Error("This AddFunc should return Error, fn is not func kind")
}
if _, err := cron.AddFunc(time.Now().Add(time.Second*2), time.Hour, func (s string, n int) { fmt.Printf("We have params here, string `%s` and nymber %d\n", s, n) }, "s", 10, 12); err == nil {
t.Error("This AddFunc should return Error, wrong number of args")
}
if _, err := cron.AddFunc(time.Now().Add(time.Second*2), time.Hour, func (s string, n int) { fmt.Printf("We have params here, string `%s` and nymber %d\n", s, n) }, "s", "s2"); err == nil {
t.Error("This AddFunc should return Error, args are not the correct type")
}
if _, err := cron.AddFunc(time.Now().Add(time.Second*2), time.Hour, func (s string, n int) { fmt.Printf("We have params here, string `%s` and nymber %d\n", s, n) }, "s", "s2"); err == nil {
t.Error("This AddFunc should return Error, syntax error")
}
// custom types and interfaces as function params
type user struct {
ID int
Name string
}
var u user
if _, err := cron.AddFunc(time.Now().Add(time.Second*2), time.Hour, func (u user) { fmt.Println("Custom type as param") }, u); err != nil {
t.Error(err)
}
type Foo interface {
Bar() string
}
if _, err := cron.AddFunc(time.Now().Add(time.Second*2), time.Hour, func (i Foo) { i.Bar() }, u); err == nil {
t.Error("This should return error, type that don't implements interface assigned as param")
}
}
func TestCronBasic(t *testing.T) {
testN := 0
testS := ""
cron := New(time.Second)
if _, err := cron.AddFunc(time.Now().Add(time.Second*1), time.Second*3, func() { testN++ }); err != nil {
t.Fatal(err)
}
if _, err := cron.AddFunc(time.Now().Add(time.Second*1), time.Second*3, func(s string) { testS = s }, "param"); err != nil {
t.Fatal(err)
}
cron.Start()
time.Sleep(time.Second * 10)
if testN != 3 {
t.Error("func not executed correctly")
}
if testS != "param" {
t.Error("func not executed or arg not passed")
}
cron.Stop()
}
func TestCronNormalSchedule(t *testing.T) {
testN := 0
testS := ""
cron := New(time.Second*2)
var wg sync.WaitGroup
wg.Add(2)
if _, err := cron.AddFunc(time.Now().Add(time.Second*4), time.Second*10, func() { testN++; wg.Done() }); err != nil {
t.Fatal(err)
}
if _, err := cron.AddFunc(time.Now().Add(time.Second*3), time.Second*10, func(s string) { testS = s; wg.Done() }, "param"); err != nil {
t.Fatal(err)
}
cron.Start()
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(5 * time.Second):
}
if testN != 1 {
t.Error("func 1 not executed as scheduled")
}
if testS != "param" {
t.Error("func 2 not executed as scheduled")
}
}
func TestCronAddAfterStopSchedule(t *testing.T) {
testN := 0
cron := New(time.Second*2)
cron.Start()
cron.Stop()
var wg sync.WaitGroup
wg.Add(1)
if _, err := cron.AddFunc(time.Now().Add(time.Second*2), time.Second*10, func() { testN++; wg.Done() }); err != nil {
t.Fatal(err)
}
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-time.After(time.Second * 5):
if testN > 0 {
t.Fatal("expected stopped cron does not run any job")
}
case <-done:
t.Fatal("expected stopped cron does not run any job")
}
}
func TestCronAddBeforeStartSchedule(t *testing.T) {
testN := 0
testS := ""
cron := New(time.Second*2)
var wg sync.WaitGroup
wg.Add(2)
if _, err := cron.AddFunc(time.Now().Add(time.Second*4), time.Second*10, func() { testN++; wg.Done() }); err != nil {
t.Fatal(err)
}
cron.Start()
time.Sleep(2 * time.Second)
if _, err := cron.AddFunc(time.Now().Add(time.Second*3), time.Second*10, func(s string) { testS = s; wg.Done() }, "param"); err != nil {
t.Fatal(err)
}
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(5 * time.Second):
}
if testN != 1 {
t.Error("func 1 not executed as scheduled")
}
if testS != "param" {
t.Error("func 2 not executed as scheduled")
}
}
func TestCronRemoveBeforeStartSchedule(t *testing.T) {
testN := 0
testS := ""
cron := New(time.Second*2)
var (
err error
id string
wg sync.WaitGroup
)
wg.Add(2)
if id, err = cron.AddFunc(time.Now().Add(time.Second), time.Second, func() { testN++; wg.Done() }); err != nil {
t.Fatal(err)
}
if _, err = cron.AddFunc(time.Now().Add(time.Second*3), time.Second*10, func(s string) { testS = s; wg.Done() }, "param"); err != nil {
t.Fatal(err)
}
cron.DelFunc(id)
cron.Start()
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
t.Fatal("expected stopped cron does not run first job")
case <-time.After(5 * time.Second):
}
if testN != 0 {
t.Error("func 1 must be removed")
}
if testS != "param" {
t.Error("func 2 not executed as scheduled")
}
}
func TestCronRemoveAfterStartSchedule(t *testing.T) {
testN := 0
testS := ""
cron := New(time.Second*2)
var (
err error
id string
wg sync.WaitGroup
)
wg.Add(1)
if id, err = cron.AddFunc(time.Now().Add(time.Second), time.Second, func() { testN++ }); err != nil {
t.Fatal(err)
}
if _, err = cron.AddFunc(time.Now().Add(time.Second*3), time.Second*10, func(s string) { testS = s; wg.Done() }, "param"); err != nil {
t.Fatal(err)
}
cron.Start()
time.Sleep(time.Second*5)
cron.DelFunc(id)
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(5 * time.Second):
}
if testN > 2 {
t.Error("func 1 must be removed before 3th tick")
}
if testS != "param" {
t.Error("func 2 not executed as scheduled")
}
}
|
package main
import "sort"
//1738. 找出第 K 大的异或坐标值
//给你一个二维矩阵 matrix 和一个整数 k ,矩阵大小为m x n 由非负整数组成。
//
//矩阵中坐标 (a, b) 的 值 可由对所有满足 0 <= i <= a < m 且 0 <= j <= b < n 的元素 matrix[i][j](下标从 0 开始计数)执行异或运算得到。
//
//请你找出matrix 的所有坐标中第 k 大的值(k 的值从 1 开始计数)。
//
//
//
//示例 1:
//
//输入:matrix = [[5,2],[1,6]], k = 1
//输出:7
//解释:坐标 (0,1) 的值是 5 XOR 2 = 7 ,为最大的值。
//示例 2:
//
//输入:matrix = [[5,2],[1,6]], k = 2
//输出:5
//解释:坐标 (0,0) 的值是 5 = 5 ,为第 2 大的值。
//示例 3:
//
//输入:matrix = [[5,2],[1,6]], k = 3
//输出:4
//解释:坐标 (1,0) 的值是 5 XOR 1 = 4 ,为第 3 大的值。
//示例 4:
//
//输入:matrix = [[5,2],[1,6]], k = 4
//输出:0
//解释:坐标 (1,1) 的值是 5 XOR 2 XOR 1 XOR 6 = 0 ,为第 4 大的值。
//
//
//提示:
//
//m == matrix.length
//n == matrix[i].length
//1 <= m, n <= 1000
//0 <= matrix[i][j] <= 10^6
//1 <= k <= m * n
//思路 前缀和 + 排序
func kthLargestValue(matrix [][]int, k int) int {
m := len(matrix)
n := len(matrix[0])
result := make([]int, m*n)
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if i == 0 && j == 0 {
result[i*n+j] = matrix[i][j]
} else if i == 0 {
result[i*n+j] = matrix[i][j] ^ result[i*n+j-1]
} else if j == 0 {
result[i*n+j] = matrix[i][j] ^ result[(i-1)*n+j]
} else {
result[i*n+j] = matrix[i][j] ^ result[(i-1)*n+j-1] ^ result[i*n+j-1] ^ result[(i-1)*n+j]
}
}
}
sort.Ints(result)
return result[len(result)-k]
}
|
package commander
// actor Assigned to execute the command
type actor struct {
names []string // the keys contain one of names than execute action
triggers map[string]bool // the keys contain all true values and none false value in triggers than execute action
action Action // executed command
ignore bool // ignore this action
break_off bool // break off both actions
}
// addIncludeKeys append include keys to actor.triggers
func (a *actor) addIncludeKeys(keys []string) {
if keys != nil && len(keys) != 0 {
if a.triggers == nil {
a.triggers = make(map[string]bool)
}
for _, key := range keys {
a.triggers[key] = true
}
}
}
// getIncludeKeys get list of include keys
func (a actor) getIncludeKeys() (keys []string) {
for key, ok := range a.triggers {
if ok {
keys = append(keys, key)
}
}
return keys
}
// addExcludeKeys append exclude keys to actor.triggers
func (a *actor) addExcludeKeys(keys []string) {
if keys != nil && len(keys) != 0 {
if a.triggers == nil {
a.triggers = make(map[string]bool)
}
for _, key := range keys {
if _, ok := a.triggers[key]; !ok {
a.triggers[key] = false
}
}
}
}
// getExcludeKeys get list of exclude keys
func (a actor) getExcludeKeys() (keys []string) {
for key, ok := range a.triggers {
if !ok {
keys = append(keys, key)
}
}
return keys
}
// setAction set executive function to actor.action
// arg is ACTION function, see ./action.go
func (a *actor) setAction(arg interface{}) {
if action := parseAction(arg); !emptyAction(action) {
a.action = action
}
}
// hasAction there is a legitimate actor.action
func (a actor) hasAction() bool {
return a.action != nil
}
// Action set executive function to actor.action and include keys to actor.triggers
// action is ACTION function, see ./action.go
func (a *actor) Action(action interface{}, keys ...[]string) {
a.setAction(action)
if len(keys) != 0 {
a.addIncludeKeys(keys[0])
}
}
// allow Determine whether meet the requirements(actor.names or actor.triggers) for the execution
func (a actor) allow(c Context) (pass bool) {
//defer func() {
// fmt.Printf("----------allow----------"+
// "\n 1.actor %#v\n 2.argv %v\n 3.action %v\n 4.pass %v\n",
// a, c.Map(), a.action != nil, pass)
//}()
for key, ok := range a.triggers {
if !ok && c.Contain(key) {
pass = false
return
}
}
for _, key := range a.names {
if c.Contain(key) {
pass = true
return
}
}
for key, ok := range a.triggers {
if ok && !c.Contain(key) {
pass = false
return
}
}
pass = len(a.triggers) != 0
return
}
// run Common external function, if allow() than execute actor.action
func (a actor) run(c Context, force ...bool) (result _Result) {
//defer func() {
// fmt.Printf("----------run----------"+
// "\n 1.actor %#v\n 2.argv %v\n 3.action %v\n 4.result %#v\n",
// a, c.Map(), a.action != nil, result)
//}()
if a.action == nil {
return
} else if len(force) != 0 && force[0] {
} else if !a.allow(c) {
return
} else if a.ignore {
return resultPass()
}
result = a.action(c)
if a.break_off && result != nil && !result.Break() {
result.setBreak()
}
return
}
|
package impala
import (
"context"
"database/sql/driver"
"log"
"time"
"github.com/apache/thrift/lib/go/thrift"
"github.com/bippio/go-impala/hive"
)
// Conn to impala. It is not used concurrently by multiple goroutines.
type Conn struct {
t thrift.TTransport
session *hive.Session
client *hive.Client
log *log.Logger
}
// Ping impala server
func (c *Conn) Ping(ctx context.Context) error {
session, err := c.OpenSession(ctx)
if err != nil {
return err
}
if err := session.Ping(ctx); err != nil {
return err
}
return nil
}
// CheckNamedValue is called before passing arguments to the driver
// and is called in place of any ColumnConverter. CheckNamedValue must do type
// validation and conversion as appropriate for the driver.
func (c *Conn) CheckNamedValue(val *driver.NamedValue) error {
t, ok := val.Value.(time.Time)
if ok {
val.Value = t.Format(hive.TimestampFormat)
return nil
}
return driver.ErrSkip
}
// Prepare returns prepared statement
func (c *Conn) Prepare(query string) (driver.Stmt, error) {
return c.PrepareContext(context.Background(), query)
}
// PrepareContext returns prepared statement
func (c *Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
return &Stmt{
conn: c,
stmt: template(query),
}, nil
}
// QueryContext executes a query that may return rows
func (c *Conn) QueryContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Rows, error) {
session, err := c.OpenSession(ctx)
if err != nil {
return nil, err
}
tmpl := template(q)
stmt := statement(tmpl, args)
return query(ctx, session, stmt)
}
// ExecContext executes a query that doesn't return rows
func (c *Conn) ExecContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Result, error) {
session, err := c.OpenSession(ctx)
if err != nil {
return nil, err
}
tmpl := template(q)
stmt := statement(tmpl, args)
return exec(ctx, session, stmt)
}
// Begin is not supported
func (c *Conn) Begin() (driver.Tx, error) {
return nil, ErrNotSupported
}
// OpenSession ensure opened session
func (c *Conn) OpenSession(ctx context.Context) (*hive.Session, error) {
if c.session == nil {
session, err := c.client.OpenSession(ctx)
if err != nil {
return nil, err
}
c.session = session
}
return c.session, nil
}
// ResetSession closes hive session
func (c *Conn) ResetSession(ctx context.Context) error {
if c.session != nil {
if err := c.session.Close(ctx); err != nil {
return err
}
c.session = nil
}
return nil
}
// Close connection
func (c *Conn) Close() error {
c.log.Printf("close connection")
return c.t.Close()
}
|
package injection
import (
"context"
"github.com/stretchr/testify/assert"
"github.com/surmus/injection/test"
"net/http"
"reflect"
"testing"
)
var middlewareFnExecuted bool
type testRoutes struct {
t *testing.T
}
func (r *testRoutes) Use(handlerFnValues ...reflect.Value) Routes {
ctx := context.WithValue(context.Background(), test.CtxKey, test.CtxVal)
ctxValue := reflect.ValueOf(ctx)
for _, handlerValue := range handlerFnValues {
handlerValue.Call([]reflect.Value{ctxValue})
}
return r
}
func (r *testRoutes) Handle(httpMethod string, endPoint string, handlerFnValues ...reflect.Value) Routes {
assert.Equal(r.t, test.Endpoint, endPoint)
assert.Equal(r.t, test.HttpMethod, httpMethod)
ctx := context.WithValue(context.Background(), test.CtxKey, test.CtxVal)
ctxValue := reflect.ValueOf(ctx)
for _, handlerValue := range handlerFnValues {
handlerValue.Call([]reflect.Value{ctxValue})
}
return r
}
func (*testRoutes) HandlerFnType() reflect.Type {
return reflect.TypeOf(testHandlerFn)
}
type invalidHandlerTypeRoutes struct {
testRoutes
}
func (*invalidHandlerTypeRoutes) HandlerFnType() reflect.Type {
return reflect.TypeOf("string")
}
type invalidSignatureHandlerRoutes struct {
testRoutes
}
func (*invalidSignatureHandlerRoutes) HandlerFnType() reflect.Type {
return reflect.TypeOf(func() {})
}
type nonContextHandlerRoutes struct {
testRoutes
}
func (*nonContextHandlerRoutes) HandlerFnType() reflect.Type {
return reflect.TypeOf(func(interface{}) {})
}
type PointerController struct {
BaseController
primitiveZeroValue int
PrimitiveValConstant string
Context context.Context
valueWithInnerDependency test.DependencyInterface
valueRequiringContext *test.DependencyStruct
t *testing.T
}
func NewPointerController(t *testing.T) *PointerController {
return &PointerController{
PrimitiveValConstant: test.Constant,
t: t,
}
}
func (c *PointerController) Routes() map[string][]string {
return map[string][]string{test.Endpoint: {"GetTest"}}
}
func (c *PointerController) GetTest(context context.Context) {
assert.NotNil(c.t, c.Context)
assert.NotNil(c.t, c.valueRequiringContext)
assert.Equal(c.t, test.Constant, c.PrimitiveValConstant)
assert.NotNil(c.t, c.valueWithInnerDependency)
assert.Equal(c.t, 0, c.primitiveZeroValue)
assert.Equal(c.t, c.Context, c.valueRequiringContext.Ctx)
assert.Equal(c.t, c.Context, context)
assert.True(
c.t,
c.valueWithInnerDependency.(*test.DependencyStruct) == c.valueRequiringContext,
"valueWithInnerDependency interface should be created from valueRequiringContext",
)
}
type ValueController struct {
primitiveValConstant string
ValueRequiringContext *test.DependencyStruct
T *testing.T
}
func NewValueController(t *testing.T) ValueController {
return ValueController{
primitiveValConstant: test.Constant,
T: t,
}
}
func (c ValueController) Routes() map[string][]string {
return map[string][]string{test.Endpoint: {"HandleRequest"}}
}
func (c ValueController) Middleware() map[string][]Handler {
middlewareFnExecuted = false
return map[string][]Handler{"HandleRequest": {
func(valueRequiringContext *test.DependencyStruct) {
middlewareFnExecuted = true
},
}}
}
func (c ValueController) HandleRequest(context context.Context, valueWithInnerDependency test.DependencyInterface) {
assert.NotNil(c.T, c.ValueRequiringContext)
assert.Equal(c.T, test.Constant, c.primitiveValConstant)
assert.NotNil(c.T, valueWithInnerDependency)
assert.True(
c.T,
valueWithInnerDependency.(*test.DependencyStruct) == c.ValueRequiringContext,
"valueWithInnerDependency interface should be created from valueRequiringContext",
)
}
type InvalidRoutesMapController struct {
BaseController
}
func (c *InvalidRoutesMapController) Routes() map[string][]string {
return map[string][]string{test.Endpoint: {"PostTest"}}
}
type InvalidMiddlewareController struct {
ValueController
}
func (c InvalidMiddlewareController) Middleware() map[string][]Handler {
return map[string][]Handler{"HandleRequest": {"INVALID-VALUE"}}
}
func testHandlerFn(ctx context.Context) {}
func setupTestHandlerFn(t *testing.T) interface{} {
return func(
ctx context.Context,
valueWithInnerDependency test.DependencyInterface,
valueRequiringContext *test.DependencyStruct,
providedConstant string,
) {
assert.NotNil(t, ctx)
assert.NotNil(t, valueRequiringContext)
assert.Equal(t, test.Constant, providedConstant)
assert.NotNil(t, valueWithInnerDependency)
assert.Equal(t, ctx, valueRequiringContext.Ctx)
assert.True(
t,
valueWithInnerDependency.(*test.DependencyStruct) == valueRequiringContext,
"valueWithInnerDependency interface should be created from valueRequiringContext",
)
assert.Equal(t, test.CtxVal, ctx.Value(test.CtxKey))
}
}
func setupInjector(t *testing.T) *Injector {
valueRequiringContextProvider := func(ctx context.Context) *test.DependencyStruct {
return &test.DependencyStruct{Ctx: ctx}
}
constantProvider := func() string {
return test.Constant
}
valueWithInnerDependencyProvider := func(dependency *test.DependencyStruct) test.DependencyInterface {
return dependency
}
injector, _ := NewInjector(&testRoutes{t: t})
injector.RegisterProviders(valueWithInnerDependencyProvider, valueRequiringContextProvider, constantProvider)
return injector
}
func TestInjector_Handle(t *testing.T) {
testCases := map[string]func(t *testing.T){
"successfully register handler and handle request": func(t *testing.T) {
injector := setupInjector(t)
handleRegisterErr := injector.Handle(http.MethodGet, test.Endpoint, setupTestHandlerFn(t))
assert.Nil(t, handleRegisterErr)
},
"resolve singletonProvider only once": func(t *testing.T) {
var resolvedValues []*test.DependencyStruct
provider := func() *test.DependencyStruct { return &test.DependencyStruct{} }
injector, _ := NewInjector(&testRoutes{t: t})
err := injector.RegisterProviders(NewSingletonProvider(provider))
for i := 0; i < 2; i++ {
injector.Handle(http.MethodGet, test.Endpoint, func(singletonVal *test.DependencyStruct) {
resolvedValues = append(resolvedValues, singletonVal)
})
}
assert.Nil(t, err)
assert.Len(t, resolvedValues, 2)
assert.True(t, resolvedValues[0] == resolvedValues[1], "both values in resolvedValues should be same instance")
},
"resolve singletonProvider only once when singleton is dependency to non singleton provider": func(t *testing.T) {
var providerExecutedTimes int
provider := func(ctx context.Context) *test.DependencyStruct {
providerExecutedTimes++
return &test.DependencyStruct{}
}
provider2 := func(dep *test.DependencyStruct) test.DependencyInterface {
return dep
}
injector, _ := NewInjector(&testRoutes{t: t})
err := injector.RegisterProviders(NewSingletonProvider(provider), provider2)
for i := 0; i < 2; i++ {
injector.Handle(http.MethodGet, test.Endpoint, func(s test.DependencyInterface) {})
}
assert.Nil(t, err)
assert.Equal(t, 1, providerExecutedTimes)
},
"resolve new instance with non singletonProvider": func(t *testing.T) {
var resolvedValues []*test.DependencyStruct
provider := func() *test.DependencyStruct { return &test.DependencyStruct{} }
injector, _ := NewInjector(&testRoutes{t: t})
err := injector.RegisterProviders(provider)
for i := 0; i < 2; i++ {
injector.Handle(http.MethodGet, test.Endpoint, func(singletonVal *test.DependencyStruct) {
resolvedValues = append(resolvedValues, singletonVal)
})
}
assert.Nil(t, err)
assert.Len(t, resolvedValues, 2)
assert.True(t, resolvedValues[0] != resolvedValues[1], "both values should be different instances")
},
"fail to register handler with unregistered dependencies": func(t *testing.T) {
injector, _ := NewInjector(&testRoutes{t: t})
testHandlerFn := setupTestHandlerFn(t)
registrationError := injector.Handle(http.MethodGet, test.Endpoint, testHandlerFn)
assert.IsType(t, Error{}, registrationError)
},
}
for testName, testCase := range testCases {
t.Run(testName, testCase)
}
}
func TestInjector_Use(t *testing.T) {
testCases := map[string]func(t *testing.T){
"successfully register handler and handle request": func(t *testing.T) {
injector := setupInjector(t)
handleRegisterErr := injector.Use(setupTestHandlerFn(t))
assert.Nil(t, handleRegisterErr)
},
"fail to register handler with unregistered dependencies": func(t *testing.T) {
injector, _ := NewInjector(&testRoutes{t: t})
testHandlerFn := setupTestHandlerFn(t)
registrationError := injector.Use(testHandlerFn)
assert.IsType(t, Error{}, registrationError)
},
}
for testName, testCase := range testCases {
t.Run(testName, testCase)
}
}
func TestInjector_RegisterController(t *testing.T) {
tests := map[string]func(t *testing.T){
"successfully for Controller pointer receiver request handler method": func(t *testing.T) {
r := setupInjector(t)
registrationError := r.RegisterController(NewPointerController(t))
assert.Nil(t, registrationError)
},
"successfully for Controller value receiver request handler method": func(t *testing.T) {
r := setupInjector(t)
registrationError := r.RegisterController(NewValueController(t))
assert.Nil(t, registrationError)
},
"should execute controller method middleware": func(t *testing.T) {
r := setupInjector(t)
registrationError := r.RegisterController(NewValueController(t))
assert.Nil(t, registrationError)
assert.True(t, middlewareFnExecuted)
},
"fail registering Controller with invalid method middleware": func(t *testing.T) {
r := setupInjector(t)
registrationError := r.RegisterController(InvalidMiddlewareController{ValueController{T: t}})
assert.IsType(t, Error{}, registrationError)
},
"fail registering Controller with unregistered dependencies": func(t *testing.T) {
injector, _ := NewInjector(&testRoutes{t: t})
registrationError := injector.RegisterController(NewPointerController(t))
assert.IsType(t, Error{}, registrationError)
},
"fail registering Controller with incorrect routes mapping": func(t *testing.T) {
injector, _ := NewInjector(&testRoutes{t: t})
registrationError := injector.RegisterController(new(InvalidRoutesMapController))
assert.IsType(t, Error{}, registrationError)
},
}
for testName, testCase := range tests {
t.Run(testName, testCase)
}
}
func TestNewInjector(t *testing.T) {
testCases := map[string]func(t *testing.T){
"should register new injector": func(t *testing.T) {
injector, setupErr := NewInjector(&testRoutes{t: t})
assert.Nil(t, setupErr)
assert.NotNil(t, injector)
},
"should fail to register injector with non function routes request handler": func(t *testing.T) {
_, setupErr := NewInjector(&invalidHandlerTypeRoutes{testRoutes{t: t}})
assert.NotNil(t, setupErr)
},
"should fail to register injector with invalid signature routes request handler function": func(t *testing.T) {
_, setupErr := NewInjector(&invalidSignatureHandlerRoutes{testRoutes{t: t}})
assert.NotNil(t, setupErr)
},
"should fail to register injector with request handler when context param not implementing context": func(t *testing.T) {
_, setupErr := NewInjector(&nonContextHandlerRoutes{testRoutes{t: t}})
assert.NotNil(t, setupErr)
},
}
for testName, testCase := range testCases {
t.Run(testName, testCase)
}
}
func TestInjector_RegisterProviders(t *testing.T) {
testCases := map[string]func(t *testing.T){
"should register providers with injector": func(t *testing.T) {
valueRequiringContextProvider := func(ctx context.Context) *test.DependencyStruct {
return &test.DependencyStruct{Ctx: ctx}
}
constantProvider := func() string {
return test.Constant
}
valueWithInnerDependencyProvider := func(dependency *test.DependencyStruct) test.DependencyInterface {
return dependency
}
injector, _ := NewInjector(&testRoutes{t: t})
err := injector.RegisterProviders(
valueWithInnerDependencyProvider,
valueRequiringContextProvider,
constantProvider,
)
assert.Nil(t, err)
},
"should fail to register invalid type provider": func(t *testing.T) {
injector, _ := NewInjector(&testRoutes{t: t})
err := injector.RegisterProviders("INVALID-PROVIDER")
assert.NotNil(t, err)
assert.IsType(t, Error{}, err)
},
"should fail to register provider with invalid return values count": func(t *testing.T) {
injector, _ := NewInjector(&testRoutes{t: t})
err := injector.RegisterProviders(func() {})
assert.NotNil(t, err)
assert.IsType(t, Error{}, err)
},
"should fail to register provider with unregistered dependency": func(t *testing.T) {
injector, _ := NewInjector(&testRoutes{t: t})
err := injector.RegisterProviders(func(dependency *test.DependencyStruct) test.DependencyInterface {
return dependency
})
assert.NotNil(t, err)
assert.IsType(t, Error{}, err)
},
}
for testName, testCase := range testCases {
t.Run(testName, testCase)
}
}
func TestFrom(t *testing.T) {
dependencyValueProvider := func(ctx context.Context) *test.DependencyStruct {
return &test.DependencyStruct{Ctx: ctx}
}
valueWithDependencyProvider := func(dependency *test.DependencyStruct) test.DependencyInterface {
return dependency
}
injectorFrom, _ := NewInjector(&testRoutes{t: t})
injectorFrom.RegisterProviders(dependencyValueProvider)
injectorCpy, cpyCreationErr := From(injectorFrom, &testRoutes{t: t})
regError := injectorCpy.RegisterProviders(valueWithDependencyProvider)
assert.Nil(t, cpyCreationErr)
assert.Nil(t, regError)
// New injector does have previously registered test.DependencyInterface
assert.Nil(t, injectorCpy.RegisterProviders(func(test.DependencyInterface) int { return 1 }))
// Old injector does not have previously registered test.DependencyInterface
assert.NotNil(t, injectorFrom.RegisterProviders(func(test.DependencyInterface) int { return 1 }))
}
|
// Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package tpcc
import (
"time"
"github.com/cockroachdb/cockroach/pkg/workload/histogram"
"github.com/cockroachdb/errors"
"github.com/codahale/hdrhistogram"
)
// SpecWarehouseFactor is the default maximum per-warehouse newOrder
// throughput per second used to compute the maximum throughput value for a
// given warehouse count. This value is provided in the TPC-C spec.
const SpecWarehouseFactor = 12.86
// DeckWarehouseFactor is the warehouse factor to be used with the workload deck
// implemented in this package. This value differs from the spec's provided
// value as the deck mechanism used by workload differs from the default
// workload but is an acceptable alternative. This is the default value.
//
// The 12.605 is computed from the operation mix and the number of secs
// it takes to cycle through a deck:
//
// 10*(18+12) + 10*(3+12) + 1*(2+10) + 1*(2+5) + 1*(2+5) = 476
//
// 10 workers per warehouse times 10 newOrder ops per deck results in:
//
// (10*10)/(476/60) = 12.605...
//
const DeckWarehouseFactor = 12.605
// PassingEfficiency is a percentage of the theoretical maximum tpmC required
// to pass TPC-C.
const PassingEfficiency = 85.0
// These values represent the maximum allowable 90th-%ile latency for the
// given queries as specified in section 5.2.5.7 of the TPC-C spec.
var passing90ThPercentile = map[string]time.Duration{
"newOrder": 5 * time.Second,
"payment": 5 * time.Second,
"orderStatus": 5 * time.Second,
"delivery": 5 * time.Second,
"stockLevel": 20 * time.Second,
}
// Result represents the outcome of a TPCC run.
type Result struct {
// ActiveWarehouses is the number of warehouses used in the TPC-C run.
ActiveWarehouses int
// Cumulative maps from query name to the cumulative response time
// histogram for the TPC-C run.
Cumulative map[string]*hdrhistogram.Histogram
// Elapsed is the amount of time captured by the Cumulative.
Elapsed time.Duration
// WarehouseFactor is the maximal number of newOrder transactions per second
// per Warehouse. If zero it defaults to DeckWarehouseFactor which is derived
// from this workload. The value is used to compute the efficiency of the run.
WarehouseFactor float64
}
// MergeResults returns a result value constructed by merging the arguments.
// It should only be used if the number of ActiveWarehouses matches and will
// panic if they differ. Elapsed is computed as the max of all elapsed values
// and makes the assumption that the distributions roughly overlap in time.
// This should be used when merging from multiple load generators during the
// same test run.
func MergeResults(results ...*Result) *Result {
if len(results) == 0 {
return nil
}
base := &Result{
ActiveWarehouses: results[0].ActiveWarehouses,
Cumulative: make(map[string]*hdrhistogram.Histogram,
len(results[0].Cumulative)),
WarehouseFactor: results[0].WarehouseFactor,
}
for _, r := range results {
if r.Elapsed > base.Elapsed {
base.Elapsed = r.Elapsed
}
if r.ActiveWarehouses != base.ActiveWarehouses {
panic(errors.Errorf("cannot merge histograms with different "+
"ActiveWarehouses values: got both %v and %v",
r.ActiveWarehouses, base.ActiveWarehouses))
}
for q, h := range r.Cumulative {
if cur, exists := base.Cumulative[q]; exists {
cur.Merge(h)
} else {
base.Cumulative[q] = histogram.Copy(h)
}
}
}
return base
}
// NewResult constructs a new Result.
func NewResult(
activeWarehouses int,
warehouseFactor float64,
elapsed time.Duration,
cumulative map[string]*hdrhistogram.Histogram,
) *Result {
return &Result{
ActiveWarehouses: activeWarehouses,
WarehouseFactor: warehouseFactor,
Elapsed: elapsed,
Cumulative: cumulative,
}
}
// NewResultWithSnapshots creates a new result from a deserialized set of
// histogram snapshots.
func NewResultWithSnapshots(
activeWarehouses int, warehouseFactor float64, snapshots map[string][]histogram.SnapshotTick,
) *Result {
var start time.Time
var end time.Time
ret := make(map[string]*hdrhistogram.Histogram, len(snapshots))
for n, snaps := range snapshots {
var cur *hdrhistogram.Histogram
for _, s := range snaps {
h := hdrhistogram.Import(s.Hist)
if cur == nil {
cur = h
} else {
cur.Merge(h)
}
if start.IsZero() || s.Now.Before(start) {
start = s.Now
}
if sEnd := s.Now.Add(s.Elapsed); end.IsZero() || sEnd.After(end) {
end = sEnd
}
}
ret[n] = cur
}
return NewResult(activeWarehouses, warehouseFactor, end.Sub(start), ret)
}
// TpmC returns a tpmC value with a warehouse factor of 12.86.
// TpmC will panic if r does not contain a "newOrder" histogram in Cumulative.
func (r *Result) TpmC() float64 {
no := r.Cumulative["newOrder"]
if no == nil {
return 0
}
return float64(no.TotalCount()) / (r.Elapsed.Seconds() / 60)
}
// Efficiency returns the efficiency of a TPC-C run.
// It relies on the WarehouseFactor which defaults to DeckWarehouseFactor.
func (r *Result) Efficiency() float64 {
tpmC := r.TpmC()
warehouseFactor := r.WarehouseFactor
if warehouseFactor == 0 {
warehouseFactor = DeckWarehouseFactor
}
return (100 * tpmC) / (warehouseFactor * float64(r.ActiveWarehouses))
}
// FailureError returns nil if the Result is passing or an error describing
// the failure if the result is failing.
func (r *Result) FailureError() error {
if _, newOrderExists := r.Cumulative["newOrder"]; !newOrderExists {
return errors.Errorf("no newOrder data exists")
}
// Collect all failing criteria errors into errs so that the returned error
// contains information about all of the failures.
var err error
if eff := r.Efficiency(); eff < PassingEfficiency {
err = errors.CombineErrors(err,
errors.Errorf("efficiency value of %v is below passing threshold of %v",
eff, PassingEfficiency))
}
for query, max90th := range passing90ThPercentile {
h, exists := r.Cumulative[query]
if !exists {
return errors.Errorf("no %v data exists", query)
}
if v := time.Duration(h.ValueAtQuantile(.9)); v > max90th {
err = errors.CombineErrors(err,
errors.Errorf("90th percentile latency for %v at %v exceeds passing threshold of %v",
query, v, max90th))
}
}
return err
}
|
package bucket
import (
"fmt"
"testing"
)
func TestCRUDValue(t *testing.T) {
b := NewLocalBucket("my.db")
if err := b.Open(); err != nil {
t.Error(err)
}
defer b.Close()
n := 10
for i := 0; i < n; i++ {
err := b.Put(fmt.Sprintf("Key#%d", i+1), []byte(fmt.Sprintf("Value#%d", i+1)))
if err != nil {
t.Error(err)
}
}
k, v, err := b.First()
if err != nil {
t.Error(err)
}
t.Log(k, string(v))
keys, err := b.BucketKeys()
if err != nil {
t.Error(err)
}
if len(keys) != n {
t.Error("Number of keys not matches")
}
for _, k := range keys {
if err := b.Remove(k); err != nil {
t.Error(err)
}
}
keys, err = b.BucketKeys()
if err != nil {
t.Error(err)
}
if len(keys) != 0 {
t.Error("Should be empty")
}
}
func TestBuckets(t *testing.T) {
b := NewLocalBucket("my.db")
if err := b.Open(); err != nil {
t.Error(err)
}
defer b.Close()
if err := b.CreateBucket("B1"); err != nil {
t.Error(err)
}
if err := b.CreateBucket("B2"); err != nil {
t.Error(err)
}
names, err := b.BucketNames()
if err != nil {
t.Error(err)
}
if err := b.RemoveAll(); err != nil {
t.Error(err)
}
names, err = b.BucketNames()
if err != nil {
t.Error(err)
}
if len(names) != 0 {
t.Error("Should no buckets")
}
}
|
/*
Copyright 2018 Bitnine Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package ag
import (
"bytes"
"database/sql/driver"
"errors"
"fmt"
"regexp"
"strconv"
)
// GraphId is a unique ID for a vertex and an edge.
type GraphId struct {
// Valid is true if GraphId is not NULL
Valid bool
b []byte
}
var nullGraphId = GraphId{}
var graphIdRegexp = regexp.MustCompile(`^(\d+)\.(\d+)$`)
// NewGraphId returns GraphId of str if str is between "1.1" and
// "65535.281474976710656". If str is "NULL", it returns GraphId whose Valid is
// false. Otherwise, it returns an error.
func NewGraphId(str string) (GraphId, error) {
if str == "NULL" {
return nullGraphId, nil
}
err := validateGraphId(str)
if err != nil {
return GraphId{}, err
}
return GraphId{true, []byte(str)}, nil
}
const (
labelBit = 16
localBit = 48
)
func validateGraphId(str string) error {
m := graphIdRegexp.FindStringSubmatch(str)
if m == nil {
return fmt.Errorf("bad graphid representation: %q", str)
}
i, err := strconv.ParseUint(m[1], 10, labelBit)
if err != nil {
return errors.New("invalid label ID: " + err.Error())
}
if i == 0 {
return fmt.Errorf("invalid label ID: %d", i)
}
i, err = strconv.ParseUint(m[2], 10, localBit)
if err != nil {
return errors.New("invalid local ID: " + err.Error())
}
if i == 0 {
return fmt.Errorf("invalid local ID: %d", i)
}
return nil
}
// Equal reports whether gid and x are the same GraphId.
func (gid GraphId) Equal(x GraphId) bool {
if !gid.Valid || !x.Valid {
return false
}
return bytes.Equal(gid.b, x.b)
}
func (gid GraphId) String() string {
if gid.Valid {
return string(gid.b)
} else {
return "NULL"
}
}
// Scan implements the database/sql Scanner interface.
func (gid *GraphId) Scan(src interface{}) error {
if src == nil {
gid.Valid, gid.b = false, nil
return nil
}
b, ok := src.([]byte)
if !ok {
return fmt.Errorf("invalid source for graphid: %T", src)
}
if len(b) < 1 {
return fmt.Errorf("invalid source for graphid: %v", b)
}
err := validateGraphId(string(b))
if err != nil {
return err
}
gid.Valid, gid.b = true, append([]byte(nil), b...)
return nil
}
// Value implements the database/sql/driver Valuer interface.
func (gid GraphId) Value() (driver.Value, error) {
if gid.Valid {
return gid.b, nil
} else {
return nil, nil
}
}
type graphIdArray []GraphId
// separated by comma (see graphid in pg_type.h)
const graphIdSeparator = byte(054)
func (a *graphIdArray) Scan(src interface{}) error {
if src == nil {
*a = nil
return nil
}
b, ok := src.([]byte)
if !ok {
return fmt.Errorf("invalid source for _graphid: %T", src)
}
if len(b) < 1 {
return fmt.Errorf("invalid source for _graphid: %v", b)
}
// remove surrounding braces
b = b[1 : len(b)-1]
// bytes.Split() returns [][]byte{[]byte{}} even if len(b) < 1.
// In this case, return empty []GraphId to distinguish between NULL and
// empty _graphid.
if len(b) < 1 {
*a = []GraphId{}
return nil
}
ss := bytes.Split(b, []byte{graphIdSeparator})
gids := make([]GraphId, len(ss))
for i, s := range ss {
if bytes.Equal(s, nullElementValue) {
gids[i] = nullGraphId
continue
}
err := gids[i].Scan(s)
if err != nil {
return errors.New("bad _graphid representation: " + err.Error())
}
}
*a = gids
return nil
}
func (a graphIdArray) Value() (driver.Value, error) {
if a == nil {
return nil, nil
}
if n := len(a); n > 0 {
// '{' + "d.d,"*n - ',' + '}' = 1+4*n-1+1 = 4*n+1
b := make([]byte, 1, 4*n+1)
b[0] = byte('{')
for i := 0; i < n; i++ {
if i > 0 {
b = append(b, graphIdSeparator)
}
if a[i].Valid {
val, _ := a[i].Value()
b = append(b, val.([]byte)...)
} else {
b = append(b, nullElementValue...)
}
}
b = append(b, '}')
return b, nil
}
return []byte("{}"), nil
}
|
package main
import "fmt"
/**
值传递与指针传递
*/
func main_() {
a := 10
b := 20
swap(a, b) //新建内存空间,存值,即10 ,20
fmt.Printf("main: a = %d,b= %d\n", a, b)
}
/**
传值:交换a,b的值
*/
func swap(a, b int) {
a, b = b, a
fmt.Printf("swap: a = %d,b= %d\n", a, b)
}
func main() {
a := 10
b := 20
fmt.Println("main:指针&a指向的值为,", *&a)
fmt.Printf("main: &a = %v,&b= %v\n", &a, &b)
swap_(&a, &b) //新建内存空间,存地址,即:0xc00000a0a8,0xc00000a0c0
fmt.Printf("main: a = %d,b= %d\n", a, b)
}
/**
传地址:交换a,b的值
*/
func swap_(pointer_a, pointer_b *int) {
fmt.Println("swap_:指针pointer_a指向的值为,", *pointer_a) //取地址的值
fmt.Printf("swap_: pointer_a = %v,pointer_b= %v\n", pointer_a, pointer_b) //打印指针
*pointer_a, *pointer_b = *pointer_b, *pointer_a //把指针b指向的值,赋予指针a指向的内存,
// 把指针a指向的值,赋予指针b指向的内存
fmt.Printf("swap_: a = %d,b= %d\n", *pointer_a, *pointer_b)
}
|
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"time"
)
type HttpClient struct {
c *http.Client
endpoint string
}
func NewHttpClient(endpoint string) *HttpClient {
hc := &http.Client{
Transport: &http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, time.Second * 8)
},
ResponseHeaderTimeout: time.Second * 5,
},
Timeout: time.Second * 10,
}
return &HttpClient{
c: hc,
endpoint: endpoint,
}
}
func (hc *HttpClient) ForwardLog(req ForwardLogRequest) ForwardLogResponse {
resp := ForwardLogResponse{}
reqBytes, err := json.Marshal(req)
if err != nil {
fmt.Println(err)
return resp
}
bodyReader := bytes.NewReader(reqBytes)
url := fmt.Sprintf("%s/forwardLog", hc.endpoint)
respObj, err := hc.c.Post(url, "application/json", bodyReader)
if err != nil {
fmt.Println(err)
return resp
}
respBytes, err := io.ReadAll(respObj.Body)
if err != nil {
fmt.Println(err)
return resp
}
defer respObj.Body.Close()
if err := json.Unmarshal(respBytes, &resp); err != nil {
fmt.Println(err)
return resp
}
return resp
}
|
package model
type Product struct {
HotelId int64 `json:"hotel,omitempty"`
Id int64 `json:"id,omitempty"`
UserId int64 `json:"usuario,omitempty"`
GroupId int64 `json:"grupo,omitempty"`
CfpopId int64 `json:"cfop,omitempty"`
Code string `json:"codigo,omitempty"`
BarCode string `json:"codigo_barras,omitempty"`
Description string `json:"descricao,omitempty"`
Comment string `json:"observacao,omitempty"`
MinStock float64 `json:"estoque_minimo,omitempty"`
MaxStock float64 `json:"estoque_maximo,omitempty"`
Stock float64 `json:"estoque,omitempty"`
CreatedAt string `json:"data_cadastro,omitempty"`
Cost float64 `json:"custo,omitempty"`
Price float64 `json:"preco,omitempty"`
ProfitMargin float64 `json:"margem_lucro,omitempty"`
IsActive string `json:"activo,omitempty"`
StockWatch string `json:"controla_estoque,omitempty"`
Buyings float64 `json:"total_compras,omitempty"`
Sales float64 `json:"total_vendas,omitempty"`
Consumption float64 `json:"total_consumo,omitempty"`
Unit string `json:"unidade,omitempty"`
Outlet float64 `json:"total_saida,omitempty"`
IcmsEcf string `json:"icms_ecf,omitempty"`
Tax float64 `json:"imposto,omitempty"`
FederalTax float64 `json:"imposto_federal,omitempty"`
StateTax float64 `json:"imposto_estadual,omitempty"`
MunicipalTax float64 `json:"imposto_municipal,omitempty"`
TaxSource float64 `json:"fonte_imposto,omitempty"`
PreparingTime int64 `json:"tempo_preparo,omitempty"`
Discrete string `json:"descritivo,omitempty"`
ServiceTax float64 `json:"taxa_servico,omitempty"`
Alcohool string `json:"bebida_alcoolica,omitempty"`
Spotlight string `json:"destaque,omitempty"`
}
|
package controller
import (
"golang.org/x/net/context"
"google.golang.org/grpc"
"github.com/brocaar/loraserver/api/nc"
)
// NopNetworkControllerClient is a dummy network-controller client which is
// used when no network-controller is present / configured.
type NopNetworkControllerClient struct{}
// HandleRXInfo publishes rx related meta-data.
func (n *NopNetworkControllerClient) HandleRXInfo(ctx context.Context, in *nc.HandleRXInfoRequest, opts ...grpc.CallOption) (*nc.HandleRXInfoResponse, error) {
return &nc.HandleRXInfoResponse{}, nil
}
// HandleDataUpMACCommand publishes a mac-command received by an end-device.
// This method will only be called in case the mac-command request was
// enqueued throught the API or when the CID is >= 0x80 (proprietary
// mac-command range).
func (n *NopNetworkControllerClient) HandleDataUpMACCommand(ctx context.Context, in *nc.HandleDataUpMACCommandRequest, opts ...grpc.CallOption) (*nc.HandleDataUpMACCommandResponse, error) {
return &nc.HandleDataUpMACCommandResponse{}, nil
}
|
package main
import (
"sync"
"math/rand"
"time"
"fmt"
)
var count int //定义一个全局变量
var rwMutex sync.RWMutex
func main() {
quit := make(chan bool)
for i := 0; i < 5; i++ {
go write()
}
for i := 0; i < 5; i++ {
go read()
}
<-quit
}
func read() {
for {
rwMutex.RLock()
fmt.Println("读取", count)
rwMutex.RUnlock()
}
}
func write() {
for {
rwMutex.Lock()
rand.Seed(time.Now().UnixNano())
count = rand.Intn(10)
fmt.Println("写入", count)
rwMutex.Unlock()
}
}
|
package messageBus
import (
"fmt"
"os"
"github.com/streadway/amqp"
)
const (
host = "localhost"
port = 5672
user = "guest"
password = "guest"
)
// Connect establishes a connection
// to the RabbitMQ instance
func Connect() (*amqp.Connection, error) {
var url string
if os.Getenv("RABBITMQ_HOST") != "" {
url = fmt.Sprintf("amqp://%s:%s@%s", user, password, os.Getenv("RABBITMQ_HOST"))
} else {
url = fmt.Sprintf("amqp://%s:%s@%s:%d", user, password, host, port)
}
connection, err := amqp.Dial(url)
if err != nil {
return nil, err
}
return connection, nil
}
// CreateChannel create a channel
// from the given connection
func CreateChannel(connection *amqp.Connection) (*amqp.Channel, error) {
channel, err := connection.Channel()
if err != nil {
return nil, err
}
return channel, nil
}
// CreateExchange creates an events exchange
func CreateExchange(channel *amqp.Channel) error {
return channel.ExchangeDeclare("events",
"topic",
true,
false,
false,
false,
nil,
)
}
// EstablishPublishQueue create exchange & links queue
func EstablishPublishQueue(channel *amqp.Channel) error {
err := CreateExchange(channel)
if err != nil {
return err
}
err = CreateQueueAndBind(channel, "links")
if err != nil {
return err
}
return nil
}
// CreateQueueAndBind declares a queue
// and binds it to our channel
func CreateQueueAndBind(channel *amqp.Channel, queue string) error {
// Create a queue
_, err := channel.QueueDeclare(queue, true, false, false, false, nil)
if err != nil {
return err
}
// Bind the queue to the exchange
err = channel.QueueBind(queue, "#", "events", false, nil)
if err != nil {
return err
}
return nil
}
// CreateMessage takes in our message body and
// creates a message to used sent in our queue
func CreateMessage(body string) amqp.Publishing {
return amqp.Publishing{
Body: []byte(body),
}
}
// PublishMessage sends our RabbitMQ messages to the queue
func PublishMessage(message amqp.Publishing, channel *amqp.Channel) error {
return channel.Publish("events",
"key",
false,
false,
message,
)
}
// ConsumeMessages subscribes and waits for messages in the queue
func ConsumeMessages(queue string, channel *amqp.Channel) (<-chan amqp.Delivery, error) {
messages, err := channel.Consume(queue,
"",
true,
false,
false,
false,
nil,
)
if err != nil {
return nil, err
}
return messages, err
}
|
package main
import (
"fmt"
"io/ioutil"
"log"
)
func GetAllFile(filepath string, s []string) ([]string, error){
fileInfo, err := ioutil.ReadDir(filepath)
if err != nil {
log.Println("read dir failed: ", err)
return s, nil
}
level := 2
for _, child := range fileInfo {
if level < 0 {
return s, nil
}
if child.IsDir() {
fullpath := filepath + "/" + child.Name()
s, err = GetAllFile(fullpath, s)
if err != nil {
log.Println("read dir failed: ", err)
return s, nil
}
} else {
fullName := filepath + "/" + child.Name()
s = append(s, fullName)
}
level--
}
return s, nil
}
func main() {
var s []string
s, _ = GetAllFile("/Users/lichunliang/workspace/go-db-test", s)
for _, v := range s {
fmt.Printf("file slice: %v\n", v)
}
} |
package ledger
import (
"context"
"time"
)
type MerchantRepository interface {
Merchant(ctx context.Context, id string) (*Merchant, error)
MerchantByAlias(ctx context.Context, alias string) (*Merchant, error)
Merchants(ctx context.Context) ([]*Merchant, error)
CreateMerchant(ctx context.Context, merchant *Merchant) (*Merchant, error)
CreateMerchantTx(ctx context.Context, tx Transactioner, merchant *Merchant) (*Merchant, error)
UpdateMerchant(ctx context.Context, id string, merchant *Merchant) (*Merchant, error)
UpdateMerchantTx(ctx context.Context, tx Transactioner, id string, merchant *Merchant) (*Merchant, error)
DeleteMerchant(ctx context.Context, id string) error
DeleteMerchantTx(ctx context.Context, tx Transactioner, id string) error
MerchantAliasesByMerchantID(ctx context.Context, merchantID string) ([]*MerchantAlias, error)
CreateMerchantAlias(ctx context.Context, alias *MerchantAlias) (*MerchantAlias, error)
CreateMerchantAliasTx(ctx context.Context, tx Transactioner, alias *MerchantAlias) (*MerchantAlias, error)
UpdateMerchantAlias(ctx context.Context, aliasID string, alias *MerchantAlias) (*MerchantAlias, error)
UpdateMerchantAliasTx(ctx context.Context, tx Transactioner, aliasID string, alias *MerchantAlias) (*MerchantAlias, error)
}
type Merchant struct {
ID string `db:"id" json:"id"`
Name string `db:"name" json:"name"`
CreatedAt time.Time `db:"created_at" json:"createdAt"`
UpdatedAt time.Time `db:"updated_at" json:"updatedAt"`
}
type MerchantAlias struct {
AliasID string `db:"alias_id" json:"aliasID"`
MerchantID string `db:"merchant_id" json:"id"`
Alias string `db:"alias" json:"name"`
CreatedAt time.Time `db:"created_at" json:"createdAt"`
UpdatedAt time.Time `db:"updated_at" json:"updatedAt"`
}
|
package order
import (
"context"
"fmt"
"net"
"net/http"
"strings"
"time"
"github.com/bakins/kubernetes-envoy-example/api/item"
"github.com/bakins/kubernetes-envoy-example/api/order"
"github.com/bakins/kubernetes-envoy-example/util"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
grpc_validator "github.com/grpc-ecosystem/go-grpc-middleware/validator"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/hkwi/h2c"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"google.golang.org/grpc"
)
func init() {
grpc_prometheus.EnableHandlingTimeHistogram()
}
// OptionsFunc sets options when creating a new server.
type OptionsFunc func(*Server) error
// Server is a wrapper for a simple front end HTTP server
type Server struct {
address string
endpoint string
server *http.Server
grpc *grpc.Server
store *orderStore
item item.ItemServiceClient
}
// New creates a new server
func New(options ...OptionsFunc) (*Server, error) {
s := &Server{
address: ":8080",
endpoint: "127.0.0.1:9090",
}
for _, f := range options {
if err := f(s); err != nil {
return nil, errors.Wrap(err, "options function failed")
}
}
ctx := context.Background()
conn, err := grpc.DialContext(
ctx,
s.endpoint,
grpc.WithInsecure(),
grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(
util.UnaryClientInterceptor(),
grpc_prometheus.UnaryClientInterceptor,
)),
grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient(
grpc_prometheus.StreamClientInterceptor,
)),
)
if err != nil {
return nil, errors.Wrap(err, "could not create grpc client")
}
s.item = item.NewItemServiceClient(conn)
s.store = newOrderStore(s, s.item)
// TODO: option to load this or not
s.store.LoadSampleData()
return s, nil
}
// SetAddress sets the listening address.
func SetAddress(address string) OptionsFunc {
return func(s *Server) error {
s.address = address
return nil
}
}
// SetEndpoint sets the address for contacting other services.
func SetEndpoint(address string) OptionsFunc {
return func(s *Server) error {
s.endpoint = address
return nil
}
}
// Run starts the server. This generally does not return.
func (s *Server) Run() error {
logger, err := util.NewDefaultLogger()
if err != nil {
return errors.Wrapf(err, "failed to create logger")
}
l, err := net.Listen("tcp", s.address)
if err != nil {
return errors.Wrapf(err, "failed to listen on %s", s.address)
}
grpc_zap.ReplaceGrpcLogger(logger)
grpc_prometheus.EnableHandlingTimeHistogram()
s.grpc = grpc.NewServer(
grpc.UnaryInterceptor(
grpc_middleware.ChainUnaryServer(
util.UnaryServerInterceptor(),
util.UnaryServerSleeperInterceptor(time.Second*3),
grpc_validator.UnaryServerInterceptor(),
grpc_prometheus.UnaryServerInterceptor,
grpc_zap.UnaryServerInterceptor(logger),
grpc_recovery.UnaryServerInterceptor(),
),
),
)
gwmux := runtime.NewServeMux()
_, port, err := net.SplitHostPort(s.address)
if err != nil {
return errors.Wrapf(err, "invalid address %s", s.address)
}
if err := order.RegisterOrderServiceHandlerFromEndpoint(context.Background(), gwmux, net.JoinHostPort("127.0.0.1", port), []grpc.DialOption{grpc.WithInsecure()}); err != nil {
return errors.Wrap(err, "failed to register grpc gateway")
}
order.RegisterOrderServiceServer(s.grpc, s.store)
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
mux.HandleFunc("/healthz", healthz)
mux.Handle("/", gwmux)
s.server = &http.Server{
Handler: h2c.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ProtoMajor == 2 &&
strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
s.grpc.ServeHTTP(w, r)
} else {
mux.ServeHTTP(w, r)
}
}),
},
}
if err := s.server.Serve(l); err != nil {
if err != http.ErrServerClosed {
return errors.Wrap(err, "failed to start http server")
}
}
return nil
}
// Stop will stop the server
func (s *Server) Stop() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
s.server.Shutdown(ctx)
}
func healthz(wr http.ResponseWriter, r *http.Request) {
fmt.Fprintf(wr, "OK\n")
}
|
package cache
import "sync"
type lockCache struct {
mu sync.RWMutex
items map[string]interface{}
}
func newLockCache() Cache {
return &lockCache{items: make(map[string]interface{})}
}
func (lc *lockCache) Get(k string) (interface{}, bool, error) {
lc.mu.RLock()
v, ok := lc.items[k]
lc.mu.RUnlock()
return v, ok, nil
}
func (lc *lockCache) Set(k string, v interface{}) error {
lc.mu.Lock()
lc.items[k] = v
lc.mu.Unlock()
return nil
}
func (lc *lockCache) Evict(k string) error {
lc.mu.Lock()
delete(lc.items, k)
lc.mu.Unlock()
return nil
}
func (lc *lockCache) Close() error { return nil }
|
// tx_test
package tx
import (
"encoding/hex"
"testing"
)
const (
txHex = "01000000" + // version
"01" + // n inputs
"26c07ece0bce7cda0ccd14d99e205f118cde27e83dd75da7b141fe487b5528fb" + //prev txid
"00000000" + // output index
"8b" + // length of scriptSig
"48304502202b7e37831273d74c8b5b1956c23e79acd660635a8d1063d413c50b218eb6bc8a022100a10a3a7b5aaa0f07827207daf81f718f51eeac96695cf1ef9f2020f21a0de02f01410452684bce6797a0a50d028e9632be0c2a7e5031b710972c2a3285520fb29fcd4ecfb5fc2bf86a1e7578e4f8a305eeb341d1c6fc0173e5837e2d3c7b178aade078" +
"ffffffff" + // sequence
"02" + // n outputs
"b06c191e01000000" + // amount of ouput 1
"19" + // length of output 1 script
"76a9143564a74f9ddb4372301c49154605573d7d1a88fe88ac" +
"00e1f50500000000" + // amount of ouput 2
"19" + // length of output 2 script
"76a914010966776006953d5567439e5e39f86a0d273bee88ac" +
"00000000" // lock time
privKey = "18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725"
sendToAddr = "1runeksijzfVxyrpiyCY2LCBvYsSiFsCm"
)
func TestDecodeTx(t *testing.T) {
b, err := hex.DecodeString(txHex)
if err != nil {
t.Fatal(err)
}
tx := &Tx{}
if err = tx.UnmarshalBinary(b); err != nil {
t.Fatal(err)
}
t.Logf("%#v", tx)
b, err = tx.MarshalBinary()
if err != nil {
t.Fatal(err)
}
t.Log(hex.EncodeToString(b) == txHex)
t.Log(tx.Hash())
}
func TestSignTx(t *testing.T) {
b, err := hex.DecodeString(txHex)
if err != nil {
t.Fatal(err)
}
tx := &Tx{}
if err = tx.UnmarshalBinary(b); err != nil {
t.Fatal(err)
}
sigMsg, err := tx.Sign(privKey)
if err != nil {
t.Fatal(err)
}
t.Log(sigMsg)
}
|
package date
import (
"errors"
"strconv"
"time"
)
//FromString converts YYYY-MM-DD string to time.Time
func FromString(s string) (time.Time, error) {
if len(s) != 10 {
return time.Time{}, errors.New("wrong format")
}
year := s[:4]
month := s[5:7]
day := s[8:]
y, err := strconv.Atoi(year)
if err != nil {
return time.Time{}, errors.New("wrong format")
}
m, err := strconv.Atoi(month)
if err != nil {
return time.Time{}, errors.New("wrong format")
}
d, err := strconv.Atoi(day)
if err != nil {
return time.Time{}, errors.New("wrong format")
}
if m < 1 || m > 12 {
return time.Time{}, errors.New("wrong format")
}
loc, _ := time.LoadLocation("")
res := time.Date(y, time.Month(m), d, 0, 0, 0, 0, loc)
return res, nil
}
func CurDate() time.Time {
loc, _ := time.LoadLocation("")
return time.Now().In(loc)
}
//ToString converts time.Time to YYYY-MM-DD string
func ToString(t time.Time) string {
y := strconv.Itoa(t.Year())
m := strconv.Itoa(int(t.Month()))
d := strconv.Itoa(t.Day())
for len(y) < 4 {
y = "0" + y
}
for len(m) < 2 {
m = "0" + m
}
for len(d) < 2 {
d = "0" + d
}
return y + "-" + m + "-" + d
}
|
package odoo
import (
"fmt"
)
// WebTourTour represents web_tour.tour model.
type WebTourTour struct {
LastUpdate *Time `xmlrpc:"__last_update,omptempty"`
DisplayName *String `xmlrpc:"display_name,omptempty"`
Id *Int `xmlrpc:"id,omptempty"`
Name *String `xmlrpc:"name,omptempty"`
UserId *Many2One `xmlrpc:"user_id,omptempty"`
}
// WebTourTours represents array of web_tour.tour model.
type WebTourTours []WebTourTour
// WebTourTourModel is the odoo model name.
const WebTourTourModel = "web_tour.tour"
// Many2One convert WebTourTour to *Many2One.
func (wt *WebTourTour) Many2One() *Many2One {
return NewMany2One(wt.Id.Get(), "")
}
// CreateWebTourTour creates a new web_tour.tour model and returns its id.
func (c *Client) CreateWebTourTour(wt *WebTourTour) (int64, error) {
ids, err := c.CreateWebTourTours([]*WebTourTour{wt})
if err != nil {
return -1, err
}
if len(ids) == 0 {
return -1, nil
}
return ids[0], nil
}
// CreateWebTourTour creates a new web_tour.tour model and returns its id.
func (c *Client) CreateWebTourTours(wts []*WebTourTour) ([]int64, error) {
var vv []interface{}
for _, v := range wts {
vv = append(vv, v)
}
return c.Create(WebTourTourModel, vv)
}
// UpdateWebTourTour updates an existing web_tour.tour record.
func (c *Client) UpdateWebTourTour(wt *WebTourTour) error {
return c.UpdateWebTourTours([]int64{wt.Id.Get()}, wt)
}
// UpdateWebTourTours updates existing web_tour.tour records.
// All records (represented by ids) will be updated by wt values.
func (c *Client) UpdateWebTourTours(ids []int64, wt *WebTourTour) error {
return c.Update(WebTourTourModel, ids, wt)
}
// DeleteWebTourTour deletes an existing web_tour.tour record.
func (c *Client) DeleteWebTourTour(id int64) error {
return c.DeleteWebTourTours([]int64{id})
}
// DeleteWebTourTours deletes existing web_tour.tour records.
func (c *Client) DeleteWebTourTours(ids []int64) error {
return c.Delete(WebTourTourModel, ids)
}
// GetWebTourTour gets web_tour.tour existing record.
func (c *Client) GetWebTourTour(id int64) (*WebTourTour, error) {
wts, err := c.GetWebTourTours([]int64{id})
if err != nil {
return nil, err
}
if wts != nil && len(*wts) > 0 {
return &((*wts)[0]), nil
}
return nil, fmt.Errorf("id %v of web_tour.tour not found", id)
}
// GetWebTourTours gets web_tour.tour existing records.
func (c *Client) GetWebTourTours(ids []int64) (*WebTourTours, error) {
wts := &WebTourTours{}
if err := c.Read(WebTourTourModel, ids, nil, wts); err != nil {
return nil, err
}
return wts, nil
}
// FindWebTourTour finds web_tour.tour record by querying it with criteria.
func (c *Client) FindWebTourTour(criteria *Criteria) (*WebTourTour, error) {
wts := &WebTourTours{}
if err := c.SearchRead(WebTourTourModel, criteria, NewOptions().Limit(1), wts); err != nil {
return nil, err
}
if wts != nil && len(*wts) > 0 {
return &((*wts)[0]), nil
}
return nil, fmt.Errorf("web_tour.tour was not found with criteria %v", criteria)
}
// FindWebTourTours finds web_tour.tour records by querying it
// and filtering it with criteria and options.
func (c *Client) FindWebTourTours(criteria *Criteria, options *Options) (*WebTourTours, error) {
wts := &WebTourTours{}
if err := c.SearchRead(WebTourTourModel, criteria, options, wts); err != nil {
return nil, err
}
return wts, nil
}
// FindWebTourTourIds finds records ids by querying it
// and filtering it with criteria and options.
func (c *Client) FindWebTourTourIds(criteria *Criteria, options *Options) ([]int64, error) {
ids, err := c.Search(WebTourTourModel, criteria, options)
if err != nil {
return []int64{}, err
}
return ids, nil
}
// FindWebTourTourId finds record id by querying it with criteria.
func (c *Client) FindWebTourTourId(criteria *Criteria, options *Options) (int64, error) {
ids, err := c.Search(WebTourTourModel, criteria, options)
if err != nil {
return -1, err
}
if len(ids) > 0 {
return ids[0], nil
}
return -1, fmt.Errorf("web_tour.tour was not found with criteria %v and options %v", criteria, options)
}
|
package api
import (
"fmt"
"net/http"
"strings"
"github.com/ledisdb/ledisdb/ledis"
"github.com/mylxsw/adanos-alert/agent/store"
"github.com/mylxsw/adanos-alert/internal/extension"
"github.com/mylxsw/adanos-alert/internal/repository"
"github.com/mylxsw/adanos-alert/pkg/misc"
"github.com/mylxsw/adanos-alert/rpc/protocol"
"github.com/mylxsw/asteria/log"
"github.com/mylxsw/glacier/infra"
"github.com/mylxsw/glacier/web"
"github.com/mylxsw/go-utils/str"
)
type EventController struct {
cc infra.Resolver
}
func NewEventController(cc infra.Resolver) web.Controller {
return &EventController{cc: cc}
}
func (m *EventController) Register(router web.Router) {
router.Group("/messages", func(router web.Router) {
router.Post("/", m.AddCommonEvent).Name("events:add:common")
router.Post("/logstash/", m.AddLogstashEvent).Name("events:add:logstash")
router.Post("/grafana/", m.AddGrafanaEvent).Name("events:add:grafana")
router.Post("/prometheus/api/v1/alerts", m.AddPrometheusEvent).Name("events:add:prometheus") // url 地址末尾不包含 "/"
router.Post("/prometheus_alertmanager/", m.AddPrometheusAlertEvent).Name("events:add:prometheus-alert")
router.Post("/openfalcon/im/", m.AddOpenFalconEvent).Name("events:add:openfalcon")
router.Post("/general/", m.AddGeneralEvent).Name("events:add:general")
})
router.Group("/events", func(router web.Router) {
router.Post("/", m.AddCommonEvent).Name("events:add:common")
router.Post("/logstash/", m.AddLogstashEvent).Name("events:add:logstash")
router.Post("/grafana/", m.AddGrafanaEvent).Name("events:add:grafana")
router.Post("/prometheus/api/v1/alerts", m.AddPrometheusEvent).Name("events:add:prometheus") // url 地址末尾不包含 "/"
router.Post("/prometheus_alertmanager/", m.AddPrometheusAlertEvent).Name("events:add:prometheus-alert")
router.Post("/openfalcon/im/", m.AddOpenFalconEvent).Name("events:add:openfalcon")
router.Post("/general/", m.AddGeneralEvent).Name("events:add:general")
})
}
func (m *EventController) saveEvent(msgRepo store.EventStore, commonMessage extension.CommonEvent, ctx web.Context) error {
commonMessage.Meta["adanos_agent_version"] = m.cc.MustGet(infra.VersionKey).(string)
commonMessage.Meta["adanos_agent_ip"] = misc.ServerIP()
m.cc.MustResolve(func(db *ledis.DB) {
agentID, _ := db.Get([]byte("agent-id"))
commonMessage.Meta["adanos_agent_id"] = string(agentID)
})
req := protocol.MessageRequest{
Data: commonMessage.Serialize(),
}
if err := msgRepo.Enqueue(&req); err != nil {
log.Warningf("本地存储失败: %s", err)
return err
}
return nil
}
func (m *EventController) errorWrap(ctx web.Context, err error) web.Response {
if err != nil {
return ctx.JSONError(err.Error(), http.StatusInternalServerError)
}
return ctx.JSON(struct{}{})
}
func (m *EventController) AddGeneralEvent(ctx web.Context, messageStore store.EventStore) web.Response {
body := ctx.Request().Body()
tags := str.FilterEmpty(append(strings.Split(ctx.Input("tags"), ","), ctx.Input("tag")))
origin := ctx.Input("origin")
metas := str.Map(str.FilterEmpty(strings.Split(ctx.Input("meta"), ",")), func(item string) string {
return strings.Join(str.Map(strings.SplitN(item, ":", 2), func(item string) string { return strings.TrimSpace(item) }), ":")
})
meta := make(repository.EventMeta)
for _, m := range metas {
kv := strings.SplitN(m, ":", 2)
if len(kv) == 2 {
meta[kv[0]] = kv[1]
}
}
evt := extension.CommonEvent{
Content: string(body),
Meta: meta,
Tags: tags,
Origin: origin,
}
if ctx.Input("control.id") != "" {
evt.Control = extension.EventControl{
ID: ctx.Input("control.id"),
InhibitInterval: ctx.Input("control.inhibit_interval"),
RecoveryAfter: ctx.Input("control.recovery_after"),
}
}
return m.errorWrap(ctx, m.saveEvent(messageStore, evt, ctx))
}
func (m *EventController) AddCommonEvent(ctx web.Context, messageStore store.EventStore) web.Response {
var commonMessage extension.CommonEvent
if err := ctx.Unmarshal(&commonMessage); err != nil {
return ctx.JSONError(fmt.Sprintf("invalid request: %v", err), http.StatusUnprocessableEntity)
}
return m.errorWrap(ctx, m.saveEvent(messageStore, commonMessage, ctx))
}
// AddLogstashEvent Add logstash message
func (m *EventController) AddLogstashEvent(ctx web.Context, messageStore store.EventStore) web.Response {
commonMessage, err := extension.LogstashToCommonEvent(ctx.Request().Body(), ctx.InputWithDefault("content-field", "message"))
if err != nil {
return ctx.JSONError(err.Error(), http.StatusInternalServerError)
}
return m.errorWrap(ctx, m.saveEvent(messageStore, *commonMessage, ctx))
}
// Add grafana message
func (m *EventController) AddGrafanaEvent(ctx web.Context, messageStore store.EventStore) web.Response {
commonMessage, err := extension.GrafanaToCommonEvent(ctx.Request().Body())
if err != nil {
return ctx.JSONError(err.Error(), http.StatusInternalServerError)
}
return m.errorWrap(ctx, m.saveEvent(messageStore, *commonMessage, ctx))
}
// add prometheus alert message
func (m *EventController) AddPrometheusEvent(ctx web.Context, messageStore store.EventStore) web.Response {
commonMessages, err := extension.PrometheusToCommonEvents(ctx.Request().Body())
if err != nil {
return m.errorWrap(ctx, err)
}
for _, cm := range commonMessages {
if err := m.saveEvent(messageStore, *cm, ctx); err != nil {
log.WithFields(log.Fields{
"message": cm,
}).Errorf("save prometheus message failed: %v", err)
continue
}
}
return m.errorWrap(ctx, nil)
}
// add prometheus-alert message
func (m *EventController) AddPrometheusAlertEvent(ctx web.Context, messageStore store.EventStore) web.Response {
commonMessage, err := extension.PrometheusAlertToCommonEvent(ctx.Request().Body())
if err != nil {
return ctx.JSONError(err.Error(), http.StatusInternalServerError)
}
return m.errorWrap(ctx, m.saveEvent(messageStore, *commonMessage, ctx))
}
// add open-falcon message
func (m *EventController) AddOpenFalconEvent(ctx web.Context, messageStore store.EventStore) web.Response {
tos := ctx.Input("tos")
content := ctx.Input("content")
if content == "" {
return ctx.JSONError("invalid request, content required", http.StatusUnprocessableEntity)
}
return m.errorWrap(ctx, m.saveEvent(messageStore, *extension.OpenFalconToCommonEvent(tos, content), ctx))
}
|
package types
import (
"fmt"
"github.com/zhaohaijun/matrixchain/common"
ct "github.com/zhaohaijun/matrixchain/core/types"
"github.com/zhaohaijun/matrixchain/errors"
comm "github.com/zhaohaijun/matrixchain/p2pserver/common"
)
type Block struct {
Blk *ct.Block
}
//Serialize message payload
func (this *Block) Serialization(sink *common.ZeroCopySink) error {
err := this.Blk.Serialization(sink)
if err != nil {
return errors.NewDetailErr(err, errors.ErrNetPackFail, fmt.Sprintf("serialize error. err:%v", err))
}
return nil
}
func (this *Block) CmdType() string {
return comm.BLOCK_TYPE
}
//Deserialize message payload
func (this *Block) Deserialization(source *common.ZeroCopySource) error {
this.Blk = new(ct.Block)
err := this.Blk.Deserialization(source)
if err != nil {
return errors.NewDetailErr(err, errors.ErrNetUnPackFail, fmt.Sprintf("read Blk error. err:%v", err))
}
return nil
}
|
/*
Copyright 2017 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
package reloaders
import (
"crypto/tls"
"encoding/json"
//"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
"github.com/adobe/butler/internal/environment"
"github.com/adobe/butler/internal/metrics"
"github.com/hashicorp/go-retryablehttp"
log "github.com/sirupsen/logrus"
)
func NewHTTPReloader(manager string, method string, entry []byte) (Reloader, error) {
var (
err error
result HTTPReloader
opts HTTPReloaderOpts
insecureSkipVerify bool
)
err = json.Unmarshal(entry, &opts)
if err != nil {
return result, err
}
newTimeout, _ := strconv.Atoi(environment.GetVar(opts.Timeout))
if newTimeout == 0 {
log.Warnf("NewHttpReloader(): could not convert %v to integer for timeout, defaulting to 0. This is probably undesired.", opts.Timeout)
}
newRetries, _ := strconv.Atoi(environment.GetVar(opts.Retries))
if newRetries == 0 {
log.Warnf("NewHttpReloader(): could not convert %v to integer for retries, defaulting to 0. This is probably undesired.", opts.Retries)
}
newRetryWaitMax, _ := strconv.Atoi(environment.GetVar(opts.RetryWaitMax))
if newRetryWaitMax == 0 {
log.Warnf("NewHttpReloader(): could not convert %v to integer for retry-wait-max, defaulting to 0. This is probably undesired.", opts.RetryWaitMax)
}
newRetryWaitMin, _ := strconv.Atoi(environment.GetVar(opts.RetryWaitMin))
if newRetryWaitMin == 0 {
log.Warnf("NewHttpReloader(): could not convert %v to integer for retry-wait-min, defaulting to 0. This is probably undesired.", opts.RetryWaitMin)
}
// ignore cert errors if defined
insecureSkipVerify = strings.ToLower(environment.GetVar(opts.InsecureSkipVerify)) == "true"
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: insecureSkipVerify},
}
opts.Client = retryablehttp.NewClient()
opts.Client.Logger.SetFlags(0)
opts.Client.Logger.SetOutput(ioutil.Discard)
opts.Client.HTTPClient.Timeout = time.Duration(newTimeout) * time.Second
opts.Client.HTTPClient.Transport = transport
opts.Client.RetryMax = newRetries
opts.Client.RetryWaitMax = time.Duration(newRetryWaitMax) * time.Second
opts.Client.RetryWaitMin = time.Duration(newRetryWaitMin) * time.Second
// Let's populate some environment variables
opts.Host = environment.GetVar(opts.Host)
opts.ContentType = environment.GetVar(opts.ContentType)
// we cannot do ints yet!
//opts.Port
opts.URI = environment.GetVar(opts.URI)
opts.Method = environment.GetVar(opts.Method)
opts.Payload = environment.GetVar(opts.Payload)
result.Method = method
result.Opts = opts
result.Manager = manager
//log.Debugf("NewHttpReloader(): opts=%#v", opts)
return result, err
}
type HTTPReloader struct {
Manager string `json:"-"`
Counter int `json:"-"`
Method string `mapstructure:"method" json:"method"`
Opts HTTPReloaderOpts `json:"opts"`
}
type HTTPReloaderOpts struct {
Client *retryablehttp.Client `json:"-"`
ContentType string `json:"content-type"`
Host string `json:"host"`
InsecureSkipVerify string `json:"insecure-skip-verify"`
Port string `mapstructure:"port" json:"port"`
URI string `json:"uri"`
Method string `json:"method"`
Payload string `json:"payload"`
Retries string `json:"retries"`
RetryWaitMax string `json:"retry-wait-max"`
RetryWaitMin string `json:"retry-wait-min"`
Timeout string `json:"timeout"`
}
func (h *HTTPReloaderOpts) GetClient() *retryablehttp.Client {
return h.Client
}
func (h HTTPReloader) Reload() error {
var (
err error
req *retryablehttp.Request
resp *http.Response
)
log.Debugf("HTTPReloader::Reload()[count=%v][manager=%v]: reloading manager using http", h.Counter, h.Manager)
o := h.GetOpts().(HTTPReloaderOpts)
c := o.GetClient()
// Set the reloader retry policy
c.CheckRetry = h.ReloaderRetryPolicy
newPort, _ := strconv.Atoi(environment.GetVar(o.Port))
if newPort == 0 {
log.Warnf("HTTPReloader::Reload()[count=%v][manager=%v]: could not convert %v to integer for port, defaulting to 0. This is probably undesired.", h.Counter, h.Manager, o.Port)
}
reloadURL := fmt.Sprintf("%s://%s:%d%s", h.Method, o.Host, newPort, o.URI)
switch o.Method {
case "post", "put", "patch":
req, err = retryablehttp.NewRequest(strings.ToUpper(o.Method), reloadURL, strings.NewReader(o.Payload))
req.Header.Add("Content-Type", o.ContentType)
default:
req, err = retryablehttp.NewRequest(strings.ToUpper(o.Method), reloadURL, nil)
}
if err != nil {
msg := fmt.Sprintf("HTTPReloader::Reload()[count=%v][manager=%v]: err=%v", h.Counter, h.Manager, err.Error())
log.Errorf(msg)
return NewReloaderError().WithMessage(err.Error()).WithCode(1)
}
log.Debugf("HTTPReloader::Reload()[count=%v][manager=%v]: %v'ing up!", h.Counter, h.Manager, o.Method)
resp, err = c.Do(req)
if err != nil {
msg := fmt.Sprintf("HTTPReloader::Reload()[count=%v][manager=%v]: err=%v", h.Counter, h.Manager, err.Error())
log.Errorf(msg)
return NewReloaderError().WithMessage(err.Error()).WithCode(1)
}
if resp.StatusCode == 200 {
log.Infof("HTTPReloader::Reload()[count=%v][manager=%v]: successfully reloaded config. http_code=%d", h.Counter, h.Manager, int(resp.StatusCode))
// at this point error should be nil, so things are OK
} else {
msg := fmt.Sprintf("HTTPReloader::Reload()[count=%v][manager=%v]: received bad response from server. http_code=%d", h.Counter, h.Manager, int(resp.StatusCode))
log.Errorf(msg)
// at this point we should raise an error
return NewReloaderError().WithMessage("received bad response from server").WithCode(resp.StatusCode)
}
return err
}
func (h *HTTPReloader) ReloaderRetryPolicy(resp *http.Response, err error) (bool, error) {
if err != nil {
metrics.SetButlerReloaderRetry(metrics.SUCCESS, h.Manager)
return true, err
}
// Here is our policy override. By default it looks for
// res.StatusCode >= 500 ...
if resp.StatusCode == 0 || resp.StatusCode >= 600 {
metrics.SetButlerReloaderRetry(metrics.SUCCESS, h.Manager)
return true, nil
}
return false, nil
}
func (h HTTPReloader) GetMethod() string {
return h.Method
}
func (h HTTPReloader) GetOpts() ReloaderOpts {
return h.Opts
}
func (h HTTPReloader) SetOpts(opts ReloaderOpts) bool {
h.Opts = opts.(HTTPReloaderOpts)
return true
}
func (h HTTPReloader) SetCounter(c int) Reloader {
h.Counter = c
return h
}
|
package main
import (
"fmt"
"hash/crc32"
"io"
"os"
)
func getHash(filename string) (uint32, error) {
// open the file
file, err := os.Open(filename)
if err != nil {
return 0, err
}
// remember to always close opened files
defer file.Close()
// create a hasher
hasher := crc32.NewIEEE()
// copy the file into the hasher
// - copy takes (dst, src) and returns (bytesWritten, error)
_, err = io.Copy(hasher, file)
// we don't care about how many bytes were written, but we do want to
// handle the error
if err != nil {
return 0, err
}
return hasher.Sum32(), nil
}
func main() {
hash1, err := getHash("test1.txt")
if err != nil {
fmt.Println(err)
return
}
hash2, err := getHash("test2.txt")
if err != nil {
fmt.Println(err)
return
}
fmt.Println("hash1:", hash1)
fmt.Println("hash2:", hash2)
fmt.Println("hash1 == hash2:", hash1 == hash2)
}
|
package worker
import (
"../object"
log "github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"time"
)
// Declaration of the repository, using the interface from object package
var Repo object.ObjectRepository
// Exported method to start the worker. Made this way so it doesn't require explicit goroutine usage
func Work() {
go execute()
}
// Starts the infinite loop for the worker
func execute() {
var registry = ProgressRegistry{Ids: make(map[int64]int)}
for {
objects, err := Repo.FindAll()
if nil != err {
log.WithFields(log.Fields{"error": err}).Error("Could not retrieve objects from the database")
}
for _, o := range objects {
go handleObject(o, ®istry)
}
// One-second "ticks"
time.Sleep(time.Second)
}
}
// Fetches the response for a single object and stores into the database
func handleObject(o *object.Object, r *ProgressRegistry) {
if r.isLocked(o.Id) {
log.WithFields(log.Fields{"id": o.Id}).
Debug("Skipping object because it's being processed by another goroutine")
return
}
// Last check + [interval] seconds
threshold := o.LastCheck.Add(time.Duration(o.Interval) * time.Second)
if threshold.Before(time.Now()) {
r.lock(o.Id)
log.WithFields(log.Fields{
"last_check": o.LastCheck,
"url": o.Url,
"interval": o.Interval,
}).Info("Interval passed after last check, retrieving response")
// Wait max 5 seconds for a response
client := &http.Client{Timeout: 5 * time.Second}
startTime := time.Now()
response, err := client.Get(o.Url)
if nil != err {
log.WithFields(log.Fields{"error": err}).Error("Error fetching response")
r.unlock(o.Id)
return
}
duration := time.Now().Sub(startTime)
body, err := ioutil.ReadAll(response.Body)
response.Body.Close()
if nil != err {
log.WithFields(log.Fields{"error": err}).Error("Response body could not be read")
r.unlock(o.Id)
return
}
bodyString := string(body)
log.WithFields(log.Fields{"response": bodyString}).Info("Response received")
if err := o.AddResponse(bodyString, duration); nil != err {
log.WithFields(log.Fields{"error": err}).Error("Error saving response")
}
r.unlock(o.Id)
}
}
|
package health_test
import (
"encoding/binary"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"github.com/cerana/cerana/acomm"
healthp "github.com/cerana/cerana/providers/health"
)
func (s *health) TestHTTPStatus() {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
status := http.StatusOK
if r.Method == "FAIL" {
status = http.StatusBadRequest
} else {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
status = http.StatusBadRequest
} else if len(body) > 0 {
status = int(binary.BigEndian.Uint64(body))
}
}
w.WriteHeader(status)
}))
defer ts.Close()
tests := []struct {
url string
method string
statusCode int
body uint64
expectedErr string
}{
{"", "GET", http.StatusOK, 0, "missing arg: url"},
{ts.URL, "", http.StatusOK, 0, ""},
{ts.URL, "GET", 0, 0, ""},
{ts.URL, "GET", http.StatusOK, 0, ""},
{ts.URL, "GET", http.StatusAccepted, http.StatusAccepted, ""},
{ts.URL, "FAIL", http.StatusOK, 0, "unexpected response status code"},
}
for _, test := range tests {
desc := fmt.Sprintf("%+v", test)
args := &healthp.HTTPStatusArgs{
URL: test.url,
Method: test.method,
StatusCode: test.statusCode,
}
if test.body != 0 {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, test.body)
args.Body = b
}
req, err := acomm.NewRequest(acomm.RequestOptions{
Task: "health-http-status",
ResponseHook: s.responseHook,
Args: args,
})
s.Require().NoError(err, desc)
resp, stream, err := s.health.HTTPStatus(req)
s.Nil(resp, desc)
s.Nil(stream, desc)
if test.expectedErr == "" {
s.Nil(err, desc)
} else {
s.EqualError(err, test.expectedErr, desc)
}
}
}
|
/*
Populating Next Right Pointers in Each Node
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
*/
package main
type TreeLinkNode struct {
Val int
Left *TreeLinkNode
Right *TreeLinkNode
Next *TreeLinkNode
}
// 后序遍历 翻译成c++后AC
func connect(root *TreeLinkNode) {
if root == nil {
return
}
queue := list.New()
queue.PushBack(root)
fakeHead := &TreeLinkNode{0,nil,nil,nil}
for queue.Len() != 0 {
size,last := queue.Len(),fakeHead
for i := 0;i < size;i++ {
curr := queue.Remove(queue.Front()).(*TreeLinkNode)
last.Next,last = curr,curr
if curr.Left != nil {
queue.PushBack(curr.Left)
}
if curr.Right != nil {
queue.PushBack(curr.Right)
}
}
last.Next = nil
}
} |
package markdown
import (
"os"
"testing"
"github.com/gebv/pikchr/markdown/syntax"
)
func TestMain(m *testing.M) {
syntax.Debug()
syntax.ErrorVerbose()
os.Exit(m.Run())
}
|
package blockchain
import (
"errors"
"github.com/ChainStack-Official/simple_blockchain/common/hash_util"
"github.com/ChainStack-Official/simple_blockchain/core/bcerr"
"github.com/ChainStack-Official/simple_blockchain/core/block"
"sync"
"time"
"github.com/ethereum/go-ethereum/log"
)
// 区块链
type Blockchain struct {
// 当前链上的所有块
blocks []block.Block
// 新的未处理的区块池(在挖矿赶不上新的交易产生时,就需要将未处理的交易放这里)
// TODO:block本身还需要一个机制来保证矿工不会修改其信息(私钥签名在这起的作用)。如果不同矿工使用了同一个PrevHash对几个不同的合法交易记账,则可能导致分叉
newBlocksPool []block.Block
// TODO:全网的难度是怎么达成共识的?
curDifficulty int
lock sync.RWMutex
dfLock sync.Mutex
newBlocksPoolLock sync.Mutex
// 用于发出新的区块提交的通知
NewBlockCommittedChan chan int
}
// 添加新的交易到待记录的池子中
func (bc *Blockchain) AddBlockToNewBlocksPool(msg string) {
bc.newBlocksPoolLock.Lock()
defer bc.newBlocksPoolLock.Unlock()
bc.newBlocksPool = append(bc.newBlocksPool, block.Block{Msg: msg, SubmitTimestamp: time.Now().Unix()})
}
// 获取链上的最后一个区块
func (bc *Blockchain) GetLastBlock() block.Block {
bc.lock.Lock()
defer bc.lock.Unlock()
return bc.blocks[len(bc.blocks)-1]
}
// 返回最近一个需要挖的区块任务
func (bc *Blockchain) GetLatestTask() (taskB block.Block) {
bc.newBlocksPoolLock.Lock()
defer bc.newBlocksPoolLock.Unlock()
if len(bc.newBlocksPool) > 0 {
return bc.newBlocksPool[0]
}
return
}
// 提交新的挖掘结果
func (bc *Blockchain) SubmitNewBlock(b block.Block) {
if err := bc.NewBlock(b); err != nil {
log.Warn("收到新的区块,但是将其加入链中时报错", "err", err.Error())
}
}
// 获取当前的难度值
func (bc *Blockchain) GetCurDifficulty() int {
bc.dfLock.Lock()
defer bc.dfLock.Unlock()
return bc.curDifficulty
}
// 改变难度值
func (bc *Blockchain) ChangeDifficulty(newDifficulty int) {
bc.dfLock.Lock()
defer bc.dfLock.Unlock()
bc.curDifficulty = newDifficulty
log.Info("修改难度值", "value", bc.curDifficulty)
}
func NewBlockchain() *Blockchain {
genesis := block.Block{
Index: 1,
Timestamp: time.Now().Unix(),
Msg: "我是创世块",
}
genesis.Hash = genesis.HashForThisBlock()
return &Blockchain{
blocks: []block.Block{genesis},
curDifficulty: 1,
NewBlockCommittedChan: make(chan int),
}
}
func (bc *Blockchain) GetBlocks() []block.Block {
return bc.blocks
}
// 收到新的块,curDifficulty:当前的难度值
func (bc *Blockchain) NewBlock(b block.Block) error {
bc.lock.Lock()
defer bc.lock.Unlock()
bc.newBlocksPoolLock.Lock()
defer bc.newBlocksPoolLock.Unlock()
if err := bc.IsValidNewBlock(b); err != nil {
return err
}
bc.blocks = append(bc.blocks, b)
// 发出新区块确认的通知,TODO:这里用事件机制实现的话就不用一层一层传递了
bc.NewBlockCommittedChan <- b.Index
log.Info("确认新块", "b index", b.Index, "msg", b.Msg)
// 检查这个块是否来自当前的交易池,如果是则要将其从池子中移除
if len(bc.newBlocksPool) > 0 && bc.newBlocksPool[0].SubmitTimestamp == b.SubmitTimestamp {
log.Info("从交易池中移除新增的块", "block index", b.Index, "block msg", b.Msg)
bc.newBlocksPool = bc.newBlocksPool[1:]
} else {
log.Warn("新增的块不是来自于当前的交易池", "block msg", b.Msg)
}
return nil
}
/*
1. 检查索引是否正确
2. 检查上个区块的hash是否正确
3. 检查新区块的hash是否正确
*/
func (bc *Blockchain) IsValidNewBlock(newB block.Block) error {
bcLen := len(bc.blocks)
if bcLen == 0 {
return nil
}
lastBlock := bc.blocks[bcLen-1]
if lastBlock.Index+1 != newB.Index {
return bcerr.GetError(bcerr.NewBlockIndexWrongErr)
} else if lastBlock.Hash != newB.PrevHash {
return bcerr.GetError(bcerr.NewBlockPrevHashWrongErr)
} else if newB.Difficulty != bc.curDifficulty {
return errors.New("新区块的难度值与当前难度不匹配")
// 检查挖出的随机数是否正确
} else if !hash_util.IsValidMineNonce(newB.Nonce, newB.Difficulty) {
return errors.New("随机数不符合难度要求")
} else if newB.HashForThisBlock() != newB.Hash {
return bcerr.GetError(bcerr.NewBlockHashWrongErr)
}
return nil
}
|
package prometheus
import (
"time"
prom_v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
)
// BaseMetricsQuery holds common parameters for all kinds of queries
type BaseMetricsQuery struct {
prom_v1.Range
RateInterval string
RateFunc string
Quantiles []string
Avg bool
ByLabels []string
}
// FillDefaults fills the struct with default parameters
func (q *BaseMetricsQuery) fillDefaults() {
q.End = time.Now()
q.Start = q.End.Add(-30 * time.Minute)
q.Step = 15 * time.Second
q.RateInterval = "1m"
q.RateFunc = "rate"
q.Avg = true
}
// IstioMetricsQuery holds query parameters for a typical metrics query
type IstioMetricsQuery struct {
BaseMetricsQuery
Filters []string
Namespace string
App string
Workload string
Service string
Direction string // outbound | inbound
RequestProtocol string // e.g. http | grpc
Reporter string // source | destination, defaults to source if not provided
}
// FillDefaults fills the struct with default parameters
func (q *IstioMetricsQuery) FillDefaults() {
q.BaseMetricsQuery.fillDefaults()
q.Reporter = "source"
q.Direction = "outbound"
}
// aladdin: 인프라 쿼리를 위해(함수정보)
// InfraMetricsQuery holds common parameters for all kinds of queries
type InfraMetricsQuery struct {
prom_v1.Range
RateInterval string
RateFunc string
Avg bool
ByLabels []string
}
// aladdin: InfraMetricsQuery의 default
// FillDefaults fills the struct with default parameters
func (q *InfraMetricsQuery) fillDefaults() {
q.End = time.Now()
q.Start = q.End.Add(-30 * time.Minute)
q.Step = 15 * time.Second
q.RateInterval = "1m"
q.Avg = false
}
// aladdin: 인프라 쿼리를 위해(필터링정보)
// InfraOptionMetricsQuery holds query parameters for a infra metrics query
type InfraOptionMetricsQuery struct {
InfraMetricsQuery
Filters []string
Condition string
Status string
Phase string
Mode string
Id string
ContainerName string
PodName string
}
// aladdin: InfraOptionMetricsQuery default
// FillDefaults fills the struct with default parameters
func (q *InfraOptionMetricsQuery) FillDefaults() {
q.InfraMetricsQuery.fillDefaults()
}
// aladdin
// Metrics contains all simple metrics
type InfraMetrics struct {
Metrics map[string]*Metric `json:"metrics"`
}
// Metrics contains all simple metrics and histograms data
type Metrics struct {
Metrics map[string]*Metric `json:"metrics"`
Histograms map[string]Histogram `json:"histograms"`
}
// Metric holds the Prometheus Matrix model, which contains one or more time series (depending on grouping)
type Metric struct {
Matrix model.Matrix `json:"matrix"`
err error
}
// Histogram contains Metric objects for several histogram-kind statistics
type Histogram = map[string]*Metric
|
package main
import (
"fmt"
"net"
)
func hErr(err error) {
if err != nil {
panic(err)
}
}
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:18000")
hErr(err)
defer conn.Close()
fmt.Println("local addr: ", conn.LocalAddr())
fmt.Println("remote addr", conn.RemoteAddr())
_, err = conn.Write([]byte("Are u ready?"))
hErr(err)
}
|
package messages
import (
"bytes"
"encoding/binary"
)
//路由消息接口
type IGateMessage interface {
// GetMsgID() uint32
// GetMyID() uint32
// GetTargetID() uint32
// SetMsgID(msgid uint32)
// SetMyID(myid uint32)
// SetTargetID(targetid uint32)
//编码,传出编码的数据和数据的长度
GateMarshal() ([]byte, uint32)
//解码,传入数据,传出使用后剩下的数据,和使用了多少字节
GateUnmarshal(buff []byte) ([]byte, uint32)
}
type IGateChange interface {
//获取中转数据
GetBuffByte() *bytes.Buffer
//设置中转数据
SetBuffByte(buff []byte)
}
/*
*/
type GateMessage struct {
MsgID uint32 `json:"-"` //消息号
MyID uint32 `json:"-"` //消息源ID
TargetID uint32 `json:"-"` //目标ID
}
func (msg *GateMessage) GetMsgID() uint32 {
return msg.MsgID
}
func (msg *GateMessage) GetMyID() uint32 {
return msg.MyID
}
func (msg *GateMessage) GetTargetID() uint32 {
return msg.TargetID
}
func (msg *GateMessage) SetMsgID(msgid uint32) {
msg.MsgID = msgid
}
func (msg *GateMessage) SetMyID(myid uint32) {
msg.MyID = myid
}
func (msg *GateMessage) SetTargetID(targetid uint32) {
msg.TargetID = targetid
}
//编码
func (msg *GateMessage) GateMarshal() ([]byte, uint32) {
buff := &bytes.Buffer{}
tmpbuf := make([]byte, 4)
binary.BigEndian.PutUint32(tmpbuf, msg.MsgID)
buff.Write(tmpbuf)
binary.BigEndian.PutUint32(tmpbuf, msg.MyID)
buff.Write(tmpbuf)
binary.BigEndian.PutUint32(tmpbuf, msg.TargetID)
buff.Write(tmpbuf)
return buff.Bytes(), uint32(buff.Len())
}
//解码
func (msg *GateMessage) GateUnmarshal(buff []byte) ([]byte, uint32) {
msg.SetMsgID(binary.BigEndian.Uint32(buff[:4]))
buff = buff[4:]
msg.SetMyID(binary.BigEndian.Uint32(buff[:4]))
buff = buff[4:]
msg.SetTargetID(binary.BigEndian.Uint32(buff[:4]))
buff = buff[4:]
return buff, 12
}
/*
gate用来中转消息的结构
*/
type GateChangeMsg struct {
buffer *bytes.Buffer
}
func (this *GateChangeMsg) GetBuffByte() *bytes.Buffer {
return this.buffer
}
func (this *GateChangeMsg) SetBuffByte(buff []byte) {
this.buffer = bytes.NewBuffer(buff)
}
/*
gate的逻辑是
识别客户端发的消息号,来决定消息要发给哪个服务器,
所以,对客户端业说,没有网关;网关是直转消息;
但是服务器可能不知道这是哪个用户发来的消息;
避免客户端伪造别人发消息,所以消息中用户信息部分应该是gate进行填充;
所以,如果是走gate,那服务器收消息部分应该按gate消息解;
解的方式就是把原消息的消息号拿出来,然后按gate的消息重组;使用的是原消息号
因为前置gate不做服务器之间的消息转发,
所以对与服务来说,知道哪个gate过来的消息是客户过来的消息,还是别的服务器过来的消息
需要先服务器连接gate,然后注册自己要听的消息,然后客户端上去拿到不同服务器的路由
所以这里的路由应该只是头解,然后就按路由信息进行转发
如果是后置gate,也只是头解出来,然后按头信息转发消息
服务器如果过网关回复给客户端的直回消息,使用网关消息ID:XXX(具体看gate消息定义)直回消息
在目标那一项中写上用户的ID就可以了;当然为了减少gate的拆解包的操作,gate应该是在收到后,
直接把后面的数据直发给客户端,所以对与客户端要解的数据的封包操作还是game做的;
对gate是黑盒的;
如果使用服务器消息转发逻辑
一、1对1的服务器转发
服务器发的消息要找网关逻辑来决定这个消息从哪来的,发到哪里去
*/
|
// 12 december 2015
package ui
import (
"unsafe"
)
// #include "ui.h"
import "C"
// RadioButtons is a Control that represents a set of checkable
// buttons from which exactly one may be chosen by the user.
//
// Due to platform-specific limitations, it is impossible for a
// RadioButtons to have no button selected (unless there are no
// buttons).
type RadioButtons struct {
c *C.uiControl
r *C.uiRadioButtons
}
// NewRadioButtons creates a new RadioButtons.
func NewRadioButtons() *RadioButtons {
r := new(RadioButtons)
r.r = C.uiNewRadioButtons()
r.c = (*C.uiControl)(unsafe.Pointer(r.r))
return r
}
// Destroy destroys the RadioButtons.
func (r *RadioButtons) Destroy() {
C.uiControlDestroy(r.c)
}
// LibuiControl returns the libui uiControl pointer that backs
// the Window. This is only used by package ui itself and should
// not be called by programs.
func (r *RadioButtons) LibuiControl() uintptr {
return uintptr(unsafe.Pointer(r.c))
}
// Handle returns the OS-level handle associated with this RadioButtons.
// On Windows this is an HWND of a libui-internal class; its
// child windows are instances of the standard Windows API
// BUTTON class (as provided by Common Controls version 6).
// On GTK+ this is a pointer to a GtkBox containing GtkRadioButtons.
// On OS X this is a pointer to a NSMatrix with NSButtonCell cells.
func (r *RadioButtons) Handle() uintptr {
return uintptr(C.uiControlHandle(r.c))
}
// Show shows the RadioButtons.
func (r *RadioButtons) Show() {
C.uiControlShow(r.c)
}
// Hide hides the RadioButtons.
func (r *RadioButtons) Hide() {
C.uiControlHide(r.c)
}
// Enable enables the RadioButtons.
func (r *RadioButtons) Enable() {
C.uiControlEnable(r.c)
}
// Disable disables the RadioButtons.
func (r *RadioButtons) Disable() {
C.uiControlDisable(r.c)
}
// Append adds the named button to the end of the RadioButtons.
// If this button is the first button, it is automatically selected.
func (r *RadioButtons) Append(text string) {
ctext := C.CString(text)
C.uiRadioButtonsAppend(r.r, ctext)
freestr(ctext)
}
|
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package memo
import (
"math"
"math/rand"
"reflect"
"testing"
"time"
"unsafe"
"github.com/cockroachdb/cockroach/pkg/sql/inverted"
"github.com/cockroachdb/cockroach/pkg/sql/opt"
"github.com/cockroachdb/cockroach/pkg/sql/opt/props/physical"
"github.com/cockroachdb/cockroach/pkg/sql/randgen"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/timeofday"
"github.com/cockroachdb/cockroach/pkg/util/timeutil/pgdate"
"golang.org/x/tools/container/intsets"
)
func TestInterner(t *testing.T) {
var in interner
json1, _ := tree.ParseDJSON(`{"a": 5, "b": [1, 2]}`)
json2, _ := tree.ParseDJSON(`{"a": 5, "b": [1, 2]}`)
json3, _ := tree.ParseDJSON(`[1, 2]`)
tupTyp1 := types.MakeLabeledTuple([]*types.T{types.Int, types.String}, []string{"a", "b"})
tupTyp2 := types.MakeLabeledTuple([]*types.T{types.Int, types.String}, []string{"a", "b"})
tupTyp3 := types.MakeTuple([]*types.T{types.Int, types.String})
tupTyp4 := types.MakeTuple([]*types.T{types.Int, types.String, types.Bool})
tupTyp5 := types.MakeLabeledTuple([]*types.T{types.Int, types.String}, []string{"c", "d"})
tupTyp6 := types.MakeLabeledTuple([]*types.T{types.String, types.Int}, []string{"c", "d"})
tup1 := tree.NewDTuple(tupTyp1, tree.NewDInt(100), tree.NewDString("foo"))
tup2 := tree.NewDTuple(tupTyp2, tree.NewDInt(100), tree.NewDString("foo"))
tup3 := tree.NewDTuple(tupTyp3, tree.NewDInt(100), tree.NewDString("foo"))
tup4 := tree.NewDTuple(tupTyp4, tree.NewDInt(100), tree.NewDString("foo"), tree.DBoolTrue)
tup5 := tree.NewDTuple(tupTyp5, tree.NewDInt(100), tree.NewDString("foo"))
tup6 := tree.NewDTuple(tupTyp5, tree.DNull, tree.DNull)
tup7 := tree.NewDTuple(tupTyp6, tree.DNull, tree.DNull)
arr1 := tree.NewDArray(tupTyp1)
arr1.Array = tree.Datums{tup1, tup2}
arr2 := tree.NewDArray(tupTyp2)
arr2.Array = tree.Datums{tup2, tup1}
arr3 := tree.NewDArray(tupTyp3)
arr3.Array = tree.Datums{tup2, tup3}
arr4 := tree.NewDArray(types.Int)
arr4.Array = tree.Datums{tree.DNull}
arr5 := tree.NewDArray(types.String)
arr5.Array = tree.Datums{tree.DNull}
arr6 := tree.NewDArray(types.Int)
arr6.Array = tree.Datums{}
arr7 := tree.NewDArray(types.String)
arr7.Array = tree.Datums{}
dec1, _ := tree.ParseDDecimal("1.0")
dec2, _ := tree.ParseDDecimal("1.0")
dec3, _ := tree.ParseDDecimal("1.00")
dec4, _ := tree.ParseDDecimal("1e0")
dec5, _ := tree.ParseDDecimal("1")
coll1, _ := tree.NewDCollatedString("foo", "sv_SE", &tree.CollationEnvironment{})
coll2, _ := tree.NewDCollatedString("foo", "sv_SE", &tree.CollationEnvironment{})
coll3, _ := tree.NewDCollatedString("foo", "en_US", &tree.CollationEnvironment{})
coll4, _ := tree.NewDCollatedString("food", "en_US", &tree.CollationEnvironment{})
tz1 := tree.MustMakeDTimestampTZ(time.Date(2018, 10, 6, 11, 49, 30, 123, time.UTC), 0)
tz2 := tree.MustMakeDTimestampTZ(time.Date(2018, 10, 6, 11, 49, 30, 123, time.UTC), 0)
tz3 := tree.MustMakeDTimestampTZ(time.Date(2018, 10, 6, 11, 49, 30, 124, time.UTC), 0)
tz4 := tree.MustMakeDTimestampTZ(time.Date(2018, 10, 6, 11, 49, 30, 124, time.FixedZone("PDT", -7)), 0)
explain1 := tree.ExplainOptions{Mode: tree.ExplainPlan}
explain1.Flags[1] = true
explain1.Flags[2] = true
explain2 := tree.ExplainOptions{Mode: tree.ExplainOpt}
explain2.Flags[1] = true
explain2.Flags[2] = true
explain3 := tree.ExplainOptions{Mode: tree.ExplainOpt}
explain3.Flags[1] = true
explain3.Flags[2] = true
explain3.Flags[3] = true
scanNode := &ScanExpr{}
andExpr := &AndExpr{}
projections1 := ProjectionsExpr{{Element: andExpr, Col: 0}}
projections2 := ProjectionsExpr{{Element: andExpr, Col: 0}}
projections3 := ProjectionsExpr{{Element: andExpr, Col: 1}}
projections4 := ProjectionsExpr{
{Element: andExpr, Col: 1},
{Element: andExpr, Col: 2},
}
projections5 := ProjectionsExpr{{Element: &AndExpr{}, Col: 1}}
aggs1 := AggregationsExpr{{Agg: CountRowsSingleton, Col: 0}}
aggs2 := AggregationsExpr{{Agg: CountRowsSingleton, Col: 0}}
aggs3 := AggregationsExpr{{Agg: CountRowsSingleton, Col: 1}}
aggs4 := AggregationsExpr{
{Agg: CountRowsSingleton, Col: 1},
{Agg: CountRowsSingleton, Col: 2},
}
aggs5 := AggregationsExpr{{Agg: &CountRowsExpr{}, Col: 1}}
int1 := &ConstExpr{Value: tree.NewDInt(10)}
int2 := &ConstExpr{Value: tree.NewDInt(20)}
frame1 := WindowFrame{
Mode: tree.RANGE,
StartBoundType: tree.UnboundedPreceding,
EndBoundType: tree.CurrentRow,
FrameExclusion: tree.NoExclusion,
}
frame2 := WindowFrame{
Mode: tree.ROWS,
StartBoundType: tree.UnboundedPreceding,
EndBoundType: tree.CurrentRow,
FrameExclusion: tree.NoExclusion,
}
wins1 := WindowsExpr{{
Function: RankSingleton,
WindowsItemPrivate: WindowsItemPrivate{Col: 0, Frame: frame1},
}}
wins2 := WindowsExpr{{
Function: RankSingleton,
WindowsItemPrivate: WindowsItemPrivate{Col: 0, Frame: frame1},
}}
wins3 := WindowsExpr{{
Function: &WindowFromOffsetExpr{Input: RankSingleton, Offset: int1},
WindowsItemPrivate: WindowsItemPrivate{Col: 0, Frame: frame1},
}}
wins4 := WindowsExpr{{
Function: &WindowFromOffsetExpr{Input: RankSingleton, Offset: int2},
WindowsItemPrivate: WindowsItemPrivate{Col: 0, Frame: frame1},
}}
wins5 := WindowsExpr{{
Function: RankSingleton,
WindowsItemPrivate: WindowsItemPrivate{Col: 0, Frame: frame2},
}}
invSpan1 := inverted.MakeSingleValSpan([]byte("abc"))
invSpan2 := inverted.MakeSingleValSpan([]byte("abc"))
invSpan3 := inverted.Span{Start: []byte("abc"), End: []byte("def")}
invSpans1 := inverted.Spans{invSpan1}
invSpans2 := inverted.Spans{invSpan2}
invSpans3 := inverted.Spans{invSpan3}
invSpans4 := inverted.Spans{invSpan1, invSpan2}
invSpans5 := inverted.Spans{invSpan2, invSpan1}
invSpans6 := inverted.Spans{invSpan1, invSpan3}
type testVariation struct {
val1 interface{}
val2 interface{}
equal bool
}
testCases := []struct {
hashFn interface{}
eqFn interface{}
variations []testVariation
}{
{hashFn: in.hasher.HashBool, eqFn: in.hasher.IsBoolEqual, variations: []testVariation{
{val1: true, val2: true, equal: true},
{val1: true, val2: false, equal: false},
}},
{hashFn: in.hasher.HashInt, eqFn: in.hasher.IsIntEqual, variations: []testVariation{
{val1: 1, val2: 1, equal: true},
{val1: 0, val2: 1, equal: false},
{val1: intsets.MaxInt, val2: intsets.MaxInt, equal: true},
{val1: intsets.MinInt, val2: intsets.MaxInt, equal: false},
}},
{hashFn: in.hasher.HashFloat64, eqFn: in.hasher.IsFloat64Equal, variations: []testVariation{
{val1: float64(0), val2: float64(0), equal: true},
{val1: float64(1e300), val2: float64(1e-300), equal: false},
{val1: math.MaxFloat64, val2: math.MaxFloat64, equal: true},
{val1: math.NaN(), val2: math.NaN(), equal: true},
{val1: math.Inf(1), val2: math.Inf(1), equal: true},
{val1: math.Inf(-1), val2: math.Inf(1), equal: false},
{val1: math.NaN(), val2: math.Inf(1), equal: false},
// Use Copysign to create negative zero float64.
{val1: float64(0), val2: math.Copysign(0, -1), equal: false},
}},
{hashFn: in.hasher.HashRune, eqFn: in.hasher.IsRuneEqual, variations: []testVariation{
{val1: rune(0), val2: rune(0), equal: true},
{val1: rune('a'), val2: rune('b'), equal: false},
{val1: rune('a'), val2: rune('A'), equal: false},
{val1: rune('🐛'), val2: rune('🐛'), equal: true},
}},
{hashFn: in.hasher.HashString, eqFn: in.hasher.IsStringEqual, variations: []testVariation{
{val1: "", val2: "", equal: true},
{val1: "abc", val2: "abcd", equal: false},
{val1: "", val2: " ", equal: false},
{val1: "the quick brown fox", val2: "the quick brown fox", equal: true},
}},
{hashFn: in.hasher.HashByte, eqFn: in.hasher.IsByteEqual, variations: []testVariation{
{val1: byte(0), val2: byte(0), equal: true},
{val1: byte('a'), val2: byte('b'), equal: false},
{val1: byte('a'), val2: byte('A'), equal: false},
{val1: byte('z'), val2: byte('z'), equal: true},
}},
{hashFn: in.hasher.HashBytes, eqFn: in.hasher.IsBytesEqual, variations: []testVariation{
{val1: []byte{}, val2: []byte{}, equal: true},
{val1: []byte{}, val2: []byte{0}, equal: false},
{val1: []byte{1, 2, 3}, val2: []byte{1, 2, 3, 4}, equal: false},
{val1: []byte{10, 1, 100}, val2: []byte{10, 1, 100}, equal: true},
}},
{hashFn: in.hasher.HashOperator, eqFn: in.hasher.IsOperatorEqual, variations: []testVariation{
{val1: opt.AndOp, val2: opt.AndOp, equal: true},
{val1: opt.SelectOp, val2: opt.InnerJoinOp, equal: false},
}},
{hashFn: in.hasher.HashGoType, eqFn: in.hasher.IsGoTypeEqual, variations: []testVariation{
{val1: reflect.TypeOf(int(0)), val2: reflect.TypeOf(int(1)), equal: true},
{val1: reflect.TypeOf(int64(0)), val2: reflect.TypeOf(int32(0)), equal: false},
}},
{hashFn: in.hasher.HashDatum, eqFn: in.hasher.IsDatumEqual, variations: []testVariation{
{val1: tree.DBoolTrue, val2: tree.DBoolTrue, equal: true},
{val1: tree.DBoolTrue, val2: tree.DBoolFalse, equal: false},
{val1: tree.NewDInt(0), val2: tree.NewDInt(0), equal: true},
{val1: tree.NewDInt(tree.DInt(intsets.MinInt)), val2: tree.NewDInt(tree.DInt(intsets.MinInt)), equal: true},
{val1: tree.NewDInt(tree.DInt(intsets.MinInt)), val2: tree.NewDInt(tree.DInt(intsets.MaxInt)), equal: false},
{val1: tree.NewDFloat(0), val2: tree.NewDFloat(0), equal: true},
{val1: tree.NewDFloat(tree.DFloat(math.NaN())), val2: tree.NewDFloat(tree.DFloat(math.NaN())), equal: true},
{val1: tree.NewDFloat(tree.DFloat(math.Inf(-1))), val2: tree.NewDFloat(tree.DFloat(math.Inf(1))), equal: false},
{val1: tree.NewDString(""), val2: tree.NewDString(""), equal: true},
{val1: tree.NewDString("123"), val2: tree.NewDString("123"), equal: true},
{val1: tree.NewDString(" "), val2: tree.NewDString("\t"), equal: false},
{val1: tree.NewDBytes(tree.DBytes([]byte{0})), val2: tree.NewDBytes(tree.DBytes([]byte{0})), equal: true},
{val1: tree.NewDBytes("foo"), val2: tree.NewDBytes("foo2"), equal: false},
{val1: tree.NewDDate(pgdate.LowDate), val2: tree.NewDDate(pgdate.LowDate), equal: true},
{val1: tree.NewDDate(pgdate.LowDate), val2: tree.NewDDate(pgdate.HighDate), equal: false},
{val1: tree.MakeDTime(timeofday.Min), val2: tree.MakeDTime(timeofday.Min), equal: true},
{val1: tree.MakeDTime(timeofday.Min), val2: tree.MakeDTime(timeofday.Max), equal: false},
{val1: json1, val2: json2, equal: true},
{val1: json2, val2: json3, equal: false},
{val1: tup1, val2: tup2, equal: true},
{val1: tup2, val2: tup3, equal: false},
{val1: tup3, val2: tup4, equal: false},
{val1: tup1, val2: tup5, equal: false},
{val1: tup6, val2: tup7, equal: false},
{val1: arr1, val2: arr2, equal: true},
{val1: arr2, val2: arr3, equal: false},
{val1: arr4, val2: arr5, equal: false},
{val1: arr4, val2: arr6, equal: false},
{val1: arr6, val2: arr7, equal: false},
{val1: dec1, val2: dec2, equal: true},
{val1: dec2, val2: dec3, equal: false},
{val1: dec3, val2: dec4, equal: false},
{val1: dec4, val2: dec5, equal: true},
{val1: coll1, val2: coll2, equal: true},
{val1: coll2, val2: coll3, equal: false},
{val1: coll3, val2: coll4, equal: false},
{val1: tz1, val2: tz2, equal: true},
{val1: tz2, val2: tz3, equal: false},
{val1: tz3, val2: tz4, equal: false},
{val1: tree.NewDOid(0), val2: tree.NewDOid(0), equal: true},
{val1: tree.NewDOid(0), val2: tree.NewDOid(1), equal: false},
{val1: tree.NewDInt(0), val2: tree.NewDFloat(0), equal: false},
{val1: tree.NewDInt(0), val2: tree.NewDOid(0), equal: false},
}},
{hashFn: in.hasher.HashType, eqFn: in.hasher.IsTypeEqual, variations: []testVariation{
{val1: types.Int, val2: types.Int, equal: true},
{val1: tupTyp1, val2: tupTyp2, equal: true},
{val1: tupTyp2, val2: tupTyp3, equal: false},
{val1: tupTyp3, val2: tupTyp4, equal: false},
}},
{hashFn: in.hasher.HashTypedExpr, eqFn: in.hasher.IsTypedExprEqual, variations: []testVariation{
{val1: tup1, val2: tup1, equal: true},
{val1: tup1, val2: tup2, equal: false},
{val1: tup2, val2: tup3, equal: false},
}},
{hashFn: in.hasher.HashColumnID, eqFn: in.hasher.IsColumnIDEqual, variations: []testVariation{
{val1: opt.ColumnID(0), val2: opt.ColumnID(0), equal: true},
{val1: opt.ColumnID(0), val2: opt.ColumnID(1), equal: false},
}},
{hashFn: in.hasher.HashColSet, eqFn: in.hasher.IsColSetEqual, variations: []testVariation{
{val1: opt.MakeColSet(), val2: opt.MakeColSet(), equal: true},
{val1: opt.MakeColSet(1, 2, 3), val2: opt.MakeColSet(3, 2, 1), equal: true},
{val1: opt.MakeColSet(1, 2, 3), val2: opt.MakeColSet(1, 2), equal: false},
}},
{hashFn: in.hasher.HashColList, eqFn: in.hasher.IsColListEqual, variations: []testVariation{
{val1: opt.ColList{}, val2: opt.ColList{}, equal: true},
{val1: opt.ColList{1, 2, 3}, val2: opt.ColList{1, 2, 3}, equal: true},
{val1: opt.ColList{1, 2, 3}, val2: opt.ColList{3, 2, 1}, equal: false},
{val1: opt.ColList{1, 2}, val2: opt.ColList{1, 2, 3}, equal: false},
}},
{hashFn: in.hasher.HashOrdering, eqFn: in.hasher.IsOrderingEqual, variations: []testVariation{
{val1: opt.Ordering{}, val2: opt.Ordering{}, equal: true},
{val1: opt.Ordering{-1, 1}, val2: opt.Ordering{-1, 1}, equal: true},
{val1: opt.Ordering{-1, 1}, val2: opt.Ordering{1, -1}, equal: false},
{val1: opt.Ordering{-1, 1}, val2: opt.Ordering{-1, 1, 2}, equal: false},
}},
{hashFn: in.hasher.HashOrderingChoice, eqFn: in.hasher.IsOrderingChoiceEqual, variations: []testVariation{
{val1: physical.ParseOrderingChoice(""), val2: physical.ParseOrderingChoice(""), equal: true},
{val1: physical.ParseOrderingChoice("+1"), val2: physical.ParseOrderingChoice("+1"), equal: true},
{val1: physical.ParseOrderingChoice("+(1|2)"), val2: physical.ParseOrderingChoice("+(2|1)"), equal: true},
{val1: physical.ParseOrderingChoice("+1 opt(2)"), val2: physical.ParseOrderingChoice("+1 opt(2)"), equal: true},
{val1: physical.ParseOrderingChoice("+1"), val2: physical.ParseOrderingChoice("-1"), equal: false},
{val1: physical.ParseOrderingChoice("+1,+2"), val2: physical.ParseOrderingChoice("+1"), equal: false},
{val1: physical.ParseOrderingChoice("+(1|2)"), val2: physical.ParseOrderingChoice("+1"), equal: false},
{val1: physical.ParseOrderingChoice("+1 opt(2)"), val2: physical.ParseOrderingChoice("+1"), equal: false},
}},
{hashFn: in.hasher.HashTableID, eqFn: in.hasher.IsTableIDEqual, variations: []testVariation{
{val1: opt.TableID(0), val2: opt.TableID(0), equal: true},
{val1: opt.TableID(0), val2: opt.TableID(1), equal: false},
}},
{hashFn: in.hasher.HashSchemaID, eqFn: in.hasher.IsSchemaIDEqual, variations: []testVariation{
{val1: opt.SchemaID(0), val2: opt.SchemaID(0), equal: true},
{val1: opt.SchemaID(0), val2: opt.SchemaID(1), equal: false},
}},
{hashFn: in.hasher.HashScanLimit, eqFn: in.hasher.IsScanLimitEqual, variations: []testVariation{
{val1: ScanLimit(100), val2: ScanLimit(100), equal: true},
{val1: ScanLimit(0), val2: ScanLimit(1), equal: false},
}},
{hashFn: in.hasher.HashScanFlags, eqFn: in.hasher.IsScanFlagsEqual, variations: []testVariation{
{val1: ScanFlags{}, val2: ScanFlags{}, equal: true},
{val1: ScanFlags{NoIndexJoin: false}, val2: ScanFlags{NoIndexJoin: true}, equal: false},
{val1: ScanFlags{NoIndexJoin: true}, val2: ScanFlags{NoIndexJoin: true}, equal: true},
{val1: ScanFlags{ForceIndex: false}, val2: ScanFlags{ForceIndex: true}, equal: false},
{val1: ScanFlags{ForceIndex: true}, val2: ScanFlags{ForceIndex: true}, equal: true},
{val1: ScanFlags{Direction: tree.Descending}, val2: ScanFlags{Direction: tree.Ascending}, equal: false},
{val1: ScanFlags{Direction: tree.Ascending}, val2: ScanFlags{Direction: tree.Ascending}, equal: true},
{val1: ScanFlags{Index: 1}, val2: ScanFlags{Index: 2}, equal: false},
{val1: ScanFlags{Index: 2}, val2: ScanFlags{Index: 2}, equal: true},
{val1: ScanFlags{NoIndexJoin: true, Index: 1}, val2: ScanFlags{NoIndexJoin: true, Index: 1}, equal: true},
{val1: ScanFlags{NoIndexJoin: true, Index: 1}, val2: ScanFlags{NoIndexJoin: true, Index: 2}, equal: false},
{val1: ScanFlags{NoIndexJoin: true, Index: 1}, val2: ScanFlags{NoIndexJoin: false, Index: 1}, equal: false},
{
val1: ScanFlags{NoIndexJoin: true, ForceIndex: true, Direction: tree.Ascending, Index: 1},
val2: ScanFlags{NoIndexJoin: false, ForceIndex: true, Direction: tree.Ascending, Index: 1},
equal: false,
},
{
val1: ScanFlags{NoIndexJoin: true, ForceIndex: true, Direction: tree.Ascending, Index: 1},
val2: ScanFlags{NoIndexJoin: true, ForceIndex: false, Direction: tree.Ascending, Index: 1},
equal: false,
},
{
val1: ScanFlags{NoIndexJoin: true, ForceIndex: true, Direction: tree.Ascending, Index: 1},
val2: ScanFlags{NoIndexJoin: true, ForceIndex: true, Direction: tree.Descending, Index: 1},
equal: false,
},
{
val1: ScanFlags{NoIndexJoin: true, ForceIndex: true, Direction: tree.Ascending, Index: 1},
val2: ScanFlags{NoIndexJoin: true, ForceIndex: true, Direction: tree.Ascending, Index: 2},
equal: false,
},
{
val1: ScanFlags{NoIndexJoin: true, ForceIndex: true, Direction: tree.Ascending, Index: 1},
val2: ScanFlags{NoIndexJoin: true, ForceIndex: true, Direction: tree.Ascending, Index: 1},
equal: true,
},
}},
{hashFn: in.hasher.HashPointer, eqFn: in.hasher.IsPointerEqual, variations: []testVariation{
{val1: unsafe.Pointer((*tree.Subquery)(nil)), val2: unsafe.Pointer((*tree.Subquery)(nil)), equal: true},
{val1: unsafe.Pointer(&tree.Subquery{}), val2: unsafe.Pointer(&tree.Subquery{}), equal: false},
}},
{hashFn: in.hasher.HashExplainOptions, eqFn: in.hasher.IsExplainOptionsEqual, variations: []testVariation{
{val1: tree.ExplainOptions{}, val2: tree.ExplainOptions{}, equal: true},
{val1: explain1, val2: explain1, equal: true},
{val1: explain1, val2: explain2, equal: false},
{val1: explain2, val2: explain3, equal: false},
}},
{hashFn: in.hasher.HashShowTraceType, eqFn: in.hasher.IsShowTraceTypeEqual, variations: []testVariation{
{val1: tree.ShowTraceKV, val2: tree.ShowTraceKV, equal: true},
{val1: tree.ShowTraceKV, val2: tree.ShowTraceRaw, equal: false},
}},
{hashFn: in.hasher.HashWindowFrame, eqFn: in.hasher.IsWindowFrameEqual, variations: []testVariation{
{
val1: WindowFrame{tree.RANGE, tree.UnboundedPreceding, tree.CurrentRow, tree.NoExclusion},
val2: WindowFrame{tree.RANGE, tree.UnboundedPreceding, tree.CurrentRow, tree.NoExclusion},
equal: true,
},
{
val1: WindowFrame{tree.RANGE, tree.UnboundedPreceding, tree.CurrentRow, tree.NoExclusion},
val2: WindowFrame{tree.ROWS, tree.UnboundedPreceding, tree.CurrentRow, tree.NoExclusion},
equal: false,
},
{
val1: WindowFrame{tree.RANGE, tree.UnboundedPreceding, tree.CurrentRow, tree.NoExclusion},
val2: WindowFrame{tree.RANGE, tree.UnboundedPreceding, tree.UnboundedFollowing, tree.NoExclusion},
equal: false,
},
{
val1: WindowFrame{tree.RANGE, tree.UnboundedPreceding, tree.CurrentRow, tree.NoExclusion},
val2: WindowFrame{tree.RANGE, tree.CurrentRow, tree.CurrentRow, tree.NoExclusion},
equal: false,
},
}},
{hashFn: in.hasher.HashTupleOrdinal, eqFn: in.hasher.IsTupleOrdinalEqual, variations: []testVariation{
{val1: TupleOrdinal(0), val2: TupleOrdinal(0), equal: true},
{val1: TupleOrdinal(0), val2: TupleOrdinal(1), equal: false},
}},
// PhysProps hash/isEqual methods are tested in TestInternerPhysProps.
{hashFn: in.hasher.HashLockingItem, eqFn: in.hasher.IsLockingItemEqual, variations: []testVariation{
{val1: (*tree.LockingItem)(nil), val2: (*tree.LockingItem)(nil), equal: true},
{
val1: (*tree.LockingItem)(nil),
val2: &tree.LockingItem{Strength: tree.ForUpdate},
equal: false,
},
{
val1: &tree.LockingItem{Strength: tree.ForShare},
val2: &tree.LockingItem{Strength: tree.ForUpdate},
equal: false,
},
{
val1: &tree.LockingItem{WaitPolicy: tree.LockWaitSkip},
val2: &tree.LockingItem{WaitPolicy: tree.LockWaitError},
equal: false,
},
{
val1: &tree.LockingItem{Strength: tree.ForUpdate, WaitPolicy: tree.LockWaitError},
val2: &tree.LockingItem{Strength: tree.ForUpdate, WaitPolicy: tree.LockWaitError},
equal: true,
},
}},
{hashFn: in.hasher.HashRelExpr, eqFn: in.hasher.IsRelExprEqual, variations: []testVariation{
{val1: (*ScanExpr)(nil), val2: (*ScanExpr)(nil), equal: true},
{val1: scanNode, val2: scanNode, equal: true},
{val1: &ScanExpr{}, val2: &ScanExpr{}, equal: false},
}},
{hashFn: in.hasher.HashScalarExpr, eqFn: in.hasher.IsScalarExprEqual, variations: []testVariation{
{val1: (*AndExpr)(nil), val2: (*AndExpr)(nil), equal: true},
{val1: andExpr, val2: andExpr, equal: true},
{val1: &AndExpr{}, val2: &AndExpr{}, equal: false},
}},
{hashFn: in.hasher.HashScalarListExpr, eqFn: in.hasher.IsScalarListExprEqual, variations: []testVariation{
{val1: ScalarListExpr{andExpr, andExpr}, val2: ScalarListExpr{andExpr, andExpr}, equal: true},
{val1: ScalarListExpr{andExpr, andExpr}, val2: ScalarListExpr{andExpr}, equal: false},
{val1: ScalarListExpr{&AndExpr{}}, val2: ScalarListExpr{&AndExpr{}}, equal: false},
}},
{hashFn: in.hasher.HashFiltersExpr, eqFn: in.hasher.IsFiltersExprEqual, variations: []testVariation{
{val1: FiltersExpr{{Condition: andExpr}}, val2: FiltersExpr{{Condition: andExpr}}, equal: true},
{val1: FiltersExpr{{Condition: andExpr}}, val2: FiltersExpr{}, equal: false},
{val1: FiltersExpr{{Condition: &AndExpr{}}}, val2: FiltersExpr{{Condition: &AndExpr{}}}, equal: false},
}},
{hashFn: in.hasher.HashProjectionsExpr, eqFn: in.hasher.IsProjectionsExprEqual, variations: []testVariation{
{val1: projections1, val2: projections2, equal: true},
{val1: projections2, val2: projections3, equal: false},
{val1: projections3, val2: projections4, equal: false},
{val1: projections3, val2: projections5, equal: false},
}},
{hashFn: in.hasher.HashAggregationsExpr, eqFn: in.hasher.IsAggregationsExprEqual, variations: []testVariation{
{val1: aggs1, val2: aggs2, equal: true},
{val1: aggs2, val2: aggs3, equal: false},
{val1: aggs3, val2: aggs4, equal: false},
{val1: aggs3, val2: aggs5, equal: false},
}},
{hashFn: in.hasher.HashWindowsExpr, eqFn: in.hasher.IsWindowsExprEqual, variations: []testVariation{
{val1: wins1, val2: wins2, equal: true},
{val1: wins1, val2: wins3, equal: false},
{val1: wins2, val2: wins3, equal: false},
{val1: wins3, val2: wins4, equal: false},
{val1: wins1, val2: wins5, equal: false},
}},
{hashFn: in.hasher.HashInvertedSpans, eqFn: in.hasher.IsInvertedSpansEqual, variations: []testVariation{
{val1: invSpans1, val2: invSpans2, equal: true},
{val1: invSpans1, val2: invSpans3, equal: false},
{val1: invSpans2, val2: invSpans4, equal: false},
{val1: invSpans4, val2: invSpans5, equal: true},
{val1: invSpans5, val2: invSpans6, equal: false},
}},
}
computeHashValue := func(hashFn reflect.Value, val interface{}) internHash {
in.hasher.Init()
hashFn.Call([]reflect.Value{reflect.ValueOf(val)})
return in.hasher.hash
}
isEqual := func(eqFn reflect.Value, val1, val2 interface{}) bool {
in.hasher.Init()
res := eqFn.Call([]reflect.Value{reflect.ValueOf(val1), reflect.ValueOf(val2)})
return res[0].Interface().(bool)
}
for _, tc := range testCases {
hashFn := reflect.ValueOf(tc.hashFn)
eqFn := reflect.ValueOf(tc.eqFn)
for _, tv := range tc.variations {
hash1 := computeHashValue(hashFn, tv.val1)
hash2 := computeHashValue(hashFn, tv.val2)
if tv.equal && hash1 != hash2 {
t.Errorf("expected hash values to be equal for %v and %v", tv.val1, tv.val2)
} else if !tv.equal && hash1 == hash2 {
t.Errorf("expected hash values to not be equal for %v and %v", tv.val1, tv.val2)
}
eq := isEqual(eqFn, tv.val1, tv.val2)
if tv.equal && !eq {
t.Errorf("expected values to be equal for %v and %v", tv.val1, tv.val2)
} else if !tv.equal && eq {
t.Errorf("expected values to not be equal for %v and %v", tv.val1, tv.val2)
}
}
}
}
func TestInternerPhysProps(t *testing.T) {
var in interner
physProps1 := physical.Required{
Presentation: physical.Presentation{{Alias: "c", ID: 1}},
Ordering: physical.ParseOrderingChoice("+(1|2),+3 opt(4,5)"),
}
physProps2 := physical.Required{
Presentation: physical.Presentation{{Alias: "c", ID: 1}},
Ordering: physical.ParseOrderingChoice("+(1|2),+3 opt(4,5)"),
}
physProps3 := physical.Required{
Presentation: physical.Presentation{{Alias: "d", ID: 1}},
Ordering: physical.ParseOrderingChoice("+(1|2),+3 opt(4,5)"),
}
physProps4 := physical.Required{
Presentation: physical.Presentation{{Alias: "d", ID: 2}},
Ordering: physical.ParseOrderingChoice("+(1|2),+3 opt(4,5)"),
}
physProps5 := physical.Required{
Presentation: physical.Presentation{{Alias: "d", ID: 2}, {Alias: "e", ID: 3}},
Ordering: physical.ParseOrderingChoice("+(1|2),+3 opt(4,5)"),
}
physProps6 := physical.Required{
Presentation: physical.Presentation{{Alias: "d", ID: 2}, {Alias: "e", ID: 3}},
Ordering: physical.ParseOrderingChoice("+(1|2),+3 opt(4,5,6)"),
}
testCases := []struct {
phys *physical.Required
inCache bool
}{
{phys: &physProps1, inCache: false},
{phys: &physProps1, inCache: true},
{phys: &physProps2, inCache: true},
{phys: &physProps3, inCache: false},
{phys: &physProps4, inCache: false},
{phys: &physProps5, inCache: false},
{phys: &physProps6, inCache: false},
}
inCache := make(map[*physical.Required]bool)
for _, tc := range testCases {
interned := in.InternPhysicalProps(tc.phys)
if tc.inCache && !inCache[interned] {
t.Errorf("expected physical props to already be in cache: %s", tc.phys)
} else if !tc.inCache && inCache[interned] {
t.Errorf("expected physical props to not yet be in cache: %s", tc.phys)
}
inCache[interned] = true
}
}
func TestInternerCollision(t *testing.T) {
var in interner
// Start with a non-colliding value to make sure it doesn't interfere with
// subsequent values.
in.hasher.Init()
in.hasher.HashString("no-collide")
in.cache.Start(in.hasher.hash)
in.cache.Next()
in.cache.Add("no-collide")
// Intern a string that will "collide" with other values.
in.hasher.Init()
in.hasher.HashString("foo")
in.cache.Start(in.hasher.hash)
in.cache.Next()
in.cache.Add("foo")
// Now simulate a collision by using same hash as "foo".
in.cache.Start(in.hasher.hash)
in.cache.Next()
in.cache.Next()
in.cache.Add("bar")
// And another.
in.cache.Start(in.hasher.hash)
in.cache.Next()
in.cache.Next()
in.cache.Next()
in.cache.Add("baz")
// Ensure that first item can still be located.
in.cache.Start(in.hasher.hash)
if !in.cache.Next() || in.cache.Item() != "foo" {
t.Errorf("expected to find foo in cache after collision")
}
// Expect to find colliding item as well.
if !in.cache.Next() || in.cache.Item() != "bar" {
t.Errorf("expected to find bar in cache after collision")
}
// And last colliding item.
if !in.cache.Next() || in.cache.Item() != "baz" {
t.Errorf("expected to find baz in cache after collision")
}
// Should be no more items.
if in.cache.Next() {
t.Errorf("expected no more colliding items in cache")
}
}
func BenchmarkEncodeDatum(b *testing.B) {
r := rand.New(rand.NewSource(0))
datums := make([]tree.Datum, 10000)
for i := range datums {
datums[i] = randgen.RandDatumWithNullChance(r, randgen.RandEncodableType(r), 0)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for _, d := range datums {
encodeDatum(nil, d)
}
}
}
func BenchmarkIsDatumEqual(b *testing.B) {
r := rand.New(rand.NewSource(0))
datums := make([]tree.Datum, 1000)
for i := range datums {
datums[i] = randgen.RandDatumWithNullChance(r, randgen.RandEncodableType(r), 0)
}
b.ResetTimer()
var h hasher
for i := 0; i < b.N; i++ {
for _, d := range datums {
// IsDatumEqual is only called on values that hash the
// same, so only benchmark it on identical datums.
h.IsDatumEqual(d, d)
}
}
}
|
package mintinterfaces
import "net"
// Interface Connector
type ConnectorInterface interface {
// Connection start to work
Start()
// Stop the connection
Stop()
// Get TCP connection
GetClientConnection() *net.TCPConn
// Get connection ID
GetClientConnID() uint32
// Get IP:Port
GetClientAddr() net.Addr
// Send data to client
Send(data []byte, cnt int) error
}
type MintHandler func(*net.TCPConn, *int, chan []byte, []byte, int) error
|
package restic
// Backend is used to store and access data.
type Backend interface {
// Location returns a string that describes the type and location of the
// repository.
Location() string
// Test a boolean value whether a File with the name and type exists.
Test(t FileType, name string) (bool, error)
// Remove removes a File with type t and name.
Remove(t FileType, name string) error
// Close the backend
Close() error
// Load returns the data stored in the backend for h at the given offset
// and saves it in p. Load has the same semantics as io.ReaderAt, except
// that a negative offset is also allowed. In this case it references a
// position relative to the end of the file (similar to Seek()).
Load(h Handle, p []byte, off int64) (int, error)
// Save stores the data in the backend under the given handle.
Save(h Handle, p []byte) error
// Stat returns information about the File identified by h.
Stat(h Handle) (FileInfo, error)
// List returns a channel that yields all names of files of type t in an
// arbitrary order. A goroutine is started for this. If the channel done is
// closed, sending stops.
List(t FileType, done <-chan struct{}) <-chan string
}
// FileInfo is returned by Stat() and contains information about a file in the
// backend.
type FileInfo struct{ Size int64 }
|
package kademlia
import (
"context"
"errors"
"fmt"
"time"
"go.uber.org/zap"
)
// BucketSize is a constant value of the total number of peer ID entries a single routing table bucket hold.
const BucketSize int = 16
// PingTimeout is a constant value of ping timeout
const PingTimeout time.Duration = 3 * time.Second
// ErrBucketFull is an error of bucket is full
var ErrBucketFull = errors.New("bucket is full")
// Protocol represnets routing/discovery structure of the Kademlia protocol.
type Protocol struct {
node *Node
logger *zap.Logger
table *Table
events Events
pingTimeout time.Duration
}
// NewProtocol returns a new instance of the Kademlia protocol.
func NewProtocol(opts ...ProtocolOption) *Protocol {
p := &Protocol{
pingTimeout: PingTimeout,
}
for _, opt := range opts {
opt(p)
}
return p
}
// Find executes the Find RPC call to find the closest peers to some given target public key. It returns the IDs of
// the closest peers it finds.
func (p *Protocol) Find(target PublicKey, opts ...IteratorOption) []ID {
return NewIterator(p.node, p.table, opts...).Find(target)
}
// Discover executes Find to discover new peers to your node through peers your node already knows
func (p *Protocol) Discover(opts ...IteratorOption) []ID {
return p.Find(p.node.ID().ID, opts...)
}
// Ping sends a ping request to an address, and returns no error if a pong is received back, and returns error if
// disconnect or not get pong response
func (p *Protocol) Ping(ctx context.Context, addr string) error {
msg, err := p.node.RequestMessage(ctx, addr, Ping{})
if err != nil {
return fmt.Errorf("failed to ping: %w", err)
}
if _, ok := msg.(Pong); !ok {
return errors.New("did not get a pong back")
}
return nil
}
// Table returns the routing table.
func (p *Protocol) Table() *Table {
return p.table
}
// Ack update the routing table
func (p *Protocol) Ack(id ID) {
for {
inserted, err := p.table.Update(id)
if err == nil {
if inserted {
if p.events.OnPeerAdmitted != nil {
p.events.OnPeerAdmitted(id)
}
} else {
if p.events.OnPeerActivity != nil {
p.events.OnPeerActivity(id)
}
}
return
}
last := p.table.Last(id.ID)
ctx, cancel := context.WithTimeout(context.Background(), p.pingTimeout)
pong, err := p.node.RequestMessage(ctx, last.Address, Ping{})
cancel()
if err != nil {
if id, deleted := p.table.Delete(last.ID); deleted {
if p.events.OnPeerEvicted != nil {
p.events.OnPeerEvicted(id)
}
}
}
if _, ok := pong.(Pong); !ok {
if id, deleted := p.table.Delete(last.ID); deleted {
if p.events.OnPeerEvicted != nil {
p.events.OnPeerEvicted(id)
}
}
}
if p.events.OnPeerEvicted != nil {
p.events.OnPeerEvicted(id)
}
return
}
}
|
package p24
import (
"fmt"
"io/ioutil"
"log"
"strconv"
"strings"
)
func Main(args []string) {
if len(args) != 2 {
log.Fatal("usage: advent-of-code-2017 24[a|b] filename")
}
switch args[0] {
case "24a", "24":
fmt.Print(Strongest(args[1]))
case "24b":
fmt.Print(Longest(args[1]))
}
}
type Conn [2]int
func load(s string) ([]Conn, []int) {
if strings.HasPrefix(s, "@") {
f, err := ioutil.ReadFile(s[1:])
if err != nil {
log.Fatal(err)
}
s = string(f)
}
conns := make([]Conn, 0)
for _, line := range strings.Split(s, "\n") {
if line == "" {
continue
}
i := strings.Index(line, "/")
if i < 0 {
log.Fatal()
}
a, err := strconv.Atoi(line[:i])
if err != nil {
log.Fatal(err)
}
b, err := strconv.Atoi(line[i+1:])
if err != nil {
log.Fatal(err)
}
conns = append(conns, Conn{a, b})
}
left := []int{}
for i := range conns {
left = append(left, i)
}
return conns, left
}
func build(conns []Conn, port int, left []int) [][]int {
result := make([][]int, 0)
// Here we build all possible bridges.
// We keep track of which components are left and search for one that match the end-of-the-bridge.
// Each step recursively build a smaller bridge with left components.
for i, n := range left {
less := func() []int {
list := append([]int{}, left[:i]...)
if i != len(left) {
list = append(list, left[i+1:]...)
}
return list
}
step := func(p int) [][]int {
tail := build(conns, conns[n][p], less())
for i, list := range tail {
tail[i] = append([]int{n}, list...)
}
if len(tail) == 0 {
tail = [][]int{[]int{n}}
}
return tail
}
if conns[n][0] == port {
result = append(result, step(1)...)
continue
}
if conns[n][1] == port {
result = append(result, step(0)...)
continue
}
}
return result
}
func Strongest(s string) int {
conns, left := load(s)
max := 0
list := build(conns, 0, left)
for _, item := range list {
n := 0
for _, i := range item {
n += conns[i][0] + conns[i][1]
}
if n > max {
max = n
}
}
return max
}
func Longest(s string) int {
conns, left := load(s)
max, longest := 0, 0
list := build(conns, 0, left)
for _, item := range list {
if len(item) >= longest {
n := 0
for _, i := range item {
n += conns[i][0] + conns[i][1]
}
if n > max {
longest, max = len(item), n
}
}
}
return max
}
|
package repository
import (
"github.com/porter-dev/porter/internal/models"
)
type NotificationConfigRepository interface {
CreateNotificationConfig(am *models.NotificationConfig) (*models.NotificationConfig, error)
ReadNotificationConfig(id uint) (*models.NotificationConfig, error)
UpdateNotificationConfig(am *models.NotificationConfig) (*models.NotificationConfig, error)
}
|
package commands
import (
"github.com/codegangsta/cli"
"github.com/mitsuse/parser-go"
)
func NewTrainCommand(c *parser.Config) cli.Command {
command := cli.Command{
Name: "train",
ShortName: "t",
Usage: "Trains a dependency parser with data.",
Action: newTrainAction(c),
Flags: []cli.Flag{
cli.StringFlag{
Name: "model,m",
Value: "model.parser",
Usage: "The output path of a trained parser.",
},
cli.StringFlag{
Name: "corpus,c",
Value: "corpus.parsed",
Usage: "The input path of a parsed corpus.",
},
},
}
return command
}
func newTrainAction(c *parser.Config) func(context *cli.Context) {
action := func(context *cli.Context) {
// TODO: Implement this.
}
return action
}
|
package sLSM
type KVIntPair struct {
kvp KVPair
i int
}
func NewKVIntPair(pair KVPair, i int) *KVIntPair {
return &KVIntPair{
kvp: pair,
i: i,
}
}
type StaticHeap struct {
h []KVIntPair
cmp Comparer
}
func NewStaticHeap(size int, cmp Comparer) *StaticHeap {
return &StaticHeap{
h: make([]KVIntPair, size),
cmp: cmp,
}
}
func (s *StaticHeap) Len() int {
return len(s.h)
}
func (s *StaticHeap) Less(i, j int) bool {
if s.cmp.Lt(s.h[i].kvp.Key, s.h[j].kvp.Key) {
return true
}
if s.cmp.Eq(s.h[i].kvp.Key, s.h[j].kvp.Key) && s.h[i].i < s.h[j].i {
return true
}
return false
}
func (s *StaticHeap) Swap(i, j int) {
s.h[i], s.h[j] = s.h[j], s.h[i]
//(*s).h[i], (*s).h[j] = (*s).h[j], (*s).h[i]
}
func (s *StaticHeap) Push(x interface{}) {
s.h = append(s.h, x.(KVIntPair))
}
func (s *StaticHeap) Pop() (v interface{}) {
s.h, v = s.h[:s.Len()-1], s.h[s.Len()-1]
return
}
|
package yelp
import "testing"
// TestParseURL tests the expected case for transforming a URL to Yelp ID
func TestParseURL(t *testing.T) {
example := "http://www.yelp.com/biz/kona-club-oakland"
if ParseURL(example) != "kona-club-oakland" {
t.Errorf("Error parsing URL. Expected: %v got: %v", "kona-club-oakland", ParseURL(example))
}
}
|
// API between the Go application and the MySql database.
package main
import (
"log"
"net/url"
"strconv"
"time"
)
type SABReports struct {
Central1 float64 `json:"central1"`
Central2 float64 `json:"central2"`
Central3 float64 `json:"central3"`
Central4 float64 `json:"central4"`
Central6 float64 `json:"central6"`
North5 float64 `json:"north5"`
North6 float64 `json:"north6"`
North7 float64 `json:"north7"`
UpdatedTime time.Time `json:"updatedTime"`
}
func notifySABReports() SABReports {
rows, err := db.Query("SELECT sfs.register, sfs.total FROM sab_form_submission AS sfs WHERE DATE(sfs.date_submitted) = CURDATE()")
checkError(err)
defer rows.Close()
reports := SABReports{
Central1: 0.00,
Central2: 0.00,
Central3: 0.00,
Central4: 0.00,
Central6: 0.00,
North5: 0.00,
North6: 0.00,
North7: 0.00,
UpdatedTime: time.Now(),
}
for rows.Next() {
var register string
var total string
err = rows.Scan(®ister, &total)
checkError(err)
switch register {
case "Central - 1":
totalToAdd, err := strconv.ParseFloat(total, 64)
checkError(err)
newTotal := reports.Central1 + totalToAdd
reports.Central1 = newTotal
case "Central - 2":
totalToAdd, err := strconv.ParseFloat(total, 64)
checkError(err)
newTotal := reports.Central2 + totalToAdd
reports.Central2 = newTotal
case "Central - 3":
totalToAdd, err := strconv.ParseFloat(total, 64)
checkError(err)
newTotal := reports.Central3 + totalToAdd
reports.Central3 = newTotal
case "Central - 4 (Repair)":
totalToAdd, err := strconv.ParseFloat(total, 64)
checkError(err)
newTotal := reports.Central4 + totalToAdd
reports.Central4 = newTotal
case "Central - 6 (Shipping)":
totalToAdd, err := strconv.ParseFloat(total, 64)
checkError(err)
newTotal := reports.Central6 + totalToAdd
reports.Central6 = newTotal
case "North - 5":
totalToAdd, err := strconv.ParseFloat(total, 64)
checkError(err)
newTotal := reports.North5 + totalToAdd
reports.North5 = newTotal
case "North - 6 (Manager's Desk)":
totalToAdd, err := strconv.ParseFloat(total, 64)
checkError(err)
newTotal := reports.North6 + totalToAdd
reports.North6 = newTotal
case "North - 7 (Repair)":
totalToAdd, err := strconv.ParseFloat(total, 64)
checkError(err)
newTotal := reports.North7 + totalToAdd
reports.North7 = newTotal
default:
panic("unrecognized reigister")
}
}
return reports
}
func submitSABForm(formData url.Values) {
// Prepare the query
stmt, err := db.Prepare("INSERT INTO sab_form_submission (date_submitted, uniqname, is_medical_student, medical_school_code, phone_number, subtotal, tax, total, rms_transaction, register) VALUES (NOW(), ?,?,?,?,?,?,?,?,?)")
checkError(err)
defer stmt.Close()
res, err := stmt.Exec(formData.Get("uniqname"), formData.Get("isMedicalStudent"), formData.Get("medicalSchoolCode"), formData.Get("phoneNumber"), formData.Get("subtotal"), formData.Get("tax"), formData.Get("total"), formData.Get("rmsTransaction"), formData.Get("register"))
checkError(err)
log.Println(res)
// Pusher event trigger
var register string
switch formData.Get("register") {
case "Central - 1":
register = "central1"
case "Central - 2":
register = "central2"
case "Central - 3":
register = "central3"
case "Central - 4 (Repair)":
register = "central4"
case "Central - 6 (Shipping)":
register = "central6"
case "North - 5":
register = "north5"
case "North - 6 (Manager's Desk)":
register = "north6"
case "North - 7 (Repair)":
register = "north7"
default:
panic("unrecognized reigster")
}
event_data := map[string]string{"register": register, "total": formData.Get("total")}
pusherClient.Trigger("reports_channel", "sab-form-submitted", event_data)
}
|
package main
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRead_OK(t *testing.T) {
bsonService := defaultBsonService{}
bson := "\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00"
result, err := bsonService.ReadNextBSON(strings.NewReader(bson))
assert.NoError(t, err, "Error wasn't expected during read.")
assert.Equal(t, []byte(bson), result)
}
func TestRead_ErrorTooShort(t *testing.T) {
bsonService := defaultBsonService{}
_, err := bsonService.ReadNextBSON(strings.NewReader("\x04"))
assert.Error(t, err, "Error was expected for being to short.")
}
func TestRead_ErrorUnexpectedEOF(t *testing.T) {
bsonService := defaultBsonService{}
_, err := bsonService.ReadNextBSON(strings.NewReader("\x16\x00\x00\x00\x02hel-\x00\x00"))
assert.Error(t, err, "Error was expected for broken doc.")
assert.Equal(t, "error reading (partial) from buffer: unexpected EOF", err.Error())
}
|
package sharding
import "math/rand"
func SetUUIDRand(r *rand.Rand) {
uuidRand = r
}
|
package leetcode
func findMin(nums []int) int {
low, mid, high := 0, 0, len(nums)-1
for low+1 < high {
mid = low + (high-low)>>1
if nums[mid] == nums[high] {
high = mid
} else if nums[mid] > nums[high] {
low = mid
} else {
high = mid
}
}
if nums[low] <= nums[high] {
return nums[low]
}
return nums[high]
}
|
package main
import "fmt"
func main() {
array := []int{3, 2, 1, 20, 5, 6, 42, -2, 4, 3}
sort(array)
fmt.Println(array)
}
func sort(array []int) {
sorted := false
for !sorted {
withoutSwap := true
for i := 0; i < len(array)-1; i++ {
if array[i] > array[i+1] {
swap(array, i, i+1)
withoutSwap = false
}
}
if withoutSwap == true {
sorted = true
}
}
}
func swap(array []int, first int, second int) {
array[first], array[second] = array[second], array[first]
}
|
package gmapssvc
import (
"encoding/json"
"fmt"
"golang.org/x/net/context"
googlemap "googlemaps.github.io/maps"
"github.com/moul/gmaps-uservice/gen/pb"
)
type Service struct {
gm *googlemap.Client
}
func New(gm *googlemap.Client) gmapspb.GmapsServiceServer {
return &Service{gm: gm}
}
func (s *Service) Directions(ctx context.Context, in *gmapspb.DirectionsRequest) (*gmapspb.DirectionsResponse, error) {
inJson, err := json.Marshal(in)
if err != nil {
return nil, err
}
var req googlemap.DirectionsRequest
if err = json.Unmarshal(inJson, &req); err != nil {
return nil, err
}
routes, geocodedWaypoint, err := s.gm.Directions(ctx, &req)
if err != nil {
return nil, err
}
var rep gmapspb.DirectionsResponse
outJson, err := json.Marshal(routes)
if err != nil {
return nil, err
}
if err = json.Unmarshal(outJson, &rep.Routes); err != nil {
return nil, err
}
outJson, err = json.Marshal(geocodedWaypoint)
if err != nil {
return nil, err
}
if err = json.Unmarshal(outJson, &rep.GeocodedWaypoint); err != nil {
return nil, err
}
return &rep, nil
}
func (s *Service) Geocode(ctx context.Context, in *gmapspb.GeocodeRequest) (*gmapspb.GeocodeResponse, error) {
inJson, err := json.Marshal(in)
if err != nil {
return nil, err
}
var req googlemap.GeocodingRequest
if err = json.Unmarshal(inJson, &req); err != nil {
fmt.Println(err.(*json.UnmarshalTypeError).Offset)
return nil, err
}
results, err := s.gm.Geocode(ctx, &req)
if err != nil {
return nil, err
}
var rep gmapspb.GeocodeResponse
outJson, err := json.Marshal(results)
if err != nil {
return nil, err
}
if err = json.Unmarshal(outJson, &rep.Results); err != nil {
return nil, err
}
return &rep, nil
}
|
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
)
func metaPublisher(resourceKey string) {
if resourceKey == "list" {
resourceKey = ""
}
res, err := http.Get("http://169.254.169.254/latest/meta-data/" + resourceKey)
if err != nil {
fmt.Printf("an error has occurred: %t\n", err)
return
}
b, e := ioutil.ReadAll(res.Body)
content := string(b)
if e != nil {
fmt.Printf("an error has occurred: %t\n", err)
return
}
if resourceKey == "list" {
fmt.Printf("%s\n\n", content)
} else {
fmt.Printf("%s: %s\n\n", resourceKey, content)
}
}
func showHelp() {
fmt.Println("Please supply resource name or resource group name as an argument to the program. " +
"A full list can be found by passing " +
"list' as an argument (i.e. ./app list) or by visiting the following link: " +
"https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html")
}
func main() {
if len(os.Args) == 1 {
showHelp()
os.Exit(0)
}
metaPublisher(strings.ToLower(os.Args[1]))
}
|
package src
import (
"github.com/kataras/iris"
"os"
)
func GetDelete(ctx iris.Context) {
if auth, _ := sess.Start(ctx).GetBoolean("IsLog"); !auth {
ctx.StatusCode(iris.StatusForbidden)
return
}
filename := ctx.Params().Get("filename")
err := os.Remove(FilePath + filename)
if err != nil {
RtData := flag {
Success: "0",
}
ctx.ContentType("application/json")
_, _ = ctx.JSON(RtData)
return
}
RtData := flag {
Success: "1",
}
ctx.ContentType("application/json")
_, _ = ctx.JSON(RtData)
}
|
type ActorState union {
| InitActorState
| AccountActorState
| StorageMarketActorState
| StorageMinerActorState
| PaymentChannelBrokerActorState
| MultisigActorState
} // representation kinded
|
package models
type Lead map[string]interface{}
func (l *Lead) Get(key string, alterValue interface{}) interface{} {
temp := *l
if _, ok := temp[key]; !ok {
return alterValue
}
return temp[key]
}
|
package conv
import (
"fmt"
"log"
"reflect"
"strconv"
)
// ToBool converts i to bool
// i can be bool, integer or string
func ToBool(i interface{}) (bool, error) {
i = Indirect(i)
switch v := i.(type) {
case bool:
return v, nil
case nil:
return false, errNilValue
case string:
return strconv.ParseBool(v)
}
if b, ok := i.([]byte); ok {
i = string(b)
}
switch v := reflect.ValueOf(i); v.Kind() {
case reflect.Bool:
return v.Bool(), nil
case reflect.String:
return strconv.ParseBool(v.String())
}
n, err := parseInt64(i)
if err != nil {
return false, fmt.Errorf("cannot convert %#v of type %T to bool", i, i)
}
return n != 0, nil
}
// MustBool converts i to bool, will panic if failed
func MustBool(i interface{}) bool {
v, err := ToBool(i)
if err != nil {
log.Panic(err)
}
return v
}
// ToBoolSlice converts i to []bool
// i is an array or slice with elements convertiable to bool
func ToBoolSlice(i interface{}) ([]bool, error) {
i = Indirect(i)
if i == nil {
return nil, nil
}
if l, ok := i.([]bool); ok {
return l, nil
}
v := reflect.ValueOf(i)
if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
return nil, fmt.Errorf("cannot convert %#v of type %T to []bool", i, i)
}
num := v.Len()
res := make([]bool, num)
var err error
for j := 0; j < num; j++ {
res[j], err = ToBool(v.Index(j).Interface())
if err != nil {
return nil, fmt.Errorf("convert index %d: %w", i, err)
}
}
return res, nil
}
// MustBoolSlice converts i to []bool, will panic if failed
func MustBoolSlice(i interface{}) []bool {
v, err := ToBoolSlice(i)
if err != nil {
log.Panic(err)
}
return v
}
|
package imageComparator
import (
"fmt"
"github.com/rs/zerolog/log"
"github.com/vitali-fedulov/images"
)
func SelectImgToCompare(uploadedImg string, compareImg string) error{
imgA, err := images.Open(uploadedImg)
if err != nil {
log.Error().Timestamp().Err(err)
}
imgB, err := images.Open(compareImg)
if err != nil {
log.Error().Timestamp().Err(err)
}
hashA, imgSizeA := images.Hash(imgA)
hashB, imgSizeB := images.Hash(imgB)
if images.Similar(hashA, hashB, imgSizeA, imgSizeB) {
fmt.Println("Images are similar.")
} else {
fmt.Println("Images are distinct.")
}
return nil
}
|
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
func absurd(n int, t []string) int {
var v int
m := make([]bool, n-1)
for _, i := range t {
fmt.Sscanf(i, "%d", &v)
if m[v] {
return v
}
m[v] = true
}
return -1
}
func main() {
var n int
data, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer data.Close()
scanner := bufio.NewScanner(data)
for scanner.Scan() {
s := strings.Split(scanner.Text(), ";")
fmt.Sscanf(s[0], "%d", &n)
fmt.Println(absurd(n, strings.Split(s[1], ",")))
}
}
|
package hivesql
import (
"reflect"
"testing"
)
func Test_parseDSN(t *testing.T) {
type args struct {
dsn string
}
tests := []struct {
name string
args args
wantCfg *config
wantErr bool
}{
{
"simple DSN",
args{"user:pass@localhost/"},
&config{
user: "user",
password: "pass",
addr: "localhost:10000",
dbName: "default",
},
false,
},
{
"ip DSN",
args{"user:pass@127.0.0.1/"},
&config{
user: "user",
password: "pass",
addr: "127.0.0.1:10000",
dbName: "default",
},
false,
},
{
"db name",
args{"user:pass@/blah"},
&config{
user: "user",
password: "pass",
addr: "localhost:10000",
dbName: "blah",
},
false,
},
{
"hive opts",
args{"user:pass@/?hive.opt1=123&hive.opt2=true"},
&config{
user: "user",
password: "pass",
addr: "localhost:10000",
dbName: "default",
hiveConfig: map[string]string{
"hive.opt1": "123",
"hive.opt2": "true",
},
},
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotCfg, err := parseDSN(tt.args.dsn)
if (err != nil) != tt.wantErr {
t.Errorf("parseDSN() error = %v, wantErr %v, cfg %v", err, tt.wantErr, tt.wantCfg)
return
}
if !reflect.DeepEqual(gotCfg, tt.wantCfg) {
t.Errorf("parseDSN() = %v, want %v", gotCfg, tt.wantCfg)
}
})
}
}
|
package section
import(
//"github.com/codebuff95/uafm"
//"github.com/codebuff95/uafm/usersession"
"github.com/codebuff95/uafm/formsession"
"feedback-admin/user"
"feedback-admin/course"
"feedback-admin/database"
"feedback-admin/faculty"
"feedback-admin/college"
"feedback-admin/password"
"feedback-admin/subject"
"feedback-admin/templates"
"net/http"
"strconv"
"time"
"log"
"errors"
"html/template"
"gopkg.in/mgo.v2/bson"
"os"
)
type Teacher struct{
Facultyid string `bson:"facultyid"`
Subjectid string `bson:"subjectid"`
}
type DetailedTeacher struct{
Facultyid string `bson:"facultyid"`
Facultyname string `bson:"facultyname"`
Subjectid string `bson:"subjectid"`
Subjectname string `bson:"subjectname"`
}
type Section struct{
Sectionid string `bson:"sectionid"`
Sectionname string `bson:"sectionname"`
Year int `bson:"year"`
Session int `bson:"session"`
Courseid string `bson:"courseid"`
Teachers *[]Teacher `bson:"teachers,omitempty"`
Passwords *[]string `bson:"passwords"`
Students int `bson:"students"`
Addedon string `bson:"addedon"`
}
type SectionPage struct{
Sections *[]Section
FormSid *string
Session *string
Collegename *string
}
func GetSections(mysession string) (*[]Section,error){
log.Println("Getting Sections Slice for session:",mysession)
mysessionint,err := strconv.Atoi(mysession)
if err != nil{
log.Println("Error converting section session to int:",err)
return nil,err
}
var mySectionSlice []Section
err = database.SectionCollection.Find(bson.M{"session":mysessionint}).Sort("courseid","year","sectionid").All(&mySectionSlice)
if err != nil{
log.Println("Error finding sections:",err)
return nil,err
}
log.Println("Success getting sectionSlice of size:",len(mySectionSlice))
if len(mySectionSlice) == 0{
log.Println("Length of mySectionSlice is 0. Returning nil Section Slice.")
return nil,nil
}
for i := 0; i < len(mySectionSlice); i++{
if mySectionSlice[i].Teachers != nil && len(*mySectionSlice[i].Teachers) == 0{
log.Println("nilling teachers for section ID:",mySectionSlice[i].Sectionid)
mySectionSlice[i].Teachers = nil
}
if mySectionSlice[i].Passwords != nil && len(*mySectionSlice[i].Passwords) == 0{
log.Println("nilling passwords for section ID:",mySectionSlice[i].Sectionid)
mySectionSlice[i].Passwords = nil
}
}
log.Println("Returning mySectionSlice")
return &mySectionSlice,nil
}
func GetSection(sectionid string) (*Section,error){
log.Println("Getting section with sectionid:",sectionid)
var mySection *Section = &Section{}
err := database.SectionCollection.Find(bson.M{"sectionid" : sectionid}).Limit(1).One(mySection)
if err != nil{
log.Println("Could not get section.")
return nil,err
}
return mySection,nil
}
func displaySectionPage(w http.ResponseWriter, r *http.Request){
log.Println("Displaying section page to user.")
r.ParseForm()
mysession := r.Form.Get("sectionsession")
//validate my session
mySessionInt,err := strconv.Atoi(mysession)
if err != nil || mySessionInt < 1990 || mySessionInt > 2030{
displayBadPage(w,r,errors.New("Bad Session"))
return
}
//
var mySectionPage SectionPage
formSid, err := formsession.CreateSession("0",time.Minute*10) //Form created will be valid for 10 minutes.
if err != nil{
log.Println("Error creating new session for Section form:",err)
displayBadPage(w,r,err)
return
}
mySectionPage.FormSid = formSid
mySectionPage.Collegename = &college.GlobalDetails.Collegename
log.Println("Creating new Section page to client",r.RemoteAddr,"with formSid:",*mySectionPage.FormSid) //Enter client ip address and new form SID.
mySectionPage.Session = &mysession
mySectionPage.Sections,_ = GetSections(mysession)
log.Println("Executing SectionPageTemplate")
templates.SectionPageTemplate.Execute(w,mySectionPage)
}
func displayBadPage(w http.ResponseWriter, r *http.Request, err error){
templates.BadPageTemplate.Execute(w,err.Error())
}
func SectionHandler(w http.ResponseWriter, r *http.Request){
log.Println("***SECTION HANDLER***")
log.Println("Serving client:",r.RemoteAddr)
_, err := user.AuthenticateRequest(r)
if err != nil{ //user session not authentic. Redirect to login page.
log.Println("User session is not authentic, displaying badpage.")
//http.Redirect(w, r, "/login", http.StatusSeeOther)
displayBadPage(w,r,err)
return
}
log.Println("User Session is authentic")
displaySectionPage(w,r)
}
func AddSectionHandler(w http.ResponseWriter, r *http.Request){
log.Println("***ADD SECTION HANDLER***")
log.Println("Serving client:",r.RemoteAddr)
_, err := user.AuthenticateRequest(r)
if err != nil{ //user session not authentic. Redirect to login page.
log.Println("User session is not authentic, displaying badpage.")
//http.Redirect(w, r, "/login", http.StatusSeeOther)
displayBadPage(w,r,err)
return
}
log.Println("User Session is authentic. Validating form and Parsing form for new Section data.")
if r.Method != "POST"{
displayBadPage(w,r,errors.New("Please add new section properly"))
return
}
r.ParseForm()
_,err = formsession.ValidateSession(r.Form.Get("formsid"))
if err != nil{
log.Println("Error validating formSid:",err,". Displaying badpage.")
displayBadPage(w,r,err)
return
}
enteredSectionId := template.HTMLEscapeString(r.Form.Get("sectionid"))
enteredSectionName := template.HTMLEscapeString(r.Form.Get("sectionname"))
enteredSectionYear,err := strconv.Atoi(template.HTMLEscapeString(r.Form.Get("sectionyear")))
if err != nil{
log.Println("Error validating entered form:",err,". Displaying badpage.")
displayBadPage(w,r,errors.New("Entered SectionYear invalid."))
return
}
enteredSectionSession,err := strconv.Atoi(template.HTMLEscapeString(r.Form.Get("sectionsession")))
if err != nil{
log.Println("Error validating entered form:",err,". Displaying badpage.")
displayBadPage(w,r,errors.New("Entered SectionSession invalid."))
return
}
enteredCourseId := template.HTMLEscapeString(r.Form.Get("sectioncourseid"))
_,err = course.GetCourse(enteredCourseId)
if err != nil{
log.Println("Error validating entered form:",err,". Displaying badpage.")
displayBadPage(w,r,errors.New("Entered CourseId invalid."))
return
}
enteredStudents,err := strconv.Atoi(template.HTMLEscapeString(r.Form.Get("sectionstudents")))
if err != nil{
log.Println("Error validating entered form:",err,". Displaying badpage.")
displayBadPage(w,r,errors.New("Entered SectionStudents invalid."))
return
}
myPasswords := password.GenerateRandomPasswords(enteredStudents)
addedOn := time.Now().Format("2006-01-02 15:04:05")
myNewSection := &Section{Sectionid : enteredSectionId, Sectionname : enteredSectionName, Year : enteredSectionYear, Session : enteredSectionSession, Courseid : enteredCourseId, Students : enteredStudents, Passwords : &myPasswords, Addedon : addedOn}
log.Println("Adding new Section with details:",*myNewSection)
err = AddSection(myNewSection)
if err != nil{
displayBadPage(w,r,err)
return
}
log.Println("Successfully added new Section with Id:",enteredSectionId,", name:",enteredSectionName)
http.Redirect(w, r, "/section?sectionsession="+strconv.Itoa(enteredSectionSession), http.StatusSeeOther)
}
func RemoveSectionHandler(w http.ResponseWriter,r *http.Request){
log.Println("***REMOVE SECTION HANDLER***")
log.Println("Serving client:",r.RemoteAddr)
_, err := user.AuthenticateRequest(r)
if err != nil{ //user session not authentic.
log.Println("User session is not authentic, displaying badpage.")
//http.Redirect(w, r, "/login", http.StatusSeeOther)
displayBadPage(w,r,err)
return
}
log.Println("User Session is authentic. Validating remove Section request.")
if r.Method != "GET"{
displayBadPage(w,r,errors.New("Please remove section properly"))
return
}
mySectionId := template.HTMLEscapeString(r.URL.Path[len("/removesection/"):])
mySection,_ := GetSection(mySectionId)
_,err = RemoveSection(mySectionId)
if err != nil{
log.Println("Problem removing Section:",err)
displayBadPage(w,r,err)
return
}
log.Println("Success removing Section:",mySectionId)
http.Redirect(w, r, "/section?sectionsession="+strconv.Itoa(mySection.Session), http.StatusSeeOther)
}
func AddSection(mysection *Section) error{
return database.SectionCollection.Insert(mysection)
}
func RemoveSection(id string) (int,error){
changeinfo,err := database.SectionCollection.RemoveAll(bson.M{"sectionid":id})
if changeinfo == nil{
return 0,err
}
return changeinfo.Removed,err
}
func AddTeacherHandler(w http.ResponseWriter, r *http.Request){
log.Println("***ADD TEACHER HANDLER***")
log.Println("Serving client:",r.RemoteAddr)
_, err := user.AuthenticateRequest(r)
if err != nil{ //user session not authentic. Redirect to login page.
log.Println("User session is not authentic, displaying badpage.")
//http.Redirect(w, r, "/login", http.StatusSeeOther)
displayBadPage(w,r,err)
return
}
log.Println("User Session is authentic. Validating form and Parsing form for new teacher data.")
if r.Method != "POST"{
displayBadPage(w,r,errors.New("Please add new teacher properly"))
return
}
r.ParseForm()
_,err = formsession.ValidateSession(r.Form.Get("formsid"))
if err != nil{
log.Println("Error validating formSid:",err,". Displaying badpage.")
displayBadPage(w,r,err)
return
}
enteredSectionId := template.HTMLEscapeString(r.Form.Get("sectionid"))
mySection,err := GetSection(enteredSectionId)
if err != nil{
log.Println("Bad Sectionid:",err)
displayBadPage(w,r,errors.New("Bad Section ID"))
return
}
enteredFacultyId := template.HTMLEscapeString(r.Form.Get("facultyid"))
_,err = faculty.GetFaculty(enteredFacultyId)
if err != nil{
log.Println("Bad Facultyid:",err)
displayBadPage(w,r,errors.New("Bad Faculty ID"))
return
}
enteredSubjectId := template.HTMLEscapeString(r.Form.Get("subjectid"))
_,err = subject.GetSubject(enteredSubjectId)
if err != nil{
log.Println("Bad Subjectid:",err)
displayBadPage(w,r,errors.New("Bad Subject ID"))
return
}
myNewTeacher := &Teacher{Facultyid : enteredFacultyId, Subjectid : enteredSubjectId}
log.Println("Adding new teacher to sectionid:",enteredSectionId," with details:",*myNewTeacher)
err = AddTeacher(enteredSectionId,myNewTeacher)
if err != nil{
log.Println("Error adding teacher to sectionid:",enteredSectionId,":",err)
displayBadPage(w,r,err)
return
}
log.Println("Successfully added new teacher to sectionid:",enteredSectionId," with FacultyId:",enteredFacultyId,", SubjectId:",enteredSubjectId)
http.Redirect(w, r, "/section?sectionsession="+strconv.Itoa(mySection.Session), http.StatusSeeOther)
}
func AddTeacher(sectionId string, myTeacher *Teacher) error{
_,err := GetSection(sectionId)
if err != nil{
return err
}
return database.SectionCollection.Update(bson.M{"sectionid" : sectionId},bson.M{"$push":bson.M{"teachers" : myTeacher}})
}
func RemoveTeacherHandler(w http.ResponseWriter, r *http.Request){
log.Println("***REMOVE TEACHER HANDLER***")
log.Println("Serving client:",r.RemoteAddr)
_, err := user.AuthenticateRequest(r)
if err != nil{ //user session not authentic. Redirect to login page.
log.Println("User session is not authentic, displaying badpage.")
//http.Redirect(w, r, "/login", http.StatusSeeOther)
displayBadPage(w,r,err)
return
}
log.Println("User Session is authentic. Validating form and Parsing form for remove teacher data.")
if r.Method != "POST"{
displayBadPage(w,r,errors.New("Please remove teacher properly"))
return
}
r.ParseForm()
_,err = formsession.ValidateSession(r.Form.Get("formsid"))
if err != nil{
log.Println("Error validating formSid:",err,". Displaying badpage.")
displayBadPage(w,r,err)
return
}
enteredSectionId := template.HTMLEscapeString(r.Form.Get("sectionid"))
mySection,err := GetSection(enteredSectionId)
if err != nil{
log.Println("Bad Sectionid:",err)
displayBadPage(w,r,errors.New("Bad Section ID"))
return
}
enteredFacultyId := template.HTMLEscapeString(r.Form.Get("facultyid"))
_,err = faculty.GetFaculty(enteredFacultyId)
if err != nil{
log.Println("Bad Facultyid:",err)
displayBadPage(w,r,errors.New("Bad Faculty ID"))
return
}
enteredSubjectId := template.HTMLEscapeString(r.Form.Get("subjectid"))
_,err = subject.GetSubject(enteredSubjectId)
if err != nil{
log.Println("Bad Subjectid:",err)
displayBadPage(w,r,errors.New("Bad Subject ID"))
return
}
myTeacher := &Teacher{Facultyid : enteredFacultyId, Subjectid : enteredSubjectId}
log.Println("Removing teacher from sectionid:",enteredSectionId," with details:",*myTeacher)
err = RemoveTeacher(enteredSectionId,myTeacher)
if err != nil{
log.Println("Error removing teacher from sectionid:",enteredSectionId,":",err)
displayBadPage(w,r,err)
return
}
log.Println("Successfully removed teacher from sectionid:",enteredSectionId," with FacultyId:",enteredFacultyId,", SubjectId:",enteredSubjectId)
http.Redirect(w, r, "/section?sectionsession="+strconv.Itoa(mySection.Session), http.StatusSeeOther)
}
func RemoveTeacher(sectionId string, myTeacher *Teacher) error{
_,err := GetSection(sectionId)
if err != nil{
return err
}
err = database.SectionCollection.Update(bson.M{"sectionid" : sectionId},bson.M{"$pull":bson.M{"teachers" : myTeacher}})
if err != nil{
return err
}
return err
//check if teacher array of section with sectionid = sectionId is empty. if yes, $unset teacher array.
}
func GetDetailedTeachers(myTeachers *[]Teacher) (*[]DetailedTeacher,error){
log.Println("*Getting Detailed Teachers*")
if myTeachers == nil || len(*myTeachers) == 0{
log.Println("myTeachers slice passed to GetDetailedTeachers is nil. Returning nil DetailedTeacher slice.")
return nil,errors.New("No Teachers")
}
myDetailedTeachers := make([]DetailedTeacher,len(*myTeachers))
for i,myTeacher := range *myTeachers{
myDetailedTeachers[i].Facultyid = myTeacher.Facultyid
myDetailedTeachers[i].Subjectid = myTeacher.Subjectid
myFaculty,err := faculty.GetFaculty(myTeacher.Facultyid)
if err != nil{
return nil,errors.New("Could not find faculty with facultyid:" + myTeacher.Facultyid)
}
myDetailedTeachers[i].Facultyname = myFaculty.Facultyname
mySubject,err := subject.GetSubject(myTeacher.Subjectid)
if err != nil{
return nil,errors.New("Could not find subject with subjectid:" + mySubject.Subjectid)
}
myDetailedTeachers[i].Subjectname = mySubject.Subjectname
}
log.Println("Success getting DetailedTeachers from Teachers. Returning slice of DetailedTeachers")
return &myDetailedTeachers,nil
}
func GenerateSectionPasswordsHandler(w http.ResponseWriter, r *http.Request){
log.Println("***GENERATE SECTION PASSWORDS HANDLER***")
log.Println("Serving client:",r.RemoteAddr)
_, err := user.AuthenticateRequest(r)
if err != nil{ //user session not authentic. Redirect to login page.
log.Println("User session is not authentic, displaying badpage.")
//http.Redirect(w, r, "/login", http.StatusSeeOther)
displayBadPage(w,r,err)
return
}
log.Println("User Session is authentic")
if r.Method != "POST"{
displayBadPage(w,r,errors.New("Please generate passwords properly"))
return
}
r.ParseForm()
mySectionId := template.HTMLEscapeString(r.Form.Get("sectionid"))
mySection,err := GetSection(mySectionId)
if err != nil || mySection == nil{
log.Println("Error finding section with section ID:",mySectionId)
displayBadPage(w,r,errors.New("Section with submitted SectionID not found"))
return
}
log.Println("Successfully got section with section ID:",mySectionId)
filewriter, err := os.Create("password-"+mySection.Sectionid+".csv")
defer filewriter.Close()
if err != nil{
log.Println("Problem opening file for writing")
displayBadPage(w,r,errors.New("Problem opening file for creating passwords"))
return
}
templates.PasswordsTemplate.Execute(filewriter,mySection)
http.Redirect(w, r, "/section?sectionsession="+strconv.Itoa(mySection.Session), http.StatusSeeOther)
return
}
|
package main
import (
//"fmt"
)
// immutable struct to keep track of characters used for a combination of words
type CharList struct {
Chars []int //length 26, chars[0] is # of 'a's, chars[1] is # of 'b's, etc
Components []string
}
func NewCharList() CharList {
return CharList{
Chars: make([]int, 26),
Components: make([]string, 0, 15),
}
}
// takes in a string, and will return a new charList with that string added
func (c CharList) addString(add string) CharList {
newChars := generateInts(add)
for i := 0; i < 26; i++ {
newChars[i] += c.Chars[i]
}
return CharList{
Chars: newChars,
Components: append(c.Components, add),
}
}
// returns false if the other has more of any char than itself
func (c CharList) withinBounds(other CharList) bool {
for i, val := range c.Chars {
if val < other.Chars[i] {
return false
}
}
return true
}
// returns false if the other has a diff # of any char than itself
func (c CharList) equals(other CharList) bool {
for i, val := range c.Chars {
if val != other.Chars[i] {
return false
}
}
return true
}
// assumes that the string passed in is all lowercase and only has alphabetical (and space) characters
func generateInts(base string) []int {
chars := make([]int, 26)
for i, len := 0, len(base); i < len; i++ {
ascii := int(base[i])
if ascii == 32 || ascii == 39 { // space or apostrophe ignored
continue
}
ascii = ascii - 97
if ascii < 0 || ascii > 26 {
chars[0] = 99999; // used to prevent words with special characters from being (e.g. é)
// used should be changed to something that is more clear
continue;
}
chars[ascii]++
}
return chars
}
|
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package crostini
import (
"context"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"chromiumos/tast/common/testexec"
"chromiumos/tast/local/chrome/vmc"
"chromiumos/tast/local/crostini"
"chromiumos/tast/testing"
)
const testScript string = "test-extra-disk.sh"
func init() {
testing.AddTest(&testing.Test{
Func: VmcExtraDisk,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Starts Crostini with an extra disk image",
Contacts: []string{"clumptini+oncall@google.com"},
SoftwareDeps: []string{"chrome", "vm_host", "untrusted_vm"},
Attr: []string{"group:mainline"},
Data: []string{testScript},
Params: []testing.Param{
// Parameters generated by params_test.go. DO NOT EDIT.
{
Name: "buster_stable",
ExtraSoftwareDeps: []string{"dlc"},
ExtraHardwareDeps: crostini.CrostiniStable,
Fixture: "crostiniBuster",
Timeout: 7 * time.Minute,
}, {
Name: "buster_unstable",
ExtraAttr: []string{"informational"},
ExtraSoftwareDeps: []string{"dlc"},
ExtraHardwareDeps: crostini.CrostiniUnstable,
Fixture: "crostiniBuster",
Timeout: 7 * time.Minute,
}, {
Name: "bullseye_stable",
ExtraSoftwareDeps: []string{"dlc"},
ExtraHardwareDeps: crostini.CrostiniStable,
Fixture: "crostiniBullseye",
Timeout: 7 * time.Minute,
}, {
Name: "bullseye_unstable",
ExtraAttr: []string{"informational"},
ExtraSoftwareDeps: []string{"dlc"},
ExtraHardwareDeps: crostini.CrostiniUnstable,
Fixture: "crostiniBullseye",
Timeout: 7 * time.Minute,
},
},
})
}
func VmcExtraDisk(ctx context.Context, s *testing.State) {
hash, err := vmc.UserIDHash(ctx)
if err != nil {
s.Fatal("Failed to get CROS_USER_ID_HASH: ", err)
}
// Create a file in a temp directory in ChromeOS and push it to the container.
dir, err := ioutil.TempDir("", "tast.crostini.VmcExtraDisk")
if err != nil {
s.Fatal("Failed to create a temp directory: ", err)
}
defer os.RemoveAll(dir)
extraDisk := filepath.Join(dir, "extra.img")
// Run `vmc extra-disk-create`
if err := vmc.Command(ctx, hash, "create-extra-disk", "--size", "256M", extraDisk).
Run(testexec.DumpLogOnError); err != nil {
s.Fatal("Failed to create an extra disk image: ", err)
}
const vmName = "tast_extra_disk_vm"
// Run `vmc create $vmName`
if err := vmc.Command(ctx, hash, "create", vmName).Run(testexec.DumpLogOnError); err != nil {
s.Fatalf("Failed to create %s VM: %v", vmName, err)
}
defer func() {
if err := vmc.Command(ctx, hash, "destroy", "-y", vmName).Run(testexec.DumpLogOnError); err != nil {
s.Errorf("Failed to destroy %s VM: %v", vmName, err)
}
}()
// Run `vmc start $vmName --extra-disk $extraDisk`.
cmd := vmc.Command(ctx, hash, "start", vmName, "--extra-disk", extraDisk)
stdin, err := cmd.StdinPipe()
if err != nil {
s.Fatal("Failed to open stdin pipe: ", err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
s.Fatal("Failed to open stdout pipe: ", err)
}
if err := cmd.Start(); err != nil {
s.Fatalf("Failed to start %s VM with %s: %v", vmName, extraDisk, err)
}
// Write the content of testScript to the VM's stdin.
f, err := os.Open(s.DataPath(testScript))
if err != nil {
s.Fatalf("Failed to open %s: %v", testScript, err)
}
defer f.Close()
if _, err := io.Copy(stdin, f); err != nil {
s.Fatal("Failed to write a test script to stdin pipe: ", err)
}
// Close stdin explicitly to get outputs.
if err := stdin.Close(); err != nil {
s.Fatal("Failed to close stdin pipe: ", err)
}
buf := new(strings.Builder)
if _, err := io.Copy(buf, stdout); err != nil {
s.Fatal("Failed to get the VM output: ", err)
}
output := string(buf.String())
if err := cmd.Wait(testexec.DumpLogOnError); err != nil {
s.Fatal("Failed to wait for exiting from the VM shell: ", err)
}
// Check if the test script ran successfully.
// Use strings.Contains instead of "==", as output contains ANSI escape sequences.
if !strings.Contains(output, "TAST_OK") {
s.Error("Test script didn't run successfully: ", output)
}
// Run `vmc stop $vmName`
if err := vmc.Command(ctx, hash, "stop", vmName).Run(testexec.DumpLogOnError); err != nil {
s.Errorf("Failed to stop %s VM: %v", vmName, err)
}
}
|
// Copyright (C) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package binaryxml
import (
"bytes"
"fmt"
"io"
"github.com/google/gapid/core/data/binary"
"github.com/google/gapid/core/data/endian"
"github.com/google/gapid/core/os/device"
)
type xmlTree struct {
rootHolder
strings *stringPool
resourceMap *xmlResourceMap
chunks []chunk
}
func (c xmlTree) xml(ctx *xmlContext) string {
b := bytes.Buffer{}
for _, chunk := range c.chunks {
s := chunk.xml(ctx)
b.WriteString(s)
b.WriteRune('\n')
}
return b.String()
}
func (c *xmlTree) visit(visitor chunkVisitor) {
ctx := xmlContext{
strings: c.strings,
namespaces: map[string]string{},
tab: " ",
}
visitor(&ctx, c, beforeContextChange)
for _, chunk := range c.chunks {
visitor(&ctx, chunk, beforeContextChange)
ctxChange, ok := chunk.(contextChange)
if ok {
ctxChange.updateContext(&ctx)
visitor(&ctx, chunk, afterContextChange)
}
}
}
func (c *xmlTree) decode(header, data []byte) error {
r := endian.Reader(bytes.NewReader(data), device.LittleEndian)
var chunk chunk
var err error
var ok bool
if chunk, err = decodeChunk(r, c); err != nil {
return err
}
if c.strings, ok = chunk.(*stringPool); !ok {
return fmt.Errorf("Expected string pool chunk, got %T", chunk)
}
if chunk, err = decodeChunk(r, c); err != nil {
return err
}
if c.resourceMap, ok = chunk.(*xmlResourceMap); !ok {
return fmt.Errorf("Expected resource map chunk, got %T", chunk)
}
for {
chunk, err = decodeChunk(r, c)
switch err {
case nil:
case io.EOF:
return nil
default:
return err
}
c.chunks = append(c.chunks, chunk)
}
}
func (c *xmlTree) encode() []byte {
return encodeChunk(resXMLType, func(w binary.Writer) {
// No custom header.
}, func(w binary.Writer) {
w.Data(c.strings.encode())
w.Data(c.resourceMap.encode())
for _, chunk := range c.chunks {
w.Data(chunk.encode())
}
})
}
func (c *xmlTree) toXmlString() string {
return c.xml(&xmlContext{
strings: c.strings,
namespaces: map[string]string{},
tab: " ",
})
}
func (c *xmlTree) decodeString(r binary.Reader) stringPoolRef {
idx := r.Uint32()
if idx != missingString {
return stringPoolRef{c.strings, idx}
}
return stringPoolRef{nil, idx}
}
// ensureAttributeMapsToResource finds a name mapping to the given resource id.
// If such a name does not exist, it is added to the string pool after the last
// string associated with a resource id, shifting all the strings after it. The
// resource map is updated to associate this string's position in the pool with
// the given resource id.
func (xml *xmlTree) ensureAttributeNameMapsToResource(resourceId uint32, attrName string) stringPoolRef {
attrIdx, foundAttr := xml.resourceMap.indexOf(resourceId)
if foundAttr {
poolRef, found := xml.strings.findFromStringPoolIndex(attrIdx)
if found {
if poolRef.get() != attrName {
panic("Attribute found but name mismatch. Perhaps this is allowed?")
}
return poolRef
} else {
panic("Resource map or string pool broken.")
}
}
insertIndex := len(xml.resourceMap.ids)
xml.resourceMap.ids = append(xml.resourceMap.ids, resourceId)
return xml.strings.insertStringAtIndex(attrName, insertIndex)
}
|
package websupport
import (
"net/url"
"net/http"
"encoding/json"
"io"
"bytes"
"encoding/base64"
)
const (
DefaultEndpoint = "https://rest.websupport.sk"
mediaType = "application/json"
)
type Client struct {
BaseURL *url.URL
UserAgent string
httpClient *http.Client
headers map[string]string
Users UserService
DNS DNSService
}
func NewClient(username, password string, httpClient *http.Client) (*Client, error) {
if httpClient == nil {
httpClient = http.DefaultClient
}
c := &Client {httpClient: httpClient}
var err error
c.BaseURL, err = url.Parse(DefaultEndpoint)
if err != nil {
return nil, err
}
c.headers = map[string]string{
"Authorization": "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password)),
}
c.Users = &UserServiceImpl{client: c}
c.DNS = &DNSServiceImpl{client: c}
return c, nil
}
func (c *Client) newRequest(method, path string, body interface{}) (*http.Request, error) {
rel := &url.URL{Path: path}
u := c.BaseURL.ResolveReference(rel)
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", mediaType)
}
req.Header.Set("Accept", mediaType)
req.Header.Set("User-Agent", c.UserAgent)
for k, v := range c.headers {
req.Header.Add(k, v)
}
return req, nil
}
func (c *Client) do(req *http.Request, v interface{}) (*http.Response, error) {
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
//buf := new(bytes.Buffer)
//buf.ReadFrom(resp.Body)
//fmt.Println(req.URL.String())
//fmt.Println("ResponseBody: ")
//fmt.Println(buf.String())
err = json.NewDecoder(resp.Body).Decode(v)
return resp, err
} |
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build !windows
package storageutils
import (
"syscall"
)
func GetTotalSizeMb(path string) (int, error) {
var stat syscall.Statfs_t
err := syscall.Statfs(path, &stat)
if err != nil {
return -1, err
}
return int(stat.Blocks * uint64(stat.Bsize) / 1024 / 1024), nil
}
func GetFreeSizeMb(path string) (int, error) {
var stat syscall.Statfs_t
err := syscall.Statfs(path, &stat)
if err != nil {
return -1, err
}
return int(stat.Bavail * uint64(stat.Bsize) / 1024 / 1024), nil
}
func GetUsedSizeMb(path string) (int, error) {
var stat syscall.Statfs_t
err := syscall.Statfs(path, &stat)
if err != nil {
return -1, err
}
return int((stat.Blocks - stat.Bfree) * uint64(stat.Bsize) / 1024 / 1024), nil
}
|
package main
import "fmt"
// task 1
func avgScores(scores [5]float64) float64 {
total := 0.0
for _, score := range scores {
total += score
}
return total / 5
}
// task 2
var pets map[string]string = map[string]string{
"Fido": "Dog",
"Jutsu": "Cat",
}
func petNames(name string) bool {
if _, ok := pets[name]; ok {
return true
}
return false
}
// task 3
var initialGroceries = []string{"lemon", "flour", "fruit", "chicken"}
func groceries(newGroceries ...string) {
foods := initialGroceries
for _, grocery := range newGroceries {
foods = append(foods, grocery)
}
fmt.Println(foods)
}
func main() {
fmt.Println(avgScores([5]float64{4, 5, 6, 7, 8}))
fmt.Println(petNames("Fido"))
groceries("rice", "wheat")
}
|
package jago
import (
"fmt"
"math"
)
/*148 (0X94)*/
func LCMP(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
panic(fmt.Sprintf("Not implemented for opcode %d\n", opcode))
}
/*149 (0X95)*/
func FCMPL(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
value2 := f.pop().(Float)
value1 := f.pop().(Float)
if math.IsNaN(float64(value1)) || math.IsNaN(float64(value2)) {
f.push(Int(-1))
return
}
if value1 > value2 {
f.push(Int(1))
}
if value1 == value2 {
f.push(Int(0))
}
if value1 < value2 {
f.push(Int(-1))
}
}
/*150 (0X96)*/
func FCMPG(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
value2 := f.pop().(Float)
value1 := f.pop().(Float)
if math.IsNaN(float64(value1)) || math.IsNaN(float64(value2)) {
f.push(Int(1))
return
}
if value1 > value2 {
f.push(Int(1))
}
if value1 == value2 {
f.push(Int(0))
}
if value1 < value2 {
f.push(Int(-1))
}
}
/*151 (0X97)*/
func DCMPL(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
panic(fmt.Sprintf("Not implemented for opcode %d\n", opcode))
}
/*152 (0X98)*/
func DCMPG(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
panic(fmt.Sprintf("Not implemented for opcode %d\n", opcode))
}
/*153 (0X99)*/
func IFEQ(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value := f.pop().(Int)
if value == 0 {
f.pc += int(offset)
}
}
/*154 (0X9A)*/
func IFNE(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value := f.pop().(Int)
if value != 0 {
f.pc += int(offset)
}
}
/*155 (0X9B)*/
func IFLT(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value := f.pop().(Int)
if value < 0 {
f.pc += int(offset)
}
}
/*156 (0X9C)*/
func IFGE(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value := f.pop().(Int)
if value >= 0 {
f.pc += int(offset)
}
}
/*157 (0X9D)*/
func IFGT(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value := f.pop().(Int)
if value > 0 {
f.pc += int(offset)
}
}
/*158 (0X9E)*/
func IFLE(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value := f.pop().(Int)
if value <= 0 {
f.pc += int(offset)
}
}
/*159 (0X9F)*/
func IF_ICMPEQ(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value2 := f.pop().(Int)
value1 := f.pop().(Int)
if value1 == value2 {
f.pc += int(offset)
}
}
/*160 (0XA0)*/
func IF_ICMPNE(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value2 := f.pop().(Int)
value1 := f.pop().(Int)
if value1 != value2 {
f.pc += int(offset)
}
}
/*161 (0XA1)*/
func IF_ICMPLT(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value2 := f.pop().(Int)
value1 := f.pop().(Int)
if value1 < value2 {
f.pc += int(offset)
}
}
/*162 (0XA2)*/
func IF_ICMPGE(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value2 := f.pop().(Int)
value1 := f.pop().(Int)
if value1 >= value2 {
f.pc += int(offset)
}
}
/*163 (0XA3)*/
func IF_ICMPGT(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value2 := f.pop().(Int)
value1 := f.pop().(Int)
if value1 > value2 {
f.pc += int(offset)
}
}
/*164 (0XA4)*/
func IF_ICMPLE(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value2 := f.pop().(Int)
value1 := f.pop().(Int)
if value1 <= value2 {
f.pc += int(offset)
}
}
/*165 (0XA5)*/
func IF_ACMPEQ(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value2 := f.pop().(ObjectRef)
value1 := f.pop().(ObjectRef)
if value1 == value2 {
f.pc += int(offset)
}
}
/*166 (0XA6)*/
func IF_ACMPNE(opcode uint8, f *Frame, t *Thread, c *Class, m *Method) {
offset := f.offset16()
value2 := f.pop().(ObjectRef)
value1 := f.pop().(ObjectRef)
if value1 != value2 {
f.pc += int(offset)
}
}
|
package esbulk
import (
"bufio"
"compress/gzip"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// Options represents bulk indexing options.
type Options struct {
Servers []string
Index string
Purge bool
Mapping string
DocType string
NumWorkers int
ZeroReplica bool
GZipped bool
BatchSize int
Verbose bool
IDField string
Scheme string // http or https; deprecated, use: Servers.
Username string
Password string
MaxRetries int
}
const (
maxRetriesUntilIndexIsDeleted = 5
)
// CreateIndexFromLDJFile reads input file and creates an index given options using
// multiple workers
func CreateIndexFromLDJFile(r io.Reader, options Options) (int, error) {
count := 0
if options.Index == "" {
return count, errors.New("index name required")
}
if options.Verbose {
log.Println(options)
}
if options.Purge {
if err := DeleteIndex(options); err != nil {
return count, err
}
// Wait until index is deleted
if err := waitForIndexDeletion(options, 0); err != nil {
log.Fatalf("unable to check if index is deleted")
}
}
// Create index if not exists.
if err := CreateIndex(options); err != nil {
return count, err
}
if options.Mapping != "" {
var reader io.Reader
if _, err := os.Stat(options.Mapping); os.IsNotExist(err) {
reader = strings.NewReader(options.Mapping)
} else {
file, err := os.Open(options.Mapping)
if err != nil {
return count, err
}
reader = bufio.NewReader(file)
}
if err := PutMapping(options, reader); err != nil {
return count, err
}
}
queue := make(chan string)
var wg sync.WaitGroup
for i := 0; i < options.NumWorkers; i++ {
wg.Add(1)
go Worker(fmt.Sprintf("worker-%d", i), options, queue, &wg)
}
for i := range options.Servers {
// Store number_of_replicas settings for restoration later.
doc, err := GetSettings(i, options)
if err != nil {
return count, err
}
// TODO(miku): Rework this.
numberOfReplicas := doc[options.Index].(map[string]interface{})["settings"].(map[string]interface{})["index"].(map[string]interface{})["number_of_replicas"]
if options.Verbose {
log.Printf("on shutdown, number_of_replicas will be set back to %s", numberOfReplicas)
}
// Shutdown procedure. TODO(miku): Handle signals, too.
defer func() {
// Realtime search & reset number of replicas.
if _, err := updateIndexSettings(fmt.Sprintf(`{"index": {"refresh_interval": "1s", "number_of_replicas": %q}}`, numberOfReplicas), options); err != nil {
log.Fatal(err)
}
// Persist documents.
if FlushIndex(i, options) != nil {
log.Fatal(err)
}
}()
// Realtime search and reset number of replicas (if specified).
var indexRequest = `{"index": {"refresh_interval": "-1"}}`
if options.ZeroReplica {
indexRequest = `{"index": {"refresh_interval": "-1", "number_of_replicas": 0}}`
}
resp, err := updateIndexSettings(indexRequest, options)
if err != nil {
return count, err
}
if resp.StatusCode >= 400 {
log.Fatal(resp)
}
}
reader := bufio.NewReader(r)
if options.GZipped {
zreader, err := gzip.NewReader(r)
if err != nil {
return count, err
}
reader = bufio.NewReader(zreader)
}
for {
line, err := reader.ReadString('\n')
if err == io.EOF {
break
}
if err != nil {
return count, err
}
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
queue <- line
count++
}
close(queue)
wg.Wait()
return count, nil
}
// IndexOptionsFromFilepath parses filename to get index options for an index insertion
func IndexOptionsFromFilepath(path string, defaults Options) (Options, error) {
log.Printf("processing file %q...", path)
if _, err := os.Stat(path); os.IsNotExist(err) {
return Options{}, fmt.Errorf("failed to load %q as it does not exists", path)
}
tokens := strings.Split(filepath.Base(path), ".")
switch len(tokens) {
case 4:
defaults.DocType = tokens[0]
defaults.IDField = tokens[1]
defaults.Index = tokens[2]
return defaults, nil
case 3:
defaults.DocType = tokens[0]
defaults.Index = tokens[1]
return defaults, nil
default:
return Options{}, fmt.Errorf("failed to parse source LDJ file %q", path)
}
}
// updateIndexSettings updates the elasticsearch index settings
func updateIndexSettings(body string, options Options) (*http.Response, error) {
// Body consist of the JSON document, e.g. `{"index": {"refresh_interval": "1s"}}`.
server := PickServerURI(options.Servers)
link := fmt.Sprintf("%s/%s/_settings", server, options.Index)
req, err := MakeHTTPRequest(options, "PUT", link, strings.NewReader(body))
if err != nil {
return nil, err
}
client := MakeHTTPClient(options.MaxRetries)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if options.Verbose {
log.Printf("applied setting: %s with status %s\n", body, resp.Status)
}
return resp, nil
}
func waitForIndexDeletion(options Options, retry int) error {
if retry > maxRetriesUntilIndexIsDeleted {
return errors.New("unable to check if index is deleted")
}
exists, err := indexExists(options)
if err != nil {
return errors.New("unable to check if index is deleted")
}
if exists {
time.Sleep(5 * time.Second)
retry++
return waitForIndexDeletion(options, retry)
}
return nil
}
func indexExists(options Options) (bool, error) {
server := PickServerURI(options.Servers)
link := fmt.Sprintf("%s/%s", server, options.Index)
req, err := MakeHTTPRequest(options, "HEAD", link, nil)
if err != nil {
return false, err
}
client := MakeHTTPClient(options.MaxRetries)
resp, err := client.Do(req)
if err != nil {
return false, err
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
return true, nil
}
if resp.StatusCode == 404 {
return false, nil
}
return false, errors.New("unable to check if index exists")
}
|
package endpoint
import (
"context"
"encoding/json"
"math"
"github.com/go-kit/kit/endpoint"
"github.com/sapawarga/userpost-service/lib/constant"
"github.com/sapawarga/userpost-service/lib/convert"
"github.com/sapawarga/userpost-service/model"
"github.com/sapawarga/userpost-service/usecase"
)
func MakeGetListUserPost(ctx context.Context, usecase usecase.UsecaseI) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*GetListUserPostRequest)
// TODO: for get metadata from headers grpc needs to update when using authorization
resp, err := usecase.GetListPost(ctx, &model.GetListRequest{
ActivityName: req.ActivityName,
Username: req.Username,
Category: req.Category,
Status: req.Status,
Page: req.Page,
Limit: req.Limit,
SortBy: req.SortBy,
OrderBy: req.OrderBy,
Search: req.Search,
DistrictID: req.DistrictID,
})
if err != nil {
return nil, err
}
totalPage := math.Ceil(float64(resp.Metadata.Total) / float64(*req.Limit))
data := &UserPostWithMetadata{
Data: resp.Data,
Metadata: &Metadata{
PerPage: convert.GetInt64FromPointer(req.Limit),
TotalPage: totalPage,
Total: resp.Metadata.Total,
CurrentPage: convert.GetInt64FromPointer(req.Page),
},
}
return map[string]interface{}{
"data": data,
}, nil
}
}
func MakeGetDetailUserPost(ctx context.Context, usecase usecase.UsecaseI) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*GetByID)
// TODO: for get metadata from headers grpc needs to update when using authorization
resp, err := usecase.GetDetailPost(ctx, req.ID)
if err != nil {
return nil, err
}
return map[string]interface{}{
"data": resp}, nil
}
}
func MakeGetListUserPostByMe(ctx context.Context, usecase usecase.UsecaseI) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*GetListUserPostRequest)
// TODO: for get metadata from headers grpc needs to update when using authorization
resp, err := usecase.GetListPostByMe(ctx, &model.GetListRequest{
ActivityName: req.ActivityName,
Username: req.Username,
Category: req.Category,
Status: req.Status,
Page: req.Page,
Limit: req.Limit,
SortBy: req.SortBy,
OrderBy: req.OrderBy,
Search: req.Search,
DistrictID: req.DistrictID,
})
if err != nil {
return nil, err
}
totalPage := math.Ceil(float64(resp.Metadata.Total) / float64(*req.Limit))
data := &UserPostWithMetadata{
Data: resp.Data,
Metadata: &Metadata{
PerPage: convert.GetInt64FromPointer(req.Limit),
TotalPage: totalPage,
Total: resp.Metadata.Total,
CurrentPage: convert.GetInt64FromPointer(req.Page),
},
}
return map[string]interface{}{
"data": data}, nil
}
}
func MakeCreateNewPost(ctx context.Context, usecase usecase.UsecaseI) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*CreateNewPostRequest)
if err := Validate(req); err != nil {
return nil, err
}
imagePathURL := req.Images[0]
imagesFormatted, err := json.Marshal(req.Images)
if err != nil {
return nil, err
}
bodyRequest := &model.CreateNewPostRequest{
Title: convert.GetStringFromPointer(req.Title),
ImagePathURL: imagePathURL.Path,
Images: string(imagesFormatted),
Tags: req.Tags,
Status: convert.GetInt64FromPointer(req.Status),
}
if err = usecase.CreateNewPost(ctx, bodyRequest); err != nil {
return nil, err
}
return &StatusResponse{
Code: constant.STATUS_CREATED,
Message: "a_post_has_been_created",
}, nil
}
}
func MakeUpdateStatusOrTitle(ctx context.Context, usecase usecase.UsecaseI) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*CreateCommentRequest)
if err := Validate(req); err != nil {
return nil, err
}
if err = usecase.UpdateTitleOrStatus(ctx, &model.UpdatePostRequest{
ID: req.UserPostID,
Status: req.Status,
Title: convert.SetPointerString(req.Text),
}); err != nil {
return nil, err
}
return &StatusResponse{
Code: constant.STATUS_UPDATED,
Message: "post_has_been_updated",
}, nil
}
}
func MakeGetCommentsByID(ctx context.Context, usecase usecase.UsecaseI) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*GetByID)
resp, err := usecase.GetCommentsByPostID(ctx, &model.GetCommentRequest{
ID: req.ID,
})
if err != nil {
return nil, err
}
data := &CommentsResponse{
Data: resp.Data,
Metadata: &Metadata{
PerPage: constant.DEFAULT_LIMIT,
Total: resp.Metadata.Total,
TotalPage: math.Ceil(float64(resp.Metadata.Total) / float64(20)),
CurrentPage: resp.Metadata.Page,
},
}
return map[string]interface{}{
"data": data}, nil
}
}
func MakeCreateComment(ctx context.Context, usecase usecase.UsecaseI) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*CreateCommentRequest)
if err := Validate(req); err != nil {
return nil, err
}
if err = usecase.CreateCommentOnPost(ctx, &model.CreateCommentRequest{
UserPostID: req.UserPostID,
Text: req.Text,
Status: convert.GetInt64FromPointer(req.Status),
}); err != nil {
return nil, err
}
return &StatusResponse{
Code: constant.STATUS_CREATED,
Message: "success_post_comment",
}, nil
}
}
func MakeLikeOrDislikePost(ctx context.Context, usecase usecase.UsecaseI) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*GetByID)
// TODO: for get metadata from headers grpc needs to update when using authorization
if err = usecase.LikeOrDislikePost(ctx, req.ID); err != nil {
return nil, err
}
return &StatusResponse{
Code: constant.STATUS_UPDATED,
Message: "success_like_or_dislike_a_post",
}, nil
}
}
func MakeCheckHealthy(ctx context.Context) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
return &StatusResponse{
Code: constant.STATUS_OK,
Message: "service_is_ok",
}, nil
}
}
func MakeCheckReadiness(ctx context.Context, usecase usecase.UsecaseI) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
if err := usecase.CheckHealthReadiness(ctx); err != nil {
return nil, err
}
return &StatusResponse{
Code: constant.STATUS_OK,
Message: "service_is_ready",
}, nil
}
}
|
package main
import (
"fmt"
)
const (
LAST_ELEMENT = 1<<16 // insert to the end of list
FIRST_ELEMENT = 0 // insert to the beginning
)
type list struct {
value string
next *list // next node
prev *list // previous node
first *list // head of the list
last *list // tail of the list
}
func (l *list) String() string {
l = l.first
s := fmt.Sprintf ("%s - ", l.value)
l = l.next
for i := 0; l.last != l; i++{
s += fmt.Sprintf("%s - ", l.value)
l = l.next
}
l = l.last
s += fmt.Sprintf ("%s", l.value)
return s
}
// insert adds the element e at index i in the list l
// first element is found from index=0
func (l *list) insert(i int, e string) {
l = l.first // jump to the beginning
for j := 0; j < i; j++ {
l = l.next
if l == l.last {
l = l.prev
break // reached the end of list
}
}
next := l.next
prev := l
node := &list{e, next, prev, l.first, l.last}
next.prev = node // append a new node
prev.next = node
}
// delete removes the element at index i in the list l
func (l *list) delete(i int) {
l = l.first.next // jump to the fisrt element
for j := 0; j < i; j++ {
l = l.next
if l == l.last {
l = l.prev
break // reached the end of list
}
}
// drop selected node index from the list
// and adjust pointers
next := l.next
prev := l.prev
prev.next = next
next.prev = prev
}
func createLinkedList() *list {
// init sentinel nodes (first and last node)
first := &list{"BEGIN", nil, nil, nil, nil} // start of the list
last := &list{"END", nil, nil, nil, nil} // end of the list
first.prev = first // init first node
first.next = last
first.first = first // pointer to the first node
first.last = last // pointer to the last node
last.prev = first // init end node
last.next = last
last.first = first
last.last = last
return first
}
func main() {
fmt.Printf("Doubly linked list\n")
l := createLinkedList()
l.insert(0, "element1")
fmt.Printf ("1 %v\n", l)
l.delete(0)
fmt.Printf ("1 %v\n", l)
l.insert(1, "element2")
fmt.Printf ("2 %v\n", l)
l.insert(2, "element3")
fmt.Printf ("3 %v\n", l)
l.insert(3, "element4")
fmt.Printf ("4 %v\n", l)
l.insert(4, "element5")
fmt.Printf ("5 %v\n", l)
l.insert(2, "middle1")
fmt.Printf ("6 %v\n", l)
l.insert(4, "middle2")
fmt.Printf ("7 %v\n", l)
l.insert(LAST_ELEMENT, "last item 1")
l.insert(LAST_ELEMENT, "last item 2")
l.insert(FIRST_ELEMENT, "first item 1")
l.insert(FIRST_ELEMENT, "first item 2")
fmt.Printf ("%v\n", l)
l.delete(FIRST_ELEMENT)
fmt.Printf ("D1 %v\n", l)
l.delete(2)
fmt.Printf ("D2 %v\n", l)
l.delete(LAST_ELEMENT)
fmt.Printf ("D3 %v\n", l)
}
|
package processor
import (
"change.com/auth/domain"
"context"
)
/**
* 用户认证处理器
*/
type CommonProcessor interface {
Authenticate(request *domain.UnifyAuthRequest, ctx context.Context) domain.UnifyAuthResponse
}
|
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"ocr.service.worker/config"
"ocr.service.worker/model"
"ocr.service.worker/module"
"os"
"time"
)
type Worker struct {
client *http.Client
rabbitmq *module.RabbitMQ
imageSuccessQueue string
imageErrorQueue string
imageTaskQueue string
aiUrl string
}
func (q *Worker) CallAICore(image model.Image) ([]byte, error) {
strImage, _ := json.Marshal(model.Image{Path: image.Path})
req, err := http.NewRequest(http.MethodPost, q.aiUrl, bytes.NewReader(strImage))
if err != nil {
return nil, err
}
res, err := q.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
fmt.Println(string(body))
return body, nil
}
func (q *Worker) HandleTask(message []byte, messageAction *module.MessageAction) {
var image model.Image
err := json.Unmarshal(message, &image)
if err != nil {
fmt.Println(err)
messageAction.Ack()
return
}
fmt.Println("[RECEIVE]: ", image)
time.Sleep(3 * time.Second)
data, err := q.CallAICore(image)
if err != nil {
image.Status = "error"
image.Error = err.Error()
imageResponse, _ := json.Marshal(image)
fmt.Println("[SEND] error: ", string(imageResponse))
err = q.rabbitmq.SendMessage(q.imageErrorQueue, imageResponse, 0)
} else {
image.Status = "done"
image.Data = string(data)
imageResponse, _ := json.Marshal(image)
fmt.Println("[SEND] success: ", imageResponse)
err = q.rabbitmq.SendMessage(q.imageSuccessQueue, imageResponse, 0)
}
if err != nil {
messageAction.Reject()
} else {
messageAction.Ack()
}
}
func NewWorker() (*Worker, error) {
CONFIG, _ := config.NewConfig(nil)
var q Worker
var err error
q.imageTaskQueue = CONFIG.GetString("IMAGE_TASK_QUEUE")
q.imageSuccessQueue = CONFIG.GetString("IMAGE_SUCCESS_QUEUE")
q.imageErrorQueue = CONFIG.GetString("IMAGE_ERROR_QUEUE")
q.aiUrl = CONFIG.GetString("AI_URL")
q.client = module.CreateClient()
rabbitmqLogin := module.RabbitMQLogin{
Host: CONFIG.GetString("RABBITMQ_HOST"),
Port: CONFIG.GetString("RABBITMQ_PORT"),
Username: CONFIG.GetString("RABBITMQ_USERNAME"),
Password: CONFIG.GetString("RABBITMQ_PASSWORD"),
VHOST: CONFIG.GetString("RABBITMQ_VHOST"),
}
q.rabbitmq, err = module.NewRabbitMQ(rabbitmqLogin)
if err != nil {
return nil, err
}
err = q.rabbitmq.CreateQueue(q.imageTaskQueue, 10)
if err != nil {
return nil, err
}
err = q.rabbitmq.CreateQueue(q.imageSuccessQueue, 0)
if err != nil {
return nil, err
}
err = q.rabbitmq.CreateQueue(q.imageErrorQueue, 0)
if err != nil {
return nil, err
}
var consumeTaskImage = module.Consume{
q.imageTaskQueue,
"",
false,
false,
false,
false,
1,
}
q.rabbitmq.Consume(consumeTaskImage, q.HandleTask)
return &q, err
}
func main() {
forever := make(chan bool)
fmt.Println("service start")
_, err := NewWorker()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
<-forever
}
|
package main
import (
"encoding/json"
"fmt"
"github.com/google/uuid"
"github.com/micro/go-micro/v2"
"strconv"
"github.com/micro/go-micro/v2/broker"
"github.com/micro/go-plugins/broker/rabbitmq/v2"
"go-micro-demos/broker/rabbitmq/config"
proto "go-micro-demos/broker/rabbitmq/proto"
"time"
)
var (
conf = config.Config()
topic = conf.Topics["rabbitmq"].Name
amqp = conf.Rabbitmq.Amqp
serviceName = conf.Services["rabbitmq"].Name
)
func main() {
fmt.Println("topic: ", topic, ", serviceName: ", serviceName)
// new service
service := micro.NewService(
micro.Name(serviceName),
micro.Version("latest"),
micro.Broker(
rabbitmq.NewBroker(broker.Addrs(amqp)),
),
)
service.Init()
brk := service.Server().Options().Broker
if err := brk.Connect();err != nil {
fmt.Printf("[pub]failed to connect broker: %v", err)
return
}
go publisher(topic, brk)
<-time.After(time.Second * 20)
}
// 发送消息
func publisher(topic string, brk broker.Broker) {
t := time.NewTicker(time.Second)
var i = 0
for _ = range t.C {
protoMsg := &proto.Message{
Id : uuid.New().String(),
Message: fmt.Sprintf("topic: %s, %d:%s", topic, i, time.Now().String()),
}
msgBody, err := json.Marshal(protoMsg)
if err != nil {
fmt.Println(err)
}
msg := &broker.Message{
Header: map[string]string{
"id": strconv.Itoa(uuid.ClockSequence()),
},
Body: msgBody,
}
fmt.Println(string(msgBody))
if err := brk.Publish(topic, msg); err != nil {
fmt.Printf("publish error: %v", err)
}
i++
}
//defer brk.Disconnect()
}
|
package execshim
import (
"io"
"os/exec"
"syscall"
)
//go:generate counterfeiter -o exec_fake/fake_cmd.go . Cmd
type Cmd interface {
Start() error
StdoutPipe() (io.ReadCloser, error)
StderrPipe() (io.ReadCloser, error)
Wait() error
Run() error
CombinedOutput() ([]byte, error)
SysProcAttr() *syscall.SysProcAttr
}
type cmd struct {
*exec.Cmd
}
func (c *cmd) Start() error {
return c.Cmd.Start()
}
func (c *cmd) StdoutPipe() (io.ReadCloser, error) {
return c.Cmd.StdoutPipe()
}
func (c *cmd) StderrPipe() (io.ReadCloser, error) {
return c.Cmd.StderrPipe()
}
func (c *cmd) Wait() error {
return c.Wait()
}
func (c *cmd) Run() error {
return c.Run()
}
func (c *cmd) CombinedOutput() ([]byte, error) {
return c.Cmd.CombinedOutput()
}
func (c *cmd) SysProcAttr() *syscall.SysProcAttr {
return c.Cmd.SysProcAttr
}
|
package main
import (
"fmt"
"github.com/mattbaird/gosaml"
)
func main() {
// Configure the app and account settings
appSettings := saml.NewAppSettings("http://www.onelogin.net", "issuer")
accountSettings := saml.NewAccountSettings("cert", "http://www.onelogin.net")
// Construct an AuthnRequest
authRequest := saml.NewAuthorizationRequest(*appSettings, *accountSettings)
// Return a SAML AuthnRequest as a string
saml, err := authRequest.GetRequest(false)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(saml)
}
|
package leetcode
// 3,2,2,3 val = 3
// 倒叙遍历 k初始化指向最后一个元素下标
// 第一次 nums[l] = 3 val 3 相等. 把 nums[l] 放在第k位置上面.此时应该把nums[k] 位置的元素放在第l位置上面
// 第二次 nums[l] = 2 val 3 不相等. 跳过
// 第三次 nums[l] = 2 val 3 不相等. 跳过
// 第四次 nums[l] = 3 val 3 相等. 把 nums[l](3) 放在第k(3-1)位置上面.此时应该把nums[k](2) 位置的元素放在第l(0)位置上面
func removeElement(nums []int, val int) int {
l := len(nums) - 1
k := l
for l >= 0 {
if nums[l] == val {
// 交换k和l对应元素的顺序.这样相等的元素都排在最后面
nums[k], nums[l] = val, nums[k]
k--
}
l--
}
return k + 1
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.