text
stringlengths
11
4.05M
package database import ( sugar "../sugar" "github.com/jinzhu/gorm" "github.com/spf13/viper" _ "github.com/jinzhu/gorm/dialects/mysql" // sd ) // MySQLDB golbal instance var MySQLDB *gorm.DB // Start open db func Start() { host := viper.GetString("mysql.host") port := viper.GetString("mysql.port") username := viper.GetString("mysql.username") password := viper.GetString("mysql.password") database := viper.GetString("mysql.db") link := username + ":" + password + "@tcp(" + host + ":" + port + ")/" + database + "?charset=utf8&parseTime=True&loc=Local" db, err := gorm.Open("mysql", link) MySQLDB = db if err != nil { sugar.Error(err) } // defer db.Close() db.LogMode(true) db.SetLogger(sugar.GetGormLogger()) } // GetSession for func GetSession() *gorm.DB { return MySQLDB }
// Copyright 2019 PingCAP, 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. // Test backup with key locked errors. // // This file is copied from pingcap/schrodinger-test#428 https://git.io/Je1md package main import ( "bytes" "context" "encoding/json" "flag" "fmt" "io" "math/rand" "net" "net/http" "strconv" "time" "github.com/pingcap/errors" "github.com/pingcap/kvproto/pkg/kvrpcpb" "github.com/pingcap/log" "github.com/pingcap/tidb/br/pkg/httputil" "github.com/pingcap/tidb/br/pkg/task" "github.com/pingcap/tidb/config" "github.com/pingcap/tidb/kv" "github.com/pingcap/tidb/parser/model" "github.com/pingcap/tidb/store/driver" "github.com/pingcap/tidb/tablecodec" "github.com/tikv/client-go/v2/oracle" "github.com/tikv/client-go/v2/tikv" "github.com/tikv/client-go/v2/tikvrpc" pd "github.com/tikv/pd/client" "go.uber.org/zap" ) var ( ca = flag.String("ca", "", "CA certificate path for TLS connection") cert = flag.String("cert", "", "certificate path for TLS connection") key = flag.String("key", "", "private key path for TLS connection") tidbStatusAddr = flag.String("tidb", "", "TiDB status address") pdAddr = flag.String("pd", "", "PD address") dbName = flag.String("db", "", "Database name") tableName = flag.String("table", "", "Table name") tableSize = flag.Int64("table-size", 10000, "Table size, row count") timeout = flag.Duration("run-timeout", time.Second*10, "The total time it executes") lockTTL = flag.Duration("lock-ttl", time.Second*10, "The TTL of locks") ) func main() { flag.Parse() if *tidbStatusAddr == "" { log.Panic("tidb status address is empty") } if *pdAddr == "" { log.Panic("pd address is empty") } if *dbName == "" { log.Panic("database name is empty") } if *tableName == "" { log.Panic("table name is empty") } ctx, cancel := context.WithTimeout(context.Background(), *timeout) defer cancel() http.DefaultClient.Timeout = *timeout tableID, err := getTableID(ctx, *tidbStatusAddr, *dbName, *tableName) if err != nil { log.Panic("get table id failed", zap.Error(err)) } pdclient, err := pd.NewClient([]string{*pdAddr}, pd.SecurityOption{ CAPath: *ca, CertPath: *cert, KeyPath: *key, }) if err != nil { log.Panic("create pd client failed", zap.Error(err)) } pdcli := &codecPDClient{Client: pdclient} if len(*ca) != 0 { tidbCfg := config.NewConfig() tidbCfg.Security.ClusterSSLCA = *ca tidbCfg.Security.ClusterSSLCert = *cert tidbCfg.Security.ClusterSSLKey = *key config.StoreGlobalConfig(tidbCfg) } driver := driver.TiKVDriver{} store, err := driver.Open(fmt.Sprintf("tikv://%s?disableGC=true", *pdAddr)) if err != nil { log.Panic("create tikv client failed", zap.Error(err)) } locker := Locker{ tableID: tableID, tableSize: *tableSize, lockTTL: *lockTTL, pdcli: pdcli, kv: store.(tikv.Storage), } err = locker.generateLocks(ctx) if err != nil { log.Panic("generate locks failed", zap.Error(err)) } } func newHTTPClient() *http.Client { if len(*ca) != 0 { tlsCfg := &task.TLSConfig{ CA: *ca, Cert: *cert, Key: *key, } cfg, err := tlsCfg.ToTLSConfig() if err != nil { log.Panic("fail to parse TLS config", zap.Error(err)) } return httputil.NewClient(cfg) } return http.DefaultClient } // getTableID of the table with specified table name. func getTableID(ctx context.Context, dbAddr, dbName, table string) (int64, error) { dbHost, _, err := net.SplitHostPort(dbAddr) if err != nil { return 0, errors.Trace(err) } dbStatusAddr := net.JoinHostPort(dbHost, "10080") url := fmt.Sprintf("https://%s/schema/%s/%s", dbStatusAddr, dbName, table) client := newHTTPClient() req, err := http.NewRequestWithContext(ctx, "GET", url, nil) if err != nil { return 0, errors.Trace(err) } resp, err := client.Do(req) if err != nil { return 0, errors.Trace(err) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return 0, errors.Trace(err) } if resp.StatusCode != 200 { return 0, errors.Errorf("HTTP request to TiDB status reporter returns %v. Body: %v", resp.StatusCode, string(body)) } var data model.TableInfo err = json.Unmarshal(body, &data) if err != nil { return 0, errors.Trace(err) } return data.ID, nil } // Locker leaves locks on a table. type Locker struct { tableID int64 tableSize int64 lockTTL time.Duration pdcli pd.Client kv tikv.Storage } // generateLocks sends Prewrite requests to TiKV to generate locks, without committing and rolling back. // //nolint:gosec func (c *Locker) generateLocks(pctx context.Context) error { log.Info("genLock started") const maxTxnSize = 1000 // How many keys should be in the next transaction. nextTxnSize := rand.Intn(maxTxnSize) + 1 // 0 is not allowed. // How many keys has been scanned since last time sending request. scannedKeys := 0 var batch []int64 ctx, cancel := context.WithCancel(context.Background()) defer cancel() for rowID := int64(0); ; rowID = (rowID + 1) % c.tableSize { select { case <-pctx.Done(): log.Info("genLock done") return nil default: } scannedKeys++ // Randomly decide whether to lock current key. lockThis := rand.Intn(2) == 0 if lockThis { batch = append(batch, rowID) if len(batch) >= nextTxnSize { // The batch is large enough to start the transaction err := c.lockKeys(ctx, batch) if err != nil { return errors.Annotate(err, "lock keys failed") } // Start the next loop batch = batch[:0] scannedKeys = 0 nextTxnSize = rand.Intn(maxTxnSize) + 1 } } } } func (c *Locker) lockKeys(ctx context.Context, rowIDs []int64) error { keys := make([][]byte, 0, len(rowIDs)) keyPrefix := tablecodec.GenTableRecordPrefix(c.tableID) for _, rowID := range rowIDs { key := tablecodec.EncodeRecordKey(keyPrefix, kv.IntHandle(rowID)) keys = append(keys, key) } primary := keys[0] for len(keys) > 0 { lockedKeys, err := c.lockBatch(ctx, keys, primary) if err != nil { return errors.Trace(err) } keys = keys[lockedKeys:] } return nil } func (c *Locker) lockBatch(ctx context.Context, keys [][]byte, primary []byte) (int, error) { const maxBatchSize = 16 * 1024 // TiKV client doesn't expose Prewrite interface directly. We need to manually locate the region and send the // Prewrite requests. bo := tikv.NewBackoffer(ctx, 20000) for { loc, err := c.kv.GetRegionCache().LocateKey(bo, keys[0]) if err != nil { return 0, errors.Trace(err) } // Get a timestamp to use as the startTs physical, logical, err := c.pdcli.GetTS(ctx) if err != nil { return 0, errors.Trace(err) } startTS := oracle.ComposeTS(physical, logical) // Pick a batch of keys and make up the mutations var mutations []*kvrpcpb.Mutation batchSize := 0 for _, key := range keys { if len(loc.EndKey) > 0 && bytes.Compare(key, loc.EndKey) >= 0 { break } if bytes.Compare(key, loc.StartKey) < 0 { break } value := randStr() mutations = append(mutations, &kvrpcpb.Mutation{ Op: kvrpcpb.Op_Put, Key: key, Value: []byte(value), }) batchSize += len(key) + len(value) if batchSize >= maxBatchSize { break } } lockedKeys := len(mutations) if lockedKeys == 0 { return 0, nil } prewrite := &kvrpcpb.PrewriteRequest{ Mutations: mutations, PrimaryLock: primary, StartVersion: startTS, LockTtl: uint64(c.lockTTL.Milliseconds()), } req := tikvrpc.NewRequest(tikvrpc.CmdPrewrite, prewrite) // Send the requests resp, err := c.kv.SendReq(bo, req, loc.Region, time.Second*20) if err != nil { return 0, errors.Annotatef( err, "send request failed. region: %+v [%+q, %+q), keys: %+q", loc.Region, loc.StartKey, loc.EndKey, keys[0:lockedKeys]) } regionErr, err := resp.GetRegionError() if err != nil { return 0, errors.Trace(err) } if regionErr != nil { err = bo.Backoff(tikv.BoRegionMiss(), errors.New(regionErr.String())) if err != nil { return 0, errors.Trace(err) } continue } prewriteResp := resp.Resp if prewriteResp == nil { return 0, errors.Errorf("response body missing") } // Ignore key errors since we never commit the transaction and we don't need to keep consistency here. return lockedKeys, nil } } //nolint:gosec func randStr() string { length := rand.Intn(128) res := "" for i := 0; i < length; i++ { res += strconv.Itoa(rand.Intn(10)) } return res }
package kafka import ( "context" "github.com/Mario-Jimenez/pricescraper/subscriber" "github.com/juju/errors" "github.com/segmentio/kafka-go" ) // Consumer receives messages from the broker type Consumer struct { consumer *kafka.Reader } // NewConsumer creates a consumer that receives messages from kafka func NewConsumer(topic, groupID string, brokers []string) *Consumer { newConsumer := kafka.NewReader(kafka.ReaderConfig{ Brokers: brokers, GroupID: groupID, Topic: topic, QueueCapacity: 1, StartOffset: kafka.FirstOffset, }) return &Consumer{ consumer: newConsumer, } } // Fetch message from the broker func (c *Consumer) Fetch(ctx context.Context) (*subscriber.Message, error) { m, err := c.consumer.FetchMessage(ctx) if err != nil { return nil, errors.New(err.Error()) } return &subscriber.Message{ Message: m.Value, Topic: m.Topic, Partition: m.Partition, Offset: m.Offset, }, nil } // Commit message to the broker // if you use fetch, you have to commit the message's offset to the broker when finished func (c *Consumer) Commit(ctx context.Context, message *subscriber.Message) error { m := kafka.Message{ Topic: message.Topic, Partition: message.Partition, Offset: message.Offset, } return c.consumer.CommitMessages(ctx, m) } // Close consumer func (c *Consumer) Close() error { return c.consumer.Close() }
package rest import ( "fmt" "net/http" "github.com/gorilla/mux" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/irisnet/irismod/modules/nft/types" ) func registerTxRoutes(cliCtx client.Context, r *mux.Router, queryRoute string) { // Mint an NFT r.HandleFunc("/nft/nfts/denoms/issue", issueDenomHandlerFn(cliCtx)).Methods("POST") // Mint an NFT r.HandleFunc("/nft/nfts/mint", mintNFTHandlerFn(cliCtx)).Methods("POST") // Update an NFT tokenData r.HandleFunc(fmt.Sprintf("/nft/nfts/{%s}/{%s}", RestParamDenom, RestParamTokenID), editNFTHandlerFn(cliCtx)).Methods("PUT") // Transfer an NFT to an address r.HandleFunc(fmt.Sprintf("/nft/nfts/{%s}/{%s}/transfer", RestParamDenom, RestParamTokenID), transferNFTHandlerFn(cliCtx)).Methods("POST") // Burn an NFT r.HandleFunc(fmt.Sprintf("/nft/nfts/{%s}/{%s}/burn", RestParamDenom, RestParamTokenID), burnNFTHandlerFn(cliCtx)).Methods("POST") } func issueDenomHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req issueDenomReq if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") return } baseReq := req.BaseReq.Sanitize() if !baseReq.ValidateBasic(w) { return } // create the message msg := types.NewMsgIssueDenom(req.ID, req.Name, req.Schema, req.Owner) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) } } func mintNFTHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req mintNFTReq if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") return } baseReq := req.BaseReq.Sanitize() if !baseReq.ValidateBasic(w) { return } if req.Recipient.Empty() { req.Recipient = req.Owner } // create the message msg := types.NewMsgMintNFT( req.ID, req.Denom, req.Name, req.URI, req.Data, req.Owner, req.Recipient, ) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) } } func editNFTHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req editNFTReq if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") return } baseReq := req.BaseReq.Sanitize() if !baseReq.ValidateBasic(w) { return } vars := mux.Vars(r) // create the message msg := types.NewMsgEditNFT( vars[RestParamTokenID], vars[RestParamDenom], req.Name, req.URI, req.Data, req.Owner, ) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) } } func transferNFTHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req transferNFTReq if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") return } baseReq := req.BaseReq.Sanitize() if !baseReq.ValidateBasic(w) { return } recipient, err := sdk.AccAddressFromBech32(req.Recipient) if err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } vars := mux.Vars(r) // create the message msg := types.NewMsgTransferNFT( vars[RestParamTokenID], vars[RestParamDenom], req.Name, req.URI, req.Data, req.Owner, recipient, ) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) } } func burnNFTHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req burnNFTReq if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { rest.WriteErrorResponse(w, http.StatusBadRequest, "failed to parse request") return } baseReq := req.BaseReq.Sanitize() if !baseReq.ValidateBasic(w) { return } vars := mux.Vars(r) // create the message msg := types.NewMsgBurnNFT( req.Owner, vars[RestParamTokenID], vars[RestParamDenom], ) if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return } tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) } }
package main import ( "fmt" ) // 46. 全排列 // 给定一个 没有重复 数字的序列,返回其所有可能的全排列。 // https://leetcode-cn.com/problems/permutations/ func main() { nums := []int{4, 5, 2, 6} fmt.Println(permute(nums)) } func permute(nums []int) (result [][]int) { n := len(nums) used := make([]bool, n) cur := make([]int, n) permuteHelper(nums, n, used, cur, 0, &result) return result } // index代表本次函数中cur需要填充的位置 func permuteHelper(nums []int, n int, used []bool, cur []int, index int, result *[][]int) { // 结束本次排列 if index == n { tmp := make([]int, index) copy(tmp, cur) *result = append(*result, tmp) return } for i := 0; i < n; i++ { // 排除已经使用的元素 if !used[i] { // 添加一个元素 cur[index] = nums[i] used[i] = true // 进入下一层 permuteHelper(nums, n, used, cur, index+1, result) // 撤销选择 used[i] = false } } }
package utils const( ID_NO_FOUND = "未找到id" ID_ERROR = "id异常" PARSE_USERNAME_PASSWORD_ERROR = "解析用户名密码失败" USER_NOT_LOGIN = "用户未登录" USER_NOT_EXIST = "用户不存在" USER_EXISTS = "用户已存在" TWO_PASSWORD_NOT_MATCH = "两次密码不一致" USERNAME_PASSWORD_ERROR = "用户名密码不正确" REGISTER_FAILED = "注册失败" PARSE_BLOG_DATA_ERROR = "解析博文数据失败" PARSE_CATEGORY_DATA_ERROR = "解析分类数据失败" GET_BLOG_DATA_ERROR = "获取博文数据失败" GET_CATEGORY_DATA_ERROR = "获取分类数据失败" CREATE_BLOG_ERROR = "创建博文失败" CREATE_CATEGORY_ERROR = "创建分类失败" DELETE_BLOG_ERROR = "删除博文失败" DELETE_CATEGORY_ERROR = "删除分类失败" UPDATE_BLOG_ERROR = "更新博文失败" UPDATE_CATEGORY_ERROR = "更新分类失败" SEARCH_BLOG_ERROR = "搜索博文失败" SEARCH_CONTENT_BLANK_ERROR = "搜索内容为空" SEARCH_ERROR = "搜索失败" )
package main import ( "github.com/gin-gonic/gin" "bcdb/api" "bcdb/config" "bcdb/db" "sync" ) func preInit() { config.LoadConfig() } func apiServer(db *db.Db) { r := gin.New() r.Use(gin.Recovery()) r.Use(func(c *gin.Context) { c.Set("db", db) c.Next() }) r.GET("/" , func(c *gin.Context) { c.String(200,"hello") }) r.GET("/:key", api.Store.Get) r.POST("/:key", api.Store.Set) r.DELETE("/:key", api.Store.Delete) r.Run() } func main() { preInit() db := db.NewDb(config.Db.DataDir) db.Init() wg := sync.WaitGroup{} wg.Add(1) go func() { apiServer(db) wg.Done() }() wg.Wait() }
package model import ( "github.com/jinzhu/gorm" ) // DB 是gorm这个包里一个连接数据库的指针,我们可以通过这个指针来对数据库进行操作 var DB *gorm.DB // Init 初始化admin:123456 func Init(connString string) error { // connString是一个字符串,他保存着连接数据所需要的信息 db, err := gorm.Open("mysql", connString) // db 就是这个函数返回的一个连接mysql的一个实例 if err != nil { panic(err) } DB = db DB.Set("gorm:table_options", "charset=utf8mb4").AutoMigrate(&User{}) // 创建用户 DB.Create(&User{ Username: "admin", Password: "123456", }) return nil }
package solver import ( "context" "fmt" "io" "os" "sync" "time" "github.com/containerd/console" "github.com/docker/buildx/util/progress" "github.com/moby/buildkit/client" "github.com/moby/buildkit/identity" digest "github.com/opencontainers/go-digest" "github.com/pkg/errors" "golang.org/x/sync/errgroup" ) // Console is intended to match the `File` interface from // package `github.com/containerd/console`. type Console interface { io.ReadWriteCloser // Fd returns its file descriptor Fd() uintptr // Name returns its file name Name() string } type ProgressOption func(*ProgressInfo) error type ProgressInfo struct { Console Console LogOutput LogOutput } type LogOutput int const ( LogOutputTTY LogOutput = iota LogOutputPlain ) func WithLogOutput(con Console, logOutput LogOutput) ProgressOption { return func(info *ProgressInfo) error { info.Console = con info.LogOutput = logOutput return nil } } type Progress interface { MultiWriter() *MultiWriter Write(pfx, name string, fn func(ctx context.Context) error) Release() Wait() error // Sync will ensure that all progress has been written. Sync() error } // NewProgress returns a Progress that presents all the progress on multiple // solves to the terminal stdout. // // Calling (*Progress).WithPrefix creates a progress writer for a callback // function, giving each solve its independent progress writer (which is // eventually closed by the solve). // // When all work has been completed, calling (*Progress).Release will start // the process for closing out the progress UI. Note that because of the // refresh rate of the interactive UI, we need to also call (*Progress).Wait // to ensure it has exited cleanly. // // Example usage without error handling: // ```go // p, _ := NewProgress(ctx) // // p.WithPrefix("work", func(ctx context.Context, pw progress.Writer) error { // defer p.Release() // return workFunc(ctx, pw) // }) // // return p.Wait() // ``` // // If your work function also needs to dynamically spawn progress writers, then // you can call (*Progress).Go to create a goroutine sharing the same errgroup. // Then you can share the underlying multiwriter by calling // (*Progress).MultiWriter(). // // ```go // p, _ := progress.NewProgress(ctx) // // p.Go(func(ctx context.Context) error { // defer p.Release() // return workFunc(ctx, p.MultiWriter()) // }) // // return p.Wait() // ``` func NewProgress(ctx context.Context, opts ...ProgressOption) (Progress, error) { info := &ProgressInfo{ Console: os.Stderr, } for _, opt := range opts { err := opt(info) if err != nil { return nil, err } } var mode string switch info.LogOutput { case LogOutputTTY: mode = "tty" case LogOutputPlain: mode = "plain" default: return nil, errors.Errorf("unknown log output %q", info.LogOutput) } spp := newSyncProgressPrinter(info.Console, mode) p := &progressUI{ origCtx: ctx, spp: spp, mw: NewMultiWriter(spp), done: make(chan struct{}), } p.g, p.ctx = errgroup.WithContext(p.origCtx) return p, nil } func (p *progressUI) Sync() error { p.mu.Lock() defer p.mu.Unlock() p.Release() err := p.waitNoLock() if err != nil { return err } p.spp.reset() p.g, p.ctx = errgroup.WithContext(p.origCtx) p.done = make(chan struct{}) return nil } type progressUI struct { mu sync.Mutex mw *MultiWriter spp *syncProgressPrinter origCtx context.Context ctx context.Context g *errgroup.Group done chan struct{} } func (p *progressUI) MultiWriter() *MultiWriter { return p.mw } func (p *progressUI) Write(pfx, name string, fn func(ctx context.Context) error) { pw := p.mw.WithPrefix(pfx, false) p.mu.Lock() defer p.mu.Unlock() p.g.Go(func() error { return write(pw, name, func() error { return fn(p.ctx) }) }) } type stackTracer interface { StackTrace() errors.StackTrace } func write(pw progress.Writer, name string, fn func() error) error { status, done := progress.NewChannel(pw) defer func() { <-done }() dgst := digest.FromBytes([]byte(identity.NewID())) tm := time.Now() vtx := client.Vertex{ Digest: dgst, Name: name, Started: &tm, } status <- &client.SolveStatus{ Vertexes: []*client.Vertex{&vtx}, } err := fn() tm2 := time.Now() vtx2 := vtx vtx2.Completed = &tm2 // On the interactive progress UI, the vertex Error will not be printed // anywhere. So we add it to the vertex logs instead. var logs []*client.VertexLog if err != nil { vtx2.Error = err.Error() // Extract stack trace from pkg/errors. if tracer, ok := errors.Cause(err).(stackTracer); ok { for _, f := range tracer.StackTrace() { logs = append(logs, &client.VertexLog{ Vertex: dgst, Data: []byte(fmt.Sprintf("%+s:%d\n", f, f)), Timestamp: tm2, }) } } } status <- &client.SolveStatus{ Vertexes: []*client.Vertex{&vtx2}, Logs: logs, } return err } func (p *progressUI) Release() { close(p.done) } func (p *progressUI) Wait() (err error) { p.mu.Lock() defer p.mu.Unlock() return p.waitNoLock() } func (p *progressUI) waitNoLock() error { defer p.spp.cancel() <-p.done err := p.spp.wait() gerr := p.g.Wait() if err == nil { return gerr } return err } type syncProgressPrinter struct { mu sync.Mutex p *progress.Printer out console.File cancel func() mode string done chan struct{} } var _ progress.Writer = (*syncProgressPrinter)(nil) func newSyncProgressPrinter(out console.File, mode string) *syncProgressPrinter { spp := &syncProgressPrinter{ out: out, mode: mode, } spp.reset() return spp } func (spp *syncProgressPrinter) reset() { // Not using shared context to not disrupt display on errors, and allow // graceful exit and report error. pctx, cancel := context.WithCancel(context.Background()) spp.mu.Lock() defer spp.mu.Unlock() spp.cancel = cancel spp.done = make(chan struct{}) spp.p = progress.NewPrinter(pctx, spp.out, spp.mode) } func (spp *syncProgressPrinter) Write(s *client.SolveStatus) { spp.mu.Lock() defer spp.mu.Unlock() select { case <-spp.done: return default: spp.p.Write(s) } } func (spp *syncProgressPrinter) wait() error { spp.mu.Lock() defer spp.mu.Unlock() close(spp.done) return spp.p.Wait() }
package encoding import ( "encoding/base64" "encoding/json" "strings" ) // DecodeBase64OrJSON decodes a JSON string that can optionally be base64 encoded. func DecodeBase64OrJSON(in string, out interface{}) error { in = strings.TrimSpace(in) // the data can be base64 encoded if !json.Valid([]byte(in)) { bs, err := base64.StdEncoding.DecodeString(in) if err != nil { return err } in = string(bs) } return json.Unmarshal([]byte(in), out) }
// Copyright 2020 MongoDB 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 main import ( "encoding/json" "fmt" "os" "time" ) type DownloadArchive struct { PreviousReleasesLink string `json:"previous_releases_link"` ReleaseDate time.Time `json:"release_date"` ReleaseNotesLink string `json:"release_notes_link"` TutorialLink string `json:"tutorial_link"` Version string `json:"version"` ManualLink string `json:"manual_link"` Platform []Platform `json:"platform"` } type Platform struct { Arch string `json:"arch"` OS string `json:"os"` PackageFormat string `json:"package_format"` Packages Package `json:"packages"` } type Package struct { Title string `json:"title"` Links []Link `json:"links"` } type Link struct { DownloadLink string `json:"download_link"` Name string `json:"name"` } func newPlatform(version, arch, system, distro, format string) *Platform { //nolint:unparam // Arch is x86_64 for now p := &Platform{} p.Arch = arch p.OS = distro p.PackageFormat = format p.Packages = Package{ Title: "MongoDB CLI", Links: []Link{ { DownloadLink: fmt.Sprintf("https://fastdl.mongodb.org/mongocli/mongocli_%s_%s_%s.%s", version, system, arch, format), Name: format, }, }, } return p } func main() { version := os.Args[1] feedFilename := "mongocli.json" fmt.Printf("Generating JSON: %s\n", feedFilename) err := generateFile(feedFilename, version) if err != nil { fmt.Printf("error encoding file: %v\n", err) os.Exit(1) } fmt.Printf("File %s has been generated\n", feedFilename) } func generateFile(name, version string) error { feedFile, err := os.Create(name) if err != nil { return err } defer feedFile.Close() downloadArchive := &DownloadArchive{ ReleaseDate: time.Now().UTC(), Version: version, ManualLink: fmt.Sprintf("https://docs.mongodb.com/mongocli/v%s/", version), PreviousReleasesLink: "https://github.com/mongodb/mongocli/releases", ReleaseNotesLink: fmt.Sprintf("https://docs.mongodb.com/mongocli/v%s/release-notes/", version), TutorialLink: fmt.Sprintf("https://docs.mongodb.com/mongocli/v%s/quick-start/", version), Platform: []Platform{ *newPlatform(version, "x86_64", "linux", "Debian 9 / Ubuntu 16.04 + 18.04", "deb"), *newPlatform(version, "x86_64", "linux", "Red Hat + CentOS 6, 7, 8 / SUSE 12 + 15 / Amazon Linux", "rpm"), *newPlatform(version, "x86_64", "windows", "Microsoft Windows", "zip"), *newPlatform(version, "x86_64", "macos", "macOS", "zip"), *newPlatform(version, "x86_64", "linux", "Linux (x86_64)", "tar.gz"), }, } jsonEncoder := json.NewEncoder(feedFile) jsonEncoder.SetIndent("", " ") return jsonEncoder.Encode(downloadArchive) }
package master import ( "fmt" "testing" ) func assertEquals(t *testing.T, got, want string) { if got != want { t.Error("Got '" + got + "', want '" + want + "'") } } func assertTrue(t *testing.T, got bool, message string) { if !got { t.Error(message) } } func assertFalse(t *testing.T, got bool, message string) { if got { t.Error(message) } } func TestGetParent(t *testing.T) { assertEquals(t, getParent(""), "/") // Is this the expected behavior? assertEquals(t, getParent("/"), "/") assertEquals(t, getParent("/a/b"), "/a") assertEquals(t, getParent("/a/b/c"), "/a/b") assertEquals(t, getParent("/a/b/c"), "/a/b") } func create(m *NamespaceManager, path string) bool { ok, err := m.Create(path) if err != nil { fmt.Println(err) } return ok } func mkdir(m *NamespaceManager, path string) bool { ok, err := m.Mkdir(path) if err != nil { fmt.Println(err) } return ok } func remove(m *NamespaceManager, path string) bool { ok, err := m.Delete(path) if err != nil { fmt.Println(err) } return ok } func list(m *NamespaceManager, path string) []string { ret, err := m.List(path) if err != nil { fmt.Println(err) } return ret } func TestCreateAndMkdir(t *testing.T) { m := NewNamespaceManager() assertTrue(t, create(m, "/a"), "Create /a should return true") assertTrue(t, mkdir(m, "/b"), "Mkdir /b should return true") assertTrue(t, mkdir(m, "/b/d"), "Mkdir /b/d should return true") assertTrue(t, mkdir(m, "/b/d/e"), "Create /b/d/e should return true") assertTrue(t, create(m, "/b/c"), "Create /b/c should return true") assertFalse(t, mkdir(m, "/a"), "Mkdir /a should return false") assertFalse(t, create(m, "/a/b"), "Create /a/b should return false") // /a is not a directory assertFalse(t, create(m, "/"), "Create / should return fasle") } func TestList(t *testing.T) { m := NewNamespaceManager() m.Mkdir("/a") m.Mkdir("/b") m.Mkdir("/c") m.Mkdir("/a/a") m.Mkdir("/a/b") m.Mkdir("/a/c") m.Mkdir("/a/a/b") m.Mkdir("/a/a/c") fmt.Println("List /a", list(m, "/a")) fmt.Println("List /a/a", list(m, "/a/a")) fmt.Println("List /", list(m, "/")) } func TestDelete(t *testing.T) { m := NewNamespaceManager() m.Mkdir("/a") m.Mkdir("/a/b") m.Mkdir("/a/c") assertFalse(t, remove(m, "/a"), "Delete /a should return false") assertTrue(t, remove(m, "/a/b"), "Delete /a/b should return true") assertTrue(t, remove(m, "/a/c"), "Delete /a/c should return true") assertTrue(t, remove(m, "/a"), "Delete /a should return true") m.Mkdir("/a") m.Mkdir("/b") m.Mkdir("/b/c") m.Mkdir("/b/c/d") assertFalse(t, remove(m, "/b/c"), "Delete /b/c should return false") assertTrue(t, remove(m, "/b/c/d"), "Delete /b/c/d should return true") assertTrue(t, remove(m, "/b/c"), "Delete /b/c should return true") assertTrue(t, remove(m, "/b"), "Delete /b should return true") } func TestSaveAndLoad(t *testing.T) { // m0 first stores some data in its namespace, then stores all // its data into a file. m0 := NewNamespaceManager() m0.Mkdir("/a") m0.Mkdir("/a/b") m0.Mkdir("/a/c") path := fmt.Sprintf("/var/tmp/namespace") m0.Store(path) // m1 will load namespace information from a file and try to // perform some namespace operations. It should fail to create // some directories because they already exist in the namespace. m1 := NewNamespaceManager() m1.Load(path) assertFalse(t, mkdir(m1, "/a"), "m1 Mkdir /a should fail.") assertFalse(t, mkdir(m1, "/a/b"), "m1 Mkdir /a/b should fail." ) assertFalse(t, mkdir(m1, "/a/c"), "m1 Mkdir /a/c should fail.") assertTrue(t, mkdir(m1, "/a/b/c"), "m1 Mkdir /a/b/c should succeed.") }
//The debug package is great for testing and debugging of parser.Interface implementations. package debug
// Copyright 2021-present Open Networking Foundation. // // 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 proposal import ( "context" "testing" "time" "github.com/onosproject/onos-lib-go/pkg/errors" "github.com/atomix/atomix-go-client/pkg/atomix/test" "github.com/atomix/atomix-go-client/pkg/atomix/test/rsm" configapi "github.com/onosproject/onos-api/go/onos/config/v2" "github.com/stretchr/testify/assert" ) func TestProposalStore(t *testing.T) { test := test.NewTest( rsm.NewProtocol(), test.WithReplicas(1), test.WithPartitions(1), ) assert.NoError(t, test.Start()) defer test.Stop() client1, err := test.NewClient("node-1") assert.NoError(t, err) client2, err := test.NewClient("node-2") assert.NoError(t, err) store1, err := NewAtomixStore(client1) assert.NoError(t, err) store2, err := NewAtomixStore(client2) assert.NoError(t, err) target1 := configapi.TargetID("target-1") target2 := configapi.TargetID("target-2") ch := make(chan configapi.ProposalEvent) err = store2.Watch(context.Background(), ch) assert.NoError(t, err) target1ConfigValues := make(map[string]*configapi.PathValue) target1ConfigValues["/foo"] = &configapi.PathValue{ Value: configapi.TypedValue{ Bytes: []byte("Hello world!"), Type: configapi.ValueType_STRING, }, } target1Config := &configapi.Proposal{ ID: configapi.ProposalID(target1), TargetID: target1, TransactionIndex: 1, Details: &configapi.Proposal_Change{ Change: &configapi.ChangeProposal{ Values: target1ConfigValues, }, }, } target2ConfigValues := make(map[string]*configapi.PathValue) target2ConfigValues["/foo"] = &configapi.PathValue{ Value: configapi.TypedValue{ Bytes: []byte("Hello world again!"), Type: configapi.ValueType_STRING, }, } target2Config := &configapi.Proposal{ ID: configapi.ProposalID(target2), TargetID: target2, TransactionIndex: 1, Details: &configapi.Proposal_Change{ Change: &configapi.ChangeProposal{ Values: target2ConfigValues, }, }, } err = store1.Create(context.TODO(), target1Config) assert.NoError(t, err) assert.Equal(t, configapi.ProposalID(target1), target1Config.ID) assert.NotEqual(t, configapi.Revision(0), target1Config.Revision) err = store2.Create(context.TODO(), target2Config) assert.NoError(t, err) assert.Equal(t, configapi.ProposalID(target2), target2Config.ID) assert.NotEqual(t, configapi.Revision(0), target2Config.Revision) // Get the proposal target1Config, err = store2.Get(context.TODO(), configapi.ProposalID(target1)) assert.NoError(t, err) assert.NotNil(t, target1Config) assert.Equal(t, configapi.ProposalID(target1), target1Config.ID) assert.NotEqual(t, configapi.Revision(0), target1Config.Revision) // Verify events were received for the proposals proposalEvent := nextEvent(t, ch) assert.Equal(t, configapi.ProposalID(target1), proposalEvent.ID) proposalEvent = nextEvent(t, ch) assert.Equal(t, configapi.ProposalID(target2), proposalEvent.ID) // Watch events for a specific proposal proposalCh := make(chan configapi.ProposalEvent) err = store1.Watch(context.TODO(), proposalCh, WithProposalID(target2Config.ID)) assert.NoError(t, err) // Update one of the proposals revision := target2Config.Revision err = store1.Update(context.TODO(), target2Config) assert.NoError(t, err) assert.NotEqual(t, revision, target2Config.Revision) event := <-proposalCh assert.Equal(t, target2Config.ID, event.Proposal.ID) assert.Equal(t, target2Config.Revision, event.Proposal.Revision) // Lists proposals proposalList, err := store1.List(context.TODO()) assert.NoError(t, err) assert.Equal(t, 2, len(proposalList)) // Read and then update the proposal target2Config, err = store2.Get(context.TODO(), configapi.ProposalID(target2)) assert.NoError(t, err) assert.NotNil(t, target2Config) now := time.Now() target2Config.Status.Phases.Initialize = &configapi.ProposalInitializePhase{ ProposalPhaseStatus: configapi.ProposalPhaseStatus{ Start: &now, }, } revision = target2Config.Revision err = store1.Update(context.TODO(), target2Config) assert.NoError(t, err) assert.NotEqual(t, revision, target2Config.Revision) event = <-proposalCh assert.Equal(t, target2Config.ID, event.Proposal.ID) assert.Equal(t, target2Config.Revision, event.Proposal.Revision) // Verify that concurrent updates fail target1Config11, err := store1.Get(context.TODO(), configapi.ProposalID(target1)) assert.NoError(t, err) target1Config12, err := store2.Get(context.TODO(), configapi.ProposalID(target1)) assert.NoError(t, err) target1Config11.Status.Phases.Initialize = &configapi.ProposalInitializePhase{ ProposalPhaseStatus: configapi.ProposalPhaseStatus{ Start: &now, }, } err = store1.Update(context.TODO(), target1Config11) assert.NoError(t, err) target1Config12.Status.Phases.Initialize = &configapi.ProposalInitializePhase{ ProposalPhaseStatus: configapi.ProposalPhaseStatus{ Start: &now, }, } err = store2.Update(context.TODO(), target1Config12) assert.Error(t, err) // Verify events were received again proposalEvent = nextEvent(t, ch) assert.Equal(t, configapi.ProposalID(target2), proposalEvent.ID) proposalEvent = nextEvent(t, ch) assert.Equal(t, configapi.ProposalID(target2), proposalEvent.ID) proposalEvent = nextEvent(t, ch) assert.Equal(t, configapi.ProposalID(target1), proposalEvent.ID) // Delete a proposal err = store1.Delete(context.TODO(), target2Config) assert.NoError(t, err) proposal, err := store2.Get(context.TODO(), configapi.ProposalID(target2)) assert.NoError(t, err) assert.NotNil(t, proposal.Deleted) err = store1.Delete(context.TODO(), target2Config) assert.NoError(t, err) proposal, err = store2.Get(context.TODO(), configapi.ProposalID(target2)) assert.Error(t, err) assert.True(t, errors.IsNotFound(err)) assert.Nil(t, proposal) event = <-proposalCh assert.Equal(t, target2Config.ID, event.Proposal.ID) assert.Equal(t, configapi.ProposalEvent_UPDATED, event.Type) event = <-proposalCh assert.Equal(t, target2Config.ID, event.Proposal.ID) assert.Equal(t, configapi.ProposalEvent_DELETED, event.Type) // Checks list of proposal after deleting a proposal proposalList, err = store2.List(context.TODO()) assert.NoError(t, err) assert.Equal(t, 1, len(proposalList)) err = store1.Close(context.TODO()) assert.NoError(t, err) err = store2.Close(context.TODO()) assert.NoError(t, err) } func nextEvent(t *testing.T, ch chan configapi.ProposalEvent) *configapi.Proposal { select { case c := <-ch: return &c.Proposal case <-time.After(5 * time.Second): t.FailNow() } return nil }
//方法的接收者,如下两个Print方法,他的接收者分别是type A和B,属于type的方法 package main import "fmt" func main() { a := new(A) a.Print() fmt.Println(a.Name) b := new(B) b.Print() fmt.Println(b.Name) var a1 A a1.Print() fmt.Println(a1.Name) var b1 B b1.Print() fmt.Println(b1.Name) } type A struct { Name string } type B struct { Name string } // value receiver 和 pointer receiver都可以被值类型和指针类型的对象调用,编译器会自动互相转换, //但是通过接口对象调用方法时,pointer receiver方法只能被指针类型的接口对象调用, //而value receiver方法既可以被指针类型的接口对象调用,也可以被值类型的接口对象调用。 func (a *A) Print() { a.Name = "AA" fmt.Println("A") } //value receiver 不会对对象的状态造成改变,所以一般建议使用pointer receiver。 func (b B) Print() { b.Name = "BB" fmt.Println("B") }
package controllers import ( "181103/models" "github.com/astaxie/beego/orm" ) type ArticleTypeController struct { BaseController } func (this *ArticleTypeController) ShowAddType() { var types []models.ArticleType o:=orm.NewOrm() o.QueryTable("ArticleType").All(&types) this.Data["types"]=types this.ShowLayout() this.TplName="articleType/addType.html" } func (this *ArticleTypeController) HandleAddType() { typename:=this.GetString("typename") if typename=="" { this.ShowLayout() this.HandleError("","articleType/addType.html") return } var articleType models.ArticleType articleType.TypeName=typename o:=orm.NewOrm() if _,err:=o.Insert(&articleType);err!=nil { this.ShowLayout() this.HandleError(err.Error(),"articleType/addType.html") return } this.Redirect("/article_type/add",302) } func (this *ArticleTypeController) DeleteType() { id,err:=this.GetInt("id") if err!=nil { this.Redirect("/article_type/add",302) return } var articleType models.ArticleType articleType.Id=id o:=orm.NewOrm() o.Delete(&articleType) this.Redirect("/article_type/add",302) }
/* Copyright 2020 The Kubernetes Authors. 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 nameutil import ( "crypto/rand" "encoding/binary" "fmt" "time" ) //go:generate mockgen -destination=./mocks/mock_generator.go -package=mocks github.com/kubernetes-sigs/minibroker/pkg/nameutil Generator // Generator is the interface that wraps the basic Generate method. type Generator interface { Generate(prefix string) (generated string, err error) } // NameGenerator satisfies the Generator interface for generating names. type NameGenerator struct { timeNow func() time.Time randRead func([]byte) (int, error) } // NewDefaultNameGenerator creates a new NameGenerator with the default dependencies. func NewDefaultNameGenerator() *NameGenerator { return NewNameGenerator(time.Now, rand.Read) } // NewNameGenerator creates a new NameGenerator. func NewNameGenerator( timeNow func() time.Time, randRead func([]byte) (int, error), ) *NameGenerator { return &NameGenerator{ timeNow: timeNow, randRead: randRead, } } // Generate generates a new name with a prefix based on the UnixNano UTC timestamp plus 2 random // bytes. func (ng *NameGenerator) Generate(prefix string) (string, error) { b := make([]byte, 10) binary.LittleEndian.PutUint64(b[0:], uint64(ng.timeNow().UTC().UnixNano())) if _, err := ng.randRead(b[8:]); err != nil { return "", fmt.Errorf("failed to generate a new name: %v", err) } name := fmt.Sprintf("%s%x", prefix, b) return name, nil }
package ldap import ( "testing" ) func TestSplitDC(t *testing.T) { base := "dc=example,dc=org" dc1 := splitDC(base) if dc1 != "example" { t.Errorf("mismatch %q and %q", dc1, "example") } }
package xdominion import ( "fmt" ) var fieldintegertypes = map[string]string{ DB_Postgres: "integer", DB_MySQL: "integer", /* DB_Base::MSSQL => array( DB_Field::INTEGER => "int" ), DB_Base::ORACLE => array( DB_Field::INTEGER => "number(16)" ) */ } type XFieldInteger struct { Name string Constraints XConstraints } // creates the name of the field with its type (to create the table) func (f XFieldInteger) CreateField(prepend string, DB string, ifText *bool) string { field := prepend + f.Name if DB == DB_Postgres && f.IsAutoIncrement() { field += " serial" } else { field += " " + fieldintegertypes[DB] } /* if ($this->checks != null) $line .= $this->checks->createCheck($id.$this->name, $DB); else { if ($DB == DB_Base::MSSQL) { $line .= " NULL"; } } */ extra := "" if f.Constraints != nil { extra = f.Constraints.CreateConstraints(prepend, f.Name, DB) } return field + extra } // creates a string representation of the value of the field for insert/update func (f XFieldInteger) CreateValue(v interface{}, table string, DB string, id string) string { return fmt.Sprint(v) } // creates the sequence used by the field (only autoincrement fields) func (f XFieldInteger) CreateSequence(table string) string { return "" } // creates the index used by the field (normal, unique, multi, multi unique) func (f XFieldInteger) CreateIndex(table string, id string, DB string) []string { if f.Constraints != nil { return f.Constraints.CreateIndex(table, id, f.Name, DB) } return []string{} } // gets the name of the field func (f XFieldInteger) GetName() string { return f.Name } // gets the type of the field func (f XFieldInteger) GetType() int { return XField_Int } // gets the checks of the field func (f XFieldInteger) GetConstraints() XConstraints { return f.Constraints } // Is it autoincrement func (f XFieldInteger) IsAutoIncrement() bool { if f.Constraints != nil { c := f.Constraints.Get(AI) if c != nil { return true } } return false }
package main import "fmt" type rect struct { width, height int } // Area method has a receiver type of *rect (pointer shown below) func (r *rect) area() int { return r.width * r.height } // Methods can be defined for either pointer or value receiver types (value shown below) func (r rect) perim() int { return 2 * r.width * 2 * r.height } func main() { r := rect{10, 5} fmt.Println("area:", r.area()) fmt.Println("perim:", r.perim()) // Go automatically handles conversion between values and pointers for method valls rp := &r fmt.Println("area:", rp.area()) fmt.Println("perim", rp.perim()) }
package pgsql import ( "testing" ) func TestNumericArray(t *testing.T) { testlist2{{ valuer: NumericArrayFromIntSlice, scanner: NumericArrayToIntSlice, data: []testdata{ { input: []int{-9223372036854775808, 9223372036854775807}, output: []int{-9223372036854775808, 9223372036854775807}}, }, }, { valuer: NumericArrayFromInt8Slice, scanner: NumericArrayToInt8Slice, data: []testdata{ { input: []int8{-128, 127}, output: []int8{-128, 127}}, }, }, { valuer: NumericArrayFromInt16Slice, scanner: NumericArrayToInt16Slice, data: []testdata{ { input: []int16{-32768, 32767}, output: []int16{-32768, 32767}}, }, }, { valuer: NumericArrayFromInt32Slice, scanner: NumericArrayToInt32Slice, data: []testdata{ { input: []int32{-2147483648, 2147483647}, output: []int32{-2147483648, 2147483647}}, }, }, { valuer: NumericArrayFromInt64Slice, scanner: NumericArrayToInt64Slice, data: []testdata{ { input: []int64{-9223372036854775808, 9223372036854775807}, output: []int64{-9223372036854775808, 9223372036854775807}}, }, }, { valuer: NumericArrayFromUintSlice, scanner: NumericArrayToUintSlice, data: []testdata{ { input: []uint{0, 2147483647}, output: []uint{0, 2147483647}}, }, }, { valuer: NumericArrayFromUint8Slice, scanner: NumericArrayToUint8Slice, data: []testdata{ { input: []uint8{0, 255}, output: []uint8{0, 255}}, }, }, { valuer: NumericArrayFromUint16Slice, scanner: NumericArrayToUint16Slice, data: []testdata{ { input: []uint16{0, 65535}, output: []uint16{0, 65535}}, }, }, { valuer: NumericArrayFromUint32Slice, scanner: NumericArrayToUint32Slice, data: []testdata{ { input: []uint32{0, 4294967295}, output: []uint32{0, 4294967295}}, }, }, { valuer: NumericArrayFromUint64Slice, scanner: NumericArrayToUint64Slice, data: []testdata{ { input: []uint64{0, 9223372036854775807}, output: []uint64{0, 9223372036854775807}}, }, }, { valuer: NumericArrayFromFloat32Slice, scanner: NumericArrayToFloat32Slice, data: []testdata{ { input: []float32{0, 2147483647.0}, output: []float32{0, 2147483647.0}}, }, }, { valuer: NumericArrayFromFloat64Slice, scanner: NumericArrayToFloat64Slice, data: []testdata{ { input: []float64{0, 922337203685477580.0}, output: []float64{0, 922337203685477580.0}}, }, }, { data: []testdata{ { input: string("{-9223372036854775808,9223372036854775807}"), output: string(`{-9223372036854775808,9223372036854775807}`)}, }, }, { data: []testdata{ { input: []byte("{-9223372036854775808,9223372036854775807}"), output: []byte(`{-9223372036854775808,9223372036854775807}`)}, }, }}.execute(t, "numericarr") }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/10/11 8:59 上午 # @File : lt_128_最长连续子序列.go # @Description : # @Attention : */ package offer // 解题关键: 用一个hashSet来处理, func longestConsecutive(nums []int) int { set := make(map[int]bool) for _, v := range nums { set[v] = true } ret := 0 for k := range set { // 如果之前的数不存在,则可以开始统计了 // 当前的数是必然存在的 if !set[k-1] { currentN := k currentL := 0 for set[currentN] { currentL++ currentN++ } if currentL > ret { ret = currentL } } } return ret }
package mymgo import ( "fmt" "strings" "dudu/config" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type Field struct { Id string Collection string } type MdbSession struct { session *mgo.Session db string } func (mdb *MdbSession) Session() *mgo.Session { return mdb.session.New() } var ( AutoIncIdCollection = "amb_config" field = &Field{ Id: "seq", Collection: "_id", } ) func GetDb(cfgs []*config.DBConfig) *MdbSession { var url = generateUrl(cfgs) session, err := mgo.Dial(url) if err != nil { panic(err.Error()) } return &MdbSession{ session: session, db: cfgs[0].Db, } } func generateUrl(cfgs []*config.DBConfig) string { if len(cfgs) == 0 { return "" } mongoUrl := "mongodb://" if cfgs[0].User != "" && cfgs[0].Passwd != "" { mongoUrl += cfgs[0].User + ":" + cfgs[0].Passwd + "@" } addrs := make([]string, 0, len(cfgs)) for _, addr := range cfgs { addrs = append(addrs, fmt.Sprintf("%s:%d", addr.Host, addr.Port)) } mongoUrl += strings.Join(addrs, ",") if cfgs[0].Db != "" { mongoUrl += "/" + cfgs[0].Db } if cfgs[0].Options != "" { mongoUrl += "?" + cfgs[0].Options } return mongoUrl } func (mdb *MdbSession) AutoIncId(name string) (id int) { s := mdb.Session() id, err := autoIncr(s.DB(mdb.db).C(AutoIncIdCollection), name) s.Close() if err != nil { panic("Get next id of [" + name + "] fail:" + err.Error()) } return } func autoIncr(c *mgo.Collection, name string) (id int, err error) { return incr(c, name, 1) } func incr(c *mgo.Collection, name string, step int) (id int, err error) { result := make(map[string]interface{}) change := mgo.Change{ Update: bson.M{"$inc": bson.M{field.Id: step}}, Upsert: true, ReturnNew: true, } _, err = c.Find(bson.M{field.Collection: name}).Apply(change, result) if err != nil { return } id, ok := result[field.Id].(int) if ok { return } id64, ok := result[field.Id].(int64) if !ok { err = fmt.Errorf("%s is ont int or int64", field.Id) return } id = int(id64) return }
package main import ( "fmt" "github.com/skorobogatov/input" ) func vis_mealy(d [][]int, f [][]rune, n int, m int, q1 int) { fmt.Println("digraph {") fmt.Println("rankdir = LR") fmt.Println("dummy [label = \"\", shape = none]") for i := 0; i < len(d); i++ { fmt.Printf("%d [shape = circle]\n", i) } fmt.Printf("dummy -> %d\n", q1) for i := 0; i < n; i++ { for j := 0; j < m; j++ { fmt.Printf("%d -> %d [label = \"%c(%c)\"]\n", i, d[i][j], j+97, f[i][j]) } } fmt.Println("}") } func main() { var n, m, q1 int input.Scanf("%d\n%d\n%d", &n, &m, &q1) D := make([][]int, n) F := make([][]rune, n) for i := 0; i < n; i++ { D[i] = make([]int, m) F[i] = make([]rune, m) } for i := 0; i < n; i++ { for j := 0; j < m; j++ { input.Scanf("%d ", &D[i][j]) } } for i := 0; i < n; i++ { for j := 0; j < m; j++ { input.Scanf("%c ", &F[i][j]) } } vis_mealy(D, F, n, m, q1) }
// This file contains tests for platforms that have no escape // mechanism for including commas in mount options. // // +build darwin package fuse_test import ( "runtime" "testing" "gx/ipfs/QmSJBsmLP1XMjv8hxYg2rUMdPDB7YUpyBo9idjrJ6Cmq6F/fuse" "gx/ipfs/QmSJBsmLP1XMjv8hxYg2rUMdPDB7YUpyBo9idjrJ6Cmq6F/fuse/fs/fstestutil" ) func TestMountOptionCommaError(t *testing.T) { t.Parallel() // this test is not tied to any specific option, it just needs // some string content var evil = "FuseTest,Marker" mnt, err := fstestutil.MountedT(t, fstestutil.SimpleFS{fstestutil.Dir{}}, nil, fuse.ForTestSetMountOption("fusetest", evil), ) if err == nil { mnt.Close() t.Fatal("expected an error about commas") } if g, e := err.Error(), `mount options cannot contain commas on `+runtime.GOOS+`: "fusetest"="FuseTest,Marker"`; g != e { t.Fatalf("wrong error: %q != %q", g, e) } }
package parser import ( "go/ast" "go/parser" "go/token" "testing" "github.com/stretchr/testify/require" ) func getASTFromSrc(src string) *ast.File { fs := token.NewFileSet() srcAST, _ := parser.ParseFile(fs, "", src, parser.ParseComments) return srcAST } func Test_parseEndpointsFrom(t *testing.T) { src := ` package hello import "context" // Service is a simple interface for a service. type Service interface { //gokit: path:"/say-hello" Hello(ctx context.Context, p Person) error } // Person presents a single person. type Person struct { Name string ` + "`" + `json:"name"` + "`" + ` } ` srcAST := getASTFromSrc(src) decl := srcAST.Decls[1].(*ast.GenDecl) spec := decl.Specs[0].(*ast.TypeSpec) p := &serviceParser{ serviceType: spec.Type.(*ast.InterfaceType), f: srcAST, packageName: srcAST.Name.Name, } endpoints := p.parseEndpoints() require.Len(t, endpoints, 1) require.Equal(t, "/say-hello", endpoints[0].HTTPPath) }
/* * Copyright (c) 2020. Ant Group. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ package config import ( "path/filepath" "time" "github.com/pkg/errors" ) const ( DefaultDaemonMode string = "multiple" DaemonModeMultiple string = "multiple" DaemonModeShared string = "shared" DaemonModeNone string = "none" DaemonModePrefetch string = "prefetch" DefaultLogLevel string = "info" defaultGCPeriod = 24 * time.Hour defaultNydusDaemonConfigPath string = "/etc/nydus/config.json" defaultNydusdBinaryPath string = "/usr/local/bin/nydusd" defaultNydusImageBinaryPath string = "/usr/local/bin/nydus-image" ) type Config struct { Address string `toml:"-"` ConvertVpcRegistry bool `toml:"-"` DaemonCfgPath string `toml:"daemon_cfg_path"` DaemonCfg DaemonConfig `toml:"-"` PublicKeyFile string `toml:"-"` RootDir string `toml:"-"` CacheDir string `toml:"cache_dir"` GCPeriod time.Duration `toml:"gc_period"` ValidateSignature bool `toml:"validate_signature"` NydusdBinaryPath string `toml:"nydusd_binary_path"` NydusImageBinaryPath string `toml:"nydus_image_binary"` DaemonMode string `toml:"daemon_mode"` AsyncRemove bool `toml:"async_remove"` EnableMetrics bool `toml:"enable_metrics"` MetricsFile string `toml:"metrics_file"` EnableStargz bool `toml:"enable_stargz"` LogLevel string `toml:"-"` } func (c *Config) FillupWithDefaults() error { if c.LogLevel == "" { c.LogLevel = DefaultLogLevel } if c.DaemonCfgPath == "" { c.DaemonCfgPath = defaultNydusDaemonConfigPath } if c.NydusdBinaryPath == "" { c.NydusdBinaryPath = defaultNydusdBinaryPath } if c.NydusImageBinaryPath == "" { c.NydusImageBinaryPath = defaultNydusImageBinaryPath } if c.DaemonMode == "" { c.DaemonMode = DefaultDaemonMode } if c.GCPeriod == 0 { c.GCPeriod = defaultGCPeriod } if len(c.CacheDir) == 0 { c.CacheDir = filepath.Join(c.RootDir, "cache") } var daemonCfg DaemonConfig if err := LoadConfig(c.DaemonCfgPath, &daemonCfg); err != nil { return errors.Wrapf(err, "failed to load config file %q", c.DaemonCfgPath) } c.DaemonCfg = daemonCfg return nil }
package main import ( "fmt" "strconv" "strings" ) type node struct { children []node metadata []int } func processNode(data []int, index int) (result node, after int) { result = node{[]node{}, []int{}} childCount := data[index] metaCount := data[index+1] index += 2 for child := 0; child < childCount; child++ { childNode, newindex := processNode(data, index) index = newindex result.children = append(result.children, childNode) } for meta := 0; meta < metaCount; meta++ { result.metadata = append(result.metadata, data[index]) index++ } return result, index } func loaddata(input string) (root node) { var data []int for _, line := range strings.Split(input, "\n") { line = strings.TrimSpace(line) if line == "" { continue } for _, val := range strings.Split(line, " ") { if ival, err := strconv.Atoi(val); err == nil { data = append(data, ival) } else { panic("Non int in line " + line) } } } index := 0 root, index = processNode(data, index) return root } func dumpTree(n node, pad string) { fmt.Println(pad + " (" + strings.Join(strings.Fields(fmt.Sprint(n.metadata)), ",") + ")") for _, c := range n.children { dumpTree(c, pad+" ") } } func sumTree(n node) int { thisNodeTotal := 0 for _, m := range n.metadata { thisNodeTotal += m } for _, c := range n.children { thisNodeTotal += sumTree(c) } return thisNodeTotal } func main() { root := loaddata(testdata()) dumpTree(root, "") fmt.Println(sumTree(root)) main2(root) } func testdata() string { return ` 2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2 ` }
package pdns_api import ( "fmt" "net/http" "net/url" "testing" "github.com/labstack/echo/v4" "github.com/pir5/pdns-api/model" ) type domainModelStub struct { } func init() { globalConfig = Config{ Auth: auth{ AuthType: AuthTypeHTTP, }, } } func (d *domainModelStub) FindBy(params map[string]interface{}) (model.Domains, error) { ds := model.Domains{} if params["name"] != nil { switch params["name"].([]string)[0] { case "ok": ds = model.Domains{ model.Domain{ ID: 1, Name: "ok.com", }, } case "error_please": return nil, fmt.Errorf("give error to you") case "deny": ds = model.Domains{ model.Domain{ ID: 1, Name: "deny.com", }, } } } else if params["id"] != nil { switch params["id"].(int) { case 1, 4: ds = model.Domains{ model.Domain{ ID: 1, Name: "ok.com", }, } case 2: return nil, fmt.Errorf("give error to you") case 3: ds = model.Domains{ model.Domain{ ID: 1, Name: "deny.com", }, } } } return ds, nil } func (d *domainModelStub) UpdateByName(name string, newDomain *model.Domain) (bool, error) { switch name { case "ok.com": return true, nil } return false, nil } func (d *domainModelStub) DeleteByName(name string) (bool, error) { switch name { case "ok.com": return true, nil } return false, nil } func (d *domainModelStub) UpdateByID(id string, newDomain *model.Domain) (bool, error) { switch id { case "1": return true, nil case "4": return false, nil } return false, nil } func (d *domainModelStub) DeleteByID(id string) (bool, error) { switch id { case "1": return true, nil case "2": return false, nil } return false, nil } func (d *domainModelStub) Create(newDomain *model.Domain) error { return nil } func Test_domainHandler_getDomains(t *testing.T) { type fields struct { domainModel model.DomainModeler } tests := []struct { name string fields fields wantErr bool wantCode int queryName string }{ { name: "ok", fields: fields{ domainModel: &domainModelStub{}, }, wantErr: false, wantCode: http.StatusOK, queryName: "ok", }, { name: "notfound", fields: fields{ domainModel: &domainModelStub{}, }, wantErr: false, wantCode: http.StatusOK, queryName: "notfound", }, { name: "get error", fields: fields{ domainModel: &domainModelStub{}, }, wantErr: false, wantCode: http.StatusInternalServerError, queryName: "error_please", }, { name: "deny", fields: fields{ domainModel: &domainModelStub{}, }, wantErr: false, wantCode: http.StatusOK, queryName: "deny", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { h := &domainHandler{ domainModel: tt.fields.domainModel, } q := make(url.Values) q.Set("name", tt.queryName) ctx, rec := dummyContext(t, "GET", "/domains?"+q.Encode(), nil) ctx.Set(AllowDomainsKey, []string{"ok.com"}) if err := h.getDomains(ctx); (err != nil) != tt.wantErr { t.Errorf("domainHandler.getDomains() error = %v, wantErr %v", err, tt.wantErr) } if rec.Code != tt.wantCode { t.Errorf("domainHandler.getDomains() got different http status code = %d, wantCode %d", rec.Code, tt.wantCode) } }) } } func Test_domainHandler_updateDomainByID(t *testing.T) { type fields struct { domainModel model.DomainModeler } tests := []struct { name string fields fields args model.Domain wantErr bool wantCode int queryName string }{ { name: "ok", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "ok.com", ID: 9999, Type: "NATIVE", }, wantErr: false, wantCode: http.StatusOK, queryName: "1", }, { name: "not found", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "ok.com", ID: 1111, Type: "NATIVE", }, wantErr: false, wantCode: http.StatusNotFound, queryName: "4", }, { name: "deny", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "deny.com", ID: 1, Type: "NATIVE", }, wantErr: false, wantCode: http.StatusForbidden, queryName: "3", }, { name: "invalid domain name", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "@.com", ID: 1, Type: "NATIVE", }, wantErr: false, wantCode: http.StatusBadRequest, queryName: "1", }, { name: "invalid domain type", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "ok.com", ID: 1, Type: "NG", }, wantErr: false, wantCode: http.StatusBadRequest, queryName: "1", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { h := &domainHandler{ domainModel: tt.fields.domainModel, } ctx, rec := dummyContext(t, "PUT", "/domains/:", tt.args) ctx.SetParamNames("id") ctx.SetParamValues(tt.queryName) ctx.Set(AllowDomainsKey, []string{"ok.com", "notfound.com"}) if err := h.updateDomainByID(ctx); (err != nil) != tt.wantErr { t.Errorf("domainHandler.updateDomainByID() error = %v, wantErr %v", err, tt.wantErr) } if rec.Code != tt.wantCode { t.Errorf("%+v", rec) t.Errorf("domainHandler.updateDomainsByID() got different http status code = %d, wantCode %d", rec.Code, tt.wantCode) } }) } } func Test_domainHandler_updateDomainByName(t *testing.T) { type fields struct { domainModel model.DomainModeler } tests := []struct { name string fields fields args model.Domain wantErr bool wantCode int queryName string }{ { name: "ok", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "ok.com", ID: 9999, Type: "NATIVE", }, wantErr: false, wantCode: http.StatusOK, queryName: "ok.com", }, { name: "not found", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "ok.com", ID: 1111, Type: "NATIVE", }, wantErr: false, wantCode: http.StatusNotFound, queryName: "notfound.com", }, { name: "deny", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "deny.com", ID: 1, Type: "NATIVE", }, wantErr: false, wantCode: http.StatusForbidden, queryName: "deny", }, { name: "invalid domain name", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "@.com", ID: 1, Type: "NATIVE", }, wantErr: false, wantCode: http.StatusBadRequest, queryName: "ok.com", }, { name: "invalid domain type", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "ok.com", ID: 1, Type: "NG", }, wantErr: false, wantCode: http.StatusBadRequest, queryName: "ok.com", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { h := &domainHandler{ domainModel: tt.fields.domainModel, } ctx, rec := dummyContext(t, "PUT", "/domains/name/:", tt.args) ctx.SetParamNames("name") ctx.SetParamValues(tt.queryName) ctx.Set(AllowDomainsKey, []string{"ok.com", "notfound.com"}) if err := h.updateDomainByName(ctx); (err != nil) != tt.wantErr { t.Errorf("domainHandler.updateDomainByName() error = %v, wantErr %v", err, tt.wantErr) } if rec.Code != tt.wantCode { t.Errorf("domainHandler.updateDomainsByName() got different http status code = %d, wantCode %d", rec.Code, tt.wantCode) } }) } } func Test_domainHandler_deleteDomainByName(t *testing.T) { type fields struct { domainModel model.DomainModeler } tests := []struct { name string fields fields wantErr bool wantCode int queryName string }{ { name: "ok", fields: fields{ domainModel: &domainModelStub{}, }, wantErr: false, wantCode: http.StatusNoContent, queryName: "ok.com", }, { name: "not found", fields: fields{ domainModel: &domainModelStub{}, }, wantErr: false, wantCode: http.StatusNotFound, queryName: "notfound.com", }, { name: "deny", fields: fields{ domainModel: &domainModelStub{}, }, wantErr: false, wantCode: http.StatusForbidden, queryName: "deny", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { h := &domainHandler{ domainModel: tt.fields.domainModel, } ctx, rec := dummyContext(t, "DELETE", "/domains/name/:", nil) ctx.SetParamNames("name") ctx.SetParamValues(tt.queryName) ctx.Set(AllowDomainsKey, []string{"ok.com", "notfound.com"}) if err := h.deleteDomainByName(ctx); (err != nil) != tt.wantErr { t.Errorf("domainHandler.deleteDomainByName() error = %v, wantErr %v", err, tt.wantErr) } if rec.Code != tt.wantCode { t.Errorf("domainHandler.deleteDomainsByName() got different http status code = %d, wantCode %d", rec.Code, tt.wantCode) } }) } } func Test_domainHandler_deleteDomainByID(t *testing.T) { type fields struct { domainModel model.DomainModeler } tests := []struct { name string fields fields wantErr bool wantCode int queryID string }{ { name: "ok", fields: fields{ domainModel: &domainModelStub{}, }, wantErr: false, wantCode: http.StatusNoContent, queryID: "1", }, { name: "not found", fields: fields{ domainModel: &domainModelStub{}, }, wantErr: false, wantCode: http.StatusNotFound, queryID: "4", }, { name: "deny", fields: fields{ domainModel: &domainModelStub{}, }, wantErr: false, wantCode: http.StatusForbidden, queryID: "3", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { h := &domainHandler{ domainModel: tt.fields.domainModel, } ctx, rec := dummyContext(t, "DELETE", "/domains/id/:", nil) ctx.SetParamNames("id") ctx.SetParamValues(tt.queryID) ctx.Set(AllowDomainsKey, []string{"ok.com", "notfound.com"}) if err := h.deleteDomainByID(ctx); (err != nil) != tt.wantErr { t.Errorf("domainHandler.deleteDomainByID() error = %v, wantErr %v", err, tt.wantErr) } if rec.Code != tt.wantCode { t.Errorf("domainHandler.deleteDomainsByID() got different http status code = %d, wantCode %d", rec.Code, tt.wantCode) } }) } } func Test_domainHandler_createDomain(t *testing.T) { type fields struct { domainModel model.DomainModeler } type args struct { c echo.Context } tests := []struct { name string fields fields args model.Domain wantErr bool wantCode int queryName string }{ { name: "ok", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "ok.com", ID: 9999, Type: "NATIVE", }, wantErr: false, wantCode: http.StatusCreated, queryName: "ok.com", }, { name: "deny", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "deny.com", ID: 1, Type: "NATIVE", }, wantErr: false, wantCode: http.StatusForbidden, queryName: "deny.com", }, { name: "invalid domain name", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "@.com", ID: 1, Type: "NATIVE", }, wantErr: false, wantCode: http.StatusBadRequest, queryName: "@.com", }, { name: "invalid domain type", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "example.com", ID: 1, Type: "NG", }, wantErr: false, wantCode: http.StatusBadRequest, queryName: "example.com", }, { name: "empty domain type", fields: fields{ domainModel: &domainModelStub{}, }, args: model.Domain{ Name: "example.com", ID: 1, }, wantErr: false, wantCode: http.StatusBadRequest, queryName: "example.com", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { h := &domainHandler{ domainModel: tt.fields.domainModel, } ctx, rec := dummyContext(t, "PUT", "/domains/:", tt.args) ctx.SetParamNames("name") ctx.SetParamValues(tt.queryName) ctx.Set(AllowDomainsKey, []string{"ok.com"}) if err := h.createDomain(ctx); (err != nil) != tt.wantErr { t.Errorf("domainHandler.createDomain() error = %v, wantErr %v", err, tt.wantErr) } if rec.Code != tt.wantCode { t.Errorf("domainHandler.createDomains() got different http status code = %d, wantCode %d", rec.Code, tt.wantCode) } }) } }
package main import ( "fmt" ) // Complete the countApplesAndOranges function below. func countApplesAndOranges(s int32, t int32, a int32, b int32, apples []int32, oranges []int32) { applesCoord := getFruitCoord(apples, a) orrangesCoord := getFruitCoord(oranges, a) fmt.Println(calcFruits(applesCoord, s, t)) fmt.Println(calcFruits(orrangesCoord, s, t)) } func calcFruits(input []int32, s int32, t int32) int32 { var total int32 for _, v := range input { if s >= v && v <= t { total = total + 1 } } return total } func getFruitCoord(fruits []int32, loc int32) []int32 { var output []int32 for _, v := range fruits { output = append(output, v+loc) } return output } func main() { countApplesAndOranges(7, 11, 5, 15, []int32{-2, 2, 1}, []int32{5, -6}) }
package handlers import ( "testing" "github.com/gin-gonic/gin" "github.com/urbn/ordernumbergenerator/app" "github.com/urbn/ordernumbergenerator/app/fixtures" "github.com/urbn/ordernumbergenerator/app/mocks" ) var ( url = "/v0/fp-us/sterling-order-number" relativePath = "/v0/:siteId/sterling-order-number" mockDao = mocks.MockOrdersDao{ "00000000", nil, } nh = OrderNumberHandler{ app.PennsylvaniaDC, mockDao, } ) func Test_GetOrderNumber_Success(t *testing.T) { testRouter := gin.Default() testRouter.POST(relativePath, nh.GetOrderNumber) response := fixtures.PerformRequest(testRouter, "POST", url) if code := response.Code; code != 200 { t.Errorf("Handler returned wrong status code: received %v expected %v", code, 200) } } func Test_GetOrderNumber_DataCenterValidation_Error(t *testing.T) { handler := nh handler.DataCenterId = "US-US" testRouter := gin.Default() testRouter.POST(relativePath, handler.GetOrderNumber) response := fixtures.PerformRequest(testRouter, "POST", url) if response.Code != 400 { t.Errorf("Handler returned wrong status code: received %v expected %v", response.Code, 400) } } func Test_GetOrderNumber_BrandIdValidation_Error(t *testing.T) { invalidPath := "/v0/no-brand/sterling-order-number" testRouter := gin.Default() testRouter.POST(relativePath, nh.GetOrderNumber) response := fixtures.PerformRequest(testRouter, "POST", invalidPath) if response.Code != 400 { t.Errorf("Handler returned wrong status code: received %v expected %v", response.Code, 400) } } func Test_GetOrderNumber_OrderNumDao_Error(t *testing.T) { handler := nh handler.Dao = mocks.MockOrdersDao{ OrderNum: "0", Error: &fixtures.MockOrderDaoError, } testRouter := gin.Default() testRouter.POST(relativePath, handler.GetOrderNumber) response := fixtures.PerformRequest(testRouter, "POST", url) if response.Code != 400 { t.Errorf("Handler returned wrong status code: received %v expected %v", response.Code, 400) } } func Test_GetOrderNumber_OrderNumValidation_Error(t *testing.T) { handler := nh handler.Dao = mocks.MockOrdersDao{ OrderNum: "0", Error: nil, } testRouter := gin.Default() testRouter.POST(relativePath, handler.GetOrderNumber) response := fixtures.PerformRequest(testRouter, "POST", url) if response.Code != 500 { t.Errorf("Handler returned wrong status code: received %v expected %v", response.Code, 500) } } func Test_buildOrderNumber(t *testing.T) { orderNumber := buildOrderNumber("US-PA", "uo", "00000001") if orderNumber != "TP00000001" { t.Errorf("Exepected orderNumber TP00000001 but got %s", orderNumber) } } func Test_validateBrandAndDataCenter_Success(t *testing.T) { result := validateBrandAndDataCenter("uo-us", app.PennsylvaniaDC) if result != nil { t.Errorf("Expected an error status of 200 but got %d", result.Code) } } func Test_validateBrandAndDataCenter_Invalid_BrandID_Error(t *testing.T) { result := validateBrandAndDataCenter("foo", app.PennsylvaniaDC) if result.Code != 400 { t.Errorf("Expected an error status of 400 but got %d", result.Code) } } func Test_validateBrandAndDataCenter_Invalid_DataCenterID_Error(t *testing.T) { result := validateBrandAndDataCenter("uo-us", "foo") if result.Code != 400 { t.Errorf("Expected an error status of 400 but got %d", result.Code) } } func Test_validateOrderNumber_Success(t *testing.T) { result := validateOrderNumber("00000001") if result != nil { t.Errorf("Expected an error status of 200 but got %d", result.Code) } } func Test_validateOrderNumber_Invalid_OrderNumber_Len_Error(t *testing.T) { result := validateOrderNumber("000") if result.Code != 500 { t.Errorf("Expected an error status of 500 but got %d", result.Code) } } func Test_validateOrderNumber_Invalid_OrderNumber_Error(t *testing.T) { result := validateOrderNumber("!!!") if result.Code != 500 { t.Errorf("Expected an error status of 500 but got %d", result.Code) } }
package resource import ( "os" "github.com/chronojam/aws-pricing-api/types/schema" "github.com/olekukonko/tablewriter" ) func GetCloudWatch() { cloudwatch := &schema.AmazonCloudWatch{} err := cloudwatch.Refresh() if err != nil { panic(err) } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Description", "USD", "Unit"}) table.SetRowLine(true) data := []*schema.AmazonCloudWatch_Product{} for _, price := range cloudwatch.Products { data = append(data, price) } for _, p := range data { for _, term := range cloudwatch.Terms { if term.Sku == p.Sku { for _, priceData := range term.PriceDimensions { x := []string{} v := append(x, priceData.Description, priceData.PricePerUnit.USD, priceData.Unit) table.Append(v) } } } } table.Render() }
package fs // Version of rclone var Version = "v1.42-DEV"
package transport import ( "crypto/md5" "encoding/base64" "encoding/hex" "encoding/json" "fmt" "net/http" "net/url" "strings" "time" cache "github.com/patrickmn/go-cache" cells_sdk "github.com/pydio/cells-sdk-go" ) type TokenStore struct { internalCache *cache.Cache } func NewTokenStore() *TokenStore { t := &TokenStore{ internalCache: cache.New(20*time.Minute, 10*time.Minute), } return t } func (t *TokenStore) Store(c *cells_sdk.SdkConfig, token string, expiry time.Duration) { //fmt.Println("[Auth] Storing token with expiration ", expiry) t.internalCache.Set(t.computeKey(c), token, expiry) } func (t *TokenStore) TokenFor(c *cells_sdk.SdkConfig) string { if token, ok := t.internalCache.Get(t.computeKey(c)); ok { return token.(string) } return "" } func (t *TokenStore) computeKey(c *cells_sdk.SdkConfig) string { // Is this relly necessary or rather security theater? // using a generic password causes issues when testing wrong password access. //s := fmt.Sprintf("%s-%s-%s-%s-%s", c.Url, c.ClientKey, c.ClientSecret, c.User, "OBFUSCATED PWD XXXX") s := fmt.Sprintf("%s-%s-%s-%s-%s", c.Url, c.ClientKey, c.ClientSecret, c.User, c.Password) hasher := md5.New() hasher.Write([]byte(s)) return hex.EncodeToString(hasher.Sum(nil)) } func retrieveToken(sdkConfig *cells_sdk.SdkConfig) (string, error) { if sdkConfig.UseTokenCache { cached := store.TokenFor(sdkConfig) if cached != "" { // fmt.Println("[Auth: Retrieved token from cache]") return cached, nil } // fmt.Println("No token found in cache, querying the server") } fullURL := sdkConfig.Url + oidcResourcePath + "/token" data := url.Values{} data.Set("grant_type", grantType) data.Add("username", sdkConfig.User) data.Add("password", sdkConfig.Password) // TODO: Scope should ask for "offline_access" as well for more realism data.Add("scope", scope) // TODO: This should be a uuid.New() for more realism data.Add("nonce", "aVerySpecialNonce") req, err := http.NewRequest("POST", fullURL, strings.NewReader(data.Encode())) if err != nil { return "", err } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") // Important: our dex API does not yet support json payload. req.Header.Add("Cache-Control", "no-cache") req.Header.Add("Authorization", basicAuthToken(sdkConfig.ClientKey, sdkConfig.ClientSecret)) res, err := GetHttpClient(sdkConfig).Do(req) if err != nil { return "", err } defer res.Body.Close() var respMap map[string]interface{} err = json.NewDecoder(res.Body).Decode(&respMap) if err != nil { return "", fmt.Errorf("could not unmarshall response with status %d: %s\nerror cause: %s", res.StatusCode, res.Status, err.Error()) } if errMsg, exists := respMap["error"]; exists { return "", fmt.Errorf("could not retrieve token, %s: %s", errMsg, respMap["error_description"]) } token := respMap["id_token"].(string) expiry := respMap["expires_in"].(float64) - 60 // Secure by shortening expiration time store.Store(sdkConfig, token, time.Duration(expiry)*time.Second) return token, nil } func basicAuthToken(username, password string) string { auth := username + ":" + password return "Basic " + base64.StdEncoding.EncodeToString([]byte(auth)) }
package middleware import ( "encoding/json" "net/http" "strconv" "github.com/root-gg/plik/server/common" "github.com/root-gg/plik/server/context" ) // Paginate parse pagination requests func Paginate(ctx *context.Context, next http.Handler) http.Handler { return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { pagingQuery := common.NewPagingQuery().WithLimit(20) header := req.Header.Get("X-Plik-Paging") if header != "" { err := json.Unmarshal([]byte(header), &pagingQuery) if err != nil { ctx.InvalidParameter("paging header") return } } else { limitStr := req.URL.Query().Get("limit") if limitStr != "" { limit, err := strconv.Atoi(limitStr) if err != nil { ctx.InvalidParameter("limit : %s", err) } pagingQuery.WithLimit(limit) } order := req.URL.Query().Get("order") if order != "" { pagingQuery.WithOrder(order) } before := req.URL.Query().Get("before") if before != "" { pagingQuery.WithBeforeCursor(before) } after := req.URL.Query().Get("after") if after != "" { pagingQuery.WithAfterCursor(after) } } if pagingQuery.Limit != nil && *pagingQuery.Limit <= 0 { ctx.InvalidParameter("limit") } if pagingQuery.Order != nil && !(*pagingQuery.Order == "asc" || *pagingQuery.Order == "desc") { ctx.InvalidParameter("order") } if pagingQuery.Before != nil && pagingQuery.After != nil { ctx.BadRequest("both before and after cursors set") } ctx.SetPagingQuery(pagingQuery) next.ServeHTTP(resp, req) }) }
// Copyright 2019 Kuei-chun Chen. All rights reserved. package atlas import ( "encoding/json" "fmt" "io/ioutil" "os" "testing" ) func TestGetClusters(t *testing.T) { var err error var data []byte var doc map[string]interface{} publicKey := os.Getenv("ATLAS_USER_PS") privateKey := os.Getenv("ATLAS_KEY_PS") groupID := os.Getenv("ATLAS_GROUP") api := NewKey(publicKey, privateKey) api.SetVerbose(testing.Verbose()) if doc, err = api.GetClusters(groupID); err != nil { t.Fatal(err) } if data, err = json.Marshal(doc); err != nil { t.Fatal(err) } os.Mkdir("./out", 0755) ofile := `./out/clusters.json` if err = ioutil.WriteFile(ofile, data, 0644); err != nil { t.Fatal(err) } } func TestGetCluster(t *testing.T) { var err error var data []byte var doc map[string]interface{} clusterName := "demo" publicKey := os.Getenv("ATLAS_USER_PS") privateKey := os.Getenv("ATLAS_KEY_PS") groupID := os.Getenv("ATLAS_GROUP") api := NewKey(publicKey, privateKey) // api.SetVerbose(testing.Verbose()) if doc, err = api.GetCluster(groupID, clusterName); err != nil { t.Fatal(err) } if data, err = json.Marshal(doc); err != nil { t.Fatal(err) } os.Mkdir("./out", 0755) ofile := fmt.Sprintf(`./out/cluster-%v.json`, clusterName) if err = ioutil.WriteFile(ofile, data, 0644); err != nil { t.Fatal(err) } }
package cmd import "github.com/spf13/cobra" var sortFlag *string var listCmd = &cobra.Command{ Use: "list", Short: "list all tasks", Args: cobra.NoArgs, Run: func(cmd *cobra.Command, args []string) { if cmd.Flags().Changed("sort") { todoController.List(sortFlag) } else { todoController.List(nil) } }, } func init() { rootCmd.AddCommand(listCmd) sortFlag = listCmd.Flags().StringP("sort", "s", "", "list all tasks alphabetically in [asc|desc] order") }
package main import ( "fmt" "math/rand" "time" ) // Operation based heartbeat func GenerateNumbers(done <-chan struct{}, numbers ...int) (<-chan struct{}, <-chan interface{}) { heartbeat := make(chan struct{}, 1) stream := make(chan interface{}) go func() { defer close(heartbeat) defer close(stream) for _, number := range numbers { fmt.Println("About to process: ", number) select { case heartbeat <- struct{}{}: default: } select { case <-done: break case stream <- number: break } } }() return heartbeat, stream } func OperationHeartbeats() { done := make(chan struct{}) heartbeatStream, numberStream := GenerateNumbers(done, 1, 2, 3, 4, 5) outer: for { select { case _, open := <-heartbeatStream: if open { fmt.Println("pulse") } case number, open := <-numberStream: if !open { break outer } fmt.Println("Number: ", number) case <-time.After(time.Millisecond): fmt.Println("Ending prematurely due to delays in heartbeats") close(done) } } } func PerformHeavyComputation(done <-chan struct{}, pulseInterval time.Duration) (<-chan struct{}, <-chan interface{}) { resultStream := make(chan interface{}) heartbeat := make(chan struct{}) go func() { defer close(resultStream) t := time.NewTicker(pulseInterval) expensiveOperation := time.After(time.Duration(rand.Intn(1000))*time.Millisecond + 3*time.Second) sentHeartbeat := false for { select { case <-t.C: if !sentHeartbeat { sentHeartbeat = true select { case heartbeat <- struct{}{}: default: } } case <-done: return case <-expensiveOperation: for { select { case <-done: return case resultStream <- "result": case <-t.C: select { case heartbeat <- struct{}{}: default: } } } } } }() return heartbeat, resultStream } func main() { done := make(chan struct{}) timeout := time.Second * 2 heartbeat, resultStream := PerformHeavyComputation(done, time.Millisecond*200) loop: for { select { case <-heartbeat: fmt.Println("pulse") case <-time.After(timeout): fmt.Println("Preempting due to hearbeat failure") break loop case <-resultStream: fmt.Println("Got result") break loop } } close(done) }
// 自动生成模板TitTopic package model import ( "github.com/jinzhu/gorm" ) type TitTopic struct { gorm.Model Title string `json:"title" form:"title" ` TopicType int `json:"topicType" form:"topicType" ` BusinessType int `json:"businessType" form:"businessType" ` IsRequired int `json:"isRequired" form:"isRequired" ` IsScored int `json:"isScored" form:"isScored" ` Order int `json:"order" form:"order" ` SurveyLatitude string `json:"surveyLatitude" form:"surveyLatitude"` Score string `json:"score" form:"score"` TitTopicOptions []TitTopicOption `json:"options" form:"options"` TitTopicRelatedList []TitTopicRelated `json:"titTopicRelatedList" form:"titTopicRelatedList"` }
// Copyright (c) 2013 - Max Persson <max@looplab.se> // // 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 fsm import ( "context" "errors" "fmt" "sort" "sync" "testing" "time" ) type fakeTransitionerObj struct { } func (t fakeTransitionerObj) transition(f *FSM) error { return &InternalError{} } func TestSameState(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "start"}, }, Callbacks{}, ) _ = fsm.Event(context.Background(), "run") if fsm.Current() != "start" { t.Error("expected state to be 'start'") } } func TestSetState(t *testing.T) { fsm := NewFSM( "walking", Events{ {Name: "walk", Src: []string{"start"}, Dst: "walking"}, }, Callbacks{}, ) fsm.SetState("start") if fsm.Current() != "start" { t.Error("expected state to be 'walking'") } err := fsm.Event(context.Background(), "walk") if err != nil { t.Error("transition is expected no error") } } func TestBadTransition(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "running"}, }, Callbacks{}, ) fsm.transitionerObj = new(fakeTransitionerObj) err := fsm.Event(context.Background(), "run") if err == nil { t.Error("bad transition should give an error") } } func TestInappropriateEvent(t *testing.T) { fsm := NewFSM( "closed", Events{ {Name: "open", Src: []string{"closed"}, Dst: "open"}, {Name: "close", Src: []string{"open"}, Dst: "closed"}, }, Callbacks{}, ) err := fsm.Event(context.Background(), "close") if e, ok := err.(InvalidEventError); !ok && e.Event != "close" && e.State != "closed" { t.Error("expected 'InvalidEventError' with correct state and event") } } func TestInvalidEvent(t *testing.T) { fsm := NewFSM( "closed", Events{ {Name: "open", Src: []string{"closed"}, Dst: "open"}, {Name: "close", Src: []string{"open"}, Dst: "closed"}, }, Callbacks{}, ) err := fsm.Event(context.Background(), "lock") if e, ok := err.(UnknownEventError); !ok && e.Event != "close" { t.Error("expected 'UnknownEventError' with correct event") } } func TestMultipleSources(t *testing.T) { fsm := NewFSM( "one", Events{ {Name: "first", Src: []string{"one"}, Dst: "two"}, {Name: "second", Src: []string{"two"}, Dst: "three"}, {Name: "reset", Src: []string{"one", "two", "three"}, Dst: "one"}, }, Callbacks{}, ) err := fsm.Event(context.Background(), "first") if err != nil { t.Errorf("transition failed %v", err) } if fsm.Current() != "two" { t.Error("expected state to be 'two'") } err = fsm.Event(context.Background(), "reset") if err != nil { t.Errorf("transition failed %v", err) } if fsm.Current() != "one" { t.Error("expected state to be 'one'") } err = fsm.Event(context.Background(), "first") if err != nil { t.Errorf("transition failed %v", err) } err = fsm.Event(context.Background(), "second") if err != nil { t.Errorf("transition failed %v", err) } if fsm.Current() != "three" { t.Error("expected state to be 'three'") } err = fsm.Event(context.Background(), "reset") if err != nil { t.Errorf("transition failed %v", err) } if fsm.Current() != "one" { t.Error("expected state to be 'one'") } } func TestMultipleEvents(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "first", Src: []string{"start"}, Dst: "one"}, {Name: "second", Src: []string{"start"}, Dst: "two"}, {Name: "reset", Src: []string{"one"}, Dst: "reset_one"}, {Name: "reset", Src: []string{"two"}, Dst: "reset_two"}, {Name: "reset", Src: []string{"reset_one", "reset_two"}, Dst: "start"}, }, Callbacks{}, ) err := fsm.Event(context.Background(), "first") if err != nil { t.Errorf("transition failed %v", err) } err = fsm.Event(context.Background(), "reset") if err != nil { t.Errorf("transition failed %v", err) } if fsm.Current() != "reset_one" { t.Error("expected state to be 'reset_one'") } err = fsm.Event(context.Background(), "reset") if err != nil { t.Errorf("transition failed %v", err) } if fsm.Current() != "start" { t.Error("expected state to be 'start'") } err = fsm.Event(context.Background(), "second") if err != nil { t.Errorf("transition failed %v", err) } err = fsm.Event(context.Background(), "reset") if err != nil { t.Errorf("transition failed %v", err) } if fsm.Current() != "reset_two" { t.Error("expected state to be 'reset_two'") } err = fsm.Event(context.Background(), "reset") if err != nil { t.Errorf("transition failed %v", err) } if fsm.Current() != "start" { t.Error("expected state to be 'start'") } } func TestGenericCallbacks(t *testing.T) { beforeEvent := false leaveState := false enterState := false afterEvent := false fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "before_event": func(_ context.Context, e *Event) { beforeEvent = true }, "leave_state": func(_ context.Context, e *Event) { leaveState = true }, "enter_state": func(_ context.Context, e *Event) { enterState = true }, "after_event": func(_ context.Context, e *Event) { afterEvent = true }, }, ) err := fsm.Event(context.Background(), "run") if err != nil { t.Errorf("transition failed %v", err) } if !(beforeEvent && leaveState && enterState && afterEvent) { t.Error("expected all callbacks to be called") } } func TestSpecificCallbacks(t *testing.T) { beforeEvent := false leaveState := false enterState := false afterEvent := false fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "before_run": func(_ context.Context, e *Event) { beforeEvent = true }, "leave_start": func(_ context.Context, e *Event) { leaveState = true }, "enter_end": func(_ context.Context, e *Event) { enterState = true }, "after_run": func(_ context.Context, e *Event) { afterEvent = true }, }, ) err := fsm.Event(context.Background(), "run") if err != nil { t.Errorf("transition failed %v", err) } if !(beforeEvent && leaveState && enterState && afterEvent) { t.Error("expected all callbacks to be called") } } func TestSpecificCallbacksShortform(t *testing.T) { enterState := false afterEvent := false fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "end": func(_ context.Context, e *Event) { enterState = true }, "run": func(_ context.Context, e *Event) { afterEvent = true }, }, ) err := fsm.Event(context.Background(), "run") if err != nil { t.Errorf("transition failed %v", err) } if !(enterState && afterEvent) { t.Error("expected all callbacks to be called") } } func TestBeforeEventWithoutTransition(t *testing.T) { beforeEvent := true fsm := NewFSM( "start", Events{ {Name: "dontrun", Src: []string{"start"}, Dst: "start"}, }, Callbacks{ "before_event": func(_ context.Context, e *Event) { beforeEvent = true }, }, ) err := fsm.Event(context.Background(), "dontrun") if e, ok := err.(NoTransitionError); !ok && e.Err != nil { t.Error("expected 'NoTransitionError' without custom error") } if fsm.Current() != "start" { t.Error("expected state to be 'start'") } if !beforeEvent { t.Error("expected callback to be called") } } func TestCancelBeforeGenericEvent(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "before_event": func(_ context.Context, e *Event) { e.Cancel() }, }, ) _ = fsm.Event(context.Background(), "run") if fsm.Current() != "start" { t.Error("expected state to be 'start'") } } func TestCancelBeforeSpecificEvent(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "before_run": func(_ context.Context, e *Event) { e.Cancel() }, }, ) _ = fsm.Event(context.Background(), "run") if fsm.Current() != "start" { t.Error("expected state to be 'start'") } } func TestCancelLeaveGenericState(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "leave_state": func(_ context.Context, e *Event) { e.Cancel() }, }, ) _ = fsm.Event(context.Background(), "run") if fsm.Current() != "start" { t.Error("expected state to be 'start'") } } func TestCancelLeaveSpecificState(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "leave_start": func(_ context.Context, e *Event) { e.Cancel() }, }, ) _ = fsm.Event(context.Background(), "run") if fsm.Current() != "start" { t.Error("expected state to be 'start'") } } func TestCancelWithError(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "before_event": func(_ context.Context, e *Event) { e.Cancel(fmt.Errorf("error")) }, }, ) err := fsm.Event(context.Background(), "run") if _, ok := err.(CanceledError); !ok { t.Error("expected only 'CanceledError'") } if e, ok := err.(CanceledError); ok && e.Err.Error() != "error" { t.Error("expected 'CanceledError' with correct custom error") } if fsm.Current() != "start" { t.Error("expected state to be 'start'") } } func TestAsyncTransitionGenericState(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "leave_state": func(_ context.Context, e *Event) { e.Async() }, }, ) _ = fsm.Event(context.Background(), "run") if fsm.Current() != "start" { t.Error("expected state to be 'start'") } err := fsm.Transition() if err != nil { t.Errorf("transition failed %v", err) } if fsm.Current() != "end" { t.Error("expected state to be 'end'") } } func TestAsyncTransitionSpecificState(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "leave_start": func(_ context.Context, e *Event) { e.Async() }, }, ) _ = fsm.Event(context.Background(), "run") if fsm.Current() != "start" { t.Error("expected state to be 'start'") } err := fsm.Transition() if err != nil { t.Errorf("transition failed %v", err) } if fsm.Current() != "end" { t.Error("expected state to be 'end'") } } func TestAsyncTransitionInProgress(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, {Name: "reset", Src: []string{"end"}, Dst: "start"}, }, Callbacks{ "leave_start": func(_ context.Context, e *Event) { e.Async() }, }, ) _ = fsm.Event(context.Background(), "run") err := fsm.Event(context.Background(), "reset") if e, ok := err.(InTransitionError); !ok && e.Event != "reset" { t.Error("expected 'InTransitionError' with correct state") } err = fsm.Transition() if err != nil { t.Errorf("transition failed %v", err) } err = fsm.Event(context.Background(), "reset") if err != nil { t.Errorf("transition failed %v", err) } if fsm.Current() != "start" { t.Error("expected state to be 'start'") } } func TestAsyncTransitionNotInProgress(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, {Name: "reset", Src: []string{"end"}, Dst: "start"}, }, Callbacks{}, ) err := fsm.Transition() if _, ok := err.(NotInTransitionError); !ok { t.Error("expected 'NotInTransitionError'") } } func TestCancelAsyncTransition(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "leave_start": func(_ context.Context, e *Event) { e.Async() }, }, ) err := fsm.Event(context.Background(), "run") asyncError, ok := err.(AsyncError) if !ok { t.Errorf("expected error to be 'AsyncError', got %v", err) } var asyncStateTransitionWasCanceled = make(chan struct{}) go func() { <-asyncError.Ctx.Done() close(asyncStateTransitionWasCanceled) }() asyncError.CancelTransition() <-asyncStateTransitionWasCanceled if err = fsm.Transition(); err != nil { t.Errorf("expected no error, got %v", err) } if fsm.Current() != "start" { t.Error("expected state to be 'start'") } } func TestCallbackNoError(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "run": func(_ context.Context, e *Event) { }, }, ) e := fsm.Event(context.Background(), "run") if e != nil { t.Error("expected no error") } } func TestCallbackError(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "run": func(_ context.Context, e *Event) { e.Err = fmt.Errorf("error") }, }, ) e := fsm.Event(context.Background(), "run") if e.Error() != "error" { t.Error("expected error to be 'error'") } } func TestCallbackArgs(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "run": func(_ context.Context, e *Event) { if len(e.Args) != 1 { t.Error("too few arguments") } arg, ok := e.Args[0].(string) if !ok { t.Error("not a string argument") } if arg != "test" { t.Error("incorrect argument") } }, }, ) err := fsm.Event(context.Background(), "run", "test") if err != nil { t.Errorf("transition failed %v", err) } } func TestCallbackPanic(t *testing.T) { panicMsg := "unexpected panic" defer func() { r := recover() if r == nil || r != panicMsg { t.Errorf("expected panic message to be '%s', got %v", panicMsg, r) } }() fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "run": func(_ context.Context, e *Event) { panic(panicMsg) }, }, ) e := fsm.Event(context.Background(), "run") if e.Error() != "error" { t.Error("expected error to be 'error'") } } func TestNoDeadLock(t *testing.T) { var fsm *FSM fsm = NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "run": func(_ context.Context, e *Event) { fsm.Current() // Should not result in a panic / deadlock }, }, ) err := fsm.Event(context.Background(), "run") if err != nil { t.Errorf("transition failed %v", err) } } func TestThreadSafetyRaceCondition(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "run": func(_ context.Context, e *Event) { }, }, ) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() _ = fsm.Current() }() err := fsm.Event(context.Background(), "run") if err != nil { t.Errorf("transition failed %v", err) } wg.Wait() } func TestDoubleTransition(t *testing.T) { var fsm *FSM var wg sync.WaitGroup wg.Add(2) fsm = NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, }, Callbacks{ "before_run": func(_ context.Context, e *Event) { wg.Done() // Imagine a concurrent event coming in of the same type while // the data access mutex is unlocked because the current transition // is running its event callbacks, getting around the "active" // transition checks if len(e.Args) == 0 { // Must be concurrent so the test may pass when we add a mutex that synchronizes // calls to Event(...). It will then fail as an inappropriate transition as we // have changed state. go func() { if err := fsm.Event(context.Background(), "run", "second run"); err != nil { fmt.Println(err) wg.Done() // It should fail, and then we unfreeze the test. } }() time.Sleep(20 * time.Millisecond) } else { panic("Was able to reissue an event mid-transition") } }, }, ) if err := fsm.Event(context.Background(), "run"); err != nil { fmt.Println(err) } wg.Wait() } func TestTransitionInCallbacks(t *testing.T) { var fsm *FSM var afterFinishCalled bool fsm = NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, {Name: "finish", Src: []string{"end"}, Dst: "finished"}, {Name: "reset", Src: []string{"end", "finished"}, Dst: "start"}, }, Callbacks{ "enter_end": func(ctx context.Context, e *Event) { if err := e.FSM.Event(ctx, "finish"); err != nil { fmt.Println(err) } }, "after_finish": func(ctx context.Context, e *Event) { afterFinishCalled = true if e.Src != "end" { panic(fmt.Sprintf("source should have been 'end' but was '%s'", e.Src)) } if err := e.FSM.Event(ctx, "reset"); err != nil { fmt.Println(err) } }, }, ) if err := fsm.Event(context.Background(), "run"); err != nil { t.Errorf("expected no error, got %v", err) } if !afterFinishCalled { t.Error("expected after_finish callback to have been executed but it wasn't") } currentState := fsm.Current() if currentState != "start" { t.Errorf("expected state to be 'start', was '%s'", currentState) } } func TestContextInCallbacks(t *testing.T) { var fsm *FSM var enterEndAsyncWorkDone = make(chan struct{}) fsm = NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "end"}, {Name: "finish", Src: []string{"end"}, Dst: "finished"}, {Name: "reset", Src: []string{"end", "finished"}, Dst: "start"}, }, Callbacks{ "enter_end": func(ctx context.Context, e *Event) { go func() { <-ctx.Done() close(enterEndAsyncWorkDone) }() <-ctx.Done() if err := e.FSM.Event(ctx, "finish"); err != nil { e.Err = fmt.Errorf("transitioning to the finished state failed: %w", err) } }, }, ) ctx, cancel := context.WithCancel(context.Background()) go func() { cancel() }() err := fsm.Event(ctx, "run") if !errors.Is(err, context.Canceled) { t.Errorf("expected 'context canceled' error, got %v", err) } <-enterEndAsyncWorkDone currentState := fsm.Current() if currentState != "end" { t.Errorf("expected state to be 'end', was '%s'", currentState) } } func TestNoTransition(t *testing.T) { fsm := NewFSM( "start", Events{ {Name: "run", Src: []string{"start"}, Dst: "start"}, }, Callbacks{}, ) err := fsm.Event(context.Background(), "run") if _, ok := err.(NoTransitionError); !ok { t.Error("expected 'NoTransitionError'") } } func ExampleNewFSM() { fsm := NewFSM( "green", Events{ {Name: "warn", Src: []string{"green"}, Dst: "yellow"}, {Name: "panic", Src: []string{"yellow"}, Dst: "red"}, {Name: "panic", Src: []string{"green"}, Dst: "red"}, {Name: "calm", Src: []string{"red"}, Dst: "yellow"}, {Name: "clear", Src: []string{"yellow"}, Dst: "green"}, }, Callbacks{ "before_warn": func(_ context.Context, e *Event) { fmt.Println("before_warn") }, "before_event": func(_ context.Context, e *Event) { fmt.Println("before_event") }, "leave_green": func(_ context.Context, e *Event) { fmt.Println("leave_green") }, "leave_state": func(_ context.Context, e *Event) { fmt.Println("leave_state") }, "enter_yellow": func(_ context.Context, e *Event) { fmt.Println("enter_yellow") }, "enter_state": func(_ context.Context, e *Event) { fmt.Println("enter_state") }, "after_warn": func(_ context.Context, e *Event) { fmt.Println("after_warn") }, "after_event": func(_ context.Context, e *Event) { fmt.Println("after_event") }, }, ) fmt.Println(fsm.Current()) err := fsm.Event(context.Background(), "warn") if err != nil { fmt.Println(err) } fmt.Println(fsm.Current()) // Output: // green // before_warn // before_event // leave_green // leave_state // enter_yellow // enter_state // after_warn // after_event // yellow } func ExampleFSM_Current() { fsm := NewFSM( "closed", Events{ {Name: "open", Src: []string{"closed"}, Dst: "open"}, {Name: "close", Src: []string{"open"}, Dst: "closed"}, }, Callbacks{}, ) fmt.Println(fsm.Current()) // Output: closed } func ExampleFSM_Is() { fsm := NewFSM( "closed", Events{ {Name: "open", Src: []string{"closed"}, Dst: "open"}, {Name: "close", Src: []string{"open"}, Dst: "closed"}, }, Callbacks{}, ) fmt.Println(fsm.Is("closed")) fmt.Println(fsm.Is("open")) // Output: // true // false } func ExampleFSM_Can() { fsm := NewFSM( "closed", Events{ {Name: "open", Src: []string{"closed"}, Dst: "open"}, {Name: "close", Src: []string{"open"}, Dst: "closed"}, }, Callbacks{}, ) fmt.Println(fsm.Can("open")) fmt.Println(fsm.Can("close")) // Output: // true // false } func ExampleFSM_AvailableTransitions() { fsm := NewFSM( "closed", Events{ {Name: "open", Src: []string{"closed"}, Dst: "open"}, {Name: "close", Src: []string{"open"}, Dst: "closed"}, {Name: "kick", Src: []string{"closed"}, Dst: "broken"}, }, Callbacks{}, ) // sort the results ordering is consistent for the output checker transitions := fsm.AvailableTransitions() sort.Strings(transitions) fmt.Println(transitions) // Output: // [kick open] } func ExampleFSM_Cannot() { fsm := NewFSM( "closed", Events{ {Name: "open", Src: []string{"closed"}, Dst: "open"}, {Name: "close", Src: []string{"open"}, Dst: "closed"}, }, Callbacks{}, ) fmt.Println(fsm.Cannot("open")) fmt.Println(fsm.Cannot("close")) // Output: // false // true } func ExampleFSM_Event() { fsm := NewFSM( "closed", Events{ {Name: "open", Src: []string{"closed"}, Dst: "open"}, {Name: "close", Src: []string{"open"}, Dst: "closed"}, }, Callbacks{}, ) fmt.Println(fsm.Current()) err := fsm.Event(context.Background(), "open") if err != nil { fmt.Println(err) } fmt.Println(fsm.Current()) err = fsm.Event(context.Background(), "close") if err != nil { fmt.Println(err) } fmt.Println(fsm.Current()) // Output: // closed // open // closed } func ExampleFSM_Transition() { fsm := NewFSM( "closed", Events{ {Name: "open", Src: []string{"closed"}, Dst: "open"}, {Name: "close", Src: []string{"open"}, Dst: "closed"}, }, Callbacks{ "leave_closed": func(_ context.Context, e *Event) { e.Async() }, }, ) err := fsm.Event(context.Background(), "open") if e, ok := err.(AsyncError); !ok && e.Err != nil { fmt.Println(err) } fmt.Println(fsm.Current()) err = fsm.Transition() if err != nil { fmt.Println(err) } fmt.Println(fsm.Current()) // Output: // closed // open }
package g2util import ( "bytes" "fmt" "io" "os" "os/exec" "strings" ) // ItfExec ... type ItfExec interface { Start() error Run() error Output() ([]byte, error) CombinedOutput() ([]byte, error) } // StdExec ... func StdExec(s string) ItfExec { return NewExecInner(s, os.Stdout) } // NewExecInner ... func NewExecInner(s string, out io.Writer) ItfExec { cmd := exec.Command("/bin/sh", "-c", s) return &execInner{cmd: cmd, out: out} } var ( _ ItfExec = &exec.Cmd{} _ ItfExec = &execInner{} ) type execInner struct { cmd *exec.Cmd out io.Writer } // setOut ... func (e *execInner) setOut() { e.cmd.Stdout = e.out; e.cmd.Stderr = e.out } func (e *execInner) Start() error { e.setOut(); return e.cmd.Start() } func (e *execInner) Run() error { e.setOut(); return e.cmd.Run() } func (e *execInner) Output() ([]byte, error) { return e.cmd.Output() } func (e *execInner) CombinedOutput() ([]byte, error) { return e.cmd.CombinedOutput() } //#------------------------------------------------------------------------------------------------------------------# // FindPidSliceByProcessName get pid list func FindPidSliceByProcessName(name string) []string { str := `ps -ef|grep -v grep|grep '{name}'|awk '{print $2}'|tr -s '\n'` p, _ := StdExec(strings.Replace(str, "{name}", name, -1)).Output() ps := strings.Split(string(bytes.TrimSpace(p)), "\n") return ps } // ProcessIsRunning is running func ProcessIsRunning(name string) bool { ps := FindPidSliceByProcessName(name) return len(ps) > 0 && len(ps[0]) > 0 } // KillProcess ...kill process func KillProcess(name string) (err error) { if !ProcessIsRunning(name) { return fmt.Errorf("process[%s] is not running", name) } ps := FindPidSliceByProcessName(name) for _, pid := range ps { _ = StdExec(fmt.Sprintf("kill %s", pid)).Run() } return }
package main import ( "bytes" "encoding/json" "io/ioutil" "net/http" ) const apiURL = "https://api.kamergotchi.nl/game" // GameAPI does the network communcation to the kamergotchi API type GameAPI struct { playerToken string } // GetGameInfo gets the current state of the game func (api *GameAPI) GetGameInfo() (Game, error) { res, err := apiRequest("/", "GET", api.playerToken, nil) if err != nil { return Game{}, err } return parseGame(res) } // SpendCare spends care on the kamergotchi func (api *GameAPI) SpendCare(careType string) (Game, error) { body, _ := json.Marshal(map[string]string{"bar": careType}) res, err := apiRequest("/care", "POST", api.playerToken, body) if err != nil { return Game{}, err } return parseGame(res) } // ClaimReward claims a reward func (api *GameAPI) ClaimReward() (Game, error) { res, err := apiRequest("/claim", "POST", api.playerToken, nil) if err != nil { return Game{}, err } return parseGame(res) } func parseGame(res []byte) (Game, error) { var info map[string]Game if err := json.Unmarshal(res, &info); err != nil { return Game{}, err } return info["game"], nil } func apiRequest(path string, method string, playerToken string, body []byte) ([]byte, error) { client := http.Client{} req, err := http.NewRequest(method, apiURL+path, bytes.NewBuffer(body)) if err != nil { return nil, err } req.Header.Add("x-player-token", playerToken) req.Header.Add("Content-Type", "application/json") res, err := client.Do(req) if err != nil { return nil, err } defer res.Body.Close() resBody, err := ioutil.ReadAll(res.Body) if err != nil { return resBody, err } return resBody, nil }
package backend import ( "google.golang.org/appengine/datastore" "time" ) type dbModel struct { key *datastore.Key `json:"-" datastore:"-"` parentKey *datastore.Key `json:"-" datastore:"-"` created time.Time } func (m *dbModel) Key() *datastore.Key { return m.key } type sessionModel struct { dbModel ended time.Time } type boardStateModel struct { dbModel lastModified time.Time } type playerModel struct { dbModel Name string Location string Hand []cardModel } type cardModel struct { dbModel Name string Color string }
package main import ( "bufio" "container/list" "fmt" "log" "os" "strconv" "strings" "github.com/RyanCarrier/dijkstra" ) type cell struct { underlying cellType erosionLevel int } type cellType byte func (c cellType) String() string { return fmt.Sprintf("%s", string(c)) } type toolType byte const ( Wet cellType = '=' Rocky cellType = '.' Narrow cellType = '|' Torch toolType = iota Climb Neither input = "day22/input.txt" //input = "day22/test.txt" ) func main() { file, err := os.Open(input) check(err) defer file.Close() ls := list.New() readAll(file, ls) line1 := ls.Front() depth, err := strconv.Atoi(strings.Split(line1.Value.(string), " ")[1]) check(err) line2coords := strings.Split(line1.Next().Value.(string), " ") coords := strings.Split(line2coords[1], ",") targetX, err := strconv.Atoi(coords[0]) check(err) targetY, err := strconv.Atoi(coords[1]) check(err) fmt.Printf("Depth is %v, target is @ %v,%v\n", depth, targetX, targetY) maxX := targetX + 50 maxY := targetY + 50 field := make([]*cell, maxX*maxY) calculateField(field, depth, targetX, targetY, maxX, maxY) //printState(field, targetX, targetY, maxX, maxY) //fmt.Printf("Solution to part 1 (risk level) is: %v\n", riskLevel(0, 0, targetX, targetY, field, maxX, maxY)) createGraph(field, targetX, targetY, maxX, maxY) //solution := part1(field) //fmt.Printf("Solution for part 1 is: %v\n", solution) //fmt.Printf("Solution for part 2 is: %v\n", part2()) } func createGraph(cells []*cell, targetX, targetY, maxX int, maxY int) { graph := dijkstra.NewGraph() for y := 0; y < maxY; y++ { for x := 0; x < maxX; x++ { types := allowedTypes[cells[linear(x, y, maxX, maxY)].underlying] for _, t := range types { graph.AddVertex(linear3d(x, y, t, maxX, maxY)) } t0 := linear3d(x, y, types[0], maxX, maxY) t1 := linear3d(x, y, types[1], maxX, maxY) check(graph.AddArc(t0, t1, 7)) check(graph.AddArc(t1, t0, 7)) } } for y := 0; y < maxY-1; y++ { for x := 0; x < maxX-1; x++ { for _, t := range allowedTypes[cells[linear(x, y, maxX, maxY)].underlying] { vertexCur := linear3d(x, y, t, maxX, maxY) for _, tr := range allowedTypes[cells[linear(x+1, y, maxX, maxY)].underlying] { vertexRight := linear3d(x+1, y, tr, maxX, maxY) if t == tr { check(graph.AddArc(vertexCur, vertexRight, 1)) check(graph.AddArc(vertexRight, vertexCur, 1)) } } for _, tb := range allowedTypes[cells[linear(x, y+1, maxX, maxY)].underlying] { vertexDown := linear3d(x, y+1, tb, maxX, maxY) if t == tb { check(graph.AddArc(vertexCur, vertexDown, 1)) check(graph.AddArc(vertexDown, vertexCur, 1)) } } } } } path, err := graph.Shortest(linear3d(0, 0, Torch, maxX, maxY), linear3d(targetX, targetY, Torch, maxX, maxY)) check(err) fmt.Printf("Path price: %v\n", path.Distance) //last := -1 //for _, p := range path.Path { // x, y := breakLinear3D(p, maxX, maxY) // var price int64 = 0 // var ok bool // if last != -1 { // price, ok = graph.Verticies[last].GetArc(p) // if !ok { // log.Fatalf("Programming error, expected arc to exist") // } // } // fmt.Printf("Path: %v, %v (price=%v)\n", x, y, price) // last = p //} } var allowedTypes = map[cellType][2]toolType{ Wet: {Climb, Neither}, Rocky: {Climb, Torch}, Narrow: {Torch, Neither}, } func breakLinear3D(id int, maxX, maxY int) (x int, y int) { return id % maxX, id % (maxX * maxY) / maxX } func riskLevel(x1 int, y1 int, x2 int, y2 int, cells []*cell, maxX, maxY int) int { totalRisk := 0 for x := x1; x <= x2; x++ { for y := y1; y <= y2; y++ { switch cells[linear(x, y, maxX, maxY)].underlying { case Wet: totalRisk += 1 case Narrow: totalRisk += 2 } } } return totalRisk } func calculateField(cells []*cell, depth, targetX, targetY int, maxX int, maxY int) { for y := 0; y < maxY; y++ { for x := 0; x < maxX; x++ { var geologicIndex int if (x == 0 && y == 0) || (x == targetX && y == targetY) { geologicIndex = 0 } else if y == 0 { geologicIndex = 16807 * x } else if x == 0 { geologicIndex = 48271 * y } else { erosionLevel1 := cells[linear(x-1, y, maxX, maxY)].erosionLevel erosionLevel2 := cells[linear(x, y-1, maxX, maxY)].erosionLevel geologicIndex = erosionLevel1 * erosionLevel2 } erosionLevel := (geologicIndex + depth) % 20183 switch erosionLevel % 3 { case 0: cells[linear(x, y, maxX, maxY)] = &cell{underlying: Rocky, erosionLevel: erosionLevel} case 1: cells[linear(x, y, maxX, maxY)] = &cell{underlying: Wet, erosionLevel: erosionLevel} case 2: cells[linear(x, y, maxX, maxY)] = &cell{underlying: Narrow, erosionLevel: erosionLevel} } } } } func check(err error) { if err != nil { log.Fatal(err) } } func readAll(file *os.File, list *list.List) { scanner := bufio.NewScanner(file) for scanner.Scan() { val := scanner.Text() list.PushBack(val) } if err := scanner.Err(); err != nil { log.Fatal(err) } } func linear(x int, y int, maxX, maxY int) int { scaled := x + y*maxX if x >= maxX { log.Fatalf("Tried to access %v,%v", x, y) } if y >= maxY { log.Fatalf("Tried to access %v,%v", x, y) } return scaled } func linear3d(x int, y int, tool toolType, maxX, maxY int) int { scaled := x + y*maxX + maxX*maxY*int(tool) if x >= maxX { log.Fatalf("Tried to access %v,%v", x, y) } if y >= maxY { log.Fatalf("Tried to access %v,%v", x, y) } return scaled } func printState(track []*cell, targetX, targetY int, maxX, maxY int) { for y := 0; y < maxY; y++ { for x := 0; x < maxX; x++ { if x == 0 && y == 0 { fmt.Print("M") } else if x == targetX && y == targetY { fmt.Print("T") } else { c := track[linear(x, y, maxX, maxY)] fmt.Printf("%v", c.underlying) } } fmt.Println() } fmt.Printf("\n") }
package enums const ( BasePath = "/api/yellow/v1" SignIn = "/signin" SignUp = "/signup" GetUsers = "/users" GetUserById = "/users/:id" UpdateUserById = "/users/:id" DeleteUserById = "/users/:id" GetTweets = "/tweets" CreateTweets = "/tweets" GetTweetById = "/tweets/:id" UpdateTweetById = "/tweets/:id" DeleteTweetById = "/tweets/:id/user/:userId" )
package proxy type SchemaType string const ( SchemaHTTP SchemaType = "http://" SchemaHTTPS SchemaType = "https://" HTTP_METHOD_GET = "GET" HTTP_METHOD_POST = "POST" CONTENT_TYPE_JSON = "application/json" CONTENT_TYPE_FORM = "application/x-www-form-urlencoded" CONTENT_TYPE_XML = "application/xml" HEADER_CONTENT_TYPE = "Content-Type" HEADER_CONTENT_KEY = "key" ) // 配置文件 type Config struct { ProxySchema SchemaType // SchemaHTTP or SchemaHTTPS ProxyHost string // 转发到的接口 Host ProxyPort string // 转发到的接口 Port ServerPort string // 代理转发服务启动的端口 Key string // 简单的校验Key }
package material import ( "github.com/mikee385/GolangRayTracer/color" ) type Material struct { Color color.ColorRGB Diffuse float32 Specular float32 Shininess int Reflection float32 Refraction float32 RefractiveIndex float32 } func NewMaterial(color color.ColorRGB) Material { return Material{ Color: color, Diffuse: 1.0, Specular: 0.0, Shininess: 0, Reflection: 0.0, Refraction: 0.0, RefractiveIndex: 0.0, } } type MaterialBuilder interface { Color(color color.ColorRGB) MaterialBuilder Diffuse(diffuse float32) MaterialBuilder Specular(specular float32) MaterialBuilder Shininess(shininess int) MaterialBuilder Reflection(reflection float32) MaterialBuilder Refraction(refraction float32) MaterialBuilder RefractiveIndex(refractiveIndex float32) MaterialBuilder ToMaterial() Material } type materialBuilder struct { color color.ColorRGB diffuse float32 specular float32 shininess int reflection float32 refraction float32 refractiveIndex float32 } func NewBuilder() MaterialBuilder { return &materialBuilder{ color: color.White(), diffuse: 1.0, specular: 0.0, shininess: 0, reflection: 0.0, refraction: 0.0, refractiveIndex: 0.0, } } func (builder *materialBuilder) Color(color color.ColorRGB) MaterialBuilder { builder.color = color return builder } func (builder *materialBuilder) Diffuse(diffuse float32) MaterialBuilder { builder.diffuse = diffuse return builder } func (builder *materialBuilder) Specular(specular float32) MaterialBuilder { builder.specular = specular return builder } func (builder *materialBuilder) Shininess(shininess int) MaterialBuilder { builder.shininess = shininess return builder } func (builder *materialBuilder) Reflection(reflection float32) MaterialBuilder { builder.reflection = reflection return builder } func (builder *materialBuilder) Refraction(refraction float32) MaterialBuilder { builder.refraction = refraction return builder } func (builder *materialBuilder) RefractiveIndex(refractiveIndex float32) MaterialBuilder { builder.refractiveIndex = refractiveIndex return builder } func (builder materialBuilder) ToMaterial() Material { return Material{ Color: builder.color, Diffuse: builder.diffuse, Specular: builder.specular, Shininess: builder.shininess, Reflection: builder.reflection, Refraction: builder.refraction, RefractiveIndex: builder.refractiveIndex, } }
package ssh import ( "testing" ) func TestRun(t *testing.T) { output, error, err := Run("localhost:22", "canux", "canux", "who") if err != nil { t.Error("failed") } else { t.Log(output) t.Log(error) } }
package validator import ( "fmt" "os" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/authelia/authelia/v4/internal/configuration/schema" ) const unexistingFilePath = "/tmp/unexisting_file" func TestShouldSetDefaultServerValues(t *testing.T) { validator := schema.NewStructValidator() config := &schema.Configuration{} ValidateServer(config, validator) assert.Len(t, validator.Errors(), 0) assert.Len(t, validator.Warnings(), 0) assert.Equal(t, schema.DefaultServerConfiguration.Address, config.Server.Address) assert.Equal(t, schema.DefaultServerConfiguration.Buffers.Read, config.Server.Buffers.Read) assert.Equal(t, schema.DefaultServerConfiguration.Buffers.Write, config.Server.Buffers.Write) assert.Equal(t, schema.DefaultServerConfiguration.TLS.Key, config.Server.TLS.Key) assert.Equal(t, schema.DefaultServerConfiguration.TLS.Certificate, config.Server.TLS.Certificate) assert.Equal(t, schema.DefaultServerConfiguration.Endpoints.EnableExpvars, config.Server.Endpoints.EnableExpvars) assert.Equal(t, schema.DefaultServerConfiguration.Endpoints.EnablePprof, config.Server.Endpoints.EnablePprof) assert.Equal(t, schema.DefaultServerConfiguration.Endpoints.Authz, config.Server.Endpoints.Authz) assert.Equal(t, "", config.Server.Host) //nolint:staticcheck assert.Equal(t, 0, config.Server.Port) //nolint:staticcheck assert.Equal(t, "", config.Server.Path) //nolint:staticcheck } func TestShouldSetDefaultServerValuesWithLegacyAddress(t *testing.T) { testCases := []struct { name string have schema.Server expected schema.Address }{ { "ShouldParseAll", schema.Server{ Host: "abc", Port: 123, Path: "subpath", }, MustParseAddress("tcp://abc:123/subpath"), }, { "ShouldParseHostAndPort", schema.Server{ Host: "abc", Port: 123, }, MustParseAddress("tcp://abc:123/"), }, { "ShouldParseHostAndPath", schema.Server{ Host: "abc", Path: "subpath", }, MustParseAddress("tcp://abc:9091/subpath"), }, { "ShouldParsePortAndPath", schema.Server{ Port: 123, Path: "subpath", }, MustParseAddress("tcp://:123/subpath"), }, { "ShouldParseHost", schema.Server{ Host: "abc", }, MustParseAddress("tcp://abc:9091/"), }, { "ShouldParsePort", schema.Server{ Port: 123, }, MustParseAddress("tcp://:123/"), }, { "ShouldParsePath", schema.Server{ Path: "subpath", }, MustParseAddress("tcp://:9091/subpath"), }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { validator := schema.NewStructValidator() config := &schema.Configuration{ Server: tc.have, } ValidateServer(config, validator) assert.Len(t, validator.Errors(), 0) assert.Len(t, validator.Warnings(), 0) assert.Equal(t, &schema.AddressTCP{Address: tc.expected}, config.Server.Address) }) } } func TestShouldSetDefaultConfig(t *testing.T) { validator := schema.NewStructValidator() config := &schema.Configuration{} ValidateServer(config, validator) assert.Len(t, validator.Errors(), 0) assert.Len(t, validator.Warnings(), 0) assert.Equal(t, schema.DefaultServerConfiguration.Buffers.Read, config.Server.Buffers.Read) assert.Equal(t, schema.DefaultServerConfiguration.Buffers.Write, config.Server.Buffers.Write) } func TestValidateSeverAddress(t *testing.T) { config := &schema.Configuration{ Server: schema.Server{ Address: &schema.AddressTCP{Address: MustParseAddress("tcp://:9091/path/")}, }, } validator := schema.NewStructValidator() ValidateServer(config, validator) require.Len(t, validator.Errors(), 1) assert.Len(t, validator.Warnings(), 0) assert.EqualError(t, validator.Errors()[0], "server: option 'address' must not and with a forward slash but it's configured as '/path/'") } func TestValidateServerShouldCorrectlyIdentifyValidAddressSchemes(t *testing.T) { testCases := []struct { have string expected string }{ {schema.AddressSchemeTCP, ""}, {schema.AddressSchemeTCP4, ""}, {schema.AddressSchemeTCP6, ""}, {schema.AddressSchemeUDP, "server: option 'address' with value 'udp://:9091' is invalid: scheme must be one of 'tcp', 'tcp4', 'tcp6', or 'unix' but is configured as 'udp'"}, {schema.AddressSchemeUDP4, "server: option 'address' with value 'udp4://:9091' is invalid: scheme must be one of 'tcp', 'tcp4', 'tcp6', or 'unix' but is configured as 'udp4'"}, {schema.AddressSchemeUDP6, "server: option 'address' with value 'udp6://:9091' is invalid: scheme must be one of 'tcp', 'tcp4', 'tcp6', or 'unix' but is configured as 'udp6'"}, {schema.AddressSchemeUnix, ""}, {"http", "server: option 'address' with value 'http://:9091' is invalid: scheme must be one of 'tcp', 'tcp4', 'tcp6', or 'unix' but is configured as 'http'"}, } have := &schema.Configuration{ Server: schema.Server{ Buffers: schema.ServerBuffers{ Read: -1, Write: -1, }, Timeouts: schema.ServerTimeouts{ Read: time.Second * -1, Write: time.Second * -1, Idle: time.Second * -1, }, }, } validator := schema.NewStructValidator() for _, tc := range testCases { t.Run(tc.have, func(t *testing.T) { validator.Clear() switch tc.have { case schema.AddressSchemeUnix: have.Server.Address = &schema.AddressTCP{Address: schema.NewAddressUnix("/path/to/authelia.sock")} default: have.Server.Address = &schema.AddressTCP{Address: schema.NewAddressFromNetworkValues(tc.have, "", 9091)} } ValidateServer(have, validator) assert.Len(t, validator.Warnings(), 0) if tc.expected == "" { assert.Len(t, validator.Errors(), 0) } else { require.Len(t, validator.Errors(), 1) assert.EqualError(t, validator.Errors()[0], tc.expected) } }) } } func TestShouldDefaultOnNegativeValues(t *testing.T) { validator := schema.NewStructValidator() config := &schema.Configuration{ Server: schema.Server{ Buffers: schema.ServerBuffers{ Read: -1, Write: -1, }, Timeouts: schema.ServerTimeouts{ Read: time.Second * -1, Write: time.Second * -1, Idle: time.Second * -1, }, }, } ValidateServer(config, validator) require.Len(t, validator.Errors(), 0) assert.Equal(t, schema.DefaultServerConfiguration.Buffers.Read, config.Server.Buffers.Read) assert.Equal(t, schema.DefaultServerConfiguration.Buffers.Write, config.Server.Buffers.Write) assert.Equal(t, schema.DefaultServerConfiguration.Timeouts.Read, config.Server.Timeouts.Read) assert.Equal(t, schema.DefaultServerConfiguration.Timeouts.Write, config.Server.Timeouts.Write) assert.Equal(t, schema.DefaultServerConfiguration.Timeouts.Idle, config.Server.Timeouts.Idle) } func TestShouldRaiseOnNonAlphanumericCharsInPath(t *testing.T) { validator := schema.NewStructValidator() config := &schema.Configuration{ Server: schema.Server{ Path: "app le", }, } ValidateServer(config, validator) require.Len(t, validator.Errors(), 1) assert.Error(t, validator.Errors()[0], "server path must only be alpha numeric characters") } func TestShouldRaiseOnForwardSlashInPath(t *testing.T) { validator := schema.NewStructValidator() config := &schema.Configuration{ Server: schema.Server{ Path: "app/le", }, } ValidateServer(config, validator) assert.Len(t, validator.Errors(), 1) assert.Error(t, validator.Errors()[0], "server path must not contain any forward slashes") } func TestShouldValidateAndUpdateAddress(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultConfig() config.Server.Address = nil ValidateServer(&config, validator) require.Len(t, validator.Errors(), 0) assert.Equal(t, "tcp://:9091/", config.Server.Address.String()) } func TestShouldRaiseErrorOnLegacyAndModernValues(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultConfig() config.Server.Host = local25 //nolint:staticcheck config.Server.Port = 9999 //nolint:staticcheck ValidateServer(&config, validator) require.Len(t, validator.Errors(), 1) assert.EqualError(t, validator.Errors()[0], "server: option 'host' and 'port' can't be configured at the same time as 'address'") } func TestShouldRaiseErrorWhenTLSCertWithoutKeyIsProvided(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultConfig() file, err := os.CreateTemp("", "cert") require.NoError(t, err) defer os.Remove(file.Name()) config.Server.TLS.Certificate = file.Name() ValidateServer(&config, validator) require.Len(t, validator.Errors(), 1) assert.EqualError(t, validator.Errors()[0], "server: tls: option 'certificate' must also be accompanied by option 'key'") } func TestShouldRaiseErrorWhenTLSCertDoesNotExist(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultConfig() file, err := os.CreateTemp("", "key") require.NoError(t, err) defer os.Remove(file.Name()) config.Server.TLS.Certificate = unexistingFilePath config.Server.TLS.Key = file.Name() ValidateServer(&config, validator) require.Len(t, validator.Errors(), 1) assert.EqualError(t, validator.Errors()[0], "server: tls: option 'certificate' with path '/tmp/unexisting_file' refers to a file that doesn't exist") } func TestShouldRaiseErrorWhenTLSKeyWithoutCertIsProvided(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultConfig() file, err := os.CreateTemp("", "key") require.NoError(t, err) defer os.Remove(file.Name()) config.Server.TLS.Key = file.Name() ValidateServer(&config, validator) require.Len(t, validator.Errors(), 1) assert.EqualError(t, validator.Errors()[0], "server: tls: option 'key' must also be accompanied by option 'certificate'") } func TestShouldRaiseErrorWhenTLSKeyDoesNotExist(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultConfig() file, err := os.CreateTemp("", "key") require.NoError(t, err) defer os.Remove(file.Name()) config.Server.TLS.Key = unexistingFilePath config.Server.TLS.Certificate = file.Name() ValidateServer(&config, validator) require.Len(t, validator.Errors(), 1) assert.EqualError(t, validator.Errors()[0], "server: tls: option 'key' with path '/tmp/unexisting_file' refers to a file that doesn't exist") } func TestShouldNotRaiseErrorWhenBothTLSCertificateAndKeyAreProvided(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultConfig() certFile, err := os.CreateTemp("", "cert") require.NoError(t, err) defer os.Remove(certFile.Name()) keyFile, err := os.CreateTemp("", "key") require.NoError(t, err) defer os.Remove(keyFile.Name()) config.Server.TLS.Certificate = certFile.Name() config.Server.TLS.Key = keyFile.Name() ValidateServer(&config, validator) require.Len(t, validator.Errors(), 0) } func TestShouldRaiseErrorWhenTLSClientCertificateDoesNotExist(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultConfig() certFile, err := os.CreateTemp("", "cert") require.NoError(t, err) defer os.Remove(certFile.Name()) keyFile, err := os.CreateTemp("", "key") require.NoError(t, err) defer os.Remove(keyFile.Name()) config.Server.TLS.Certificate = certFile.Name() config.Server.TLS.Key = keyFile.Name() config.Server.TLS.ClientCertificates = []string{"/tmp/unexisting"} ValidateServer(&config, validator) require.Len(t, validator.Errors(), 1) assert.EqualError(t, validator.Errors()[0], "server: tls: option 'client_certificates' with path '/tmp/unexisting' refers to a file that doesn't exist") } func TestShouldRaiseErrorWhenTLSClientAuthIsDefinedButNotServerCertificate(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultConfig() certFile, err := os.CreateTemp("", "cert") require.NoError(t, err) defer os.Remove(certFile.Name()) config.Server.TLS.ClientCertificates = []string{certFile.Name()} ValidateServer(&config, validator) require.Len(t, validator.Errors(), 1) assert.EqualError(t, validator.Errors()[0], "server: tls: client authentication cannot be configured if no server certificate and key are provided") } func TestShouldNotUpdateConfig(t *testing.T) { validator := schema.NewStructValidator() config := newDefaultConfig() ValidateServer(&config, validator) require.Len(t, validator.Errors(), 0) assert.Equal(t, "tcp://127.0.0.1:9090/", config.Server.Address.String()) } func TestServerEndpointsDevelShouldWarn(t *testing.T) { config := &schema.Configuration{ Server: schema.Server{ Endpoints: schema.ServerEndpoints{ EnablePprof: true, EnableExpvars: true, }, }, } validator := schema.NewStructValidator() ValidateServer(config, validator) require.Len(t, validator.Warnings(), 2) assert.Len(t, validator.Errors(), 0) assert.EqualError(t, validator.Warnings()[0], "server: endpoints: option 'enable_expvars' should not be enabled in production") assert.EqualError(t, validator.Warnings()[1], "server: endpoints: option 'enable_pprof' should not be enabled in production") } func TestServerAuthzEndpointErrors(t *testing.T) { testCases := []struct { name string have map[string]schema.ServerEndpointsAuthz errs []string }{ {"ShouldAllowDefaultEndpoints", schema.DefaultServerConfiguration.Endpoints.Authz, nil}, {"ShouldAllowSetDefaultEndpoints", nil, nil}, { "ShouldErrorOnInvalidEndpointImplementations", map[string]schema.ServerEndpointsAuthz{ "example": {Implementation: "zero"}, }, []string{ "server: endpoints: authz: example: option 'implementation' must be one of 'AuthRequest', 'ForwardAuth', 'ExtAuthz', or 'Legacy' but it's configured as 'zero'", }, }, { "ShouldErrorOnInvalidEndpointImplementationLegacy", map[string]schema.ServerEndpointsAuthz{ "legacy": {Implementation: "zero"}, }, []string{ "server: endpoints: authz: legacy: option 'implementation' must be one of 'AuthRequest', 'ForwardAuth', 'ExtAuthz', or 'Legacy' but it's configured as 'zero'", }, }, { "ShouldErrorOnInvalidEndpointLegacyImplementation", map[string]schema.ServerEndpointsAuthz{ "legacy": {Implementation: "ExtAuthz"}, }, []string{"server: endpoints: authz: legacy: option 'implementation' is invalid: the endpoint with the name 'legacy' must use the 'Legacy' implementation"}, }, { "ShouldErrorOnInvalidAuthnStrategies", map[string]schema.ServerEndpointsAuthz{ "example": {Implementation: "ExtAuthz", AuthnStrategies: []schema.ServerEndpointsAuthzAuthnStrategy{{Name: "bad-name"}}}, }, []string{ "server: endpoints: authz: example: authn_strategies: option 'name' must be one of 'CookieSession', 'HeaderAuthorization', 'HeaderProxyAuthorization', 'HeaderAuthRequestProxyAuthorization', or 'HeaderLegacy' but it's configured as 'bad-name'", }, }, { "ShouldErrorOnDuplicateName", map[string]schema.ServerEndpointsAuthz{ "example": {Implementation: "ExtAuthz", AuthnStrategies: []schema.ServerEndpointsAuthzAuthnStrategy{{Name: "CookieSession"}, {Name: "CookieSession"}}}, }, []string{"server: endpoints: authz: example: authn_strategies: duplicate strategy name detected with name 'CookieSession'"}, }, { "ShouldErrorOnInvalidChars", map[string]schema.ServerEndpointsAuthz{ "/abc": {Implementation: "ForwardAuth"}, "/abc/": {Implementation: "ForwardAuth"}, "abc/": {Implementation: "ForwardAuth"}, "1abc": {Implementation: "ForwardAuth"}, "1abc1": {Implementation: "ForwardAuth"}, "abc1": {Implementation: "ForwardAuth"}, "-abc": {Implementation: "ForwardAuth"}, "-abc-": {Implementation: "ForwardAuth"}, "abc-": {Implementation: "ForwardAuth"}, }, []string{ "server: endpoints: authz: -abc: contains invalid characters", "server: endpoints: authz: -abc-: contains invalid characters", "server: endpoints: authz: /abc: contains invalid characters", "server: endpoints: authz: /abc/: contains invalid characters", "server: endpoints: authz: 1abc: contains invalid characters", "server: endpoints: authz: 1abc1: contains invalid characters", "server: endpoints: authz: abc-: contains invalid characters", "server: endpoints: authz: abc/: contains invalid characters", "server: endpoints: authz: abc1: contains invalid characters", }, }, { "ShouldErrorOnEndpointsWithDuplicatePrefix", map[string]schema.ServerEndpointsAuthz{ "apple": {Implementation: "ForwardAuth"}, "apple/abc": {Implementation: "ForwardAuth"}, "pear/abc": {Implementation: "ExtAuthz"}, "pear": {Implementation: "ExtAuthz"}, "another": {Implementation: "ExtAuthz"}, "another/test": {Implementation: "ForwardAuth"}, "anotherb/test": {Implementation: "ForwardAuth"}, "anothe": {Implementation: "ExtAuthz"}, "anotherc/test": {Implementation: "ForwardAuth"}, "anotherc": {Implementation: "ExtAuthz"}, "anotherd/test": {Implementation: "ForwardAuth"}, "anotherd": {Implementation: "Legacy"}, "anothere/test": {Implementation: "ExtAuthz"}, "anothere": {Implementation: "ExtAuthz"}, }, []string{ "server: endpoints: authz: another/test: endpoint starts with the same prefix as the 'another' endpoint with the 'ExtAuthz' implementation which accepts prefixes as part of its implementation", "server: endpoints: authz: anotherc/test: endpoint starts with the same prefix as the 'anotherc' endpoint with the 'ExtAuthz' implementation which accepts prefixes as part of its implementation", "server: endpoints: authz: anotherd/test: endpoint starts with the same prefix as the 'anotherd' endpoint with the 'Legacy' implementation which accepts prefixes as part of its implementation", "server: endpoints: authz: anothere/test: endpoint starts with the same prefix as the 'anothere' endpoint with the 'ExtAuthz' implementation which accepts prefixes as part of its implementation", "server: endpoints: authz: pear/abc: endpoint starts with the same prefix as the 'pear' endpoint with the 'ExtAuthz' implementation which accepts prefixes as part of its implementation", }, }, } validator := schema.NewStructValidator() for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { validator.Clear() config := newDefaultConfig() config.Server.Endpoints.Authz = tc.have ValidateServerEndpoints(&config, validator) if tc.errs == nil { assert.Len(t, validator.Warnings(), 0) assert.Len(t, validator.Errors(), 0) } else { require.Len(t, validator.Errors(), len(tc.errs)) for i, expected := range tc.errs { assert.EqualError(t, validator.Errors()[i], expected) } } }) } } func TestServerAuthzEndpointLegacyAsImplementationLegacyWhenBlank(t *testing.T) { have := map[string]schema.ServerEndpointsAuthz{ "legacy": {}, } config := newDefaultConfig() config.Server.Endpoints.Authz = have validator := schema.NewStructValidator() ValidateServerEndpoints(&config, validator) assert.Len(t, validator.Warnings(), 0) assert.Len(t, validator.Errors(), 0) assert.Equal(t, authzImplementationLegacy, config.Server.Endpoints.Authz[legacy].Implementation) } func TestValidateTLSPathStatInvalidArgument(t *testing.T) { val := schema.NewStructValidator() validateServerTLSFileExists("key", string([]byte{0x0, 0x1}), val) require.Len(t, val.Errors(), 1) assert.EqualError(t, val.Errors()[0], "server: tls: option 'key' with path '\x00\x01' could not be verified due to a file system error: stat \x00\x01: invalid argument") } func TestValidateTLSPathIsDir(t *testing.T) { dir := t.TempDir() val := schema.NewStructValidator() validateServerTLSFileExists("key", dir, val) require.Len(t, val.Errors(), 1) assert.EqualError(t, val.Errors()[0], fmt.Sprintf("server: tls: option 'key' with path '%s' refers to a directory but it should refer to a file", dir)) }
package classic import ( "encoding/json" "errors" "testing" ) var tasks = []struct { listRaw []byte }{ { listRaw: []byte(`{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}`), }, { listRaw: []byte(`{}`), }, } func makeLinkedListByJSON(raw []byte) (*ListNode, error) { list := new(ListNode) if err := json.Unmarshal(raw, list); err != nil { return nil, err } // empty ListNode if list.ID == "" { return nil, nil } var head, np *ListNode M := make(map[string]*ListNode) for p := list; p != nil; p = p.Next { M[p.ID] = p if np == nil { head, np = p, p } else { np.Next = p np = np.Next } } for p := head; p != nil; p = p.Next { if p.Random != nil { ref, ok := M[p.Random.Ref] if !ok { return nil, errors.New("random lost ref") } p.Random = ref } } return head, nil } func Test_makeLinkedListByJSON(t *testing.T) { for _, task := range tasks { list, err := makeLinkedListByJSON(task.listRaw) if err != nil { t.Fatal(err) } for p := list; p != nil; p = p.Next { t.Logf("Val: %d, Address: %p", p.Val, p) if p.Next != nil { t.Logf("Next: %+v", p.Next) } if p.Random != nil { t.Logf("Random: %+v", p.Random) } } } } func Test_copyRandomList(t *testing.T) { for fIdx, f := range []func(*ListNode) *ListNode{copyRandomList} { for i, task := range tasks { h1, err := makeLinkedListByJSON(task.listRaw) if err != nil { t.Fatal(err) } h2 := f(h1) // check M1, M2 := make(map[*ListNode]int), make(map[*ListNode]int) for idx, p1, p2 := -0, h1, h2; p1 != nil && p2 != nil; idx, p1, p2 = idx+1, p1.Next, p2.Next { M1[p1], M2[p2] = idx, idx } for p1, p2 := h1, h2; p1 != nil && p2 != nil; p1, p2 = p1.Next, p2.Next { if p1 == p2 { t.Errorf("func #%d, task #%d failed, two lists have sharded node", fIdx, i) } if p1.Val != p2.Val { t.Errorf("func #%d, task #%d failed, value not match, got: %d, expect: %d", fIdx, i, p2.Val, p1.Val) } if p1.Random == nil { if p2.Random != nil { t.Errorf("func #%d, task #%d failed, wrong random, got: %+v, expect: %+v", fIdx, i, p2.Random, p1.Random) } } else { if idx1, idx2 := M1[p1.Random], M2[p2.Random]; idx1 != idx2 { t.Errorf("func #%d, task #%d failed, wrong random index, got: %+v, expect: %+v", fIdx, i, idx2, idx1) } } } } } }
package main import ( "log" "strings" irc "github.com/thoj/go-ircevent" ) func ircOnCommand(e *irc.Event) { parts := strings.SplitN(e.Message(), " ", 2) switch parts[0] { case "!quit": if len(parts) > 1 { app.irc.QuitMessage = strings.TrimPrefix(e.Message(), parts[1]) } app.irc.Quit() case "!join": app.irc.Join(parts[1]) case "!part": app.irc.Part(parts[1]) default: log.Printf("Uknown command %v", parts) } }
package reports import ( "net/url" "strconv" ) const ( // ReportExportSBOMEndpoint is the endpoint for generating SBOMs ReportExportSBOMEndpoint = "v1/report/getSBOM" ) // Standard is a string enum of supported SBOM standards type Standard string // Encoding is a string enum of supported file/data encoding standards type Encoding string const ( // StandardUnknown denotes that the Standard is unknown StandardUnknown Standard = "unknown" // EncodingUnknown denotes that the Encoding is unknown EncodingUnknown Encoding = "unknown" // StandardCycloneDX indicates that the SBOM adheres to the CycloneDX standard StandardCycloneDX Standard = "CycloneDX" // StandardIonChannel indicates that the SBOM adheres to the Ion Channel standard StandardIonChannel Standard = "IonChannel" // StandardSPDX indicates that the SBOM adheres to the SPDX standard StandardSPDX Standard = "SPDX" // EncodingCSV indicates that the SBOM is stored in CSV format EncodingCSV Encoding = "CSV" // EncodingJSON indicates that the SBOM is stored in JSON format EncodingJSON Encoding = "JSON" // EncodingTagValue indicates that the SBOM is stored in tag-value format EncodingTagValue Encoding = "tag-value" // EncodingXLSX indicates that the SBOM is stored in XLSX format EncodingXLSX Encoding = "XLSX" // EncodingXML indicates that the SBOM is stored in XML format EncodingXML Encoding = "XML" // EncodingYAML indicates that the SBOM is stored in YAML format EncodingYAML Encoding = "YAML" ) // SBOMExportOptions represents all the different settings a user can specify for how the SBOM is exported. // Specify only one of the following data sources to generate the SBOM from: // * ProjectIDs (a slice of one or more project IDs) // * TeamID (the ID of a team containing one or more projects; this will use all the team's projects) // * SoftwareListID (the ID of a software list containing one or more components; this will use all the list's components) // * ComponentIDs (a slice of one or more software list component IDs) // Format (required) specifies which format/standard the SBOM will be exported in. // IncludeDependencies will include all the direct and transitive dependencies of each item in the SBOM if true, // or exclude all the dependencies if false, leaving only the items themselves. // TeamIsTopLevel applies only to SBOMs generated using the TeamID field. If true, the top-level item in the SBOM's // hierarchy will be the team. If false, all the team's projects will be on the top level of the hierarchy. type SBOMExportOptions struct { ProjectIDs []string `json:"ids"` TeamID string `json:"team_id"` SoftwareListID string `json:"sbom_id"` ComponentIDs []string `json:"sbom_entry_ids"` Standard Standard `json:"sbom_type"` Encoding Encoding `json:"encoding"` IncludeDependencies bool `json:"include_dependencies"` TeamIsTopLevel bool `json:"team_top_level"` } // Params converts an SBOMExportOptions object into a URL param object for use in making an API request func (options SBOMExportOptions) Params() url.Values { params := url.Values{} params.Set("sbom_type", string(options.Standard)) params.Set("encoding", string(options.Encoding)) params.Set("include_dependencies", strconv.FormatBool(options.IncludeDependencies)) params.Set("team_top_level", strconv.FormatBool(options.TeamIsTopLevel)) return params }
package stats import ( mapset "github.com/deckarep/golang-set" "github.com/idena-network/idena-go/blockchain" "github.com/idena-network/idena-go/blockchain/types" "github.com/idena-network/idena-go/common" "github.com/idena-network/idena-go/common/math" "github.com/idena-network/idena-go/core/appstate" "github.com/idena-network/idena-go/stats/collector" statsTypes "github.com/idena-network/idena-go/stats/types" "github.com/idena-network/idena-indexer/core/conversion" "github.com/idena-network/idena-indexer/db" "github.com/shopspring/decimal" "math/big" ) type statsCollector struct { stats *Stats invitationRewardsByAddrAndType map[common.Address]map[RewardType]*RewardStats } func NewStatsCollector() collector.StatsCollector { return &statsCollector{} } func (c *statsCollector) EnableCollecting() { c.stats = &Stats{} } func (c *statsCollector) initRewardStats() { if c.stats.RewardsStats != nil { return } c.stats.RewardsStats = &RewardsStats{} } func (c *statsCollector) initInvitationRewardsByAddrAndType() { if c.invitationRewardsByAddrAndType != nil { return } c.invitationRewardsByAddrAndType = make(map[common.Address]map[RewardType]*RewardStats) } func (c *statsCollector) SetValidation(validation *statsTypes.ValidationStats) { c.stats.ValidationStats = validation } func (c *statsCollector) SetAuthors(authors *types.ValidationAuthors) { c.initRewardStats() c.stats.RewardsStats.Authors = authors } func (c *statsCollector) SetTotalReward(amount *big.Int) { c.initRewardStats() c.stats.RewardsStats.Total = amount } func (c *statsCollector) SetTotalValidationReward(amount *big.Int) { c.initRewardStats() c.stats.RewardsStats.Validation = amount } func (c *statsCollector) SetTotalFlipsReward(amount *big.Int) { c.initRewardStats() c.stats.RewardsStats.Flips = amount } func (c *statsCollector) SetTotalInvitationsReward(amount *big.Int) { c.initRewardStats() c.stats.RewardsStats.Invitations = amount } func (c *statsCollector) SetTotalFoundationPayouts(amount *big.Int) { c.initRewardStats() c.stats.RewardsStats.FoundationPayouts = amount } func (c *statsCollector) SetTotalZeroWalletFund(amount *big.Int) { c.initRewardStats() c.stats.RewardsStats.ZeroWalletFund = amount } func (c *statsCollector) AddValidationReward(addr common.Address, age uint16, balance *big.Int, stake *big.Int) { c.addReward(addr, balance, stake, Validation) if c.stats.RewardsStats.AgesByAddress == nil { c.stats.RewardsStats.AgesByAddress = make(map[string]uint16) } c.stats.RewardsStats.AgesByAddress[conversion.ConvertAddress(addr)] = age + 1 } func (c *statsCollector) AddFlipsReward(addr common.Address, balance *big.Int, stake *big.Int) { c.addReward(addr, balance, stake, Flips) } func (c *statsCollector) AddInvitationsReward(addr common.Address, balance *big.Int, stake *big.Int, age uint16) { var rewardType RewardType switch age { case 1: rewardType = Invitations case 2: rewardType = Invitations2 case 3: rewardType = Invitations3 default: return } c.addReward(addr, balance, stake, rewardType) } func (c *statsCollector) AddFoundationPayout(addr common.Address, balance *big.Int) { c.addReward(addr, balance, nil, FoundationPayouts) } func (c *statsCollector) AddZeroWalletFund(addr common.Address, balance *big.Int) { c.addReward(addr, balance, nil, ZeroWalletFund) } func (c *statsCollector) addReward(addr common.Address, balance *big.Int, stake *big.Int, rewardType RewardType) { if (balance == nil || balance.Sign() == 0) && (stake == nil || stake.Sign() == 0) { return } c.initRewardStats() rewardsStats := &RewardStats{ Address: addr, Balance: balance, Stake: stake, Type: rewardType, } if c.increaseInvitationRewardIfExists(rewardsStats) { return } c.stats.RewardsStats.Rewards = append(c.stats.RewardsStats.Rewards, rewardsStats) } func (c *statsCollector) increaseInvitationRewardIfExists(rewardsStats *RewardStats) bool { if rewardsStats.Type != Invitations && rewardsStats.Type != Invitations2 && rewardsStats.Type != Invitations3 { return false } c.initInvitationRewardsByAddrAndType() addrInvitationRewardsByType, ok := c.invitationRewardsByAddrAndType[rewardsStats.Address] if ok { if ir, ok := addrInvitationRewardsByType[rewardsStats.Type]; ok { ir.Balance.Add(ir.Balance, rewardsStats.Balance) ir.Stake.Add(ir.Stake, rewardsStats.Stake) return true } } else { addrInvitationRewardsByType = make(map[RewardType]*RewardStats) } addrInvitationRewardsByType[rewardsStats.Type] = rewardsStats c.invitationRewardsByAddrAndType[rewardsStats.Address] = addrInvitationRewardsByType return false } func (c *statsCollector) AddProposerReward(addr common.Address, balance *big.Int, stake *big.Int) { c.addMiningReward(addr, balance, stake, true) } func (c *statsCollector) AddFinalCommitteeReward(addr common.Address, balance *big.Int, stake *big.Int) { c.addMiningReward(addr, balance, stake, false) c.stats.FinalCommittee = append(c.stats.FinalCommittee, addr) } func (c *statsCollector) addMiningReward(addr common.Address, balance *big.Int, stake *big.Int, isProposerReward bool) { c.stats.MiningRewards = append(c.stats.MiningRewards, &db.MiningReward{ Address: conversion.ConvertAddress(addr), Balance: blockchain.ConvertToFloat(balance), Stake: blockchain.ConvertToFloat(stake), Proposer: isProposerReward, }) } func (c *statsCollector) AfterSubPenalty(addr common.Address, amount *big.Int, appState *appstate.AppState) { if amount == nil || amount.Sign() != 1 { return } c.detectAndCollectCompletedPenalty(addr, appState) } func (c *statsCollector) detectAndCollectCompletedPenalty(addr common.Address, appState *appstate.AppState) { updatedPenalty := appState.State.GetPenalty(addr) if updatedPenalty != nil && updatedPenalty.Sign() == 1 { return } c.initBurntPenaltiesByAddr() c.stats.BurntPenaltiesByAddr[addr] = updatedPenalty } func (c *statsCollector) BeforeClearPenalty(addr common.Address, appState *appstate.AppState) { c.detectAndCollectBurntPenalty(addr, appState) } func (c *statsCollector) BeforeSetPenalty(addr common.Address, appState *appstate.AppState) { c.detectAndCollectBurntPenalty(addr, appState) } func (c *statsCollector) detectAndCollectBurntPenalty(addr common.Address, appState *appstate.AppState) { curPenalty := appState.State.GetPenalty(addr) if curPenalty == nil || curPenalty.Sign() != 1 { return } c.initBurntPenaltiesByAddr() c.stats.BurntPenaltiesByAddr[addr] = curPenalty } func (c *statsCollector) initBurntPenaltiesByAddr() { if c.stats.BurntPenaltiesByAddr != nil { return } c.stats.BurntPenaltiesByAddr = make(map[common.Address]*big.Int) } func (c *statsCollector) AddMintedCoins(amount *big.Int) { if amount == nil { return } if c.stats.MintedCoins == nil { c.stats.MintedCoins = big.NewInt(0) } c.stats.MintedCoins.Add(c.stats.MintedCoins, amount) } func (c *statsCollector) addBurntCoins(addr common.Address, amount *big.Int, reason db.BurntCoinsReason, tx *types.Transaction) { if amount == nil || amount.Sign() == 0 { return } if c.stats.BurntCoins == nil { c.stats.BurntCoins = big.NewInt(0) } if c.stats.BurntCoinsByAddr == nil { c.stats.BurntCoinsByAddr = make(map[common.Address][]*db.BurntCoins) } c.stats.BurntCoins.Add(c.stats.BurntCoins, amount) var txHash string if tx != nil { txHash = tx.Hash().Hex() } c.stats.BurntCoinsByAddr[addr] = append(c.stats.BurntCoinsByAddr[addr], &db.BurntCoins{ Amount: blockchain.ConvertToFloat(amount), Reason: reason, TxHash: txHash, }) } func (c *statsCollector) AddPenaltyBurntCoins(addr common.Address, amount *big.Int) { c.addBurntCoins(addr, amount, db.PenaltyBurntCoins, nil) } func (c *statsCollector) AddInviteBurntCoins(addr common.Address, amount *big.Int, tx *types.Transaction) { c.addBurntCoins(addr, amount, db.InviteBurntCoins, tx) } func (c *statsCollector) AddFeeBurntCoins(addr common.Address, feeAmount *big.Int, burntRate float32, tx *types.Transaction) { if feeAmount == nil || feeAmount.Sign() == 0 { return } burntFee := decimal.NewFromBigInt(feeAmount, 0) burntFee = burntFee.Mul(decimal.NewFromFloat32(burntRate)) c.addBurntCoins(addr, math.ToInt(burntFee), db.FeeBurntCoins, tx) } func (c *statsCollector) AddKilledBurntCoins(addr common.Address, amount *big.Int) { c.addBurntCoins(addr, amount, db.KilledBurntCoins, nil) } func (c *statsCollector) AddBurnTxBurntCoins(addr common.Address, tx *types.Transaction) { c.addBurntCoins(addr, tx.AmountOrZero(), db.BurnTxBurntCoins, tx) } func (c *statsCollector) AfterBalanceUpdate(addr common.Address, appState *appstate.AppState) { c.initBalanceUpdatesByAddr() c.stats.BalanceUpdateAddrs.Add(addr) } func (c *statsCollector) initBalanceUpdatesByAddr() { if c.stats.BalanceUpdateAddrs != nil { return } c.stats.BalanceUpdateAddrs = mapset.NewSet() } func (c *statsCollector) GetStats() *Stats { return c.stats } func (c *statsCollector) CompleteCollecting() { c.stats = nil c.invitationRewardsByAddrAndType = nil } func (c *statsCollector) AfterKillIdentity(addr common.Address, appState *appstate.AppState) { c.initKilledAddrs() c.stats.KilledAddrs.Add(addr) } func (c *statsCollector) initKilledAddrs() { if c.stats.KilledAddrs != nil { return } c.stats.KilledAddrs = mapset.NewSet() } func (c *statsCollector) AfterAddStake(addr common.Address, amount *big.Int) { if c.stats.KilledAddrs == nil || !c.stats.KilledAddrs.Contains(addr) { return } c.addBurntCoins(addr, amount, db.KilledBurntCoins, nil) }
package main import ( "flag" "log" "math/rand" "net/http" "strconv" "time" "github.com/rbxb/signedcookie" ) var port string func init() { flag.StringVar(&port, "port", ":8080", "The port to listen at.") } func main() { flag.Parse() rand.Seed(time.Now().Unix()) http.HandleFunc("/", serve) log.Fatal(http.ListenAndServe(port, nil)) } // Responds with a random number or the value stored in the client's cookie. func serve(w http.ResponseWriter, req *http.Request) { if b, ok := signedcookie.DefaultSigner.Verify(req, "example"); ok { // If a cookie exists, send it back to the client w.Write(b) } else { // or generate a number and set it to a cookie. n := rand.Int() b := []byte(strconv.Itoa(n)) signedcookie.DefaultSigner.SetCookie(w, "example", b, time.Now().Add(time.Hour)) w.Write(b) } }
package model import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" ) // GetSVC get DynamoDB SVC func GetSVC() (*dynamodb.DynamoDB, error) { session, err := session.NewSession( &aws.Config{Region: aws.String("ap-northeast-1")}, ) if err != nil { return nil, err } svc := dynamodb.New(session) return svc, nil } // User DynamoDB Resut User Struct type User struct { ID string Email *string DisplayName string Career *string AvatarURI *string Message *string } // Work DynamoDB Result Work Struct type Work struct { ID string UserID string Title string Tags *[]string ImageURL *string Description string CreatedAt string }
/** * User: Baoxu * Date: 13-5-16 * Time: 下午4:07 */ package main import ( "net/http" "log" "html/template" "fmt" ) /** * 自定义类型,路由控制器 * 根据URI中不同的地址,执行不同的函数 */ type Router struct { } /** * 路由控制器指定路由之后的处理函数 * 如果是请求根目录,执行此函数 */ func serverDefault(w http.ResponseWriter, r *http.Request) { fmt.Println("method:", r.Method) //获取请求的方法 //解析模板 t, err := template.ParseFiles("tmpl/html/index.html") if (err != nil) { log.Println(err) } p := Person{UserName: "我是内部成员变量"} //执行模板,合并变量并输出 t.Execute(w, p) } /*******************************************************************/ /* 主执行函数,主要作为端口监听服务器 */ /*******************************************************************/ func main() { //设置访问路由 http.Handle("/css/", http.FileServer(http.Dir("tmpl"))) http.Handle("/js/", http.FileServer(http.Dir("tmpl"))) //设置控制器路由 http.HandleFunc("/", serverDefault) //设置监听的端口 err := http.ListenAndServe(":9000", nil) if err != nil { log.Fatal("ListenAndServer: ", err) } }
package auth import ( "net/url" "reflect" "testing" ) func testParse(t *testing.T, header string, fixture Challenge) { challenge, err := ParseChallenge(header) if err != nil { return } if expected, actual := fixture.realm.String(), challenge.realm.String(); expected != actual { t.Fatalf("realm failed to parse; got %s, expected %s", actual, expected) } if expected, actual := fixture.service, challenge.service; expected != actual { t.Fatalf("service failed to parse; got %s, expected %s", actual, expected) } if expected, actual := fixture.scope, challenge.scope; !reflect.DeepEqual(expected, actual) { t.Fatalf("challenge failed to parse; got %v, expected %v", actual, expected) } } func testAuthUrl(t *testing.T, header, scheme, host, path string, scopes []string) { challenge, err := ParseChallenge(header) if err != nil { t.Fatal(err) } authUrl := challenge.buildRequestUrl() if expected, actual := scheme, authUrl.Scheme; expected != actual { t.Fatalf("auth URL scheme not constructed correctly; got %s, expected %s", actual, expected) } if expected, actual := host, authUrl.Host; expected != actual { t.Fatalf("auth URL host not constructed correctly; got %s, expected %s", actual, expected) } if expected, actual := path, authUrl.Path; expected != actual { t.Fatalf("auth URL path not constructed correctly; got %s, expected %s", actual, expected) } if expected, actual := scopes, authUrl.Query()["scope"]; !reflect.DeepEqual(expected, actual) { t.Fatalf("auth URL schemes not constructed correctly; got %v, expected %v", actual, expected) } } func TestSimple(t *testing.T) { testcase := `Bearer realm="https://auth.docker.io/token",service="registry.docker.io",scope="repository:samalba/my-app:pull,push"` fixtureUrl, _ := url.Parse("https://auth.docker.io/token") testParse(t, testcase, Challenge{ realm: fixtureUrl, service: "registry.docker.io", scope: []string{ "repository:samalba/my-app:pull,push", }, }) testAuthUrl(t, testcase, "https", "auth.docker.io", "/token", []string{ "repository:samalba/my-app:pull,push", }) } func TestHeaderPort(t *testing.T) { testcase := `Bearer realm="https://auth.docker.io:8888/token",service="registry.docker.io:9999",scope="repository:samalba/my-app:pull,push"` fixtureUrl, _ := url.Parse("https://auth.docker.io:8888/token") testParse(t, testcase, Challenge{ realm: fixtureUrl, service: "registry.docker.io:9999", scope: []string{ "repository:samalba/my-app:pull,push", }, }) testAuthUrl(t, testcase, "https", "auth.docker.io:8888", "/token", []string{ "repository:samalba/my-app:pull,push", }) } func TestParseHeaderIpPort(t *testing.T) { testcase := `Bearer realm="https://192.168.1.1:8888/token",service="192.168.1.2:8888",scope="repository:samalba/my-app:pull,push"` fixtureUrl, _ := url.Parse("https://192.168.1.1:8888/token") testParse(t, testcase, Challenge{ realm: fixtureUrl, service: "192.168.1.2:8888", scope: []string{ "repository:samalba/my-app:pull,push", }, }) testAuthUrl(t, testcase, "https", "192.168.1.1:8888", "/token", []string{ "repository:samalba/my-app:pull,push", }) } func TestParseHeaderMultiScope(t *testing.T) { testcase := `Bearer realm="https://auth.docker.io/token",service="registry.docker.io",scope="repository:samalba/my-app:pull,push repository:samalba/my-app:foo,bar"` fixtureUrl, _ := url.Parse("https://auth.docker.io/token") testParse(t, testcase, Challenge{ realm: fixtureUrl, service: "registry.docker.io", scope: []string{ "repository:samalba/my-app:pull,push", "repository:samalba/my-app:foo,bar", }, }) testAuthUrl(t, testcase, "https", "auth.docker.io", "/token", []string{ "repository:samalba/my-app:pull,push", "repository:samalba/my-app:foo,bar", }) } func TestInvalid(t *testing.T) { _, err := ParseChallenge(`Bearrer realm="https://auth.docker.io/token",service="registry.docker.io",scope="repository:samalba/my-app:pull,push"`) if err == nil { t.Fatal("parsing an invalid challenge header should fail") } }
package persistencetests import ( "go.temporal.io/server/common/persistence/sql/sqlplugin/mysql" "go.temporal.io/server/common/persistence/sql/sqlplugin/postgresql" "go.temporal.io/server/common/service/config" "go.temporal.io/server/environment" ) const ( testMySQLUser = "temporal" testMySQLPassword = "temporal" testMySQLSchemaDir = "schema/mysql/v57" testPostgreSQLUser = "temporal" testPostgreSQLPassword = "temporal" testPostgreSQLSchemaDir = "schema/postgresql/v96" ) // GetMySQLTestClusterOption return test options func GetMySQLTestClusterOption() *TestBaseOptions { return &TestBaseOptions{ SQLDBPluginName: mysql.PluginName, DBUsername: testMySQLUser, DBPassword: testMySQLPassword, DBHost: environment.GetMySQLAddress(), DBPort: environment.GetMySQLPort(), SchemaDir: testMySQLSchemaDir, StoreType: config.StoreTypeSQL, } } // GetPostgreSQLTestClusterOption return test options func GetPostgreSQLTestClusterOption() *TestBaseOptions { return &TestBaseOptions{ SQLDBPluginName: postgresql.PluginName, DBUsername: testPostgreSQLUser, DBPassword: testPostgreSQLPassword, DBHost: environment.GetPostgreSQLAddress(), DBPort: environment.GetPostgreSQLPort(), SchemaDir: testPostgreSQLSchemaDir, StoreType: config.StoreTypeSQL, } }
package xflag import ( "flag" "go/build" "os" "reflect" "testing" "github.com/goaltools/xflag/cflag" ) var ( f1 = flag.String("key1", "value1_def", "flag from default section, file 1") f2 = flag.String("section:key1", "value2_def", "flag from `section`, file 2") f3 = flag.String("arg", "value_def", "flag from arguments") f4 = flag.String("doesNotExist", "default", "flag without input") f5 = cflag.Strings("doesNotExistToo[]", []string{"default"}, "xflag/cflag without input") f6 = cflag.Strings("key2[]", []string{"default"}, "xflag/cflag from default section, file 1") ) func TestParse(t *testing.T) { // Simulating "--arg value" input arguments. os.Args = []string{os.Args[0], "--arg", "value"} err := Parse("./testdata/file1.ini", "./testdata/file2.ini") if err != nil { t.Errorf(`No error expected, got "%v".`, err) } for _, v := range []struct { val, exp interface{} }{ {*f1, build.Default.GOPATH}, {*f2, "value2"}, {*f3, "value"}, {*f4, "default"}, {*f5, []string{"default"}}, {*f6, []string{"value2", "value2_1"}}, } { if !reflect.DeepEqual(v.val, v.exp) { t.Errorf(`Incorrect value of the flag. Expected "%s", got "%s".`, v.exp, v.val) } } } func TestParse_IncorrectFile(t *testing.T) { err := Parse("file_does_not_exist") if err == nil { t.Errorf("File does not exist, error expected.") } }
package handlers import ( "fmt" "net/url" "github.com/valyala/fasthttp" "github.com/authelia/authelia/v4/internal/authorization" "github.com/authelia/authelia/v4/internal/middlewares" ) func handleAuthzGetObjectAuthRequest(ctx *middlewares.AutheliaCtx) (object authorization.Object, err error) { var ( targetURL *url.URL rawURL, method []byte ) if rawURL = ctx.XOriginalURL(); len(rawURL) == 0 { return object, middlewares.ErrMissingXOriginalURL } if targetURL, err = url.ParseRequestURI(string(rawURL)); err != nil { return object, fmt.Errorf("failed to parse X-Original-URL header: %w", err) } if method = ctx.XOriginalMethod(); len(method) == 0 { return object, fmt.Errorf("header 'X-Original-Method' is empty") } if hasInvalidMethodCharacters(method) { return object, fmt.Errorf("header 'X-Original-Method' with value '%s' has invalid characters", method) } return authorization.NewObjectRaw(targetURL, method), nil } func handleAuthzUnauthorizedAuthRequest(ctx *middlewares.AutheliaCtx, authn *Authn, redirectionURL *url.URL) { ctx.Logger.Infof(logFmtAuthzRedirect, authn.Object.URL.String(), authn.Method, authn.Username, fasthttp.StatusUnauthorized, redirectionURL) switch authn.Object.Method { case fasthttp.MethodHead: ctx.SpecialRedirectNoBody(redirectionURL.String(), fasthttp.StatusUnauthorized) default: ctx.SpecialRedirect(redirectionURL.String(), fasthttp.StatusUnauthorized) } }
package stuff type Vitalstats struct { Name string // freetext Link string // full url Power string // more or less freetext BatteryRem string // ["yes"|"no"|"unk"] (normalized by scraper making best guess) ReleaseDate string Type string // so far, ["phone"|"tablet"|"phablet"] CMSupport string // freetext (more or less csv) } type Scraper func() []Vitalstats
package main import ( "context" "fmt" "os" "os/signal" "syscall" "github.com/andywow/golang-lessons/lesson-calendar/internal/calendar/config" "github.com/andywow/golang-lessons/lesson-calendar/internal/calendar/logconfig" "github.com/andywow/golang-lessons/lesson-calendar/internal/calendar/msgsystem/rabbitmq" "github.com/andywow/golang-lessons/lesson-calendar/internal/calendar/repository/dbstorage" "github.com/andywow/golang-lessons/lesson-calendar/internal/scheduler" ) func main() { cfg, err := config.ParseConfig() if err != nil { fmt.Println(err) os.Exit(1) } logger, err := logconfig.GetLoggerForConfig(cfg) if err != nil { fmt.Printf("could not configure logger: %v\n", err) os.Exit(1) } defer func() { if err := logger.Sync(); err != nil { fmt.Printf("could not sync logger: %v\n", err) } }() sugar := logger.Sugar() ctx, cancel := context.WithCancel(context.Background()) defer cancel() repository, err := dbstorage.NewDatabaseStorage(ctx, cfg.DB) if err != nil { sugar.Fatalf("error, while connecting to database: %s", err) } sugar.Info("Storage initialized") mqsystem, err := rabbitmq.NewRabbitMQ(ctx, cfg.RabbitMQ) if err != nil { sugar.Fatalf("error, while connecting to message system: %s", err) } sugar.Info("Message system initialized") cron := scheduler.Scheduler{} signalChannel := make(chan os.Signal, 1) signal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM) go func() { sig := <-signalChannel sugar.Infof("received signal: %s", sig) sugar.Info("wait maximum 1 minute for correct termination") cancel() }() cron.Start(ctx, scheduler.WithLogger(logger), scheduler.WithRepository(&repository), scheduler.WithMsgSystem(&mqsystem)) }
package line_segment import ( "math" "github.com/go-gl/gl/v4.1-core/gl" "../basic" ) type bead struct { prev *basic.Point current *basic.Point } const VertexCount = 32 func NewBead(prev, current *basic.Point) *bead { b := &bead{ prev: prev, current: current, } return b } func (b *bead) color() (float32, float32, float32, float32) { return 1.0, 0.0, 1.0, 1.0 } func (b *bead) Update(dt float32) { g := &basic.Point{Y: -9.8} next := b.current.Add(b.current).Sub(b.prev).Add(g.Mult(dt*dt)) b.prev = b.current b.current = next } func (b *bead) Draw() { array := make([]float32, (VertexCount*3)*7) for i := 0; i < VertexCount; i++ { r := 0.02 theta := math.Pi*2.0*float64(i)/ VertexCount array[(i*3)*7+0], array[(i*3)*7+1], array[(i*3)*7+2] = b.current.Elements() array[(i*3)*7+3], array[(i*3)*7+4], array[(i*3)*7+5], array[(i*3)*7+6] = b.color() array[(i*3+1)*7+0], array[(i*3+1)*7+1], array[(i*3+1)*7+2] = b.current.Add( &basic.Point{ X: float32(r*math.Cos(theta)), Y: float32(r*math.Sin(theta)), }).Elements() array[(i*3+1)*7+3], array[(i*3+1)*7+4], array[(i*3+1)*7+5], array[(i*3+1)*7+6] = b.color() theta2 := math.Pi*2.0*float64(i+1)/ VertexCount array[(i*3+2)*7+0], array[(i*3+2)*7+1], array[(i*3+2)*7+2] = b.current.Add( &basic.Point{ X: float32(r*math.Cos(theta2)), Y: float32(r*math.Sin(theta2)), }).Elements() array[(i*3+2)*7+3], array[(i*3+2)*7+4], array[(i*3+2)*7+5], array[(i*3+2)*7+6] = b.color() } VAO := makeVao(array) gl.BindVertexArray(VAO) gl.DrawArrays(gl.TRIANGLES, 0, 3*7*VertexCount) }
package humanity import ( "fmt" "strconv" ) type Pilot struct { *Human } func (h *Human) String() string { return fmt.Sprintf("%v, %v years old from %v", h.Name, strconv.Itoa(h.Age), h.Country) }
package preparer import ( "fmt" "io" "io/ioutil" "os" "os/user" "path/filepath" "runtime" "testing" . "github.com/anthonybishopric/gotcha" "github.com/gofrs/uuid" "github.com/square/p2/pkg/artifact" "github.com/square/p2/pkg/auth" "github.com/square/p2/pkg/cgroups" "github.com/square/p2/pkg/launch" "github.com/square/p2/pkg/logging" "github.com/square/p2/pkg/manifest" "github.com/square/p2/pkg/osversion" "github.com/square/p2/pkg/pods" "github.com/square/p2/pkg/store/consul" "github.com/square/p2/pkg/store/consul/consulutil" "github.com/square/p2/pkg/store/consul/podstore" "github.com/square/p2/pkg/uri" "github.com/square/p2/pkg/util" ) func TestLoadConfigWillMarshalYaml(t *testing.T) { configPath := util.From(runtime.Caller(0)).ExpandPath("test_preparer_config.yaml") preparerConfig, err := LoadConfig(configPath) Assert(t).IsNil(err, "should have read config correctly") Assert(t).AreEqual("/dev/shm/p2-may-run", preparerConfig.RequireFile, "did not read the require file correctly") Assert(t).AreEqual("foohost", preparerConfig.NodeName.String(), "did not read the node name correctly") Assert(t).AreEqual("0.0.0.0", preparerConfig.ConsulAddress, "did not read the consul address correctly") Assert(t).IsTrue(preparerConfig.ConsulHttps, "did not read consul HTTPS correctly (should be true)") Assert(t).AreEqual("/etc/p2/hooks", preparerConfig.HooksDirectory, "did not read the hooks directory correctly") Assert(t).AreEqual("/etc/p2.keyring", preparerConfig.Auth["keyring"], "did not read the keyring path correctly") Assert(t).AreEqual(1, len(preparerConfig.ExtraLogDestinations), "should have picked up 1 log destination") Assert(t).AreEqual(1, len(preparerConfig.HooksRequired), "should have picked up 1 required hook") destination := preparerConfig.ExtraLogDestinations[0] Assert(t).AreEqual(logging.OutSocket, destination.Type, "should have been the socket type") Assert(t).AreEqual("/var/log/p2-socket.out", destination.Path, "should have parsed path correctly") } func TestInstallHooks(t *testing.T) { destDir, _ := ioutil.TempDir("", "pods") defer os.RemoveAll(destDir) execDir, err := ioutil.TempDir("", "exec") defer os.RemoveAll(execDir) Assert(t).IsNil(err, "should not have erred creating a tempdir") current, err := user.Current() Assert(t).IsNil(err, "test setup: could not get the current user") builder := manifest.NewBuilder() builder.SetID("users") builder.SetRunAsUser(current.Username) builder.SetLaunchables(map[launch.LaunchableID]launch.LaunchableStanza{ "create": { Location: util.From(runtime.Caller(0)).ExpandPath("testdata/hoisted-hello_def456.tar.gz"), LaunchableType: "hoist", }, }) podManifest := builder.GetManifest() hookFactory := pods.NewHookFactory(destDir, "testNode", uri.DefaultFetcher) hooksPod := hookFactory.NewHookPod(podManifest.ID()) hooksPod.SetSubsystemer(&FakeSubsystemer{}) preparer := Preparer{ hooksManifest: podManifest, hooksPod: hooksPod, hooksExecDir: execDir, Logger: logging.DefaultLogger, artifactRegistry: artifact.NewRegistry(nil, uri.DefaultFetcher, osversion.DefaultDetector), artifactVerifier: auth.NopVerifier(), } err = preparer.InstallHooks() Assert(t).IsNil(err, "There should not have been an error in the call to SyncOnce()") currentAlias := filepath.Join(destDir, "users", "create", "current", "bin", "launch") _, err = os.Stat(currentAlias) Assert(t).IsNil(err, fmt.Sprintf("%s should have been created", currentAlias)) hookFile := filepath.Join(execDir, "users__create__launch") _, err = os.Stat(hookFile) Assert(t).IsNil(err, "should have created the user launch script") } func TestBuildRealityAtLaunch(t *testing.T) { podID := "some-app" testDir := "./tmp" podRoot := filepath.Join(testDir, "data/pods/") fixture := consulutil.NewFixture(t) defer fixture.Stop() store := consul.NewConsulStore(fixture.Client) podStore := podstore.NewConsul(fixture.Client.KV()) preparer := Preparer{ node: "test.local", client: fixture.Client, Logger: logging.DefaultLogger, store: store, podStore: podStore, podRoot: podRoot, } from, err := os.Open("./testdata/test_current_manifest.yaml") if err != nil { t.Fatalf("Error opening ./testdata/test_current_manifest.yaml: %s", err) } defer from.Close() uuidStr := uuid.Must(uuid.NewV4()).String() apps := []string{podID, podID + "-" + uuidStr} for _, app := range apps { err := os.MkdirAll(filepath.Join(podRoot, app), 0755) if err != nil { t.Fatalf("Error making tmp directory: %s", err) } to, err := os.OpenFile(filepath.Join(podRoot, app, "current_manifest.yaml"), os.O_RDWR|os.O_CREATE, 0755) if err != nil { t.Fatalf("Error opening destination current_manifest.yaml: %s", err) } defer to.Close() _, err = io.Copy(to, from) if err != nil { t.Fatalf("Error copying ./testdata/test_current_manifest.yaml to tmp: %s", err) } } defer func() { err := os.RemoveAll(testDir) if err != nil { t.Fatalf("Unable to remove tmp directory used for testing: %s", err) } }() err = preparer.BuildRealityAtLaunch() if err != nil { t.Fatalf("Error in BuildRealityAtLaunch: %s", err) } reality, _, err := store.ListPods(consul.REALITY_TREE, preparer.node) if err != nil { t.Fatalf("Error reading reality tree: %s", err) } match := false for _, result := range reality { if result.Manifest.ID().String() == podID { match = true break } } if !match { t.Fatalf("Did not find podID %s in reality tree", podID) } realityIndexPath := fmt.Sprintf("reality/%s/%s", preparer.node, uuidStr) pair, _, err := preparer.client.KV().Get(realityIndexPath, nil) if err != nil { t.Fatalf("Unable to fetch the key (%s): %s", realityIndexPath, err) } if pair == nil { t.Fatalf("%s should have been written but it wasn't", realityIndexPath) } } type FakeSubsystemer struct { tmpdir string } func (fs *FakeSubsystemer) Find() (cgroups.Subsystems, error) { var err error if fs.tmpdir == "" { fs.tmpdir, err = ioutil.TempDir("", "") if err != nil { return cgroups.Subsystems{}, err } if err = os.Chmod(fs.tmpdir, os.ModePerm); err != nil { return cgroups.Subsystems{}, err } } return cgroups.Subsystems{CPU: filepath.Join(fs.tmpdir, "cpu"), Memory: filepath.Join(fs.tmpdir, "memory")}, nil }
package config import ( "bytes" "flag" "fmt" "strings" ) // Config contains values to configure runs. type Config struct { // Username is a Github username. Username string // Repos contains repository names to run against. // Multiple values should be separated by comma. Repos string // RepoNames contains already parsed repository names from Repos. RepoNames []string // GithubAccessToken is a Github access token. GithubAccessToken string // Action is a string representation of a specific action to run. Action string // dryRun runs everything as normal is set to true. // If set to false, does not push changes and does not create a PR. DryRun bool } // NewFromFlags parses the command-line arguments provided to the program. // Typically os.Args[0] is provided as 'progname' and os.args[1:] as 'args'. // Returns the Config in case parsing succeeded, or an error. In any case, the // output of the flag.Parse is returned in output. // A special case is usage requests with -h or -help: then the error // flag.ErrHelp is returned and output will contain the usage message. func NewFromFlags(progname string, args []string) (*Config, string, error) { flags := flag.NewFlagSet(progname, flag.ContinueOnError) var buf bytes.Buffer flags.SetOutput(&buf) config := new(Config) flags.StringVar(&config.Username, "username", "", "Github username") flags.StringVar(&config.Repos, "repos", "", "Github repos to update, comma separeted") flags.StringVar(&config.Action, "action", "", "Action to run") flags.StringVar(&config.GithubAccessToken, "github-access-token", "", "Github access token") flags.BoolVar(&config.DryRun, "dry-run", false, "Dry run (do not push anything if true)") if err := flags.Parse(args); err != nil { return nil, buf.String(), err } if config.Username == "" { return nil, "", fmt.Errorf("username is blank, should be specified") } if config.Action == "" { return nil, "", fmt.Errorf("action is blank, should be specified") } supportedActionsMap := map[string]bool{ "gofmt": true, } supportedActions := []string{} for action := range supportedActionsMap { supportedActions = append(supportedActions, action) } if _, ok := supportedActionsMap[config.Action]; !ok { return nil, "", fmt.Errorf("action %q is not supported, supported actions: %v", config.Action, supportedActions) } if !config.DryRun && config.GithubAccessToken == "" { return nil, "", fmt.Errorf("github-access-token is blank, should be specified") } if config.Repos != "" { config.RepoNames = strings.Split(config.Repos, ",") } return config, buf.String(), nil }
/* Copyright 2020 The SuperEdge Authors. 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 options import ( "github.com/spf13/pflag" ) type Options struct { CAFile string KeyFile string CertFile string Master string KubeConfig string BindAddress string InsecureMode bool HostName string WrapperInCluster bool NotifyChannelSize int Debug bool ServiceAutonomyEnhancementOption ServiceAutonomyEnhancementOptions } func NewGridWrapperOptions() *Options { return &Options{ BindAddress: "0.0.0.0:9999", InsecureMode: true, NotifyChannelSize: 100, WrapperInCluster: true, ServiceAutonomyEnhancementOption: ServiceAutonomyEnhancementOptions{ Enabled: true, UpdateInterval: 5, AppStatusSvc: "http://10.244.5.35:8888/localinfo", }, } } func (sc *Options) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&sc.CAFile, "ca-file", sc.CAFile, "Certificate Authority file for communication between wrapper and kube-proxy") fs.StringVar(&sc.KeyFile, "key-file", sc.KeyFile, "Private key file for communication between wrapper and kube-proxy") fs.StringVar(&sc.CertFile, "cert-file", sc.CertFile, "Certificate file for communication between wrapper and kube-proxy") fs.StringVar(&sc.KubeConfig, "kubeconfig", sc.KubeConfig, "kubeconfig for wrapper to communicate to apiserver") fs.StringVar(&sc.Master, "master", sc.KubeConfig, "The address for wrapper to communicate to apiserver (overrides any value in kubeconfig)") fs.StringVar(&sc.BindAddress, "bind-address", sc.BindAddress, "wrapper bind address, ip:port") fs.BoolVar(&sc.InsecureMode, "insecure", sc.InsecureMode, "if true, disable tls communication between wrapper and kube-proxy") fs.StringVar(&sc.HostName, "hostname", sc.HostName, "hostname for this wrapper") fs.BoolVar(&sc.WrapperInCluster, "wrapper-in-cluster", sc.WrapperInCluster, "wrapper k8s in cluster config") fs.IntVar(&sc.NotifyChannelSize, "notify-channel-size", sc.NotifyChannelSize, "channel size for service and endpoints sent") fs.BoolVar(&sc.Debug, "debug", sc.Debug, "enable pprof handler") fs.Var(&sc.ServiceAutonomyEnhancementOption, "service-autonomy-enhancement", "service-autonomy-enhancement") }
package silverfish import ( "errors" "time" entity "silverfish/silverfish/entity" "gopkg.in/mgo.v2/bson" ) // Auth export type Auth struct { hashSalt *string sessionSalt *string userInf *entity.MongoInf sessions map[string]*entity.Session } // NewAuth export func NewAuth(hashSalt *string, userInf *entity.MongoInf) *Auth { saltTmp := "SILVERFISH" a := new(Auth) a.hashSalt = hashSalt a.userInf = userInf a.sessionSalt = &saltTmp a.sessions = map[string]*entity.Session{} return a } // ExpireLoop export func (a *Auth) ExpireLoop() { newSessions := map[string]*entity.Session{} for k, v := range a.sessions { if v.IsExpired() == false { newSessions[k] = v } } a.sessions = newSessions } // GetSession export func (a *Auth) GetSession(sessionToken *string) (*entity.Session, error) { if _, ok := a.sessions[*sessionToken]; ok { session := a.sessions[*sessionToken] session.KeepAlive() return session, nil } return nil, errors.New("SessionToken not exists") } // InsertSession export func (a *Auth) InsertSession(user *entity.User, keepLogin bool) *entity.Session { a.ExpireLoop() payload := (*user).Account + time.Now().String() sessionToken := SHA512Str(&payload, a.sessionSalt) if _, ok := a.sessions[*sessionToken]; ok { return a.InsertSession(user, keepLogin) } session := entity.NewSession(keepLogin, sessionToken, user) a.sessions[*sessionToken] = session return session } // IsTokenValid export func (a *Auth) IsTokenValid(sessionToken *string) bool { if val, ok := a.sessions[*sessionToken]; ok { result := val.IsExpired() if result == true { delete(a.sessions, *sessionToken) return false } a.sessions[*sessionToken].KeepAlive() return true } return false } // KillSession export func (a *Auth) KillSession(sessionToken *string) bool { if _, ok := a.sessions[*sessionToken]; ok { delete(a.sessions, *sessionToken) return true } return false } // Register export func (a *Auth) Register(isAdmin bool, account, password *string) (*entity.User, error) { hashedPassword := SHA512Str(password, a.hashSalt) _, err := a.userInf.FindOne(bson.M{"account": *account}, &entity.User{}) if err != nil { if err.Error() == "not found" { registerTime := time.Now() user := &entity.User{ IsAdmin: isAdmin, Account: *account, Password: *hashedPassword, RegisterDatetime: registerTime, LastLoginDatetime: registerTime, Bookmark: &entity.Bookmark{}, } a.userInf.Upsert(bson.M{"account": *account}, user) return &entity.User{ IsAdmin: user.IsAdmin, Account: user.Account, RegisterDatetime: user.RegisterDatetime, LastLoginDatetime: user.LastLoginDatetime, Bookmark: user.Bookmark, }, nil } return nil, err } return nil, errors.New("account exists") } // Login export func (a *Auth) Login(account, password *string) (*entity.User, error) { hashedPassword := SHA512Str(password, a.hashSalt) result, err := a.userInf.FindOne(bson.M{"account": *account}, &entity.User{}) if err != nil { if err.Error() == "not found" { return nil, errors.New("Account not exists") } return nil, err } user := result.(*entity.User) if user.Password != *hashedPassword { return nil, errors.New("Account or Password wrong") } user.LastLoginDatetime = time.Now() a.userInf.Upsert(bson.M{"account": account}, user) return &entity.User{ IsAdmin: user.IsAdmin, Account: user.Account, RegisterDatetime: user.RegisterDatetime, LastLoginDatetime: user.LastLoginDatetime, Bookmark: user.Bookmark, }, nil } // IsAdmin export func (a *Auth) IsAdmin(account *string) (bool, error) { result, err := a.userInf.FindOne(bson.M{"account": account}, &entity.User{}) if err != nil { return false, errors.New("Account not exists") } return result.(*entity.User).IsAdmin, nil }
package main import ( "github.com/feng/future/goc/util" ) func main() { util.GoSum(4, 5) }
/* Copyright 2021 The KubeVela Authors. 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 resourcekeeper import ( "context" "testing" "github.com/stretchr/testify/require" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1" ) func TestNamespaceAdmissionHandler_Validate(t *testing.T) { AllowCrossNamespaceResource = false defer func() { AllowCrossNamespaceResource = true }() handler := &NamespaceAdmissionHandler{ app: &v1beta1.Application{ObjectMeta: v1.ObjectMeta{Namespace: "test"}}, } objs := []*unstructured.Unstructured{{ Object: map[string]interface{}{ "metadata": map[string]interface{}{ "name": "demo", "namespace": "demo", }, }, }} err := handler.Validate(context.Background(), objs) r := require.New(t) r.NotNil(err) r.Contains(err.Error(), "forbidden resource") AllowCrossNamespaceResource = true r.NoError(handler.Validate(context.Background(), objs)) } func TestResourceTypeAdmissionHandler_Validate(t *testing.T) { defer func() { AllowResourceTypes = "" }() r := require.New(t) objs := []*unstructured.Unstructured{{ Object: map[string]interface{}{ "apiVersion": "v1", "kind": "Secret", "metadata": map[string]interface{}{ "name": "demo", "namespace": "demo", }, }, }} AllowResourceTypes = "blacklist:Service.v1,Secret.v1" err := (&ResourceTypeAdmissionHandler{}).Validate(context.Background(), objs) r.NotNil(err) r.Contains(err.Error(), "forbidden resource") AllowResourceTypes = "blacklist:ConfigMap.v1,Deployment.v1.apps" r.NoError((&ResourceTypeAdmissionHandler{}).Validate(context.Background(), objs)) AllowResourceTypes = "whitelist:ConfigMap.v1,Deployment.v1.apps" err = (&ResourceTypeAdmissionHandler{}).Validate(context.Background(), objs) r.NotNil(err) r.Contains(err.Error(), "forbidden resource") AllowResourceTypes = "whitelist:Service.v1,Secret.v1" r.NoError((&ResourceTypeAdmissionHandler{}).Validate(context.Background(), objs)) }
package postgres import ( "github.com/morscino/wallet-engine/utility/config" "gorm.io/driver/postgres" "gorm.io/gorm" ) func DbConnect(database config.PsqlDatabaseConfig) *gorm.DB { db, err := gorm.Open(postgres.New(postgres.Config{ DSN: "user=" + database.User + " password=" + database.Password + " dbname=" + database.Name + " sslmode=" + database.SSLMode, PreferSimpleProtocol: true, }), &gorm.Config{}) if err != nil { //log.Error("Could not connect to database : %v", err) panic(err.Error()) } return db }
// Set client options package main import ( "context" "fmt" "log" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) // You will be using this Trainer type later in the program type Trainer struct { Name string Age int City string } func main() { // Rest of the code will go here } clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") // Connect to MongoDB client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { log.Fatal(err) } // Check the connection err = client.Ping(context.TODO(), nil) if err != nil { log.Fatal(err) } fmt.Println("Connected to MongoDB!")
package models import ( "context" "github.com/misgorod/co-dev/errors" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/gridfs" "io" ) type File struct { ID primitive.ObjectID `json:"id"` } func DownloadFile(ctx context.Context, client *mongo.Client, id string, writer io.Writer) error { db := client.Database("codev") bucket, err := gridfs.NewBucket(db) if err != nil { return err } obj, err := primitive.ObjectIDFromHex(id) if err != nil { return err } _, err = bucket.DownloadToStream(obj, writer) if err != nil { if err == gridfs.ErrFileNotFound { return errors.ErrNoFile } return err } return nil }
// 15 april 2015 package pgidl import ( "fmt" "io" ) //go:generate go tool yacc pgidl.y func Parse(r io.Reader, filename string) (idl IDL, errs []string) { yyErrorVerbose = true l := newLexer(r, filename) yyParse(l) for _, e := range l.errs { errs = append(errs, fmt.Sprintf("%s %s", e.pos, e.msg)) } if len(errs) == 0 { return l.idl, nil } return nil, errs }
package bootstrap import ( "k8s.io/apimachinery/pkg/util/sets" "github.com/openshift/installer/pkg/types" ) // MergedMirrorSets consolidates a list of ImageDigestSources so that each // source appears only once. func MergedMirrorSets(sources []types.ImageDigestSource) []types.ImageDigestSource { sourceSet := make(map[string][]string) mirrorSet := make(map[string]sets.String) orderedSources := []string{} for _, group := range sources { if _, ok := sourceSet[group.Source]; !ok { orderedSources = append(orderedSources, group.Source) sourceSet[group.Source] = nil mirrorSet[group.Source] = sets.NewString() } for _, mirror := range group.Mirrors { if !mirrorSet[group.Source].Has(mirror) { sourceSet[group.Source] = append(sourceSet[group.Source], mirror) mirrorSet[group.Source].Insert(mirror) } } } out := []types.ImageDigestSource{} for _, source := range orderedSources { out = append(out, types.ImageDigestSource{Source: source, Mirrors: sourceSet[source]}) } return out } // ContentSourceToDigestMirror creates the ImageContentSource to ImageDigestSource struct // ImageContentSource is deprecated, use ImageDigestSource. func ContentSourceToDigestMirror(sources []types.ImageContentSource) []types.ImageDigestSource { digestSources := []types.ImageDigestSource{} for _, s := range sources { digestSources = append(digestSources, types.ImageDigestSource(s)) } return digestSources }
package pg import ( "github.com/kyleconroy/sqlc/internal/sql/ast" ) type CreatePublicationStmt struct { Pubname *string Options *ast.List Tables *ast.List ForAllTables bool } func (n *CreatePublicationStmt) Pos() int { return 0 }
package bclient import ( "math/big" ) // EthDaiPrice returns the price of ETH in terms of DAI func (bc *BClient) EthDaiPrice() (*big.Int, error) { reserves, err := bc.uc.GetReserves(WETHTokenAddress, DAITokenAddress) if err != nil { return nil, err } return new(big.Int).Div(reserves.Reserve1, reserves.Reserve0), nil }
package models import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "github.com/spf13/pflag" "github.com/spf13/viper" "gopkg.in/redis.v4" "log" "strconv" ) var Db *gorm.DB var Redis *redis.Client func init() { parseFlag() var err error viper.AddConfigPath("config") err = viper.ReadInConfig() if err != nil { log.Fatal(err) } viper.WatchConfig() var constr string host := viper.GetString("mysql.host") port := viper.GetInt("mysql.port") user := viper.GetString("mysql.user") password := viper.GetString("mysql.password") database := viper.GetString("mysql.database") constr = fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, database) Db, err = gorm.Open("mysql", constr) if err != nil { log.Fatal(err) } //Db.LogMode(true) Db.AutoMigrate(&Record{}) redisHost := viper.GetString("redis.host") redisPort := viper.GetInt("redis.port") redisPassword := viper.GetString("redis.password") redisDatabase := viper.GetInt("redis.database") Redis = redis.NewClient(&redis.Options{ Addr: redisHost + ":" + strconv.Itoa(redisPort), Password: redisPassword, DB: redisDatabase, }) } func parseFlag() { pflag.String("mysql.host","127.0.0.1","mysql host") pflag.Int("mysql.port",3306,"mysql port") pflag.String("mysql.user","root","user for mysql") pflag.String("mysql.password","root","password from mysql") pflag.String("mysql.database","mbui","mysql database") pflag.String("redis.host","127.0.0.1","redis host") pflag.Int("redis.port",6379,"redis port") pflag.String("redis.password","","redis auth") pflag.Int("redis.database",0,"redis producer database") pflag.String("redis.key","maxwell","redis producer list key name") pflag.Int("web.port",8080,"web service port") pflag.Bool("debug",false,"run gin in debug mode?") pflag.Parse() viper.BindPFlags(pflag.CommandLine) }
package main import "fmt" type animal interface { move() speak() } type dog struct { name string color string } type cat struct { name string color string } func (d dog) move() { fmt.Printf("%s color is %s,run adn run\n", d.name, d.color) } func (d dog) speak() { fmt.Printf("%s 汪汪汪\n", d.name) } func (c cat) move() { fmt.Printf("%s color is %s,run adn run\n", c.name, c.color) } func (c cat) speak() { fmt.Printf("%s 喵喵喵\n", c.name) } func mover(a animal) { a.move() } func speaker(a animal) { a.speak() } func main() { d1 := dog{ name: "小黑狗", color: "黑色", } c1 := cat{ name: "小花猫", color: "白黄", } mover(d1) mover(c1) speaker(d1) speaker(c1) }
package main import ( "fmt" "net/http" ) type myHandler struct{} func main() { // http.HandleFunc("/", myHandler{}) if err := http.ListenAndServe(":8088", &myHandler{}); err != nil { fmt.Println(err) } else { fmt.Println("serve is start in port:8088..") } } func (this *myHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { fmt.Println(req.URL) rw.Write([]byte("index")) } func handlerFunc1(rw http.ResponseWriter, req *http.Request) { rw.Write(([]byte)("This is handler func..")) }
package modules import ( builderDomain "../../domain/builder" "../../infrastructure/ssh/builder" ) type BuilderModule interface { LoadBuilders() *builderDomain.ISshCommandBuilder } func LoadBuilders() builderDomain.ISshCommandBuilder { sshBuilder := builder.InitSshCommandBuilder() return sshBuilder }
package main import ( "fmt" ) func main() { f := func(s string) { fmt.Println("I Assign String value to this func", s) } f("Strange") }
package rpcservice import ( "fmt" "github.com/goodsign/gosmsc" . "github.com/goodsign/gosmsc/contract" "net/http" ) //Service Definition type SMSService struct { senderChecker *gosmsc.SenderCheckerImpl } func NewSMSService(senderChecker *gosmsc.SenderCheckerImpl) (*SMSService, error) { if senderChecker == nil { return nil, fmt.Errorf("nil senderChecker") } return &SMSService{senderChecker}, nil } type Send_Args struct { Phone string Text string Track bool } type Send_Reply struct { Id int64 } // SMSCClientInterface implementation func (h *SMSService) Send(r *http.Request, msg *Send_Args, reply *Send_Reply) error { logger.Trace("") id, err := h.senderChecker.Send(msg.Phone, msg.Text, msg.Track) if err != nil { return err } reply.Id = id return nil } type GetActualStatus_Args struct { Id int64 } type GetActualStatus_Reply struct { Status *MessageStatus } // SMSCClientInterface implementation func (h *SMSService) GetActualStatus(r *http.Request, msg *GetActualStatus_Args, reply *GetActualStatus_Reply) error { logger.Trace("") status, err := h.senderChecker.GetActualStatus(msg.Id) if err != nil { return err } reply.Status = status return nil }
package group type insertRequest struct { BaseGroupId int `json:"baseGroupId"` Code string `json:"code" validate:"required"` Description string `json:"description" validate:"required"` } func insertRequestConvert(r *insertRequest) *Group { return &Group{ Code: r.Code, Description: r.Description, } } type insertResponse Group func newInsertResponse(group *Group) *insertResponse { return (*insertResponse)(group) } type updateRequest struct { Id int `json:"id" validate:"required"` Code string `json:"code" validate:"required"` Description string `json:"description" validate:"required"` } func updateRequestConvert(r *updateRequest) *Group { return &Group{ Id: r.Id, Code: r.Code, Description: r.Description, } } type updateResponse Group func newUpdateResponse(group *Group) *updateResponse { return (*updateResponse)(group) } type listResponse []Group func newListResponse(groups []Group) listResponse { return groups } type deleteRequest struct { Id int `json:"id" validate:"required"` } type getRequest struct { Id int `json:"id" validate:"required"` }
// Copyright (c) 2017, 0qdk4o. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package main import ( "crypto/tls" "fmt" "io" "net" "net/http" "os" "github.com/abegin/systemd" ) func HelloServer(w http.ResponseWriter, req *http.Request) { heihei := fmt.Sprintf("Request proto %v from client %v\n", req.Proto, req.RemoteAddr) io.WriteString(w, "hello socket activated world!\n") io.WriteString(w, heihei+"\n") } func StartupTLS(ln net.Listener, c chan error) { mysrv := http.Server{Handler: http.HandlerFunc(HelloServer)} cer, err := tls.LoadX509KeyPair("/home/go/bin/server.crt", "/home/go/bin/server.key") if err != nil { c <- err return } config := &tls.Config{ Certificates: []tls.Certificate{cer}, NextProtos: []string{"h2", "http/1.1"}, PreferServerCipherSuites: true, } fmt.Println("Starting Https service...") err = mysrv.Serve(tls.NewListener(ln, config)) if err != nil { c <- err } } func StartupHttp(ln net.Listener, c chan error) { mysrv := &http.Server{Handler: http.HandlerFunc(HelloServer)} fmt.Println("Starting Http service...") err := mysrv.Serve(ln) if err != nil { c <- err } } func RunServer(lnhttp, lnhttps net.Listener) chan error { cherr := make(chan error) go StartupTLS(lnhttps, cherr) go StartupHttp(lnhttp, cherr) return cherr } func main() { listeners, err := systemd.Listeners() if err != nil { fmt.Fprintf(os.Stderr, "WARNING: %v\n", err) } if len(listeners) != 2 { panic("Unexpected number of socket activation fds") } cherr := RunServer(listeners[0], listeners[1]) select { case err := <-cherr: fmt.Fprintf(os.Stderr, "Could not start service %v\n", err) os.Exit(1) } }
// struct areform to/as grouping data together // struct are typed collection of fields // macam2 koleksi lapangan terdeklarasi{eksplisit} // struct dari person akan berisi tentang tinggi,usia // struct dari identitas akan berisi tentang alamat, nama package main type person struct { name string age int } // metode untuk membuat objek(newPerson) baru // dengan melakukan passing `name`` sbg args1 dan // tipe metode menggunakan pointer *person func newPerson(name string) *person { }
package saml import ( "encoding/base64" "encoding/pem" "encoding/xml" "io/ioutil" "net/http" "os" "sync/atomic" "github.com/pkg/errors" ) // ServiceProvider represents a service provider. type ServiceProvider struct { MetadataURL string // Identifier of the SP entity (must be a URI) EntityID string // Assertion Consumer Service URL // Specifies where the <AuthnResponse> message MUST be returned to ACSURL string // SAML protocol binding to be used when returning the <Response> message. // Supports only HTTP-POST binding ACSBinding string AllowIdpInitiated bool SecurityOpts // File system location of the private key file KeyFile string // File system location of the cert file CertFile string // Private key can also be provided as a param // For now we need to write to a temp file since xmlsec requires a physical file to validate the document signature PrivkeyPEM string // Cert can also be provided as a param // For now we need to write to a temp file since xmlsec requires a physical file to validate the document signature PubkeyPEM string DTDFile string pemCert atomic.Value // Identity Provider settings the Service Provider instance should use IdPMetadataURL string IdPMetadataXML []byte IdPMetadata *Metadata // Identifier of the SP entity (must be a URI) IdPEntityID string // File system location of the cert file IdPCertFile string // Cert can also be provided as a param // For now we need to write to a temp file since xmlsec requires a physical file to validate the document signature IdPPubkeyPEM string // SAML protocol binding to be used when sending the <AuthnRequest> message IdPSSOServiceBinding string // URL Target of the IdP where the SP will send the AuthnRequest message IdPSSOServiceURL string // Whether to sign the SAML Request sent to the IdP to initiate the SSO workflow IdPSignSAMLRequest bool } // PrivkeyFile returns a physical path where the SP's key can be accessed. func (sp *ServiceProvider) PrivkeyFile() (string, error) { if sp.KeyFile != "" { return sp.KeyFile, nil } if sp.PrivkeyPEM != "" { return writeFile([]byte(sp.PrivkeyPEM)) } return "", errors.New("missing sp private key") } // PubkeyFile returns a physical path where the SP's public certificate can be // accessed. func (sp *ServiceProvider) PubkeyFile() (string, error) { if sp.CertFile != "" { return validateKeyFile(sp.CertFile, nil) } if sp.PubkeyPEM != "" { return validateKeyFile(writeFile([]byte(sp.PubkeyPEM))) } return "", errors.New("missing sp public key") } // GetIdPCertFile returns a physical path where the IdP certificate can be // accessed. func (sp *ServiceProvider) GetIdPCertFile() (string, error) { if sp.IdPPubkeyPEM == "" { return "", errors.New("missing idp certificate") } certBytes, _ := base64.StdEncoding.DecodeString(sp.IdPPubkeyPEM) certBytes = pem.EncodeToMemory(&pem.Block{ Type: "CERTIFICATE", Bytes: certBytes, }) return writeFile(certBytes) } func (sp *ServiceProvider) ParseIdPMetadata() (*Metadata, error) { var metadata *Metadata switch { case len(sp.IdPMetadataXML) > 0: if err := xml.Unmarshal(sp.IdPMetadataXML, &metadata); err != nil { return nil, errors.Wrapf(err, "failed to unmarshal metadata: %v", string(sp.IdPMetadataXML)) } case sp.IdPMetadataURL != "": res, err := http.Get(sp.IdPMetadataURL) if err != nil { return nil, errors.Wrapf(err, "failed to get %q", sp.IdPMetadataURL) } defer res.Body.Close() buf, err := ioutil.ReadAll(res.Body) if err != nil { return nil, errors.Wrapf(err, "failed to read body from %q", sp.IdPMetadataURL) } if err := xml.Unmarshal(buf, &metadata); err != nil { return nil, errors.Wrapf(err, "failed to unmarshal body: %+v", string(buf)) } } if metadata == nil { return nil, errors.Errorf("missing idp metadata xml/url") } return metadata, nil } // Cert returns a *pem.Block value that corresponds to the SP's certificate. func (sp *ServiceProvider) Cert() (*pem.Block, error) { if v := sp.pemCert.Load(); v != nil { return v.(*pem.Block), nil } certFile, err := sp.PubkeyFile() if err != nil { return nil, errors.Wrap(err, "failed to get sp cert key file") } fp, err := os.Open(certFile) if err != nil { return nil, errors.Wrapf(err, "failed to open sp cert file: %v", certFile) } defer fp.Close() buf, err := ioutil.ReadAll(fp) if err != nil { return nil, errors.Wrap(err, "failed to read sp cert file") } cert, _ := pem.Decode(buf) if cert == nil { return nil, errors.New("invalid sp certificate") } sp.pemCert.Store(cert) return cert, nil } // Metadata returns a metadata value based on the SP's data. func (sp *ServiceProvider) Metadata() (*Metadata, error) { cert, err := sp.Cert() if err != nil { return nil, errors.Wrap(err, "failed to get sp cert") } certStr := base64.StdEncoding.EncodeToString(cert.Bytes) metadata := &Metadata{ EntityID: sp.MetadataURL, ValidUntil: Now().Add(defaultValidDuration), SPSSODescriptor: &SPSSODescriptor{ AuthnRequestsSigned: false, WantAssertionsSigned: true, ProtocolSupportEnumeration: "urn:oasis:names:tc:SAML:2.0:protocol", KeyDescriptor: []KeyDescriptor{ KeyDescriptor{ Use: "signing", KeyInfo: KeyInfo{ Certificate: certStr, }, }, KeyDescriptor{ Use: "encryption", KeyInfo: KeyInfo{ Certificate: certStr, }, EncryptionMethods: []EncryptionMethod{ EncryptionMethod{Algorithm: "http://www.w3.org/2001/04/xmlenc#aes128-cbc"}, EncryptionMethod{Algorithm: "http://www.w3.org/2001/04/xmlenc#aes192-cbc"}, EncryptionMethod{Algorithm: "http://www.w3.org/2001/04/xmlenc#aes256-cbc"}, EncryptionMethod{Algorithm: "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"}, }, }, }, AssertionConsumerService: []IndexedEndpoint{{ Binding: HTTPPostBinding, Location: sp.ACSURL, Index: 1, }}, }, } return metadata, nil } // NewAuthnRequest creates a new AuthnRequest object for the given IdP URL. func (sp *ServiceProvider) NewAuthnRequest() (*AuthnRequest, error) { req := AuthnRequest{ AssertionConsumerServiceURL: sp.ACSURL, Destination: sp.IdPSSOServiceURL, ID: NewID(), IssueInstant: NewSAMLTime(Now()), Version: "2.0", ProtocolBinding: HTTPPostBinding, Issuer: Issuer{ Format: NameIDEntityFormat, Value: sp.MetadataURL, }, NameIDPolicy: NameIDPolicy{ AllowCreate: true, Format: NameIDEmailAddressFormat, }, } // Spec lists that the xmlns also needs to be namespaced: https://docs.oasis-open.org/security/saml/v2.0/saml-schema-protocol-2.0.xsd // TODO: create custom marshaler req.XMLNamespace = ProtocolNamespace req.XMLName.Local = "samlp:AuthnRequest" req.NameIDPolicy.XMLName.Local = "samlp:NameIDPolicy" return &req, nil }
package main import ( "fmt" "net/http" "encoding/json" ) func VerifySchnorr(w http.ResponseWriter, r *http.Request) { encoder := json.NewEncoder(w) var schnorrSignature SchnorrSignature err := ReadContentsIntoStruct(r, &schnorrSignature) if err != nil { encoder.Encode(Response{Err: &Error{Msg: err.Error()}}) return } P, err := NewECPoint(schnorrSignature.P.X, schnorrSignature.P.Y, err) if err != nil { encoder.Encode(Response{Err: &Error{Msg: err.Error()}}) return } M := schnorrSignature.M E, err := NewBigInt(schnorrSignature.E, err) S, err := NewBigInt(schnorrSignature.S, err) isValid, err := VerifySchnorrSignature(P, M, E, S, err) if err != nil { encoder.Encode(Response{Err: &Error{Msg: err.Error()}}) return } encoder.Encode(Response{Text: fmt.Sprintf("%t", isValid)}) }
package model import ( "fmt" "../compotent" "../middlerware" ) type DoraModel struct { compotent.CurdHandler //数据库连接实例 tn string //数据库名 } var DoraHandler DoraModel func init() { db, err := middlerware.Cont.Get("db") if err != nil { panic(fmt.Sprintf("内部错误, error:`%v`", err)) } gd := middlerware.GetDB(db) //形成依赖 if gd == nil { panic("内部错误, 数据库单例类型异常") } tn := "dora" DoraHandler = DoraModel{ compotent.CurdHandler{ gd.Table(tn), }, tn, } }
/* * @lc app=leetcode.cn id=50 lang=golang * * [50] Pow(x, n) */ // @lc code=start package main import "fmt" func main() { } func myPow(x float64, n int) float64 { switch { case n == 0 || x == 1: return 1 case n == 1: return x case x == 0: return 0 case } if x > 1 && n > 1 { sum := float64(1) for i := 0 ; i < n; i++ { sum = sum * x } return sum } if x == 1 || n == 0 { return 0 } } } func myPow(x float64, n int) float64 { if n >= 0 { return quickMul(x, n) } return 1.0 / quickMul(x, -n) } func quickMul(x float64, n int) float64 { if n == 0 { return 1 } y := quickMul(x, n/2) if n%2 == 0 { return y * y } return y * y * x } // @lc code=end
package main func callhome() { }
// +build darwin linux package main import ( //"math/rand" //"time" //"golang.org/x/mobile/app" //"golang.org/x/mobile/event/key" //"golang.org/x/mobile/event/lifecycle" //"golang.org/x/mobile/event/paint" //"golang.org/x/mobile/event/size" //"golang.org/x/mobile/event/touch" //"golang.org/x/mobile/exp/gl/glutil" //"golang.org/x/mobile/exp/sprite/clock" //"golang.org/x/mobile/gl" ) func main() { _textScreenMain( _appReset , _appPaint ) }
package main import ( "log" "os" "crypto/x509" "fmt" "github.com/olegsmetanin/golang-grpc/api/cert" api "github.com/olegsmetanin/golang-grpc/api/proto" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/grpclog" ) const ( port = 10000 defaultName = "world" ) func main() { // Set up a connection to the server. var err error demoCertPool := x509.NewCertPool() ok := demoCertPool.AppendCertsFromPEM([]byte(cert.Cert)) if !ok { panic("bad certs") } demoAddr := fmt.Sprintf("localhost:%d", port) var opts []grpc.DialOption creds := credentials.NewClientTLSFromCert(demoCertPool, demoAddr) opts = append(opts, grpc.WithTransportCredentials(creds)) conn, err := grpc.Dial(demoAddr, opts...) if err != nil { grpclog.Fatalf("fail to dial: %v", err) } defer conn.Close() c := api.NewGreeterClient(conn) // Contact the server and print out its response. name := defaultName if len(os.Args) > 1 { name = os.Args[1] } r, err := c.SayHello(context.Background(), &api.HelloRequest{Name: name}) if err != nil { log.Fatalf("could not greet: %v", err) } log.Printf("Greeting: %s", r.Message) }
package handler import ( "context" "github.com/micro/go-log" file "bussinessenv/srv/file/proto/file" ) type File struct { } func (f *File) UploadFile(ctx context.Context, req *file.UploadFileRequest, resp *file.Response) error { log.Log(req.Name) log.Log(req.File) return nil } func (f *File) DeleteFile(ctx context.Context, req *file.DeleteFileRequest, resp *file.Response) error { log.Log("received File.DeleteFile request, Fid is : ", req.Fid) resp.Status = 0 resp.Name = "email.docx" resp.Msg = "deleted success" resp.Size = 0 resp.Mime = "" return nil } func (f *File) UpdateFile(ctx context.Context, req *file.UpdateFileRequest, resp *file.Response) error { return nil }
package model import ( "time" ) type Recognize struct { RecognizeId int `json:"recognize_id"` RecognizeRestaurantId int `json:"title"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` DeletedAt time.Time `json:"deleted_at"` }
package main import ( "bufio" "encoding/json" "fmt" "io" "os" "regexp" "strings" ) type Wiki struct { /* JSON構造体定義 書式は:変数名[tab]型名[tab]`json:"キー名"`  # JSON構造体の深さが可変のものは別途定義する必要あり。 */ Text string `json:"text"` Title string `json:"title"` } func main() { wiki := []Wiki{} var check string re := regexp.MustCompile(".*Category:(.*)]]") /* 対象ファイルを読み込み、JSONをParseし、ハッシュへ格納 */ f, _ := os.Open("./jawiki-country.json") defer f.Close() r := bufio.NewReader(f) for { b, err := r.ReadBytes('\n') var w Wiki if err == io.EOF { break } /* func Unmarshal(data []byte, v interface{}) error 第一引数にはJSONのbyte列、第二引数にはJSONをマッピングしたい値(今回の場合、構造体)のポインタ */ json.Unmarshal([]byte(b), &w) wiki = append(wiki, w) /* 作成したハッシュのvalueをrangeで取り出し、 イギリスにマッチするハッシュを検出。 */ for _, name := range wiki { if name.Title == "イギリス" { check = name.Text } } } /* func (re *Regexp) FindSubmatch(b []byte) [][]byte */ for _, s := range strings.Split(check, "\n") { ret := re.FindSubmatch([]byte(s)) if ret != nil { fmt.Println(string(ret[1])) } } }
package main import ( "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter12/kafkaflow" sarama "github.com/Shopify/sarama" flow "github.com/trustmaster/goflow" ) func main() { consumer, err := sarama.NewConsumer([]string{"localhost:9092"}, nil) if err != nil { panic(err) } defer consumer.Close() partitionConsumer, err := consumer.ConsumePartition("example", 0, sarama.OffsetNewest) if err != nil { panic(err) } defer partitionConsumer.Close() net := kafkaflow.NewUpperApp() in := make(chan string) net.SetInPort("In", in) wait := flow.Run(net) defer func() { close(in) <-wait }() for { msg := <-partitionConsumer.Messages() in <- string(msg.Value) } }
/* On Pomax's Primer on Bézier Curves this "fairly funky image" appears: https://pomax.github.io/bezierinfo/#canonical This is related to the fact that every cubic Bézier curve can be put in a "canonical form" by an affine transformation that maps its first three control points to (0,0), (0,1) and (1,1) respectively. Where the fourth and last control point lies after the transformation then determines the curve's nature – suppose it lies at (x,y), then If y >= 1 the curve has a single inflection point (green region in the image). If y <= 1 but y >= (-x^2 +2x + 3)/4 and x <= 1 the curve has two inflection points. If y <= (-x^2 + 3x)/3 and x <= 0 or y <= 1 and 0 <= x <= 1 or y <= 1 and x >= 1 the curve is a simple arch with no inflection points. In all other cases the curve has a loop (red region in the image). Task Given the coordinates of the transformed curve's fourth point (x,y) in any reasonable format, output the curve's type, which is exactly one of "arch", "single inflection", "double inflection" or "loop". If (x,y) is on the boundary between two or more regions you may output the type corresponding to any of those regions. You may also use any four distinct values to represent the curve types. This is code-golf; fewest bytes wins. Test cases (x,y) -> type(s) (2,2) -> single (-1,2) -> single (2,0) -> arch (1,-2) -> arch (-1,-2) -> arch (-2,0) -> double (-3,-1) -> double (-1,-1) -> loop (-3,-4) -> loop (0,1) -> single or double (-1,0) -> double or loop (-3,-3) -> double or loop (0,0) -> arch or loop (2,1) -> arch or single (1,1) -> single or double or arch or loop */ package main import "math" func main() { assert(classify(2, 2) == "single") assert(classify(-1, 2) == "single") assert(classify(2, 0) == "arch") assert(classify(1, -2) == "arch") assert(classify(-1, -2) == "arch") assert(classify(-2, 0) == "double") assert(classify(-3, -1) == "double") assert(classify(-1, -1) == "loop") assert(classify(-3, -4) == "loop") assert(classify(0, 1) == "single") assert(classify(-1, 0) == "double") assert(classify(-3, -3) == "double") assert(classify(0, 0) == "arch") assert(classify(2, 1) == "single") assert(classify(1, 1) == "single") } func assert(x bool) { if !x { panic("assertion failed") } } func classify(x, y float64) string { if y >= 1 { return "single" } v := (-x*x + 2*x + 3) / 4 if y <= 1 && y >= v && x <= 1 { return "double" } u := (-x*x + 3*x) / 3 v = (math.Sqrt(3*(4*x-x*x)) - x) / 2 if (y <= u && x <= 0) || (y <= v && (0 <= x && x <= 1)) || (y <= 1 && x >= 1) { return "arch" } return "loop" }
package set import ( "reflect" "testing" ) func TestT(t *testing.T) { set1, set2 := NewT(reflect.TypeOf(0)), NewT(reflect.TypeOf(0)) set1.Add(1, 2, 3, 4, 5) set2.Add(3, 4, 5, 6, 7) t.Run("union", func(t *testing.T) { list := TUnion(set1, set2).List().([]int) requireEqualAfterSort(t, []int{1, 2, 3, 4, 5, 6, 7}, list) }) t.Run("intersect", func(t *testing.T) { list := TIntersect(set1, set2).List().([]int) requireEqualAfterSort(t, []int{3, 4, 5}, list) }) t.Run("subtract", func(t *testing.T) { list := TSubtract(set1, set2).List().([]int) requireEqualAfterSort(t, []int{1, 2}, list) }) t.Run("diff", func(t *testing.T) { both, only1, only2 := TDiff(set1, set2) requireEqualAfterSort(t, []int{3, 4, 5}, both.List().([]int)) requireEqualAfterSort(t, []int{1, 2}, only1.List().([]int)) requireEqualAfterSort(t, []int{6, 7}, only2.List().([]int)) }) }
package main import ( "fmt" "net/http" "testing" "github.com/max0ne/twitter_thing/back/middleware" "github.com/stretchr/testify/suite" ) type GetNewUserTestSuite struct { RouteTestSuite } func TestGetNewUserTest(t *testing.T) { suite.Run(t, new(GetNewUserTestSuite)) } func signUpForAnotherBunchOfUsers(unameStart, unameEnd int) []TestCase { tcs := []TestCase{} for idx := unameStart; idx < unameEnd; idx++ { tcs = append(tcs, TestCase{ desc: "sign up 1 user", method: "POST", path: "/user/signup", form: map[string]string{ "uname": fmt.Sprintf("u%d", idx), "password": fmt.Sprintf("u%dpass", idx), }, expCode: 200, }, ) } return tcs } func (suite *GetNewUserTestSuite) Test() { var token string addToken := func(req *http.Request) { if token != "" { req.Header.Add(middleware.TokenHeader, token) } } storeToken := func(resp *http.Response, bodyString string) { token = resp.Header.Get(middleware.TokenHeader) } testcases := []TestCase{ TestCase{ desc: "empty before any user sign up", method: "GET", path: "/user/new", expCode: 200, expBodyMapArr: []map[string]string{}, }, TestCase{ desc: "sign up 1 user", method: "POST", path: "/user/signup", form: map[string]string{ "uname": "u1", "password": "u1pass", }, expCode: 200, expBodyMap: nil, }, TestCase{ desc: "has this 1 user", method: "GET", path: "/user/new", expCode: 200, expBodyMapArr: []map[string]string{ map[string]string{ "uname": "u1", }, }, }, TestCase{ desc: "sign up another user", method: "POST", path: "/user/signup", form: map[string]string{ "uname": "u2", "password": "u2pass", }, expCode: 200, expBodyMap: nil, }, TestCase{ desc: "has these 2 user", method: "GET", path: "/user/new", expCode: 200, expBodyMapArr: []map[string]string{ map[string]string{ "uname": "u1", }, map[string]string{ "uname": "u2", }, }, }, } testcases = append(testcases, signUpForAnotherBunchOfUsers(3, 12)...) testcases = append(testcases, []TestCase{ TestCase{ desc: "has the last 10 users, excluding the very first one", method: "GET", path: "/user/new", expCode: 200, expBodyMapArr: []map[string]string{ map[string]string{ "uname": "u2", }, map[string]string{ "uname": "u3", }, map[string]string{ "uname": "u4", }, map[string]string{ "uname": "u5", }, map[string]string{ "uname": "u6", }, map[string]string{ "uname": "u7", }, map[string]string{ "uname": "u8", }, map[string]string{ "uname": "u9", }, map[string]string{ "uname": "u10", }, map[string]string{ "uname": "u11", }, }, }, TestCase{ desc: "sign in to user 2", method: "POST", path: "/user/login", form: map[string]string{ "uname": "u2", "password": "u2pass", }, expCode: 200, postTestCase: storeToken, }, TestCase{ desc: "new users does not contain current user", method: "GET", path: "/user/new", expCode: 200, expBodyMapArr: []map[string]string{ map[string]string{ "uname": "u3", }, map[string]string{ "uname": "u4", }, map[string]string{ "uname": "u5", }, map[string]string{ "uname": "u6", }, map[string]string{ "uname": "u7", }, map[string]string{ "uname": "u8", }, map[string]string{ "uname": "u9", }, map[string]string{ "uname": "u10", }, map[string]string{ "uname": "u11", }, }, }, }...) for _, tc := range testcases { oldPreTestCase := tc.preTestCase tc.preTestCase = func(req *http.Request) { if oldPreTestCase != nil { oldPreTestCase(req) } addToken(req) } suite.runTestCase(tc) } }