text
stringlengths
11
4.05M
package models import ( "github.com/astaxie/beego/orm" "github.com/astaxie/beego" "fmt" "time" "math/rand" ) const ( mysqlDriver = "mysql" ) type Poetry struct { Id int64 `orm:"auto;index"` Url string Content string `orm:"type(text)"` Author string `orm:"size(128)"` Interpret string `orm:"type(text)"` Title string `orm:"size(128)"` Poetuid string `orm:"size(128)"` } type Tag struct { Id int `orm:"auto;index"` Tag string `orm:"unique;size(128)"` TagCategory string `orm:"size(128)"` } type PoetryTag struct { Id int `orm:"auto;index"` TagId int PoetryId int64 BestLines string `orm:"size(128)"` } type TagState struct { Tag Tag PoetryId int64 PoetryTagId int BestLines string Active bool } func RegisterDB() { mysqlConn := fmt.Sprintf("%s:%s@%s", beego.AppConfig.String("dbusername"), beego.AppConfig.String("dbpassword"), beego.AppConfig.String("dbdatabase")) beego.Info("mysql conn:", mysqlConn) orm.RegisterDataBase("default", mysqlDriver, mysqlConn, 30) orm.RegisterModel(new(Poetry), new(Tag), new(PoetryTag)) // 自动建表 orm.RunSyncdb("default", false, true) } func SearchPoetry(title, content string) ([]*Poetry, error) { o := orm.NewOrm() poetries := make([]*Poetry, 0) qs := o.QueryTable("poetry") var err error _, err = qs.Filter("title__contains", title).Filter("content__contains", content).Limit(20).All(&poetries) if err != nil { beego.Error(err) return nil, err } return poetries, err } func GetPoetry(id int64) (*Poetry, error) { o := orm.NewOrm() poetry := Poetry{Id: id} var err error err = o.Read(&poetry) if err != nil { beego.Error(err) } return &poetry, err } func GetAllTags() ([]*Tag, error) { o := orm.NewOrm() tags := make([]*Tag, 0) qs := o.QueryTable("tag") _, err := qs.All(&tags) if err != nil { beego.Error(err) } return tags, err } func GetPoetriesByTagId(tagId int) ([]*Poetry, error) { o := orm.NewOrm() poetries := make([]*Poetry, 0) poetryTags := make([]*PoetryTag, 0) _, err := o.QueryTable("poetry_tag").Filter("tag_id", tagId).All(&poetryTags) ids := make([]int64, 0) for _, poetryTag := range poetryTags { ids = append(ids, poetryTag.PoetryId) } beego.Info("poetry ids:", ids) if len(ids) != 0 { _, err = o.QueryTable("poetry").Filter("id__in", ids).All(&poetries) if err != nil { beego.Error(err) } } return poetries, err } func AddTag(tag, tagcate string) (int64, error) { t := Tag{Tag: tag, TagCategory: tagcate} o := orm.NewOrm() id, err := o.Insert(&t) if err != nil { beego.Error(err) } return id, err } func DelTag(id int) error { t := Tag{Id: id} o := orm.NewOrm() _, err := o.Delete(&t) if err != nil { beego.Error(err) } return err } func SetPoetryTag(poetryId int64, tagId int, bestLines string) error { poetryTag := PoetryTag{PoetryId: poetryId, TagId: tagId, BestLines: bestLines} o := orm.NewOrm() _, err := o.Insert(&poetryTag) if err != nil { beego.Error(err) } return err } func DelPoetryTag(poetryTagId int) error { poetryTag := PoetryTag{Id: poetryTagId} o := orm.NewOrm() _, err := o.Delete(&poetryTag) if err != nil { beego.Error(err) } return err } func DelTagsOfPoetry(tagId int) error { poetryTag := PoetryTag{TagId: tagId} o := orm.NewOrm() _, err := o.Delete(&poetryTag) if err != nil { beego.Error(err) } return err } func GetPoetryTagState(id int64) ([]*TagState, error) { poetryTags := make([]*PoetryTag, 0) o := orm.NewOrm() qs := o.QueryTable("poetry_tag") _, err := qs.Filter("poetry_id", id).All(&poetryTags) if err != nil { beego.Error(err) } tags := make([]*Tag, 0) _, err = o.QueryTable("tag").All(&tags) if err != nil { beego.Error(err) } tagsStates := make([]*TagState, 0) beego.Info("tags", tags, " tags2", poetryTags) for _, t := range tags { tagSt := new(TagState) tagSt.Tag = *t tagSt.Active = false tagSt.PoetryId = id for _, t2 := range poetryTags { if t.Id == t2.TagId { tagSt.Active = true tagSt.BestLines = t2.BestLines tagSt.PoetryTagId = t2.Id break } } tagsStates = append(tagsStates, tagSt) } return tagsStates, err } func InTagMatch(keyword string) (int, error) { o := orm.NewOrm() tags := make([]*Tag, 0) _, err := o.QueryTable("tag").Filter("tag", keyword).All(&tags) if len(tags) > 0 { return tags[0].Id, nil } return -1, err } func RandomPoetry(tagId int) (string, error) { o := orm.NewOrm() poetryTags := make([]*PoetryTag, 0) qs := o.QueryTable("poetry_tag") qs.Filter("tag_id", tagId).All(&poetryTags) if len(poetryTags) > 0 { rand.Seed(time.Now().UnixNano()) t := rand.Intn(len(poetryTags)) beego.Info("index:", t) return poetryTags[t].BestLines, nil } return "", nil }
package main import ( "fmt" "log" "net/http" "os" "github.com/sensu-community/sensu-plugin-sdk/sensu" "github.com/sensu/sensu-go/types" ) // Config represents the check plugin config. type Config struct { sensu.PluginConfig Example string } var ( plugin = Config{ PluginConfig: sensu.PluginConfig{ Name: "sensu-test-check", Short: "test sensu check", Keyspace: "sensu.io/plugins/sensu-test-check/config", }, } options = []*sensu.PluginConfigOption{ &sensu.PluginConfigOption{ Path: "example", Env: "CHECK_EXAMPLE", Argument: "example", Shorthand: "e", Default: "", Usage: "An example string configuration option", Value: &plugin.Example, }, } ) var urls = map[string]string{ "MainPage": "http://geocitizen.link:8080/citizen", } func main() { useStdin := false fi, err := os.Stdin.Stat() if err != nil { fmt.Printf("Error check stdin: %v\n", err) panic(err) } //Check the Mode bitmask for Named Pipe to indicate stdin is connected if fi.Mode()&os.ModeNamedPipe != 0 { log.Println("using stdin") useStdin = true } check := sensu.NewGoCheck(&plugin.PluginConfig, options, checkArgs, executeCheck, useStdin) check.Execute() } func checkArgs(event *types.Event) (int, error) { if len(plugin.Example) == 0 { return sensu.CheckStateWarning, fmt.Errorf("--example or CHECK_EXAMPLE environment variable is required") } return sensu.CheckStateOK, nil } func executeCheck(event *types.Event) (int, error) { for service, url := range urls { resp, err := http.Get(url) if err != nil { log.Printf("%s: check ERROR: %s\n", service, err) return sensu.CheckStateCritical, nil } resp.Body.Close() if resp.StatusCode != 200 { log.Printf("%s: status check ERROR: %d != 200\n Runbook:https://github.com/DevOpsAcademySS/Geocitizen/wiki/Geocitizen-blue-green-deployment-on-K8S\n", service, resp.StatusCode) return sensu.CheckStateCritical, nil } log.Printf("%s: status OK", service) } return sensu.CheckStateOK, nil }
package gunit import ( "testing" ) func TestBatchCheck(t *testing.T) { RunTest(&BatchCheckTest{}, t) } type BatchCheckTest struct { } func (self *BatchCheckTest) TestSanity(c *Case) { c.Batch(self.foo()). AssertEquals(1). AssertEquals(-1). AssertNil() } func (self *BatchCheckTest) TestSkip(c *Case) { c.Batch(self.foo()). Skip(1). AssertEquals(-1). AssertNil() } func (self *BatchCheckTest) TestExpect(c *Case) { c.Batch(self.foo()). Skip(1). ExpectEquals(-1). ExpectNil() c.Batch(self.bar()). ExpectTrue(). ExpectFalse() } func (self *BatchCheckTest) TestBoolean(c *Case) { c.Batch(self.bar()). AssertTrue(). AssertFalse() } func (self *BatchCheckTest) foo() (int, int, error) { return 1, -1, nil } func (self *BatchCheckTest) bar() (bool, bool) { return true, false }
package commands import ( "errors" "flag" ) type indictSetup struct { flags *flag.FlagSet } func setupForIndict() indictSetup { flags := flag.NewFlagSet("indict", flag.ExitOnError) return indictSetup{ flags: flags, } } func (setup indictSetup) Parse(args []string) Command { setup.flags.Parse(args) paths := setup.flags.Args() if len(paths) == 0 { return suggestHelpWith( errors.New("defendant path(s) required for indictment")) } return &indictCommand{ paths: paths, } }
package trace //GinTrace .. type GinTrace struct { traceID string } //TraceID .. func (g *GinTrace) TraceID() string { return g.traceID } //NewGinTrace .. func NewGinTrace(s string) Trace { return &GinTrace{ traceID: s, } }
package Problem0556 import "sort" func nextGreaterElement(n int) int { nums := make([]int, 0, 10) lastTail := n % 10 // 用于标记 n 已经为其能表现的最大值 // 例如, n == 4321,就不可能变得更大了 isMax := true for n > 0 { tail := n % 10 if tail < lastTail { // 较高位上存在较小的值 // n 还可以变大 isMax = false } lastTail = tail nums = append(nums, tail) n /= 10 } // 由于 n 不可能再变大了,所以,提前结束 if isMax { return -1 } // nums 中 digit 的存入顺序与实际顺序相反 // 需要逆转一下 nums reverse(nums) // 按照题意,交换 nums 中,两个数的位子 beg := exchange(nums) // 重新排列 nums 尾部的数字,使得 nums 更小 sort.Ints(nums[beg:]) res := combine(nums) if res > 1<<31-1 { return -1 } return res } func reverse(ss []int) { i, j := 0, len(ss)-1 for i < j { ss[i], ss[j] = ss[j], ss[i] i++ j-- } } // 找到最大的 i 使得 // s[j] 是 s[i+1:] 中大于 s[i] 的最小值 // s[i], s[j] 互换后 // 返回 i+1 func exchange(a []int) int { var i, j int for i = len(a) - 2; 0 <= i; i-- { n := a[i] min := 10 index := i for j = i + 1; j < len(a); j++ { if n < a[j] && a[j] < min { min = a[j] index = j } } if i < index { a[i], a[index] = a[index], a[i] break } } return i + 1 } // 把 a 整合成一个 int func combine(a []int) int { num := 0 for i := range a { num = num*10 + a[i] } return num }
package main import ( "fmt" "github.com/boggo/neat/experiments/threes/libthrees" "math" "math/rand" ) var D = libthrees.DOWN var U = libthrees.UP var R = libthrees.RIGHT var L = libthrees.LEFT var tMoves = []libthrees.Direction{D, U, R, L} func randMove(g libthrees.Game) (libthrees.Direction, bool) { if g.IsOver() { return U, false } var pMoves []libthrees.Direction for _, d := range tMoves { if g.CanMove(d) { pMoves = append(pMoves, d) } } CMove := rand.Intn(len(pMoves)) return pMoves[CMove], true } func avgMoves(i int) float64 { g := libthrees.Game{} moves := 0.0 for I := 0; I < i; I++ { for !g.IsOver() { m, _ := randMove(g) g.Move(m) moves += 1 } g = libthrees.Game{} g.Initialize() } moves /= float64(i) return moves } /* func avgTotal(iter int, i int, c chan float64) { for I := 0; I < iter; I++ { go avgMoves(i,c) } } */ func stdDev(f []float64) float64 { if len(f) == 0 { fmt.Println("Bruh") return -1.0 } m := 0.0 for _, v := range f { m += v } m /= float64(len(f)) s := 0.0 for _, v := range f { s += (v - m) * (v - m) } s /= float64(len(f)) return math.Pow(s, 0.5) } func main() { sum := 0.0 max := 0.0 min := 9999999.0 Ssum := []float64{} test := libthrees.Game{} test.Initialize() for i := 0; i < 200000; i++ { v := avgMoves(100) Ssum = append(Ssum,v) if i % 1000 == 0 { fmt.Println(i) } if v > max { max = v } if v < min { min = v } } for _,i := range Ssum { sum += i } sum /= float64(len(Ssum)) fmt.Println(sum) fmt.Println(stdDev(Ssum)) fmt.Println("The max is", max) fmt.Println("The min is", min) fmt.Println("Lel") /* fmt.Println(test) test.PrintBoard(); test.Move(D) test.PrintBoard(); test.Move(L) test.PrintBoard(); test.Move(L) test.PrintBoard(); test.Move(L) test.PrintBoard(); test.Move(L) test.PrintBoard(); fmt.Println(test) fmt.Println(test.TestDeck()) */ }
// Exercise 06_appendonlylog guides you through using replay as an append-only-log. Since // it is possible to directly consume RunCreated events (with their data) from // application logic via a reflex consumer, modelling an append-only-log is as simple as defining // a worklfow with only an input and without any logic, or activities, or outputs. package main import ( "context" "github.com/corverroos/replay/typedreplay" "github.com/luno/fate" "github.com/luno/jettison/log" "github.com/luno/reflex" tut "github.com/corverroos/replaytutorial" // Alias replaytutorial to tut for brevity. ) // Step 0: main functions always just call tut.Main(Main). func main() { tut.Main(Main) } // Step 1: Replay always requires protobufs, so generate your types. //go:generate protoc --go_out=plugins=grpc:. ./pb.proto // Step 2: typedreplay requires a locally defined Backends. type Backends struct{} // Step 3: Define typedreplay namespace var _ = typedreplay.Namespace{ Name: "06_appendonlylog", Workflows: []typedreplay.Workflow{ { Name: "append", Description: "Appends data to the event log on creation (no actual logic)", Input: new(Data), }, }, // No activities or outputs since application logic directly consumes the RunCreated events as the log. } // Step 4: Generate the type-safe replay API for the above definition. //go:generate typedreplay // noop workflow function. func noop(flow appendFlow, ts *Data) {} // Step 5: Define your Main function which is equivalent to a main function, just with some prepared state. func Main(ctx context.Context, s tut.State) error { // Call the generated startReplayLoops. // Note technically one doesn't even need to start the workflow consumer loop since it doesn't do anything. startReplayLoops(s.AppCtxFunc, s.Replay, s.Cursors, Backends{}, noop) // TODO(you): Append some events to the log by calling RunAppend. Note that unique run IDs are required. // Define the log consume function _ = func(ctx context.Context, f fate.Fate, e *reflex.Event) error { // TODO(you): Use the generated HandleAppendRun to consume the log entries // and just print the values panic("implement me") } // TODO(you): Define and run the reflex spec using the generated StreamAppend function that streams entries of append-only-log. log.Info(ctx, "Press Ctrl-C to exit...") <-ctx.Done() return nil } // Step 6: Run the program and confirm the same expected output. //go:generate go run github.com/corverroos/replaytutorial/06_appendonlylog // Step 7: Experiments // - Add multiple independent log entry consumers
package settings import ( "github.com/cjburchell/go-uatu" "github.com/cjburchell/tools-go/env" ) var Log = log.CreateDefaultSettings() var PubSubAddress = env.Get("PUB_SUB_ADDRESS", "tcp://localhost:4222") var PubSubToken = env.Get("PUB_SUB_TOKEN", "token") var DataServiceToken = env.Get("COMMAND_TOKEN", "token")
package slice func elimnateAdjDuplicate(s []string) []string { n := len(s) for i := 0; i < n-1; i++ { if s[i] == s[i+1] { copy(s[i:], s[i+1:]) //costy n-- } } return s[:n] } func elimnateAdjDuplicate1(s []string) []string { c := 0 for _, str := range s { if s[c] == str { continue } c++ s[c] = str } return s[:c+1] }
package piscine func Capitalize(s string) string { sring := []rune(s) // кастинг : создаем массив рун cast len := 0 // вычисление длины строки for range sring { len++ } for i, bykva := range sring { // дайет доступ к каждой букве и диджителу if i == 0 || !isAlphaNum(sring[i-1]) { // проверяем если первая буква в слове if bykva >= 'a' && bykva <= 'z' { // проверяем если маленькая sring[i] = bykva - 32 // замена на большую } } else { if bykva >= 'A' && bykva <= 'Z' { // если это большая sring[i] = bykva + 32 // замена на маленькую } } } return string(sring) // возвращаем тип стринг } func isAlphaNum(a rune) bool { // сделали чтобы проверить if a >= 'a' && a <= 'z' { // маленькая ли буква return true } if a >= 'A' && a <= 'Z' { // большая ли буква return true } if a >= '0' && a <= '9' { // цифра ли return true } return false }
// Copyright (C) 2018 Storj Labs, Inc. // See LICENSE for copying information. package readcloser import "io" // MultiReadCloser is a MultiReader extension that returns a ReaderCloser // that's the logical concatenation of the provided input readers. // They're read sequentially. Once all inputs have returned EOF, // Read will return EOF. If any of the readers return a non-nil, // non-EOF error, Read will return that error. func MultiReadCloser(readers ...io.ReadCloser) io.ReadCloser { r := make([]io.Reader, len(readers)) for i := range readers { r[i] = readers[i] } c := make([]io.Closer, len(readers)) for i := range readers { c[i] = readers[i] } return &multiReadCloser{io.MultiReader(r...), c} } type multiReadCloser struct { multireader io.Reader closers []io.Closer } func (l *multiReadCloser) Read(p []byte) (n int, err error) { return l.multireader.Read(p) } func (l *multiReadCloser) Close() error { var firstErr error for _, c := range l.closers { err := c.Close() if err != nil && firstErr == nil { firstErr = err } } return firstErr }
package main import ( "github.com/gin-gonic/gin" "strconv" "encoding/json" ) const JsonByteStreamHeader = "application/json; charset=utf-8" const FloatType = "float" const StringType = "string" const BinaryType = "binary" func main(){ r := gin.Default() r.POST("/learn", GetLearningRequest) r.POST("/learnIonosphere", GetIonosphereLearningRequest) r.POST("/learnAutos",GetAutosLearningRequest) r.Run(":3000") } func SendResponse(c *gin.Context,resp *LearningResponse){ bodyBytes, _ := json.Marshal(resp) c.Header("Content-Length", strconv.Itoa(len(bodyBytes))) c.Data(200,JsonByteStreamHeader,bodyBytes) } func GetLearningRequest(c *gin.Context) { req := new(JSONLearningRequest) handler(req,c) } func GetIonosphereLearningRequest(c *gin.Context){ req := new(IonosphereLearningRequest) handler(req,c) } func GetAutosLearningRequest(c *gin.Context){ req := new(AutosLearningRequest) handler(req,c) } func handler(req LearningRequestInterface, c *gin.Context) { req.ReceiveRequest(c) resp := ProcessLearningRequest(req) SendResponse(c,resp) }
package sort import ( "fmt" "math/rand" "testing" "github.com/stretchr/testify/require" ) func TestHeap(t *testing.T) { randArray := func() []string { n := 1000 // 000 -> 999 array := make([]string, n) for i := 0; i < n; i++ { array[i] = fmt.Sprintf("%03d", i) } for i := 0; i < n; i++ { j := i + rand.Intn(n-i) // nolint: gosec array[i], array[j] = array[j], array[i] } return array } t.Run("normal", func(t *testing.T) { heap := Heap[string]{ Less: func(o1, o2 string) bool { return o1 < o2 }, } for _, v := range randArray() { heap.Append(v) } for i, v := range heap.Dump() { require.Equal(t, fmt.Sprintf("%03d", i), v) } }) t.Run("sized", func(t *testing.T) { heap := Heap[string]{ Less: func(o1, o2 string) bool { return o1 < o2 }, Size: 10, } for _, v := range randArray() { heap.Append(v) } require.Equal(t, []interface{}{ "000", "001", "002", "003", "004", "005", "006", "007", "008", "009", }, heap.Dump()) }) }
package controllers import ( "github.com/revel/revel" ) type App struct { *revel.Controller } func (c *App) Index() revel.Result { return c.Render() } func (c *App) GetUser(id int) revel.Result { a := 1 + id return c.RenderJSON(a) }
package aliastest import "fmt" func Get() { fmt.Println("get") } func init() { fmt.Println("init") } func main() { fmt.Println("test step 2") }
package model import ( "easyurl/infra/db/mysql" sq "github.com/Masterminds/squirrel" "log" ) type ApiDevKeyItem struct { ApiDevKey string `json:"api_dev_key"` UserId uint32 `json:"user_id"` Status uint8 `json:"status"` CreateTs uint64 `json:"create_ts"` UpdateTs uint64 `json:"update_ts"` } func GetOneByApiKey(apiDevKey string) (ApiDevKeyItem, error) { sql, args, err := sq.Select("*"). From("api_dev_keys"). Where(sq.Eq{"status": 2, "api_dev_key": apiDevKey}). Limit(1). ToSql() if err != nil { log.Println(err) return ApiDevKeyItem{}, err } var apiDevKeyItem ApiDevKeyItem if row := mysql.Db.QueryRow(sql, args...); row != nil { err := row.Scan(&apiDevKeyItem.ApiDevKey, &apiDevKeyItem.UserId, &apiDevKeyItem.Status, &apiDevKeyItem.CreateTs, &apiDevKeyItem.UpdateTs) if err != nil { return ApiDevKeyItem{}, err } } return apiDevKeyItem, nil }
package main import ( "fmt" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/loopfz/gadgeto/tonic" "github.com/wI2L/fizz" "github.com/wI2L/fizz/openapi" ) // NewRouter returns a new router for the // Pet Store. func NewRouter() (*fizz.Fizz, error) { engine := gin.New() engine.Use(cors.Default()) fizz := fizz.NewFromEngine(engine) // Override type names. // fizz.Generator().OverrideTypeName(reflect.TypeOf(Fruit{}), "SweetFruit") // Initialize the informations of // the API that will be served with // the specification. infos := &openapi.Info{ Title: "Fruits Market", Description: `This is a sample Fruits market server.`, Version: "1.0.0", } // Create a new route that serve the OpenAPI spec. fizz.GET("/openapi.json", nil, fizz.OpenAPI(infos, "json")) // Setup routes. routes(fizz.Group("/market", "market", "Your daily dose of freshness")) if len(fizz.Errors()) != 0 { return nil, fmt.Errorf("fizz errors: %v", fizz.Errors()) } return fizz, nil } func routes(grp *fizz.RouterGroup) { // Add a new fruit to the market. grp.POST("", []fizz.OperationOption{ fizz.Summary("Add a fruit to the market"), fizz.Response("400", "Bad request", nil, nil, map[string]interface{}{"error": "fruit already exists"}, ), }, tonic.Handler(CreateFruit, 200)) // Remove a fruit from the market, // probably because it rotted. grp.DELETE("/:name", []fizz.OperationOption{ fizz.Summary("Remove a fruit from the market"), fizz.ResponseWithExamples("400", "Bad request", nil, nil, map[string]interface{}{ "fruitNotFound": map[string]interface{}{"error": "fruit not found"}, "invalidApiKey": map[string]interface{}{"error": "invalid api key"}, }), }, tonic.Handler(DeleteFruit, 204)) // List all available fruits. grp.GET("", []fizz.OperationOption{ fizz.Summary("List the fruits of the market"), fizz.Response("400", "Bad request", nil, nil, nil), fizz.Header("X-Market-Listing-Size", "Listing size", fizz.Long), }, tonic.Handler(ListFruits, 200)) }
package main import ( "fmt" "sync" "testing" "gitgud.io/softashell/comfy-translator/translator" ) func TestQueue(t *testing.T) { q := NewQueue() req := translator.Request{ Text: "test", } if len(q.items) != 0 { t.Error("Queue not empty?") } ch, wait := q.Join(req) if ch != nil { t.Error("Returned unexpected channel") } if wait == true { t.Error("We shouldn't wait here") } if len(q.items) != 1 { t.Error("Queue does not contain one item") } wg := sync.WaitGroup{} joinWait(t, q, req, &wg, "test") joinWait(t, q, req, &wg, "test") joinWait(t, q, req, &wg, "test") if q.items[0].count != 3 { t.Error("Does not have enough waiting jobs") } q.Push(req, "test") if len(q.items) != 0 { t.Error("Queue not empty") } wg.Wait() } func joinWait(t *testing.T, q *Queue, req translator.Request, wg *sync.WaitGroup, expecting string) { ch, wait := q.Join(req) if wait != true { t.Error("We should wait here") } if ch == nil { t.Error("Didn't return channel") } go func(chan string) { wg.Add(1) defer wg.Done() out := <-ch fmt.Println("got", out) if out != expecting { t.Error("Unexpected output for waiting function") } }(ch) }
/** * @author liangbo * @email liangbogopher87@gmail.com * @date 2017/10/11 22:58 */ package model import ( "time" "pet/utils" "third/gorm" ) // 用户信息表 type User struct { UserId int64 `gorm:"primary_key"; sql:"AUTO_INCREMENT"` Phone string `sql:"type:varchar(64)"` // 电话号码 Name string `sql:"type:varchar(128)"` // 姓名 Gender string `sql:"type:smallint(6)"` // 性别,0: 无性别 1: 男 2: 女 Email string `sql:"type:varchar(128)"` RegistType int `sql:"type:"smallint(6)"` // 1:微信 2:官网 Nickname string `sql:"type:varchar(128)"` // 微信昵称 Avatar string `sql:"type:varchar(128)"` // 微信头像 Openid string `sql:"type:varchar(255)"` // 微信公共号的用户标志 CreateTime time.Time `sql:"type:datetime"` UpdateTime time.Time `sql:"type:datetime"` LastLogin time.Time `sql:"type:datetime"` Password string `sql:"type:varbinary(128)"` } func (user_info *User) TableName() string { return "pet.user" } // 新建用户 func (user_info *User) Create(id *int64) error { now := time.Now() user_info.CreateTime = now user_info.UpdateTime = now user_info.LastLogin = now err := PET_DB.Table(user_info.TableName()).Create(user_info).Error if nil != err { err = utils.NewInternalError(utils.DbErrCode, err) utils.Logger.Error("create user error: %v", err) return err } id = &user_info.UserId return nil } // 通过微信用户标志拉取用户标志 func (user_info *User) GetUserByOpenid(openid string) error { err := PET_DB.Table(user_info.TableName()).Where("openid = ?", openid).Limit(1).Find(user_info).Error if gorm.RecordNotFound == err { utils.Logger.Warning("user not found by openid, openid: %s", openid) err = nil } else if nil != err { err = utils.NewInternalError(utils.DbErrCode, err) utils.Logger.Error("get user by openid failed, openid: %s, error: %v", openid, err) return err } return nil } // get user by phone func (user_info *User) GetUserByPhone(phone string) error { err := PET_DB.Table(user_info.TableName()).Where("phone = ?", phone).Limit(1).Find(user_info).Error if gorm.RecordNotFound == err { utils.Logger.Warning("user not found by phone, phone: %s", phone) err = nil } else if nil != err { err = utils.NewInternalError(utils.DbErrCode, err) utils.Logger.Error("get user by phone failed, phone: %s, error: %v", phone, err) return err } return nil } // 判断电话号码是否存在 func CheckPhoneExist(phone string) (err error, flag bool, user_info *User) { user_info = new(User) err = PET_DB.Table("pet.user").Where("phone = ?", phone).Limit(1).Find(user_info).Error if err == gorm.RecordNotFound { flag = false err = nil } else if err == nil { flag = true } else { err = utils.NewInternalError(utils.DbErrCode, err) utils.Logger.Error("CheckPhoneExist failed, error: %v", err) return } return }
package db import ( "context" "encoding/json" "fmt" "github.com/yandex-cloud/examples/serverless/alice-shareable-todolist/app/model" "github.com/yandex-cloud/ydb-go-sdk" "github.com/yandex-cloud/ydb-go-sdk/table" ) func (r *repository) GetTODOList(ctx context.Context, id model.TODOListID) (*model.TODOList, error) { const query = ` DECLARE $id AS string; SELECT id, owner_user_id, items FROM todolist WHERE id = $id; ` var list *model.TODOList err := r.execute(ctx, func(ctx context.Context, s *table.Session, txc *table.TransactionControl) (*table.Transaction, error) { tx, res, err := s.Execute(ctx, txc, query, table.NewQueryParameters( table.ValueParam("$id", ydb.StringValue([]byte(id))), )) if err != nil { return nil, err } defer res.Close() if !res.NextSet() || !res.NextRow() { return tx, nil } list = &model.TODOList{} return tx, readTODOList(res, list) }) return list, err } func (r *repository) SaveTODOList(ctx context.Context, list *model.TODOList) error { const query = ` DECLARE $id AS string; DECLARE $owner_user_id AS string; DECLARE $items AS json; UPSERT INTO todolist(id, owner_user_id, items) VALUES ($id, $owner_user_id, $items); ` itemsJson, err := json.Marshal(list.Items) if err != nil { return fmt.Errorf("serializing list items: %w", err) } return r.execute(ctx, func(ctx context.Context, s *table.Session, txc *table.TransactionControl) (*table.Transaction, error) { tx, _, err := s.Execute(ctx, txc, query, table.NewQueryParameters( table.ValueParam("$id", ydb.StringValue([]byte(list.ID))), table.ValueParam("$owner_user_id", ydb.StringValue([]byte(list.Owner))), table.ValueParam("$items", ydb.JSONValue(string(itemsJson))), )) return tx, err }) } func (r *repository) DeleteTODOList(ctx context.Context, id model.TODOListID) error { const query = ` DECLARE $id AS string; DELETE FROM todolist WHERE id = $id; ` return r.execute(ctx, func(ctx context.Context, s *table.Session, txc *table.TransactionControl) (*table.Transaction, error) { tx, _, err := s.Execute(ctx, txc, query, table.NewQueryParameters( table.ValueParam("$id", ydb.StringValue([]byte(id))), )) return tx, err }) } func readTODOList(res *table.Result, l *model.TODOList) error { er := entityReader("todo_list") if id, err := er.fieldString(res, "id"); err != nil { return err } else { l.ID = model.TODOListID(id) } if owner, err := er.fieldString(res, "owner_user_id"); err != nil { return err } else { l.Owner = model.UserID(owner) } res.SeekItem("items") res.Unwrap() if res.Err() != nil { return res.Err() } return readTODOListItem(res, &l.Items) } func readTODOListItem(res *table.Result, item *[]*model.ListItem) error { itemJson := res.JSON() if res.Err() != nil { return fmt.Errorf("reading list item: %w", res.Err()) } err := json.Unmarshal([]byte(itemJson), item) if err != nil { return fmt.Errorf("parsing list item: %w", err) } return nil }
package acmt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00200106 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:acmt.002.001.06 Document"` Message *AccountDetailsConfirmationV06 `xml:"AcctDtlsConf"` } func (d *Document00200106) AddMessage() *AccountDetailsConfirmationV06 { d.Message = new(AccountDetailsConfirmationV06) return d.Message } // Scope // An account servicer, for example, a registrar, transfer agent, custodian bank or securities depository sends the AccountDetailsConfirmation message to the account owner, for example, an investor to confirm the opening of an account, execution of an AccountModificationInstruction or to return information requested in a GetAccountDetails message. // Usage // The AccountDetailsConfirmation message is used to confirm the opening of an account, modification of an account or the provision of information requested in a previously sent GetAccountDetails message. The message contains detailed information relevant to the opened account. // When the AccountDetailsConfirmation is used to confirm execution of an AccountModificationInstruction message, it contains the modified subsets of account details that were specified in the AccountModificationInstruction. // When the AccountDetailsConfirmation is used to reply to a GetAccountDetails message, it returns the selected subsets of account details that were specified in the GetAccountDetails message. type AccountDetailsConfirmationV06 struct { // Reference that uniquely identifies the message from a business application standpoint. MessageIdentification *iso20022.MessageIdentification1 `xml:"MsgId"` // Identifies a related order or settlement transaction. OrderReference *iso20022.InvestmentFundOrder4 `xml:"OrdrRef,omitempty"` // Reference to a linked message that was previously received. RelatedReference *iso20022.AdditionalReference6 `xml:"RltdRef,omitempty"` // Information about the request or instruction which triggered this confirmation. ConfirmationDetails *iso20022.AccountManagementConfirmation3 `xml:"ConfDtls"` // Confirmation of the information related to the investment account. InvestmentAccount *iso20022.InvestmentAccount50 `xml:"InvstmtAcct,omitempty"` // Confirmation of information related to parties that are related to the account, for example, primary account owner. AccountParties *iso20022.AccountParties13 `xml:"AcctPties,omitempty"` // Confirmation of an intermediary or other party related to the management of the account. In some markets, when this intermediary is a party acting on behalf of the investor for which it has opened an account at, for example, a central securities depository or international central securities depository, this party is known by the investor as the 'account controller'. Intermediaries []*iso20022.Intermediary36 `xml:"Intrmies,omitempty"` // Confirmation of referral information. Placement *iso20022.ReferredAgent2 `xml:"Plcmnt,omitempty"` // Confirmation of eligibility conditions applicable when there is an allocation of new issues for hedge fund account opening. NewIssueAllocation *iso20022.NewIssueAllocation2 `xml:"NewIsseAllcn,omitempty"` // Confirmation of the information related to a savings plan that is related to the account. SavingsInvestmentPlan []*iso20022.InvestmentPlan12 `xml:"SvgsInvstmtPlan,omitempty"` // Confirmation of the information related to a withdrawal plan that is related to the account. WithdrawalInvestmentPlan []*iso20022.InvestmentPlan12 `xml:"WdrwlInvstmtPlan,omitempty"` // Confirmation of a cash settlement standing instruction associated to transactions on the account. CashSettlement []*iso20022.CashSettlement1 `xml:"CshSttlm,omitempty"` // Identifies documents to be provided for the account opening. ServiceLevelAgreement []*iso20022.DocumentToSend3 `xml:"SvcLvlAgrmt,omitempty"` // Additional information concerning limitations and restrictions on the account. AdditionalInformation []*iso20022.AccountRestrictions1 `xml:"AddtlInf,omitempty"` // Identifies the market practice to which the message conforms. MarketPracticeVersion *iso20022.MarketPracticeVersion1 `xml:"MktPrctcVrsn,omitempty"` // Additional information that cannot be captured in the structured elements and/or any other specific block. Extension []*iso20022.Extension1 `xml:"Xtnsn,omitempty"` } func (a *AccountDetailsConfirmationV06) AddMessageIdentification() *iso20022.MessageIdentification1 { a.MessageIdentification = new(iso20022.MessageIdentification1) return a.MessageIdentification } func (a *AccountDetailsConfirmationV06) AddOrderReference() *iso20022.InvestmentFundOrder4 { a.OrderReference = new(iso20022.InvestmentFundOrder4) return a.OrderReference } func (a *AccountDetailsConfirmationV06) AddRelatedReference() *iso20022.AdditionalReference6 { a.RelatedReference = new(iso20022.AdditionalReference6) return a.RelatedReference } func (a *AccountDetailsConfirmationV06) AddConfirmationDetails() *iso20022.AccountManagementConfirmation3 { a.ConfirmationDetails = new(iso20022.AccountManagementConfirmation3) return a.ConfirmationDetails } func (a *AccountDetailsConfirmationV06) AddInvestmentAccount() *iso20022.InvestmentAccount50 { a.InvestmentAccount = new(iso20022.InvestmentAccount50) return a.InvestmentAccount } func (a *AccountDetailsConfirmationV06) AddAccountParties() *iso20022.AccountParties13 { a.AccountParties = new(iso20022.AccountParties13) return a.AccountParties } func (a *AccountDetailsConfirmationV06) AddIntermediaries() *iso20022.Intermediary36 { newValue := new(iso20022.Intermediary36) a.Intermediaries = append(a.Intermediaries, newValue) return newValue } func (a *AccountDetailsConfirmationV06) AddPlacement() *iso20022.ReferredAgent2 { a.Placement = new(iso20022.ReferredAgent2) return a.Placement } func (a *AccountDetailsConfirmationV06) AddNewIssueAllocation() *iso20022.NewIssueAllocation2 { a.NewIssueAllocation = new(iso20022.NewIssueAllocation2) return a.NewIssueAllocation } func (a *AccountDetailsConfirmationV06) AddSavingsInvestmentPlan() *iso20022.InvestmentPlan12 { newValue := new(iso20022.InvestmentPlan12) a.SavingsInvestmentPlan = append(a.SavingsInvestmentPlan, newValue) return newValue } func (a *AccountDetailsConfirmationV06) AddWithdrawalInvestmentPlan() *iso20022.InvestmentPlan12 { newValue := new(iso20022.InvestmentPlan12) a.WithdrawalInvestmentPlan = append(a.WithdrawalInvestmentPlan, newValue) return newValue } func (a *AccountDetailsConfirmationV06) AddCashSettlement() *iso20022.CashSettlement1 { newValue := new(iso20022.CashSettlement1) a.CashSettlement = append(a.CashSettlement, newValue) return newValue } func (a *AccountDetailsConfirmationV06) AddServiceLevelAgreement() *iso20022.DocumentToSend3 { newValue := new(iso20022.DocumentToSend3) a.ServiceLevelAgreement = append(a.ServiceLevelAgreement, newValue) return newValue } func (a *AccountDetailsConfirmationV06) AddAdditionalInformation() *iso20022.AccountRestrictions1 { newValue := new(iso20022.AccountRestrictions1) a.AdditionalInformation = append(a.AdditionalInformation, newValue) return newValue } func (a *AccountDetailsConfirmationV06) AddMarketPracticeVersion() *iso20022.MarketPracticeVersion1 { a.MarketPracticeVersion = new(iso20022.MarketPracticeVersion1) return a.MarketPracticeVersion } func (a *AccountDetailsConfirmationV06) AddExtension() *iso20022.Extension1 { newValue := new(iso20022.Extension1) a.Extension = append(a.Extension, newValue) return newValue }
package generator import ( "fmt" "github.com/golang/protobuf/ptypes" "github.com/goombaio/namegenerator" "github.com/yaminmhd/go-kafka-producer-protobuf/generatedProtos/person" "math/rand" "time" ) func NewPerson() *person.PersonMessage { timestamp, _ := ptypes.TimestampProto(time.Now().UTC()) person := &person.PersonMessage{ Name: randomNameGenerator(), Id: int32(randomId()), Email: randomEmail(), Phones: []*person.PhoneNumber{ {Number: randomPhoneNumber(), Type: randomPhoneType()}, }, LastUpdated: timestamp, } return person } func randomNameGenerator() string { seed := time.Now().UTC().UnixNano() nameGenerator := namegenerator.NewNameGenerator(seed) name := nameGenerator.Generate() return name } func randomId() int { rand.Seed(time.Now().UnixNano()) return random(90000000,99999999) } func randomPhoneNumber() string { return fmt.Sprintf("%v", randomId()) } func randomEmail() string { return fmt.Sprintf("%v@gmail.com", randomNameGenerator()) } func random(min int, max int) int { return rand.Intn(max-min) + min } func randomPhoneType() person.PhoneType { randomSource := rand.NewSource(time.Now().UnixNano()) source := rand.New(randomSource) switch source.Intn(3) { case 1: return 0 case 2: return 1 default: return 2 } }
package circular import ( "fmt" "errors" ) type Buffer struct { capacity int nextRead, nextWrite int isFull bool buffer []byte } func NewBuffer(size int) *Buffer { buffer := make([]byte, size) return &Buffer{ capacity: size, nextRead: 0, nextWrite: 0, isFull: false, buffer: buffer, } } func (buffer *Buffer) size() int { return (buffer.nextWrite - buffer.nextRead + buffer.capacity) % buffer.capacity } func (buffer *Buffer) isEmpty() bool { return buffer.size() == 0 && !buffer.isFull } func (buffer *Buffer) ReadByte() (byte, error) { if buffer.isEmpty() { return ' ', errors.New("Buffer is empty: Could not read from it.") } b := buffer.buffer[buffer.nextRead] buffer.nextRead = (buffer.nextRead + 1) % buffer.capacity buffer.isFull = false return b, nil } func (buffer *Buffer) WriteByte(b byte) error { if buffer.isFull { return errors.New("Buffer is full: Could not write to it.") } buffer.Overwrite(b) return nil } func (buffer *Buffer) Overwrite(b byte) { buffer.buffer[buffer.nextWrite] = b if buffer.isFull { buffer.nextRead = (buffer.nextRead + 1) % buffer.capacity } buffer.nextWrite = (buffer.nextWrite + 1) % buffer.capacity buffer.isFull = buffer.nextRead == buffer.nextWrite } func (buffer *Buffer) Reset() { buffer.nextRead = 0 buffer.nextWrite = 0 buffer.isFull = false buffer.buffer = make([]byte, buffer.capacity) } func (buffer *Buffer) String() string { return fmt.Sprintf("capacity: %v\nnextRead: %v\nnextWrite: %v\nbuffer: %v\n", buffer.capacity, buffer.nextRead, buffer.nextWrite, buffer.buffer) }
package libminio import ( "bytes" "image" "image/jpeg" _ "image/png" "log" "net/http" "os" "testing" ) func TestLibMinio(t *testing.T) { client := NewClient() client.Host = "-" client.AccessKey = "-" client.SecretKey = "-+" client.Bucket = "" client.Region = "-" client.SSL = true file, _ := os.Open("/Users/zzz/Downloads/prod.png") defer file.Close() fileImg, _, err := image.Decode(file) if err != nil { t.Fatal(err) } fileName := "content/square/marketplace/3bed03b8-76db-4526-8fb4-18f581dd958b.jpg" var newBuf bytes.Buffer err = jpeg.Encode(&newBuf, fileImg, nil) if err != nil { t.Fatal(err) } contentType := http.DetectContentType(newBuf.Bytes()) t.Log(contentType) t.Log(fileName) url, err := client.Upload(fileName, newBuf.Bytes(), int64(newBuf.Len()), http.DetectContentType(newBuf.Bytes())) if err != nil { t.Fatal(err) } log.Println(url) }
package pkg import ( "bytes" "encoding/json" "fmt" "os" "reflect" "regexp" "text/template" "github.com/Masterminds/sprig/v3" "github.com/goccy/go-yaml" "github.com/pkg/errors" ) func GetTPLFuncsMap() template.FuncMap { tplFuncs := make(template.FuncMap) // Add all Sprig functions for key, fn := range sprig.TxtFuncMap() { tplFuncs[key] = fn } // Own functions tplFuncs["dump"] = tplDump tplFuncs["fileReadToString"] = tplFileReadToString tplFuncs["yamlDecode"] = tplYAMLDecode tplFuncs["yamlToJson"] = tplYAMLToJson tplFuncs["cleanNewLines"] = tplCleanNewLines tplFuncs["eq"] = tplEq tplFuncs["ne"] = tplNE tplFuncs["lt"] = tplLT tplFuncs["le"] = tplLE tplFuncs["gt"] = tplGT tplFuncs["ge"] = tplGE return tplFuncs } func ExecuteTextTemplate(tpl *template.Template, args interface{}) (string, error) { var buf bytes.Buffer if err := tpl.Execute(&buf, args); err != nil { return "", errors.WithMessage(err, "failed to execute template") } return buf.String(), nil } func tplYAMLDecode(value string) (interface{}, error) { var outYAML interface{} if err := yaml.Unmarshal([]byte(value), &outYAML); err != nil { return nil, errors.WithMessage(err, "failed to unmarshal yaml value") } jsonCompatibleMap := SanitizeInterfaceToMapString(outYAML) return jsonCompatibleMap, nil } func tplYAMLToJson(value string) (string, error) { intf, err := tplYAMLDecode(value) if err != nil { return "", err } bodyJSON, err := json.Marshal(intf) if err != nil { return "", errors.WithMessage(err, "failed to marshal json from yaml") } return string(bodyJSON), nil } func tplFileReadToString(path string) (string, error) { b, err := os.ReadFile(path) if err != nil { return "", errors.WithMessage(err, "failed to read file") } return string(b), nil } // Straight from sprig func strval(v interface{}) string { switch v := v.(type) { case string: return v case []byte: return string(v) case error: return v.Error() case fmt.Stringer: return v.String() default: return fmt.Sprintf("%v", v) } } func indirect(v reflect.Value) (rv reflect.Value, isNil bool) { for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() { if v.IsNil() { return v, true } } return v, false } func tplDump(value interface{}) (string, error) { rt := reflect.ValueOf(value) if rt.Kind() == reflect.Ptr { rt, _ = indirect(rt) } if !rt.IsValid() { return "<no value>", nil } switch rt.Kind() { case reflect.Slice, reflect.Array, reflect.Map, reflect.Struct: marshaled, err := yaml.MarshalWithOptions(value, yaml.UseLiteralStyleIfMultiline(true)) if err != nil { return "", err } return string(marshaled), nil default: return strval(value), nil } } var regexCleanNewLines = regexp.MustCompile(`(\n\s*){3,}`) func tplCleanNewLines(text string) string { return regexCleanNewLines.ReplaceAllString(text, "\n\n") }
package service import ( "context" pb "github.com/johnbellone/persona-service/internal/gen/persona/api/v1" ptypes "github.com/johnbellone/persona-service/internal/gen/persona/type" "github.com/johnbellone/persona-service/internal/server" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type GroupHandler struct { config *server.Config } func NewGroupHandler(c *server.Config) *GroupHandler { return &GroupHandler{config: c} } func (h *GroupHandler) Create(ctx context.Context, req *pb.GroupRequest) (*pb.GroupResponse, error) { return nil, status.Error(codes.Unimplemented, "Not implemented") } func (h *GroupHandler) Get(ctx context.Context, req *pb.GroupRequest) (*ptypes.Group, error) { return nil, status.Error(codes.Unimplemented, "Not implemented") } func (h *GroupHandler) Update(ctx context.Context, req *ptypes.Group) (*pb.GroupResponse, error) { return nil, status.Error(codes.Unimplemented, "Not implemented") } func (h *GroupHandler) Delete(ctx context.Context, req *pb.GroupRequest) (*pb.GroupResponse, error) { return nil, status.Error(codes.Unimplemented, "Not implemented") }
// CSV parser package main import "encoding/csv" import "io/ioutil" import "io" import "os" import "fmt" import "strings" var Debug bool const dbgLimit = 100 func ParseCsv(filename string, columnsToParse map[string]string) []Entity { file, err := os.Open(filename) if err != nil { panic(err) } if Debug { parsedStr, _ := ioutil.ReadAll(file) if len(parsedStr) > dbgLimit { fmt.Printf("Found file contents:\n%s ...\n\n", string(parsedStr[:dbgLimit])) } else { fmt.Printf("Found file contents:\n%s\n\n", string(parsedStr)) } file.Seek(0, os.SEEK_SET) // rewind to start of file } csvReader := csv.NewReader(file) colMap := initColumnMap(&columnsToParse, csvReader) entities := initEntitiesFromCsv(csvReader, colMap) if Debug { fmt.Print(`Parsed entities: `, entities, "\n\n") } return entities } // init mapping of column titles and its index numbers // function will search for titles of columns in the first row and move pointer to second line func initColumnMap(columnsToParse *map[string]string, csvReader *csv.Reader) map[string]int { titles, err := csvReader.Read() if err == io.EOF { panic(`File is empty`) } colMap := map[string]int{} for colKey, colName := range *columnsToParse { for i, s := range titles { if colName == s { colMap[colKey] = i break } } if _, ok := colMap[colKey]; !ok { panic(fmt.Sprintln(`Field not found within list of titles:`, colName)) } } if Debug { fmt.Println(`Mapped titles and columns:`, colMap) } return colMap } func parseRefIds(rawValue string, entityId string) (refIds []string, refs []Ref) { refIds = strings.Split(rawValue, `,`) for i, v := range refIds { refId := strings.TrimSpace(v) if refId == `` { // skip empty refs continue } refPieces := strings.Split(refId, `[`) refId = strings.TrimSpace(refPieces[0]) ref := Ref{Id: entityId + `-` + refId, RefId: refId} if len(refPieces) > 1 { ref.Style = strings.TrimRight(refPieces[1], `]`) } refs = append(refs, ref) refIds[i] = refId } return refIds, refs } func initEntitiesFromCsv(csvReader *csv.Reader, colMap map[string]int) []Entity { var entities []Entity for { record, err := csvReader.Read() if err == io.EOF { break } if err != nil { panic(err) } refIds, refs := parseRefIds(record[colMap[`ref`]], record[colMap[`id`]]) var entity = Entity{Id: record[colMap[`id`]], Name: record[colMap[`name`]], RefIds: refIds, Refs: refs, Style: record[colMap[`style`]]} entity.Group = strings.TrimSpace(record[colMap[`group`]]) if entity.Id != `` && entity.Name != `` { entities = append(entities, entity) } else if Debug { fmt.Println(`Skipping entity with empty id or name:`, entity) } } addEntityDeps(&entities) return entities } // add entity dependencies between each other func addEntityDeps(entities *[]Entity) { for i, entity := range *entities { for _, refId := range entity.RefIds { if refId == `` { // skip empty refIds continue } found := false for _, sub := range *entities { if sub.Id == refId { (*entities)[i].AddChild(&sub) // entity cannot be set directly found = true break } } if !found { fmt.Fprintf(os.Stderr, `Failed to find reference ID "%s" for row ID "%s"%s`, refId, entity.Id, "\n") } } } }
package main import ( "bytes" "crypto/tls" "encoding/json" "fmt" "github.com/icza/dyno" flags "github.com/jessevdk/go-flags" "golang.org/x/net/http2" "io/ioutil" "log" "net/http" "net/url" "os" "strconv" "strings" "time" ) // https://golang.org/pkg/net/http/ // https://godoc.org/github.com/jessevdk/go-flags // https://qiita.com/t-mochizuki/items/4ffc478fedae7b776805 type Options struct { Verbose bool `short:"v" long:"verbose" description:"Show verbose debug information"` Vhost string `short:"H" long:"vhost" description:"Host header"` Ipaddr string `short:"I" long:"ipaddr" description:"IP address"` Port int `short:"p" long:"port" description:"TCP Port" default:"0"` Warn float64 `short:"w" long:"warn" description:"Warning time in second" default:"5.0"` Crit float64 `short:"c" long:"crit" description:"Critical time in second" default:"10.0"` Headers []string `short:"k" long:"header" description:"additional headers, acceptable multiple times"` Timeout int `short:"t" long:"timeout" description:"Timeout in second" default:"10"` Uri string `short:"u" long:"uri" description:"URI" default:"/"` Ssl bool `short:"S" long:"ssl" description:"Enable TLS"` Expect string `short:"e" long:"expect" description:"Expected status codes (csv)" default:""` JsonKey string `long:"json-key" description:"JSON key "` JsonValue string `long:"json-value" description:"Expected json value"` Method string `short:"j" long:"method" description:"HTTP METHOD (GET, HEAD, POST)" default:"GET"` UserAgent string `short:"A" long:"useragent" description:"User-Agent header" default:"check_http_go"` ClientCertFile string `short:"J" long:"client-cert" description:"Client Certificate File"` PrivateKeyFile string `short:"K" long:"private-key" description:"Private Key File"` Version bool `long:"version" description:"Print version"` } const ( NagiosOk = 0 NagiosWarning = 1 NagiosCritical = 2 NagiosUnknown = 3 Version = "0.2" ) func genTlsConfig(opts Options) *tls.Config { conf := &tls.Config{} conf.InsecureSkipVerify = true if opts.ClientCertFile != "" && opts.PrivateKeyFile != "" { cert, err := tls.LoadX509KeyPair(opts.ClientCertFile, opts.PrivateKeyFile) if err != nil { fmt.Printf("HTTP UNKNOWN - %s\n", err) os.Exit(NagiosUnknown) } conf.Certificates = []tls.Certificate{cert} } return conf } func prettyPrintJSON(b []byte) ([]byte, error) { var out bytes.Buffer err := json.Indent(&out, b, "", " ") return out.Bytes(), err } func main() { var opts Options var result_message string var host_header string var additional_out []byte scheme := "http" _, err := flags.Parse(&opts) if err != nil { os.Exit(NagiosUnknown) } if opts.Version { fmt.Printf("check_http_go: %s\n", Version) os.Exit(0) } if opts.Ipaddr == "" && opts.Vhost != "" { opts.Ipaddr = opts.Vhost } if opts.Ipaddr == "" { os.Exit(NagiosUnknown) } host_header = opts.Ipaddr if opts.Vhost != "" { host_header = opts.Vhost } if opts.Port == 0 { if opts.Ssl { scheme = "https" opts.Port = 443 } else { opts.Port = 80 } } // https://golang.org/pkg/crypto/tls/#Config tr := &http.Transport{ TLSClientConfig: genTlsConfig(opts), } // https://github.com/golang/go/issues/17051 // https://qiita.com/catatsuy/items/ee4fc094c6b9c39ee08f if err := http2.ConfigureTransport(tr); err != nil { log.Fatalf("Failed to configure h2 transport: %s", err) } c := &http.Client{ Timeout: time.Duration(opts.Timeout) * time.Second, // https://jonathanmh.com/tracing-preventing-http-redirects-golang/ CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, Transport: tr, } url_str := scheme + "://" + opts.Ipaddr + ":" + strconv.Itoa(opts.Port) + opts.Uri values := url.Values{} req, err := http.NewRequest(opts.Method, url_str, strings.NewReader(values.Encode())) if err != nil { fmt.Printf("HTTP UNKNOWN - %s\n", err) os.Exit(NagiosUnknown) } req.Host = host_header req.Header.Set("User-Agent", opts.UserAgent) for _, header := range opts.Headers { hdr := strings.SplitN(header, ": ", 2) req.Header.Set(hdr[0], hdr[1]) } t1 := time.Now() resp, err := c.Do(req) if err != nil { fmt.Printf("HTTP CRITICAL - %s\n", err) os.Exit(NagiosCritical) } defer resp.Body.Close() buf, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("HTTP CRITICAL - %s\n", err) os.Exit(NagiosCritical) } t2 := time.Now() diff := t2.Sub(t1) status_text := strconv.Itoa(resp.StatusCode) size := len(buf) if opts.Verbose { fmt.Print(string(buf)) } nagios_status := NagiosOk if opts.Expect == "" { if resp.StatusCode >= 500 { nagios_status = NagiosCritical result_message = fmt.Sprintf("Unexpected http status code: %d", resp.StatusCode) } else if resp.StatusCode >= 400 { nagios_status = NagiosWarning result_message = fmt.Sprintf("Unexpected http status code: %d", resp.StatusCode) } } else { nagios_status = NagiosWarning for _, expect := range strings.Split(opts.Expect, ",") { if status_text == expect { nagios_status = NagiosOk } } if nagios_status == NagiosWarning { result_message = fmt.Sprintf("Unexpected http status code: %d", resp.StatusCode) } } if opts.JsonKey != "" && opts.JsonValue != "" { // https://stackoverflow.com/questions/27689058/convert-string-to-interface t := strings.Split(opts.JsonKey, ".") s := make([]interface{}, len(t)) for i, v := range t { s[i] = v } // https://reformatcode.com/code/json/taking-a-json-string-unmarshaling-it-into-a-mapstringinterface-editing-and-marshaling-it-into-a-byte-seems-more-complicated-then-it-should-be var d map[string]interface{} json.Unmarshal(buf, &d) // https://qiita.com/hnakamur/items/c3560a4b780487ef6065 v, _ := dyno.Get(d, s...) if v != opts.JsonValue { nagios_status = NagiosCritical result_message = fmt.Sprintf("`%s` is not `%s`", opts.JsonKey, opts.JsonValue) } additional_out, err = prettyPrintJSON(buf) } if nagios_status == NagiosOk { if diff.Seconds() > opts.Crit { nagios_status = NagiosCritical result_message = fmt.Sprintf("response time %3.fs exceeded critical threshold %.3fs", diff.Seconds(), opts.Crit) } else if diff.Seconds() > opts.Warn { nagios_status = NagiosWarning result_message = fmt.Sprintf("response time %3.fs exceeded warning threshold %.3fs", diff.Seconds(), opts.Warn) } } result_str := "OK" if nagios_status == NagiosWarning { result_str = "WARNING" } else if nagios_status == NagiosCritical { result_str = "CRITICAL" } fmt.Printf("HTTP %s: %s %s - %d bytes in %.3f second response time |time=%.6fs;;;%.6f size=%dB;;;0\n", result_str, resp.Proto, resp.Status, size, diff.Seconds(), diff.Seconds(), 0.0, size) if result_message != "" { fmt.Println(result_message) } if len(additional_out) > 0 { fmt.Printf("\n%s", additional_out) } os.Exit(nagios_status) }
// hasarace.go // go run -race hasarace.go package main import "fmt" var x int func main() { for i := 1; i <= 1000; i++ { go func() { x++ }() } fmt.Println(x) }
package main import ( "fmt" "os" "path/filepath" "regexp" ) const ( jsDRegEx = `\.js(\?*.*\d*")` jsSRegEx = `\.js(\?*.*\d*')` cssDRegEx = `\.css(\?*\w*=*\d*")` cssSRegEx = `\.css(\?*\w*=*\d*')` jsDVFormat = ".js?v=%d\"" jsSVFormat = ".js?v=%d'" cssDVFormat = ".css?v=%d\"" cssSVFormat = ".css?v=%d'" ) func modifyLine(line string, version int) string { //Utility method which inserts the version. jsDQuote := regexp.MustCompile(jsDRegEx) jsSQuote := regexp.MustCompile(jsSRegEx) cssDQuote := regexp.MustCompile(cssDRegEx) cssSQuote := regexp.MustCompile(cssSRegEx) if jsDQuote.MatchString(line) { line = jsDQuote.ReplaceAllString(line, fmt.Sprintf(jsDVFormat, version)) } else if jsSQuote.MatchString(line) { line = jsSQuote.ReplaceAllString(line, fmt.Sprintf(jsSVFormat, version)) } else if cssDQuote.MatchString(line) { line = cssDQuote.ReplaceAllString(line, fmt.Sprintf(cssDVFormat, version)) } else if cssSQuote.MatchString(line) { line = cssSQuote.ReplaceAllString(line, fmt.Sprintf(cssSVFormat, version)) } return line } func getHTMLFiles(rootDir string) ([]vFile, error) { vFiles := []vFile{} err := filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error { if info.IsDir() || (filepath.Ext(path) != ".html" && filepath.Ext(path) != ".htm") { return nil } fileDetail := vFile{name: info.Name(), path: path} vFiles = append(vFiles, fileDetail) return nil }) return vFiles, err } func readFileContents(vFiles []vFile) error { var err error for i := 0; i < len(vFiles); i++ { err = vFiles[i].readContent() if err != nil { break } } return err }
package socketmode import "encoding/json" // Event is the event sent to the consumer of Client type Event struct { Type EventType Data interface{} // Request is the json-decoded raw WebSocket message that is received via the Slack Socket Mode // WebSocket connection. Request *Request } type ErrorBadMessage struct { Cause error Message json.RawMessage } type ErrorWriteFailed struct { Cause error Response *Response } type errorRequestedDisconnect struct { } func (e errorRequestedDisconnect) Error() string { return "disconnection requested: Slack requested us to disconnect" }
package main import ( "fmt" "github.com/sinksmell/files-cmp/client/utils" "github.com/sinksmell/files-cmp/models" "testing" ) var ( HOST string = "http://localhost:8080/v1/check" HASH_URL string = "/hash" FILE_URL string = "/file" ) // 测试是否能正确post json数据 func TestPostHash(t *testing.T) { req := &models.HashRequest{FileName: "hello.txt", Hash: "qwertyuiop"} if resp, err := utils.PostHash(req, HOST+HASH_URL); err != nil { t.Fatal(err) return } else { fmt.Println(resp) } } // 测试json解析是否正常 func TestParseResp(t *testing.T) { if res, err := utils.ParseResp([]byte(`{"code": 0,"msg": "OK"}`)); err != nil { // fmt.Println(err) t.Fatal(err) } else { t.Log(res) } } // 测试能否正确地提交文件 func TestPostFile(t *testing.T) { target := "http://localhost:8080/v1/check/file" fileName := "dog.png" if res, err := utils.PostFile(fileName, target, models.FILE_PATH, models.CMP_FILE); err != nil { fmt.Println(err) return } else { fmt.Println(res) } } // 测试能否正确地计算分组文件的MD5 并发送 func TestSendGroupMd5(t *testing.T) { utils.SendGrpMd5("group_2.txt", HOST+HASH_URL) }
/* * @lc app=leetcode id=144 lang=golang * * [144] Binary Tree Preorder Traversal */ // @lc code=start /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func preorderTraversal(root *TreeNode) []int { if root == nil { return nil } stack := []*TreeNode{root} result := make([]int, 0) for len(stack) > 0 { cur := stack[len(stack)-1] stack = stack[:len(stack)-1] result = append(result, cur.Val) if cur.Right != nil { stack = append(stack, cur.Right) } if cur.Left != nil { stack = append(stack, cur.Left) } } return result } // @lc code=end
package base type Repository interface { NextIdentity() Identity }
package main import "errors" // User represents a collection of Users type User struct { ID string followers map[*User]bool } const ( errUnknownCommand = "Unknown message type" ) // Follow another User func (c *User) Follow(other *User) { other.followers[c] = true } // Unfollow another user func (c *User) Unfollow(other *User) { delete(other.followers, c) } // Follows returns true if a user follows the given // user, false otherwise func (c *User) Follows(other *User) bool { _, ok := other.followers[c] return ok } // GetFollowers returns a slice of followers func (c *User) GetFollowers() []*User { followerSlice := make([]*User, len(c.followers)) index := 0 for k := range c.followers { followerSlice[index] = k index++ } return followerSlice } // NewUser creates a new user func NewUser(id string) *User { return &User{ID: id, followers: make(map[*User]bool)} } // UserCollection represents a collection of users type UserCollection struct { Users []*User userMap map[string]*User } func (uc *UserCollection) getUserByID(id string) (*User, bool) { user, ok := uc.userMap[id] return user, ok } func handleUnfollowMessage(uc *UserCollection, m Message) ([]*User, error) { fromUser := uc.GetOrCreateUser(m.FromID) toUser := uc.GetOrCreateUser(m.ToID) fromUser.Unfollow(toUser) return nil, nil } func handleFollowMessage(uc *UserCollection, m Message) ([]*User, error) { fromUser := uc.GetOrCreateUser(m.FromID) toUser := uc.GetOrCreateUser(m.ToID) fromUser.Follow(toUser) return []*User{toUser}, nil } func handleBroadcastMessage(uc *UserCollection, m Message) ([]*User, error) { return uc.Users, nil } func handlePrivateMessage(uc *UserCollection, m Message) ([]*User, error) { return []*User{uc.GetOrCreateUser(m.ToID)}, nil } func handleStatusUpdate(uc *UserCollection, m Message) ([]*User, error) { user := uc.GetOrCreateUser(m.FromID) return user.GetFollowers(), nil } // UpdateAndGetNotifiees handles the message and returns the users who need to be notified func (uc *UserCollection) UpdateAndGetNotifiees(m Message) ([]*User, error) { switch m.Type { case "U": return handleUnfollowMessage(uc, m) case "F": return handleFollowMessage(uc, m) case "B": return handleBroadcastMessage(uc, m) case "P": return handlePrivateMessage(uc, m) case "S": return handleStatusUpdate(uc, m) default: return nil, errors.New(errUnknownCommand) } } // GetOrCreateUser gets or creates a user func (uc *UserCollection) GetOrCreateUser(id string) *User { user, ok := uc.userMap[id] if !ok { user = NewUser(id) uc.Users = append(uc.Users, user) uc.userMap[id] = user } return user } // NewUserCollection creates an initialized UserCollection func NewUserCollection() UserCollection { return UserCollection{Users: []*User{}, userMap: make(map[string]*User)} }
package routers import ( "github.com/astaxie/beego" "github.com/astaxie/beego/context/param" ) func init() { beego.GlobalControllerRouter["walletApi/src/api:ApiContactController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiContactController"], beego.ControllerComments{ Method: "Post", Router: `/addContact`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiContactController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiContactController"], beego.ControllerComments{ Method: "Delete", Router: `/deleteContact`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiContactController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiContactController"], beego.ControllerComments{ Method: "QueryAll", Router: `/getContactAll/:address`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiContactController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiContactController"], beego.ControllerComments{ Method: "Query", Router: `/getContactInfo/:id`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiContactController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiContactController"], beego.ControllerComments{ Method: "Update", Router: `/updateContact`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiQuestionController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiQuestionController"], beego.ControllerComments{ Method: "Post", Router: `/addQuestion`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiQuestionController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiQuestionController"], beego.ControllerComments{ Method: "Delete", Router: `/deleteQuestion/:id`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiQuestionController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiQuestionController"], beego.ControllerComments{ Method: "QueryAll", Router: `/getQuestionAll`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiQuestionController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiQuestionController"], beego.ControllerComments{ Method: "Query", Router: `/getQuestionInfo/:id`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiQuestionController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiQuestionController"], beego.ControllerComments{ Method: "Update", Router: `/updateQuestion`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiSignController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiSignController"], beego.ControllerComments{ Method: "GetSignStatus", Router: `/getSignStatus/:qrCode`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiSignController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiSignController"], beego.ControllerComments{ Method: "QueryAllSignInfos", Router: `/queryAllSignInfos`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiSignController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiSignController"], beego.ControllerComments{ Method: "QueryConfirmInfo", Router: `/queryConfirmInfo/:qrCode`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiSignController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiSignController"], beego.ControllerComments{ Method: "QuerySignInfo", Router: `/querySignInfo/:qrCode`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiSignController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiSignController"], beego.ControllerComments{ Method: "Update", Router: `/updateSignData`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiVersionController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiVersionController"], beego.ControllerComments{ Method: "GetVersionLogs", Router: `/GetVersionLogs`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:ApiVersionController"] = append(beego.GlobalControllerRouter["walletApi/src/api:ApiVersionController"], beego.ControllerComments{ Method: "Get", Router: `/getVersionInfo/:platType`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryAllTokens", Router: `/queryAllTokens`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryBalance", Router: `/queryBalance/:address`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryChargeGas", Router: `/queryChargeGas`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryContractInfo", Router: `/queryContractInfo/:address/:version`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryContractList", Router: `/queryContractList/:address`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryJpushMsgInfo", Router: `/queryJpushMsgInfo/:msgId`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryJpushMsgList", Router: `/queryJpushMsgList`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryMasterTokenInfo", Router: `/queryMasterTokenInfo`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryPublishCCRequireNum", Router: `/queryPublishCCRequireNum`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryPublishTokenRequireNum", Router: `/queryPublishTokenRequireNum`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryReturnGasConfig", Router: `/queryReturnGasConfig`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryReturnItemsOfWait", Router: `/queryReturnItemsOfWait`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryReturnNumOfWait", Router: `/queryReturnNumOfWait`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QuerySysMsgInfo", Router: `/querySysMsgInfo/:msgId`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QuerySysMsgList", Router: `/querySysMsgList`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryTokenInfo", Router: `/queryTokenInfo/:tokenId`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryTransferCount", Router: `/queryTransferCount/:address`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryTransferDetails", Router: `/queryTransferDetails`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryTransferList", Router: `/queryTransferList`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryTransferListByAddress", Router: `/queryTransferListByAddress`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryTransferListByToken", Router: `/queryTransferListByToken`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryTransferStatistics", Router: `/queryTransferStatistics`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "QueryVestingInfo", Router: `/queryVestingInfo`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "Transfer", Router: `/sendRawTransaction`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "UpdatePubkey", Router: `/updateWalletPubkey`, AllowHTTPMethods: []string{"post"}, MethodParams: param.Make(), Filters: nil, Params: nil}) beego.GlobalControllerRouter["walletApi/src/api:WalletController"] = append(beego.GlobalControllerRouter["walletApi/src/api:WalletController"], beego.ControllerComments{ Method: "WalletIsExist", Router: `/walletIsExist/:address`, AllowHTTPMethods: []string{"get"}, MethodParams: param.Make(), Filters: nil, Params: nil}) }
// Copyright 2020 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. package telemetry import ( "crypto/sha1" // #nosec G505 "fmt" "sort" "strconv" "strings" ) // hashString returns the SHA1 checksum in hex of the string. func hashString(text string) (string, error) { hash := sha1.New() // #nosec G401 _, err := hash.Write([]byte(text)) if err != nil { return "", err } hashed := hash.Sum(nil) return fmt.Sprintf("%x", hashed), nil } // parseAddressAndHash parses an address in HOST:PORT format, returns the hashed host and the port. func parseAddressAndHash(address string) (result string, portName string, err error) { var host, port string if !strings.Contains(address, ":") { host = address port = "" } else { parts := strings.Split(address, ":") lastPart := parts[len(parts)-1] if _, err := strconv.Atoi(lastPart); err != nil { // Ensure that all plaintext part (i.e. port) will never contain sensitive data. // The port part is not int, recognize all as host. host = address port = "" } else { host = strings.Join(parts[:len(parts)-1], ":") port = lastPart } } res, err := hashString(host) if err != nil { return "", "", err } return res, port, err } // See https://stackoverflow.com/a/58026884 func sortedStringContains(s []string, searchTerm string) bool { i := sort.SearchStrings(s, searchTerm) return i < len(s) && s[i] == searchTerm }
package checker import ( "context" "errors" "github.com/cybertec-postgresql/vip-manager/vipconfig" ) // ErrUnsupportedEndpointType is returned for an unsupported endpoint var ErrUnsupportedEndpointType = errors.New("given endpoint type not supported") // LeaderChecker is the interface for checking leadership type LeaderChecker interface { GetChangeNotificationStream(ctx context.Context, out chan<- bool) error } // NewLeaderChecker returns a new LeaderChecker instance depending on the configuration func NewLeaderChecker(con *vipconfig.Config) (LeaderChecker, error) { var lc LeaderChecker var err error switch con.EndpointType { case "consul": lc, err = NewConsulLeaderChecker(con) case "etcd", "etcd3": lc, err = NewEtcdLeaderChecker(con) default: err = ErrUnsupportedEndpointType } return lc, err }
package main import ( "fmt" "log" "math/rand" "os" "time" "github.com/codegangsta/cli" "gopkg.in/gin-gonic/gin.v1" ) func main() { app := cli.NewApp() app.Name = "rubusidaeus" app.Usage = "Serve image form raspberry pi camera, but quickly" app.Flags = []cli.Flag{ cli.IntFlag{ Name: "port", Value: 8080, Usage: "port for serving", EnvVar: "PORT", }, cli.StringFlag{ Name: "username,u", Value: "admin", Usage: "username required to view camera, empty for no account required", EnvVar: "USERNAME", }, cli.StringFlag{ Name: "password,p", Value: "", Usage: "password for account, random by default, see log output", EnvVar: "PASSWORD", }, } app.Action = start app.Run(os.Args) } func start(ctx *cli.Context) { r := gin.Default() // a health check is nice to have r.GET("/healthz", func(c *gin.Context) { c.JSON(200, gin.H{ "alive": true, }) }) var authMiddlewares []gin.HandlerFunc if u := ctx.GlobalString("username"); u != "" { log.Println("username: " + u) password := randPassword(12) if p := ctx.GlobalString("password"); p != "" { password = p } else { log.Println("password: " + password) } authMiddlewares = append(authMiddlewares, gin.BasicAuth(gin.Accounts{ u: password, })) } authorized := r.Group("/camera", authMiddlewares...) authorized.GET("/image.jpg", getImage) addr := fmt.Sprintf(":%d", ctx.GlobalInt("port")) err := r.Run(addr) if err != nil { log.Panic(err) } } func randPassword(length int) string { rand.Seed(time.Now().UTC().UnixNano()) var chars = []rune("ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz123456789") passwd := make([]rune, length) for i := range passwd { passwd[i] = chars[rand.Intn(len(chars))] } return string(passwd) }
package main import ( "fmt" ) func main() { var a, b, c int fmt.Scanln(&a) fmt.Scanln(&b) c= a + b fmt.Println("SOMA =",c) }
/* Copyright 2011 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package client import ( "flag" "log" "io/ioutil" "os" "path/filepath" "strings" "sync" "camli/blobref" "camli/jsonconfig" "camli/jsonsign" "camli/osutil" ) // These override the JSON config file ~/.camli/config "server" and // "password" keys var flagServer *string = flag.String("blobserver", "", "camlistore blob server") var flagPassword *string = flag.String("password", "", "password for blob server") func ConfigFilePath() string { return filepath.Join(osutil.CamliConfigDir(), "config") } var configOnce sync.Once var config = make(map[string]interface{}) func parseConfig() { configPath := ConfigFilePath() var err os.Error if config, err = jsonconfig.ReadFile(configPath); err != nil { log.Fatal(err.String()) return } } func cleanServer(server string) string { // Remove trailing slash if provided. if strings.HasSuffix(server, "/") { server = server[0 : len(server)-1] } // Add "http://" prefix if not present: if !strings.HasPrefix(server, "http") { server = "http://" + server } return server } func blobServerOrDie() string { if *flagServer != "" { return cleanServer(*flagServer) } configOnce.Do(parseConfig) value, ok := config["blobServer"] var server string if ok { server = value.(string) } server = cleanServer(server) if !ok || server == "" { log.Fatalf("Missing or invalid \"blobServer\" in %q", ConfigFilePath()) } return server } func passwordOrDie() string { if *flagPassword != "" { return *flagPassword } configOnce.Do(parseConfig) value, ok := config["blobServerPassword"] var password string if ok { password, ok = value.(string) } if !ok { log.Fatalf("No --password parameter specified, and no \"blobServerPassword\" defined in %q", ConfigFilePath()) } if password == "" { // TODO: provide way to override warning? // Or make a way to do deferred errors? A blank password might // be valid, but it might also signal the root cause of an error // in the future. log.Printf("Warning: blank \"blobServerPassword\" defined in %q", ConfigFilePath()) } return password } // Returns blobref of signer's public key, or nil if unconfigured. func (c *Client) SignerPublicKeyBlobref() *blobref.BlobRef { return SignerPublicKeyBlobref() } func (c *Client) SecretRingFile() string { configOnce.Do(parseConfig) keyRing, ok := config["secretRing"].(string) if ok && keyRing != "" { return keyRing } return jsonsign.DefaultSecRingPath() } // TODO: move to config package? func SignerPublicKeyBlobref() *blobref.BlobRef { configOnce.Do(parseConfig) key := "keyId" keyId, ok := config[key].(string) if !ok { log.Printf("No key %q in JSON configuration file %q; have you run \"camput init\"?", key, ConfigFilePath()) return nil } keyRing, _ := config["secretRing"].(string) entity, err := jsonsign.EntityFromSecring(keyId, keyRing) if err != nil { log.Printf("Couldn't find keyId %q in secret ring: %v", keyId, err) return nil } armored, err := jsonsign.ArmoredPublicKey(entity) if err != nil { log.Printf("Error serializing public key: %v", err) return nil } selfPubKeyDir, ok := config["selfPubKeyDir"].(string) if !ok { log.Printf("No 'selfPubKeyDir' defined in %q", ConfigFilePath()) return nil } fi, err := os.Stat(selfPubKeyDir) if err != nil || !fi.IsDirectory() { log.Printf("selfPubKeyDir of %q doesn't exist or not a directory", selfPubKeyDir) return nil } br := blobref.Sha1FromString(armored) pubFile := filepath.Join(selfPubKeyDir, br.String()+".camli") log.Printf("key file: %q", pubFile) fi, err = os.Stat(pubFile) if err != nil { err = ioutil.WriteFile(pubFile, []byte(armored), 0644) if err != nil { log.Printf("Error writing public key to %q: %v", pubFile, err) return nil } } return br } func (c *Client) GetBlobFetcher() blobref.SeekFetcher { // Use blobref.NewSeriesFetcher(...all configured fetch paths...) return blobref.NewConfigDirFetcher() }
// Generic OneWire driver. package embd import "sync" type w1BusFactory func(byte) W1Bus type w1Driver struct { busMap map[byte]W1Bus busMapLock sync.Mutex ibf w1BusFactory } // NewW1Driver returns a W1Driver interface which allows control // over the OneWire subsystem. func NewW1Driver(ibf w1BusFactory) W1Driver { return &w1Driver{ busMap: make(map[byte]W1Bus), ibf: ibf, } } func (i *w1Driver) Bus(l byte) W1Bus { i.busMapLock.Lock() defer i.busMapLock.Unlock() if b, ok := i.busMap[l]; ok { return b } b := i.ibf(l) i.busMap[l] = b return b } func (i *w1Driver) Close() error { for _, b := range i.busMap { b.Close() } return nil }
package dao type CreatePoll struct { Question string Options []string } type OptionIdUserId struct { OptionId int ` binding:"required"` UserId int ` binding:"required"` } type QuestionIdUserId struct { QuestionId int ` binding:"required"` UserId int ` binding:"required"` }
// Package usecase defines the business logic of the requirement. // The general flow of the requirements are explicitly stated in the code. package usecase
package server import ( "net/http" "github.com/google/uuid" ) // RequestID retrieves the request id from the context. func RequestID(req *http.Request) uuid.UUID { requestID, ok := req.Context().Value(requestIDKey).(uuid.UUID) if !ok { return uuid.Nil } return requestID }
package transpose func Transpose(input []string) []string { if len(input) == 0 { return []string{} } totalNumberOfRows := maxRows(input) totalNumberOfColumns := len(input) output := make([]string, totalNumberOfRows[0]) for column := 0; column < totalNumberOfColumns; column++ { for row := 0; row < totalNumberOfRows[column]; row++ { if row < len(input[column]) { output[row] += string(input[column][row]) } else { output[row] += " " } } } return output } func maxRows(input []string) []int { maxForEachColumn := []int{} for _ = range input { maxForEachColumn = append(maxForEachColumn, 0) } maxForEachColumn[len(input) - 1] = len(input[len(input) - 1]) for i := len(input) - 2; i >= 0; i-- { maxForEachColumn[i] = max(maxForEachColumn[i + 1], len(input[i])) } return maxForEachColumn } func max(a, b int) int { if a > b { return a } return b }
package mt type AnimType uint8 const ( NoAnim AnimType = iota // none VerticalFrameAnim // vertical frame SpriteSheetAnim // sprite sheet maxAnim ) //go:generate stringer -linecomment -type AnimType type TileAnim struct { Type AnimType //mt:assert %s.Type < maxAnim //mt:if %s.Type == SpriteSheetAnim AspectRatio [2]uint8 //mt:end //mt:if %s.Type == VerticalFrameAnim NFrames [2]uint16 //mt:end //mt:if %s.Type != NoAnim Duration float32 // in seconds //mt:end }
package generator import ( "fmt" "github.com/jazztong/csla/cross" "github.com/jazztong/csla/provider/fileloader" "io/ioutil" "os" "path" ) type awsAPILambdaGolang struct { TemplatePrefix string } func (t *awsAPILambdaGolang) Generate(req Request) { // Create folder if err := os.Mkdir(req.Name, os.ModePerm); err != nil { panic(err) } for _, v := range t.Files() { if v.Generate(req) { binary, err := fileloader.Load(path.Join(t.TemplatePrefix, fmt.Sprintf("%s.tmpl", v.Name))) if err != nil { cross.Error(err.Error()) panic(err) } err = ioutil.WriteFile(path.Join(req.Name, v.Name), binary, os.ModeDevice) if err != nil { panic(err) } } } cross.Print("Init project %s successful", req.Name) } // NewAwsAPILambdaGolang create new generator for aws api lambda golang func NewAwsAPILambdaGolang() Generator { return &awsAPILambdaGolang{TemplatePrefix: "template/aws-api-lambda-golang"} } func (t *awsAPILambdaGolang) Files() []File { return []File{ File{Name: ".gitignore", Generate: func(req Request) bool { return true }}, File{Name: "main.go", Generate: func(req Request) bool { return true }}, File{Name: "Makefile", Generate: func(req Request) bool { return true }}, } }
package routes import ( "devbook-api/src/controllers" "net/http" ) var authRoute = Route{ URI: "/login", Method: http.MethodPost, Handler: controllers.Auth, RequestAuth: false, }
package transport // AdminSignIn 用户登录参数映射 type AdminSignIn struct { Username string `form:"username" json:"username" binding:"required"` Password string `form:"password" json:"password" binding:"required"` } // AdminCreate 创建后台用户映射 type AdminCreate struct { Username string `form:"username" json:"username" binding:"required"` Password string `form:"password" json:"password" binding:"required"` RepeatInput string `form:"repeat_input" json:"repeat_input" binding:"required,eqcsfield=Password"` NickName string `form:"nickname" json:"nickname" binding:"required"` Email string `form:"email" json:"email" binding:"required,email"` Note string `form:"note" json:"note"` }
package core import ( "io" "os" "path" "github.com/evan-buss/openbooks/dcc" "github.com/evan-buss/openbooks/util" ) func DownloadExtractDCCString(baseDir, dccStr string, progress io.Writer) (string, error) { // Download the file and wait until it is completed download, err := dcc.ParseString(dccStr) if err != nil { return "", err } dccPath := path.Join(baseDir, download.Filename) file, err := os.Create(dccPath) if err != nil { return "", err } writer := io.Writer(file) if progress != nil { writer = io.MultiWriter(file, progress) } // Download DCC data to the file err = download.Download(writer) if err != nil { return "", err } file.Close() if !util.IsArchive(dccPath) { return dccPath, nil } extractedPath, err := util.ExtractArchive(dccPath) if err != nil { return "", err } return extractedPath, nil }
package models_test import ( "github.com/APTrust/exchange/constants" "github.com/APTrust/exchange/models" "github.com/stretchr/testify/assert" "os" "testing" "time" ) var bagDate time.Time = time.Date(2104, 7, 2, 12, 0, 0, 0, time.UTC) var ingestDate time.Time = time.Date(2014, 9, 10, 12, 0, 0, 0, time.UTC) func SampleWorkItem() *models.WorkItem { return &models.WorkItem{ Id: 9000, ObjectIdentifier: "ncsu.edu/some_object", GenericFileIdentifier: "ncsu.edu/some_object/data/doc.pdf", Name: "Sample Document", Bucket: "aptrust.receiving.ncsu.edu", ETag: "12345", Size: 31337, BagDate: bagDate, InstitutionId: 324, Date: ingestDate, Note: "so many!", Action: "Ingest", Stage: "Store", Status: "Success", Outcome: "happy day!", Retry: true, Node: "", Pid: 0, NeedsAdminReview: false, CreatedAt: ingestDate, UpdatedAt: ingestDate, } } func TestWorkItemSerializeForPharos(t *testing.T) { workItem := SampleWorkItem() bytes, err := workItem.SerializeForPharos() if err != nil { t.Error(err) } expected := `{"action":"Ingest","aptrust_approver":null,"bag_date":"2104-07-02T12:00:00Z","bucket":"aptrust.receiving.ncsu.edu","date":"2014-09-10T12:00:00Z","etag":"12345","generic_file_identifier":"ncsu.edu/some_object/data/doc.pdf","inst_approver":null,"institution_id":324,"name":"Sample Document","needs_admin_review":false,"node":"","note":"so many!","object_identifier":"ncsu.edu/some_object","outcome":"happy day!","pid":0,"queued_at":null,"retry":true,"size":31337,"stage":"Store","stage_started_at":null,"status":"Success","user":""}` assert.Equal(t, expected, string(bytes)) } func TestWorkItemHasBeenStored(t *testing.T) { workItem := models.WorkItem{ Action: "Ingest", Stage: "Record", Status: "Success", } assert.True(t, workItem.HasBeenStored()) workItem.Stage = constants.StageCleanup assert.True(t, workItem.HasBeenStored()) workItem.Stage = constants.StageStore workItem.Status = constants.StatusPending assert.True(t, workItem.HasBeenStored()) workItem.Stage = constants.StageStore workItem.Status = constants.StatusStarted assert.False(t, workItem.HasBeenStored()) workItem.Stage = constants.StageFetch assert.False(t, workItem.HasBeenStored()) workItem.Stage = constants.StageUnpack assert.False(t, workItem.HasBeenStored()) workItem.Stage = constants.StageValidate assert.False(t, workItem.HasBeenStored()) } func TestIsStoring(t *testing.T) { workItem := models.WorkItem{ Action: "Ingest", Stage: "Store", Status: "Started", } assert.True(t, workItem.IsStoring()) workItem.Status = "Pending" assert.False(t, workItem.IsStoring()) workItem.Status = "Started" workItem.Stage = "Record" assert.False(t, workItem.IsStoring()) } func TestWorkItemShouldTryIngest(t *testing.T) { workItem := models.WorkItem{ Action: "Ingest", Stage: "Receive", Status: "Pending", Retry: true, } // Test stages assert.True(t, workItem.ShouldTryIngest()) workItem.Stage = "Fetch" assert.True(t, workItem.ShouldTryIngest()) workItem.Stage = "Unpack" assert.True(t, workItem.ShouldTryIngest()) workItem.Stage = "Validate" assert.True(t, workItem.ShouldTryIngest()) workItem.Stage = "Record" assert.False(t, workItem.ShouldTryIngest()) // Test Store/Pending and Store/Started workItem.Stage = "Store" workItem.Status = "Started" assert.False(t, workItem.ShouldTryIngest()) workItem.Stage = "Store" workItem.Status = "Pending" assert.False(t, workItem.ShouldTryIngest()) // Test Retry = false workItem.Status = "Started" workItem.Retry = false workItem.Stage = "Receive" assert.False(t, workItem.ShouldTryIngest()) workItem.Stage = "Fetch" assert.False(t, workItem.ShouldTryIngest()) workItem.Stage = "Unpack" assert.False(t, workItem.ShouldTryIngest()) workItem.Stage = "Validate" assert.False(t, workItem.ShouldTryIngest()) workItem.Stage = "Record" assert.False(t, workItem.ShouldTryIngest()) } func getWorkItems(action string) []*models.WorkItem { workItems := make([]*models.WorkItem, 3) workItems[0] = &models.WorkItem{ Action: action, Stage: "Resolve", Status: constants.StatusSuccess, } workItems[1] = &models.WorkItem{ Action: action, Stage: "Resolve", Status: constants.StatusFailed, } workItems[2] = &models.WorkItem{ Action: action, Stage: "Requested", Status: constants.StatusPending, } return workItems } func TestHasPendingDeleteRequest(t *testing.T) { workItems := getWorkItems(constants.ActionDelete) assert.True(t, models.HasPendingDeleteRequest(workItems)) workItems[2].Status = constants.StatusStarted assert.True(t, models.HasPendingDeleteRequest(workItems)) workItems[2].Status = constants.StatusCancelled assert.False(t, models.HasPendingDeleteRequest(workItems)) } func TestHasPendingRestoreRequest(t *testing.T) { workItems := getWorkItems(constants.ActionRestore) assert.True(t, models.HasPendingRestoreRequest(workItems)) workItems[2].Status = constants.StatusStarted assert.True(t, models.HasPendingRestoreRequest(workItems)) workItems[2].Status = constants.StatusCancelled assert.False(t, models.HasPendingRestoreRequest(workItems)) } func TestHasPendingIngestRequest(t *testing.T) { workItems := getWorkItems(constants.ActionIngest) assert.True(t, models.HasPendingIngestRequest(workItems)) workItems[2].Status = constants.StatusStarted assert.True(t, models.HasPendingIngestRequest(workItems)) workItems[2].Status = constants.StatusCancelled assert.False(t, models.HasPendingIngestRequest(workItems)) } func TestSetNodeAndPid(t *testing.T) { item := SampleWorkItem() item.SetNodeAndPid() hostname, _ := os.Hostname() if hostname == "" { assert.Equal(t, "hostname?", item.Node) } else { assert.Equal(t, hostname, item.Node) } assert.EqualValues(t, os.Getpid(), item.Pid) } func TestBelogsToOtherWorker(t *testing.T) { item := SampleWorkItem() assert.False(t, item.BelongsToAnotherWorker()) item.SetNodeAndPid() assert.False(t, item.BelongsToAnotherWorker()) item.Pid = item.Pid + 1 assert.True(t, item.BelongsToAnotherWorker()) item.Pid = item.Pid - 1 assert.False(t, item.BelongsToAnotherWorker()) item.Node = "some.other.host.kom" assert.True(t, item.BelongsToAnotherWorker()) } func TestIsInProgress(t *testing.T) { item := SampleWorkItem() item.Node = "" item.Pid = 0 assert.False(t, item.IsInProgress()) item.SetNodeAndPid() assert.True(t, item.IsInProgress()) } func TestIsPastIngest(t *testing.T) { item := SampleWorkItem() item.Stage = constants.StageReceive assert.False(t, item.IsPastIngest()) item.Stage = constants.StageFetch assert.False(t, item.IsPastIngest()) item.Stage = constants.StageUnpack assert.False(t, item.IsPastIngest()) item.Stage = constants.StageValidate assert.False(t, item.IsPastIngest()) item.Stage = constants.StageStore assert.True(t, item.IsPastIngest()) item.Stage = constants.StageRecord assert.True(t, item.IsPastIngest()) item.Stage = constants.StageCleanup assert.True(t, item.IsPastIngest()) } func TestMsgSkippingInProgress(t *testing.T) { item := SampleWorkItem() item.Id = 999 item.Name = "bag1.tar" item.Node = "node1" item.Pid = 1234 timestamp, _ := time.Parse(time.RFC3339, "2017-05-22T17:10:00Z") item.UpdatedAt = timestamp expected := "Marking NSQ message for WorkItem 999 (bag1.tar) as finished without doing any work, because this item is currently in process by node node1, pid 1234. WorkItem was last updated at 2017-05-22 17:10:00 +0000 UTC." assert.Equal(t, expected, item.MsgSkippingInProgress()) } func TestMsgPastIngest(t *testing.T) { item := SampleWorkItem() item.Id = 999 item.Name = "bag1.tar" expected := "Marking NSQ Message for WorkItem 999 (bag1.tar) as finished without doing any work, because this item is already past the ingest phase." assert.Equal(t, expected, item.MsgPastIngest()) } func TestMsgAlreadyOnDisk(t *testing.T) { item := SampleWorkItem() item.Name = "bag1.tar" expected := "Bag bag1.tar is already on disk and appears to be complete." assert.Equal(t, expected, item.MsgAlreadyOnDisk()) } func TestMsgAlreadyValidated(t *testing.T) { item := SampleWorkItem() item.Name = "bag1.tar" expected := "Bag bag1.tar has already been validated. Now it's going to the cleanup channel." assert.Equal(t, expected, item.MsgAlreadyValidated()) } func TestMsgGoingToValidation(t *testing.T) { item := SampleWorkItem() item.Name = "bag1.tar" expected := "Bag bag1.tar is going into the validation channel." assert.Equal(t, expected, item.MsgGoingToValidation()) } func TestMsgGoingToFetch(t *testing.T) { item := SampleWorkItem() item.Name = "bag1.tar" expected := "Bag bag1.tar is going into the fetch channel." assert.Equal(t, expected, item.MsgGoingToFetch()) }
/* Copyright (c) 2018 VMware, Inc. All Rights Reserved. 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 disk import ( "context" "flag" "fmt" "github.com/vmware/govmomi/govc/cli" "github.com/vmware/govmomi/govc/flags" "github.com/vmware/govmomi/object" ) type cp struct { *flags.DatastoreFlag spec } func init() { cli.Register("datastore.disk.cp", &cp{}) } func (cmd *cp) Register(ctx context.Context, f *flag.FlagSet) { cmd.DatastoreFlag, ctx = flags.NewDatastoreFlag(ctx) cmd.DatastoreFlag.Register(ctx, f) cmd.spec.Register(ctx, f) } func (cmd *cp) Usage() string { return "SRC DST" } func (cmd *cp) Description() string { return `Copy SRC to DST disk on DS. Examples: govc datastore.disk.cp disks/disk1.vmdk disks/disk2.vmdk` } func (cmd *cp) Run(ctx context.Context, f *flag.FlagSet) error { if f.NArg() != 2 { return flag.ErrHelp } dc, err := cmd.Datacenter() if err != nil { return err } ds, err := cmd.Datastore() if err != nil { return err } m := object.NewVirtualDiskManager(ds.Client()) src := ds.Path(f.Arg(0)) dst := ds.Path(f.Arg(1)) task, err := m.CopyVirtualDisk(ctx, src, dc, dst, dc, &cmd.spec.VirtualDiskSpec, cmd.force) if err != nil { return err } logger := cmd.ProgressLogger(fmt.Sprintf("Copying %s to %s...", src, dst)) defer logger.Wait() _, err = task.WaitForResult(ctx, logger) return err }
// Package pubsub contains utilities for handling Google Cloud Pub/Sub events. package pubsub import ( "fmt" "regexp" "strings" "time" "cloud.google.com/go/functions/metadata" "github.com/GoogleCloudPlatform/functions-framework-go/internal/fftypes" ) const ( pubsubEventType = "google.pubsub.topic.publish" pubsubMessageType = "type.googleapis.com/google.pubusb.v1.PubsubMessage" pubsubService = "pubsub.googleapis.com" ) // LegacyPushSubscriptionEvent is the event payload for legacy Cloud Pub/Sub // push subscription triggers (https://cloud.google.com/functions/docs/calling/pubsub#legacy_cloud_pubsub_triggers). // This matched the event payload that is sent by Pub/Sub to HTTP push // subscription endpoints (https://cloud.google.com/pubsub/docs/push#receiving_messages). type LegacyPushSubscriptionEvent struct { Subscription string `json:"subscription"` Message `json:"message"` } // Message represents a Pub/Sub message. type Message struct { // ID identifies this message. // This ID is assigned by the server and is populated for Messages obtained from a subscription. // This field is read-only. ID string `json:"messageId"` // Data is the actual data in the message. Data []byte `json:"data"` // Attributes represents the key-value pairs the current message // is labelled with. Attributes map[string]string `json:"attributes"` // The time at which the message was published. // This is populated by the server for Messages obtained from a subscription. // This field is read-only. PublishTime time.Time `json:"publishTime"` } // ExtractTopicFromRequestPath extracts a Pub/Sub topic from a URL request path. func ExtractTopicFromRequestPath(path string) (string, error) { re := regexp.MustCompile(`(projects\/[^/?]+\/topics\/[^/?]+)/*`) matches := re.FindStringSubmatch(path) if matches == nil { // Prevent log injection by removing newline characters in path replacer := strings.NewReplacer("\n", "", "\r", "") escapedPath := replacer.Replace(path) return "", fmt.Errorf("failed to extract Pub/Sub topic name from the URL request path: %q, configure your subscription's push endpoint to use the following path pattern: 'projects/PROJECT_NAME/topics/TOPIC_NAME'", escapedPath) } // Index 0 is the entire input string matched, index 1 is the first submatch return matches[1], nil } // ToBackgroundEvent converts the event to the standard BackgroundEvent format // for Background Functions. func (e *LegacyPushSubscriptionEvent) ToBackgroundEvent(topic string) *fftypes.BackgroundEvent { timestamp := e.Message.PublishTime if timestamp.IsZero() { timestamp = time.Now() } return &fftypes.BackgroundEvent{ Metadata: &metadata.Metadata{ EventID: e.ID, Timestamp: timestamp, EventType: pubsubEventType, Resource: &metadata.Resource{ Name: topic, Type: pubsubMessageType, Service: pubsubService, }, }, Data: map[string]interface{}{ "@type": pubsubMessageType, "data": e.Message.Data, "attributes": e.Message.Attributes, }, } }
package dic import ( "fmt" "bytes" "encoding/gob" "github.com/soundTricker/kagome/data" ) type Content struct { Pos, Pos1, Pos2, Pos3, Katuyougata, Katuyoukei, Kihonkei, Yomi, Pronunciation string } func (this Content) String() string { return fmt.Sprintf("%v, %v, %v, %v, %v, %v, %v, %v, %v", this.Pos, this.Pos1, this.Pos2, this.Pos3, this.Katuyougata, this.Katuyoukei, this.Kihonkei, this.Yomi, this.Pronunciation) } var Contents []Content func init() { vec, err := data.Asset("data/contents.dic") if err != nil { panic(err) } decorder := gob.NewDecoder(bytes.NewBuffer(vec)) if err = decorder.Decode(&Contents); err != nil { panic(err) } }
package perf import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strconv" "strings" "github.com/gofrs/uuid" "github.com/manifoldco/promptui" termbox "github.com/nsf/termbox-go" log "github.com/sirupsen/logrus" "github.com/layer5io/meshery/internal/sql" "github.com/ghodss/yaml" "github.com/layer5io/meshery/mesheryctl/internal/cli/root/config" "github.com/layer5io/meshery/mesheryctl/internal/cli/root/constants" "github.com/layer5io/meshery/mesheryctl/pkg/utils" "github.com/layer5io/meshery/models" "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/viper" ) var ( pageSize = 25 expand bool ) type profileStruct struct { Name string ID *uuid.UUID TotalResults int Endpoints []string QPS int Duration string Loadgenerators []string ServiceMesh string LastRun *sql.Time } var profileCmd = &cobra.Command{ Use: "profile [profile-name]", Short: "List performance profiles", Long: `List all the available performance profiles`, Args: cobra.MinimumNArgs(0), Example: ` // List performance profiles (maximum 25 profiles) mesheryctl perf profile // List performance profiles with search (maximum 25 profiles) mesheryctl perf profile test profile 2 // View single performance profile with detailed information mesheryctl perf profile --view `, RunE: func(cmd *cobra.Command, args []string) error { // used for searching performance profile var searchString string // setting up for error formatting cmdUsed = "profile" mctlCfg, err := config.GetMesheryCtl(viper.GetViper()) if err != nil { return ErrMesheryConfig(err) } profileURL := mctlCfg.GetBaseMesheryURL() + "/api/user/performance/profiles" // set default tokenpath for command. if tokenPath == "" { tokenPath = constants.GetCurrentAuthToken() } if len(args) > 0 { // Merge args to get profile-name searchString = strings.Join(args, "%20") } data, expandedData, body, err := fetchPerformanceProfiles(profileURL, searchString) if err != nil { return err } if len(data) == 0 { log.Info("No Performance Profiles to display") return nil } if outputFormatFlag != "" { var tempStruct *models.PerformanceProfilesAPIResponse err := json.Unmarshal(body, &tempStruct) if err != nil { return ErrFailUnmarshal(err) } body, _ = json.Marshal(tempStruct.Profiles) if outputFormatFlag == "yaml" { body, _ = yaml.JSONToYAML(body) } else if outputFormatFlag != "json" { return ErrInvalidOutputChoice() } log.Info(string(body)) } else if !expand { utils.PrintToTable([]string{"Name", "ID", "RESULTS", "Load-Generator", "Last-Run"}, data) } else { // if data consists only one profile, directly print profile index := 0 if len(data) > 1 { index, err = userPrompt("profile", "Enter index of the profile", data) if err != nil { return err } } a := expandedData[index] fmt.Printf("Name: %v\n", a.Name) fmt.Printf("ID: %s\n", a.ID.String()) fmt.Printf("Total Results: %d\n", a.TotalResults) fmt.Printf("Endpoint: %v\n", a.Endpoints[0]) fmt.Printf("Load Generators: %v\n", a.Loadgenerators[0]) fmt.Printf("Test run duration: %v\n", a.Duration) fmt.Printf("QPS: %d\n", a.QPS) fmt.Printf("Service Mesh: %v\n", a.ServiceMesh) if a.LastRun != nil { fmt.Printf("Last Run: %v\n", a.LastRun.Time.Format("2006-01-02 15:04:05")) } else { fmt.Printf("Last Run: %v\n", "nil") } } return nil }, } // Fetch all the profiles func fetchPerformanceProfiles(url, searchString string) ([][]string, []profileStruct, []byte, error) { client := &http.Client{} var response *models.PerformanceProfilesAPIResponse // update the url tempURL := fmt.Sprintf("%s?page_size=%d&page=%d", url, pageSize, resultPage-1) if searchString != "" { tempURL = tempURL + "&search=" + searchString } req, _ := http.NewRequest("GET", tempURL, nil) err := utils.AddAuthDetails(req, tokenPath) if err != nil { return nil, nil, nil, ErrAttachAuthToken(err) } resp, err := client.Do(req) if err != nil { return nil, nil, nil, ErrFailRequest(err) } // failsafe for not being authenticated if utils.ContentTypeIsHTML(resp) { return nil, nil, nil, ErrUnauthenticated() } // failsafe for the case when a valid uuid v4 is not an id of any pattern (bad api call) if resp.StatusCode != 200 { return nil, nil, nil, ErrFailReqStatus(resp.StatusCode) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, nil, nil, errors.Wrap(err, utils.PerfError("failed to read response body")) } err = json.Unmarshal(body, &response) if err != nil { return nil, nil, nil, ErrFailUnmarshal(err) } var data [][]string var expendedData []profileStruct for _, profile := range response.Profiles { // adding stuff to data for list output if profile.LastRun != nil { data = append(data, []string{profile.Name, profile.ID.String(), fmt.Sprintf("%d", profile.TotalResults), profile.LoadGenerators[0], profile.LastRun.Time.Format("2006-01-02 15:04:05")}) } else { data = append(data, []string{profile.Name, profile.ID.String(), fmt.Sprintf("%d", profile.TotalResults), profile.LoadGenerators[0], ""}) } // adding stuff to expendedData for expended output a := profileStruct{ Name: profile.Name, ID: profile.ID, TotalResults: profile.TotalResults, Endpoints: profile.Endpoints, QPS: profile.QPS, Duration: profile.Duration, Loadgenerators: profile.LoadGenerators, LastRun: profile.LastRun, ServiceMesh: profile.ServiceMesh, } expendedData = append(expendedData, a) } return data, expendedData, body, nil } func init() { profileCmd.Flags().BoolVarP(&expand, "view", "", false, "(optional) View single performance profile with more info") profileCmd.Flags().IntVarP(&resultPage, "page", "p", 1, "(optional) List next set of performance results with --page (default = 1)") } func userPrompt(key string, label string, data [][]string) (int, error) { err := termbox.Init() if err != nil { return -1, err } for i, a := range data { data[i] = append([]string{strconv.Itoa(i)}, a...) } if key == "result" { utils.PrintToTable([]string{"Index", "Name", "Mesh", "QPS", "Duration", "P50", "P99.9", "Start-Time"}, data) } else { utils.PrintToTable([]string{"Index", "Name", "ID", "RESULTS", "Load-Generator", "Last-Run"}, data) } fmt.Printf("\n") validate := func(input string) error { index, err := strconv.Atoi(input) if err != nil { return err } if index < 0 || index >= len(data) { return errors.New("Invalid index") } return nil } prompt := promptui.Prompt{ Label: label, Validate: validate, } result, err := prompt.Run() if err != nil { termbox.Close() return -1, fmt.Errorf("prompt failed %v", err) } termbox.Close() index, err := strconv.Atoi(result) if err != nil { return -1, err } return index, nil }
/* No one is quite certain what the emoticon >:U is intended to represent, but many scholars believe it looks like an angry duck. Let's assume that's the case. Task Given an integer n between 0 and 3 inclusive, print or return quack if n = 0, >:U if n = 1, U U > : U U > U U > : U U UUU if n = 2, or >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U>:U>:U if n = 3. You can assume the input will always be valid. There should be no leading space in the output, but any amount of trailing space is fine. Ducks (with the possible exception of @cobaltduck) have no tolerance for loopholes. Shortest code in bytes wins. */ package main import "fmt" func main() { for i := 0; i <= 3; i++ { quack(i) } } func quack(n int) { tab := []string{q0, q1, q2, q3} fmt.Println(tab[n&3]) } const q0 = `quack` const q1 = `>:U` const q2 = ` U U > : U U > U U > : U U UUU` const q3 = ` >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U >:U>:U>:U`
package gobchest import ( "fmt" "math/rand" "time" ) var ( pt = fmt.Printf ) func init() { rand.Seed(time.Now().UnixNano()) }
package response import ( //"encoding/json" ) func SuccRes() map[string]interface{} { return map[string]interface{} { "ok": true, } } func FailRes(message interface {}) map[string]interface{} { return map[string]interface{} { "ok": false, "message": message, } }
package container import ( "bitbucket.org/avanz/anotherPomodoro/common" "bitbucket.org/avanz/anotherPomodoro/custom/widget" "bitbucket.org/avanz/anotherPomodoro/repository" "encoding/json" "fmt" "fyne.io/fyne" "fyne.io/fyne/theme" "time" ) type PomodoroDoneContainer struct { *fyne.Container repository repository.IPomodoroRepository } func NewPomodoroDoneContainer(boxLayout fyne.Layout, repository repository.IPomodoroRepository) *PomodoroDoneContainer { container := &PomodoroDoneContainer{ Container: fyne.NewContainerWithLayout(boxLayout), repository: repository, } for i := 0; i < 48; i++ { pomodoro := widget.NewPomodoro(5, theme.BackgroundColor()) container.AddObject(pomodoro) } return container } type PomodoroStruct struct { TimeStarted string TimeDuration int } func (c PomodoroDoneContainer) AddPomodoro() { timeDuration := 25 * time.Minute err := c.repository.Read("settings", "timeDuration", &timeDuration) if err != nil { panic(err) } pauseDuration := 5 * time.Minute err = c.repository.Read("settings", "pauseDuration", &pauseDuration) if err != nil { panic(err) } workdoneToday := "workdone" + time.Now().Format("20060102") pomodoroList, _ := c.repository.ReadAll(workdoneToday) layout := "02-01-2006 15:04" started := time.Now().UTC() currentPosition := c.getPosition(started) skipInsert := false for _, pString := range pomodoroList { p := PomodoroStruct{} if err := json.Unmarshal([]byte(pString), &p); err != nil { common.MainErrorListener <- err } started, err := time.Parse(layout, p.TimeStarted) if err != nil { common.MainErrorListener <- err } pPosition := c.getPosition(started) if pPosition == currentPosition && !skipInsert { skipInsert = true } c.Objects[pPosition] = widget.NewPomodoro(5, common.Green) } if !skipInsert { pomodoroStruct := PomodoroStruct{ TimeStarted: started.Format(layout), TimeDuration: int(timeDuration.Minutes()), } if err := c.repository.Write(workdoneToday, fmt.Sprintf("pomodoro_%d", currentPosition), pomodoroStruct); err != nil { common.MainErrorListener <- err } } } func (c PomodoroDoneContainer) getPosition(started time.Time) int { pPosition := started.Hour() * 2 if started.Minute() > 30 { pPosition = pPosition + 1 } return pPosition }
package app import ( "errors" "github.com/BurntSushi/toml" "github.com/domac/ats_check/util" "path/filepath" ) type AppConfig struct { Parents []string Haproxys []string Parents_config_path string Remap_config_path string Records_config_path string Health_check string Retry int Retry_sleep_ms int Check_duration_second int filepath string Setup_records_config_cmd string Setup_parent_config_cmd string Is_parent int } //载入配置文件 func LoadConfig(fp string) (*AppConfig, error) { if fp == "" { return nil, errors.New("the config file dir is empty") } if err := util.CheckDataFileExist(fp); err != nil { return nil, err } var cfg *AppConfig if fp != "" { _, err := toml.DecodeFile(fp, &cfg) if err != nil { return nil, err } } cp, _ := filepath.Abs(fp) cfg.filepath = cp return cfg, nil }
package foundation import ( "fmt" "html/template" "io/ioutil" "os" "path/filepath" "strings" ) type ( _Template struct { Filters []Filter Delims Delimiters } Delimiters struct { Left, Right string } ) var ( Template _Template = _Template{ // Sets default html template filters Filters: []Filter{ Newline2BreakFilter(), RawFilter(), }, } ) // ToTemplateMap transfer func (t _Template) ToTemplateMap() map[string]interface{} { result := map[string]interface{}{} size := len(t.Filters) for i := 0; i < size; i++ { flt := t.Filters[i] result[flt.Name] = flt.Func } return result } // isValid checks func (d Delimiters) isValid() bool { return len(d.Left) > 0 && len(d.Right) > 0 } // Get returns delimiters of left and right. func (d Delimiters) Get() (string, string) { return d.Left, d.Right } func templateName(relativePath, filename string) string { relativePath = filepath.Clean(relativePath) filename = filepath.Clean(filename) name := strings.Replace(filename, relativePath+"/", "", -1) return name } // applyBody func applyBody(t *template.Template, names, bodies []string) (*template.Template, error) { for i := 0; i < len(names); i++ { name, body := names[i], bodies[i] var tmpl *template.Template if t == nil { t = template.New(name) } if name == t.Name() { tmpl = t } else { tmpl = t.New(name) } if len(Template.Filters) > 0 { tmpl = applyFilters(tmpl, Template.Filters...) } if Template.Delims.isValid() { tmpl.Delims(Template.Delims.Get()) } DebugPrintf("Parse as \"%s\"\n", name) _, err := tmpl.Parse(body) if err != nil { return nil, err } } return t, nil } // parseFiles is the helper for the method and function. If the argument // template is nil, it is created from the first file. func parseFiles(t *template.Template, relativePath string, filenames ...string) (*template.Template, error) { if len(filenames) == 0 { // Not really a problem, but be consistent. return nil, fmt.Errorf("html/template: no files named in call to ParseFiles") } for _, filename := range filenames { b, err := ioutil.ReadFile(filename) if err != nil { return nil, err } s := string(b) name := templateName(relativePath, filename) // First template becomes return value if not already defined, // and we use that one for subsequent New calls to associate // all the templates together. Also, if this file has the same name // as t, this file becomes the contents of t, so // t, err := New(name).Funcs(xxx).ParseFiles(name) // works. Otherwise we create a new template associated with t. var tmpl *template.Template if t == nil { t = template.New(name) } if name == t.Name() { tmpl = t } else { tmpl = t.New(name) } if len(Template.Filters) > 0 { tmpl = applyFilters(tmpl, Template.Filters...) } if Template.Delims.isValid() { tmpl.Delims(Template.Delims.Get()) } DebugPrintf("Parse as \"%s\"\n", name) _, err = tmpl.Parse(s) if err != nil { return nil, err } } return t, nil } // parseGlob is the implementation of the function and method ParseGlob. func parseGlob(t *template.Template, relativePath, pattern string) (*template.Template, error) { glob := func(t *template.Template, relativePath, pattern string) (*template.Template, error) { filenames, err := filepath.Glob(pattern) if err != nil { return nil, err } if len(filenames) == 0 { return nil, fmt.Errorf("html/template: pattern matches no files: %#q", pattern) } return parseFiles(t, relativePath, filenames...) } info, err := os.Stat(pattern) if err != nil { return nil, err } patterns := []string{} if info.IsDir() { walker := func(p string, f os.FileInfo, err error) error { if !f.IsDir() { patterns = append(patterns, p) } return nil } if err := filepath.Walk(pattern, walker); err != nil { return nil, err } } else { patterns = []string{pattern} } for _, pat := range patterns { templ, err := glob(t, relativePath, pat) if err != nil { return nil, err } t = templ } return t, nil } // applyFilters sets functions of template. func applyFilters(t *template.Template, filters ...Filter) *template.Template { funcMap := template.FuncMap{} for _, filter := range filters { if filter.Func == nil { continue } funcMap[filter.Name] = filter.Func } return t.Funcs(funcMap) }
package main import ( "bufio" "fmt" "github.com/pkg/errors" "gopkg.in/src-d/go-git.v4" "gopkg.in/src-d/go-git.v4/plumbing" "gopkg.in/src-d/go-git.v4/plumbing/filemode" "gopkg.in/src-d/go-git.v4/plumbing/object" "io" "log" "os" "path" "strings" "unicode" ) func main() { if len(os.Args) != 2 { log.Fatal("Expected exactly one argument: /path/to/git/repository") } repoPath := os.Args[1] repo, err := git.PlainOpen(repoPath) if err == git.ErrRepositoryNotExists { log.Fatalf("No git repository found: %s", repoPath) } else if err != nil { log.Fatal(errors.Wrap(err, "open git repository failed")) } branchRefs, err := repo.Branches() if err != nil { log.Fatal(errors.Wrap(err, "list branches failed")) } for { branchRef, err := branchRefs.Next() if err == io.EOF { break } else if err != nil { log.Fatal(errors.Wrap(err, "next branch failed")) } branchCommit, err := repo.CommitObject(branchRef.Hash()) if err == plumbing.ErrObjectNotFound { log.Fatalf("Branch %s points to invalid or non-commit ref %s", branchRef.Name(), branchRef.Hash()) } else if err != nil { log.Fatal(errors.Wrap(err, "find branch commit failed")) } branchTree, err := branchCommit.Tree() if err != nil { log.Fatal(errors.Wrap(err, "find branch tree failed")) } walker := object.NewTreeWalker(branchTree, true, map[plumbing.Hash]bool{}) fmt.Println(branchRef.Name()) for { entryPath, entry, err := walker.Next() if err == io.EOF { break } else if err != nil { log.Fatal(errors.Wrap(err, "tree walking failed")) } dirPath, _ := path.Split(entryPath) var dirDepth int if len(dirPath) > 0 { dirDepth = len(strings.Split(path.Clean(dirPath), "/")) } dirPadding := strings.Repeat("| ", dirDepth) fmt.Printf(" %s|- %s\n", dirPadding, getDisplayName(&entry, branchTree)) } } } func getDisplayName(entry *object.TreeEntry, tree *object.Tree) string { switch entry.Mode { case filemode.Empty: return fmt.Sprintf("%s [0]", entry.Name) case filemode.Dir: return fmt.Sprintf("%s/", entry.Name) case filemode.Regular, filemode.Deprecated: file, err := tree.TreeEntryFile(entry) if err != nil { log.Fatal(errors.Wrapf(err, "get file failed for entry %s", entry.Hash)) } var preview string if isBinary, err := file.IsBinary(); err != nil { log.Fatalf("Unable to test if file %s is binary: %s", file.Hash, err) } else if isBinary { preview = "(binary)" } else { reader, err := file.Reader() defer reader.Close() if err != nil { log.Fatalf("Unable to read file %s: %s", file.Hash, err) } fileHead, err := readBoundedString(bufio.NewReader(reader), 40) if err != nil { log.Fatalf("Unable to read head of file %s: %s", file.Hash, err) } preview = fmt.Sprintf(`"%s"`, fileHead) } return fmt.Sprintf("%s [%s] %s", file.Name, file.Hash.String()[:8], preview) case filemode.Executable: return fmt.Sprintf("%s [* %s]", entry.Name, entry.Hash.String()[:8]) case filemode.Symlink: return fmt.Sprintf("%s [->]", entry.Name) case filemode.Submodule: return fmt.Sprintf("%s [@]", entry.Name) } log.Fatalf("Unrecognized mode %s for entry: %s", entry.Mode, entry.Hash) panic("unreachable") } func readBoundedString(reader *bufio.Reader, maxLen int) (string, error) { var runes []rune for len(runes) < maxLen+1 { r, _, err := reader.ReadRune() if err == io.EOF { break } else if err != nil { return "", err } if !unicode.IsPrint(r) { if unicode.IsSpace(r) { r = ' ' } else { r = unicode.ReplacementChar } } runes = append(runes, r) } if len(runes) == maxLen+1 { // The file is longer than maxLen, so we need to abridge. runes = runes[:maxLen] runes[maxLen-1] = '…' } return string(runes), nil }
package gotoml import ( "fmt" ) const ( // parse erros CouldNotParse = iota // get errors KeyNotFound InvalidType ) type ParseError struct { Reason int LineNumber int } type GetError struct { Reason int RequestedKey string RequestedType string ActualValue string } func (e *GetError) Error() string { switch e.Reason { case KeyNotFound: return fmt.Sprintf("Could not find key %s of type %s", e.RequestedKey, e.RequestedType) case InvalidType: return fmt.Sprintf("Could not parse key %s as type %s", e.RequestedKey, e.RequestedType) } return "Unknown reason for GetError" } func NewKeyNotFoundError(k string, t string) *GetError { return &GetError{KeyNotFound, k, t, ""} } func NewInvalidTypeError(k string, v string, t string) *GetError { return &GetError{InvalidType, k, t, v} }
package main_test import ( analysis "github.com/plholx/awesome-go-analysis" "testing" ) func TestInitDB(t *testing.T){ analysis.InitDB() }
package main import ( "fmt" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type GeneralRecord struct { Type string `bson:"type"` } type Person struct { Name string `bson:"name"` Phone string `bson:"phone"` } type Company struct { Name string `bson:"company"` Boss string `bson:"boss"` } func main() { session, err := mgo.Dial("localhost") if err != nil { panic(err) } defer session.Close() // Optional. Switch the session to a monotonic behavior. session.SetMode(mgo.Monotonic, true) var rawRecords []*bson.Raw c := session.DB("test").C("people") if err := c.Find(nil).All(&rawRecords); err != nil { panic(err) } else { var general GeneralRecord var person Person var company Company for _, raw := range rawRecords { if err = raw.Unmarshal(&general); err != nil { panic(err) } fmt.Println("typetest", general.Type) switch general.Type { case "person": if err = raw.Unmarshal(&person); err != nil { panic(err) } else { fmt.Printf("Person: %#v\n", person) } case "company": if err = raw.Unmarshal(&company); err != nil { panic(err) } else { fmt.Printf("Company: %#v\n", company) } } } } }
package cmd import ( "github.com/myechuri/ukd/server/api" "github.com/spf13/cobra" "golang.org/x/net/context" "google.golang.org/grpc" "log" ) var ( ukName string imageLocation string serverAddress string visor string ) func start(cmd *cobra.Command, args []string) { // TODO: TLS serverAddress := cmd.InheritedFlags().Lookup("server-endpoint").Value.String() conn, err := grpc.Dial(serverAddress, grpc.WithInsecure()) if err != nil { log.Fatalf("fail to dial: %v", err) } defer conn.Close() client := api.NewUkdClient(conn) startRequest := &api.StartRequest{ Name: ukName, Visor: visor, Location: imageLocation, } reply, _ := client.Start(context.Background(), startRequest) log.Printf("Application unikernel started: %t, IP: %s, Info: %s", reply.Success, reply.Ip, reply.Info) } func StartCommand() *cobra.Command { var startCmd = &cobra.Command{ Use: "start", Short: "Start a Unikernel", Long: `Start a unikernel with a given name and image location, using given hypervisor (default: kvm-qemu)`, Run: func(cmd *cobra.Command, args []string) { start(cmd, args) }, } startCmd.Flags().StringVar(&ukName, "name", "", "name of the application") startCmd.Flags().StringVar(&imageLocation, "image-location", "", "location of the application image") startCmd.Flags().StringVar(&visor, "hypervisor", "kvm-qemu", "hypervisor to use") return startCmd }
package main import ( "bufio" "fmt" "os" "strconv" ) func main() { reader := bufio.NewReaderSize(os.Stdin, 100001) line, _, _ := reader.ReadLine() t, _ := strconv.Atoi(string(line)) for ; t > 0; t-- { text, _, _ := reader.ReadLine() cnt := 0 for i := 0; i < len(text)-1; i++ { if text[i] == text[i+1] { cnt++ } } fmt.Println(cnt) } }
package local import ( "fmt" "os" "os/exec" "path/filepath" "runtime" "time" "github.com/fatih/color" "github.com/linuxkit/rtf/logger" "github.com/linuxkit/rtf/sysinfo" ) const ( // GroupFileName is the name of the group script (without the extension) GroupFileName = "group" // PreTestFileName is the name of a pre-test script (without the extension) PreTestFileName = "pre-test" // PostTestFileName is the name of a post-test script (without the extension) PostTestFileName = "post-test" // TestFileName is the name of a test script (without the extension) TestFileName = "test" ) // checkScript checks if a script with 'name' exists in 'path' func checkScript(path, name string) (string, error) { // On Windows, powershell scripts take precedence. if runtime.GOOS == "windows" { f := filepath.Join(path, name+".ps1") if _, err := os.Stat(f); err == nil { return f, nil } } f := filepath.Join(path, name+".sh") if _, err := os.Stat(f); err != nil { // On non-windows, shell scripts take precedence but we check for powershell too if runtime.GOOS != "windows" { f := filepath.Join(path, name+".ps1") if _, err := os.Stat(f); err == nil { return f, nil } } return "", err } return f, nil } // Project is a group of tests and other groups with a few higher level functions type Project struct { *Group shard int totalShards int } // Group is a group of tests and other groups type Group struct { Parent *Group Tags *Tags Path string GroupFilePath string PreTestPath string PostTestPath string order int Labels map[string]bool NotLabels map[string]bool Children []TestContainer } // Test is a test type Test struct { Parent *Group Tags *Tags Path string TestFilePath string Command exec.Cmd Repeat int order int Summary string Author string Labels map[string]bool NotLabels map[string]bool } // TestResult is the result of a test run type TestResult int const ( // Pass is a test pass Pass = iota // Fail is a test failure Fail // Skip is a test skip Skip // Cancel is a test cancellation Cancel ) // TestResultNames provides a mapping of numerical result values to human readable strings var TestResultNames = map[TestResult]string{ Pass: "Pass", Fail: "Fail", Skip: "Skip", Cancel: "Cancel", } // Sprintf prints the arguments using fmt.Sprintf but colours it depending on the TestResult func (r TestResult) Sprintf(format string, a ...interface{}) string { switch r { case Pass: return color.GreenString(format, a...) case Fail: return color.RedString(format, a...) case Cancel: return color.YellowString(format, a...) case Skip: return color.YellowString(format, a...) } return fmt.Sprintf(format, a...) } // TestResultColorFunc provides a mapping of numerical result values to a fmt.Sprintf() style function var TestResultColorFunc = map[TestResult]func(a ...interface{}) string{} // Result encapsulates a TestResult and additional data about a test run type Result struct { Test *Test `json:"-"` Name string `json:"name,omitempty"` // Name may be different to Test.Name() for repeated tests. TestResult TestResult `json:"result"` BenchmarkResult string `json:"benchmark,omitempty"` StartTime time.Time `json:"start,omitempty"` EndTime time.Time `json:"end,omitempty"` Duration time.Duration `json:"duration,omitempty"` } // Info encapsulates the information necessary to list tests and test groups type Info struct { Name string TestResult TestResult Summary string Issue string Labels map[string]bool NotLabels map[string]bool } // LabelString returns all labels in a comma separated string func (i *Info) LabelString() string { return makeLabelString(i.Labels, i.NotLabels, ", ") } // OSInfo contains information about the OS the tests are running on type OSInfo struct { OS string Version string Name string Arch string } // RunConfig contains runtime configuration information type RunConfig struct { Extra bool CaseDir string LogDir string Logger logger.LogDispatcher SystemInfo sysinfo.SystemInfo Labels map[string]bool NotLabels map[string]bool TestPattern string Parallel bool IncludeInit bool restrictToTests map[string]bool } // GroupCommand is a command that is runnable, either a test or pre/post script. type GroupCommand struct { Name string Type string FilePath string Path string } // TestContainer is a container that can hold one or more tests type TestContainer interface { Order() int List(config RunConfig) []Info Run(config RunConfig) ([]Result, error) Gather(config RunConfig) ([]TestContainer, int) } // ByOrder implements the sort.Sorter interface for TestContainer type ByOrder []TestContainer // Len returns the length of the []TestContainer func (a ByOrder) Len() int { return len(a) } // Swap swaps two items in a []TestContainer func (a ByOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] } // Less compares whether the order of i is less than that of j func (a ByOrder) Less(i, j int) bool { return a[i].Order() < a[j].Order() } // Summary contains a summary of a whole run, mostly used for writing out a JSON file type Summary struct { ID string `json:"id,omitempty"` StartTime time.Time `json:"start,omitempty"` EndTime time.Time `json:"end,omitempty"` SystemInfo sysinfo.SystemInfo `json:"system,omitempty"` Labels []string `json:"labels,omitempty"` Results []Result `json:"results,omitempty"` }
package Parse import ( "../Misc" "bufio" "errors" "os" ) //Parsing -p and -P supplied parameters func ParsePass(h *Misc.HostInfo) ([]string, error) { switch { case h.Passfile != "" && h.Password != "": return nil, errors.New("-p and -P cannot exist at the same time") case h.Passfile == "" && h.Password == "": return nil, errors.New("Please use -p or -P to specify the username") case h.Passfile == "" && h.Password != "": return []string{h.Password}, nil case h.Passfile != "" && h.Password == "": file, err := Readfile(h.Passfile) return file, err } return nil, errors.New("unknown error") } //Parsing -u and -U supplied parameters func ParseUser(h *Misc.HostInfo) ([]string, error) { switch { case h.Userfile != "" && h.Username != "": return nil, errors.New("-u and -U cannot exist at the same time") case h.Userfile == "" && h.Username == "": return nil, errors.New("Please use -u or -U to specify the username") case h.Userfile == "" && h.Username != "": return []string{h.Username}, nil case h.Userfile != "" && h.Username == "": file, err := Readfile(h.Userfile) return file, err } return nil, errors.New("unknown error") } //Read the contents of the file func Readfile(filename string) ([]string, error) { file, err := os.Open(filename) if err != nil { return nil, errors.New("There was an error opening the file") } var content []string scanner := bufio.NewScanner(file) for scanner.Scan() { content = append(content, scanner.Text()) } return content, nil }
// Copyright 2021 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. package paging import "math" // A paging request may be separated into multi requests if there are more data than a page. // The paging size grows from min to max. See https://github.com/pingcap/tidb/issues/36328 // e.g. a paging request scans over range (r1, r200), it requires 128 rows in the first batch, // if it's not drained, then the paging size grows, the new range is calculated like (r100, r200), then send a request again. // Compare with the common unary request, paging request allows early access of data, it offers a streaming-like way processing data. const ( MinPagingSize uint64 = 128 maxPagingSizeShift = 7 pagingSizeGrow = 2 MaxPagingSize = 50000 pagingGrowingSum = ((2 << maxPagingSizeShift) - 1) * MinPagingSize Threshold uint64 = 960 ) // GrowPagingSize grows the paging size and ensures it does not exceed MaxPagingSize func GrowPagingSize(size uint64, max uint64) uint64 { if max < MaxPagingSize { // Defensive programing, for example, call with max = 0. // max should never less than MaxPagingSize. // Otherwise the session variable maybe wrong, or the distsql request does not obey the session variable setting. max = MaxPagingSize } size <<= 1 if size > max { return max } return size } // CalculateSeekCnt calculates the seek count from expect count func CalculateSeekCnt(expectCnt uint64) float64 { if expectCnt == 0 { return 0 } if expectCnt > pagingGrowingSum { // if the expectCnt is larger than pagingGrowingSum, calculate the seekCnt for the excess. return float64(8 + (expectCnt-pagingGrowingSum+MaxPagingSize-1)/MaxPagingSize) } if expectCnt > MinPagingSize { // if the expectCnt is less than pagingGrowingSum, // calculate the seekCnt(number of terms) from the sum of a geometric progression. // expectCnt = minPagingSize * (pagingSizeGrow ^ seekCnt - 1) / (pagingSizeGrow - 1) // simplify (pagingSizeGrow ^ seekCnt - 1) to pagingSizeGrow ^ seekCnt, we can infer that // seekCnt = log((pagingSizeGrow - 1) * expectCnt / minPagingSize) / log(pagingSizeGrow) return 1 + float64(int(math.Log(float64((pagingSizeGrow-1)*expectCnt)/float64(MinPagingSize))/math.Log(float64(pagingSizeGrow)))) } return 1 }
// Copyright (c) 2020 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package starlark import ( "fmt" "os" "path/filepath" "strings" "testing" "go.starlark.net/starlark" "go.starlark.net/starlarkstruct" ) func TestKubeCapture(t *testing.T) { tests := []struct { name string kwargs func(t *testing.T) []starlark.Tuple eval func(t *testing.T, kwargs []starlark.Tuple) }{ { name: "simple test with namespaced objects", kwargs: func(t *testing.T) []starlark.Tuple { return []starlark.Tuple{ []starlark.Value{starlark.String("what"), starlark.String("objects")}, []starlark.Value{starlark.String("groups"), starlark.NewList([]starlark.Value{starlark.String("core")})}, []starlark.Value{starlark.String("kinds"), starlark.NewList([]starlark.Value{starlark.String("services")})}, []starlark.Value{starlark.String("namespaces"), starlark.NewList([]starlark.Value{starlark.String("default"), starlark.String("kube-system")})}, } }, eval: func(t *testing.T, kwargs []starlark.Tuple) { val, err := KubeCaptureFn(newTestThreadLocal(t), nil, nil, kwargs) if err != nil { t.Fatalf("failed to execute: %s", err) } resultStruct, ok := val.(*starlarkstruct.Struct) if !ok { t.Fatalf("expecting type *starlarkstruct.Struct, got %T", val) } errVal, err := resultStruct.Attr("error") if err != nil { t.Error(err) } resultErr := errVal.(starlark.String).GoString() if resultErr != "" { t.Fatalf("starlark func failed: %s", resultErr) } fileVal, err := resultStruct.Attr("file") if err != nil { t.Error(err) } fileValStr, ok := fileVal.(starlark.String) if !ok { t.Fatalf("unexpected type for starlark value") } workDir := fileValStr.GoString() fileInfo, err := os.Stat(workDir) if err != nil { t.Fatalf("stat(%s) failed: %s", workDir, err) } if !fileInfo.IsDir() { t.Fatalf("expecting starlark function to return a dir") } defer os.RemoveAll(workDir) path := filepath.Join(workDir, "core_v1", "kube-system") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s to be a directory", path) } files, err := os.ReadDir(path) if err != nil { t.Fatalf("ReadeDir(%s) failed: %s", path, err) } if len(files) < 1 { t.Errorf("directory should have at least 1 file but has none: %s:", path) } path = filepath.Join(workDir, "core_v1", "default") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s to exist: %s", path, err) } files, err = os.ReadDir(path) if err != nil { t.Fatalf("ReadeDir(%s) failed: %s", path, err) } if len(files) < 1 { t.Errorf("directory should have at least 1 file but has none: %s:", path) } }, }, { name: "test for non-namespaced objects", kwargs: func(t *testing.T) []starlark.Tuple { return []starlark.Tuple{ []starlark.Value{starlark.String("what"), starlark.String("objects")}, []starlark.Value{starlark.String("groups"), starlark.NewList([]starlark.Value{starlark.String("core")})}, []starlark.Value{starlark.String("kinds"), starlark.NewList([]starlark.Value{starlark.String("nodes")})}, } }, eval: func(t *testing.T, kwargs []starlark.Tuple) { val, err := KubeCaptureFn(newTestThreadLocal(t), nil, nil, kwargs) if err != nil { t.Fatalf("failed to execute: %s", err) } resultStruct, ok := val.(*starlarkstruct.Struct) if !ok { t.Fatalf("expecting type *starlarkstruct.Struct, got %T", val) } errVal, err := resultStruct.Attr("error") if err != nil { t.Error(err) } resultErr := errVal.(starlark.String).GoString() if resultErr != "" { t.Fatalf("starlark func failed: %s", resultErr) } fileVal, err := resultStruct.Attr("file") if err != nil { t.Error(err) } fileValStr, ok := fileVal.(starlark.String) if !ok { t.Fatalf("unexpected type for starlark value") } captureDir := fileValStr.GoString() defer os.RemoveAll(captureDir) path := filepath.Join(captureDir, "core_v1") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s file to exist: %s", path, err) } files, err := os.ReadDir(path) if err != nil { t.Fatalf("ReadeDir(%s) failed: %s", path, err) } if len(files) != 1 { t.Errorf("directory should have at least 1 file but has none: %s:", path) } if files[0].IsDir() { t.Errorf("expecting to find a regular file, but found dir: %s", files[0].Name()) } if !strings.Contains(files[0].Name(), "nodes-") { t.Errorf("expecting to find a node output file, but fond: %s", files[0].Name()) } }, }, { name: "simple test with objects in categories", kwargs: func(t *testing.T) []starlark.Tuple { return []starlark.Tuple{ []starlark.Value{starlark.String("what"), starlark.String("objects")}, []starlark.Value{starlark.String("groups"), starlark.NewList([]starlark.Value{starlark.String("core")})}, []starlark.Value{starlark.String("categories"), starlark.NewList([]starlark.Value{starlark.String("all")})}, []starlark.Value{starlark.String("namespaces"), starlark.NewList([]starlark.Value{starlark.String("default"), starlark.String("kube-system")})}, } }, eval: func(t *testing.T, kwargs []starlark.Tuple) { val, err := KubeCaptureFn(newTestThreadLocal(t), nil, nil, kwargs) if err != nil { t.Fatalf("failed to execute: %s", err) } resultStruct, ok := val.(*starlarkstruct.Struct) if !ok { t.Fatalf("expecting type *starlarkstruct.Struct, got %T", val) } errVal, err := resultStruct.Attr("error") if err != nil { t.Error(err) } resultErr := errVal.(starlark.String).GoString() if resultErr != "" { t.Fatalf("starlark func failed: %s", resultErr) } fileVal, err := resultStruct.Attr("file") if err != nil { t.Error(err) } fileValStr, ok := fileVal.(starlark.String) if !ok { t.Fatalf("unexpected type for starlark value") } captureDir := fileValStr.GoString() defer os.RemoveAll(captureDir) fileInfo, err := os.Stat(captureDir) if err != nil { t.Fatalf("stat(%s) failed: %s", captureDir, err) } if !fileInfo.IsDir() { t.Fatalf("expecting starlark function to return a dir") } path := filepath.Join(captureDir, "core_v1", "kube-system") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s to be a directory", path) } path = filepath.Join(captureDir, "core_v1", "default") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s to exist: %s", path, err) } files, err := os.ReadDir(path) if err != nil { t.Fatalf("ReadeDir(%s) failed: %s", path, err) } if len(files) < 1 { t.Errorf("directory should have at least 1 file but has none: %s:", path) } }, }, { name: "search for all logs in a namespace", kwargs: func(t *testing.T) []starlark.Tuple { return []starlark.Tuple{ []starlark.Value{starlark.String("what"), starlark.String("logs")}, []starlark.Value{starlark.String("namespaces"), starlark.NewList([]starlark.Value{starlark.String("kube-system")})}, } }, eval: func(t *testing.T, kwargs []starlark.Tuple) { val, err := KubeCaptureFn(newTestThreadLocal(t), nil, nil, kwargs) if err != nil { t.Fatalf("failed to execute: %s", err) } resultStruct, ok := val.(*starlarkstruct.Struct) if !ok { t.Fatalf("expecting type *starlarkstruct.Struct, got %T", val) } errVal, err := resultStruct.Attr("error") if err != nil { t.Error(err) } resultErr := errVal.(starlark.String).GoString() if resultErr != "" { t.Fatalf("starlark func failed: %s", resultErr) } fileVal, err := resultStruct.Attr("file") if err != nil { t.Error(err) } fileValStr, ok := fileVal.(starlark.String) if !ok { t.Fatalf("unexpected type for starlark value") } captureDir := fileValStr.GoString() if _, err := os.Stat(captureDir); err != nil { t.Fatalf("stat(%s) failed: %s", captureDir, err) } defer os.RemoveAll(captureDir) path := filepath.Join(captureDir, "core_v1", "kube-system") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s to be a directory", path) } files, err := os.ReadDir(path) if err != nil { t.Fatalf("ReadeDir(%s) failed: %s", path, err) } if len(files) < 3 { t.Error("unexpected number of log files for namespace kube-system:", len(files)) } }, }, { name: "search for logs for a specific container", kwargs: func(t *testing.T) []starlark.Tuple { return []starlark.Tuple{ []starlark.Value{starlark.String("what"), starlark.String("logs")}, []starlark.Value{starlark.String("namespaces"), starlark.NewList([]starlark.Value{starlark.String("kube-system")})}, []starlark.Value{starlark.String("containers"), starlark.NewList([]starlark.Value{starlark.String("etcd")})}, } }, eval: func(t *testing.T, kwargs []starlark.Tuple) { val, err := KubeCaptureFn(newTestThreadLocal(t), nil, nil, kwargs) if err != nil { t.Fatalf("failed to execute: %s", err) } resultStruct, ok := val.(*starlarkstruct.Struct) if !ok { t.Fatalf("expecting type *starlarkstruct.Struct, got %T", val) } errVal, err := resultStruct.Attr("error") if err != nil { t.Error(err) } resultErr := errVal.(starlark.String).GoString() if resultErr != "" { t.Fatalf("starlark func failed: %s", resultErr) } fileVal, err := resultStruct.Attr("file") if err != nil { t.Error(err) } fileValStr, ok := fileVal.(starlark.String) if !ok { t.Fatalf("unexpected type for starlark value") } captureDir := fileValStr.GoString() if _, err := os.Stat(captureDir); err != nil { t.Fatalf("stat(%s) failed: %s", captureDir, err) } defer os.RemoveAll(captureDir) path := filepath.Join(captureDir, "core_v1", "kube-system") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s to be a directory", path) } files, err := os.ReadDir(path) if err != nil { t.Fatalf("ReadeDir(%s) failed: %s", path, err) } if len(files) == 0 { t.Error("unexpected number of log files for namespace kube-system:", len(files)) } }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { test.eval(t, test.kwargs(t)) }) } } func TestKubeCaptureScript(t *testing.T) { workdir := testSupport.TmpDirRoot() k8sconfig := testSupport.KindKubeConfigFile() clusterCtxName := testSupport.KindClusterContextName() execute := func(t *testing.T, script string) *starlarkstruct.Struct { executor := New() if err := executor.Exec("test.kube.capture", strings.NewReader(script)); err != nil { t.Fatalf("failed to exec: %s", err) } if !executor.result.Has("kube_data") { t.Fatalf("script result must be assigned to a value") } data, ok := executor.result["kube_data"].(*starlarkstruct.Struct) if !ok { t.Fatal("script result is not a struct") } return data } tests := []struct { name string script string eval func(t *testing.T, script string) }{ { name: "simple search with namespaced objects with cluster context", script: fmt.Sprintf(` crashd_config(workdir="%s") set_defaults(kube_config(path="%s", cluster_context="%s")) kube_data = kube_capture(what="objects", groups=["core"], kinds=["services"], namespaces=["default", "kube-system"])`, workdir, k8sconfig, clusterCtxName), eval: func(t *testing.T, script string) { data := execute(t, script) fileVal, err := data.Attr("file") if err != nil { t.Error(err) } fileValStr, ok := fileVal.(starlark.String) if !ok { t.Fatalf("unexpected type for starlark value") } workDir := fileValStr.GoString() fileInfo, err := os.Stat(workDir) if err != nil { t.Fatalf("stat(%s) failed: %s", workDir, err) } if !fileInfo.IsDir() { t.Fatalf("expecting starlark function to return a dir") } defer os.RemoveAll(workDir) path := filepath.Join(workDir, "core_v1", "kube-system") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s to be a directory", path) } files, err := os.ReadDir(path) if err != nil { t.Fatalf("ReadeDir(%s) failed: %s", path, err) } if len(files) < 1 { t.Errorf("directory should have at least 1 file but has none: %s:", path) } path = filepath.Join(workDir, "core_v1", "default") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s to exist", path) } files, err = os.ReadDir(path) if err != nil { t.Fatalf("ReadeDir(%s) failed: %s", path, err) } if len(files) < 1 { t.Errorf("directory should have at least 1 file but has none: %s:", path) } }, }, { name: "search with non-namespaced objects", script: fmt.Sprintf(` crashd_config(workdir="%s") set_defaults(kube_config(path="%s")) kube_data = kube_capture(what="objects", groups=["core"], kinds=["nodes"])`, workdir, k8sconfig), eval: func(t *testing.T, script string) { data := execute(t, script) fileVal, err := data.Attr("file") if err != nil { t.Error(err) } fileValStr, ok := fileVal.(starlark.String) if !ok { t.Fatalf("unexpected type for starlark value") } captureDir := fileValStr.GoString() defer os.RemoveAll(captureDir) path := filepath.Join(captureDir, "core_v1") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s file to exist", path) } files, err := os.ReadDir(path) if err != nil { t.Fatalf("ReadeDir(%s) failed: %s", path, err) } if len(files) != 1 { t.Errorf("directory should have at least 1 file but has none: %s:", path) } if files[0].IsDir() { t.Errorf("expecting to find a regular file, but found dir: %s", files[0].Name()) } if !strings.Contains(files[0].Name(), "nodes-") { t.Errorf("expecting to find a node output file, but fond: %s", files[0].Name()) } }, }, { name: "search with objects in categories", script: fmt.Sprintf(` crashd_config(workdir="%s") set_defaults(kube_config(path="%s")) kube_data = kube_capture(what="objects", groups=["core"], categories=["all"], namespaces=["default","kube-system"])`, workdir, k8sconfig), eval: func(t *testing.T, script string) { data := execute(t, script) fileVal, err := data.Attr("file") if err != nil { t.Error(err) } fileValStr, ok := fileVal.(starlark.String) if !ok { t.Fatalf("unexpected type for starlark value") } captureDir := fileValStr.GoString() defer os.RemoveAll(captureDir) fileInfo, err := os.Stat(captureDir) if err != nil { t.Fatalf("stat(%s) failed: %s", captureDir, err) } if !fileInfo.IsDir() { t.Fatalf("expecting starlark function to return a dir") } path := filepath.Join(captureDir, "core_v1", "kube-system") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s to be a directory", path) } path = filepath.Join(captureDir, "core_v1", "default") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s to exist", path) } files, err := os.ReadDir(path) if err != nil { t.Fatalf("ReadeDir(%s) failed: %s", path, err) } if len(files) < 1 { t.Errorf("directory should have at least 1 file but has none: %s:", path) } }, }, { name: "search for all logs in a namespace with cluster context", script: fmt.Sprintf(` crashd_config(workdir="%s") set_defaults(kube_config(path="%s", cluster_context="%s")) kube_data = kube_capture(what="logs", namespaces=["kube-system"])`, workdir, k8sconfig, clusterCtxName), eval: func(t *testing.T, script string) { data := execute(t, script) fileVal, err := data.Attr("file") if err != nil { t.Error(err) } fileValStr, ok := fileVal.(starlark.String) if !ok { t.Fatalf("unexpected type for starlark value") } captureDir := fileValStr.GoString() if _, err := os.Stat(captureDir); err != nil { t.Fatalf("stat(%s) failed: %s", captureDir, err) } defer os.RemoveAll(captureDir) path := filepath.Join(captureDir, "core_v1", "kube-system") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s to be a directory", path) } files, err := os.ReadDir(path) if err != nil { t.Fatalf("ReadeDir(%s) failed: %s", path, err) } if len(files) < 3 { t.Error("unexpected number of log files for namespace kube-system:", len(files)) } }, }, { name: "search for logs in specific container", script: fmt.Sprintf(` crashd_config(workdir="%s") set_defaults(kube_config(path="%s")) kube_data = kube_capture(what="logs", namespaces=["kube-system"], containers=["etcd"])`, workdir, k8sconfig), eval: func(t *testing.T, script string) { data := execute(t, script) fileVal, err := data.Attr("file") if err != nil { t.Error(err) } fileValStr, ok := fileVal.(starlark.String) if !ok { t.Fatalf("unexpected type for starlark value") } captureDir := fileValStr.GoString() if _, err := os.Stat(captureDir); err != nil { t.Fatalf("stat(%s) failed: %s", captureDir, err) } defer os.RemoveAll(captureDir) path := filepath.Join(captureDir, "core_v1", "kube-system") if _, err := os.Stat(path); err != nil { t.Fatalf("expecting %s to be a directory", path) } files, err := os.ReadDir(path) if err != nil { t.Fatalf("ReadeDir(%s) failed: %s", path, err) } if len(files) == 0 { t.Error("unexpected number of log files for namespace kube-system:", len(files)) } }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { test.eval(t, test.script) }) } } func TestKubeCapture_WithBadKubeconfig(t *testing.T) { script := ` cfg = kube_config(path="/foo/bar") kube_capture(what="logs", namespaces=["kube-system"], containers=["etcd"], kube_config=cfg) ` executor := New() if err := executor.Exec("test.kube.capture", strings.NewReader(script)); err == nil { t.Fatalf("expected failure, but did not get it") } }
package main import ( "fmt" "math/rand" "time" ) func generateRandomNrBetween(low int, high int) int { return rand.Intn(high-low) + low + 1 } func guessNumberBetweenNumbers(number int, low int, high int) { var tries = 0 rand.Seed(time.Now().UnixNano()) for { tries++ fmt.Printf("\nTry %1v - ", tries) fmt.Printf("Guess between %2v and %3v: ", low, high) var guess = generateRandomNrBetween(low, high) if guess == number { fmt.Println("Guess correct. The number was 17") break } else if guess > number { high = guess fmt.Printf("Your guess %3v is too big", guess) } else { low = guess fmt.Printf("Your guess %3v is too small", guess) } } }
package lintcode /** * @param n: An integer * @param nums: An array * @return: the Kth largest element */ func kthLargestElement(n int, nums []int) int { quickSort(nums) return nums[len(nums)-n] } func quickSort(nums []int) { if len(nums) == 0 || len(nums) == 1 { return } i := 0 j := len(nums) - 1 for i < j { for j-1 >= 0 && j > i && nums[j] >= nums[0] { j-- } for i+1 < len(nums) && j > i && nums[i] <= nums[0] { i++ } if i == j { break } else { swap(nums, i, j) } } swap(nums, 0, j) quickSort(nums[0:j]) quickSort(nums[j+1 : len(nums)]) } func swap(nums []int, i int, j int) { if i == j { return } tmp := nums[i] nums[i] = nums[j] nums[j] = tmp }
package templates import ( "context" "github.com/profzone/eden-framework/pkg/courier" "github.com/profzone/eden-framework/pkg/courier/httpx" ) func init() { Router.Register(courier.NewRouter(CreateTemplate{})) } // 创建模板 type CreateTemplate struct { httpx.MethodPost } func (req CreateTemplate) Path() string { return "" } func (req CreateTemplate) Output(ctx context.Context) (result interface{}, err error) { return }
package game_map import ( "github.com/faiface/pixel" "github.com/faiface/pixel/pixelgl" "github.com/steelx/go-rpg-cgm/combat" "github.com/steelx/go-rpg-cgm/gui" "github.com/steelx/go-rpg-cgm/world" ) type CombatTargetState struct { CombatState *CombatState Stack *gui.StateStack //The internal stack of states from the CombatState object. DefaultSelector func(state *CombatState) []*combat.Actor //The function that chooses which characters are targeted //when the state begins. CanSwitchSide bool SelectType world.CombatTargetType OnSelect func(targets []*combat.Actor) OnExit func() Targets, Enemies, Party []*combat.Actor MarkerPNG pixel.Picture Marker *pixel.Sprite MarkerPosition pixel.Vec } type CombatChoiceParams struct { OnSelect func(targets []*combat.Actor) OnExit func() SwitchSides bool DefaultSelector func(state *CombatState) []*combat.Actor TargetType world.CombatTargetType } func CombatTargetStateCreate(state *CombatState, choiceParams CombatChoiceParams) *CombatTargetState { t := &CombatTargetState{ CombatState: state, Stack: state.InternalStack, DefaultSelector: choiceParams.DefaultSelector, CanSwitchSide: choiceParams.SwitchSides, SelectType: choiceParams.TargetType, OnSelect: choiceParams.OnSelect, OnExit: choiceParams.OnExit, MarkerPNG: gui.CursorPng, Marker: pixel.NewSprite(gui.CursorPng, gui.CursorPng.Bounds()), } if t.DefaultSelector == nil { if t.SelectType == world.CombatTargetTypeONE { t.DefaultSelector = CombatSelector.WeakestEnemy } else if t.SelectType == world.CombatTargetTypeSIDE { t.DefaultSelector = CombatSelector.SideEnemy } else if t.SelectType == world.CombatTargetTypeALL { t.DefaultSelector = CombatSelector.SelectAll } } return t } func (t *CombatTargetState) Enter() { t.Enemies = t.CombatState.Actors[enemies] t.Party = t.CombatState.Actors[party] t.Targets = t.DefaultSelector(t.CombatState) } func (t *CombatTargetState) Exit() { t.Enemies = nil t.Party = nil t.Targets = nil t.OnExit() } func (t *CombatTargetState) Update(dt float64) bool { return true } func (t *CombatTargetState) Render(renderer *pixelgl.Window) { for _, v := range t.Targets { char := t.CombatState.ActorCharMap[v] pos := char.Entity.GetTargetPosition() pos = pos.Add(pixel.V(0, t.MarkerPNG.Bounds().W()/2)) t.MarkerPosition = pos t.Marker.Draw(renderer, pixel.IM.Moved(pos)) } } func (t *CombatTargetState) HandleInput(win *pixelgl.Window) { if win.JustPressed(pixelgl.KeyBackspace) { t.Stack.Pop() } else if win.JustPressed(pixelgl.KeyUp) { t.Up() } else if win.JustPressed(pixelgl.KeyDown) { t.Down() } else if win.JustPressed(pixelgl.KeyLeft) { t.Left() } else if win.JustPressed(pixelgl.KeyRight) { t.Right() } else if win.JustPressed(pixelgl.KeySpace) { t.OnSelect(t.Targets) } } ///////////////////////////////// // CombatTargetState additional methods below ///////////////////////////////// func (t CombatTargetState) GetActorList(actor *combat.Actor) []*combat.Actor { if isParty := t.CombatState.IsPartyMember(actor); isParty { return t.Party } return t.Enemies } //GetIndex finds Actors based on uniq names, since we might copy paste Enemies of same entity //e.g. combat.ActorCreate(enemyDef, "1") func (t CombatTargetState) GetIndex(listI []*combat.Actor, item *combat.Actor) int { for k, v := range listI { if v.Name == item.Name { return k } } return 0 } func (t *CombatTargetState) Left() { if !t.CanSwitchSide || !t.CombatState.IsPartyMember(t.Targets[0]) { return } if t.SelectType == world.CombatTargetTypeONE { t.Targets = []*combat.Actor{t.Enemies[0]} } if t.SelectType == world.CombatTargetTypeSIDE { t.Targets = t.Enemies } } func (t *CombatTargetState) Right() { if !t.CanSwitchSide || !t.CombatState.IsPartyMember(t.Targets[0]) { return } if t.SelectType == world.CombatTargetTypeONE { t.Targets = []*combat.Actor{t.Party[0]} } if t.SelectType == world.CombatTargetTypeSIDE { t.Targets = t.Party } } func (t *CombatTargetState) Up() { if t.SelectType != world.CombatTargetTypeONE { return } selected := t.Targets[0] side := t.GetActorList(selected) index := t.GetIndex(side, selected) index = index + 1 if index >= len(side) { index = 0 } t.Targets = []*combat.Actor{side[index]} } func (t *CombatTargetState) Down() { if t.SelectType != world.CombatTargetTypeONE { return } selected := t.Targets[0] side := t.GetActorList(selected) index := t.GetIndex(side, selected) index = index - 1 if index == -1 { index = len(side) - 1 } t.Targets = []*combat.Actor{side[index]} }
package postgres // schema name const prefix = `montesquieu` // This stmt is run on every startup to ensure that database structures exist, and if they don't, it creates them const stmtStartup = ` create schema ` + prefix + ` create table if not exists users ( id bigserial not null constraint users_pk primary key, display_name text, login text unique, password text ) create unique index if not exists users_id_uindex on users (id) create table if not exists authors ( id bigserial not null constraint authors_pk primary key, user_id bigint constraint authors_users_id_fk references users unique, name text ) create unique index if not exists authors_id_uindex on authors (id) create table if not exists articles ( title text, article_id bigserial not null constraint articles_pk primary key, author_id integer not null constraint articles_authors_id_fk references authors, html_content text, html_preview text, timestamp bigint ) create unique index if not exists articles_article_id_uindex on articles (article_id) create unique index if not exists authors_id_uindex on authors (id) create unique index if not exists users_id_uindex on users (id) create table if not exists sessions ( id bigint not null constraint sessions_pk primary key unique, user_id bigint not null constraint sessions_users_id_fk references users on delete cascade, valid_until timestamp ) create unique index if not exists sessions_id_uindex on sessions (id) create table if not exists comments ( comment_id bigint not null constraint comments_pk primary key unique, user_id bigint not null constraint comments_users_id_fk references users on update cascade, unsafe_content text ) create unique index if not exists comments_comment_id_uindex on comments (comment_id) create table if not exists admins ( user_id bigint not null constraint admins_pk primary key unique constraint admins_users_id_fk references users on delete cascade ); ` // articles const stmtLoadArticlesSortedByNewest = `select title, article_id, author_id, html_preview, timestamp from ` + prefix + `.articles order by timestamp desc offset $1 limit $2;` const stmtNewArticle = `insert into ` + prefix + `.articles (title, author_id, html_content, html_preview, timestamp) values ($1,$2,$3,$4,$5);` const stmtEditArticle = `update ` + prefix + `.articles set title = $1, author_id = $2, html_content = $3, html_preview = $4, timestamp = $5 where article_id = $6;` const stmtRemoveArticle = `delete from ` + prefix + `.articles where article_id = $1;` const stmtGetArticleByID = `select title, author_id, html_content, timestamp from ` + prefix + `.articles where article_id = $1;` const stmtArticleNumber = `select count(article_id) from ` + prefix + `.articles;` // users const stmtListUsers = `select id, display_name, login from ` + prefix + `.users order by id offset $1 limit $2;` const stmtAddUser = `insert into ` + prefix + `.users (display_name, login, password) values ($1,$2,$3);` const stmtEditUser = `update ` + prefix + `.users set display_name = $1, login = $2, password = $3 where id = $4;` const stmtRemoveUser = `delete from ` + prefix + `.users where id = $1;` const stmtGetUserID = `select id from ` + prefix + `.users where login = $1;` const stmtGetUser = `select id, display_name, login, password from ` + prefix + `.users where id = $1;` // authors const stmtListAuthors = `select ` + prefix + `.users.id as user_id, display_name as user_display_name, login,` + prefix + `.authors.id as author_id, name as author_name from ` + prefix + `.users inner join ` + prefix + `.authors on ` + prefix + `.authors.user_id=` + prefix + `.users.id order by ` + prefix + `.users.id offset $1 limit $2;` const stmtGetAuthor = `select id, name from ` + prefix + `.authors where user_id = $1;` const stmtAddAuthor = `insert into ` + prefix + `.authors (user_id, name) values ($1, $2);` const stmtLinkAuthor = `update ` + prefix + `.authors set user_id = $1 where id = $2;` const stmtRemoveAuthor = `delete from ` + prefix + `.authors where id = $1;` // admins const stmtPromoteToAdmin = `insert into ` + prefix + `.admins values ($1);` const stmtDemoteFromAdmin = `delete from ` + prefix + `.admins where user_id = $1;` const stmtIsAdmin = `select count(user_id) from ` + prefix + `.admins where user_id = $1;` const stmtListAdmins = `select id, display_name, login from ` + prefix + `.users inner join ` + prefix + `.admins on user_id=id order by ` + prefix + `.users.id offset $1 limit $2;`
package main import ( "fmt" // "html" "log" "net/http" "github.com/gorilla/mux" "database/sql" _ "github.com/go-sql-driver/mysql" "encoding/json" "strconv" ) type Todo struct { ID int `json:"id"` Value string `json:"value"` Checked bool `json:"checked"` } // handle all the different API routes func main() { router := mux.NewRouter() router.HandleFunc("/", Index).Methods("GET") router.HandleFunc("/getAllTodos", GetAllTodos).Methods("GET") router.HandleFunc("/getOpenTodos", GetOpenTodos).Methods("GET") router.HandleFunc("/createTodos", CreateTodos).Methods("POST") router.HandleFunc("/checkTodos", CheckTodos).Methods("POST") router.HandleFunc("/uncheckTodos", UncheckTodos).Methods("POST") log.Fatal(http.ListenAndServe(":80", router)) } // main page for the API service func Index(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Hey Brendan!") } // get all the todos func GetAllTodos(w http.ResponseWriter, req *http.Request) { var todoItems = querySql("SELECT id, value, checked FROM todo") todoJson, err := json.Marshal(todoItems) if err != nil { fmt.Fprintf(w, "DB has messed up") return } w.Header().Set("Content-Type", "application/json") w.Write(todoJson) } // get all open or unchecked todos func GetOpenTodos(w http.ResponseWriter, req *http.Request) { var todoItems = querySql("SELECT id, value, checked FROM todo WHERE checked = false") todoJson, err := json.Marshal(todoItems) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.Write(todoJson) } // create a list of new todos func CreateTodos(w http.ResponseWriter, req *http.Request) { todoItems := DecodeTodoRequest(req) //error check: must have at least one todo item entry if len(todoItems) < 1 { fmt.Fprintf(w, "Need to provide at least 1 todo item to create!") return } //error check: all items to be created need value field provided for _, todoItem := range todoItems { if todoItem.Value == "" { fmt.Fprintf(w, "All todo items provided must provide a value field") return } } for _, todoItem := range todoItems { log.Print("Todo params are: " + todoItem.Value) executeSql("INSERT INTO todo (value) values ('" + todoItem.Value + "')") } } // check todos based on id func CheckTodos(w http.ResponseWriter, req *http.Request) { todoItemsToCheck := DecodeTodoRequest(req) //error check: must have at least one todo item entry if len(todoItemsToCheck) < 1 { fmt.Fprintf(w, "Need to provide at least 1 todo item to check!") return } //error check: all items to be checked need id field provided for _, todoItemToCheck := range todoItemsToCheck { if todoItemToCheck.ID == 0 { fmt.Fprintf(w, "All todo items provided must provide an id field") return } } for _, todoItemToCheck := range todoItemsToCheck { log.Print("Todo params are: " + strconv.Itoa(todoItemToCheck.ID)) executeSql("UPDATE todo SET checked = 1 WHERE id = " + strconv.Itoa(todoItemToCheck.ID)) } } // uncheck todos based on id func UncheckTodos(w http.ResponseWriter, req *http.Request) { todoItemsToUncheck := DecodeTodoRequest(req) //error check: must have at least one todo item entry if len(todoItemsToUncheck) < 1 { fmt.Fprintf(w, "Need to provide at least 1 todo item to check!") return } //error check: all items to be checked need id field provided for _, todoItemToUncheck := range todoItemsToUncheck { if todoItemToUncheck.ID == 0 { fmt.Fprintf(w, "All todo items provided must provide an id field") return } } for _, todoItemToUncheck := range todoItemsToUncheck { log.Print("Todo params are: " + strconv.Itoa(todoItemToUncheck.ID)) executeSql("UPDATE todo SET checked = 0 WHERE id = " + strconv.Itoa(todoItemToUncheck.ID)) } } func DecodeTodoRequest(req *http.Request) (todoItems []Todo) { decoder := json.NewDecoder(req.Body) err := decoder.Decode(&todoItems) if err != nil { log.Panic(err) } return } func executeSql(stmnt string) { db, err := sql.Open("mysql", "root:bob@tcp(db:3306)/todo") if err != nil { log.Panic(err); log.Fatal("Error: Connection to the DB messed up") } defer db.Close() _, err = db.Exec(stmnt) if err != nil { log.Panic(err); log.Fatal("Error: SQL execution messed up") } } func querySql(query string) (todoItems []Todo) { db, err := sql.Open("mysql", "root:bob@tcp(db:3306)/todo") if err != nil { log.Panic(err); log.Fatal("Error: Connection to the DB messed up") } defer db.Close() rows, err := db.Query(query) if err != nil { log.Panic(err); log.Fatal("Error: SQL query messed up") } defer rows.Close() for rows.Next() { var todoItem Todo rows.Scan(&todoItem.ID, &todoItem.Value, &todoItem.Checked) todoItems = append(todoItems, todoItem) } if err != nil { log.Panic(err); log.Fatal("Error: SQL execution messed up") } return }
package pgsql import ( "database/sql" "database/sql/driver" "strconv" ) // LineFromFloat64Array3 returns a driver.Valuer that produces a PostgreSQL line from the given Go [3]float64. func LineFromFloat64Array3(val [3]float64) driver.Valuer { return lineFromFloat64Array3{val: val} } // LineToFloat64Array3 returns an sql.Scanner that converts a PostgreSQL line into a Go [3]float64 and sets it to val. func LineToFloat64Array3(val *[3]float64) sql.Scanner { return lineToFloat64Array3{val: val} } type lineFromFloat64Array3 struct { val [3]float64 } func (v lineFromFloat64Array3) Value() (driver.Value, error) { out := make([]byte, 1, 7) // len(`{a,b,c}`) == 7 (min size) out[0] = '{' out = strconv.AppendFloat(out, v.val[0], 'f', -1, 64) out = append(out, ',') out = strconv.AppendFloat(out, v.val[1], 'f', -1, 64) out = append(out, ',') out = strconv.AppendFloat(out, v.val[2], 'f', -1, 64) out = append(out, '}') return out, nil } type lineToFloat64Array3 struct { val *[3]float64 } func (v lineToFloat64Array3) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { return nil } line := pgParseLine(data) f0, err := strconv.ParseFloat(string(line[0]), 64) if err != nil { return err } f1, err := strconv.ParseFloat(string(line[1]), 64) if err != nil { return err } f2, err := strconv.ParseFloat(string(line[2]), 64) if err != nil { return err } *v.val = [3]float64{f0, f1, f2} return nil }
package libStarter import "io" type IFormatter interface { Format(cmdParams *CmdParams) IFormatter WriteOut(writer io.Writer) error } // 格式化信息结构体 type FormatterStruct struct { PackageName string ImportList map[string]ImportItem Name string StructName string TypeName string } type ImportItem struct { Alias string Package string }
package server import ( "encoding/json" "fmt" "io/ioutil" "net/http" "github.com/gorilla/mux" "github.com/holly-graham/scheduleapi/schedule" ) type ScheduleServer struct { scheduleService *schedule.ScheduleService } func NewServer(scheduleService *schedule.ScheduleService) *ScheduleServer { return &ScheduleServer{ scheduleService: scheduleService, } } func (s *ScheduleServer) ListActivitiesHandler(rw http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) chosenDay := vars["chosenDay"] activities, err := s.scheduleService.ListActivities(chosenDay) if err != nil { fmt.Println("Error listing activities:", err) rw.WriteHeader(http.StatusInternalServerError) return } activitiesJSON, err := json.Marshal(activities) if err != nil { fmt.Println("Error marshaling activities:", err) rw.WriteHeader(http.StatusInternalServerError) return } rw.Header().Add("Content-Type", "application/json") rw.Write(activitiesJSON) } type CreateActivityRequest struct { Time string Description string } func (s *ScheduleServer) AddActivityHandler(rw http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) chosenDay := vars["chosenDay"] requestBody, err := ioutil.ReadAll(r.Body) if err != nil { fmt.Println("Error reading request body:", err) rw.WriteHeader(http.StatusBadRequest) return } var newActivity CreateActivityRequest err = json.Unmarshal(requestBody, &newActivity) if err != nil { fmt.Println("Error unmarshaling new activity details:", err) rw.WriteHeader(http.StatusBadRequest) return } newScheduleActivity := schedule.Activity{ Time: newActivity.Time, Description: newActivity.Description, } s.scheduleService.AddActivity(newScheduleActivity, chosenDay) err = s.scheduleService.AddActivity(newScheduleActivity, chosenDay) if err != nil { fmt.Println("Error creating activity:", err) rw.WriteHeader(http.StatusInternalServerError) return } rw.WriteHeader(http.StatusCreated) }
package main import ( "fmt" //"net/http" //"os" //"path" //"strings" //"encoding/json" "github.com/espebra/filebin2/dbl" "github.com/espebra/filebin2/s3" "time" ) type Lurker struct { dao *dbl.DAO s3 *s3.S3AO interval time.Duration retention uint64 } func (l *Lurker) Init(interval int, retention uint64) (err error) { l.interval = time.Second * time.Duration(interval) l.retention = retention return nil } func (l *Lurker) Run() { fmt.Printf("Starting Lurker process (interval: %s)\n", l.interval.String()) ticker := time.NewTicker(l.interval) done := make(chan bool) go func() { for { select { case <-done: return case _ = <-ticker.C: t0 := time.Now() l.DeletePendingFiles() l.DeletePendingBins() l.CleanTransactions() fmt.Printf("Lurker completed run in %.3fs\n", time.Since(t0).Seconds()) } } }() } func (l *Lurker) DeletePendingFiles() { files, err := l.dao.File().GetPendingDelete() if err != nil { fmt.Printf("Unable to GetPendingDelete(): %s\n", err.Error()) return } if len(files) > 0 { fmt.Printf("Found %d files pending removal.\n", len(files)) for _, file := range files { //fmt.Printf(" > Bin %s, filename %s\n", file.Bin, file.Filename) if err := l.s3.RemoveObject(file.Bin, file.Filename); err != nil { fmt.Printf("Unable to delete file %s from bin %s from S3.\n", file.Filename, file.Bin) return } file.InStorage = false if err := l.dao.File().Update(&file); err != nil { fmt.Printf("Unable to update filename %s (id %d) in bin %s: %s\n", file.Filename, file.Id, file.Bin, err.Error()) return } } } } func (l *Lurker) DeletePendingBins() { bins, err := l.dao.Bin().GetPendingDelete() if err != nil { fmt.Printf("Unable to GetPendingDelete(): %s\n", err.Error()) return } if len(bins) > 0 { fmt.Printf("Found %d bins pending removal.\n", len(bins)) for _, bin := range bins { //fmt.Printf(" > Bin %s\n", bin.Id) files, err := l.dao.File().GetByBin(bin.Id, true) if err != nil { fmt.Printf("Unable to GetByBin: %s\n", err.Error()) return } for _, file := range files { if err := l.s3.RemoveObject(file.Bin, file.Filename); err != nil { fmt.Printf("Unable to delete file %s from bin %s from S3.\n", file.Filename, file.Bin) return } fmt.Printf("Removing file %s from bin %s\n", file.Filename, bin.Id) file.InStorage = false if err := l.dao.File().Update(&file); err != nil { fmt.Printf("Unable to update filename %s (id %d) in bin %s: %s\n", file.Filename, file.Id, file.Bin, err.Error()) return } } if err := l.dao.Bin().Update(&bin); err != nil { fmt.Printf("Unable to update bin %s: %s\n", bin.Id, err.Error()) return } } } } func (l *Lurker) CleanTransactions() { count, err := l.dao.Transaction().Cleanup(l.retention) if err != nil { fmt.Printf("Unable to Transactions().Cleanup(): %s\n", err.Error()) return } if count > 0 { fmt.Printf("Removed %d log transactions.\n", count) } }
package datapool import ( "database/sql" "encoding/json" "fmt" "io/ioutil" "log" "math" "math/rand" "net/http" "os" "strconv" "sync" "time" //_ driver for tds "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" _ "github.com/thda/tds" ) var ( // //imdg // //Xerjdcrbq10 //DB - pointer for DB connect pool DB *sql.DB Cnfg Config JsonPool []Operation ConnectionPool sync.Map //TempIDSyncMap sync.Map metrics = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "sybase_operation_count", Help: "operation count", }, []string{"node", "table", "operation_type"}, ) errmetrics = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "sybase_operation_error_count", Help: "operation error count", }, []string{"node", "table", "operation_type", "error"}, ) ) type Instance struct { Host string DB *sql.DB Duration time.Duration C chan TypeOrSTR Operations []Operation } type Config []struct { Host string `json:"Host"` Port string `json:"Port"` DBName string `json:"DBName"` Tables []struct { TableName string `json:"TableName"` InsertCount float64 `json:"InsertCount"` UpdateCount float64 `json:"UpdateCount"` } `json:"Tables"` } type Operation struct { Tablename string `json:"tablename"` Insert string `json:"insert"` Update []struct { Str string `json:"str"` } `json:"update"` Delete string `json:"delete"` } //TypeOrSTR - temp struct for exec to database type TypeOrSTR struct { TableName string OperationType string STR string } func init() { err := readConfig() if err != nil { log.Panicf("[Panic] read config errors: %s", err) } err = readJSON() if err != nil { log.Panicf("[Panic] read json files errors: %s", err) } l := len(Cnfg) for i := 0; i < l; i++ { cnxStr := "tds://sa:password@" + Cnfg[i].Host + ":" + Cnfg[i].Port + "/" + Cnfg[i].DBName + "?charset=utf8" db, err := sql.Open("tds", cnxStr) if err != nil { log.Fatalln("Init connection error ", err) } ConnectionPool.Store(Cnfg[i].Host, db) } prometheus.MustRegister(metrics) prometheus.MustRegister(errmetrics) http.Handle("/metrics", promhttp.Handler()) log.Printf("[INFO] " + " Listenport: 9990") go http.ListenAndServe(":9990", nil) } func (instance Instance) RunInstance(wg *sync.WaitGroup) { var tempIDSyncMap sync.Map lastIDSlice, err := GetLastIDFromTable(instance.DB) if err != nil { log.Printf("[ERROR] getlastid error: %s", err) } var localwg sync.WaitGroup localwg.Add(1) go Writer(instance.Host, instance.DB, instance.C, instance.Duration, &localwg, &tempIDSyncMap) l := len(instance.Operations) for i := 0; i < l; i++ { tablename := instance.Operations[i].Tablename for _, val := range Cnfg { l := len(val.Tables) for i := 0; i < l; i++ { if val.Tables[i].TableName == tablename { localwg.Add(1) go instance.Operations[i].Reader(instance.C, val.Tables[i].InsertCount, val.Tables[i].UpdateCount, instance.Duration, &localwg) break } } } } localwg.Wait() clearDataBaseAfterTest(instance.DB, &lastIDSlice) wg.Done() } func Writer(host string, db *sql.DB, c chan TypeOrSTR, d time.Duration, wg *sync.WaitGroup, tempIDSyncMap *sync.Map) { start := time.Now() var typeOrSTR TypeOrSTR for { typeOrSTR = <-c switch typeOrSTR.OperationType { case "insert": i, err := db.Exec(typeOrSTR.STR) if err != nil { log.Println("Exec insert: ", err) errmetrics.With(prometheus.Labels{"node": host, "table": typeOrSTR.TableName, "operation_type": "Insert", "error": err.Error()}).Inc() } else { metrics.With(prometheus.Labels{"node": host, "table": typeOrSTR.TableName, "operation_type": "Insert"}).Inc() id, err := i.LastInsertId() if err != nil { log.Println("Exec insert: ", err) } else { pt, ok := tempIDSyncMap.Load(typeOrSTR.TableName) if ok { temp := append(pt.([]int64), id) tempIDSyncMap.Store(typeOrSTR.TableName, temp) } else { tempIDSyncMap.Store(typeOrSTR.TableName, []int64{id}) } } } case "update": pt, ok := tempIDSyncMap.Load(typeOrSTR.TableName) if ok { l := len(pt.([]int64)) updates := pt.([]int64) _, err := db.Exec(typeOrSTR.STR, updates[rand.Intn(l)]) if err != nil { errmetrics.With(prometheus.Labels{"node": host, "table": typeOrSTR.TableName, "operation_type": "Update", "error": err.Error()}).Inc() } else { metrics.With(prometheus.Labels{"node": host, "table": typeOrSTR.TableName, "operation_type": "Update"}).Inc() } } case "delete": pt, ok := tempIDSyncMap.Load(typeOrSTR.TableName) if ok { deletes := pt.([]int64) randID := rand.Intn(len(pt.([]int64))) id := deletes[randID] _, err := db.Exec(typeOrSTR.STR, id) if err != nil { errmetrics.With(prometheus.Labels{"node": host, "table": typeOrSTR.TableName, "operation_type": "Delete", "error": err.Error()}).Inc() } else { metrics.With(prometheus.Labels{"node": host, "table": typeOrSTR.TableName, "operation_type": "Delete"}).Inc() tempIDSyncMap.Store(typeOrSTR.TableName, append(deletes[:randID], deletes[randID+1:]...)) } } } if time.Now().Sub(start) >= d { wg.Done() break } } } func GetLastIDFromTable(db *sql.DB) (map[string]uint64, error) { lastIDSlice := make(map[string]uint64) l := len(JsonPool) for i := 0; i < l; i++ { var id uint64 rows, err := db.Query("select max(" + getNameTableID(JsonPool[i].Tablename) + ") from " + JsonPool[i].Tablename) if err != nil { return nil, err } for rows.Next() { rows.Scan(&id) } lastIDSlice[JsonPool[i].Tablename] = id } return lastIDSlice, nil } func (o Operation) Reader(c chan TypeOrSTR, insertCount float64, updateCount float64, d time.Duration, wg *sync.WaitGroup) { start := time.Now() pacing := time.Duration(math.Round(3600000000/insertCount)) * time.Microsecond var rate float64 if insertCount < updateCount { rate = math.Round(updateCount / insertCount) } else { rate = 1 } insDelTic := time.NewTicker(pacing) updateTic := time.NewTicker(pacing / time.Duration(rate)) deleteflag := true for { c <- TypeOrSTR{o.Tablename, "insert", o.Insert} l := len(o.Update) for i := 0; i < int(rate); i++ { c <- TypeOrSTR{o.Tablename, "update", o.Update[rand.Intn(l)].Str} <-updateTic.C } if deleteflag { c <- TypeOrSTR{o.Tablename, "delete", o.Delete} deleteflag = false } else { deleteflag = true } if time.Now().Sub(start) >= d { wg.Done() break } <-insDelTic.C } } func readConfig() (err error) { file, err := os.Open("./datapool/config.json") if err != nil { return err } err = json.NewDecoder(file).Decode(&Cnfg) if err != nil { return err } return nil } func readJSON() (err error) { files, err := ioutil.ReadDir("./json") if err != nil { return err } for _, f := range files { oper := Operation{} file, err := os.Open("./json/" + f.Name()) if err != nil { return err } err = json.NewDecoder(file).Decode(&oper) if err != nil { return err } JsonPool = append(JsonPool, oper) } return nil } func getNameTableID(tablename string) (res string) { switch tablename { case "tCard": res = "CardID" case "tCardProduct": res = "CardProductID" case "tContract": res = "ContractID" case "tContractCredit": res = "ContractCreditID" case "tInstitution": res = "InstitutionID" case "tNode": res = "NodeID" case "tResource": res = "ResourceID" case "tSecurity": res = "SecurityID" } return res } func remove(slice []int64, s int) []int64 { return append(slice[:s], slice[s+1:]...) } func clearDataBaseAfterTest(db *sql.DB, lastIDSlice *map[string]uint64) (err error) { for key, value := range *lastIDSlice { _, err = db.Exec("delete from " + key + " where " + getNameTableID(key) + " > " + strconv.FormatUint(value, 10)) if err != nil { fmt.Printf("[ERROR] delete err %s", err) //return nil } } return nil }
package auth import ( "context" "fmt" "log" "os" "strings" "cloud.google.com/go/firestore" "cloud.google.com/go/functions/metadata" firebase "firebase.google.com/go" usermodel "github.com/modeckrus/firebase/usermodel" ) //AuthEvent is type AuthEvent struct { Email string `json:"email"` UID string `json:"uid"` } // GOOGLE_CLOUD_PROJECT is automatically set by the Cloud Functions runtime. var projectID = os.Getenv("GOOGLE_CLOUD_PROJECT") // client is a Firestore client, reused between function invocations. var fstore *firestore.Client func init() { // Use the application default credentials. conf := &firebase.Config{ProjectID: projectID} // Use context.Background() because the app/client should persist across // invocations. ctx := context.Background() app, err := firebase.NewApp(ctx, conf) if err != nil { log.Fatalf("firebase.NewApp: %v", err) } fstore, err = app.Firestore(ctx) if err != nil { log.Fatalf("app.Firestore: %v", err) } } // AuthEventFunc is triggered by a change to a Firestore document. func AuthEventFunc(ctx context.Context, e AuthEvent) error { meta, err := metadata.FromContext(ctx) if err != nil { return fmt.Errorf("metadata.FromContext: %v", err) } log.Printf("Function triggered by change to: %v", meta.Resource) log.Printf("%v", e) nick := strings.Split(e.Email, "@")[0] fstore.Collection("user").Doc(e.UID).Set(ctx, usermodel.User{ UID: e.UID, Email: e.Email, Nick: nick, Name: nick, Surname: nick, IsSetted: false, }) fstore.Collection("user").Doc(e.UID).Collection("subscribers").Doc(e.UID).Set(ctx, usermodel.SubModel{ UID: e.UID, Nick: nick, Avatar: "avatars/default.jpg", }) return nil }
package main import ( "strconv" "sync" "github.com/prometheus/client_golang/prometheus" ) const prefix = "ping_" var ( labelNames = []string{"target", "ip", "ip_version"} bestDesc = prometheus.NewDesc(prefix+"rtt_best_ms", "Best round trip time in millis", labelNames, nil) worstDesc = prometheus.NewDesc(prefix+"rtt_worst_ms", "Worst round trip time in millis", labelNames, nil) meanDesc = prometheus.NewDesc(prefix+"rtt_mean_ms", "Mean round trip time in millis", labelNames, nil) stddevDesc = prometheus.NewDesc(prefix+"rtt_std_deviation_ms", "Standard deviation in millis", labelNames, nil) lossDesc = prometheus.NewDesc(prefix+"loss_percent", "Packet loss in percent", labelNames, nil) progDesc = prometheus.NewDesc(prefix+"up", "ping_exporter version", nil, prometheus.Labels{"version": version}) mutex = &sync.Mutex{} ) type pingCollector struct { targets []*target } func (p *pingCollector) Describe(ch chan<- *prometheus.Desc) { ch <- lossDesc ch <- bestDesc ch <- worstDesc ch <- meanDesc ch <- stddevDesc ch <- progDesc } func (p *pingCollector) Collect(ch chan<- prometheus.Metric) { mutex.Lock() defer mutex.Unlock() ch <- prometheus.MustNewConstMetric(progDesc, prometheus.GaugeValue, 1) for _, t := range p.targets { for _, r := range t.runners { p.collectForRunner(t, r, ch) } } } func (p *pingCollector) collectForRunner(t *target, r *runner, ch chan<- prometheus.Metric) { stats := r.stats if stats == nil { return } ipVersion := 6 if r.ip.To4() != nil { ipVersion = 4 } l := []string{t.host, r.ip.String(), strconv.Itoa(ipVersion)} ch <- prometheus.MustNewConstMetric(bestDesc, prometheus.GaugeValue, float64(stats.MinRtt.Milliseconds()), l...) ch <- prometheus.MustNewConstMetric(worstDesc, prometheus.GaugeValue, float64(stats.MaxRtt.Milliseconds()), l...) ch <- prometheus.MustNewConstMetric(meanDesc, prometheus.GaugeValue, float64(stats.AvgRtt.Milliseconds()), l...) ch <- prometheus.MustNewConstMetric(stddevDesc, prometheus.GaugeValue, float64(stats.StdDevRtt.Milliseconds()), l...) ch <- prometheus.MustNewConstMetric(lossDesc, prometheus.GaugeValue, stats.PacketLoss, l...) }
package sessions import ( "backend/internal/domain" "github.com/gorilla/sessions" ) type gorillaSession struct { session *sessions.Session } func NewGorillaSession(session *sessions.Session) Session { return &gorillaSession{ session: session, } } func (g *gorillaSession) IsAuthenticated() bool { ok, value := g.session.Values["authenticated"].(bool) return ok && value } func (g *gorillaSession) PlayerId() domain.PlayerId { value, ok := g.session.Values["player_id"].(string) if !ok { panic("no player_id in session") } playerId, err := domain.ParsePlayerId(value) if err != nil { panic("invalid player_id in session") } return playerId } func (g *gorillaSession) Authenticate(playerId domain.PlayerId) { g.session.Values["authenticated"] = true g.session.Values["player_id"] = playerId.String() }
package main import ( "fmt" "io/ioutil" "math/rand" "time" ) func random(min, max int) int { return rand.Intn(max-min) + min } func main() { // http://golangcookbook.blogspot.ca/2012/11/generate-random-number-in-given-range.html rand.Seed(time.Now().Unix()) byteArray, err := ioutil.ReadFile("./tests/pdfs/pdf-sample.pdf") if err != nil { fmt.Println("error reading file") panic(err) } fuzzFactor := 250 numWrites := len(byteArray)/fuzzFactor + 1 fmt.Printf("Writing %d random bytes...\n", numWrites) for i := 0; i < numWrites; i++ { rn := random(0, len(byteArray)) rbyte := byte(random(0, 255)) byteArray[rn] = rbyte } err = ioutil.WriteFile("./changed.pdf", byteArray, 0644) if err != nil { fmt.Println("error writing file") panic(err) } else { fmt.Println("Done!") } }
package wolfenstein import ( "github.com/llgcode/draw2d/draw2dimg" "github.com/llgcode/draw2d/draw2dkit" "image/color" "math" ) type GameState struct { level []int mapSize int blockSize int player Player } type Player struct { position Point delta Point } type Point struct { x float64 y float64 angle float64 } func NewGameState(width, height int) (*GameState, error) { var gs GameState // silly level gs.level = []int{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, } gs.mapSize = 8 gs.blockSize = 64 gs.player = Player{ position: Point{ float64(gs.mapSize * gs.blockSize / 2), float64(gs.mapSize * gs.blockSize / 2), 0.0, }, delta: Point{0, 0, 0.0}, } gs.updateDelta() return &gs, nil } func (gs *GameState) GetMapSize() int { return gs.mapSize } func (gs *GameState) GetLevel() []int { return gs.level } func (gs *GameState) GetPlayer() Player { return gs.player } func (gs *GameState) GetPlayerPosition() (x, y, deltaX, deltaY float64) { return gs.player.position.x, gs.player.position.y, gs.player.delta.x, gs.player.delta.y } func (gs *GameState) GetBlockSize() int { return gs.blockSize } func (gs *GameState) GetPlayerAngle() float64 { return gs.player.position.angle } func (gs *GameState) MoveUp() { gs.player.position.x += gs.player.delta.x gs.player.position.y += gs.player.delta.y } func (gs *GameState) MoveDown() { gs.player.position.x -= gs.player.delta.x gs.player.position.y -= gs.player.delta.y } func (gs *GameState) MoveLeft() { gs.player.position.angle -= 0.1 if gs.player.position.angle < 0 { gs.player.position.angle += 2 * math.Pi } gs.updateDelta() } func (gs *GameState) MoveRight() { gs.player.position.angle += 0.1 if gs.player.position.angle > 2*math.Pi { gs.player.position.angle -= 2 * math.Pi } gs.updateDelta() } func (gs *GameState) updateDelta() { gs.player.delta.x = math.Cos(gs.player.position.angle) * 5 gs.player.delta.y = math.Sin(gs.player.position.angle) * 5 } func (gs *GameState) RenderRay(gc *draw2dimg.GraphicContext) { // player position as origin posX := gs.player.position.x posY := gs.player.position.y posAngle := gs.player.position.angle blockSize := gs.GetBlockSize() var rayX, rayY float64 for x := 0; x < 1; x++ { //which cell of the map we're in mapX := int(math.Trunc(posX / float64(blockSize)))*blockSize // right if posAngle < math.Pi/2 || posAngle > 3*math.Pi/2 { rayX = posX + (float64(blockSize) - (posX - float64(mapX))) rayY = posY + (float64(blockSize)-(posX-float64(mapX)))*math.Tan(posAngle) } // left if posAngle > math.Pi/2 && posAngle < 3*math.Pi/2 { rayX = posX - (float64(blockSize) - (posX - float64(mapX))) rayY = posY + (float64(blockSize)-(posX-float64(mapX)))*-math.Tan(posAngle) } gc.SetFillColor(color.RGBA{0x00, 0x00, 0xff, 0xff}) gc.SetStrokeColor(color.RGBA{0x00, 0x00, 0xff, 0xff}) draw2dkit.Circle(gc, rayX, rayY, 2) gc.FillStroke() } }
package router import ( "errors" "github.com/nedp/command" ) type Slots interface { // Add finds a free slot and assigns it to the specified command. // // Returns // the index of the slot assigned to the command. Add(c command.Interface) (int, error) // Run is a wrapper for Run on the command in slot i. // i must be positive, slot i must be assigned to a command, and // the command must not already be running. // // Returns // an error if there is a problem running the command; and // command.Run's result if the command runs successfully. Run(i int, outCh chan<- string) (bool, error) // Free unassigns the slot with index i. // i must be positive, slot i must be assigned to a command, and // the command must not be running. // // Returns // nil if successful; // ErrNotAssigned if slot i is not assigned; and // ErrStillRunning if the command in slot i is running. Free(i int) error // Command returns the command most recently assigned to slot i. // i must be positive. // // Returns // (the command, nil) if successfuly; and // (nil, ErrNotAssigned) if slot i has never been assigned. Command(i int) (command.Interface, error) } type slots struct { commands []command.Interface pubCommands []command.Interface nUsed int iSlot int maxNSlots int } var ( ErrNotAssigned = errors.New("the slot is unassigned") ErrStillRunning = errors.New("the command is still running") ErrNoFreeSlots = errors.New("there are no free slots") ) const growthRate = 2 const sparsityFactor = 2 func NewSlots(nSlots int, maxNSlots int) Slots { return newSlots(nSlots, maxNSlots) } func newSlots(nSlots int, maxNSlots int) *slots { // Preconditions if nSlots < 0 { panic("router.NewSlots: nSlots out of range") } return &slots{ commands: make([]command.Interface, nSlots), pubCommands: make([]command.Interface, nSlots), nUsed: 0, iSlot: 0, maxNSlots: maxNSlots, } } func (s *slots) Add(c command.Interface) (int, error) { if s.nUsed == s.maxNSlots { return 0, ErrNoFreeSlots } // Add new `nil` slots if it's getting crowded, up to the maximum. if (len(s.commands) < s.maxNSlots) && (s.nUsed*sparsityFactor >= len(s.commands)) { targetNSlots := growthRate * len(s.commands) if targetNSlots == len(s.commands) { targetNSlots += 1 } if targetNSlots > s.maxNSlots { targetNSlots = s.maxNSlots } nNewSlots := targetNSlots - len(s.commands) newSlots := make([]command.Interface, nNewSlots) s.iSlot = len(s.commands) s.commands = append(s.commands, newSlots...) newSlots = make([]command.Interface, nNewSlots) s.pubCommands = append(s.pubCommands, newSlots...) } // Find a free slot i := s.iSlot for s.commands[i] != nil { if i + 1 == len(s.commands) { i = 0 } i += 1 } // Add the command s.commands[i] = c s.pubCommands[i] = c s.nUsed += 1 // Skip the next slot in a future search to maintain sparsity, // reducing the expected number of checks. s.iSlot = i + sparsityFactor for s.iSlot >= len(s.commands) { s.iSlot -= len(s.commands) } return i, nil } func (s *slots) Run(i int, outCh chan<- string) (bool, error) { // Preconditions if i < 0 { panic("Router.*slots.Run: i out of range") } if s.commands[i] == nil { return false, ErrNotAssigned } if s.commands[i].IsRunning() { return false, ErrStillRunning } return s.commands[i].Run(outCh), nil } func (s *slots) Free(i int) error { // Preconditions if i < 0 { panic("Router.*slots.Free: i out of range") } if s.commands[i] == nil { return ErrNotAssigned } if s.commands[i].IsRunning() { return ErrStillRunning } s.commands[i] = nil s.nUsed -= 1 return nil } func (s *slots) Command(i int) (command.Interface, error) { // Preconditions if i < 0 { panic("Router.slots.Command: i out of range") } if s.pubCommands[i] == nil { return nil, ErrNotAssigned } return s.pubCommands[i], nil }
package models import ( _ "github.com/lib/pq" "github.com/astaxie/beego/orm" "time" "fmt" "github.com/astaxie/beego" "github.com/Pallinder/go-randomdata" ) type AuthUser struct { Id int First string Last string Email string Password string Reg_key string Reg_date time.Time `orm:"auto_now_add;type(datetime)"` } //Connect to database.. func init() { //orm.RegisterModel(new(AuthUser)) orm.RegisterModelWithPrefix("snaphy_", new(AuthUser)) // orm.RegisterDataBase("default", "mysql", "root:root@/orm_test?charset=utf8") orm.RegisterDriver("postgres", orm.DRPostgres) database, user, password := getDatabaseCredentials() connString := fmt.Sprintf("postgres://%s:%s@localhost/%s?sslmode=disable", user, password, database) orm.RegisterDataBase("default", "postgres", connString ) name := "default" force := false verbose := true orm.Debug = true err := orm.RunSyncdb(name, force, verbose) if err != nil { fmt.Println(err) } } func makeTimestamp() int64 { return time.Now().UnixNano() / int64(time.Millisecond) } func insertData(){ auth_user := new(AuthUser) auth_user.First = randomdata.FirstName(randomdata.RandomGender) auth_user.Last = randomdata.LastName() auth_user.Email = randomdata.Email() auth_user.Password = randomdata.Digits(6) auth_user.Reg_key = randomdata.Digits(16) o := orm.NewOrm() o.Insert(auth_user) } //Get the database name, username and password info for postgresql. func getDatabaseCredentials() (string, string, string){ database := beego.AppConfig.String("postgres::database") user := beego.AppConfig.String("postgres::user") password := beego.AppConfig.String("postgres::password") return database, user, password }
package main func longestWord(words []string) string { isLiving := make(map[string]bool) for i := 0; i < len(words); i++ { isLiving[words[i]] = true } return longestWordExec(isLiving, "") } func longestWordExec(isLiving map[string]bool, nowStr string) string { ans := nowStr for i := 'a'; i <= 'z'; i++ { str := nowStr + string(i) if isLiving[str] { str = longestWordExec(isLiving, str) if len(ans) < len(str) { ans = str } } } return ans } /* 总结 1. 该题我采用了搜索的方法AC。 2. 官方有人用字典树的方法做这个题 3. 官方有用排序+set做这道题的 */
/* For license and copyright information please see LEGAL file in repository */ package approuter import ( "fmt" "os" "os/signal" "syscall" "time" ) // Server represents an ChaparKhane server needed data to serving as server. type Server struct { Status int // 0:stop 1:running GracefulStop chan os.Signal // GracefulStop is a channel of os.Signals that we will watch for -SIGTERM Network Network Handlers Handlers PublicKeyCryptography AppPublicKeyCryptography ConnectionPool map[[16]byte]*ConnectionData // --TODO-- Just one process can give new ConnectionID due concurrency problems! or lock needs Assets *Assets // Data in Assets dependency(folder) of repo } // Network : type Network struct { UIPRange [14]byte MTU uint16 // Maximum Transmission Unit. network+transport+application } // Handlers use to store related data use in handle packet from start to end! type Handlers struct { UIPHandler PacketHandler SCPHandler PacketHandler Services map[uint32]ServiceFunc } // PacketHandler use to register packet handler! type PacketHandler func(*Server, []byte) // ServiceFunc use to register server public services (APIs) just for DefaultServer and not use in generator! type ServiceFunc func(*StreamData) // AppPublicKeyCryptography : Public-key for related domain. type AppPublicKeyCryptography struct { PublicKey [32]byte // Use new algorithm like 256bit ECC(256bit) instead of RSA(4096bit) PrivateKey [32]byte // Use new algorithm like 256bit ECC(256bit) instead of RSA(4096bit) } // NewServer will make new server object func NewServer() *Server { var s = Server{ GracefulStop: make(chan os.Signal), ConnectionPool: make(map[[16]byte]*ConnectionData), } s.Handlers.Services = make(map[uint32]ServiceFunc) // make public & private key and store them s.PublicKeyCryptography.PublicKey = [32]byte{} s.PublicKeyCryptography.PrivateKey = [32]byte{} return &s } // RegisterPublicKey use to register public key in apis.sabz.city func (s *Server) RegisterPublicKey() (err error) { return nil } // RegisterUIP use to get new UIP & MTU from OS router! func (s *Server) RegisterUIP() (err error) { // send PublicKey to router and get IP if user granted. otherwise log error. s.Network.UIPRange = [14]byte{} // Get MTU from router s.Network.MTU = 1200 // Because ChaparKhane is server based application must have IP access. // otherwise close server app and return err return nil } // Start will start the server. func (s *Server) Start() (err error) { // Tell others server start! s.Status = 1 // watch for SIGTERM and SIGINT from the operating system, and notify the app on the channel signal.Notify(s.GracefulStop, syscall.SIGTERM) signal.Notify(s.GracefulStop, syscall.SIGINT) go func() { // wait for our os signal to stop the app // on the graceful stop channel // this goroutine will block until we get an OS signal var sig = <-s.GracefulStop fmt.Printf("caught sig: %+v", sig) // sleep for 60 seconds to waiting for app to finish, fmt.Println("Waiting for server to finish, will take 60 seconds") time.Sleep(60 * time.Second) s.Shutdown() os.Exit(s.Status) }() // Get UserGivenPermission from OS // Make & Register publicKey if err = s.RegisterPublicKey(); err != nil { return err } // Get IP & MTU from OS router. Register income packet service. if err = s.RegisterIP(); err != nil { return err } // register s.Handlers.UIPHandler for income packet handler return nil } // Shutdown use to graceful stop server!! func (s *Server) Shutdown() { // ... Do business Logic for shutdown // Shutdown works by: // first closing open listener for income packet and refuse all new packet, // then closing all idle connections, // and then waiting indefinitely for connections to return to idle // and then shut down // Send signal to DNS & Certificate server to revoke app data. // it must change to 0 otherwise it means app can't close normally s.Status = 1 }
package main import ( "fmt" "os" ) var moofUrl string = "C:/Users/peili/Desktop/26f_init.mp4" func main() { fmt.Println("hu test begin") fileOP, err := os.Open(moofUrl) if err != nil { println("failed to open source file.") return } defer fileOP.Close() fileStat, _ := fileOP.Stat() fmt.Println("xxxxx fileSize = ", fileStat.Size()) // readSeeker := bufio.NewReader(fileOP) // doesn't need to use bufio // test var demuxer = NewFmp4Parser(fileOP) // logD.Print(test) // test_end _ = demuxer.Parse() }
package csv import ( "encoding/csv" "io" ) func ReadFile(r io.Reader) ([]string, error) { csvReader := csv.NewReader(r) macAddresses := make([]string, 0) for { record, err := csvReader.Read() if err == io.EOF { break } if err != nil { return nil, err } macAddresses = append(macAddresses, record[0]) } if len(macAddresses) == 0 { return macAddresses, nil } return macAddresses[1:], nil }
package cmd import ( "fmt" "github.com/alewgbl/fdwctl/internal/config" "github.com/alewgbl/fdwctl/internal/database" "github.com/alewgbl/fdwctl/internal/logger" "github.com/alewgbl/fdwctl/internal/model" "github.com/alewgbl/fdwctl/internal/util" "github.com/spf13/cobra" "strconv" "strings" ) var ( createCmd = &cobra.Command{ Use: "create <object type>", Short: "Create objects", PersistentPreRunE: preDoCreate, PersistentPostRun: postDoCreate, } createServerCmd = &cobra.Command{ Use: "server <server name>", Short: "Create a foreign server", Run: createServer, Args: cobra.MinimumNArgs(1), } createExtensionCmd = &cobra.Command{ Use: "extension <extension name>", Short: "Create a PG extension (usually postgres_fdw)", Run: createExtension, Args: cobra.MinimumNArgs(1), } createUsermapCmd = &cobra.Command{ Use: "usermap", Short: "Create a user mapping for a foreign server", Run: createUsermap, } createSchemaCmd = &cobra.Command{ Use: "schema", Short: "Create (import) a schema from a foreign server", Run: createSchema, } serverHost string serverPort string serverDBName string localUser string remoteUser string remotePassword string serverName string localSchemaName string remoteSchemaName string csServerName string importEnums bool importEnumConnection string ) func init() { createServerCmd.Flags().StringVar(&serverHost, "serverhost", "", "hostname of the remote PG server") createServerCmd.Flags().StringVar(&serverPort, "serverport", "5432", "port of the remote PG server") createServerCmd.Flags().StringVar(&serverDBName, "serverdbname", "", "database name on remote PG server") _ = createServerCmd.MarkFlagRequired("serverhost") _ = createServerCmd.MarkFlagRequired("serverport") _ = createServerCmd.MarkFlagRequired("serverdbname") createUsermapCmd.Flags().StringVar(&serverName, "servername", "", "foreign server name") createUsermapCmd.Flags().StringVar(&localUser, "localuser", "", "local user name") createUsermapCmd.Flags().StringVar(&remoteUser, "remoteuser", "", "remote user name") createUsermapCmd.Flags().StringVar(&remotePassword, "remotepassword", "", "remote user password") _ = createUsermapCmd.MarkFlagRequired("servername") _ = createUsermapCmd.MarkFlagRequired("localuser") _ = createUsermapCmd.MarkFlagRequired("remoteuser") _ = createUsermapCmd.MarkFlagRequired("remotepassword") createSchemaCmd.Flags().StringVar(&localSchemaName, "localschema", "", "local schema name") createSchemaCmd.Flags().StringVar(&csServerName, "servername", "", "foreign server name") createSchemaCmd.Flags().StringVar(&remoteSchemaName, "remoteschema", "", "the remote schema to import") createSchemaCmd.Flags().BoolVar(&importEnums, "importenums", false, "attempt to auto-create ENUMs locally before import") createSchemaCmd.Flags().StringVar(&importEnumConnection, "enumconnection", "", "connection string of database to import enums from") // TODO: Add a flag to accept a list of users for grants _ = createSchemaCmd.MarkFlagRequired("localschema") _ = createSchemaCmd.MarkFlagRequired("servername") _ = createSchemaCmd.MarkFlagRequired("remoteschema") createCmd.AddCommand(createServerCmd) createCmd.AddCommand(createExtensionCmd) createCmd.AddCommand(createUsermapCmd) createCmd.AddCommand(createSchemaCmd) } func preDoCreate(cmd *cobra.Command, _ []string) error { var err error log := logger.Log(cmd.Context()). WithField("function", "preDoCreate") dbConnection, err = database.GetConnection(cmd.Context(), config.Instance().GetDatabaseConnectionString()) if err != nil { return logger.ErrorfAsError(log, "error getting database connection: %s", err) } return nil } func postDoCreate(cmd *cobra.Command, _ []string) { database.CloseConnection(cmd.Context(), dbConnection) } func createExtension(cmd *cobra.Command, args []string) { log := logger.Log(cmd.Context()). WithField("function", "createExtension") extName := strings.TrimSpace(args[0]) err := util.CreateExtension(cmd.Context(), dbConnection, model.Extension{ Name: extName, }) if err != nil { log.Errorf("error creating extension %s: %s", extName, err) return } log.Infof("extension %s created", extName) } func createServer(cmd *cobra.Command, args []string) { log := logger.Log(cmd.Context()). WithField("function", "createServer") serverSlug := strings.TrimSpace(args[0]) if serverSlug == "" { hostSlug := strings.Replace(serverHost, ".", "_", -1) serverSlug = fmt.Sprintf("%s_%s_%s", hostSlug, serverPort, serverDBName) /* If the server slug starts with a number, prepend "server_" to it since PG doesn't like a number at the beginning of a server name. */ log.Debugf("serverSlug: %s", serverSlug) if util.StartsWithNumber(serverSlug) { serverSlug = fmt.Sprintf("server_%s", serverSlug) } } portInt, err := strconv.Atoi(serverPort) if err != nil { log.Errorf("error converting port to integer: %s", err) return } err = util.CreateServer(cmd.Context(), dbConnection, model.ForeignServer{ Name: serverSlug, Host: serverHost, Port: portInt, DB: serverDBName, }) if err != nil { log.Errorf("error creating server: %s", err) return } log.Infof("server %s created", serverSlug) } func createUsermap(cmd *cobra.Command, _ []string) { log := logger.Log(cmd.Context()). WithField("function", "createUsermap") err := util.EnsureUser(cmd.Context(), dbConnection, localUser, remotePassword) if err != nil { log.Errorf("error ensuring local user exists: %s", err) return } err = util.CreateUserMap(cmd.Context(), dbConnection, model.UserMap{ ServerName: serverName, LocalUser: localUser, RemoteUser: remoteUser, RemoteSecret: model.Secret{ Value: remotePassword, }, }) if err != nil { log.Errorf("error creating user mapping: %s", err) return } log.Infof("user mapping %s -> %s created", localUser, remoteUser) } func createSchema(cmd *cobra.Command, _ []string) { log := logger.Log(cmd.Context()). WithField("function", "createSchema") err := util.ImportSchema(cmd.Context(), dbConnection, csServerName, model.Schema{ ServerName: csServerName, LocalSchema: localSchemaName, RemoteSchema: remoteSchemaName, ImportENUMs: importEnums, ENUMConnection: importEnumConnection, SchemaGrants: model.Grants{ Users: make([]string, 0), }, }) if err != nil { log.Errorf("error importing foreign schema: %s", err) return } log.Infof("foreign schema %s imported", remoteSchemaName) }
package image import ( "bytes" "context" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/pkg/errors" "io" "io/ioutil" "strings" ) type FakeDownloader struct { DownloadContents []byte DownloadError error } func (fd FakeDownloader) Download(url string, ctx context.Context) (io.Reader, error) { if fd.DownloadContents == nil { return nil, fd.DownloadError } return bytes.NewReader(fd.DownloadContents), fd.DownloadError } var _ = Describe("Compressor", func() { var singleDownloader FakeDownloader BeforeEach(func() { singleDownloader = FakeDownloader{ DownloadContents: []byte(strings.Repeat("a", 128)), DownloadError: nil, } }) It("should compress wrapped downloader", func() { compressor := TryCompress(singleDownloader) compressedReader, err := compressor.Download("", context.TODO()) Expect(err).ToNot(HaveOccurred()) compressedReadAll, err := ioutil.ReadAll(compressedReader) Expect(err).ToNot(HaveOccurred()) Expect(len(compressedReadAll)).To(BeNumerically("<", len(singleDownloader.DownloadContents))) }) Context("when single downloader returns an error", func() { BeforeEach(func() { singleDownloader = FakeDownloader{ DownloadContents: nil, DownloadError: errors.New("some download error"), } }) It("should return an error", func() { compressor := TryCompress(singleDownloader) _, err := compressor.Download("", context.TODO()) Expect(err).To(Equal(singleDownloader.DownloadError)) }) }) })
package acoustid import ( "io/ioutil" "net/http" "testing" "github.com/jarcoal/httpmock" "github.com/stretchr/testify/assert" hc "github.com/ocramh/fingerprinter/internal/httpclient" fp "github.com/ocramh/fingerprinter/pkg/fingerprint" ) func TestLookupFingerprintOK(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() testDataFilepath := "../../test/data/acoustid_response.json" data, err := ioutil.ReadFile(testDataFilepath) assert.NoError(t, err) httpmock.RegisterResponder("POST", AcoustIDBaseURL, func(req *http.Request) (*http.Response, error) { resp := httpmock.NewBytesResponse(http.StatusOK, data) return resp, nil }, ) acClient := NewAcoustID("secret-key") fingerprint := fp.Fingerprint{ Duration: 100, Value: "the-extracted-fingerprint", } got, err := acClient.LookupFingerprint(&fingerprint, false) assert.NoError(t, err) assert.Equal(t, &AcoustIDLookupResp{ Status: "ok", Results: []ACLookupResult{ { ID: "033908fc-19da-4afa-a8a8-f8e1b87ada75", Score: 0.995636, Recordings: []Recording{ { MBRecordingID: "d4d24fa2-22f5-4b02-8751-8c0cf9cd02b2", MBReleaseGroups: []ReleaseGroup{ { ID: "baca2dcc-b3e7-4e5f-9560-68513356125d", Title: "La Di Da Di", Type: "Album", Releases: []Release{ {ID: "c100950b-5000-402c-a0dc-eb334840d134"}, {ID: "c0925a40-863c-4df7-bb22-8a2f74c124c2"}, {ID: "6e1d42d8-0cd5-4774-8606-ce33687893bc"}, {ID: "05ea68c9-0f99-4b18-bddc-3f3f584b6143"}, }, }, }, }, }, }, }, }, got) } func TestLookupFingerprintStatusNotOK(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() testDataFilepath := "../../test/data/acoustid_err_response.json" data, err := ioutil.ReadFile(testDataFilepath) assert.NoError(t, err) httpmock.RegisterResponder("POST", AcoustIDBaseURL, func(req *http.Request) (*http.Response, error) { resp := httpmock.NewBytesResponse(http.StatusBadRequest, data) return resp, nil }, ) acClient := NewAcoustID("secret-key") fingerprint := fp.Fingerprint{ Duration: 100, Value: "the-extracted-fingerprint", } _, err = acClient.LookupFingerprint(&fingerprint, false) assert.Equal(t, hc.HTTPError{ Code: http.StatusBadRequest, Message: "invalid fingerprint", }, err) } func TestLookupFingerprintStatusServiceUnavailable(t *testing.T) { httpmock.Activate() defer httpmock.DeactivateAndReset() httpmock.RegisterResponder("POST", AcoustIDBaseURL, func(req *http.Request) (*http.Response, error) { resp := httpmock.NewBytesResponse(http.StatusServiceUnavailable, []byte{}) return resp, nil }, ) acClient := NewAcoustID("secret-key") fingerprint := fp.Fingerprint{ Duration: 100, Value: "the-extracted-fingerprint", } _, err := acClient.LookupFingerprint(&fingerprint, true) assert.Equal(t, hc.HTTPError{ Code: http.StatusServiceUnavailable, Message: "upstream service not available", }, err) assert.Equal(t, 2, httpmock.GetTotalCallCount()) }
package test_helper import ( "github.com/lyokato/goidc/flow" "github.com/lyokato/goidc/prompt" ) type ( TestClient struct { id string ownerId int64 secret string redirectURI string idTokenAlg string idTokenKeyId string idTokenKey interface{} grantTypes map[string]bool Enabled bool } ) func NewTestClient(ownerId int64, id, secret, redirectURI, alg string, key interface{}, keyId string) *TestClient { return &TestClient{ ownerId: ownerId, id: id, secret: secret, redirectURI: redirectURI, idTokenAlg: alg, idTokenKey: key, idTokenKeyId: keyId, grantTypes: make(map[string]bool, 0), Enabled: true, } } func (c *TestClient) AllowToUseGrantType(gt string) { c.grantTypes[gt] = true } func (c *TestClient) CanUseFlow(flowType flow.FlowType) bool { return true } func (c *TestClient) CanUseGrantType(gt string) bool { allowed, exists := c.grantTypes[gt] if exists { return allowed } else { return false } } func (c *TestClient) CanUseRedirectURI(url string) bool { return (c.redirectURI == url) } func (c *TestClient) CanUseScope(flowType flow.FlowType, scope string) bool { return true } func (c *TestClient) GetOwnerUserId() int64 { return c.ownerId } func (c *TestClient) GetId() string { return c.id } func (c *TestClient) MatchSecret(secret string) bool { return c.secret == secret } func (c *TestClient) GetIdTokenAlg() string { return c.idTokenAlg } func (c *TestClient) GetIdTokenKeyId() string { return c.idTokenKeyId } func (c *TestClient) GetIdTokenKey() interface{} { return c.idTokenKey } func (c *TestClient) GetNoConsentPromptPolicy() prompt.NoConsentPromptPolicy { return prompt.NoConsentPromptPolicyForceConsent } func (c *TestClient) GetNonePromptPolicy() prompt.NonePromptPolicy { return prompt.NonePromptPolicyForbidden } func (c *TestClient) GetAssertionKey(alg, kid string) interface{} { return []byte(c.secret) }
package domain import ( "strconv" "time" "github.com/pkg/errors" ) // Trading defines the Trading domain type Trading struct { ID int Pair string Share float64 Price float64 CreatedAt time.Time } // NewTrading builds a new Trading structure ensuring its values func NewTrading(tradeID int, pair string, size string, price string, createdAt time.Time) (Trading, error) { sizeNumber, err := strconv.ParseFloat(size, 64) if err != nil { return Trading{}, errors.Wrap(err, "error to convert size to float64") } priceNumber, err := strconv.ParseFloat(price, 64) if err != nil { return Trading{}, errors.Wrap(err, "error to convert price to float64") } return Trading{ID: tradeID, Pair: pair, Share: sizeNumber, Price: priceNumber, CreatedAt: createdAt}, nil }