text
stringlengths
11
4.05M
package sstats import ( "math" "testing" ) func TestFisherUpdate(t *testing.T) { sp, err := NewFisher(5) if err != nil { t.Fatal(err) } valx := []float64{1, 2, 3, 2, 1, 2, 3, 2, 1} expected := []float64{0, 0.881, math.Inf(1), 0, -1.899, 0, 1.899, 0, -1.899} for i, v := range valx { sp.Update(v) val := sp.Value() if math.Abs(val-expected[i]) > 1e-3 { t.Errorf("Expected value %.3f, but got %.3f\n", expected[i], val) continue } } } func BenchmarkFisherUpdate(b *testing.B) { window := 1000 numValues := 100000 sp, err := NewFisher(window) if err != nil { b.Fatal(err) } for j := 0; j < b.N; j++ { for i := 0; i < numValues; i++ { sp.Update(float64(i)) } sp.Reset() } }
package main import ( "context" "time" "github.com/gopherjs/gopherjs/js" "github.com/goxjs/websocket" "github.com/nayarsystems/gobbus" ) func main() { js.Global.Set("obbus", map[string]interface{}{ "connect": func(address string) *js.Object { promise := js.Global.Get("Promise").New(func(res, rej func(interface{})) { go func() { var bus *gobbus.Obbus ret := js.MakeWrapper(map[string]interface{}{}) connected := false subscriptions := make(map[*context.CancelFunc]bool, 0) conn, err := websocket.Dial(address, "http://gobbus.jsclient") if err != nil { rej("Error connecting to websocket gateway: " + err.Error()) return } bus = gobbus.NewObbus(conn, &gobbus.ObbusOpts{ Timeout: time.Second * 30, }) connected = true ret.Set("debug", func(d bool) { if bus != nil { bus.Debug = d } }) ret.Set("subscribe", func(path string, cb func(interface{})) *js.Object { ctx, cancelFun := context.WithCancel(bus.GetContext()) subscriptions[&cancelFun] = true go func() { defer cancelFun() if !connected { return } rchan := make(chan *gobbus.Message, 1000) bus.Subscribe(rchan, path) loop: for { select { case <-ctx.Done(): break loop case msg, ok := <-rchan: if !ok { break loop } cb(map[string]interface{}{ "Topic": msg.Topic, "Value": msg.GetValue(), "Flags": msg.Flags, "ResponseTopic": msg.Rtopic, }) } } bus.Unsubscribe(rchan, path) }() ret := js.MakeWrapper(map[string]interface{}{}) ret.Set("topic", path) ret.Set("cancel", func() { delete(subscriptions, &cancelFun) cancelFun() }) return ret }) ret.Set("unsubscribeAll", func(path string, cb func(interface{})) *js.Object { promise := js.Global.Get("Promise").New(func(res, rej func(interface{})) { go func() { if !connected { rej("Not Connected") return } for cancelFun, _ := range subscriptions { delete(subscriptions, cancelFun) (*cancelFun)() } res(nil) }() }) return promise }) ret.Set("publishString", func(topic string, val string, flags *js.Object, rtopic string) *js.Object { promise := js.Global.Get("Promise").New(func(res, rej func(interface{})) { go func() { if !connected { rej("Not Connected") return } i, err := bus.PublishStr(topic, val, parseFlags(flags), rtopic, true) if err != nil { rej(err.Error()) } else { res(i) } }() }) return promise }) ret.Set("publishInteger", func(topic string, val int, flags *js.Object, rtopic string) *js.Object { promise := js.Global.Get("Promise").New(func(res, rej func(interface{})) { go func() { if !connected { rej("Not Connected") return } i, err := bus.PublishInt(topic, val, parseFlags(flags), rtopic, true) if err != nil { rej(err.Error()) } else { res(i) } }() }) return promise }) ret.Set("publishDouble", func(topic string, val float64, flags *js.Object, rtopic string) *js.Object { promise := js.Global.Get("Promise").New(func(res, rej func(interface{})) { go func() { if !connected { rej("Not Connected") return } i, err := bus.PublishDbl(topic, val, parseFlags(flags), rtopic, true) if err != nil { rej(err.Error()) } else { res(i) } }() }) return promise }) ret.Set("publishBuffer", func(topic string, val []byte, flags *js.Object, rtopic string) *js.Object { promise := js.Global.Get("Promise").New(func(res, rej func(interface{})) { go func() { if !connected { rej("Not Connected") return } i, err := bus.PublishBuf(topic, val, parseFlags(flags), rtopic, true) if err != nil { rej(err.Error()) } else { res(i) } }() }) return promise }) ret.Set("rpcString", func(topic string, val string, flags *js.Object, timeoutms int64) *js.Object { promise := js.Global.Get("Promise").New(func(res, rej func(interface{})) { go func() { if !connected { rej("Not Connected") return } i, err := bus.RpcStr(topic, val, parseFlags(flags), time.Millisecond*time.Duration(timeoutms*1000)) if err != nil { rej(err.Error()) } else { res(i.GetValue()) } }() }) return promise }) ret.Set("rpcInteger", func(topic string, val int, flags *js.Object, timeoutms int) *js.Object { promise := js.Global.Get("Promise").New(func(res, rej func(interface{})) { go func() { if !connected { rej("Not Connected") return } i, err := bus.RpcInt(topic, val, parseFlags(flags), time.Millisecond*time.Duration(timeoutms*1000)) if err != nil { rej(err.Error()) } else { res(i.GetValue()) } }() }) return promise }) ret.Set("rpcDouble", func(topic string, val float64, flags *js.Object, timeoutms int) *js.Object { promise := js.Global.Get("Promise").New(func(res, rej func(interface{})) { go func() { if !connected { rej("Not Connected") return } i, err := bus.RpcDbl(topic, val, parseFlags(flags), time.Millisecond*time.Duration(timeoutms*1000)) if err != nil { rej(err.Error()) } else { res(i.GetValue()) } }() }) return promise }) ret.Set("rpcBuffer", func(topic string, val []byte, flags *js.Object, timeoutms int) *js.Object { promise := js.Global.Get("Promise").New(func(res, rej func(interface{})) { go func() { if !connected { rej("Not Connected") return } i, err := bus.RpcBuf(topic, val, parseFlags(flags), time.Millisecond*time.Duration(timeoutms*1000)) if err != nil { rej(err.Error()) } else { res(i.GetValue()) } }() }) return promise }) ret.Set("close", func() { go func() { if bus != nil && bus.GetContext().Err() == nil { bus.Close(nil) } }() }) res(ret) }() }) return promise }, "newMessageFlags": func() *gobbus.MessageFlags { return &gobbus.MessageFlags{} }, }) } type MessageFlags struct { *js.Object Instant bool `js:"Instant"` NonRecursive bool `js:"NonRecursive"` Response bool `js:"Response"` Error bool `js:"Error"` } func parseFlags(flags *js.Object) *gobbus.MessageFlags { jsflags := &MessageFlags{Object: flags} return &gobbus.MessageFlags{ Instant: jsflags.Instant, Error: jsflags.Error, NonRecursive: jsflags.NonRecursive, Response: jsflags.Response, } }
package config import ( "github.com/nicksnyder/go-i18n/v2/i18n" ) // 系统配置 type App struct { Address string Static string Log string Locale string Language string } type Database struct { Driver string Address string Database string User string Password string } type Configuration struct { App App Db Database LocaleBundle *i18n.Bundle } //var config *Configuration //var once sync.Once
package main import ( "fmt" "example.com/hello/composite/github" ) func main() { re, err := github.SearchIssues([]string{"vue", "vuex"}) if err != nil { fmt.Println(err) } fmt.Println(re.TotalCount) // fmt.Println(re.Items[:2]) // jsonMovie() github.Text(re) github.HTML(re) } func listTest(li []int) { li = append(li, 2) }
package lc import "sort" // Time: O(n^2) // Benchmark: 552ms 6.4mb | 9% 88% func minMoves(nums []int) int { if len(nums) <= 1 { return 0 } sort.Ints(nums) var total int pos := len(nums) - 1 for nums[0] != nums[pos] { d := nums[pos] - nums[0] total += d for i := 0; i < pos; i++ { nums[i] += d } pos-- } return total }
package metrics import ( "crypto/tls" "encoding/base64" "encoding/json" "fmt" "net/http" "regexp" "strings" "time" log "github.com/sirupsen/logrus" ) func getAuthHeader(user, token string) string { if user != "" && token != "" { s := user + ":" + token return "Basic " + base64.StdEncoding.EncodeToString([]byte(s)) } return "" } func getJSON(url, user, token string, insecure bool, target interface{}) (string, error) { start := time.Now() log.Debug("Connecting to ", url) client := &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { if len(via) >= 4 { return fmt.Errorf("stopped after 4 redirects") } req.Header.Add("Authorization", getAuthHeader(user, token)) return nil }, Timeout: 60 * time.Second, } if insecure { tr := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: insecure, }, } client.Transport = tr } req, err := http.NewRequest("GET", url, nil) if err != nil { return "", fmt.Errorf("Error Creating request: %v", err) } req.Header.Add("Authorization", getAuthHeader(user, token)) resp, err := client.Do(req) if err != nil { return "", fmt.Errorf("Error Collecting JSON from API: %v", err) } respFormatted := json.NewDecoder(resp.Body).Decode(target) resp.Body.Close() log.Debug("Time to get json: ", float64((time.Since(start))/time.Millisecond), " ms") return getNext(resp.Header.Get("Link")), respFormatted } func getNext(header string) string { if len(header) == 0 { return "" } linkFormat, err := regexp.Compile("^ *<([^>]+)> *; *rel=\"next\"") if err != nil { log.Error("Error checking header format ", err) return "" } for _, line := range strings.Split(header, ",") { if linkFormat.MatchString(line) { return linkFormat.ReplaceAllString(line, "$1") } } return "" }
package catapult import ( "context" "encoding/json" "fmt" "net/http" "strings" "github.com/Clever/ci-scripts/internal/environment" "github.com/Clever/circle-ci-integrations/gen-go/client" "github.com/Clever/circle-ci-integrations/gen-go/models" "github.com/Clever/wag/logging/wagclientlogger" ) // Artifact aliases a catapult models.CatapultApplication, and contains // information about the location of a build artifact so that catapult // can correctly inject it at deploy time. type Artifact = models.CatapultApplication // Catapult wraps the circle-ci-integrations service with a trimmed down // and simplified API. type Catapult struct { client client.Client } // New initializes Catapult with a circle-ci-integrations client that // handles basic auth and discovers it's url via ci environment variables. func New() *Catapult { // circle-ci-integrations up until this app was requested against in // ci via curl. Because of this the url environment variable was the // full protocol, hostname and path. This cleans up the variable so // we only have the proto and hostname. There are two separate // variables provided to provide legacy support so clean up both // possibilities url := strings.TrimSuffix(environment.CatapultURL, "/v2/catapult") url = strings.TrimSuffix(url, "/catapult") var rt http.RoundTripper = &basicAuthTransport{} cli := client.New(url, fmtPrinlnLogger{}, &rt) return &Catapult{client: cli} } // Publish a list of build artifacts to catapult. func (c *Catapult) Publish(ctx context.Context, artifacts []*Artifact) error { for _, art := range artifacts { err := c.client.PostCatapultV2(ctx, &models.CatapultPublishRequest{ Username: environment.CircleUser, Reponame: environment.Repo, Buildnum: environment.CircleBuildNum, App: art, }) if err != nil { return fmt.Errorf("failed to publish %s with catapult: %v", art.ID, err) } } return nil } // Wraps the default http transport in a very thin wrapper which just // adds basic auth to all of the requests. The auth params are pulled // from the ci environment. type basicAuthTransport struct{} func (ba *basicAuthTransport) RoundTrip(r *http.Request) (*http.Response, error) { r.SetBasicAuth(environment.CatapultUser, environment.CatapultPassword) return http.DefaultTransport.RoundTrip(r) } // A lightweight logger which prints the wag client logs to standard out. type fmtPrinlnLogger struct{} func (fmtPrinlnLogger) Log(level wagclientlogger.LogLevel, title string, data map[string]interface{}) { bs, _ := json.Marshal(data) fmt.Printf("%s - %s %s\n", levelString(level), title, string(bs)) } func levelString(l wagclientlogger.LogLevel) string { switch l { case 0: return "TRACE" case 1: return "DEBUG" case 2: return "INFO" case 3: return "WARNING" case 4: return "ERROR" case 5: return "CRITICAL" case 6: return "FROM_ENV" default: return "INFO" } }
package main const algoHighRiseThreshold1 = 0.20 // price rise ratio /* * High Rise Algorithm * Description: * Based on each KLine, if Close price > initialPrice, sell the gain part; * otherwise, do nothing. * The idea is to keep the remain 'value' at most as initialPrice. */ func algoHighRise(balanceBase *float64, balanceQuote *float64, kline *KlineRo, initialAmount float64, initialPrice float64, demo bool) (float64,float64){ sell := 0.0 buy := 0.0 if initialPrice<=0 { return 0,0 } ratio := (kline.Close - initialPrice)/initialPrice if ratio <= algoHighRiseThreshold1 { return 0,0 } sell = *balanceBase *balanceQuote += (sell - buy)*kline.Close *balanceBase += buy - sell return buy,sell }
package main import "fmt" type Key struct { v int } type Value struct { v int } func main() { var m map[string]string m = make(map[string]string) m["abc"] = "bbb" fmt.Println(m["abc"]) m1 := make(map[int]string) m1[53] = "ddd" fmt.Println(m1[53]) fmt.Println(m1[55]) m2 := make(map[int]int) m2[4] = 4 fmt.Println("m2[10] = ", m2[10]) m3 := make(map[int]bool) m3[4] = true fmt.Println(m3[6]) v, ok := m2[10] v1, ok1 := m2[4] fmt.Println(v, ok, v1, ok1) delete(m2, 4) m2[2] = 5 m2[10] = 101 for key, value := range m2 { fmt.Println(key, " = ", value) } }
package main import ( "review/zinx/net" "review/zinx/ziface" "fmt" ) //创建路由控制器 type PingRouter struct { net.BaseRouter } //处理业务之前的方法 func (r *PingRouter) PreHandle(request ziface.IRequest) { fmt.Println("Call Router PreHandle ...") _,err := request.GetConnection().GetTCPconnection().Write([]byte("before ping ...\n")) if err!=nil{ fmt.Println("call back before ping err:",err) return } } //真正处理业务的方法 func (r *PingRouter) Handle(request ziface.IRequest) { fmt.Println("Call Router Handle ...") _,err := request.GetConnection().GetTCPconnection().Write([]byte("ping ping ping ...\n")) if err!=nil{ fmt.Println("call back ping err:",err) return } } //处理业务之后的方法 func (r *PingRouter) PostHandle(request ziface.IRequest) { fmt.Println("Call Router PostHandle ...") _,err := request.GetConnection().GetTCPconnection().Write([]byte("after ping ...\n")) if err!=nil{ fmt.Println("call back after ping err:",err) return } } func main() { //创建一个zinx server对象 s := net.NewServer("zinx v0.1") //添加router s.AddRouter(&PingRouter{}) //让server对象 启动服务 s.Serve() return }
package main import ( "fmt" "math/rand" "time" ) // CODE OMIT func foo1() { for { time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond) fmt.Println("foo1") } } func main() { // GO OMIT go foo1() // HL for i := 0; i < 10; i++ { time.Sleep(1 * time.Second) fmt.Println("main") } } // END OMIT
package main import ( "github.com/google/uuid" "log" "os" "strings" ) func main() { identifier := getUUID() println(identifier) println(strings.Replace(identifier, "-", "", 4)) } func getUUID() string { if len(os.Args) > 1 { identifier, err := uuid.Parse(os.Args[1]) if err != nil { log.Fatal("Format must be a valid UUID") } return identifier.String() } return uuid.New().String() }
package DbService import ( "fmt" "ledger/DbUtil" "time" ) func WorkEntry_PreExe(workID string, workName string, ownerName string, adminName string, timeNow time.Time, txId string) []byte { result := InsertWorkEntry_PreExe(workID, workName, ownerName, adminName, timeNow) return result } func WorkEntry(workID string, workName string, ownerName string, adminName string, timeNow time.Time, txId string) bool { txHash := createTxhash(adminName, ownerName, workName, timeNow, txId) result, _ := InsertWorkEntry(workID, workName, ownerName, adminName, timeNow, txId, txHash) if result == false { return result } // postRead := []string{} DbUtil.Load(&postRead, "txhash") fmt.Println("txhash", postRead) postRead = append(postRead, txHash) DbUtil.Store(postRead, "txhash") // return result }
package implementations var KEY = "really_useful_object" type SerializationObject struct { String1, String2, String3, String4, String5 string FieldX string } type Implementation interface { Get() (object *SerializationObject, err error) Set(object *SerializationObject) (err error) Del() (err error) GetOneField(fieldName string) (value string, err error) SetOneField(fieldName string, value string) (err error) }
// Copyright 2021 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package smb import ( "context" "io/ioutil" "path/filepath" "strings" "time" "golang.org/x/sys/unix" "chromiumos/tast/common/testexec" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" "chromiumos/tast/local/procutil" "chromiumos/tast/testing" ) // Server is the instance of the smb daemon. type Server struct { cmd *testexec.Cmd running bool serverErr chan error } const ( smbdServerBinaryPath = "/usr/local/sbin/smbd" smbdServerTerminatedSignal = "signal: terminated" ) // NewServer sets up a smb daemon using the supplied smb.conf file. func NewServer(smbConf string) *Server { cmd := testexec.CommandContext( context.Background(), smbdServerBinaryPath, // NOLINT "--daemon", // Start smbd as a daemon. "--foreground", // Foreground the process, ensuring we can signal it via os.Signal. "--debug-stdout", // Send the logs to stdout to ensure we can dump them on failure. "--no-process-group", // Stop smbd from creating a process group. "--configfile="+smbConf, // Pass our custom smbd.conf file. "--debuglevel=5") // Up the logging level to provide for better debugging. return &Server{cmd: cmd, running: false, serverErr: make(chan error)} } // Stop tries to gracefully shut down the underlying smb daemon by sending a // SIGTERM signal to the process. // https://www.samba.org/samba/docs/current/man-html/smbd.8.html func (s *Server) Stop(ctx context.Context) error { if !s.running { serverErr := <-s.serverErr return errors.Wrap(serverErr, "failed to stop smbd, not running may have crashed") } // Reserve 5s to force kill smbd if we can't gracefully shut it down. ctx, cancel := ctxutil.Shorten(ctx, 5*time.Second) defer cancel() // Attempt to send a SIGTERM to smbd. if err := s.cmd.Signal(unix.SIGTERM); err != nil { return errors.Wrap(err, "failed to send SIGTERM to smbd") } // If the shortened context hits the deadline, send a SIGKILL otherwise // recover the error (if any) after sending SIGTERM. select { case <-ctx.Done(): s.cmd.Kill() return errors.New("failed trying to stop smbd, send SIGKILL instead") case err := <-s.serverErr: if err != nil { return errors.Wrap(err, "failed trying to stop smbd") } } return nil } // Start begins the smb daemon and ensures it's log file is adequately flushed // to a file in the event an error occurs. // A SIGTERM is not considered worth of a log dump here due to Stop() sending // a SIGTERM to gracefully shut down the process. func (s *Server) Start(ctx context.Context) error { if s.running { return errors.New("smbd already running") } if err := terminateRunningSmbdInstances(ctx); err != nil { return err } s.running = true go func() { output, err := s.cmd.CombinedOutput() s.running = false if err == nil { s.serverErr <- nil return } if err != nil && strings.Contains(err.Error(), smbdServerTerminatedSignal) { testing.ContextLog(ctx, "smbd received a terminated signal") s.serverErr <- nil return } testing.ContextLog(ctx, "smbd may have crashed, dumping logs: ", err) outDir, ok := testing.ContextOutDir(ctx) if ok { errorLogPath := filepath.Join(outDir, "smbd.log") if err := ioutil.WriteFile(errorLogPath, output, 0644); err != nil { testing.ContextLog(ctx, "Failed to write smbd logs to: ", errorLogPath) } } else { testing.ContextLog(ctx, "Failed to get the out directory to dump smbd logs") } s.serverErr <- errors.Wrap(err, "smbd has crashed") }() return nil } // terminateRunningSmbdInstances finds any running instances of smbd and // terminates them prior to running to ensure uniqueness. func terminateRunningSmbdInstances(ctx context.Context) (retErr error) { instances, err := procutil.FindAll(procutil.ByExe(smbdServerBinaryPath)) if err != nil && err != procutil.ErrNotFound { return errors.Wrap(err, "failed to find running smbd instances") } if len(instances) == 0 { return nil } testing.ContextLogf(ctx, "Found %d running smbd instances, terminating them", len(instances)) for _, proc := range instances { if err = proc.SendSignal(unix.SIGTERM); err != nil { retErr = errors.Wrap(err, "failed to terminate smbd instance") } } return }
package main import "fmt" func main() { fmt.Println("Hello, World!\n") printMessage("Hi", "I am Ragul!") fmt.Println("") firstname := "Ragul" lastname := "Ravindira" printMessageTwo(&firstname, &lastname) // pointer parameters fmt.Println("") sum("The sum is: ", 1, 2, 3, 4, 5) // variatic parameters fmt.Println("") t := total(1, 2, 3, 4, 5) fmt.Println("The total is: ", t) fmt.Println("") ts := totalSum(1, 2, 3, 4, 5) fmt.Println("The total sum is: ", *ts) fmt.Println("") d, err := divide(6.0, 4.0) if err != nil { fmt.Println(err) return } fmt.Println(d) fmt.Println("") /** Anonymous functions */ for i := 0; i < 5; i++ { func(i int) { fmt.Println(i) }(i) } /** Anonymous functions as variable */ f := func() { // var f func() = func() {} fmt.Println("\nAnonymous functions as variable") } f() fmt.Println("") /** Method Invocation */ g := greeter{ greeting: "Hello", name: "GO", } g.greet() fmt.Println("The new g.name is: ", g.name) } /** Function with multiple parameter */ func printMessage(greeting string, name string) { //func printMessage(greeting, name string) { // if same type fmt.Println(greeting, name) } /** Function with pointer parameters */ func printMessageTwo(firstname, lastname *string) { fmt.Println(*firstname, *lastname) fmt.Println(firstname, lastname) // prints the address *lastname = "Dravid" fmt.Println(*firstname, *lastname) } func sum(msg string, values ...int) { fmt.Println(values) result := 0 for _, v := range values { result += v } fmt.Println(msg, result) } /** Function with return values */ func total(values ...int) int { fmt.Println(values) result := 0 for _, v := range values { result += v } return result } /** Function with return values as pointers */ func totalSum(values ...int) *int { fmt.Println(values) result := 0 for _, v := range values { result += v } return &result } /** Function with multiple return values */ func divide(a, b float64) (float64, error) { if b == 0.0 { return 0.0, fmt.Errorf("cannot divide by zero") } return a / b, nil } /** Method Invocation */ type greeter struct { greeting string name string } func (g greeter) greet() { // func (g greeter) greet() { // attributes can be changed when parsed as pointer fmt.Println(g.greeting, g.name) g.name = "" }
package tsk import ( "go4eat-api/pkg/tsk" ) // NewList func func NewList() *tsk.List { return tsk.NewList([]*tsk.Task{ tsk.NewTask("server", "Run server", server), tsk.NewTask("dbindexes", "Create database indexes", dbIndexes), tsk.NewTask("places", "Create places", places), }) }
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // package common import ( "testing" "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) func TestErrWithStatus(t *testing.T) { t.Run("wrap in regular error and downcast", func(t *testing.T) { err := errors.New("test") err = ErrWrap(400, err, "test error 2") err = errors.Wrap(err, "test error 3") err = errors.Wrap(err, "test error 4") err = errors.Wrap(err, "test error 5") status := ErrToStatus(err) assert.Equal(t, 400, status) assert.Equal(t, "test error 5: test error 4: test error 3: test error 2: test", err.Error()) }) t.Run("wrap error with status and downcast", func(t *testing.T) { err := NewErr(404, errors.New("error")) err = errors.Wrap(err, "test error 2") err = errors.Wrap(err, "test error 3") status := ErrToStatus(err) assert.Equal(t, 404, status) assert.Equal(t, "test error 3: test error 2: error", err.Error()) }) t.Run("wrap with error with status and get latest status", func(t *testing.T) { err := NewErr(404, errors.New("error")) err = ErrWrapf(400, err, "old error status: %d", ErrToStatus(err)) status := ErrToStatus(err) assert.Equal(t, 400, status) assert.Equal(t, "old error status: 404: error", err.Error()) }) }
package main import ( "binary_tree/tree" "fmt" "log" "os" "strconv" ) /* Two nodes in a binary tree can be called cousins if they are on the same level of the tree but have different parents. For example, in the following diagram 4 and 6 are cousins. 1 / \ 2 3 / \ \ 4 5 6 Given a binary tree and a particular node, find all cousins of that node. */ func main() { // Read value of "particular node" targetNodeValue, err := strconv.Atoi(os.Args[1]) if err != nil { log.Fatal(err) } fmt.Printf("Node of interest has value %d\n", targetNodeValue) // Construct BST from all the remaining command line values // Using a BST because by entering nodes in bread-first order, // I can get any shape tree I want. root := tree.CreateNumericFromString(os.Args[2]) d, p := findDepth(root, targetNodeValue, 0) fmt.Printf("Particular node of value %d at depth %d, parent %d\n", targetNodeValue, d, p) nodesAtDepth(root, targetNodeValue, p, d, 0) } // findDepth returns the depth in the tree (root has depth 0) // of a node with data value of value (argument), // or -1 if value not found. Also return the value of the parent node. func findDepth(node *tree.NumericNode, value int, depth int) (int, int) { if node == nil { return -1, 0 } if node.Data == value { return depth, 0 } d, p := findDepth(node.Left, value, depth+1) if d > -1 { if d == depth+1 { // this is the parent node return d, node.Data } return d, p } d, p = findDepth(node.Right, value, depth+1) if d > -1 { if d == depth+1 { // this is the parent node return d, node.Data } } return d, p } // nodesAtDepth prints the value of nodes at depth desiredDepth, // but not the node with data value cousin. That's the "particular node" // itself. func nodesAtDepth(node *tree.NumericNode, parentValue, cousin, desiredDepth, depth int) { if node == nil || node.Data == cousin || node.Data == parentValue { return } if desiredDepth == depth { fmt.Printf("Cousin node %d\n", node.Data) return } nodesAtDepth(node.Left, parentValue, cousin, desiredDepth, depth+1) nodesAtDepth(node.Right, parentValue, cousin, desiredDepth, depth+1) }
package main import ( "bytes" "crypto/rand" "fmt" "io" "log" "net/http" "os" ) func randomString() string { b := make([]byte, 16) _, err := rand.Read(b) if err != nil { log.Fatal(err) } uuid := fmt.Sprintf("%x%x%x%x%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) return uuid } func generateFileName() string { // By default, save images to $HOME/Pictures/Wallpapers var output bytes.Buffer val, _ := os.LookupEnv("HOME") output.WriteString(val) output.WriteString("/Pictures/Wallpapers/") output.WriteString(randomString()) output.WriteString(".jpeg") return output.String() } func download(url string) error { filepath := generateFileName() res, err := http.Get(url) if err != nil { return err } // Defer => Execute as last action in function defer res.Body.Close() img, err := os.Create(filepath) if err != nil { return err } defer img.Close() io.Copy(img, res.Body) return err } func main() { const url = "https://source.unsplash.com/random/3840x2160/?wallpaper" if err := download(url); err != nil { fmt.Println("An error has occured!\n", err) } }
package main import "fmt" import "math" const s string ="contant" func main() { fmt.Println(s) const n = 5000000 const d = 3e20/n fmt.Println(d) fmt.Println(int(d)) fmt.Println(math.Sin(n)) }
// Copyright 2009 Michael Stephens. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package mongo import ( "os"; "io"; "io/ioutil"; "net"; "fmt"; "rand"; "bytes"; "encoding/binary"; "container/vector"; ) var last_req int32 const ( _OP_REPLY = 1; _OP_MSG = 1000; _OP_UPDATE = 2001; _OP_INSERT = 2002; _OP_GET_BY_OID = 2003; _OP_QUERY = 2004; _OP_GET_MORE = 2005; _OP_DELETE = 2006; _OP_KILL_CURSORS = 2007; ) type message interface { Bytes() []byte; RequestID() int32; OpCode() int32; } type Connection struct { host string; port int; conn *net.TCPConn; } func Connect(host string, port int) (*Connection, os.Error) { laddr, _ := net.ResolveTCPAddr("localhost"); addr, _ := net.ResolveTCPAddr(fmt.Sprintf("%s:%d", host, port)); conn, err := net.DialTCP("tcp", laddr, addr); if err != nil { return nil, err } return &Connection{host, port, conn}, nil; } func header(length, reqID, respTo, opCode int32) []byte { b := make([]byte, 16); binary.LittleEndian.PutUint32(b[0:4], uint32(length)); binary.LittleEndian.PutUint32(b[4:8], uint32(reqID)); binary.LittleEndian.PutUint32(b[8:12], uint32(respTo)); binary.LittleEndian.PutUint32(b[12:16], uint32(opCode)); return b; } func (c *Connection) writeMessage(m message) os.Error { body := m.Bytes(); hb := header(int32(len(body)+16), m.RequestID(), 0, m.OpCode()); msg := bytes.Add(hb, body); _, err := c.conn.Write(msg); last_req = m.RequestID(); return err; } func (c *Connection) readReply() (*replyMsg, os.Error) { size_bits, _ := ioutil.ReadAll(io.LimitReader(c.conn, 4)); size := binary.LittleEndian.Uint32(size_bits); rest, _ := ioutil.ReadAll(io.LimitReader(c.conn, int64(size)-4)); reply := parseReply(rest); return reply, nil; } type Database struct { conn *Connection; name string; } func (c *Connection) GetDB(name string) *Database { return &Database{c, name} } func (db *Database) Drop() os.Error { cmd, err := Marshal(map[string]int{"dropDatabase": 1}); if err != nil { return err } _, err = db.Command(cmd); return err; } func (db *Database) Repair(preserveClonedFilesOnFailure, backupOriginalFiles bool) os.Error { cmd := &_Object{map[string]BSON{"repairDatabase": &_Number{1, _Null{}}, "preserveClonedFilesOnFailure": &_Boolean{preserveClonedFilesOnFailure, _Null{}}, "backupOriginalFiles": &_Boolean{backupOriginalFiles, _Null{}}}, _Null{}}; _, err := db.Command(cmd); return err; } type Collection struct { db *Database; name string; } func (db *Database) GetCollection(name string) *Collection { return &Collection{db, name} } type Cursor struct { collection *Collection; id int64; pos int; docs *vector.Vector; } func (c *Cursor) HasMore() bool { if c.pos < c.docs.Len() { return true } err := c.GetMore(); if err != nil { return false } return c.pos < c.docs.Len(); } func (c *Cursor) GetNext() (BSON, os.Error) { if c.HasMore() { doc := c.docs.At(c.pos).(BSON); c.pos = c.pos + 1; return doc, nil; } return nil, os.NewError("cursor failure"); } func (c *Cursor) GetMore() os.Error { if c.id == 0 { return os.NewError("no cursorID") } gm := &getMoreMsg{c.collection.fullName(), 0, c.id, rand.Int31()}; conn := c.collection.db.conn; err := conn.writeMessage(gm); if err != nil { return err } reply, err := conn.readReply(); if err != nil { return err } c.pos = 0; c.docs = reply.docs; return nil; } func (c *Cursor) Close() os.Error { if c.id == 0 { // not open on server return nil } req_id := rand.Int31(); km := &killMsg{1, []int64{c.id}, req_id}; conn := c.collection.db.conn; return conn.writeMessage(km); } func (c *Collection) fullName() string { return c.db.name + "." + c.name } type indexDesc struct { Name string; Ns string; Key map[string]int; } func (c *Collection) EnsureIndex(name string, index map[string]int) os.Error { coll := c.db.GetCollection("system.indexes"); id := &indexDesc{name, c.fullName(), index}; desc, err := Marshal(id); if err != nil { return err } return coll.Insert(desc); } func (c *Collection) DropIndexes() os.Error { return c.DropIndex("*") } func (c *Collection) DropIndex(name string) os.Error { cmdm := map[string]string{"deleteIndexes": c.fullName(), "index": name}; cmd, err := Marshal(cmdm); if err != nil { return err } _, err = c.db.Command(cmd); return err; } func (c *Collection) Drop() os.Error { cmdm := map[string]string{"drop": c.fullName()}; cmd, err := Marshal(cmdm); if err != nil { return err } _, err = c.db.Command(cmd); return err; } func (c *Collection) Insert(doc BSON) os.Error { im := &insertMsg{c.fullName(), doc, rand.Int31()}; return c.db.conn.writeMessage(im); } func (c *Collection) Remove(selector BSON) os.Error { dm := &deleteMsg{c.fullName(), selector, rand.Int31()}; return c.db.conn.writeMessage(dm); } func (coll *Collection) Query(query BSON, skip, limit int) (*Cursor, os.Error) { req_id := rand.Int31(); conn := coll.db.conn; qm := &queryMsg{0, coll.fullName(), int32(skip), int32(limit), query, req_id}; err := conn.writeMessage(qm); if err != nil { return nil, err } reply, err := conn.readReply(); if err != nil { return nil, err } if reply.responseTo != req_id { return nil, os.NewError("wrong responseTo code") } return &Cursor{coll, reply.cursorID, 0, reply.docs}, nil; } func (coll *Collection) FindAll(query BSON) (*Cursor, os.Error) { return coll.Query(query, 0, 0) } func (coll *Collection) FindOne(query BSON) (BSON, os.Error) { cursor, err := coll.Query(query, 0, 1); if err != nil { return nil, err } return cursor.GetNext(); } func (coll *Collection) Count(query BSON) (int64, os.Error) { cmd := &_Object{map[string]BSON{"count": &_String{coll.name, _Null{}}, "query": query}, _Null{}}; reply, err := coll.db.Command(cmd); if err != nil { return -1, err } return int64(reply.Get("n").Number()), nil; } func (coll *Collection) update(um *updateMsg) os.Error { um.requestID = rand.Int31(); conn := coll.db.conn; return conn.writeMessage(um); } func (coll *Collection) Update(selector, document BSON) os.Error { return coll.update(&updateMsg{coll.fullName(), 0, selector, document, 0}) } func (coll *Collection) Upsert(selector, document BSON) os.Error { return coll.update(&updateMsg{coll.fullName(), 1, selector, document, 0}) } func (coll *Collection) UpdateAll(selector, document BSON) os.Error { return coll.update(&updateMsg{coll.fullName(), 2, selector, document, 0}) } func (coll *Collection) UpsertAll(selector, document BSON) os.Error { return coll.update(&updateMsg{coll.fullName(), 3, selector, document, 0}) } func (db *Database) Command(cmd BSON) (BSON, os.Error) { coll := db.GetCollection("$cmd"); return coll.FindOne(cmd); } type queryMsg struct { opts int32; fullCollectionName string; numberToSkip int32; numberToReturn int32; query BSON; requestID int32; } func (q *queryMsg) OpCode() int32 { return _OP_QUERY } func (q *queryMsg) RequestID() int32 { return q.requestID } func (q *queryMsg) Bytes() []byte { b := make([]byte, 4); binary.LittleEndian.PutUint32(b, uint32(q.opts)); buf := bytes.NewBuffer(b); buf.WriteString(q.fullCollectionName); buf.WriteByte(0); binary.LittleEndian.PutUint32(b, uint32(q.numberToSkip)); buf.Write(b); binary.LittleEndian.PutUint32(b, uint32(q.numberToReturn)); buf.Write(b); buf.Write(q.query.Bytes()); return buf.Bytes(); } type insertMsg struct { fullCollectionName string; doc BSON; requestID int32; } func (i *insertMsg) OpCode() int32 { return _OP_INSERT } func (i *insertMsg) RequestID() int32 { return i.requestID } func (i *insertMsg) Bytes() []byte { buf := bytes.NewBuffer(make([]byte, 4)); buf.WriteString(i.fullCollectionName); buf.WriteByte(0); buf.Write(i.doc.Bytes()); return buf.Bytes(); } type deleteMsg struct { fullCollectionName string; selector BSON; requestID int32; } func (d *deleteMsg) OpCode() int32 { return _OP_DELETE } func (d *deleteMsg) RequestID() int32 { return d.requestID } func (d *deleteMsg) Bytes() []byte { zero := make([]byte, 4); buf := bytes.NewBuffer(zero); buf.WriteString(d.fullCollectionName); buf.WriteByte(0); buf.Write(zero); buf.Write(d.selector.Bytes()); return buf.Bytes(); } type getMoreMsg struct { fullCollectionName string; numberToReturn int32; cursorID int64; requestID int32; } func (g *getMoreMsg) OpCode() int32 { return _OP_GET_MORE } func (g *getMoreMsg) RequestID() int32 { return g.requestID } func (g *getMoreMsg) Bytes() []byte { buf := bytes.NewBuffer(make([]byte, 4)); buf.WriteString(g.fullCollectionName); buf.WriteByte(0); b := make([]byte, 4); binary.LittleEndian.PutUint32(b, uint32(g.numberToReturn)); buf.Write(b); b = make([]byte, 8); binary.LittleEndian.PutUint64(b, uint64(g.cursorID)); buf.Write(b); return buf.Bytes(); } func (db *Database) GetCollectionNames() *vector.StringVector { return new(vector.StringVector) } type replyMsg struct { responseTo int32; responseFlag int32; cursorID int64; startingFrom int32; numberReturned int32; docs *vector.Vector; } func parseReply(b []byte) *replyMsg { r := new(replyMsg); r.responseTo = int32(binary.LittleEndian.Uint32(b[4:8])); r.responseFlag = int32(binary.LittleEndian.Uint32(b[12:16])); r.cursorID = int64(binary.LittleEndian.Uint64(b[16:24])); r.startingFrom = int32(binary.LittleEndian.Uint32(b[24:28])); r.numberReturned = int32(binary.LittleEndian.Uint32(b[28:32])); r.docs = new(vector.Vector) if r.numberReturned > 0 { buf := bytes.NewBuffer(b[36:len(b)]); for i := 0; int32(i) < r.numberReturned; i++ { var bson BSON; bb := new(_BSONBuilder); bb.ptr = &bson; bb.Object(); Parse(buf, bb); r.docs.Push(bson); ioutil.ReadAll(io.LimitReader(buf, 4)); } } return r; } type updateMsg struct { fullCollectionName string; flags int32; selector, document BSON; requestID int32; } func (u *updateMsg) OpCode() int32 { return _OP_UPDATE } func (u *updateMsg) RequestID() int32 { return u.requestID } func (u *updateMsg) Bytes() []byte { buf := bytes.NewBuffer(make([]byte, 4)); buf.WriteString(u.fullCollectionName); buf.WriteByte(0); b := make([]byte, 4); binary.LittleEndian.PutUint32(b, uint32(u.flags)); buf.Write(b); buf.Write(u.selector.Bytes()); buf.Write(u.document.Bytes()); return buf.Bytes(); } type killMsg struct { numberOfCursorIDs int32; cursorIDs []int64; requestID int32; } func (k *killMsg) OpCode() int32 { return _OP_KILL_CURSORS } func (k *killMsg) RequestID() int32 { return k.requestID } func (k *killMsg) Bytes() []byte { buf := bytes.NewBuffer(make([]byte, 4)); b := make([]byte, 4); binary.LittleEndian.PutUint32(b, uint32(k.numberOfCursorIDs)); buf.Write(b); b = make([]byte, 8); for _, id := range k.cursorIDs { binary.LittleEndian.PutUint64(b, uint64(id)); buf.Write(b); } return buf.Bytes(); }
package util import ( "log" "os" "strings" ) func Getenv(key string, def ...string) string { res := strings.TrimSpace(os.Getenv(key)) if res == "" { if len(def) == 1 { return def[0] } log.Fatalln("missing", key) } return res }
package odoo import ( "fmt" ) // AccountInvoiceRefund represents account.invoice.refund model. type AccountInvoiceRefund struct { LastUpdate *Time `xmlrpc:"__last_update,omptempty"` CreateDate *Time `xmlrpc:"create_date,omptempty"` CreateUid *Many2One `xmlrpc:"create_uid,omptempty"` Date *Time `xmlrpc:"date,omptempty"` DateInvoice *Time `xmlrpc:"date_invoice,omptempty"` Description *String `xmlrpc:"description,omptempty"` DisplayName *String `xmlrpc:"display_name,omptempty"` FilterRefund *Selection `xmlrpc:"filter_refund,omptempty"` Id *Int `xmlrpc:"id,omptempty"` RefundOnly *Bool `xmlrpc:"refund_only,omptempty"` WriteDate *Time `xmlrpc:"write_date,omptempty"` WriteUid *Many2One `xmlrpc:"write_uid,omptempty"` } // AccountInvoiceRefunds represents array of account.invoice.refund model. type AccountInvoiceRefunds []AccountInvoiceRefund // AccountInvoiceRefundModel is the odoo model name. const AccountInvoiceRefundModel = "account.invoice.refund" // Many2One convert AccountInvoiceRefund to *Many2One. func (air *AccountInvoiceRefund) Many2One() *Many2One { return NewMany2One(air.Id.Get(), "") } // CreateAccountInvoiceRefund creates a new account.invoice.refund model and returns its id. func (c *Client) CreateAccountInvoiceRefund(air *AccountInvoiceRefund) (int64, error) { ids, err := c.CreateAccountInvoiceRefunds([]*AccountInvoiceRefund{air}) if err != nil { return -1, err } if len(ids) == 0 { return -1, nil } return ids[0], nil } // CreateAccountInvoiceRefund creates a new account.invoice.refund model and returns its id. func (c *Client) CreateAccountInvoiceRefunds(airs []*AccountInvoiceRefund) ([]int64, error) { var vv []interface{} for _, v := range airs { vv = append(vv, v) } return c.Create(AccountInvoiceRefundModel, vv) } // UpdateAccountInvoiceRefund updates an existing account.invoice.refund record. func (c *Client) UpdateAccountInvoiceRefund(air *AccountInvoiceRefund) error { return c.UpdateAccountInvoiceRefunds([]int64{air.Id.Get()}, air) } // UpdateAccountInvoiceRefunds updates existing account.invoice.refund records. // All records (represented by ids) will be updated by air values. func (c *Client) UpdateAccountInvoiceRefunds(ids []int64, air *AccountInvoiceRefund) error { return c.Update(AccountInvoiceRefundModel, ids, air) } // DeleteAccountInvoiceRefund deletes an existing account.invoice.refund record. func (c *Client) DeleteAccountInvoiceRefund(id int64) error { return c.DeleteAccountInvoiceRefunds([]int64{id}) } // DeleteAccountInvoiceRefunds deletes existing account.invoice.refund records. func (c *Client) DeleteAccountInvoiceRefunds(ids []int64) error { return c.Delete(AccountInvoiceRefundModel, ids) } // GetAccountInvoiceRefund gets account.invoice.refund existing record. func (c *Client) GetAccountInvoiceRefund(id int64) (*AccountInvoiceRefund, error) { airs, err := c.GetAccountInvoiceRefunds([]int64{id}) if err != nil { return nil, err } if airs != nil && len(*airs) > 0 { return &((*airs)[0]), nil } return nil, fmt.Errorf("id %v of account.invoice.refund not found", id) } // GetAccountInvoiceRefunds gets account.invoice.refund existing records. func (c *Client) GetAccountInvoiceRefunds(ids []int64) (*AccountInvoiceRefunds, error) { airs := &AccountInvoiceRefunds{} if err := c.Read(AccountInvoiceRefundModel, ids, nil, airs); err != nil { return nil, err } return airs, nil } // FindAccountInvoiceRefund finds account.invoice.refund record by querying it with criteria. func (c *Client) FindAccountInvoiceRefund(criteria *Criteria) (*AccountInvoiceRefund, error) { airs := &AccountInvoiceRefunds{} if err := c.SearchRead(AccountInvoiceRefundModel, criteria, NewOptions().Limit(1), airs); err != nil { return nil, err } if airs != nil && len(*airs) > 0 { return &((*airs)[0]), nil } return nil, fmt.Errorf("account.invoice.refund was not found with criteria %v", criteria) } // FindAccountInvoiceRefunds finds account.invoice.refund records by querying it // and filtering it with criteria and options. func (c *Client) FindAccountInvoiceRefunds(criteria *Criteria, options *Options) (*AccountInvoiceRefunds, error) { airs := &AccountInvoiceRefunds{} if err := c.SearchRead(AccountInvoiceRefundModel, criteria, options, airs); err != nil { return nil, err } return airs, nil } // FindAccountInvoiceRefundIds finds records ids by querying it // and filtering it with criteria and options. func (c *Client) FindAccountInvoiceRefundIds(criteria *Criteria, options *Options) ([]int64, error) { ids, err := c.Search(AccountInvoiceRefundModel, criteria, options) if err != nil { return []int64{}, err } return ids, nil } // FindAccountInvoiceRefundId finds record id by querying it with criteria. func (c *Client) FindAccountInvoiceRefundId(criteria *Criteria, options *Options) (int64, error) { ids, err := c.Search(AccountInvoiceRefundModel, criteria, options) if err != nil { return -1, err } if len(ids) > 0 { return ids[0], nil } return -1, fmt.Errorf("account.invoice.refund was not found with criteria %v and options %v", criteria, options) }
package iterators import ( "io" ) // Iterator define a separate object that encapsulates accessing and traversing an aggregate object. // Clients use an iterator to access and traverse an aggregate without knowing its representation (data structures). // Interface design inspirited by https://golang.org/pkg/encoding/json/#Decoder // https://en.wikipedia.org/wiki/Iterator_pattern type Iterator[V any] interface { // Closer is required to make it able to cancel iterators where resources are being used behind the scene // for all other cases where the underling io is handled on a higher level, it should simply return nil io.Closer // Err return the error cause. Err() error // Next will ensure that Value returns the next item when executed. // If the next value is not retrievable, Next should return false and ensure Err() will return the error cause. Next() bool // Value returns the current value in the iterator. // The action should be repeatable without side effects. Value() V }
package datastore import ( "errors" "github.com/jelmerdereus/gowebtemplate/models" "github.com/jinzhu/gorm" ) // UserStore is an ORM layer that satisfies the UserRepo interface type UserStore struct { DBORM } // NewUserRepo is a constructor func NewUserRepo(orm *DBORM) (UserRepo, error) { if orm == nil { return nil, errors.New("No ORM provided") } orm.AutoMigrate(&models.User{}) store := UserStore{} store.DB = orm.DB return &store, nil } // GetAllUsers returns a list of User objects func (store *UserStore) GetAllUsers() (users []models.User, err error) { return users, store.Find(&users).Error } //GetUserByAlias returns the User object of the user with the given alias func (store *UserStore) GetUserByAlias(alias string) (user models.User, err error) { return user, store.First(&user, &models.User{Alias: alias}).Error } //GetUserByID returns the User object of the user with the given ID func (store *UserStore) GetUserByID(id int) (user models.User, err error) { return user, store.First(&user, &models.User{Model: gorm.Model{ID: uint(id)}}).Error } // AddUser adds a User object to the database and returns the user func (store *UserStore) AddUser(newUser models.User) (models.User, error) { return newUser, store.Create(&newUser).Error } // UpdateUser updates a User object and returns it func (store *UserStore) UpdateUser(user *models.User) error { return store.Save(user).Error } // DeleteUser deletes a User object and returns the object with DeletedAt timestamp func (store *UserStore) DeleteUser(user models.User) error { return store.Delete(&user).Error }
/* Copyright 2021-2023 ICS-FORTH. 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 debug import ( "fmt" "path" "path/filepath" "runtime" ) func GetCallerInfo(skip int) (fileName, funcName string, line int) { programCounter, file, line, ok := runtime.Caller(skip) if !ok { return } fileName = path.Base(file) funcName = runtime.FuncForPC(programCounter).Name() return } func GetCallerLine() string { fileName, funcName, line := GetCallerInfo(3) _ = fileName return fmt.Sprintf("%s:%d", filepath.Base(funcName), line) }
package messagequeue import ( "encoding/json" _ "github.com/jinzhu/gorm/dialects/mysql" "github.com/streadway/amqp" "log" "math/rand" "rabbitmqdemoProject/model" "time" ) func failError(err error, msg string) { if err != nil { log.Fatalf("%s: %s", msg, err) } } //func OpenCreater() { //router := gin.Default() //router.POST("/order", func(c *gin.Context) { // userid:= c.Query("userid") // goodid := c.Query("goodid") // shopid := c.Query("shopid") // number := c.Query("number") // Order(userid,shopid,goodid,number) // go model.C(userid,shopid,goodid,number) // c.JSON(http.StatusOK, gin.H{ // "status": gin.H{ // "status_code": http.StatusOK, // "status": "ok", // }, // "user-id": userid, // "good-id": goodid, // "shop-id": shopid, // "number": number, // }) //}) // //router.Run() //} //conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/") //failError(err, "Can't connect to MQ") //defer conn.Close() //amqpChannel, err := conn.Channel() //failError(err, "Can't create a Channel") //defer amqpChannel.Close() //queue, err := amqpChannel.QueueDeclare("goodList", true, false, false, // false, nil) //failError(err, "Could not declare queue") //rand.Seed(time.Now().UnixNano()) //good := Order{Userid: rand.Intn(100), Shopid:1, // Number:rand.Intn(99999), Goodid:2} //body, err := json.Marshal(good) //if err != nil { // failError(err, "Error encoding JSON") //} //err = amqpChannel.Publish("", queue.Name, false, false, amqp.Publishing{ // DeliveryMode: amqp.Persistent, // ContentType: "text/plain", // Body: body, //}) //if err != nil { // log.Fatalf("Error publishing message: %s", err) //} //log.Printf("AddGood: %s", string(body)) //} func Order(userid string,shopid string,goodid string,number string){ conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/") failError(err, "Can't connect to MQ") defer conn.Close() amqpChannel, err := conn.Channel() failError(err, "Can't create a Channel") defer amqpChannel.Close() queue, err := amqpChannel.QueueDeclare("goodList", true, false, false, false, nil) failError(err, "Could not declare queue") rand.Seed(time.Now().UnixNano()) good := model.Order{Userid:userid , Shopid:shopid, Number:number, Goodid:goodid} body, err := json.Marshal(good) if err != nil { failError(err, "Error encoding JSON") } err = amqpChannel.Publish("", queue.Name, false, false, amqp.Publishing{ DeliveryMode: amqp.Persistent, ContentType: "text/plain", Body: body, }) if err != nil { log.Fatalf("Error publishing message: %s", err) } log.Printf("AddGood: %s", string(body)) }
package main import ( "flag" "fmt" "io/ioutil" "net/url" "os" "os/exec" "path/filepath" "regexp" "strings" ) var ( // Finds markdown links of the form [foo](bar "alt-text"). linkRE = regexp.MustCompile(`\[([^]]*)\]\(([^)]*)\)`) // Splits the link target into link target and alt-text. altTextRE = regexp.MustCompile(`(.*)( ".*")`) version = flag.String("version", "", "A version tag to process docs. (e.g. 1.0).") remote = flag.String("remote", "upstream", "The name of the remote repo from which to pull docs.") ) func fixURL(u *url.URL) (modified bool) { if u.Host != "" { return } if strings.HasSuffix(u.Path, ".md") { u.Path = u.Path[:len(u.Path)-3] + ".html" modified = true } if strings.HasSuffix(u.Path, "/") { u.Path = u.Path + "README.html" modified = true } return } func processFile(filename string) error { fileBytes, err := ioutil.ReadFile(filename) if err != nil { return err } output := linkRE.ReplaceAllFunc(fileBytes, func(in []byte) (out []byte) { match := linkRE.FindSubmatch(in) visibleText := string(match[1]) linkText := string(match[2]) altText := "" if parts := altTextRE.FindStringSubmatch(linkText); parts != nil { linkText = parts[1] altText = parts[2] } u, err := url.Parse(linkText) if err != nil { return in } if !fixURL(u) { return in } return []byte(fmt.Sprintf("[%s](%s)", visibleText, u.String()+altText)) }) f, err := os.Create(filename) if err != nil { return err } _, err = f.WriteString("---\nlayout: docwithnav\n---\n") if err != nil { return err } _, err = f.Write(output) return err } func copyFiles(remoteRepo, directory, releaseTag string) error { prefix := fmt.Sprintf("--prefix=%s", directory) tagRef := fmt.Sprintf("%s/%s", remoteRepo, releaseTag) gitCmd := exec.Command("git", "archive", "--format=tar", prefix, tagRef, "docs", "examples") tarCmd := exec.Command("tar", "-x") var err error tarCmd.Stdin, err = gitCmd.StdoutPipe() if err != nil { return err } fmt.Printf("Copying docs and examples from %s to %s\n", tagRef, directory) if err = tarCmd.Start(); err != nil { return err } if err = gitCmd.Run(); err != nil { return err } return tarCmd.Wait() } func main() { flag.Parse() if len(*version) == 0 { fmt.Println("You must specify a version with --version.") os.Exit(1) } if err := checkCWD(); err != nil { fmt.Printf("Could not find the kubernetes root: %v\n", err) os.Exit(1) } dir := fmt.Sprintf("v%s/", *version) releaseTag := fmt.Sprintf("release-%s", *version) if err := copyFiles(*remote, dir, releaseTag); err != nil { fmt.Printf("Error copying files: %v\n", err) os.Exit(1) } err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() && strings.HasSuffix(info.Name(), ".md") { fmt.Printf("Processing %s\n", path) return processFile(path) } return nil }) if err != nil { fmt.Printf("Error while processing markdown files: %v\n", err) os.Exit(1) } } func checkCWD() error { dir, err := exec.Command("git", "rev-parse", "--show-toplevel").Output() if err != nil { return err } return os.Chdir(strings.TrimSpace(string(dir))) }
package main import "gorm.io/gorm" // 与另一个模型建立一对一的关联,但它和一对一关系有些许不同。 这种关联表明一个模型的每个实例都包含或拥有另一个模型的一个实例。 // 跟belongsto不同,模型之间并没有从属关系,同时关联不能为0 // User 有一张 CreditCard,UserID 是外键 type User struct { gorm.Model CreditCard CreditCard } type CreditCard struct { gorm.Model Number string UserID uint }
package codec import ( "io" "github.com/coinexchain/codon" ) func ShowInfo() { codon.ShowInfoForVar(nil, RangeProof{}) codon.ShowInfoForVar(nil, IAVLAbsenceOp{}) codon.ShowInfoForVar(nil, IAVLValueOp{}) } var TypeEntryList = []codon.TypeEntry{ {Alias: "RangeProof", Value: RangeProof{}}, {Alias: "ProofInnerNode", Value: ProofInnerNode{}}, {Alias: "ProofLeafNode", Value: ProofLeafNode{}}, {Alias: "PathToLeaf", Value: PathToLeaf{}}, {Alias: "IAVLAbsenceOp", Value: IAVLAbsenceOp{}}, {Alias: "IAVLValueOp", Value: IAVLValueOp{}}, } func GenerateCodecFile(w io.Writer) { codon.GenerateCodecFile(w, nil, nil, TypeEntryList, codon.BridgeLogic, codon.ImportsForBridgeLogic) } const MaxSliceLength = 10 const MaxStringLength = 100
package runtime import ( "net/http" xmpp "github.com/mattn/go-xmpp" ) type HookHandler func(*xmpp.Client, []Hook) func(http.ResponseWriter, *http.Request) var HookRegister map[string]HookHandler func init() { HookRegister = make(map[string]HookHandler) }
// 本题为考试单行多行输入输出规范示例,无需提交,不计分。 package main import ( "fmt" ) func main() { //test a := 0 b := 0 c := 0 fmt.Scan(&a, &b, &c) fmt.Printf("%d\n", a+b) fmt.Printf("c=%d\n", c) }
package tcpip import "testing" import "encoding/binary" import "bytes" func TestEthHdrDecode(t *testing.T) { skb := alloc_skb(BUFLEN) dmac := []byte{1, 1, 1, 1, 1, 1} smac := []byte{2, 2, 2, 2, 2, 2} copy(skb.data[0:6], dmac) copy(skb.data[6:12], smac) binary.BigEndian.PutUint16(skb.data[12:14], ETH_P_ARP) hdr := eth_hdr_decode(skb) if !bytes.Equal(dmac, hdr.dmac) { t.Error("dmac wrong") } if !bytes.Equal(smac, hdr.smac) { t.Error("smac wrong") } if hdr.ethertype != ETH_P_ARP { t.Error("wrong ethertype") } }
package p_00401_00500 // 415. Add Strings, https://leetcode.com/problems/add-strings/ import ( "strconv" "strings" ) func addStrings(num1 string, num2 string) string { i := len(num1) - 1 j := len(num2) - 1 cnt := 0 var res []int n := 0 for i >= 0 || j >= 0 { sum := 0 sum += n if i >= 0 { sum += int(num1[i] - '0') } if j >= 0 { sum += int(num2[j] - '0') } res = append(res, sum%10) n = sum / 10 i-- j-- cnt++ } if n > 0 { res = append(res, n) } var b strings.Builder for i := len(res) - 1; i >= 0; i-- { b.WriteString(strconv.Itoa(res[i])) } return b.String() }
package cron import ( "os" "fmt" "io" "time" ) var defaultFormat = func(Values ...interface{}) string { var formattedArgs []interface{} for _, arg := range Values { if t, ok := arg.(time.Time); ok { arg = t.Format("2006-01-02 15:04:05") } formattedArgs = append(formattedArgs, arg," ") } return fmt.Sprint(formattedArgs...) } // DefaultLogger 默认Logger var DefaultLogger Logger = PrintfLogger(os.Stdout,defaultFormat) // LogFormatter log格式化func type LogFormatter func(Values ...interface{}) string // PrintLogger ... type PrintLogger struct { out io.Writer Format LogFormatter } func PrintfLogger(o io.Writer,f LogFormatter) Logger { return PrintLogger{o, f} } func (l PrintLogger) Info(values ...interface{}) { fmt.Fprintln(l.out,"[Cron]",l.Format(values...)) } func (l PrintLogger) Error(err error,values ...interface{}) { fmt.Fprintln(l.out,"[Error]",err, l.Format(values...)) } // Logger is Log interface type Logger interface { Info(values ...interface{}) Error(err error,value ...interface{}) }
package main import( "fmt" "math" ) func main(){ num := 600851475143 //infers 64bit int sqrt := int(math.Sqrt(float64(num))) found := false var resulti int var resultk int for i := sqrt; i > 1; i--{ for k := 1; k < sqrt; k+=2{ fmt.Println(checkIfPrime(i), i,checkIfPrime(k), k) if(i*k == num){ if (checkIfPrime(i) && checkIfPrime(k)){ found = true resulti = i resultk = k } } } if(found == true){ fmt.Println(resulti, resultk) break; } } } func checkIfPrime(num int) (bool){ sqrt := int(math.Sqrt(float64(num))) prime := true for i := 1; i <= sqrt; i++{ for k:= 1; k <= sqrt; k++{ if (i*k == num){ prime = false break; } } } return prime }
package backend import ( "bytes" "context" "encoding/json" "fmt" "math/big" "strconv" "github.com/cosmos/cosmos-sdk/client/flags" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/server" authtx "github.com/cosmos/cosmos-sdk/x/auth/tx" "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/params" tmrpctypes "github.com/tendermint/tendermint/rpc/core/types" "google.golang.org/grpc" "google.golang.org/grpc/metadata" "github.com/pkg/errors" "github.com/tendermint/tendermint/libs/log" tmtypes "github.com/tendermint/tendermint/types" "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" grpctypes "github.com/cosmos/cosmos-sdk/types/grpc" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/tharsis/ethermint/rpc/ethereum/namespaces/eth/filters" "github.com/tharsis/ethermint/rpc/ethereum/types" "github.com/tharsis/ethermint/server/config" ethermint "github.com/tharsis/ethermint/types" evmtypes "github.com/tharsis/ethermint/x/evm/types" feemarkettypes "github.com/tharsis/ethermint/x/feemarket/types" ) // Backend implements the functionality shared within namespaces. // Implemented by EVMBackend. type Backend interface { // General Ethereum API RPCGasCap() uint64 // global gas cap for eth_call over rpc: DoS protection RPCTxFeeCap() float64 // RPCTxFeeCap is the global transaction fee(price * gaslimit) cap for, // send-transction variants. The unit is ether. RPCMinGasPrice() int64 SuggestGasTipCap() (*big.Int, error) // Blockchain API BlockNumber() (hexutil.Uint64, error) GetTendermintBlockByNumber(blockNum types.BlockNumber) (*tmrpctypes.ResultBlock, error) GetBlockByNumber(blockNum types.BlockNumber, fullTx bool) (map[string]interface{}, error) GetBlockByHash(hash common.Hash, fullTx bool) (map[string]interface{}, error) CurrentHeader() *ethtypes.Header HeaderByNumber(blockNum types.BlockNumber) (*ethtypes.Header, error) HeaderByHash(blockHash common.Hash) (*ethtypes.Header, error) PendingTransactions() ([]*sdk.Tx, error) GetTransactionLogs(txHash common.Hash) ([]*ethtypes.Log, error) GetTransactionCount(address common.Address, blockNum types.BlockNumber) (*hexutil.Uint64, error) SendTransaction(args evmtypes.TransactionArgs) (common.Hash, error) GetCoinbase() (sdk.AccAddress, error) GetTransactionByHash(txHash common.Hash) (*types.RPCTransaction, error) GetTxByEthHash(txHash common.Hash) (*tmrpctypes.ResultTx, error) EstimateGas(args evmtypes.TransactionArgs, blockNrOptional *types.BlockNumber) (hexutil.Uint64, error) BaseFee(height int64) (*big.Int, error) // Filter API BloomStatus() (uint64, uint64) GetLogs(hash common.Hash) ([][]*ethtypes.Log, error) GetLogsByHeight(height *int64) ([][]*ethtypes.Log, error) GetFilteredBlocks(from int64, to int64, filter [][]filters.BloomIV, filterAddresses bool) ([]int64, error) ChainConfig() *params.ChainConfig SetTxDefaults(args evmtypes.TransactionArgs) (evmtypes.TransactionArgs, error) } var _ Backend = (*EVMBackend)(nil) var bAttributeKeyEthereumBloom = []byte(evmtypes.AttributeKeyEthereumBloom) // EVMBackend implements the Backend interface type EVMBackend struct { ctx context.Context clientCtx client.Context queryClient *types.QueryClient // gRPC query client logger log.Logger chainID *big.Int cfg config.Config } // NewEVMBackend creates a new EVMBackend instance func NewEVMBackend(ctx *server.Context, logger log.Logger, clientCtx client.Context) *EVMBackend { chainID, err := ethermint.ParseChainID(clientCtx.ChainID) if err != nil { panic(err) } appConf := config.GetConfig(ctx.Viper) return &EVMBackend{ ctx: context.Background(), clientCtx: clientCtx, queryClient: types.NewQueryClient(clientCtx), logger: logger.With("module", "evm-backend"), chainID: chainID, cfg: appConf, } } // BlockNumber returns the current block number in abci app state. // Because abci app state could lag behind from tendermint latest block, it's more stable // for the client to use the latest block number in abci app state than tendermint rpc. func (e *EVMBackend) BlockNumber() (hexutil.Uint64, error) { // do any grpc query, ignore the response and use the returned block height var header metadata.MD _, err := e.queryClient.Params(e.ctx, &evmtypes.QueryParamsRequest{}, grpc.Header(&header)) if err != nil { return hexutil.Uint64(0), err } blockHeightHeader := header.Get(grpctypes.GRPCBlockHeightHeader) if headerLen := len(blockHeightHeader); headerLen != 1 { return 0, fmt.Errorf("unexpected '%s' gRPC header length; got %d, expected: %d", grpctypes.GRPCBlockHeightHeader, headerLen, 1) } height, err := strconv.ParseUint(blockHeightHeader[0], 10, 64) if err != nil { return 0, fmt.Errorf("failed to parse block height: %w", err) } return hexutil.Uint64(height), nil } // GetBlockByNumber returns the block identified by number. func (e *EVMBackend) GetBlockByNumber(blockNum types.BlockNumber, fullTx bool) (map[string]interface{}, error) { resBlock, err := e.GetTendermintBlockByNumber(blockNum) if err != nil { return nil, err } // return if requested block height is greater than the current one if resBlock == nil || resBlock.Block == nil { return nil, nil } res, err := e.EthBlockFromTendermint(resBlock.Block, fullTx) if err != nil { e.logger.Debug("EthBlockFromTendermint failed", "height", blockNum, "error", err.Error()) return nil, err } return res, nil } // GetBlockByHash returns the block identified by hash. func (e *EVMBackend) GetBlockByHash(hash common.Hash, fullTx bool) (map[string]interface{}, error) { resBlock, err := e.clientCtx.Client.BlockByHash(e.ctx, hash.Bytes()) if err != nil { e.logger.Debug("BlockByHash block not found", "hash", hash.Hex(), "error", err.Error()) return nil, err } if resBlock.Block == nil { e.logger.Debug("BlockByHash block not found", "hash", hash.Hex()) return nil, nil } return e.EthBlockFromTendermint(resBlock.Block, fullTx) } // GetTendermintBlockByNumber returns a Tendermint format block by block number func (e *EVMBackend) GetTendermintBlockByNumber(blockNum types.BlockNumber) (*tmrpctypes.ResultBlock, error) { height := blockNum.Int64() currentBlockNumber, _ := e.BlockNumber() switch blockNum { case types.EthLatestBlockNumber: if currentBlockNumber > 0 { height = int64(currentBlockNumber) } case types.EthPendingBlockNumber: if currentBlockNumber > 0 { height = int64(currentBlockNumber) } case types.EthEarliestBlockNumber: height = 1 default: if blockNum < 0 { return nil, errors.Errorf("cannot fetch a negative block height: %d", height) } if height > int64(currentBlockNumber) { return nil, nil } } resBlock, err := e.clientCtx.Client.Block(e.ctx, &height) if err != nil { if resBlock, err = e.clientCtx.Client.Block(e.ctx, nil); err != nil { e.logger.Debug("tendermint client failed to get latest block", "height", height, "error", err.Error()) return nil, nil } } if resBlock.Block == nil { e.logger.Debug("GetBlockByNumber block not found", "height", height) return nil, nil } return resBlock, nil } // BlockBloom query block bloom filter from block results func (e *EVMBackend) BlockBloom(height *int64) (ethtypes.Bloom, error) { result, err := e.clientCtx.Client.BlockResults(e.ctx, height) if err != nil { return ethtypes.Bloom{}, err } for _, event := range result.EndBlockEvents { if event.Type != evmtypes.EventTypeBlockBloom { continue } for _, attr := range event.Attributes { if bytes.Equal(attr.Key, bAttributeKeyEthereumBloom) { return ethtypes.BytesToBloom(attr.Value), nil } } } return ethtypes.Bloom{}, errors.New("block bloom event is not found") } // EthBlockFromTendermint returns a JSON-RPC compatible Ethereum block from a given Tendermint block and its block result. func (e *EVMBackend) EthBlockFromTendermint( block *tmtypes.Block, fullTx bool, ) (map[string]interface{}, error) { ethRPCTxs := []interface{}{} ctx := types.ContextWithHeight(block.Height) baseFee, err := e.BaseFee(block.Height) if err != nil { return nil, err } for i, txBz := range block.Txs { tx, err := e.clientCtx.TxConfig.TxDecoder()(txBz) if err != nil { e.logger.Debug("failed to decode transaction in block", "height", block.Height, "error", err.Error()) continue } for _, msg := range tx.GetMsgs() { ethMsg, ok := msg.(*evmtypes.MsgEthereumTx) if !ok { continue } tx := ethMsg.AsTransaction() if !fullTx { hash := tx.Hash() ethRPCTxs = append(ethRPCTxs, hash) continue } rpcTx, err := types.NewRPCTransaction( tx, common.BytesToHash(block.Hash()), uint64(block.Height), uint64(i), baseFee, ) if err != nil { e.logger.Debug("NewTransactionFromData for receipt failed", "hash", tx.Hash().Hex(), "error", err.Error()) continue } ethRPCTxs = append(ethRPCTxs, rpcTx) } } bloom, err := e.BlockBloom(&block.Height) if err != nil { e.logger.Debug("failed to query BlockBloom", "height", block.Height, "error", err.Error()) } req := &evmtypes.QueryValidatorAccountRequest{ ConsAddress: sdk.ConsAddress(block.Header.ProposerAddress).String(), } res, err := e.queryClient.ValidatorAccount(ctx, req) if err != nil { e.logger.Debug( "failed to query validator operator address", "height", block.Height, "cons-address", req.ConsAddress, "error", err.Error(), ) return nil, err } addr, err := sdk.AccAddressFromBech32(res.AccountAddress) if err != nil { return nil, err } validatorAddr := common.BytesToAddress(addr) gasLimit, err := types.BlockMaxGasFromConsensusParams(ctx, e.clientCtx) if err != nil { e.logger.Error("failed to query consensus params", "error", err.Error()) } resBlockResult, err := e.clientCtx.Client.BlockResults(e.ctx, &block.Height) if err != nil { e.logger.Debug("EthBlockFromTendermint block result not found", "height", block.Height, "error", err.Error()) return nil, err } gasUsed := uint64(0) for _, txsResult := range resBlockResult.TxsResults { gasUsed += uint64(txsResult.GetGasUsed()) } formattedBlock := types.FormatBlock( block.Header, block.Size(), gasLimit, new(big.Int).SetUint64(gasUsed), ethRPCTxs, bloom, validatorAddr, baseFee, ) return formattedBlock, nil } // CurrentHeader returns the latest block header func (e *EVMBackend) CurrentHeader() *ethtypes.Header { header, _ := e.HeaderByNumber(types.EthLatestBlockNumber) return header } // HeaderByNumber returns the block header identified by height. func (e *EVMBackend) HeaderByNumber(blockNum types.BlockNumber) (*ethtypes.Header, error) { height := blockNum.Int64() currentBlockNumber, _ := e.BlockNumber() switch blockNum { case types.EthLatestBlockNumber: if currentBlockNumber > 0 { height = int64(currentBlockNumber) } case types.EthPendingBlockNumber: if currentBlockNumber > 0 { height = int64(currentBlockNumber) } case types.EthEarliestBlockNumber: height = 1 default: if blockNum < 0 { return nil, errors.Errorf("incorrect block height: %d", height) } } resBlock, err := e.clientCtx.Client.Block(e.ctx, &height) if err != nil { e.logger.Debug("HeaderByNumber failed") return nil, err } bloom, err := e.BlockBloom(&resBlock.Block.Height) if err != nil { e.logger.Debug("HeaderByNumber BlockBloom failed", "height", resBlock.Block.Height) } baseFee, err := e.BaseFee(resBlock.Block.Height) if err != nil { e.logger.Debug("HeaderByNumber BaseFee failed", "height", resBlock.Block.Height, "error", err.Error()) return nil, err } ethHeader := types.EthHeaderFromTendermint(resBlock.Block.Header, baseFee) ethHeader.Bloom = bloom return ethHeader, nil } // HeaderByHash returns the block header identified by hash. func (e *EVMBackend) HeaderByHash(blockHash common.Hash) (*ethtypes.Header, error) { resBlock, err := e.clientCtx.Client.BlockByHash(e.ctx, blockHash.Bytes()) if err != nil { e.logger.Debug("HeaderByHash failed", "hash", blockHash.Hex()) return nil, err } if resBlock.Block == nil { return nil, errors.Errorf("block not found for hash %s", blockHash.Hex()) } bloom, err := e.BlockBloom(&resBlock.Block.Height) if err != nil { e.logger.Debug("HeaderByHash BlockBloom failed", "height", resBlock.Block.Height) } baseFee, err := e.BaseFee(resBlock.Block.Height) if err != nil { e.logger.Debug("HeaderByHash BaseFee failed", "height", resBlock.Block.Height, "error", err.Error()) return nil, err } ethHeader := types.EthHeaderFromTendermint(resBlock.Block.Header, baseFee) ethHeader.Bloom = bloom return ethHeader, nil } // GetTransactionLogs returns the logs given a transaction hash. // It returns an error if there's an encoding error. // If no logs are found for the tx hash, the error is nil. func (e *EVMBackend) GetTransactionLogs(txHash common.Hash) ([]*ethtypes.Log, error) { tx, err := e.GetTxByEthHash(txHash) if err != nil { return nil, err } return TxLogsFromEvents(tx.TxResult.Events) } // PendingTransactions returns the transactions that are in the transaction pool // and have a from address that is one of the accounts this node manages. func (e *EVMBackend) PendingTransactions() ([]*sdk.Tx, error) { res, err := e.clientCtx.Client.UnconfirmedTxs(e.ctx, nil) if err != nil { return nil, err } result := make([]*sdk.Tx, 0, len(res.Txs)) for _, txBz := range res.Txs { tx, err := e.clientCtx.TxConfig.TxDecoder()(txBz) if err != nil { return nil, err } result = append(result, &tx) } return result, nil } // GetLogsByHeight returns all the logs from all the ethereum transactions in a block. func (e *EVMBackend) GetLogsByHeight(height *int64) ([][]*ethtypes.Log, error) { // NOTE: we query the state in case the tx result logs are not persisted after an upgrade. blockRes, err := e.clientCtx.Client.BlockResults(e.ctx, height) if err != nil { return nil, err } blockLogs := [][]*ethtypes.Log{} for _, txResult := range blockRes.TxsResults { logs, err := TxLogsFromEvents(txResult.Events) if err != nil { return nil, err } blockLogs = append(blockLogs, logs) } return blockLogs, nil } // GetLogs returns all the logs from all the ethereum transactions in a block. func (e *EVMBackend) GetLogs(hash common.Hash) ([][]*ethtypes.Log, error) { block, err := e.clientCtx.Client.BlockByHash(e.ctx, hash.Bytes()) if err != nil { return nil, err } return e.GetLogsByHeight(&block.Block.Header.Height) } func (e *EVMBackend) GetLogsByNumber(blockNum types.BlockNumber) ([][]*ethtypes.Log, error) { height := blockNum.Int64() currentBlockNumber, _ := e.BlockNumber() switch blockNum { case types.EthLatestBlockNumber: if currentBlockNumber > 0 { height = int64(currentBlockNumber) } case types.EthPendingBlockNumber: if currentBlockNumber > 0 { height = int64(currentBlockNumber) } case types.EthEarliestBlockNumber: height = 1 default: if blockNum < 0 { return nil, errors.Errorf("incorrect block height: %d", height) } } return e.GetLogsByHeight(&height) } // BloomStatus returns the BloomBitsBlocks and the number of processed sections maintained // by the chain indexer. func (e *EVMBackend) BloomStatus() (uint64, uint64) { return 4096, 0 } // GetCoinbase is the address that staking rewards will be send to (alias for Etherbase). func (e *EVMBackend) GetCoinbase() (sdk.AccAddress, error) { node, err := e.clientCtx.GetNode() if err != nil { return nil, err } status, err := node.Status(e.ctx) if err != nil { return nil, err } req := &evmtypes.QueryValidatorAccountRequest{ ConsAddress: sdk.ConsAddress(status.ValidatorInfo.Address).String(), } res, err := e.queryClient.ValidatorAccount(e.ctx, req) if err != nil { return nil, err } address, _ := sdk.AccAddressFromBech32(res.AccountAddress) return address, nil } // GetTransactionByHash returns the Ethereum format transaction identified by Ethereum transaction hash func (e *EVMBackend) GetTransactionByHash(txHash common.Hash) (*types.RPCTransaction, error) { res, err := e.GetTxByEthHash(txHash) if err != nil { // try to find tx in mempool txs, err := e.PendingTransactions() if err != nil { e.logger.Debug("tx not found", "hash", txHash.Hex(), "error", err.Error()) return nil, nil } for _, tx := range txs { msg, err := evmtypes.UnwrapEthereumMsg(tx) if err != nil { // not ethereum tx continue } if msg.Hash == txHash.Hex() { rpctx, err := types.NewTransactionFromMsg( msg, common.Hash{}, uint64(0), uint64(0), e.chainID, ) if err != nil { return nil, err } return rpctx, nil } } e.logger.Debug("tx not found", "hash", txHash.Hex()) return nil, nil } resBlock, err := e.clientCtx.Client.Block(e.ctx, &res.Height) if err != nil { e.logger.Debug("block not found", "height", res.Height, "error", err.Error()) return nil, nil } tx, err := e.clientCtx.TxConfig.TxDecoder()(res.Tx) if err != nil { e.logger.Debug("decoding failed", "error", err.Error()) return nil, fmt.Errorf("failed to decode tx: %w", err) } msg, err := evmtypes.UnwrapEthereumMsg(&tx) if err != nil { e.logger.Debug("invalid tx", "error", err.Error()) return nil, err } return types.NewTransactionFromMsg( msg, common.BytesToHash(resBlock.Block.Hash()), uint64(res.Height), uint64(res.Index), e.chainID, ) } // GetTxByEthHash uses `/tx_query` to find transaction by ethereum tx hash // TODO: Don't need to convert once hashing is fixed on Tendermint // https://github.com/tendermint/tendermint/issues/6539 func (e *EVMBackend) GetTxByEthHash(hash common.Hash) (*tmrpctypes.ResultTx, error) { query := fmt.Sprintf("%s.%s='%s'", evmtypes.TypeMsgEthereumTx, evmtypes.AttributeKeyEthereumTxHash, hash.Hex()) resTxs, err := e.clientCtx.Client.TxSearch(e.ctx, query, false, nil, nil, "") if err != nil { return nil, err } if len(resTxs.Txs) == 0 { return nil, errors.Errorf("ethereum tx not found for hash %s", hash.Hex()) } return resTxs.Txs[0], nil } func (e *EVMBackend) SendTransaction(args evmtypes.TransactionArgs) (common.Hash, error) { // Look up the wallet containing the requested signer _, err := e.clientCtx.Keyring.KeyByAddress(sdk.AccAddress(args.From.Bytes())) if err != nil { e.logger.Error("failed to find key in keyring", "address", args.From, "error", err.Error()) return common.Hash{}, fmt.Errorf("%s; %s", keystore.ErrNoMatch, err.Error()) } args, err = e.SetTxDefaults(args) if err != nil { return common.Hash{}, err } msg := args.ToTransaction() if err := msg.ValidateBasic(); err != nil { e.logger.Debug("tx failed basic validation", "error", err.Error()) return common.Hash{}, err } bn, err := e.BlockNumber() if err != nil { e.logger.Debug("failed to fetch latest block number", "error", err.Error()) return common.Hash{}, err } signer := ethtypes.MakeSigner(e.ChainConfig(), new(big.Int).SetUint64(uint64(bn))) // Sign transaction if err := msg.Sign(signer, e.clientCtx.Keyring); err != nil { e.logger.Debug("failed to sign tx", "error", err.Error()) return common.Hash{}, err } // Assemble transaction from fields builder, ok := e.clientCtx.TxConfig.NewTxBuilder().(authtx.ExtensionOptionsTxBuilder) if !ok { e.logger.Error("clientCtx.TxConfig.NewTxBuilder returns unsupported builder", "error", err.Error()) } option, err := codectypes.NewAnyWithValue(&evmtypes.ExtensionOptionsEthereumTx{}) if err != nil { e.logger.Error("codectypes.NewAnyWithValue failed to pack an obvious value", "error", err.Error()) return common.Hash{}, err } builder.SetExtensionOptions(option) if err = builder.SetMsgs(msg); err != nil { e.logger.Error("builder.SetMsgs failed", "error", err.Error()) } // Query params to use the EVM denomination res, err := e.queryClient.QueryClient.Params(e.ctx, &evmtypes.QueryParamsRequest{}) if err != nil { e.logger.Error("failed to query evm params", "error", err.Error()) return common.Hash{}, err } txData, err := evmtypes.UnpackTxData(msg.Data) if err != nil { e.logger.Error("failed to unpack tx data", "error", err.Error()) return common.Hash{}, err } fees := sdk.Coins{sdk.NewCoin(res.Params.EvmDenom, sdk.NewIntFromBigInt(txData.Fee()))} builder.SetFeeAmount(fees) builder.SetGasLimit(msg.GetGas()) // Encode transaction by default Tx encoder txEncoder := e.clientCtx.TxConfig.TxEncoder() txBytes, err := txEncoder(builder.GetTx()) if err != nil { e.logger.Error("failed to encode eth tx using default encoder", "error", err.Error()) return common.Hash{}, err } txHash := msg.AsTransaction().Hash() // Broadcast transaction in sync mode (default) // NOTE: If error is encountered on the node, the broadcast will not return an error syncCtx := e.clientCtx.WithBroadcastMode(flags.BroadcastSync) rsp, err := syncCtx.BroadcastTx(txBytes) if err != nil || rsp.Code != 0 { if err == nil { err = errors.New(rsp.RawLog) } e.logger.Error("failed to broadcast tx", "error", err.Error()) return txHash, err } // Return transaction hash return txHash, nil } // EstimateGas returns an estimate of gas usage for the given smart contract call. func (e *EVMBackend) EstimateGas(args evmtypes.TransactionArgs, blockNrOptional *types.BlockNumber) (hexutil.Uint64, error) { blockNr := types.EthPendingBlockNumber if blockNrOptional != nil { blockNr = *blockNrOptional } bz, err := json.Marshal(&args) if err != nil { return 0, err } req := evmtypes.EthCallRequest{ Args: bz, GasCap: e.RPCGasCap(), } // From ContextWithHeight: if the provided height is 0, // it will return an empty context and the gRPC query will use // the latest block height for querying. res, err := e.queryClient.EstimateGas(types.ContextWithHeight(blockNr.Int64()), &req) if err != nil { return 0, err } return hexutil.Uint64(res.Gas), nil } // GetTransactionCount returns the number of transactions at the given address up to the given block number. func (e *EVMBackend) GetTransactionCount(address common.Address, blockNum types.BlockNumber) (*hexutil.Uint64, error) { // Get nonce (sequence) from account from := sdk.AccAddress(address.Bytes()) accRet := e.clientCtx.AccountRetriever err := accRet.EnsureExists(e.clientCtx, from) if err != nil { // account doesn't exist yet, return 0 n := hexutil.Uint64(0) return &n, nil } includePending := blockNum == types.EthPendingBlockNumber nonce, err := e.getAccountNonce(address, includePending, blockNum.Int64(), e.logger) if err != nil { return nil, err } n := hexutil.Uint64(nonce) return &n, nil } // RPCGasCap is the global gas cap for eth-call variants. func (e *EVMBackend) RPCGasCap() uint64 { return e.cfg.JSONRPC.GasCap } // RPCGasCap is the global gas cap for eth-call variants. func (e *EVMBackend) RPCTxFeeCap() float64 { return e.cfg.JSONRPC.TxFeeCap } // RPCFilterCap is the limit for total number of filters that can be created func (e *EVMBackend) RPCFilterCap() int32 { return e.cfg.JSONRPC.FilterCap } // RPCMinGasPrice returns the minimum gas price for a transaction obtained from // the node config. If set value is 0, it will default to 20. func (e *EVMBackend) RPCMinGasPrice() int64 { evmParams, err := e.queryClient.Params(e.ctx, &evmtypes.QueryParamsRequest{}) if err != nil { return ethermint.DefaultGasPrice } minGasPrice := e.cfg.GetMinGasPrices() amt := minGasPrice.AmountOf(evmParams.Params.EvmDenom).TruncateInt64() if amt == 0 { return ethermint.DefaultGasPrice } return amt } // ChainConfig return the ethereum chain configuration func (e *EVMBackend) ChainConfig() *params.ChainConfig { params, err := e.queryClient.Params(e.ctx, &evmtypes.QueryParamsRequest{}) if err != nil { return nil } return params.Params.ChainConfig.EthereumConfig(e.chainID) } // SuggestGasTipCap returns the suggested tip cap func (e *EVMBackend) SuggestGasTipCap() (*big.Int, error) { out := new(big.Int).SetInt64(e.RPCMinGasPrice()) return out, nil } // BaseFee returns the base fee tracked by the Fee Market module. If the base fee is not enabled, // it returns the initial base fee amount. Return nil if London is not activated. func (e *EVMBackend) BaseFee(height int64) (*big.Int, error) { cfg := e.ChainConfig() if !cfg.IsLondon(new(big.Int).SetInt64(height)) { return nil, nil } blockRes, err := e.clientCtx.Client.BlockResults(e.ctx, &height) if err != nil { return nil, err } baseFee := types.BaseFeeFromEvents(blockRes.EndBlockEvents) if baseFee != nil { return baseFee, nil } // If we cannot find in events, we tried to get it from the state. // It will return feemarket.baseFee if london is activated but feemarket is not enable res, err := e.queryClient.FeeMarket.BaseFee(types.ContextWithHeight(height), &feemarkettypes.QueryBaseFeeRequest{}) if err == nil && res.BaseFee != nil { return res.BaseFee.BigInt(), nil } return nil, nil } // GetFilteredBlocks returns the block height list match the given bloom filters. func (e *EVMBackend) GetFilteredBlocks( from int64, to int64, filters [][]filters.BloomIV, filterAddresses bool, ) ([]int64, error) { matchedBlocks := make([]int64, 0) BLOCKS: for height := from; height <= to; height++ { if err := e.ctx.Err(); err != nil { e.logger.Error("EVMBackend context error", "err", err) return nil, err } h := height bloom, err := e.BlockBloom(&h) if err != nil { e.logger.Error("retrieve header failed", "blockHeight", height, "err", err) return nil, err } for i, filter := range filters { // filter the header bloom with the addresses if filterAddresses && i == 0 { if !checkMatches(bloom, filter) { continue BLOCKS } // the filter doesn't have any topics if len(filters) == 1 { matchedBlocks = append(matchedBlocks, height) continue BLOCKS } continue } // filter the bloom with topics if len(filter) > 0 && !checkMatches(bloom, filter) { continue BLOCKS } } matchedBlocks = append(matchedBlocks, height) } return matchedBlocks, nil } // checkMatches revised the function from // https://github.com/ethereum/go-ethereum/blob/401354976bb44f0ad4455ca1e0b5c0dc31d9a5f5/core/types/bloom9.go#L88 func checkMatches(bloom ethtypes.Bloom, filter []filters.BloomIV) bool { for _, bloomIV := range filter { if bloomIV.V[0] == bloomIV.V[0]&bloom[bloomIV.I[0]] && bloomIV.V[1] == bloomIV.V[1]&bloom[bloomIV.I[1]] && bloomIV.V[2] == bloomIV.V[2]&bloom[bloomIV.I[2]] { return true } } return false }
package tencent import ( "fmt" "strconv" "strings" ) func Code1123() { fmt.Println(isHappy(2)) } /** 编写一个算法来判断一个数是不是“快乐数”。 一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。 示例: 输入: 19 输出: true 解释: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 */ /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func isHappy(n int) bool { if n == 4 { return false } numArr := strings.Split(strconv.Itoa(n), "") resNum := 0 for _, item := range numArr { numInt, _ := strconv.Atoi(item) resNum += numInt * numInt } if resNum == 1 { return true } else { return isHappy(resNum) } }
package main import ( "fmt" "sync" parser "github.com/natsukagami/go-osu-parser" ) const concurrentExtractors = 8 func extractor(input <-chan string, success chan<- BeatmapFile, fail chan<- error, wg *sync.WaitGroup) { defer wg.Done() for file := range input { log("%s being parsed\n", file) beatmap, err := parser.ParseFile(file) if err != nil { fail <- fmt.Errorf("Cannot parse %s: %v", file, err) } else { success <- BeatmapFile{ &beatmap, file, "", } } } } func init() { wg := sync.WaitGroup{} wg.Add(concurrentExtractors) for i := 0; i < concurrentExtractors; i++ { go extractor(OsuFiles, Beatmaps, Failed, &wg) } go func() { wg.Wait() close(Beatmaps) allDone.Done() }() }
package http import ( "net/http" "github.com/vikash/gofr/pkg/gofr/logging" "github.com/vikash/gofr/pkg/gofr/http/middleware" "github.com/rs/cors" "github.com/gorilla/mux" ) type Router struct { mux.Router } func NewRouter() *Router { muxRouter := mux.NewRouter().StrictSlash(false) muxRouter.Use( middleware.Tracer, middleware.Logging(logging.NewLogger(logging.INFO)), ) cors := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, AllowOriginRequestFunc: func(r *http.Request, origin string) bool { return true }, AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"}, ExposedHeaders: []string{"Link"}, AllowCredentials: true, OptionsPassthrough: true, MaxAge: 3599, // Maximum value not ignored by any of major browsers }) muxRouter.Use(cors.Handler) return &Router{ Router: *muxRouter, } } func (rou *Router) Add(method, pattern string, handler http.Handler) { rou.Router.NewRoute().Methods(method).Path(pattern).Handler(handler) }
package main import ( "fmt" "os" ) var _redis *RedisExecutor = nil func main() { //fmt.Println("Please select table.") //repl() WriteLn("redis cli") args := os.Args[1:] Debug("main", args) e, opt, cmds := GetHostOpt(args) if e != nil { WriteLn(e) os.Exit(1) return } _redis = NewRedisExecutor(opt) if len(cmds) > 0 { option, cmds := GetCmdOpt(cmds) Debug("main", opt, option, cmds) command := &RedisCommand{ Args: cmds, Option: option, } ch := _redis.asyncExecute(command, nil) for true { resp := <-ch if resp == nil { break } if resp.Error != nil { Debug("main", resp.Error) WriteLn(resp.Error) } else { resp.Format(command.Option.FormatType, false) } ch <- nil } } else { repl() } //GetOpt(parseArg("-d 11 ee aaaaa bbb ccc 哈哈哈 欧克,asd \"aaa\\\\ bbb\"bb -f json -d 11 -r 10 -s -e -kk -es a ccccccc")) } func repl() { repl := NewREPL(_redis) err := repl.run() if err != nil { fmt.Println(err) os.Exit(-2) } }
package main type Video struct { FileID string `json:"file_id"` Width int `json:"width"` Height int `json:"height"` Duration int `json:"duration"` Thumbnail *PhotoSize `json:"thumb"` // optional MimeType string `json:"mime_type"` // optional FileSize int `json:"file_size"` // optional }
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package wpacli import ( "bytes" "context" "io" "os" "reflect" "strings" "testing" "chromiumos/tast/errors" ) func TestSudoWPACLI(t *testing.T) { testcases := []struct { input []string expect []string }{ { input: nil, expect: []string{"-u", "wpa", "-g", "wpa", "wpa_cli"}, }, { input: []string{"-i", "wlan0", "ping"}, expect: []string{"-u", "wpa", "-g", "wpa", "wpa_cli", "-i", "wlan0", "ping"}, }, } for _, tc := range testcases { result := sudoWPACLI(tc.input...) if !reflect.DeepEqual(result, tc.expect) { t.Errorf("sudoWPACLI outputs differs; got %v, want %v", result, tc.expect) } } } type cmdOutError struct { cmdOut []byte err error } type cmdRunner struct { script map[string]cmdOutError } func newCmdRunner() *cmdRunner { return &cmdRunner{script: make(map[string]cmdOutError)} } func (r *cmdRunner) Output(ctx context.Context, cmd string, args ...string) ([]byte, error) { if len(args) < 2 { return nil, errors.Errorf("insufficent #args: got %d; want >=2", len(args)) } iface := args[len(args)-2] s, ok := r.script[iface] if !ok { return nil, errors.Errorf("invalid interface %s", iface) } return s.cmdOut, s.err } func (r *cmdRunner) Run(ctx context.Context, cmd string, args ...string) error { return errors.New("shall not be called") } // CreateCmd is a mock function which does nothing. func (r *cmdRunner) CreateCmd(ctx context.Context, cmd string, args ...string) { return } // SetStdOut is a mock function which does nothing. func (r *cmdRunner) SetStdOut(stdoutFile *os.File) { return } // StderrPipe is a mock function which always returns nil. func (r *cmdRunner) StderrPipe() (io.ReadCloser, error) { return nil, errors.New("shall not be called") } // StartCmd is a mock function which always returns nil. func (r *cmdRunner) StartCmd() error { return errors.New("shall not be called") } // WaitCmd is a mock function which always returns nil. func (r *cmdRunner) WaitCmd() error { return errors.New("shall not be called") } // CmdExists is a mock function which always returns false. func (r *cmdRunner) CmdExists() bool { return false } // ReleaseProcess is a mock function which always returns nil. func (r *cmdRunner) ReleaseProcess() error { return errors.New("shall not be called") } // ResetCmd is a mock function which does nothing. func (r *cmdRunner) ResetCmd() { return } func TestPing(t *testing.T) { cr := newCmdRunner() cr.script["wlan0"] = cmdOutError{cmdOut: []byte("PONG"), err: nil} cr.script["wlan1"] = cmdOutError{cmdOut: []byte("..."), err: nil} r := NewRunner(cr) ctx := context.Background() testcases := []struct { iface string expect cmdOutError }{ { iface: "foo", expect: cmdOutError{ cmdOut: nil, err: errors.New("failed running wpa_cli"), }, }, { iface: "wlan0", expect: cmdOutError{ cmdOut: []byte("PONG"), err: nil, }, }, { iface: "wlan1", expect: cmdOutError{ cmdOut: []byte("..."), err: errors.New("failed to see 'PONG'"), }, }, } // hasPrefix returns true if err begins with expect. hasPrefix := func(err, expect error) bool { return strings.HasPrefix(err.Error(), expect.Error()) } for _, tc := range testcases { cmdOut, err := r.Ping(ctx, tc.iface) if tc.expect.cmdOut == nil { if cmdOut != nil { t.Errorf("Unexpected Ping(%s) output: got %s, want nil", tc.iface, string(cmdOut)) } } else { if !bytes.Equal(cmdOut, tc.expect.cmdOut) { t.Errorf("Unexpected Ping(%s) output: got %s, want %s", tc.iface, string(cmdOut), string(tc.expect.cmdOut)) } } if tc.expect.err == nil { if err != nil { t.Errorf("Unexpected Ping(%s) err: got %s, want nil", tc.iface, err) } } else { if !hasPrefix(err, tc.expect.err) { t.Errorf("Unexpected Ping(%s) err: got %s, want prefix %s", tc.iface, err, tc.expect.err) } } } }
package veolia import ( "fmt" "io/ioutil" "os" "strings" "testing" ) //func TestConsumption(t *testing.T) { // veolia := NewVeolia() // veolia.Username = "XXXXX" // veolia.Password = "XXXXX" // conso, err := veolia.getConsumption() // if err != nil { // t.Fatal(err) // } // for _, e := range conso { // fmt.Println(e.Day, " > ", e.Index, " > ", e.Consumption, " > ", e.Type) // } //} func TestFailedLogin(t *testing.T) { veolia := NewVeolia() veolia.Username = "XXXXX" veolia.Password = "XXXXX" _, err := veolia.getConsumption() if !strings.Contains(err.Error(), "Login failed") { t.Error(err) } } func TestReadFile(t *testing.T) { f, _ := os.Open("test/sample.xls") defer f.Close() c, _ := ioutil.ReadAll(f) conso, _ := readConsumptionXls(c) for _, e := range conso { fmt.Println(e.Day, " > ", e.Index, " > ", e.Consumption, " > ", e.Type) } }
// Copyright 2020 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package platform import ( "context" "net" "chromiumos/tast/common/testexec" "chromiumos/tast/local/bundles/cros/platform/screenlatency" "chromiumos/tast/local/input" "chromiumos/tast/testing" ) func init() { testing.AddTest(&testing.Test{ Func: ScreenLatency, Desc: "Tests latency between pressing a key and having it shown on a screen", Contacts: []string{"mblsha@google.com"}, Attr: []string{}, SoftwareDeps: []string{}, Params: []testing.Param{}, }) } // ScreenLatency uses a companion Android app to measure latency between a // key press being simulated and a character appearing on the screen. // // TODO(mblsha): See the http://go/project-slate-handover for future direction info. func ScreenLatency(ctx context.Context, s *testing.State) { keyboard, err := input.Keyboard(ctx) if err != nil { s.Fatal("Failed to create keyboard device: ", err) } ln, _ := net.Listen("tcp", "127.0.0.1:") _, serverPort, _ := net.SplitHostPort(ln.Addr().String()) testing.ContextLog(ctx, "Listening on address: ", ln.Addr()) openAppCommand := testexec.CommandContext(ctx, "adb", "shell", "am", "start", "-n", "com.android.example.camera2.slowmo/com.example.android.camera2.slowmo.CameraActivity", "--es", "port "+serverPort) if err := openAppCommand.Run(testexec.DumpLogOnError); err != nil { s.Fatal("Failed to start companion Android app using adb") } portForwardingCommand := testexec.CommandContext(ctx, "adb", "reverse", "tcp:"+serverPort, "tcp:"+serverPort) if err := portForwardingCommand.Run(testexec.DumpLogOnError); err != nil { s.Fatal("Failed to initiate TCP connection with a companion Android app") } screenlatency.CommunicateWithCompanionApp(ctx, s, ln, keyboard) }
package dto import "time" type errorRespose struct { Message string `json:"message"` Description string `json:"description"` Timestamp time.Time `json:"timestamp"` } func NewErrorResponse(msg string, desc string) errorRespose { return errorRespose{Message: msg, Description: desc, Timestamp: time.Now()} } type Respose struct { Message string `json:"message"` Description string `json:"description"` }
package main import ( "bytes" "fmt" "github.com/docopt/docopt.go" "io" "log" "os" ) func ByteToString(r io.ReadCloser) string { buf := new(bytes.Buffer) buf.ReadFrom(r) return buf.String() } func main() { arguments, err := docopt.Parse(usage, nil, true, "oclmagic v0.1", false) if err != nil { log.Fatal("Error parsing usage. Error: ", err.Error()) } hashcat := arguments["--hashcat"].(string) args := []string{ "-m=5500", `/tmp/ntlm`, "--debug-mode=4", "-a=3", `?a?a?a?a?a?a?a`, } fmt.Printf("%#v\n", hashcat) fmt.Printf("%#v\n", args) var procAttr os.ProcAttr procAttr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr} pid, err := os.StartProcess(hashcat, args, &procAttr) if err != nil { log.Fatalf("Start Failed: %v", err) } _, err = pid.Wait() }
// Copyright 2020 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. package protoreflect import ( "reflect" "strings" jsonb "github.com/cockroachdb/cockroach/pkg/util/json" "github.com/cockroachdb/cockroach/pkg/util/protoutil" "github.com/cockroachdb/errors" "github.com/gogo/protobuf/jsonpb" "github.com/gogo/protobuf/proto" ) // NewMessage creates a new protocol message object, given its fully // qualified name. func NewMessage(name string) (protoutil.Message, error) { // Get the reflected type of the protocol message. rt := proto.MessageType(name) if rt == nil { return nil, errors.Newf("unknown proto message type %s", name) } // If the message is known, we should get the pointer to our message. if rt.Kind() != reflect.Ptr { return nil, errors.AssertionFailedf( "expected ptr to message, got %s instead", rt.Kind().String()) } // Construct message of appropriate type, through reflection. rv := reflect.New(rt.Elem()) msg, ok := rv.Interface().(protoutil.Message) if !ok { // Just to be safe; return nil, errors.AssertionFailedf( "unexpected proto type for %s; expected protoutil.Message, got %T", name, rv.Interface()) } return msg, nil } // DecodeMessage decodes protocol message specified as its fully // qualified name, and it's marshaled data, into a protoutil.Message. func DecodeMessage(name string, data []byte) (protoutil.Message, error) { msg, err := NewMessage(name) if err != nil { return nil, err } // Now, parse data as our proto message. if err := protoutil.Unmarshal(data, msg); err != nil { return nil, errors.Wrapf(err, "failed to unmarshal proto %s", name) } return msg, nil } // MessageToJSON converts a protocol message into a JSONB object. The // emitDefaults flag dictates whether fields with zero values are rendered or // not. func MessageToJSON(msg protoutil.Message, emitDefaults bool) (jsonb.JSON, error) { // Convert to json. jsonEncoder := jsonpb.Marshaler{EmitDefaults: emitDefaults} msgJSON, err := jsonEncoder.MarshalToString(msg) if err != nil { return nil, errors.Wrapf(err, "marshaling %s; msg=%+v", proto.MessageName(msg), msg) } return jsonb.ParseJSON(msgJSON) } // JSONBMarshalToMessage initializes the target protocol message with // the data in the input JSONB object. // Returns serialized byte representation of the protocol message. func JSONBMarshalToMessage(input jsonb.JSON, target protoutil.Message) ([]byte, error) { json := &jsonpb.Unmarshaler{} if err := json.Unmarshal(strings.NewReader(input.String()), target); err != nil { return nil, errors.Wrapf(err, "unmarshaling json to %s", proto.MessageName(target)) } data, err := protoutil.Marshal(target) if err != nil { return nil, errors.Wrapf(err, "marshaling to proto %s", proto.MessageName(target)) } return data, nil }
package models import "database/sql" _ "github.com/mattn/go-sqlite3" type User struct { id int `json:"id"` firstName string `json:"firstName"` otherNames string `json:"otherNames"` email string `json:"email"` userName string `json:"userName"` password string `json:"password"` } type UserCollectionDetails struct { Users[]User `json:"users"` } func CreateUser(db *sql.DB, name string) (int64 error) { sql := "INSERT INTO users(firstName, otherNames, email, userName, password) VALUES(?)" Stmt, err1 := db.Prepare(sql) if err1 != nil { panic(err1) } defer.Stmt.Close() result, err2 := stmt.Exec(firstName, otherNames, email, userName, password) if err2 { panic(err2) } return result.LastInsertId() }
package prime import "math" var pList = []int{2} var pMap = map[int]bool{2: true} var latest = 2 func IsPrime(param int) bool { getPrimeUnder(param) _, exist := pMap[param] return exist } func getPrimeUnder(param int) { if param <= 2 || param < latest { return } for i := latest + 1; i <= param; i++ { _isPrime := true _threshold := int(math.Ceil(math.Sqrt(float64(i)))) for _, prime := range pList { if prime > _threshold { break } if (i % prime) == 0 { _isPrime = false break } } if _isPrime { pList = append(pList, i) pMap[i] = true } } latest = param }
/* ###################################################################### # Author: (__AUTHOR__) # Created Time: __CREATE_DATETIME__ # File Name: server.go # Description: ####################################################################### */ package main import ( "__PROJECT_NAME__/controllers" "__PROJECT_NAME__/libs/middlewares" "github.com/gin-gonic/gin" ) func NewUiServer() (r *gin.Engine, err error) { r = gin.New() r.Use(middlewares.Logger(), gin.Recovery()) r.MaxMultipartMemory = 2 << 20 // 2M site := r.Group("") { controller := controllers.NewSiteController() site.GET("/ping", controller.Ping) site.HEAD("/ping", controller.Ping) site.POST("/login", controller.Login) } return }
package exactlyonce import "github.com/payfazz/fazzkit/event/stan/message" //Opt exactly once options type Opt struct { DbName string Repository message.Repository } //NewOpt create exactly once options func NewOpt(opt Opt) *Opt { newOpt := &Opt{ DbName: opt.DbName, Repository: opt.Repository, } return newOpt }
package models type ChineseFoodSubGroup struct { GroupID string `orm:"column(GroupID);size(10)"` SubGroupID string `orm:"column(SubGroupID);size(10)"` SubGroupName string `orm:"column(SubGroupName);size(255);null"` }
package main import "fmt" type Books struct { title string author string id int } func main() { fmt.Print("hello world") arr1 := [3]int{1,2,3} fmt.Print(arr1) slice := make([]int,0,10) fmt.Print(slice) //ptr, len, cap := slice slice = append(slice, 1,2,3) fmt.Println(slice,cap(slice),len(slice)) var ip *int a := 20 ip = &a fmt.Println(*ip) b := Books{"111","1111",1} fmt.Println(b) var struct_poi *Books struct_poi = &b fmt.Println(struct_poi.author) for i, num := range slice { fmt.Println(i , num) } mapp := make(map[string]string) mapp["a"] = "A" mapp["b"] = "B" for k, v := range mapp { fmt.Println(k, v) } fmt.Println(mapp["b"]) delete(mapp,"b") fmt.Println(mapp["b"]) }
package main import ( "database/sql" "fmt" "github.com/go-sql-driver/mysql" ) // var ( // text string // ) func main() { db, _ := sql.Open("mysql", "root:mice@/mice") // defer db.Close() fmt.Println(db) // row, err := db.Exec("SHOW CREATE TABLE events") // if err != nil { // fmt.Println("err") // if _, err := row.LastInsertId(); err != nil { // fmt.Println("err") // } // } }
package legacy import ( "io" "os" "strconv" ) type ( fileServer struct { urlList FileTable } FileTable map[string]File file struct { contentType ContentType path string } File interface { ContentType() ContentType File() (*os.File, error) } ContentType string ) const ( ContentTypeHTML ContentType = "text/html; charset=UTF-8" ) func NewFile(path string, contentType ContentType) File { return &file{ path: path, contentType: contentType, } } func (f *file) ContentType() ContentType { return f.contentType } func (f *file) File() (*os.File, error) { return os.Open(f.path) } func NewFileTableServer(urlList FileTable) Handler { return &fileServer{ urlList: urlList, } } func (f *fileServer) ServeHTTP(w ResponseWriter, r *Request) { urlFile, ok := f.urlList[r.URL.Path] if !ok { NotFound(w) return } file, err := urlFile.File() if err != nil { mytoHTTPError(w, err) return } defer file.Close() d, err := file.Stat() if err != nil { mytoHTTPError(w, err) return } if d.IsDir() { NotFound(w) return } w.Header().Set("Content-Type", string(urlFile.ContentType())) w.Header().Set("Server", "DStaticServer 0.1") sendSize := d.Size() w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10)) w.WriteHeader(StatusOK) io.CopyN(w, file, sendSize) } func mytoHTTPError(w ResponseWriter, err error) { if os.IsNotExist(err) { NotFound(w) return } if os.IsPermission(err) { Forbidden(w) return } InternalServerError(w) return }
package directorywatcher import ( "os" "path/filepath" "time" "github.com/adampresley/logging" ) /* DirectoryWatcher provides a set of functions to watch for changes on a directory. It allows you to specificy a base and a function to be called when a change on an file occurs. */ type DirectoryWatcher struct { BasePath string PauseTime time.Duration Recurse bool log *logging.Logger startTime time.Time } /* FileChangedEventFunc defines the function that is called when a change event occurs */ type FileChangedEventFunc func(path string, info os.FileInfo, startTime time.Time, modificationTime time.Time) error /* NewDirectoryWatcher creates a new instance of a directory watcher. */ func NewDirectoryWatcher(basePath string, log *logging.Logger) *DirectoryWatcher { return &DirectoryWatcher{ BasePath: basePath, PauseTime: 500, Recurse: true, log: log, startTime: time.Now(), } } /* SetPauseTime determines how much time elapses (in milliseconds) between directory scans. The default is 500 milliseconds. */ func (watcher *DirectoryWatcher) SetPauseTime(pauseTime time.Duration) { watcher.PauseTime = pauseTime } /* SetRecurse determines if the watcher will recurse down subdirectories. The default is true. */ func (watcher *DirectoryWatcher) SetRecurse(recurse bool) { watcher.Recurse = recurse } /* Watch initiates a watch goroutine on the base directory. The function passed in will be called when a file is changed. */ func (watcher *DirectoryWatcher) Watch(fileChangedEvent FileChangedEventFunc) { watcher.log.Info("Listening for directory changes on", watcher.BasePath) /* * Walk the directory tree and scan for changes */ go func() { for { filepath.Walk(watcher.BasePath, func(path string, info os.FileInfo, err error) error { if !watcher.Recurse { if filepath.Dir(path) != "." { return filepath.SkipDir } } if info.ModTime().After(watcher.startTime) { result := fileChangedEvent(path, info, watcher.startTime, info.ModTime()) watcher.startTime = time.Now() return result } return nil }) time.Sleep(watcher.PauseTime * time.Millisecond) } }() }
package companyxchallenge import ( "encoding/json" "io/ioutil" "net/http" "strings" "time" ) const ( firstnameConst = "FIRSTNAME" lastnameConst = "LASTNAME" // API endpoints. Hack: hardcode FIRSTNAME and LASTNAME into the Norris // API so we can fetch a random name and get a random joke simultaneously. nameAPIEndpoint = "http://uinames.com/api/" jokeAPIEndpoint = ("http://api.icndb.com/jokes/random?firstName=" + firstnameConst + "&lastName=" + lastnameConst) // Time in seconds to timeout fetching from endpoints timeoutConst = 3 ) type nameJSON struct { Name string `json:"name"` Surname string `json:"surname"` } type jokeJSON struct { Joke string `json:"joke"` } type chuckNorrisJSON struct { Joke *jokeJSON `json:"value"` } func getName() (string, string, error) { newName := nameJSON{} client := http.Client{Timeout: time.Second * timeoutConst} response, err := client.Get(nameAPIEndpoint) if err != nil { return "", "", err } defer response.Body.Close() body, readerr := ioutil.ReadAll(response.Body) if readerr != nil { return "", "", err } json.Unmarshal(body, &newName) return newName.Name, newName.Surname, nil } func getChuckNorrisJoke() (string, error) { newJoke := chuckNorrisJSON{} client := http.Client{Timeout: time.Second * timeoutConst} response, err := client.Get(jokeAPIEndpoint) if err != nil { return "", err } defer response.Body.Close() body, readerr := ioutil.ReadAll(response.Body) if readerr != nil { return "", err } json.Unmarshal(body, &newJoke) return newJoke.Joke.Joke, nil } type nameFetchResult struct { firstName string lastName string err error } type jokeFetchResult struct { joke string err error } // Async wrapper so we can fetch name and joke at the same time func getNameAsync(ret chan nameFetchResult) { firstName, lastName, err := getName() result := nameFetchResult{firstName: firstName, lastName: lastName, err: err} ret <- result } // Async wrapper so we can fetch joke and name at the same time func getChuckNorrisJokeAsync(ret chan jokeFetchResult) { joke, err := getChuckNorrisJoke() result := jokeFetchResult{joke: joke, err: err} ret <- result } func interpolateJokeString(firstname, lastname, joke string) string { replacer := strings.NewReplacer(firstnameConst, firstname, lastnameConst, lastname) return replacer.Replace(joke) } // GetRandomJoke Fetches a random joke from the names API/CNDB func GetRandomJoke() (string, error) { // Channels to get return values back from goroutines nameGetResult := make(chan nameFetchResult) jokeGetResult := make(chan jokeFetchResult) // Spin up goroutines go getNameAsync(nameGetResult) go getChuckNorrisJokeAsync(jokeGetResult) // Wait for fetches to complete nameStruct := <-nameGetResult jokeStruct := <-jokeGetResult // Error checking if nameStruct.err != nil { return "", nameStruct.err } if jokeStruct.err != nil { return "", jokeStruct.err } interpoletedJokeString := interpolateJokeString(nameStruct.firstName, nameStruct.lastName, jokeStruct.joke) return interpoletedJokeString, nil }
/* * Copyright (c) 2016, Shinya Yagyu * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package address import ( "crypto/sha256" "errors" "fmt" "log" "github.com/bitgoin/address/base58" "github.com/bitgoin/address/btcec" "golang.org/x/crypto/ripemd160" ) var ( secp256k1 = btcec.S256() ) //Params is parameters of the coin. type Params struct { DumpedPrivateKeyHeader []byte AddressHeader []byte P2SHHeader []byte HDPrivateKeyID []byte HDPublicKeyID []byte } //PublicKey represents public key for bitcoin type PublicKey struct { *btcec.PublicKey isCompressed bool param *Params } //PrivateKey represents private key for bitcoin type PrivateKey struct { *btcec.PrivateKey PublicKey *PublicKey } //NewPublicKey returns PublicKey struct using public key hex string. func NewPublicKey(pubKeyByte []byte, param *Params) (*PublicKey, error) { key, err := btcec.ParsePubKey(pubKeyByte, secp256k1) if err != nil { return nil, err } isCompressed := false if len(pubKeyByte) == btcec.PubKeyBytesLenCompressed { isCompressed = true } return &PublicKey{ PublicKey: key, isCompressed: isCompressed, param: param, }, nil } //FromWIF gets PublicKey and PrivateKey from private key of WIF format. func FromWIF(wif string, param *Params) (*PrivateKey, error) { pb, err := base58.Decode(wif) if err != nil { return nil, err } ok := false for _, h := range param.DumpedPrivateKeyHeader { if pb[0] == h { ok = true } } if !ok { return nil, errors.New("wif is invalid") } isCompressed := false if len(pb) == btcec.PrivKeyBytesLen+2 && pb[btcec.PrivKeyBytesLen+1] == 0x01 { pb = pb[:len(pb)-1] isCompressed = true log.Println("compressed") } //Get the raw public priv, pub := btcec.PrivKeyFromBytes(secp256k1, pb[1:]) return &PrivateKey{ PrivateKey: priv, PublicKey: &PublicKey{ PublicKey: pub, isCompressed: isCompressed, param: param, }, }, nil } //NewPrivateKey creates and returns PrivateKey from bytes. func NewPrivateKey(pb []byte, param *Params) *PrivateKey { priv, pub := btcec.PrivKeyFromBytes(secp256k1, pb) return &PrivateKey{ PrivateKey: priv, PublicKey: &PublicKey{ PublicKey: pub, isCompressed: true, param: param, }, } } //Generate generates random PublicKey and PrivateKey. func Generate(param *Params) (*PrivateKey, error) { prikey, err := btcec.NewPrivateKey(secp256k1) if err != nil { return nil, err } key := &PrivateKey{ PublicKey: &PublicKey{ PublicKey: prikey.PubKey(), isCompressed: true, param: param, }, PrivateKey: prikey, } return key, nil } //Sign sign data. func (priv *PrivateKey) Sign(hash []byte) ([]byte, error) { sig, err := priv.PrivateKey.Sign(hash) if err != nil { return nil, err } return sig.Serialize(), nil } //WIFAddress returns WIF format string from PrivateKey func (priv *PrivateKey) WIFAddress() string { p := priv.Serialize() if priv.PublicKey.isCompressed { p = append(p, 0x1) } p = append(p, 0x0) copy(p[1:], p[:len(p)-1]) p[0] = priv.PublicKey.param.DumpedPrivateKeyHeader[0] return base58.Encode(p) } //Serialize serializes public key depending on isCompressed. func (pub *PublicKey) Serialize() []byte { if pub.isCompressed { return pub.SerializeCompressed() } return pub.SerializeUncompressed() } //AddressBytes returns bitcoin address bytes from PublicKey func (pub *PublicKey) AddressBytes() []byte { //Next we get a sha256 hash of the public key generated //via ECDSA, and then get a ripemd160 hash of the sha256 hash. shadPublicKeyBytes := sha256.Sum256(pub.Serialize()) ripeHash := ripemd160.New() if _, err := ripeHash.Write(shadPublicKeyBytes[:]); err != nil { log.Fatal(err) } return ripeHash.Sum(nil) } //Address returns bitcoin address from PublicKey func (pub *PublicKey) Address() string { ripeHashedBytes := pub.AddressBytes() ripeHashedBytes = append(pub.param.AddressHeader, ripeHashedBytes...) return base58.Encode(ripeHashedBytes) } //DecodeAddress converts bitcoin address to hex form. func DecodeAddress(addr string) ([]byte, error) { pb, err := base58.Decode(addr) if err != nil { return nil, err } return pb[1:], nil } //Verify verifies signature is valid or not. func (pub *PublicKey) Verify(signature []byte, data []byte) error { sig, err := btcec.ParseSignature(signature, secp256k1) if err != nil { return err } valid := sig.Verify(data, pub.PublicKey) if !valid { return fmt.Errorf("signature is invalid") } return nil } //AddressBytes returns ripeme160(sha256(redeem)) (address of redeem script). func AddressBytes(redeem []byte) []byte { h := sha256.Sum256(redeem) ripeHash := ripemd160.New() if _, err := ripeHash.Write(h[:]); err != nil { log.Fatal(err) } return ripeHash.Sum(nil) } //Address returns ripeme160(sha256(redeem)) (address of redeem script). func Address(redeem []byte, header byte) string { ripeHashedBytes := AddressBytes(redeem) ripeHashedBytes = append(ripeHashedBytes, 0x0) copy(ripeHashedBytes[1:], ripeHashedBytes[:len(ripeHashedBytes)-1]) ripeHashedBytes[0] = header return base58.Encode(ripeHashedBytes) }
// Copyright 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package netlink import ( "fmt" "gvisor.dev/gvisor/pkg/abi/linux" "gvisor.dev/gvisor/pkg/context" "gvisor.dev/gvisor/pkg/sentry/fsimpl/sockfs" "gvisor.dev/gvisor/pkg/sentry/kernel" "gvisor.dev/gvisor/pkg/sentry/socket" "gvisor.dev/gvisor/pkg/sentry/vfs" "gvisor.dev/gvisor/pkg/syserr" ) // Protocol is the implementation of a netlink socket protocol. type Protocol interface { // Protocol returns the Linux netlink protocol value. Protocol() int // CanSend returns true if this protocol may ever send messages. // // TODO(gvisor.dev/issue/1119): This is a workaround to allow // advertising support for otherwise unimplemented features on sockets // that will never send messages, thus making those features no-ops. CanSend() bool // ProcessMessage processes a single message from userspace. // // If err == nil, any messages added to ms will be sent back to the // other end of the socket. Setting ms.Multi will cause an NLMSG_DONE // message to be sent even if ms contains no messages. ProcessMessage(ctx context.Context, msg *Message, ms *MessageSet) *syserr.Error } // Provider is a function that creates a new Protocol for a specific netlink // protocol. // // Note that this is distinct from socket.Provider, which is used for all // socket families. type Provider func(t *kernel.Task) (Protocol, *syserr.Error) // protocols holds a map of all known address protocols and their provider. var protocols = make(map[int]Provider) // RegisterProvider registers the provider of a given address protocol so that // netlink sockets of that type can be created via socket(2). // // Preconditions: May only be called before any netlink sockets are created. func RegisterProvider(protocol int, provider Provider) { if p, ok := protocols[protocol]; ok { panic(fmt.Sprintf("Netlink protocol %d already provided by %+v", protocol, p)) } protocols[protocol] = provider } // socketProvider implements socket.Provider. type socketProvider struct { } // Socket implements socket.Provider.Socket. func (*socketProvider) Socket(t *kernel.Task, stype linux.SockType, protocol int) (*vfs.FileDescription, *syserr.Error) { // Netlink sockets must be specified as datagram or raw, but they // behave the same regardless of type. if stype != linux.SOCK_DGRAM && stype != linux.SOCK_RAW { return nil, syserr.ErrSocketNotSupported } provider, ok := protocols[protocol] if !ok { return nil, syserr.ErrProtocolNotSupported } p, err := provider(t) if err != nil { return nil, err } s, err := New(t, stype, p) if err != nil { return nil, err } vfsfd := &s.vfsfd mnt := t.Kernel().SocketMount() d := sockfs.NewDentry(t, mnt) defer d.DecRef(t) if err := vfsfd.Init(s, linux.O_RDWR, mnt, d, &vfs.FileDescriptionOptions{ DenyPRead: true, DenyPWrite: true, UseDentryMetadata: true, }); err != nil { return nil, syserr.FromError(err) } return vfsfd, nil } // Pair implements socket.Provider.Pair by returning an error. func (*socketProvider) Pair(*kernel.Task, linux.SockType, int) (*vfs.FileDescription, *vfs.FileDescription, *syserr.Error) { // Netlink sockets never supports creating socket pairs. return nil, nil, syserr.ErrNotSupported } // init registers the socket provider. func init() { socket.RegisterProvider(linux.AF_NETLINK, &socketProvider{}) }
package releases var NoMgoSess = "nil pointer passed from session to Mongo" var ErrReleaseNotFound = "Could not find a release for the given ID" var ErrCategoryNotFound = "Could not find releases under specified category" const ErrInsertNote = "Error inserting note: " const ErrAddNoteToRelease = "Error adding note to release: " const ErrEmptyComment = "Comment cannot be empty." const ErrFetchingNotes = "Error fetching notes: "
package vehicle import ( "time" "github.com/evcc-io/evcc/api" "github.com/evcc-io/evcc/util" "github.com/evcc-io/evcc/vehicle/volvo/connected" ) // VolvoConnected is an api.Vehicle implementation for Volvo Connected Car vehicles type VolvoConnected struct { *embed *connected.Provider } func init() { registry.Add("volvo-connected", NewVolvoConnectedFromConfig) } // NewVolvoConnectedFromConfig creates a new VolvoConnected vehicle func NewVolvoConnectedFromConfig(other map[string]interface{}) (api.Vehicle, error) { cc := struct { embed `mapstructure:",squash"` User, Password string VIN string // ClientID, ClientSecret string // Sandbox bool VccApiKey string Cache time.Duration }{ Cache: interval, } if err := util.DecodeOther(other, &cc); err != nil { return nil, err } if cc.User == "" || cc.Password == "" { return nil, api.ErrMissingCredentials } // if cc.ClientID == "" && cc.ClientSecret == "" { // return nil, errors.New("missing credentials") // } // var options []VolvoConnected.IdentityOptions // TODO Load tokens from a persistence storage and use those during startup // e.g. persistence.Load("key") // if tokens != nil { // options = append(options, VolvoConnected.WithToken(&oauth2.Token{ // AccessToken: tokens.Access, // RefreshToken: tokens.Refresh, // Expiry: tokens.Expiry, // })) // } log := util.NewLogger("volvo-cc").Redact(cc.User, cc.Password, cc.VIN, cc.VccApiKey) // identity, err := connected.NewIdentity(log, cc.ClientID, cc.ClientSecret) identity, err := connected.NewIdentity(log) if err != nil { return nil, err } ts, err := identity.Login(cc.User, cc.Password) if err != nil { return nil, err } // api := connected.NewAPI(log, identity, cc.Sandbox) api := connected.NewAPI(log, ts, cc.VccApiKey) cc.VIN, err = ensureVehicle(cc.VIN, api.Vehicles) v := &VolvoConnected{ embed: &cc.embed, Provider: connected.NewProvider(api, cc.VIN, cc.Cache), } return v, err }
package main import ( "fmt" "time" ) func main() { // 创建一个判断是否终止的channel quit := make(chan bool) fmt.Println("now:", time.Now()) // 创建周期定时器 myTicker := time.NewTicker(time.Second) // 1s i := 0 go func(){ for { nowTime := <-myTicker.C i++ fmt.Println("nowTime:", nowTime) if i == 6 { quit <- true // 解除主go程阻塞,即 <-quit fmt.Println("结束") break // return or runtime.Goexit } } }() //for{} <-quit // 子协程 循环获取<-myTicker.C 期间,一直阻塞 }
package flipper import ( "runtime" "sync" "testing" ) func TestStackEquals(t *testing.T) { s := &Stack{} s.cakes = []bool{false, false, false, false, false, false} test := []bool{false, false, false, false, false, false} if !s.Equals(test) { t.Errorf("equals failed valid %+v, %+v\n", s.cakes, test) } test[5] = true if s.Equals(test) { t.Errorf("equals failed invalid %+v, %+v\n", s.cakes, test) } if s.Equals([]bool{false, false, false, false, false}) { t.Errorf("equals failed invalid short size %+v, %+v\n", s.cakes, test) } if s.Equals([]bool{false, false, false, false, false, false, false}) { t.Errorf("equals failed invalid long size %+v, %+v\n", s.cakes, test) } s.cakes = []bool{} if !s.Equals([]bool{}) { t.Errorf("equals failed 0 length %+v, %+v\n", s.cakes, test) } for l := 0; l <= 10; l++ { s.cakes = make([]bool, l) // test a bunch of mutations... just cuz for i := 0; i < l; i++ { test = make([]bool, l) s.cakes[i] = true if s.Equals(test) { t.Errorf("equals failed. should be false %+v, %+v\n", s.cakes, test) } for j := 0; j < l; j++ { test[j] = true check := s.Equals(test) if i == j { // test should succeed iff i == j if !check { t.Errorf("equals failed. should be true %+v, %+v\n", s.cakes, test) } } else { if check { t.Errorf("equals failed. should be false %+v, %+v\n", s.cakes, test) } } } } } } func TestNewStack(t *testing.T) { s, err := NewStack("++++") if err != nil { t.Fatal(err) } if !s.Equals([]bool{true, true, true, true}) { t.Errorf("NewStack failed %+v\n", s.cakes) } s, err = NewStack("+-+-") if err != nil { t.Fatal(err) } if !s.Equals([]bool{true, false, true, false}) { t.Errorf("NewStack failed %+v\n", s.cakes) } s, err = NewStack("----") if err != nil { t.Fatal(err) } if !s.Equals([]bool{false, false, false, false}) { t.Errorf("NewStack failed %+v\n", s.cakes) } s, err = NewStack("----+") if err != nil { t.Fatal(err) } if !s.Equals([]bool{false, false, false, false, true}) { t.Errorf("NewStack failed %+v\n", s.cakes) } s, err = NewStack("----+a") if err != errInvalidString { t.Errorf("NewStack failed invalid string") } } func testStackEqualsStringCases(t *testing.T, s *Stack, cases []string) { for _, test := range cases { ok, err := s.EqualsString(test) if err != nil { t.Fatal(err) } if ok { t.Errorf("EqualsString failed: %s, %+v\n", test, s.cakes) } } } func TestStackEqualsString(t *testing.T) { s, err := NewStack("++++") if err != nil { t.Fatal(err) } test := "++++" ok, err := s.EqualsString(test) if err != nil { t.Fatal(err) } if !ok { t.Errorf("EqualsString failed: %s, %+v\n", test, s.cakes) } cases := []string{ "+++-", "----", "+-+-", "-+-+", "+---", } testStackEqualsStringCases(t, s, cases) test = "+++++" ok, err = s.EqualsString(test) if err != nil { t.Fatal(err) } if ok { t.Errorf("EqualsString failed size diff: %s, %+v\n", test, s.cakes) } s, err = NewStack("-----") if err != nil { t.Fatal(err) } cases = []string{ "++++-", "----+", "+-+-+", "-+-+-", "+----", } testStackEqualsStringCases(t, s, cases) // bad string ok, err = s.EqualsString("+-+-0") if ok || err != errInvalidString { t.Errorf("EqualsString failed invalid string\n") } } func TestFlip(t *testing.T) { s := &Stack{} s.cakes = []bool{false, true, false, true, false} count := 0 if s.Count() != count { t.Errorf("incorrect count %d, should be %d", s.Count(), count) } err := s.Flip(5) if err != nil { t.Fatal(err) } if !s.Equals([]bool{true, false, true, false, true}) { t.Errorf("Bad flip check %+v\n", s.cakes) } count = 1 if s.Count() != count { t.Errorf("incorrect count %d, should be %d", s.Count(), count) } err = s.Flip(4) if err != nil { t.Fatal(err) } if !s.Equals([]bool{true, false, true, false, true}) { t.Errorf("Bad flip check %+v\n", s.cakes) } count = 2 if s.Count() != count { t.Errorf("incorrect count %d, should be %d", s.Count(), count) } err = s.Flip(3) if err != nil { t.Fatal(err) } if !s.Equals([]bool{false, true, false, false, true}) { t.Errorf("Bad flip check %+v\n", s.cakes) } count = 3 if s.Count() != count { t.Errorf("incorrect count %d, should be %d", s.Count(), count) } err = s.Flip(2) if err != nil { t.Fatal(err) } if !s.Equals([]bool{false, true, false, false, true}) { t.Errorf("Bad flip check %+v\n", s.cakes) } count = 4 if s.Count() != count { t.Errorf("incorrect count %d, should be %d", s.Count(), count) } err = s.Flip(1) if err != nil { t.Fatal(err) } if !s.Equals([]bool{true, true, false, false, true}) { t.Errorf("Bad flip check %+v\n", s.cakes) } count = 5 if s.Count() != count { t.Errorf("incorrect count %d, should be %d", s.Count(), count) } err = s.Flip(6) if err != errFlipTooMany { t.Fatal("uncaught overflow error") } count = 5 if s.Count() != count { t.Errorf("incorrect count %d, should be %d", s.Count(), count) } } func TestIsHappy(t *testing.T) { s := &Stack{} s.cakes = []bool{false, true, false, true, false} if s.IsHappy() { t.Errorf("not a valid win condition") } s.cakes = []bool{true, true, false, true, false} if s.IsHappy() { t.Errorf("not a valid win condition") } s.cakes = []bool{true, true, true, true, false} if s.IsHappy() { t.Errorf("not a valid win condition") } s.cakes = []bool{false, false, false, false, false} if s.IsHappy() { t.Errorf("not a valid win condition") } s.cakes = []bool{true, true, true, true, true} if !s.IsHappy() { t.Errorf("valid condition not detected") } } func TestLowestFlip(t *testing.T) { s := &Stack{} s.cakes = []bool{false, true, false, true, false} n := s.LowestFlip() b := 5 if n != b { t.Errorf("%d should be %d", n, b) } s.cakes = []bool{false, false, false, false, true} n = s.LowestFlip() b = 4 if n != b { t.Errorf("%d should be %d", n, b) } s.cakes = []bool{false, true, false, true, true} n = s.LowestFlip() b = 3 if n != b { t.Errorf("%d should be %d", n, b) } s.cakes = []bool{false, false, true, true, true} n = s.LowestFlip() b = 2 if n != b { t.Errorf("%d should be %d", n, b) } s.cakes = []bool{false, true, true, true, true} n = s.LowestFlip() b = 1 if n != b { t.Errorf("%d should be %d", n, b) } s.cakes = []bool{true, true, true, true, true} n = s.LowestFlip() b = 0 if n != b { t.Errorf("%d should be %d", n, b) } } func TestPrepTop(t *testing.T) { s := &Stack{} s.cakes = []bool{false, false, false, false, false} n := s.PrepTop() b := 0 if n != b { t.Errorf("%d should be %d", n, b) } s.cakes = []bool{false, true, true, true, true} n = s.PrepTop() b = 0 if n != b { t.Errorf("%d should be %d", n, b) } s.cakes = []bool{true, false, true, true, true} n = s.PrepTop() b = 1 if n != b { t.Errorf("%d should be %d", n, b) } s.cakes = []bool{true, true, false, true, true} n = s.PrepTop() b = 2 if n != b { t.Errorf("%d should be %d", n, b) } s.cakes = []bool{true, true, true, false, true} n = s.PrepTop() b = 3 if n != b { t.Errorf("%d should be %d", n, b) } s.cakes = []bool{true, true, true, true, false} n = s.PrepTop() b = 4 if n != b { t.Errorf("%d should be %d", n, b) } s.cakes = []bool{true, true, true, true, true} n = s.PrepTop() b = 5 if n != b { t.Errorf("%d should be %d", n, b) } } func solveCase(t *testing.T, in string, sol int) { s, err := NewStack(in) if err != nil { t.Fatal(err) } flips, err := s.Solve() if err != nil { t.Fatal(err) } if flips != sol { t.Errorf("solution incorrect: %d, expected: %d\n", flips, sol) } } func TestSolve(t *testing.T) { cases := []string{ "-", "-+", "+-", "+++", "--+-", } solutions := []int{ 1, 1, 2, 0, 3, } if len(cases) != len(solutions) { t.Errorf("bad Solve cases/solutions") } for i := range cases { solveCase(t, cases[i], solutions[i]) } } func breakStuff(s *Stack, length int, cakes bool, kill chan bool) { for { copee := make([]bool, length) if cakes { for i := range copee { copee[i] = true } } if length == 4 { copee[3] = false } select { case <-kill: return default: s.cakes = copee } } } func TestSolveErrorReturnsHack(t *testing.T) { // as written, it's not possible to have Solve return an error... unless we break it using concurrency! // WARNING! This test is just a bad idea, but I wanted to play and see if it would actually // cause code coverage to show these "unreachable" errors could be covered... // Turns out it actually works. // take into account GOMAXPROCS for Travis CI. gmp := runtime.GOMAXPROCS(0) if gmp < 4 { runtime.GOMAXPROCS(4) } routines := 2 wg := &sync.WaitGroup{} s, err := NewStack("+++-") if err != nil { t.Fatal(err) } kill := make(chan bool) // break when PrepTop makes Solve fail. // when race condition triggers, PrepTop gets set by breakStuff and returns 5, which is too many. // it cannot trigger on LowestFlip, as the race version has no - for i := 0; i < routines/2; i++ { go breakStuff(s, 5, true, kill) } for i := 0; i < routines/2; i++ { go breakStuff(s, 4, true, kill) } wg.Add(1) go func() { defer func() { if r := recover(); r != nil { // if it causes a panic, we gotta try again :( TestSolveErrorReturnsHack(t) wg.Done() } }() for { _, err := s.Solve() if err == errFlipTooMany { break } } wg.Done() }() wg.Wait() for i := 0; i < routines; i++ { kill <- true } // break when LowestFlip makes Solve fail. // when race condition triggers, LowestFlip will return 5, which is too many. // cannot trigger PrepTop, as there are no + for i := 0; i < routines; i++ { go breakStuff(s, 5, false, kill) } for i := 0; i < routines/2; i++ { go breakStuff(s, 4, true, kill) } wg.Add(1) go func() { defer func() { if r := recover(); r != nil { // if it causes a panic, we gotta try again :( TestSolveErrorReturnsHack(t) wg.Done() } }() for { _, err := s.Solve() if err == errFlipTooMany { break } } wg.Done() }() wg.Wait() for i := 0; i < routines; i++ { kill <- true } }
package Best_Time_to_Buy_and_Sell_Stock import ( "github.com/stretchr/testify/assert" "testing" ) func TestBestProfit(t *testing.T) { ast := assert.New(t) case1 := []int{7, 1, 5, 3, 6, 4} ast.Equal(maxProfit(case1), 5) case2 := []int{7, 6, 4, 3, 1} ast.Equal(maxProfit(case2), 0) }
package main import "golang.org/x/sys/windows" func init() { user32 := windows.NewLazySystemDLL("user32.dll") defer func() { _ = recover() windows.FreeLibrary(windows.Handle(user32.Handle())) }() user32.NewProc("SetProcessDPIAware").Call() }
package main import ( "flag" "os" "os/signal" "syscall" "strings" "github.com/docker/go-plugins-helpers/ipam" "github.com/docker/go-plugins-helpers/network" "github.com/wrouesnel/go.log" "github.com/wrouesnel/multihttp" "github.com/wrouesnel/docker-vde-plugin/fsutil" "gopkg.in/alecthomas/kingpin.v2" "github.com/docker/go-plugins-helpers/sdk" "net/url" "runtime" ) const ( NetworkPluginName string = "vde" ) // TODO: do some checks to make sure we properly clean up func main() { dockerPluginPath := kingpin.Flag("docker-net-plugins", "Listen path for the plugin.").Default("unix:///run/docker/plugins/vde.sock,unix:///run/docker/plugins/vde-ipam.sock").String() socketRoot := kingpin.Flag("socket-root", "Path where networks and sockets should be created").Default("/run/docker-vde-plugin").String() loglevel := kingpin.Flag("log-level", "Logging Level").Default("info").String() logformat := kingpin.Flag("log-format", "If set use a syslog logger or JSON logging. Example: logger:syslog?appname=bob&local=7 or logger:stdout?json=true. Defaults to stderr.").Default("stderr").String() kingpin.Parse() exitCh := make(chan int) sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) go func() { <- sigCh exitCh <- 0 }() // Include debugging facilities to dump stack traces. sigUsr := make(chan os.Signal, 1) signal.Notify(sigUsr, syscall.SIGUSR1) go func() { for _ = range sigUsr { bufSize := 8192 for { stacktrace := make([]byte,bufSize) n := runtime.Stack(stacktrace,true) if n < bufSize { os.Stderr.Write(stacktrace) break } bufSize = bufSize * 2 } } }() // Check for the programs we need to actually work fsutil.MustLookupPaths( "ip", "vde_switch", "vde_plug2tap", "vde_plug", "dpipe", ) flag.Set("log.level", *loglevel) flag.Set("log.format", *logformat) if !fsutil.PathExists(*socketRoot) { err := os.MkdirAll(*socketRoot, os.FileMode(0777)) if err != nil { log.Panicln("socket-root does not exist.") } } else if !fsutil.PathIsDir(*socketRoot) { log.Panicln("socket-root exists but is not a directory.") } log.Infoln("VDE default socket directories:", *socketRoot) log.Infoln("Docker Plugin Path:", *dockerPluginPath) driver := NewVDENetworkDriver(*socketRoot) ipamDriver := &IPAMDriver{driver} handler := sdk.NewHandler() network.InitMux(handler, driver) ipam.InitMux(handler, ipamDriver) // For the time being we only support serving on a unix-host since cross- // host or remote support doesn't make sense. listenAddrs := []string{} for _, s := range strings.Split(*dockerPluginPath,",") { u, err := url.Parse(s) if err != nil { log.Panicln("Could not parse URL listen path:", err) } if u.Scheme != "unix" { log.Panicln("Only the \"unix\" paths are currently supported.") } listenAddrs = append(listenAddrs, u.String()) } //u, err := user.Lookup("root") //if err != nil { // log.Panicln("Error looking up user identity for plugin.") //} // //gid, err := strconv.Atoi(u.Gid) //if err != nil { // log.Panicln("Could not convert gid to integer:", u.Gid, err) //} // Handle listening on multiple addresses to work around docker 1.13 // multihost bug. listeners, err := multihttp.Listen(listenAddrs, handler) // Don't block if we were already cleaning up safely. go func() { if err != nil { log.Errorln("Failed to start listening on a given address:", err) exitCh <- 1 } }() // Wait to exit. exitCode := <- exitCh for _, l := range listeners { l.Close() } os.Exit(exitCode) }
package common import "testing" func Test_codeBlock(t *testing.T) { type args struct { header []string in [][]string } tests := []struct { name string args args want string }{ { name: "", args: args{ header: []string{"A", "B", "C"}, in: [][]string{ {"AAAA", "BBBBB", "CCCCCCC"}, {"AAAA", "BBBBB", "CCCCCCC"}, {"AAAA", "BBBBB", "CCCCCCC"}, }, }, want: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := codeBlock(tt.args.header, tt.args.in); got != tt.want { t.Errorf("codeBlock() = %v, want %v", got, tt.want) } }) } }
package main import ( "fmt" "log" "net/http" "os" "os/signal" "syscall" "github.com/CafeLucuma/go-play/plates/pkg/adding" "github.com/CafeLucuma/go-play/plates/pkg/http/rest" "github.com/CafeLucuma/go-play/plates/pkg/listing" "github.com/CafeLucuma/go-play/plates/pkg/storage/postgres" "github.com/joho/godotenv" ) func main() { //loading environment variables godotenv.Load() server := rest.NewServer() storage, err := postgres.NewStorage() if err != nil { panic(err) } defer storage.CloseDB() adding := adding.NewService(storage) listing := listing.NewService(storage) c := make(chan os.Signal) signal.Notify(c, os.Interrupt, os.Kill, syscall.SIGTERM) go func() { log.Fatal(http.ListenAndServe(":8081", server.GetHandler(adding, listing))) }() <-c fmt.Println("Canceled by the user!") }
package main /* Паттерн «Фасад», является структурным, т.е. отвечает за построение удобных в поддержке иерархий классов. Т.е. «Фасад» - это простой интерфейс для работы со сложной подсистемой, содержащей множество классов, а следовательно он определяет интерфейс более высокого уровня, который упрощает использование остальной подсистемы. Пример: есть сложная подсистема автомобиля: 1) Руль; 2) Сиденье; 3) Аудио; 4) Кондиционер. Все они являются независимыми друг от друга, но ими можно управлять в единой системе – «Автомобиле». Так, мы можем повернуть руль, включить музыку и т.д.. Следовательно, тип «Автомобиль» - это интерфейса высокого уровня, содержащий указатель на составные части всей системы (руль, сиденье и т.д.) => у него есть метод, позволяющий использовать функции составляющих его систему структур – выключить кондиционер, поднять спинку сиденья и т.д.. Такой подход позволяет использовать объект типа «Автомобиль» для доступа ко всем функциям его подсистемы. «Плюсы использования»: 1) Упрощение доступа ко всем элементам сложной подсистемы; 2) Упрощение дальнейшей поддержки структур (при изменении логики, достаточно изменить работу членов иерархии). «Минусы использования»: 1) Сложное в составлении (можно «забыть» добавить зависимость); 2) Не весь функции иерархии может быть доступен. */ import ( "facade/facade" "fmt" ) func main() { m := facade.NewCar() fmt.Println(m.Actions()) }
package events import ( "github.com/Phala-Network/go-substrate-rpc-client/v3/types" ) type ChainBridgeEvents struct { ChainBridge_FungibleTransfer []EventFungibleTransfer //nolint:stylecheck,golint ChainBridge_NonFungibleTransfer []EventNonFungibleTransfer //nolint:stylecheck,golint ChainBridge_GenericTransfer []EventGenericTransfer //nolint:stylecheck,golint ChainBridge_RelayerThresholdChanged []EventRelayerThresholdChanged //nolint:stylecheck,golint ChainBridge_ChainWhitelisted []EventChainWhitelisted //nolint:stylecheck,golint ChainBridge_RelayerAdded []EventRelayerAdded //nolint:stylecheck,golint ChainBridge_RelayerRemoved []EventRelayerRemoved //nolint:stylecheck,golint ChainBridge_VoteFor []EventVoteFor //nolint:stylecheck,golint ChainBridge_VoteAgainst []EventVoteAgainst //nolint:stylecheck,golint ChainBridge_ProposalApproved []EventProposalApproved //nolint:stylecheck,golint ChainBridge_ProposalRejected []EventProposalRejected //nolint:stylecheck,golint ChainBridge_ProposalSucceeded []EventProposalSucceeded //nolint:stylecheck,golint ChainBridge_ProposalFailed []EventProposalFailed //nolint:stylecheck,golint } type BridgeTransferEvents struct { BridgeTransfer_FeeUpdated []EventFeeUpdated //nolint:stylecheck,golint } type PhalaGateKeeperEvents struct { PhalaRegistry_GatekeeperAdded []EventGatekeeperAdded //nolint:stylecheck,golint } type PhalaMiningEvents struct { PhalaMining_CoolDownExpirationChanged []EventCoolDownExpirationChanged //nolint:stylecheck,golint PhalaMining_MinerStarted []EventMinerStarted //nolint:stylecheck,golint PhalaMining_MinerStopped []EventMinerStopped //nolint:stylecheck,golint PhalaMining_MinerReclaimed []EventMinerReclaimed //nolint:stylecheck,golint PhalaMining_MinerBound []EventMinerBound //nolint:stylecheck,golint PhalaMining_MinerUnbound []EventMinerUnbound //nolint:stylecheck,golint PhalaMining_MinerEnterUnresponsive []EventMinerEnterUnresponsive //nolint:stylecheck,golint PhalaMining_MinerExitUnresponive []EventMinerExitUnresponive //nolint:stylecheck,golint } type PhalaStakepoolEvents struct { PhalaStakePool_PoolCreated []EventPoolCreated //nolint:stylecheck,golint PhalaStakePool_PoolCommissionSet []EventPoolCommissionSet //nolint:stylecheck,golint PhalaStakePool_PoolCapacitySet []EventPoolCapacitySet //nolint:stylecheck,golint PhalaStakePool_PoolWorkerAdded []EventPoolWorkerAdded //nolint:stylecheck,golint PhalaStakePool_Contribution []EventContribution //nolint:stylecheck,golint PhalaStakePool_Withdrawal []EventWithdrawal //nolint:stylecheck,golint PhalaStakePool_RewardsWithdrawn []EventRewardsWithdrawn //nolint:stylecheck,golint } type KittiesEvents struct { KittyStorage_Created []EventKittiesCreated //nolint:stylecheck,golint KittyStorage_Transferred []EventKittiesTransferred //nolint:stylecheck,golint KittyStorage_TransferToChain []EventKittiesTransferToChain //nolint:stylecheck,golint KittyStorage_NewLottery []EventKittiesNewLottery //nolint:stylecheck,golint KittyStorage_Open []EventKittiesOpen //nolint:stylecheck,golint } // pallet chain-bridge type EventFungibleTransfer struct { Phase types.Phase Destination types.U8 DepositNonce types.U64 ResourceId types.Bytes32 Amount types.U256 Recipient types.Bytes Topics []types.Hash } type EventNonFungibleTransfer struct { Phase types.Phase Destination types.U8 DepositNonce types.U64 ResourceId types.Bytes32 TokenId types.Bytes Recipient types.Bytes Metadata types.Bytes Topics []types.Hash } type EventGenericTransfer struct { Phase types.Phase Destination types.U8 DepositNonce types.U64 ResourceId types.Bytes32 Metadata types.Bytes Topics []types.Hash } type EventRelayerThresholdChanged struct { Phase types.Phase Threshold types.U32 Topics []types.Hash } type EventChainWhitelisted struct { Phase types.Phase ChainId types.U8 Topics []types.Hash } type EventRelayerAdded struct { Phase types.Phase Relayer types.AccountID Topics []types.Hash } type EventRelayerRemoved struct { Phase types.Phase Relayer types.AccountID Topics []types.Hash } type EventVoteFor struct { Phase types.Phase SourceId types.U8 DepositNonce types.U64 Voter types.AccountID Topics []types.Hash } type EventVoteAgainst struct { Phase types.Phase SourceId types.U8 DepositNonce types.U64 Voter types.AccountID Topics []types.Hash } type EventProposalApproved struct { Phase types.Phase SourceId types.U8 DepositNonce types.U64 Topics []types.Hash } type EventProposalRejected struct { Phase types.Phase SourceId types.U8 DepositNonce types.U64 Topics []types.Hash } type EventProposalSucceeded struct { Phase types.Phase SourceId types.U8 DepositNonce types.U64 Topics []types.Hash } type EventProposalFailed struct { Phase types.Phase SourceId types.U8 DepositNonce types.U64 Topics []types.Hash } // pallet bridge-transfer type EventFeeUpdated struct { Phase types.Phase ChainID types.U8 MinFee types.U128 FeeScale types.U32 Topics []types.Hash } // pallet phala: registry type EventGatekeeperAdded struct { Phase types.Phase Worker types.Bytes Topics []types.Hash } // pallet phala: mining type EventCoolDownExpirationChanged struct { Phase types.Phase Period types.U64 Topics []types.Hash } type EventMinerStarted struct { Phase types.Phase Miner types.AccountID Topics []types.Hash } type EventMinerStopped struct { Phase types.Phase Miner types.AccountID Topics []types.Hash } type EventMinerReclaimed struct { Phase types.Phase User types.AccountID Topics []types.Hash } type EventMinerBound struct { Phase types.Phase Miner types.AccountID Worker types.Bytes Topics []types.Hash } type EventMinerUnbound struct { Phase types.Phase Miner types.AccountID Worker types.Bytes Topics []types.Hash } type EventMinerEnterUnresponsive struct { Phase types.Phase Miner types.AccountID Topics []types.Hash } type EventMinerExitUnresponive struct { Phase types.Phase Miner types.AccountID Topics []types.Hash } // pallet phala: stakepool type EventPoolCreated struct { Phase types.Phase Owner types.AccountID Pid types.U64 Topics []types.Hash } type EventPoolCommissionSet struct { Phase types.Phase Pid types.U64 Commission types.U32 Topics []types.Hash } type EventPoolCapacitySet struct { Phase types.Phase Pid types.U64 Cap types.U128 Topics []types.Hash } type EventPoolWorkerAdded struct { Phase types.Phase Pid types.U64 Worker types.Bytes Topics []types.Hash } type EventContribution struct { Phase types.Phase Pid types.U64 User types.AccountID Amount types.U128 Topics []types.Hash } type EventWithdrawal struct { Phase types.Phase Pid types.U64 User types.AccountID Amount types.U128 Topics []types.Hash } type EventRewardsWithdrawn struct { Phase types.Phase Pid types.U64 User types.AccountID Amount types.U128 Topics []types.Hash } // pallet-kitties type EventKittiesCreated struct { Phase types.Phase Arg0 types.AccountID Arg1 types.Hash Topics []types.Hash } type EventKittiesTransferred struct { Phase types.Phase Arg0 types.AccountID Arg1 types.AccountID Arg2 types.Hash Topics []types.Hash } type EventKittiesTransferToChain struct { Phase types.Phase Arg0 types.AccountID Arg1 types.Hash Arg2 types.U64 Topics []types.Hash } type EventKittiesNewLottery struct { Phase types.Phase Arg0 types.U32 Arg1 types.U32 Topics []types.Hash } type EventKittiesOpen struct { Phase types.Phase Arg0 types.U32 Arg1 types.Hash Arg2 types.Hash Topics []types.Hash } // pallet claim // DEPRECATED
package errors import ( "encoding/json" "fmt" ) type CodedError interface { error ErrorCode() Code } type Code uint32 const ( ErrorCodeGeneric Code = iota ErrorCodeUnknownAddress ErrorCodeInsufficientBalance ErrorCodeInvalidJumpDest ErrorCodeInsufficientGas ErrorCodeMemoryOutOfBounds ErrorCodeCodeOutOfBounds ErrorCodeInputOutOfBounds ErrorCodeReturnDataOutOfBounds ErrorCodeCallStackOverflow ErrorCodeCallStackUnderflow ErrorCodeDataStackOverflow ErrorCodeDataStackUnderflow ErrorCodeInvalidContract ErrorCodeNativeContractCodeCopy ErrorCodeExecutionAborted ErrorCodeExecutionReverted ErrorCodePermissionDenied ErrorCodeNativeFunction ErrorCodeEventPublish ) func (c Code) ErrorCode() Code { return c } func (c Code) Error() string { switch c { case ErrorCodeUnknownAddress: return "Unknown address" case ErrorCodeInsufficientBalance: return "Insufficient balance" case ErrorCodeInvalidJumpDest: return "Invalid jump dest" case ErrorCodeInsufficientGas: return "Insufficient gas" case ErrorCodeMemoryOutOfBounds: return "Memory out of bounds" case ErrorCodeCodeOutOfBounds: return "Code out of bounds" case ErrorCodeInputOutOfBounds: return "Input out of bounds" case ErrorCodeReturnDataOutOfBounds: return "Return data out of bounds" case ErrorCodeCallStackOverflow: return "Call stack overflow" case ErrorCodeCallStackUnderflow: return "Call stack underflow" case ErrorCodeDataStackOverflow: return "Data stack overflow" case ErrorCodeDataStackUnderflow: return "Data stack underflow" case ErrorCodeInvalidContract: return "Invalid contract" case ErrorCodeNativeContractCodeCopy: return "Tried to copy native contract code" case ErrorCodeExecutionAborted: return "Execution aborted" case ErrorCodeExecutionReverted: return "Execution reverted" case ErrorCodeNativeFunction: return "Native function error" case ErrorCodeEventPublish: return "Event publish error" case ErrorCodeGeneric: return "Generic error" default: return "Unknown error" } } func NewCodedError(errorCode Code, exception string) *Exception { if exception == "" { return nil } return &Exception{ Code: &ErrorCode{ Code: uint32(errorCode), }, Exception: exception, } } // Wraps any error as a Exception func AsCodedError(err error) *Exception { if err == nil { return nil } switch e := err.(type) { case *Exception: return e case CodedError: return NewCodedError(e.ErrorCode(), e.Error()) default: return NewCodedError(ErrorCodeGeneric, err.Error()) } } func Wrap(err CodedError, message string) *Exception { return NewCodedError(err.ErrorCode(), message+": "+err.Error()) } func Errorf(format string, a ...interface{}) CodedError { return ErrorCodef(ErrorCodeGeneric, format, a...) } func ErrorCodef(errorCode Code, format string, a ...interface{}) CodedError { return NewCodedError(errorCode, fmt.Sprintf(format, a...)) } func (e *Exception) AsError() error { // We need to return a bare untyped error here so that err == nil downstream if e == nil { return nil } return e } func (e *Exception) ErrorCode() Code { return Code(e.GetCode().Code) } func (e *Exception) Error() string { if e == nil { return "" } return fmt.Sprintf("Error %v: %s", e.Code.Code, e.Exception) } func NewErrorCode(code Code) *ErrorCode { return &ErrorCode{ Code: uint32(code), } } func (e ErrorCode) MarshalJSON() ([]byte, error) { return json.Marshal(e.Code) } func (e *ErrorCode) UnmarshalJSON(bs []byte) error { return json.Unmarshal(bs, &(e.Code)) }
package main import ( "context" "fmt" "os" "testing" "time" "github.com/4726/discussion-board/services/posts/models" pb "github.com/4726/discussion-board/services/posts/read/pb" "github.com/golang/protobuf/proto" "github.com/stretchr/testify/assert" "google.golang.org/grpc" "google.golang.org/grpc/credentials" ) var testApi *Api var testAddr string var testCFG Config func TestMain(m *testing.M) { cfg, err := ConfigFromFile("config_test.json") if err != nil { panic(err) } api, err := NewApi(cfg) if err != nil { panic(err) } testApi = api testCFG = cfg addr := fmt.Sprintf(":%v", cfg.ListenPort) testAddr = addr go api.Run(addr) time.Sleep(time.Second * 3) i := m.Run() testApi.db.Close() //close server os.Exit(i) } func testSetup(t testing.TB) (pb.PostsReadClient, []models.Post) { creds, err := credentials.NewClientTLSFromFile(testCFG.TLSCert, testCFG.TLSServerName) assert.NoError(t, err) conn, err := grpc.Dial(testAddr, grpc.WithTransportCredentials(creds)) assert.NoError(t, err) // defer conn.Close() c := pb.NewPostsReadClient(conn) cleanDB(t) posts := fillDBTestData(t) return c, posts } func TestGetFullPostNoId(t *testing.T) { c, posts := testSetup(t) req := &pb.Id{} _, err := c.GetFullPost(context.TODO(), req) assert.Error(t, err) postsAfter, commentsAfter := queryDBTest(t) assertPostsEqual(t, posts, postsAfter) assert.Len(t, commentsAfter, 2) } func TestGetFullPostDoesNotExist(t *testing.T) { c, posts := testSetup(t) req := &pb.Id{Id: proto.Uint64(5)} _, err := c.GetFullPost(context.TODO(), req) assert.Error(t, err) postsAfter, commentsAfter := queryDBTest(t) assertPostsEqual(t, posts, postsAfter) assert.Len(t, commentsAfter, 2) } func TestGetFullPost(t *testing.T) { c, posts := testSetup(t) req := &pb.Id{Id: proto.Uint64(1)} resp, err := c.GetFullPost(context.TODO(), req) assert.NoError(t, err) assertPostEqual(t, posts[0], protoPostToModelPost(resp)) postsAfter, commentsAfter := queryDBTest(t) assertPostsEqual(t, posts, postsAfter) assert.Len(t, commentsAfter, 2) } func TestGetPostsNoTotal(t *testing.T) { c, posts := testSetup(t) req := &pb.GetPostsQuery{} _, err := c.GetPosts(context.TODO(), req) assert.Error(t, err) postsAfter, commentsAfter := queryDBTest(t) assertPostsEqual(t, posts, postsAfter) assert.Len(t, commentsAfter, 2) } func TestGetPostsNoPosts(t *testing.T) { c, posts := testSetup(t) req := &pb.GetPostsQuery{Total: proto.Uint64(1), From: proto.Uint64(10)} resp, err := c.GetPosts(context.TODO(), req) assert.NoError(t, err) assert.Len(t, resp.Posts, 0) postsAfter, commentsAfter := queryDBTest(t) assertPostsEqual(t, posts, postsAfter) assert.Len(t, commentsAfter, 2) } func TestGetPostsUserNoPosts(t *testing.T) { c, posts := testSetup(t) req := &pb.GetPostsQuery{Total: proto.Uint64(1), UserId: proto.Uint64(10)} resp, err := c.GetPosts(context.TODO(), req) assert.NoError(t, err) assert.Len(t, resp.Posts, 0) postsAfter, commentsAfter := queryDBTest(t) assertPostsEqual(t, posts, postsAfter) assert.Len(t, commentsAfter, 2) } func TestGetPostsSorted(t *testing.T) { c, posts := testSetup(t) req := &pb.GetPostsQuery{Total: proto.Uint64(10), Sort: proto.String("created_at")} resp, err := c.GetPosts(context.TODO(), req) assert.NoError(t, err) expected := posts assertMiniPostsEqual(t, expected, protoPostsToModelPosts(resp.Posts)) postsAfter, comments := queryDBTest(t) assert.Len(t, posts, 3) assert.Len(t, comments, 2) assertPostsEqual(t, posts, postsAfter) } func TestGetPostsUserSorted(t *testing.T) { c, posts := testSetup(t) req := &pb.GetPostsQuery{Total: proto.Uint64(10), Sort: proto.String("created_at"), UserId: proto.Uint64(1)} resp, err := c.GetPosts(context.TODO(), req) assert.NoError(t, err) expected := []models.Post{posts[1], posts[2]} assertMiniPostsEqual(t, expected, protoPostsToModelPosts(resp.Posts)) psotsAfter, comments := queryDBTest(t) assert.Len(t, comments, 2) assertPostsEqual(t, posts, psotsAfter) } func TestGetPostsUnSorted(t *testing.T) { c, posts := testSetup(t) req := &pb.GetPostsQuery{Total: proto.Uint64(10)} resp, err := c.GetPosts(context.TODO(), req) assert.NoError(t, err) expected := []models.Post{posts[2], posts[1], posts[0]} assertMiniPostsEqual(t, expected, protoPostsToModelPosts(resp.Posts)) postsAfter, comments := queryDBTest(t) assert.Len(t, comments, 2) assertPostsEqual(t, posts, postsAfter) } func TestGetPostsUserUnSorted(t *testing.T) { c, posts := testSetup(t) req := &pb.GetPostsQuery{Total: proto.Uint64(10), UserId: proto.Uint64(1)} resp, err := c.GetPosts(context.TODO(), req) assert.NoError(t, err) expected := []models.Post{posts[2], posts[1]} assertMiniPostsEqual(t, expected, protoPostsToModelPosts(resp.Posts)) postsAfter, comments := queryDBTest(t) assert.Len(t, comments, 2) assertPostsEqual(t, posts, postsAfter) } func TestGetPostsTotal(t *testing.T) { c, posts := testSetup(t) req := &pb.GetPostsQuery{Total: proto.Uint64(2)} resp, err := c.GetPosts(context.TODO(), req) assert.NoError(t, err) expected := []models.Post{posts[2], posts[1]} assertMiniPostsEqual(t, expected, protoPostsToModelPosts(resp.Posts)) postsAfter, comments := queryDBTest(t) assert.Len(t, comments, 2) assertPostsEqual(t, posts, postsAfter) } func TestGetPostsFrom(t *testing.T) { c, posts := testSetup(t) req := &pb.GetPostsQuery{Total: proto.Uint64(2), From: proto.Uint64(1)} resp, err := c.GetPosts(context.TODO(), req) assert.NoError(t, err) expected := []models.Post{posts[1], posts[0]} assertMiniPostsEqual(t, expected, protoPostsToModelPosts(resp.Posts)) postsAfter, commentsAfter := queryDBTest(t) assertPostsEqual(t, posts, postsAfter) assert.Len(t, commentsAfter, 2) } func TestGetPostsByIdNone(t *testing.T) { c, posts := testSetup(t) req := &pb.Ids{} resp, err := c.GetPostsById(context.TODO(), req) assert.NoError(t, err) assert.Len(t, resp.Posts, 0) postsAfter, comments := queryDBTest(t) assert.Len(t, comments, 2) assertPostsEqual(t, posts, postsAfter) } func TestGetMultiplePostsDoesNotExist(t *testing.T) { c, posts := testSetup(t) req := &pb.Ids{Id: []uint64{5, 10}} resp, err := c.GetPostsById(context.TODO(), req) assert.NoError(t, err) assert.Len(t, resp.Posts, 0) postsAfter, comments := queryDBTest(t) assert.Len(t, comments, 2) assertPostsEqual(t, posts, postsAfter) } func TestGetMultiplePosts(t *testing.T) { c, posts := testSetup(t) req := &pb.Ids{Id: []uint64{2, 3}} resp, err := c.GetPostsById(context.TODO(), req) assert.NoError(t, err) expected := []models.Post{posts[1], posts[2]} assertMiniPostsEqual(t, expected, protoPostsToModelPosts(resp.Posts)) postsAfter, comments := queryDBTest(t) assert.Len(t, comments, 2) assertPostsEqual(t, posts, postsAfter) } func cleanDB(t testing.TB) { testApi.db.Exec("DELETE FROM comments;") testApi.db.Exec("DELETE FROM posts;") testApi.db.Exec("ALTER TABLE posts AUTO_INCREMENT = 1;") testApi.db.Exec("ALTER TABLE comments AUTO_INCREMENT = 1;") } func queryDBTest(t testing.TB) ([]models.Post, []models.Comment) { posts := []models.Post{} comments := []models.Comment{} assert.NoError(t, testApi.db.Preload("Comments").Find(&posts).Error) assert.NoError(t, testApi.db.Find(&comments).Error) return posts, comments } func assertPostEqual(t testing.TB, expected, actual models.Post) { assert.WithinDuration(t, expected.CreatedAt, actual.CreatedAt, time.Second) assert.WithinDuration(t, expected.UpdatedAt, actual.UpdatedAt, time.Second) assert.Equal(t, len(expected.Comments), len(actual.Comments)) for i, v := range expected.Comments { assert.WithinDuration(t, v.CreatedAt, actual.Comments[i].CreatedAt, time.Second) v.CreatedAt, actual.Comments[i].CreatedAt = time.Time{}, time.Time{} assert.Equal(t, v, actual.Comments[i]) } expected.CreatedAt, expected.UpdatedAt = time.Time{}, time.Time{} actual.CreatedAt, actual.UpdatedAt = time.Time{}, time.Time{} expected.Comments, actual.Comments = []models.Comment{}, []models.Comment{} assert.Equal(t, expected, actual) } func assertPostsEqual(t testing.TB, expected, actual []models.Post) { for i, v := range expected { assertPostEqual(t, v, actual[i]) } } func assertMiniPostEqual(t testing.TB, expected, actual models.Post) { expected.Body = "" actual.Body = "" expected.Comments = []models.Comment{} actual.Comments = []models.Comment{} assertPostEqual(t, expected, actual) } func assertMiniPostsEqual(t testing.TB, expected, actual []models.Post) { for i, v := range expected { assertMiniPostEqual(t, v, actual[i]) } } func fillDBTestData(t testing.TB) []models.Post { post := addPostForTesting(t, 2, "title", "hello world", 0) time.Sleep(time.Second) post2 := addPostForTesting(t, 1, "title2", "hello world 2", 5) time.Sleep(time.Second) comment1 := addCommentForTesting(t, 3, "my comment", 0, post2.ID) comment2 := addCommentForTesting(t, 4, "another comment", 0, post2.ID) post2.Comments = []models.Comment{comment1, comment2} post3 := addPostForTesting(t, 1, "title3", "hello world 3", 0) return []models.Post{post, post2, post3} } func addPostForTesting(t testing.TB, userID uint64, title, body string, likes int64) models.Post { created := time.Now() post := models.Post{ UserID: userID, Title: title, Body: body, Likes: likes, CreatedAt: created, UpdatedAt: created, Comments: []models.Comment{}, } err := testApi.db.Save(&post).Error assert.NoError(t, err) return post } func addCommentForTesting(t testing.TB, userID uint64, body string, likes int64, postID uint64) models.Comment { created := time.Now() comment := models.Comment{ PostID: postID, UserID: userID, Body: body, Likes: likes, CreatedAt: created, } err := testApi.db.Save(&comment).Error assert.NoError(t, err) return comment } func protoPostsToModelPosts(posts []*pb.Post) []models.Post { modelPosts := []models.Post{} for _, v := range posts { modelPosts = append(modelPosts, protoPostToModelPost(v)) } return modelPosts } func protoPostToModelPost(post *pb.Post) models.Post { modelComments := []models.Comment{} for _, v := range post.Comments { modelComment := protoCommentToModelComment(v) modelComments = append(modelComments, modelComment) } return models.Post{ ID: *post.Id, UserID: *post.UserId, Title: *post.Title, Body: *post.Body, Likes: *post.Likes, CreatedAt: time.Unix(*post.CreatedAt, 0), UpdatedAt: time.Unix(*post.UpdatedAt, 0), Comments: modelComments, } } func protoCommentToModelComment(comment *pb.Comment) models.Comment { return models.Comment{ ID: *comment.Id, PostID: *comment.PostId, ParentID: *comment.ParentId, UserID: *comment.UserId, Body: *comment.Body, CreatedAt: time.Unix(*comment.CreatedAt, 0), Likes: *comment.Likes, } }
package model import "time" // DeletionPendingReport is a collection of configurable time cutoffs that are // used to summarize installation deletion times. There is also an Overflow // value that counts installations that fall outside all provided time cutoffs. // Examples of DeletionPendingReport cutoffs: // 1. Every day for a week // 2, Every hour for a day // 3. Within 1 hour, 1 day, 1 month, 1 year type DeletionPendingReport struct { Cutoffs []*DeletionPendingTimeCutoff Overflow int } // DeletionPendingTimeCutoff is a single deletion time cutoff. type DeletionPendingTimeCutoff struct { Name string Millis int64 Count int } // NewCutoff adds a new deletion time cutoff. func (dpr *DeletionPendingReport) NewCutoff(name string, cutoffTime time.Time) { dpr.Cutoffs = append(dpr.Cutoffs, &DeletionPendingTimeCutoff{ Name: name, Millis: GetMillisAtTime(cutoffTime), }) } // Count increases the Count value of the first Cutoff that is greater than the // provided Millis. func (dpr *DeletionPendingReport) Count(millis int64) { for _, cutoff := range dpr.Cutoffs { if cutoff.Millis > millis { cutoff.Count++ return } } // The time passed in is greater than all cutoffs so add it to the overflow. dpr.Overflow++ }
// Copyright (c) 2019-present Mattermost, Inc. All Rights Reserved. // See License.txt for license information. package simplecontroller import ( "errors" "fmt" "time" "github.com/mattermost/mattermost-load-test/loadtest/user" ) type UserAction struct { run func() user.UserStatus waitAfter time.Duration } func (c *SimpleController) signUp() user.UserStatus { if c.user.Store().Id() != "" { return user.UserStatus{User: c.user, Info: "user already signed up"} } email := fmt.Sprintf("testuser%d@example.com", c.user.Id()) username := fmt.Sprintf("testuser%d", c.user.Id()) password := "testpwd" err := c.user.SignUp(email, username, password) if err != nil { return user.UserStatus{User: c.user, Err: err, Code: user.STATUS_ERROR} } return user.UserStatus{User: c.user, Info: "signed up"} } func (c *SimpleController) login() user.UserStatus { // return here if already logged in err := c.user.Login() if err != nil { return user.UserStatus{User: c.user, Err: err, Code: user.STATUS_ERROR} } err = c.user.Connect() if err != nil { return user.UserStatus{User: c.user, Err: err, Code: user.STATUS_ERROR} } return user.UserStatus{User: c.user, Info: "logged in"} } func (c *SimpleController) logout() user.UserStatus { // return here if already logged out err := c.user.Disconnect() if err != nil { return user.UserStatus{User: c.user, Err: err, Code: user.STATUS_ERROR} } ok, err := c.user.Logout() if err != nil { return user.UserStatus{User: c.user, Err: err, Code: user.STATUS_ERROR} } if !ok { return user.UserStatus{User: c.user, Err: errors.New("User did not logout"), Code: user.STATUS_ERROR} } return user.UserStatus{User: c.user, Info: "logged out"} }
// Copyright 2022 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package wmp import ( "context" "fmt" "strings" "time" "chromiumos/tast/ctxutil" "chromiumos/tast/errors" "chromiumos/tast/local/apps" "chromiumos/tast/local/arc" "chromiumos/tast/local/arc/optin" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/ash" "chromiumos/tast/local/chrome/browser" "chromiumos/tast/local/chrome/browser/browserfixt" "chromiumos/tast/local/chrome/lacros/lacrosfixt" "chromiumos/tast/local/chrome/uiauto" "chromiumos/tast/local/chrome/uiauto/event" "chromiumos/tast/local/chrome/uiauto/faillog" "chromiumos/tast/local/chrome/uiauto/mouse" "chromiumos/tast/local/chrome/uiauto/nodewith" "chromiumos/tast/local/chrome/uiauto/pointer" "chromiumos/tast/local/input" "chromiumos/tast/testing" ) func init() { testing.AddTest(&testing.Test{ Func: OverviewCloseAll, LacrosStatus: testing.LacrosVariantExists, Desc: "Checks that windows and desk can be closed", Contacts: []string{ "yzd@chromium.org", "chromeos-wmp@google.com", "cros-commercial-productivity-eng@google.com", "chromeos-sw-engprod@google.com", }, Attr: []string{"group:mainline", "informational"}, SoftwareDeps: []string{"chrome", "android_vm"}, Params: []testing.Param{{ Val: browser.TypeAsh, }, { Name: "lacros", Val: browser.TypeLacros, ExtraSoftwareDeps: []string{"lacros"}, }}, Timeout: chrome.GAIALoginTimeout + arc.BootTimeout + 120*time.Second, SearchFlags: []*testing.StringPair{{ Key: "feature_id", // Close the desk and its windows after task completion. Value: "screenplay-a8ad8d9d-ed34-48e1-a984-25570a099f75", }}, VarDeps: []string{"ui.gaiaPoolDefault"}, }) } func OverviewCloseAll(ctx context.Context, s *testing.State) { // Reserves five seconds for various cleanup. cleanupCtx := ctx ctx, cancel := ctxutil.Shorten(ctx, 5*time.Second) defer cancel() bt := s.Param().(browser.Type) cr, _, closeBrowser, err := browserfixt.SetUpWithNewChrome(ctx, bt, lacrosfixt.NewConfig(), chrome.GAIALoginPool(s.RequiredVar("ui.gaiaPoolDefault")), chrome.EnableFeatures("DesksCloseAll"), chrome.ARCSupported(), chrome.ExtraArgs(arc.DisableSyncFlags()...)) if err != nil { s.Fatal("Failed to start Chrome: ", err) } defer cr.Close(cleanupCtx) defer closeBrowser(cleanupCtx) tconn, err := cr.TestAPIConn(ctx) if err != nil { s.Fatal("Failed to create Test API connection: ", err) } cleanup, err := ash.EnsureTabletModeEnabled(ctx, tconn, false) if err != nil { s.Fatal("Failed to ensure clamshell mode: ", err) } defer cleanup(cleanupCtx) defer faillog.DumpUITreeOnError(cleanupCtx, s.OutDir(), s.HasError, tconn) ac := uiauto.New(tconn) kb, err := input.Keyboard(ctx) if err != nil { s.Fatal("Failed to create a keyboard: ", err) } defer kb.Close() pc := pointer.NewMouse(tconn) defer pc.Close() // Sets up for launching ARC apps. if err := optin.PerformAndClose(ctx, cr, tconn); err != nil { s.Fatal("Failed to optin to Play Store and Close: ", err) } // Sets up ARC. a, err := arc.New(ctx, s.OutDir()) if err != nil { s.Fatal("Failed to start ARC: ", err) } defer a.Close(cleanupCtx) if err := a.WaitIntentHelper(ctx); err != nil { s.Fatal("Failed to wait for ARC Intent Helper: ", err) } // Enters overview mode. if err := ash.SetOverviewModeAndWait(ctx, tconn, true); err != nil { s.Fatal("Failed to set overview mode: ", err) } defer ash.SetOverviewModeAndWait(cleanupCtx, tconn, false) defer ash.CleanUpDesks(cleanupCtx, tconn) newDeskButton := nodewith.ClassName("ZeroStateIconButton") desk2NameView := nodewith.ClassName("DeskNameView").Name("Desk 2") desk2Name := "BusyDesk" if err := uiauto.Combine( "create a new desk by clicking new desk button", ac.DoDefault(newDeskButton), // The focus on the new desk should be on the desk name field. ac.WaitUntilExists(desk2NameView.Focused()), kb.TypeAction(desk2Name), kb.AccelAction("Enter"), )(ctx); err != nil { s.Fatal("Failed to change the name of the second desk: ", err) } // Exits overview mode. if err := ash.SetOverviewModeAndWait(ctx, tconn, false); err != nil { s.Fatal("Failed to exit overview mode: ", err) } // If we are in lacros-chrome, then browserfixt.SetUp has already opened a // blank browser window in the first desk. In that case, we want to move the // already-existing browser window over to the second desk with a keyboard // shortcut and wait for the window to finish moving. if bt == browser.TypeLacros { if err := ash.MoveActiveWindowToAdjacentDesk(ctx, tconn, ash.WindowMovementDirectionRight); err != nil { s.Fatal("Failed to move lacros window to desk 2: ", err) } } // Activates the second desk and launch app windows on it. if err := ash.ActivateDeskAtIndex(ctx, tconn, 1); err != nil { s.Fatal("Failed to activate desk 2: ", err) } // Opens PlayStore, Chrome and Files. As mentioned above, if we are in // lacros-chrome we will already have a chrome window, so if that is the case // then we can skip opening another browser window. for _, app := range []apps.App{apps.PlayStore, apps.Chrome, apps.FilesSWA} { if bt == browser.TypeLacros && app == apps.Chrome { continue } if err := apps.Launch(ctx, tconn, app.ID); err != nil { s.Fatalf("Failed to open %s: %v", app.Name, err) } if err := ash.WaitForApp(ctx, tconn, app.ID, time.Minute); err != nil { s.Fatalf("%s did not appear in shelf after launch: %s", app.Name, err) } // Waits for the launched app window to become visible. if err := ash.WaitForCondition(ctx, tconn, func(w *ash.Window) bool { return w.IsVisible && strings.Contains(w.Title, app.Name) }, &testing.PollOptions{Timeout: 30 * time.Second}); err != nil { s.Fatalf("%v app window not visible after launching: %v", app.Name, err) } } if err := ac.WithInterval(2*time.Second).WaitUntilNoEvent(nodewith.Root(), event.LocationChanged)(ctx); err != nil { s.Fatal("Failed to wait for app launch events to be completed: ", err) } // Enters overview mode. if err := ash.SetOverviewModeAndWait(ctx, tconn, true); err != nil { s.Fatal("Failed to set overview mode: ", err) } desk2DeskMiniView := nodewith.ClassName("DeskMiniView").Name(fmt.Sprintf("Desk: %s", desk2Name)) // Gets the location of the second desk mini view. desk2DeskMiniViewLoc, err := ac.Location(ctx, desk2DeskMiniView) if err != nil { s.Fatalf("Failed to get the mini view location of desk %s: %v", desk2Name, err) } // Moves the mouse to second desk mini view and hover. if err := mouse.Move(tconn, desk2DeskMiniViewLoc.CenterPoint(), 100*time.Millisecond)(ctx); err != nil { s.Fatal("Failed to hover at the second desk mini view: ", err) } // Finds the "Close All" button. closeAllButton := nodewith.ClassName("CloseButton").Name("Close desk and windows") // Closes a desk and windows on it. if err := pc.Click(closeAllButton)(ctx); err != nil { s.Fatal("Failed to close all windows on a desk: ", err) } // There should be no visible windows at this point. wc, err := ash.CountVisibleWindows(ctx, tconn) if err != nil { s.Fatal("Failed to count visible windows: ", err) } if wc != 0 { s.Fatalf("Unexpected number of visible windows: got %v, want 0", wc) } // Exits overview mode. if err := ash.SetOverviewModeAndWait(ctx, tconn, false); err != nil { s.Fatal("Failed to exit overview mode: ", err) } // Waits for the CloseAll toast to show up and disappear. if err := uiauto.Combine( "Wait for CloseAll toast", ac.WaitUntilExists(nodewith.ClassName("ToastOverlay")), ac.WaitUntilGone(nodewith.ClassName("ToastOverlay")), )(ctx); err != nil { s.Fatal("Failed to find CloseAll toast: ", err) } // We force close windows with a posted task 1 second after the toast's // destruction starts to close them asynchronously, so the windows may still // be closing after 1 second. To account for this possible delay, we give the // windows 2 seconds to fully close in case force closing a window takes extra // time. if err := testing.Poll(ctx, func(ctx context.Context) error { // There should be 0 existing windows after one second. ws, err := ash.GetAllWindows(ctx, tconn) if err != nil { return testing.PollBreak(errors.Wrap(err, "failed to count windows")) } if len(ws) != 0 { return errors.Errorf("unexpected number of windows: got %v, want 0", len(ws)) } return nil }, &testing.PollOptions{ Timeout: 2 * time.Second, Interval: 100 * time.Millisecond, }); err != nil { s.Fatal("Did not reach expected state: ", err) } // There should be only one desk remaining. dc, err := ash.GetDeskCount(ctx, tconn) if err != nil { s.Fatal("Failed to count desks: ", err) } if dc != 1 { s.Fatalf("Unexpected number of desks: got %v, want 1", dc) } }
package usage import ( "fmt" "DA/3_stack/stack" // "DA/6_tree/tree" ) // HuffNode 节点 type HuffNode struct { Weight int Left int Right int Parent int } // HuffCode 编码 type HuffCode struct { Weight int code stack.OrderStack } // HtreeInit 树 func HtreeInit(weight []int) []HuffNode { length := len(weight) if length == 0 { return nil } htree := make([]HuffNode, length * 2 - 1) for i := 0; i < length * 2 - 1; i++ { htree[i].Left = -1 htree[i].Right = -1 htree[i].Parent = -1 if i < length { htree[i].Weight = weight[i] } else { htree[i].Weight = -1 } } for i := length; i < length * 2 - 1; i++ { p1 := 0 p2 := 0 w1 := 100 w2 := 100 for j := 0; j < i; j++ { if htree[j].Parent == -1 { if htree[j].Weight < w1 { p2 = p1 w2 = w1 p1 = j w1 = htree[j].Weight } else if htree[j].Weight < w2 { p2 = j w2 = htree[j].Weight } } } htree[i].Left = p1 htree[i].Right = p2 htree[p1].Parent = i htree[p2].Parent = i htree[i].Weight = htree[p1].Weight + htree[p2].Weight } return htree } // HtreeOutput ... func HtreeOutput(htree []HuffNode) { length := len(htree) if length == 0 { return } fmt.Println("Htree") for i := 0; i < length; i++ { fmt.Printf("%d:\tParent: %v\tLeft: %v\tRight: %v\tWeight: %v\n", i, htree[i].Parent, htree[i].Left, htree[i].Right, htree[i].Weight) } fmt.Println() } // HcodeOutput 编码 func HcodeOutput(htree []HuffNode, length int) { if length == 0 { return } hcode := make([]HuffCode, length) for i := 0; i < length; i++ { child := i parent := htree[child].Parent for parent != -1 { if htree[parent].Left == child { // 左孩子的分支是 0 hcode[i].code.Push(0) } else if htree[parent].Right == child { // 右孩子的分支是 1 hcode[i].code.Push(1) } child = parent parent = htree[child].Parent } hcode[i].Weight = htree[i].Weight } fmt.Println("hcode") for i := 0; i < length; i++ { fmt.Printf("%d:\t%v\t", i, hcode[i].Weight) for !hcode[i].code.Empty() { fmt.Printf("%v", hcode[i].code.Pop()) } fmt.Println() } } // HuffmanTest ... func HuffmanTest() { fmt.Println("HuffmanTest begin") array := []int{6, 2, 3, 9, 12, 24, 10, 8} htree := HtreeInit(array) HtreeOutput(htree) HcodeOutput(htree, len(array)) fmt.Println("HuffmanTest end") }
package main import "fmt" func init() { } func main() { test_map_a() } //定义:map 是一种特殊的数据结构:一种元素对(pair)的无序集合,pair 的一个元素是 key,对应的另一个元 //素是 value,所以这个结构也称为关联数组或字典 //声明方式:var map1 map[keytype]valuetype var map1 map[string]int //注意事项:1.未初始化的 map 的值是 nil,2.key 可以是任意可以用 == 或者 != 操作符比较的类型,比如 string、int、float。所以数组、切片和结构 //体不能作为 key,但是指针和接口类型可以。如果要用结构体作为 key 可以提供 Key() 和 Hash() 方 //法,这样可以通过结构体的域计算出唯一的数字或者字符串的 key。3.value可以是任意类型,4.map 传递给函数的代价很小:在 32 位机器上占 4 个字节,64 位机器上占 8 个字节,无论实际上存储了 //多少数据。通过 key 在 map 中寻找值是很快的,比线性查找快得多,但是仍然比从数组和切片的索引中 直接读取要慢 100 倍; func test_map_a() { var map1 map[int]string var map2 = map[string]int{"one":1,"two":12} map1 = map[int]string{1:"one", 2:"two"} fmt.Printf("the map1 key 1 is:%s\n",map1[1]) fmt.Printf("the map2 key 1 is:%d\n",map2["one"]) }
package api type Direction int const ( Bottom Direction = iota Top North South West East ) type Position struct { Vec3d Vec2f onGround bool } type Vec3d struct { x, y, z float64 } type Vec2f struct { yaw, pitch float32 } func (pos *Position) GetX() (x float64) { if pos == nil { return 0 } x = pos.x return } func (pos *Position) SetX(x float64) { if pos == nil { return } pos.x = x } func (pos *Position) GetY() (y float64) { if pos == nil { return 0 } y = pos.y return } func (pos *Position) SetY(y float64) { if pos == nil { return } pos.y = y } func (pos *Position) GetZ() (z float64) { if pos == nil { return 0 } z = pos.z return } func (pos *Position) SetZ(z float64) { if pos == nil { return } pos.z = z } func (pos *Position) GetYaw() (yaw float32) { if pos == nil { return 0 } yaw = pos.yaw return } func (pos *Position) SetYaw(yaw float32) { if pos == nil { return } pos.yaw = yaw } func (pos *Position) GetPitch() (pitch float32) { if pos == nil { return 0 } pitch = pos.pitch return } func (pos *Position) SetPitch(pitch float32) { if pos == nil { return } pos.pitch = pitch } func (pos *Position) GetOnGround() (onGround bool) { if pos == nil { return false } onGround = pos.onGround return } func (pos *Position) SetOnGround(onGround bool) { if pos == nil { return } pos.onGround = onGround }
package cache import ( "github.com/kosotd/go-microservice-skeleton/cache" "github.com/kosotd/go-microservice-skeleton/config" "gotest.tools/assert" "testing" "time" ) type testConfig struct { config config.Config } func (c *testConfig) GetBaseConfig() *config.Config { return &c.config } func init() { conf := &testConfig{} config.InitConfig(conf, func(helper config.EnvHelper) {}) conf.GetBaseConfig().CacheExpiration = "200ms" conf.GetBaseConfig().CacheUpdatePeriod = "1ms" cache.InitBigCache() } func TestBigCache(t *testing.T) { err := cache.SetData("key", []byte("value")) assert.NilError(t, err) value, ok := cache.GetData("key") assert.Equal(t, ok, true) assert.Equal(t, "value", string(value)) time.Sleep(1 * time.Second) _, ok = cache.GetData("key") assert.Equal(t, ok, false) }
package crawl import ( "bytes" "io/ioutil" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "strings" "sync" ) // A Page is a single page in a Site type Page struct { OrigURL url.URL // URL without any changes URL url.URL // Final URL Redirect *Page // Where this page redirected to OutputPath string // Absolute path of output file Fingerprint string // Hash of content after all transforms cr *crawler pending bool // If load is in-progress wg sync.WaitGroup // For waiting for load to finish } // UserAgent is the agent sent with every crawler request const UserAgent = "acrylic/crawler" func newPage(cr *crawler, u *url.URL) *Page { pg := &Page{ OrigURL: *u, URL: *u, cr: cr, } pg.pending = !pg.IsExternal() if pg.pending { pg.cr.wg.Add(1) pg.wg.Add(1) go pg.load() } return pg } func (pg *Page) setLoaded() { if pg.pending { pg.pending = false pg.wg.Done() } } func (pg *Page) waitLoaded() { // Unfortunately, this can lead to deadlock if 2+ Contents rely on each // other and haven't finished loading. It's quite complex to avoid this // (you'd need a full dependency graph since you can have long loops like "a // -> b -> c -> d -> a"), so rather than try to put something in that only // works in a few, limited cases and gives a false sense of security, let's // just consistently deadlock if it comes up. // // All things considered, this should be quite rare. pg.wg.Wait() } func (pg *Page) addError(err error) { pg.cr.addError(pg.OrigURL, err) } func (pg *Page) load() { defer pg.cr.wg.Done() defer pg.setLoaded() req := httptest.NewRequest("GET", pg.OrigURL.String(), nil) req.Header.Set("Accept", pathContentType+",*/*") req.Header.Set("User-Agent", UserAgent) rr := httptest.NewRecorder() pg.cr.handler.ServeHTTP(rr, req) err := pg.handleResp(rr) if err != nil { pg.addError(err) } } func (pg *Page) handleResp(rr *httptest.ResponseRecorder) error { resp, err := newResponse(rr) if err != nil { return err } switch resp.status { case http.StatusOK: return pg.render(resp) case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect: redirURL, err := pg.OrigURL.Parse(resp.header.Get("Location")) if err != nil { return err } pg.Redirect = pg.cr.get(redirURL) return nil default: body, _ := resp.body.get() return ResponseError{ Status: resp.status, Body: bytes.TrimSpace(body), } } } func (pg *Page) render(resp *response) error { variant := resp.header.Get(variantHeader) if variant != "" { u, err := pg.URL.Parse(variant) if err != nil { return err } pg.URL = *u } // Need to claim after any variant changes so that variant paths won't // collide if claimer, ok := pg.cr.claimPage(pg, pg.URL.Path); !ok { pg.setAliasOf(claimer) return nil } needsFingerprint := pg.cr.shouldFingerprint(pg.URL, resp.body.mediaType) if !needsFingerprint { pg.setOutputPath() } err := pg.applyTransforms(resp) if err != nil { return err } // Fingerprint after transforms so that any sub-resources with changed // fingerprints change this resource's fingerprint. if needsFingerprint { fp, err := pg.cr.fingerprints.get(resp) if err != nil { return err } pg.Fingerprint = fp pg.setOutputPath() } err = checkServeMime(pg.OutputPath, resp.body.mediaType) if err != nil { // This is just advisory, so no need to fail hard pg.addError(err) } // Need to be sure that output file and all dirs in between are safe for use err = pg.cr.claimFile(pg, pg.OutputPath) if err != nil { return err } if resp.body.canSymlink() { // Need to mark the src as used so that it doesn't get cleaned up, // leaving a broken symlink. pg.cr.setUsed(resp.body.symSrc) err := filePrepWrite(pg.OutputPath) if err != nil { return err } return os.Symlink(absPath(resp.body.symSrc), pg.OutputPath) } // If the file hasn't changed, don't write anything: this is mainly for // rsync. equal, err := fileEquals(pg.OutputPath, resp.body.b) if err != nil || equal { return err } err = filePrepWrite(pg.OutputPath) if err != nil { return err } return ioutil.WriteFile(pg.OutputPath, resp.body.b, 0666) } func (pg *Page) setAliasOf(o *Page) { o.waitLoaded() pg.OutputPath = o.OutputPath pg.Fingerprint = o.Fingerprint } func (pg *Page) setOutputPath() { outPath := pg.URL.Path // If going to a directory, need to add an index.html if strings.HasSuffix(outPath, "/") { outPath += "index.html" } if pg.Fingerprint != "" { outPath = addFingerprint(outPath, pg.Fingerprint) // A fingerprint modifies the dest path, so need to reflect that back in // the URL so that everything can be rewritten correctly pg.URL.Path = outPath } pg.OutputPath = absPath(filepath.Join(pg.cr.output, outPath)) pg.setLoaded() } func (pg *Page) applyTransforms(resp *response) error { transforms := pg.cr.transforms[resp.body.mediaType] if len(transforms) == 0 { return nil } b, err := resp.body.get() if err != nil { return err } lr := (*linkResolver)(pg) for _, transform := range transforms { b, err = transform(lr, b) if err != nil { return err } } resp.body.set(b) return nil } // IsExternal checks if this content refers to an external URL func (pg *Page) IsExternal() bool { return pg.URL.Scheme != "" || pg.URL.Opaque != "" || pg.URL.Host != "" } const maxRedirects = 25 func (pg *Page) followRedirects() (*Page, error) { curr := pg curr.waitLoaded() seen := make(map[*Page]struct{}) for curr.Redirect != nil { if _, ok := seen[curr]; ok { return nil, RedirectLoopError{ Start: pg.OrigURL.String(), End: curr.OrigURL.String(), } } seen[curr] = struct{}{} if len(seen) > maxRedirects { return nil, TooManyRedirectsError{ Start: pg.OrigURL.String(), End: curr.OrigURL.String(), } } curr = curr.Redirect curr.waitLoaded() } return curr, nil } // FollowRedirects follows every redirect to the final Page func (pg *Page) FollowRedirects() *Page { // There's no need to do any checks here as in followRedirects(): it // shouldn't be possible to access a page externally if there's an error // during Crawl(). for pg.Redirect != nil { pg = pg.Redirect } return pg }
//go:generate go-bindata -pkg tmpl -o tmpl_bindata.go -ignore '\.go' . package tmpl
package herokuapi import ( "context" "encoding/json" "flag" "fmt" "io/ioutil" "net/http" "time" "github.com/carlmjohnson/errutil" "github.com/spotlightpa/almanack/pkg/common" ) func ConfigureFlagSet(fl *flag.FlagSet) *Configurator { conf := Configurator{fl: fl} fl.StringVar(&conf.apiKey, "heroku-api-key", "", "`API key` for retrieving config from Heroku") fl.StringVar(&conf.appName, "heroku-app-name", "", "`name` for Heroku app to get config from") return &conf } type Configurator struct { fl *flag.FlagSet apiKey, appName string } const timeout = 5 * time.Second func (conf *Configurator) Request() (vals map[string]string, err error) { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() req, err := http.NewRequestWithContext( ctx, http.MethodGet, "https://api.heroku.com/apps/"+conf.appName+"/config-vars", nil, ) if err != nil { return } req.Header.Set("Authorization", "Bearer "+conf.apiKey) req.Header.Set("Accept", "application/vnd.heroku+json; version=3") resp, err := http.DefaultClient.Do(req) if err != nil { return } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("bad status from Heroku: %s", resp.Status) } b, err := ioutil.ReadAll(resp.Body) if err != nil { return } vals = make(map[string]string) if err = json.Unmarshal(b, &vals); err != nil { return nil, err } return vals, nil } func listVisitedFlagNames(fl *flag.FlagSet) map[string]bool { seen := make(map[string]bool) fl.Visit(func(f *flag.Flag) { seen[f.Name] = true }) return seen } func (conf *Configurator) Configure(l common.Logger, f2c map[string]string) error { if conf.apiKey == "" { l.Printf("no Heroku API key") return nil } seen := listVisitedFlagNames(conf.fl) unseen := []*flag.Flag{} conf.fl.VisitAll(func(ff *flag.Flag) { if !seen[ff.Name] && f2c[ff.Name] != "" { unseen = append(unseen, ff) } }) if len(unseen) == 0 { l.Printf("no missing values for Heroku to enrich") return nil } vals, err := conf.Request() if err != nil { return err } var errs errutil.Slice for _, ff := range unseen { cname := f2c[ff.Name] val := vals[cname] if val == "" { l.Printf("%s not set as %s in Heroku", ff.Name, cname) } else { l.Printf("setting %s from Heroku", ff.Name) errs.Push(conf.fl.Set(ff.Name, val)) } } return errs.Merge() }
package utils import "strconv" func ToInt64(s string) (int64, error) { n, err := strconv.ParseInt(s, 10, 64) return n, err } func MustToInt64(s string) int64 { n, err := ToInt64(s) if err != nil { panic(err) } return n }
package main import ( "github.com/life-assistant-go/utils" ) func main() { type YY struct { Path string } type TestGorm struct { Title string `gorm:"not null;"` Tag string YY } var test = TestGorm{ Title: "", Tag: "333", } utils.ValidateStruct(test) utils.DB.Create(&test) // app.DBTable() // app.Router() }
package server import ( "github.com/labstack/echo" "net/http" ) func handleReportState(c echo.Context) error { return c.JSON(http.StatusOK, map[string]string{ "message": "ok", }) } func handleFulfillState(c echo.Context) error { return c.JSON(http.StatusOK, State{ Properties: []Property{ { Action: ActionCameraStream, Value: "https://camerastream.homegate.cc/000-00-000", }, { Action: ActionOnOff, Value: "ON", }, }, }) }
package arrays import ( "fmt" ) func main() { a := make([][]int, 3) count := 1 for i := 0; i < 3; i++ { a[i] = make([]int,3) for j := 0; j < 3; j++ { a[i][j] = count count++ } } fmt.Println(rotateImage(a)) } func rotateImage(a [][]int) [][]int { new := make([][]int, len(a)) for i := 0; i < len(a);i++ { new[i] = make([]int, len(a)) for j := 0; j < len(a); j++ { new[i][j] = a[len(a)-1-j][i] } } return new }
package main import "fmt" import "sync" func main() { wg := &sync.WaitGroup{} wg.Add(2) ch1 := make(chan int, 0) //ch2 := make(chan int,0) arr1 := [5]int{0, 2, 4, 6, 8} arr2 := [5]int{1, 3, 5, 7, 9} go func() { for i, v := range arr1 { ch1 <- i fmt.Println(v) <-ch1 } wg.Done() }() go func() { for i, v := range arr2 { <-ch1 fmt.Println(v) ch1 <- i } wg.Done() }() wg.Wait() sync. }
/* Copyright 2022 Gravitational, 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 types import ( "time" "github.com/gravitational/trace" "github.com/gravitational/teleport/api/utils" ) // PluginType represents the type of the plugin type PluginType string const ( // PluginTypeUnknown is returned when no plugin type matches. PluginTypeUnknown PluginType = "" // PluginTypeSlack is the Slack access request plugin PluginTypeSlack = "slack" // PluginTypeOpenAI is the OpenAI plugin PluginTypeOpenAI = "openai" ) // Plugin represents a plugin instance type Plugin interface { // ResourceWithSecrets provides common resource methods. ResourceWithSecrets Clone() Plugin GetCredentials() PluginCredentials GetStatus() PluginStatus GetType() PluginType SetCredentials(PluginCredentials) error SetStatus(PluginStatus) error } // PluginCredentials are the credentials embedded in Plugin type PluginCredentials interface { GetOauth2AccessToken() *PluginOAuth2AccessTokenCredentials } // PluginStatus is the plugin status type PluginStatus interface { GetCode() PluginStatusCode } // NewPluginV1 creates a new PluginV1 resource. func NewPluginV1(metadata Metadata, spec PluginSpecV1, creds *PluginCredentialsV1) *PluginV1 { p := &PluginV1{ Metadata: metadata, Spec: spec, } if creds != nil { p.SetCredentials(creds) } return p } // CheckAndSetDefaults checks validity of all parameters and sets defaults. func (p *PluginV1) CheckAndSetDefaults() error { p.setStaticFields() if err := p.Metadata.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } switch settings := p.Spec.Settings.(type) { case *PluginSpecV1_SlackAccessPlugin: // Check settings. if settings.SlackAccessPlugin == nil { return trace.BadParameter("settings must be set") } if err := settings.SlackAccessPlugin.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } if p.Credentials == nil { // TODO: after credential exchange during creation is implemented, // this should validate that credentials are not empty break } if p.Credentials.GetOauth2AccessToken() == nil { return trace.BadParameter("Slack access plugin can only be used with OAuth2 access token credential type") } if err := p.Credentials.GetOauth2AccessToken().CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } case *PluginSpecV1_Openai: if p.Credentials == nil { return trace.BadParameter("credentials must be set") } bearer := p.Credentials.GetBearerToken() if bearer == nil { return trace.BadParameter("openai plugin must be used with the bearer token credential type") } if (bearer.Token == "") == (bearer.TokenFile == "") { return trace.BadParameter("exactly one of Token and TokenFile must be specified") } default: return trace.BadParameter("settings are not set or have an unknown type") } return nil } // WithoutSecrets returns an instance of resource without secrets. func (p *PluginV1) WithoutSecrets() Resource { if p.Credentials == nil { return p } p2 := p.Clone().(*PluginV1) p2.SetCredentials(nil) return p2 } func (p *PluginV1) setStaticFields() { p.Kind = KindPlugin p.Version = V1 } // Clone returns a copy of the Plugin instance func (p *PluginV1) Clone() Plugin { return utils.CloneProtoMsg(p) } // GetVersion returns resource version func (p *PluginV1) GetVersion() string { return p.Version } // GetKind returns resource kind func (p *PluginV1) GetKind() string { return p.Kind } // GetSubKind returns resource sub kind func (p *PluginV1) GetSubKind() string { return p.SubKind } // SetSubKind sets resource subkind func (p *PluginV1) SetSubKind(s string) { p.SubKind = s } // GetResourceID returns resource ID func (p *PluginV1) GetResourceID() int64 { return p.Metadata.ID } // SetResourceID sets resource ID func (p *PluginV1) SetResourceID(id int64) { p.Metadata.ID = id } // GetMetadata returns object metadata func (p *PluginV1) GetMetadata() Metadata { return p.Metadata } // SetMetadata sets object metadata func (p *PluginV1) SetMetadata(meta Metadata) { p.Metadata = meta } // Expiry returns expiry time for the object func (p *PluginV1) Expiry() time.Time { return p.Metadata.Expiry() } // SetExpiry sets expiry time for the object func (p *PluginV1) SetExpiry(expires time.Time) { p.Metadata.SetExpiry(expires) } // GetName returns the name of the User func (p *PluginV1) GetName() string { return p.Metadata.Name } // SetName sets the name of the User func (p *PluginV1) SetName(e string) { p.Metadata.Name = e } // GetCredentials implements Plugin func (p *PluginV1) GetCredentials() PluginCredentials { return p.Credentials } // SetCredentials implements Plugin func (p *PluginV1) SetCredentials(creds PluginCredentials) error { if creds == nil { p.Credentials = nil return nil } switch creds := creds.(type) { case *PluginCredentialsV1: p.Credentials = creds default: return trace.BadParameter("unsupported plugin credential type %T", creds) } return nil } // GetStatus implements Plugin func (p *PluginV1) GetStatus() PluginStatus { return p.Status } // SetStatus implements Plugin func (p *PluginV1) SetStatus(status PluginStatus) error { if status == nil { p.Status = PluginStatusV1{} return nil } p.Status = PluginStatusV1{ Code: status.GetCode(), } return nil } // GetType implements Plugin func (p *PluginV1) GetType() PluginType { switch p.Spec.Settings.(type) { case *PluginSpecV1_SlackAccessPlugin: return PluginTypeSlack case *PluginSpecV1_Openai: return PluginTypeOpenAI default: return PluginTypeUnknown } } // CheckAndSetDefaults validates and set the default values func (s *PluginSlackAccessSettings) CheckAndSetDefaults() error { if s.FallbackChannel == "" { return trace.BadParameter("fallback_channel must be set") } return nil } // CheckAndSetDefaults validates and set the default values func (c *PluginOAuth2AuthorizationCodeCredentials) CheckAndSetDefaults() error { if c.AuthorizationCode == "" { return trace.BadParameter("authorization_code must be set") } if c.RedirectUri == "" { return trace.BadParameter("redirect_uri must be set") } return nil } // CheckAndSetDefaults validates and set the default values func (c *PluginOAuth2AccessTokenCredentials) CheckAndSetDefaults() error { if c.AccessToken == "" { return trace.BadParameter("access_token must be set") } if c.RefreshToken == "" { return trace.BadParameter("refresh_token must be set") } c.Expires = c.Expires.UTC() return nil } // GetCode returns the status code func (c PluginStatusV1) GetCode() PluginStatusCode { return c.Code }
// Copyright © SAS Institute 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 ratelimit import ( "context" "time" "golang.org/x/time/rate" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "github.com/sassoftware/relic/v7/lib/pkcs7" "github.com/sassoftware/relic/v7/lib/pkcs9" ) var metricRateLimited = promauto.NewCounter(prometheus.CounterOpts{ Name: "timestamper_rate_limited_seconds", Help: "Cumulative number of seconds waiting for rate limits", }) type limiter struct { Timestamper pkcs9.Timestamper Limit *rate.Limiter } func New(t pkcs9.Timestamper, r float64, burst int) pkcs9.Timestamper { if r == 0 { return t } if burst < 1 { burst = 1 } return &limiter{t, rate.NewLimiter(rate.Limit(r), burst)} } func (l *limiter) Timestamp(ctx context.Context, req *pkcs9.Request) (*pkcs7.ContentInfoSignedData, error) { start := time.Now() if err := l.Limit.Wait(ctx); err != nil { return nil, err } if waited := time.Since(start); waited > 1*time.Millisecond { metricRateLimited.Add(time.Since(start).Seconds()) } return l.Timestamper.Timestamp(ctx, req) }
package main import ( "fmt" "sort" ) // type a os.File // type b io.Writer // type c bytes.Buffer // type d time.Duration // var w io.Writer // var rwc io.ReadWriteCloser // var x interface{} = time.Now() // func main() { // w = os.Stdout // w = new(bytes.Buffer) // rwc = os.Stdout // // rwc = new(bytes.Buffer) // w = rwc // // rwc = w // fmt.Printf("%v", x) // } //sort 1. 序列的长度;2.两个元素的比较结果;3.交换两个元素的方式 type StringSlice []string func (p StringSlice) Len() int { return len(p) } func (p StringSlice) Less(i, j int) bool { return p[i] < p[j] } func (p StringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func main() { names := []string{"d", "c", "e", "a"} sort.Sort(StringSlice(names)) fmt.Println(names) }
package handler import ( "net/http" "github.com/go-chi/render" "github.com/pagient/pagient-server/pkg/model" "github.com/pagient/pagient-server/pkg/presenter/renderer" "github.com/pagient/pagient-server/pkg/presenter/router/middleware/context" "github.com/pagient/pagient-server/pkg/service" ) // GetPatients lists all patients func GetPatients(patientService service.PatientService) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { patients, err := patientService.GetAll() if err != nil { render.Render(w, req, renderer.ErrInternalServer(err)) return } render.RenderList(w, req, renderer.NewPatientListResponse(patients)) } } // AddPatient adds a patient func AddPatient(patientService service.PatientService) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { patientReq := &renderer.PatientRequest{} if err := render.Bind(req, patientReq); err != nil { render.Render(w, req, renderer.ErrBadRequest(err)) return } // Set clientID to the client that added the patientReq ctxClient := req.Context().Value(context.ClientKey).(*model.Client) if ctxClient == nil { http.Error(w, http.StatusText(http.StatusUnauthorized), 401) return } patientReq.ClientID = ctxClient.ID patient, err := patientService.Add(patientReq.GetModel()) if err != nil { if service.IsModelExistErr(err) { render.Render(w, req, renderer.ErrConflict(err)) return } if service.IsModelValidationErr(err) { render.Render(w, req, renderer.ErrValidation(err)) return } // on any other error raise 500 status render.Render(w, req, renderer.ErrInternalServer(err)) return } render.Status(req, http.StatusCreated) render.Render(w, req, renderer.NewPatientResponse(patient)) } } // GetPatient returns the patient by specified id func GetPatient() http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { ctxPatient := req.Context().Value(context.PatientKey).(*model.Patient) render.Render(w, req, renderer.NewPatientResponse(ctxPatient)) } } // UpdatePatient updates a patient by specified id func UpdatePatient(patientService service.PatientService) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { patientReq := &renderer.PatientRequest{} if err := render.Bind(req, patientReq); err != nil { render.Render(w, req, renderer.ErrBadRequest(err)) return } // Set clientID to the client that updated the patient ctxClient := req.Context().Value(context.ClientKey).(*model.Client) if ctxClient != nil { patientReq.ClientID = ctxClient.ID } patient, err := patientService.Update(patientReq.GetModel()) if err != nil { if service.IsModelValidationErr(err) { render.Render(w, req, renderer.ErrValidation(err)) return } if service.IsExternalServiceErr(err) { render.Render(w, req, renderer.ErrGateway(err)) return } // on any other error raise 500 status render.Render(w, req, renderer.ErrInternalServer(err)) return } render.Render(w, req, renderer.NewPatientResponse(patient)) } } // DeletePatient deletes a patient by specified id func DeletePatient(patientService service.PatientService) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { ctxPatient := req.Context().Value(context.PatientKey).(*model.Patient) if err := patientService.Remove(ctxPatient); err != nil { if service.IsInvalidArgumentErr(err) { render.Render(w, req, renderer.ErrBadRequest(err)) return } render.Render(w, req, renderer.ErrInternalServer(err)) return } w.WriteHeader(http.StatusNoContent) } }
package main /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func largestValues(root *TreeNode) []int { var ret = []int{} var dfs func(r *TreeNode, idx int) dfs = func(r *TreeNode, idx int) { if r == nil { return } if len(ret) == idx { ret = append(ret, r.Val) } if r.Val > ret[idx] { ret[idx] = r.Val } dfs(r.Left, idx+1) dfs(r.Right, idx+1) } dfs(root, 0) return ret }
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package tsaddr handles Tailscale-specific IPs and ranges. package tsaddr import ( "sync" "inet.af/netaddr" ) // ChromeOSVMRange returns the subset of the CGNAT IPv4 range used by // ChromeOS to interconnect the host OS to containers and VMs. We // avoid allocating Tailscale IPs from it, to avoid conflicts. func ChromeOSVMRange() netaddr.IPPrefix { chromeOSRange.Do(func() { mustPrefix(&chromeOSRange.v, "100.115.92.0/23") }) return chromeOSRange.v } var chromeOSRange oncePrefix // CGNATRange returns the Carrier Grade NAT address range that // is the superset range that Tailscale assigns out of. // See https://tailscale.com/kb/1015/100.x-addresses. // Note that Tailscale does not assign out of the ChromeOSVMRange. func CGNATRange() netaddr.IPPrefix { cgnatRange.Do(func() { mustPrefix(&cgnatRange.v, "100.64.0.0/10") }) return cgnatRange.v } var ( cgnatRange oncePrefix ulaRange oncePrefix tsUlaRange oncePrefix ula4To6Range oncePrefix ulaEph6Range oncePrefix ) // TailscaleServiceIP returns the listen address of services // provided by Tailscale itself such as the MagicDNS proxy. func TailscaleServiceIP() netaddr.IP { return netaddr.IPv4(100, 100, 100, 100) // "100.100.100.100" for those grepping } // IsTailscaleIP reports whether ip is an IP address in a range that // Tailscale assigns from. func IsTailscaleIP(ip netaddr.IP) bool { if ip.Is4() { return CGNATRange().Contains(ip) && !ChromeOSVMRange().Contains(ip) } return TailscaleULARange().Contains(ip) } // TailscaleULARange returns the IPv6 Unique Local Address range that // is the superset range that Tailscale assigns out of. func TailscaleULARange() netaddr.IPPrefix { tsUlaRange.Do(func() { mustPrefix(&tsUlaRange.v, "fd7a:115c:a1e0::/48") }) return tsUlaRange.v } // Tailscale4To6Range returns the subset of TailscaleULARange used for // auto-translated Tailscale ipv4 addresses. func Tailscale4To6Range() netaddr.IPPrefix { // This IP range has no significance, beyond being a subset of // TailscaleULARange. The bits from /48 to /104 were picked at // random. ula4To6Range.Do(func() { mustPrefix(&ula4To6Range.v, "fd7a:115c:a1e0:ab12:4843:cd96:6200::/104") }) return ula4To6Range.v } // TailscaleEphemeral6Range returns the subset of TailscaleULARange // used for ephemeral IPv6-only Tailscale nodes. func TailscaleEphemeral6Range() netaddr.IPPrefix { // This IP range has no significance, beyond being a subset of // TailscaleULARange. The bits from /48 to /64 were picked at // random, with the only criterion being to not be the conflict // with the Tailscale4To6Range above. ulaEph6Range.Do(func() { mustPrefix(&ulaEph6Range.v, "fd7a:115c:a1e0:efe3::/64") }) return ulaEph6Range.v } // Tailscale4To6Placeholder returns an IP address that can be used as // a source IP when one is required, but a netmap didn't provide // any. This address never gets allocated by the 4-to-6 algorithm in // control. // // Currently used to work around a Windows limitation when programming // IPv6 routes in corner cases. func Tailscale4To6Placeholder() netaddr.IP { return Tailscale4To6Range().IP() } // Tailscale4To6 returns a Tailscale IPv6 address that maps 1:1 to the // given Tailscale IPv4 address. Returns a zero IP if ipv4 isn't a // Tailscale IPv4 address. func Tailscale4To6(ipv4 netaddr.IP) netaddr.IP { if !ipv4.Is4() || !IsTailscaleIP(ipv4) { return netaddr.IP{} } ret := Tailscale4To6Range().IP().As16() v4 := ipv4.As4() copy(ret[13:], v4[1:]) return netaddr.IPFrom16(ret) } func mustPrefix(v *netaddr.IPPrefix, prefix string) { var err error *v, err = netaddr.ParseIPPrefix(prefix) if err != nil { panic(err) } } type oncePrefix struct { sync.Once v netaddr.IPPrefix } // NewContainsIPFunc returns a func that reports whether ip is in addrs. // // It's optimized for the cases of addrs being empty and addrs // containing 1 or 2 single-IP prefixes (such as one IPv4 address and // one IPv6 address). // // Otherwise the implementation is somewhat slow. func NewContainsIPFunc(addrs []netaddr.IPPrefix) func(ip netaddr.IP) bool { // Specialize the three common cases: no address, just IPv4 // (or just IPv6), and both IPv4 and IPv6. if len(addrs) == 0 { return func(netaddr.IP) bool { return false } } // If any addr is more than a single IP, then just do the slow // linear thing until // https://github.com/inetaf/netaddr/issues/139 is done. for _, a := range addrs { if a.IsSingleIP() { continue } acopy := append([]netaddr.IPPrefix(nil), addrs...) return func(ip netaddr.IP) bool { for _, a := range acopy { if a.Contains(ip) { return true } } return false } } // Fast paths for 1 and 2 IPs: if len(addrs) == 1 { a := addrs[0] return func(ip netaddr.IP) bool { return ip == a.IP() } } if len(addrs) == 2 { a, b := addrs[0], addrs[1] return func(ip netaddr.IP) bool { return ip == a.IP() || ip == b.IP() } } // General case: m := map[netaddr.IP]bool{} for _, a := range addrs { m[a.IP()] = true } return func(ip netaddr.IP) bool { return m[ip] } } // PrefixesContainsFunc reports whether f is true for any IPPrefix in // ipp. func PrefixesContainsFunc(ipp []netaddr.IPPrefix, f func(netaddr.IPPrefix) bool) bool { for _, v := range ipp { if f(v) { return true } } return false } // IPsContainsFunc reports whether f is true for any IP in ips. func IPsContainsFunc(ips []netaddr.IP, f func(netaddr.IP) bool) bool { for _, v := range ips { if f(v) { return true } } return false } // PrefixIs4 reports whether p is an IPv4 prefix. func PrefixIs4(p netaddr.IPPrefix) bool { return p.IP().Is4() } // PrefixIs6 reports whether p is an IPv6 prefix. func PrefixIs6(p netaddr.IPPrefix) bool { return p.IP().Is6() }
package main import ( "github.com/oceanho/gw/contrib/apps/stor" ) var AppPlugin stor.App func init() { AppPlugin = stor.New() }
// 139. Sort 格式化 分類 排序 直接更改記憶體位置的值所以不用return // https://golang.org/pkg/sort/ package main import ( "fmt" "sort" ) func main() { s := []int{5, 2, 6, 3, 1, 4} // unsorted x := []string{"and", "q", "M", "ming", "Dr.", "zo", "xxx", "ga", "A"} fmt.Println(s) sort.Ints(s) fmt.Println(s) fmt.Println(x) sort.Strings(x) fmt.Println(x) }
package main import "sort" func minMeetingRooms(intervals [][]int) int { if len(intervals) < 1 { return 0 } //var array svalue = intervals //sort.Sort(array) sort.Slice(intervals, func(i, j int) bool { return intervals[i][1] < intervals[j][1] }) max := 1 count := 1 for i, v := range intervals { count = 1 for k := i + 1; k < len(intervals); k++ { if v[1] > intervals[k][0] { count++ } } if count > max { max = count } } return max } type svalue [][]int func (p svalue) Len() int { return len(p) } func (p svalue) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p svalue) Less(i, j int) bool { if p[i][1] < p[j][1] { return true } return false }
// Copyright 2019 - 2022 The Samply Community // // 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 fhir import "encoding/json" // THIS FILE IS GENERATED BY https://github.com/samply/golang-fhir-models // PLEASE DO NOT EDIT BY HAND // PlanDefinition is documented here http://hl7.org/fhir/StructureDefinition/PlanDefinition type PlanDefinition struct { Id *string `bson:"id,omitempty" json:"id,omitempty"` Meta *Meta `bson:"meta,omitempty" json:"meta,omitempty"` ImplicitRules *string `bson:"implicitRules,omitempty" json:"implicitRules,omitempty"` Language *string `bson:"language,omitempty" json:"language,omitempty"` Text *Narrative `bson:"text,omitempty" json:"text,omitempty"` Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"` ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"` Url *string `bson:"url,omitempty" json:"url,omitempty"` Identifier []Identifier `bson:"identifier,omitempty" json:"identifier,omitempty"` Version *string `bson:"version,omitempty" json:"version,omitempty"` Name *string `bson:"name,omitempty" json:"name,omitempty"` Title *string `bson:"title,omitempty" json:"title,omitempty"` Subtitle *string `bson:"subtitle,omitempty" json:"subtitle,omitempty"` Type *CodeableConcept `bson:"type,omitempty" json:"type,omitempty"` Status PublicationStatus `bson:"status" json:"status"` Experimental *bool `bson:"experimental,omitempty" json:"experimental,omitempty"` SubjectCodeableConcept *CodeableConcept `bson:"subjectCodeableConcept,omitempty" json:"subjectCodeableConcept,omitempty"` SubjectReference *Reference `bson:"subjectReference,omitempty" json:"subjectReference,omitempty"` Date *string `bson:"date,omitempty" json:"date,omitempty"` Publisher *string `bson:"publisher,omitempty" json:"publisher,omitempty"` Contact []ContactDetail `bson:"contact,omitempty" json:"contact,omitempty"` Description *string `bson:"description,omitempty" json:"description,omitempty"` UseContext []UsageContext `bson:"useContext,omitempty" json:"useContext,omitempty"` Jurisdiction []CodeableConcept `bson:"jurisdiction,omitempty" json:"jurisdiction,omitempty"` Purpose *string `bson:"purpose,omitempty" json:"purpose,omitempty"` Usage *string `bson:"usage,omitempty" json:"usage,omitempty"` Copyright *string `bson:"copyright,omitempty" json:"copyright,omitempty"` ApprovalDate *string `bson:"approvalDate,omitempty" json:"approvalDate,omitempty"` LastReviewDate *string `bson:"lastReviewDate,omitempty" json:"lastReviewDate,omitempty"` EffectivePeriod *Period `bson:"effectivePeriod,omitempty" json:"effectivePeriod,omitempty"` Topic []CodeableConcept `bson:"topic,omitempty" json:"topic,omitempty"` Author []ContactDetail `bson:"author,omitempty" json:"author,omitempty"` Editor []ContactDetail `bson:"editor,omitempty" json:"editor,omitempty"` Reviewer []ContactDetail `bson:"reviewer,omitempty" json:"reviewer,omitempty"` Endorser []ContactDetail `bson:"endorser,omitempty" json:"endorser,omitempty"` RelatedArtifact []RelatedArtifact `bson:"relatedArtifact,omitempty" json:"relatedArtifact,omitempty"` Library []string `bson:"library,omitempty" json:"library,omitempty"` Goal []PlanDefinitionGoal `bson:"goal,omitempty" json:"goal,omitempty"` Action []PlanDefinitionAction `bson:"action,omitempty" json:"action,omitempty"` } type PlanDefinitionGoal struct { Id *string `bson:"id,omitempty" json:"id,omitempty"` Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"` ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"` Category *CodeableConcept `bson:"category,omitempty" json:"category,omitempty"` Description CodeableConcept `bson:"description" json:"description"` Priority *CodeableConcept `bson:"priority,omitempty" json:"priority,omitempty"` Start *CodeableConcept `bson:"start,omitempty" json:"start,omitempty"` Addresses []CodeableConcept `bson:"addresses,omitempty" json:"addresses,omitempty"` Documentation []RelatedArtifact `bson:"documentation,omitempty" json:"documentation,omitempty"` Target []PlanDefinitionGoalTarget `bson:"target,omitempty" json:"target,omitempty"` } type PlanDefinitionGoalTarget struct { Id *string `bson:"id,omitempty" json:"id,omitempty"` Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"` ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"` Measure *CodeableConcept `bson:"measure,omitempty" json:"measure,omitempty"` DetailQuantity *Quantity `bson:"detailQuantity,omitempty" json:"detailQuantity,omitempty"` DetailRange *Range `bson:"detailRange,omitempty" json:"detailRange,omitempty"` DetailCodeableConcept *CodeableConcept `bson:"detailCodeableConcept,omitempty" json:"detailCodeableConcept,omitempty"` Due *Duration `bson:"due,omitempty" json:"due,omitempty"` } type PlanDefinitionAction struct { Id *string `bson:"id,omitempty" json:"id,omitempty"` Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"` ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"` Prefix *string `bson:"prefix,omitempty" json:"prefix,omitempty"` Title *string `bson:"title,omitempty" json:"title,omitempty"` Description *string `bson:"description,omitempty" json:"description,omitempty"` TextEquivalent *string `bson:"textEquivalent,omitempty" json:"textEquivalent,omitempty"` Priority *RequestPriority `bson:"priority,omitempty" json:"priority,omitempty"` Code []CodeableConcept `bson:"code,omitempty" json:"code,omitempty"` Reason []CodeableConcept `bson:"reason,omitempty" json:"reason,omitempty"` Documentation []RelatedArtifact `bson:"documentation,omitempty" json:"documentation,omitempty"` GoalId []string `bson:"goalId,omitempty" json:"goalId,omitempty"` SubjectCodeableConcept *CodeableConcept `bson:"subjectCodeableConcept,omitempty" json:"subjectCodeableConcept,omitempty"` SubjectReference *Reference `bson:"subjectReference,omitempty" json:"subjectReference,omitempty"` Trigger []TriggerDefinition `bson:"trigger,omitempty" json:"trigger,omitempty"` Condition []PlanDefinitionActionCondition `bson:"condition,omitempty" json:"condition,omitempty"` Input []DataRequirement `bson:"input,omitempty" json:"input,omitempty"` Output []DataRequirement `bson:"output,omitempty" json:"output,omitempty"` RelatedAction []PlanDefinitionActionRelatedAction `bson:"relatedAction,omitempty" json:"relatedAction,omitempty"` TimingDateTime *string `bson:"timingDateTime,omitempty" json:"timingDateTime,omitempty"` TimingAge *Age `bson:"timingAge,omitempty" json:"timingAge,omitempty"` TimingPeriod *Period `bson:"timingPeriod,omitempty" json:"timingPeriod,omitempty"` TimingDuration *Duration `bson:"timingDuration,omitempty" json:"timingDuration,omitempty"` TimingRange *Range `bson:"timingRange,omitempty" json:"timingRange,omitempty"` TimingTiming *Timing `bson:"timingTiming,omitempty" json:"timingTiming,omitempty"` Participant []PlanDefinitionActionParticipant `bson:"participant,omitempty" json:"participant,omitempty"` Type *CodeableConcept `bson:"type,omitempty" json:"type,omitempty"` GroupingBehavior *ActionGroupingBehavior `bson:"groupingBehavior,omitempty" json:"groupingBehavior,omitempty"` SelectionBehavior *ActionSelectionBehavior `bson:"selectionBehavior,omitempty" json:"selectionBehavior,omitempty"` RequiredBehavior *ActionRequiredBehavior `bson:"requiredBehavior,omitempty" json:"requiredBehavior,omitempty"` PrecheckBehavior *ActionPrecheckBehavior `bson:"precheckBehavior,omitempty" json:"precheckBehavior,omitempty"` CardinalityBehavior *ActionCardinalityBehavior `bson:"cardinalityBehavior,omitempty" json:"cardinalityBehavior,omitempty"` DefinitionCanonical *string `bson:"definitionCanonical,omitempty" json:"definitionCanonical,omitempty"` DefinitionUri *string `bson:"definitionUri,omitempty" json:"definitionUri,omitempty"` Transform *string `bson:"transform,omitempty" json:"transform,omitempty"` DynamicValue []PlanDefinitionActionDynamicValue `bson:"dynamicValue,omitempty" json:"dynamicValue,omitempty"` Action []PlanDefinitionAction `bson:"action,omitempty" json:"action,omitempty"` } type PlanDefinitionActionCondition struct { Id *string `bson:"id,omitempty" json:"id,omitempty"` Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"` ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"` Kind ActionConditionKind `bson:"kind" json:"kind"` Expression *Expression `bson:"expression,omitempty" json:"expression,omitempty"` } type PlanDefinitionActionRelatedAction struct { Id *string `bson:"id,omitempty" json:"id,omitempty"` Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"` ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"` ActionId string `bson:"actionId" json:"actionId"` Relationship ActionRelationshipType `bson:"relationship" json:"relationship"` OffsetDuration *Duration `bson:"offsetDuration,omitempty" json:"offsetDuration,omitempty"` OffsetRange *Range `bson:"offsetRange,omitempty" json:"offsetRange,omitempty"` } type PlanDefinitionActionParticipant struct { Id *string `bson:"id,omitempty" json:"id,omitempty"` Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"` ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"` Type ActionParticipantType `bson:"type" json:"type"` Role *CodeableConcept `bson:"role,omitempty" json:"role,omitempty"` } type PlanDefinitionActionDynamicValue struct { Id *string `bson:"id,omitempty" json:"id,omitempty"` Extension []Extension `bson:"extension,omitempty" json:"extension,omitempty"` ModifierExtension []Extension `bson:"modifierExtension,omitempty" json:"modifierExtension,omitempty"` Path *string `bson:"path,omitempty" json:"path,omitempty"` Expression *Expression `bson:"expression,omitempty" json:"expression,omitempty"` } type OtherPlanDefinition PlanDefinition // MarshalJSON marshals the given PlanDefinition as JSON into a byte slice func (r PlanDefinition) MarshalJSON() ([]byte, error) { return json.Marshal(struct { OtherPlanDefinition ResourceType string `json:"resourceType"` }{ OtherPlanDefinition: OtherPlanDefinition(r), ResourceType: "PlanDefinition", }) } // UnmarshalPlanDefinition unmarshals a PlanDefinition. func UnmarshalPlanDefinition(b []byte) (PlanDefinition, error) { var planDefinition PlanDefinition if err := json.Unmarshal(b, &planDefinition); err != nil { return planDefinition, err } return planDefinition, nil }
package main import "k8s-client/example" func main(){ //var kubeconfig *string //if home := homedir.HomeDir(); home != "" { // kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file") //} else { // kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file") //} //flag.Parse() // //config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) //if err != nil { // panic(err) //} //clientset, err := kubernetes.NewForConfig(config) //if err != nil { // panic(err) //} example.GetdeploymentList() example.CreatepodsByyaml() }