text
stringlengths
11
4.05M
package main import ( "fmt" "os" "github.com/urfave/cli" "github.com/micnncim/git-emot/cmd" ) func init() { if !cmd.IsInitialized() { fmt.Println("Initialize") if err := cmd.InitMsgs(); err != nil { fmt.Println(err) } } } func main() { app := cli.NewApp() app.Name = "git-emot" app.Commands = []cli.Command{ cmd.AddCmd(), cmd.ListCmd(), cmd.RemoveCmd(), cmd.EditCmd(), cmd.BrowseCmd(), cmd.PullCmd(), cmd.PushCmd(), } app.Usage = "git commit messages with emoji" app.Action = cmd.Commit app.Run(os.Args) }
package main import "fmt" func main() { switch "Shikamaru" { case "Sasuke", "Naruto", "Sakura": fmt.Println("Team 7") case "Shikamaru", "Choji", "Ino": fmt.Println("Team 10") case "Kiba", "Hinata", "Shino": fmt.Println("Team 8") case "Neji", "Lee", "Tenten": fmt.Println("Team 11") default: fmt.Println("Konohagakure village") } } // Team 10
package hermes import ( "encoding/json" "fmt" "runtime" "time" "github.com/gorilla/websocket" ) type WebSocket struct { ws *websocket.Conn quit chan bool Stream chan *Event Errors chan error } type Event struct { Event string `json:"event"` Data interface{} `json:"data"` } func (s *WebSocket) Close() { s.quit <- true } func (s *WebSocket) Subscribe(channel string) error { a := &Event{ Event: "pusher:subscribe", Data: map[string]interface{}{ "channel": channel, }, } return s.ws.WriteJSON(a) } func (s *WebSocket) SendTextMessage(message []byte) error { return s.ws.WriteMessage(websocket.TextMessage, message) } func (s *WebSocket) Ping() error { a := &Event{ Event: "pusher:ping", } return s.ws.WriteJSON(a) } func (s *WebSocket) Pong() error { a := &Event{ Event: "pusher:pong", } return s.ws.WriteJSON(a) } func NewWebSocket(opts ...Option) (*WebSocket, error) { var ( err error options = newOptions(opts...) s = &WebSocket{ quit: make(chan bool, 1), Stream: make(chan *Event), Errors: make(chan error), } ) // set up websocket s.ws, _, err = websocket.DefaultDialer.Dial(options.url, nil) if err != nil { return nil, fmt.Errorf("error dialing websocket: %s", err) } go func() { defer func() { if err = s.ws.Close(); err != nil { s.Errors <- err } }() for { runtime.Gosched() if err = s.ws.SetReadDeadline(time.Now().Add(options.deadline)); err != nil { s.Errors <- err } select { case <-s.quit: return default: var message []byte var err error _, message, err = s.ws.ReadMessage() if err != nil { s.Errors <- err continue } e := &Event{} err = json.Unmarshal(message, e) if err != nil { s.Errors <- err continue } s.Stream <- e } } }() return s, nil }
package practice import ( "fmt" "testing" ) func Test_cloneGraph(t *testing.T) { type args struct { node *Node } tests := []struct { name string args args }{ { name: "example 1", args: args{ node: newGraph([][]int{ {2, 4}, {1, 3}, {2, 4}, {1, 3}, }), }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := cloneGraph(tt.args.node); !isCopyed(got, tt.args.node) { t.Error("not copyed correct") } }) } } func Test_isCopyed(t *testing.T) { tests := []struct { al1, al2 [][]int want bool }{ { al1: [][]int{ {2, 3}, {1, 3}, {1, 2}, }, al2: [][]int{ {2, 3}, {1, 3}, {1, 2}, }, want: true, }, { al1: [][]int{ {3, 4}, {4}, {1}, {1, 2}, }, al2: [][]int{ {3, 4}, {3}, {1, 2}, {1}, }, want: false, }, } for idx, tt := range tests { t.Run(fmt.Sprintf("test %d", idx), func(t *testing.T) { if got := isCopyed(newGraph(tt.al1), newGraph(tt.al2)); got != tt.want { t.Errorf("expected: %v, got: %v", tt.want, got) } }) } }
package main import ( "flag" "fmt" "os" "sort" "strings" "github.com/aws/aws-sdk-go-v2/aws/endpoints" "github.com/aws/aws-sdk-go-v2/aws/external" "github.com/aws/aws-sdk-go-v2/service/ec2" ) // Version of the CLI const CLIVersion = "0.2.1" func main() { cfg, err := external.LoadDefaultAWSConfig() if err != nil { panic(err) } cfg.Region = endpoints.UsEast1RegionID ec2svc := ec2.New(cfg) var versionFlag = flag.Bool("version", false, "Displays current version.") listCommand := flag.NewFlagSet("list", flag.ExitOnError) helpMessage := `Oh no - you forgot to specify what exactly to do! Must provide a subcommand out of the following options: list Example usage: $ awsprey list web:staging ` if len(os.Args) <= 1 { fmt.Println(helpMessage) os.Exit(1) } flag.Parse() if *versionFlag { fmt.Println(CLIVersion) os.Exit(0) } switch os.Args[1] { case "list": listCommand.Parse(os.Args[2:]) default: flag.PrintDefaults() os.Exit(1) } if listCommand.Parsed() { if len(os.Args) <= 2 { // shouldn't have to do this, error handling should be at parse time fmt.Println(helpMessage) } listArg := os.Args[2] filterValues := strings.Split(listArg, ":") dryRun := false tagFilterService := "tag:service" tagFilterEnvironment := "tag:environment" filterRunningState := "instance-state-code" serviceFilters := []ec2.Filter{ { Name: &tagFilterService, Values: []string{filterValues[0]}, }, { Name: &tagFilterEnvironment, Values: []string{filterValues[1]}, }, { Name: &filterRunningState, Values: []string{"16"}, // 16: "running" state }, } if len(os.Args) > 3 && os.Args[3] == "with" { switch os.Args[4] { case "tag": tag := os.Args[5] extraFilters := strings.Split(tag, ":") key := "tag:" + extraFilters[0] extraServiceFilters := ec2.Filter{ Name: &key, Values: []string{extraFilters[1]}, } serviceFilters = append(serviceFilters, extraServiceFilters) default: errorMessage := fmt.Sprintf( "%s is not a supported input. Choose: 'tag'.", os.Args[4], ) fmt.Println(errorMessage) os.Exit(1) } } input := ec2.DescribeInstancesInput{ DryRun: &dryRun, Filters: serviceFilters, } req := ec2svc.DescribeInstancesRequest(&input) resp, err := req.Send() if err != nil { panic(err) } // TODO: when the whole function is refactored out from `main` we should //return the list of instance names var instanceNames []string for _, reservation := range resp.Reservations { for _, instance := range reservation.Instances { for _, tag := range instance.Tags { if *tag.Key == "Name" { instanceNames = append(instanceNames, *tag.Value) } } } } sort.Strings(instanceNames) for _, instance := range instanceNames { fmt.Println(instance) } } }
package datastruct import ( "github.com/MintegralTech/juno/document" . "github.com/smartystreets/goconvey/convey" "testing" ) func TestSliceIterator(t *testing.T) { sl := NewSlice() sl.Add(1, nil) sl.Add(3, nil) Convey("New Slice Iterator", t, func() { iter := sl.Iterator() v := iter.Current() So(v, ShouldNotBeNil) So(v.Key(), ShouldEqual, 1) So(iter.HasNext(), ShouldBeTrue) iter.Next() v = iter.Current() So(v, ShouldNotBeNil) So(v.Key(), ShouldEqual, 3) So(iter.HasNext(), ShouldBeTrue) iter.Next() So(iter.Current(), ShouldBeNil) }) s := NewSlice() for i := 0; i < 100; i++ { s.Add(document.DocId(i), nil) } for i := 101; i < 150; i += 3 { s.Add(document.DocId(i), nil) } Convey("Next", t, func() { iter := s.Iterator() So(iter.HasNext(), ShouldBeTrue) v := iter.Current() So(v, ShouldNotBeNil) So(v.Key(), ShouldEqual, 0) iter.Next() elem := iter.Current() So(elem, ShouldNotBeNil) So(elem, ShouldNotBeNil) So(elem.Key(), ShouldEqual, 1) v = iter.GetGE(5) So(v, ShouldNotBeNil) So(v.Key(), ShouldEqual, 5) elem = iter.Current() So(elem, ShouldNotBeNil) So(elem, ShouldNotBeNil) So(elem.Key(), ShouldEqual, 5) iter.Next() elem = iter.Current() So(elem, ShouldNotBeNil) So(elem, ShouldNotBeNil) So(elem.Key(), ShouldEqual, 6) v = iter.GetGE(102) So(v, ShouldNotBeNil) So(v.Key(), ShouldEqual, 104) elem = iter.Current() So(elem, ShouldNotBeNil) So(elem, ShouldNotBeNil) So(elem.Key(), ShouldEqual, 104) So(iter.HasNext(), ShouldBeTrue) v = iter.GetGE(147) So(v, ShouldNotBeNil) So(v.Key(), ShouldEqual, 149) elem = iter.Current() So(elem, ShouldNotBeNil) So(elem, ShouldNotBeNil) So(elem.Key(), ShouldEqual, 149) So(iter.HasNext(), ShouldBeTrue) v = iter.GetGE(160) So(v, ShouldBeNil) elem = iter.Current() So(elem, ShouldBeNil) So(iter.HasNext(), ShouldBeFalse) }) } func TestSliceIterator_GetGE(t *testing.T) { s := NewSlice() for i := 0; i < 100; i++ { s.Add(document.DocId(i), nil) } a := s.Iterator() Convey("getGE", t, func() { v := a.GetGE(99) So(v.key, ShouldEqual, 99) v = a.GetGE(99) So(v.key, ShouldEqual, 99) v = a.GetGE(99) So(v.key, ShouldEqual, 99) }) aa := NewSlice() for i := 0; i < 1000; i++ { aa.Add(document.DocId(i), nil) } s1 := aa.Iterator() Convey("del", t, func() { v := s1.GetGE(10) So(v.key, ShouldEqual, 10) v = s1.GetGE(324) So(v.key, ShouldEqual, 324) So(aa.Len(), ShouldEqual, 1000) v = s1.GetGE(10) So(v.key, ShouldEqual, 324) v = s1.GetGE(324) So(v.key, ShouldEqual, 324) }) }
package Modules import "flag" type config struct { Port string Path string SUrl string Logg string } var Config config func (a *config) Init() { flag.StringVar(&a.Port, "p", "233", "监听端口") flag.StringVar(&a.Path, "path", "/", "心跳路径") flag.StringVar(&a.SUrl, "url", "", "上报URL") flag.StringVar(&a.Logg, "log", "false", "日志开关") flag.Parse() }
package esSearch import ( . "github.com/smartystreets/goconvey/convey" "testing" ) func TestIsEsCluserOk(t *testing.T) { Convey("test is es cluster is ok", t, func() { Convey("case 1,succ", func() { isOK := IsEsCluserOk() So(isOK, ShouldBeTrue) }) }) } func TestNewEsClient(t *testing.T) { esCli := NewEsClient() if esCli == nil { t.Error("new es cli return error.") } } func TestUseEs(t *testing.T) { Convey("test useEs func", t, func() { Convey("case 1,succ", func() { err := UseEs() So(err, ShouldBeNil) }) }) } func TestAddDocmToIndex(t *testing.T) { Convey("test add a doc in index", t, func() { Convey("case 1,succ", func() { err := AddDocmToIndex() So(err, ShouldBeNil) }) }) } func TestSearchEs(t *testing.T) { Convey("test search a name", t, func() { Convey("case 1,succ", func() { err := SearchEs() So(err, ShouldBeNil) }) }) } func TestReadLog(t *testing.T) { Convey("test readLog", t, func() { Convey("case 1,succ", func() { readLog() }) }) }
package config import ( "encoding/json" "fmt" "strings" jT "github.com/kellerza/template" log "github.com/sirupsen/logrus" "github.com/srl-labs/containerlab/nodes" "github.com/srl-labs/containerlab/types" ) // templates to execute var TemplateNames []string // path to additional templates var TemplatePaths []string type NodeConfig struct { TargetNode *types.NodeConfig // All the variables used to render the template Vars map[string]interface{} // the Rendered templates Data []string Info []string } func RenderAll(nodes map[string]nodes.Node, links map[int]*types.Link) (map[string]*NodeConfig, error) { res := make(map[string]*NodeConfig) if len(TemplatePaths) == 0 { return nil, fmt.Errorf("please specify one of more paths with --template-path") } if len(TemplateNames) == 0 { var err error TemplateNames, err = GetTemplateNamesInDirs(TemplatePaths) if err != nil { return nil, err } if len(TemplateNames) == 0 { return nil, fmt.Errorf("no templates files were found by %s path", TemplatePaths) } } tmpl, err := jT.New("", jT.SearchPath(TemplatePaths...)) if err != nil { return nil, err } for nodeName, vars := range PrepareVars(nodes, links) { res[nodeName] = &NodeConfig{ TargetNode: nodes[nodeName].Config(), Vars: vars, } for _, baseN := range TemplateNames { tmplN := fmt.Sprintf("%s__%s.tmpl", baseN, vars["role"]) data1, err := tmpl.ExecuteTemplate(tmplN, vars) if err != nil { return nil, err } data1 = strings.ReplaceAll(strings.Trim(data1, "\n \t"), "\n\n\n", "\n\n") res[nodeName].Data = append(res[nodeName].Data, data1) res[nodeName].Info = append(res[nodeName].Info, tmplN) } } return res, nil } // Implement stringer for conf snippet func (c *NodeConfig) String() string { s := fmt.Sprintf("%s: %v", c.TargetNode.ShortName, c.Info) return s } // Print the config func (c *NodeConfig) Print(printLines int) { var s strings.Builder s.WriteString(c.TargetNode.ShortName) if log.IsLevelEnabled(log.DebugLevel) { s.WriteString(" vars = ") vars, _ := json.MarshalIndent(c.Vars, "", " ") s.Write(vars[0 : len(vars)-1]) s.WriteString(" }") } if printLines > 0 { for idx, conf := range c.Data { fmt.Fprintf(&s, "\n Template %s for %s = [[", c.Info[idx], c.TargetNode.ShortName) cl := strings.SplitN(conf, "\n", printLines+1) if len(cl) > printLines { cl[printLines] = "..." } for _, l := range cl { s.WriteString("\n ") s.WriteString(l) } s.WriteString("\n ]]") } } log.Infoln(s.String()) }
package infrastructure import ( "encoding/json" "fmt" "net/http" "strconv" "time" "github.com/julienschmidt/httprouter" "github.com/michaldziurowski/tech-challenge-time/server/timetracking/usecases" ) const USERID string = "user@domain.com" func HttpHandler() http.Handler { inMemoryStorage := NewInMemoryStorage() dateProvider := NewDateProvider() service := usecases.NewService(inMemoryStorage, inMemoryStorage, dateProvider) router := httprouter.New() router.GET("/ping", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { _, _ = w.Write([]byte("pong")) }) router.POST("/api/v1/sessions", addSession(service)) router.PATCH("/api/v1/sessions/:sessionId", setSessionName(service)) router.POST("/api/v1/sessions/:sessionId/stop", stopSession(service)) router.POST("/api/v1/sessions/:sessionId/resume", resumeSession(service)) router.GET("/api/v1/sessions", getSessions(service)) return router } type addSessionRequest struct { Name string Time time.Time } func addSession(s usecases.Service) func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { decoder := json.NewDecoder(r.Body) var sessionRequest addSessionRequest err := decoder.Decode(&sessionRequest) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } sessionId, _ := s.StartSession(USERID, sessionRequest.Name, sessionRequest.Time) w.Header().Set("Location", fmt.Sprintf("/sessions/%v", sessionId)) w.WriteHeader(http.StatusCreated) } } type setSessionNameRequest struct { NewName string } func setSessionName(s usecases.Service) func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { decoder := json.NewDecoder(r.Body) sessionId, err := strconv.Atoi(p.ByName("sessionId")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } var setNameRequest setSessionNameRequest err = decoder.Decode(&setNameRequest) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } _ = s.SetSessionName(USERID, int64(sessionId), setNameRequest.NewName) w.WriteHeader(http.StatusOK) } } type sessionEventRequest struct { Time time.Time } func stopSession(s usecases.Service) func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { decoder := json.NewDecoder(r.Body) sessionId, err := strconv.Atoi(p.ByName("sessionId")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } var stopRequest sessionEventRequest err = decoder.Decode(&stopRequest) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } _ = s.StopSession(USERID, int64(sessionId), stopRequest.Time) w.WriteHeader(http.StatusOK) } } func resumeSession(s usecases.Service) func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { decoder := json.NewDecoder(r.Body) sessionId, err := strconv.Atoi(p.ByName("sessionId")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } var resumeRequest sessionEventRequest err = decoder.Decode(&resumeRequest) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } _ = s.ResumeSession(USERID, int64(sessionId), resumeRequest.Time) w.WriteHeader(http.StatusOK) } } func getSessions(s usecases.Service) func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { queryValues := r.URL.Query() from, err := time.Parse(time.RFC3339, queryValues.Get("from")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } to, err := time.Parse(time.RFC3339, queryValues.Get("to")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } sessions, err := s.GetSessionsByRange(USERID, from, to) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } sessionsJson, _ := json.Marshal(sessions) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) _, _ = w.Write(sessionsJson) } }
package main import ( "database/sql" "encoding/json" "fmt" _ "github.com/go-sql-driver/mysql" "io/ioutil" "log" "net/http" "strconv" "time" ) type withdrawalData struct { UserId int Alipay string Name string Amount int } type handlCash struct { UserId int Alipay string Name string Amount int CommitTime string Status int } type withdrawJson struct { Code int } type recordData struct { UserId int CommitTime string Status int Amount int } func getWithddraw(userId string, db *sql.DB) ([](map[string]interface{}), bool) { var flag bool = false str_sql := "select status, amount,commitTime from withdrawal where userId=?" rows, err := db.Query(str_sql, userId) if err != nil { log.Println("error info:", err) } defer rows.Close() var status int var amount int var commitTime string slice := make([](map[string]interface{}), 0) for rows.Next() { dataMap := make(map[string]interface{}) err := rows.Scan(&status, &amount, &commitTime) if err != nil { log.Println(err) } t, _ := time.ParseInLocation("2006-01-02 15:04:05", commitTime, time.Local) dataMap["userId"], _ = strconv.Atoi(userId) dataMap["status"] = status dataMap["amount"] = amount dataMap["commitTime"] = t.Unix() if status == 0 { flag = true } log.Println("getEvent-->dataMap:", dataMap) slice = append(slice, dataMap) } return slice, flag } func withdrawal(w http.ResponseWriter, req *http.Request) { //提现请求 retValue := NewBaseJsonData() var data withdrawalData result, _ := ioutil.ReadAll(req.Body) req.Body.Close() json.Unmarshal([]byte(result), &data) log.Println("withdrawalData:", data) userId := strconv.Itoa(data.UserId) alipay := data.Alipay name := data.Name amount := data.Amount flag := checkUserId(userId, Db) if flag { _, b := getWithddraw(userId, Db) if b { retValue.Code = 300 retValue.Message = "have one record about withdrawal" bytes, _ := json.Marshal(retValue) fmt.Fprint(w, string(bytes), "\n") log.Println("还有未审核通过的提现申请") } else { userMap := getUserInfo(userId, Db) log.Println("userMap:", userMap) log.Println("用户提交提现申请事件") total_cash := (int)(userMap["cash"].(float32)) log.Println("用户拥有的总额cash:", total_cash) if amount <= total_cash && amount >= 30 { retValue.Code = 200 retValue.Message = "success" bytes, _ := json.Marshal(retValue) fmt.Fprint(w, string(bytes), "\n") log.Println("在db中插入提现记录") tx, _ := Db.Begin() _, err1 := tx.Exec(`insert withdrawal(userId, alipay, name, status, amount) values(?, ?, ?, ?, ? )`, userId, alipay, name, 0, amount) if err1 != nil { log.Println("error info:", err1) } _, err2 := tx.Exec(`update userInfo set cash = cash- ? where userId = ?`, amount, userId) if err2 != nil { log.Println("error info:", err2) } tx.Commit() } else { retValue.Code = 400 retValue.Message = "failed" bytes, _ := json.Marshal(retValue) fmt.Fprint(w, string(bytes), "\n") } } } else { retValue := `{"code":500,"message":"userId not in db"}` fmt.Fprint(w, retValue, "\n") log.Println("用户未注册userId", userId) } } func withdrawalRcord(w http.ResponseWriter, req *http.Request) { //提现记录接口 req.ParseForm() param_id, _ := req.Form["userId"] userId := param_id[0] slice, _ := getWithddraw(userId, Db) log.Println("提现记录:", slice) bytes, _ := json.Marshal(slice) fmt.Fprint(w, string(bytes), "\n") } func listWithdraw(w http.ResponseWriter, req *http.Request) { tody_date := time.Now() date := tody_date.AddDate(0, 0, -6).Format("2006-01-02 15:04:05") str_sql := `select * from withdrawal where commitTime >= ?` var userId int var alipay string var name string var commitTime string var amount int var status int tx, _ := Db.Begin() defer tx.Commit() rows, err := tx.Query(str_sql, date) if err != nil { log.Println("error info:", err) } defer rows.Close() slice := make([](map[string]interface{}), 0) for rows.Next() { dataMap := make(map[string]interface{}) err := rows.Scan(&userId, &alipay, &name, &commitTime, &status, &amount) if err != nil { log.Println("error info:", err) } dataMap["userId"] = userId dataMap["alipay"] = alipay dataMap["name"] = name dataMap["commitTime"] = commitTime dataMap["status"] = status dataMap["amount"] = amount log.Println("listFeedback-->dataMap:", dataMap) slice = append(slice, dataMap) } bytes, _ := json.Marshal(slice) fmt.Fprint(w, string(bytes), "\n") } func HandleWithdrawal(w http.ResponseWriter, req *http.Request) { //处理客户支付宝提现 log.Println("listen ListWithdrawal ") var data handlCash result, _ := ioutil.ReadAll(req.Body) req.Body.Close() json.Unmarshal([]byte(result), &data) log.Println("HandleWithdrawal withdrawalData:", data) userId := strconv.Itoa(data.UserId) flag := checkUserId(userId, Db) if !flag { str := `{"Code":400,"message:":"userId not in db"}` fmt.Fprint(w, str, "\n") log.Println("用户未注册userId", data.UserId) return } tx, _ := Db.Begin() defer tx.Commit() if data.Status != 1 { sql_str1 := "update withdrawal set status = ? where userID = ? and commitTime = ?" st1, err1 := tx.Exec(sql_str1, 1, userId, data.CommitTime) log.Println("db exec result:", st1, " err info:", err1) //tx.Exec("update userInfo set cash = cash - ? where userId=?", amount, userId) //sql_str2 := "update userInfo set cash= cash- ? where userID = ?" //st2, err2 := tx.Exec(sql_str2, data.Amount, userId) //log.Println("db exec result:", st2, " err info:", err2) if err1 != nil { retValue := NewBaseJsonData() retValue.Code = 300 retValue.Data = 0 retValue.Message = "failed" bytes, _ := json.Marshal(retValue) fmt.Fprint(w, string(bytes), "\n") } else { retValue := NewBaseJsonData() retValue.Code = 200 retValue.Data = 0 retValue.Message = "success" bytes, _ := json.Marshal(retValue) fmt.Fprint(w, string(bytes), "\n") } } else { retValue := NewBaseJsonData() retValue.Code = 600 retValue.Data = 0 retValue.Message = "failed" bytes, _ := json.Marshal(retValue) fmt.Fprint(w, string(bytes), "\n") } }
package injector import ( corev1 "k8s.io/api/core/v1" ) const ( patchPathContainer = "/spec/containers/1" patchPathAnnotation = "/metadata/annotations" ) // PodPatch represents a RFC 6902 patch document for pods. type PodPatch struct { original *corev1.Pod patchOps []*patchOp } // NewPodPatch returns a new instance of PodPatch. func NewPodPatch(pod *corev1.Pod) *PodPatch { return &PodPatch{ original: pod, patchOps: []*patchOp{}, } } func (p *PodPatch) addContainerPatch(container *corev1.Container) { p.patchOps = append(p.patchOps, &patchOp{ Op: "add", Path: patchPathContainer, Value: container, }) } func (p *PodPatch) addAnnotationPatch() { p.patchOps = append(p.patchOps, &patchOp{ Op: "add", Path: patchPathAnnotation, Value: map[string]string{annotationKeySidecarInjection: "false"}, }) } // patchOp represents a RFC 6902 patch operation. type patchOp struct { Op string `json:"op"` Path string `json:"path"` Value interface{} `json:"value",omitempty` }
package config import ( "log" "os" "github.com/joho/godotenv" ) type SpotifyConfig struct { ClientID string SecretKey string } type JwtConfig struct { SecretKey string } type Config struct { Spotify SpotifyConfig Jwt JwtConfig } func Init() *Config { err := godotenv.Load() if err != nil { log.Print("No .env file found") } return &Config{ Spotify: SpotifyConfig{ ClientID: getEnv("SPOTIFY_ID", ""), SecretKey: getEnv("SPOTIFY_SECRET", ""), }, Jwt: JwtConfig{ SecretKey: getEnv("JWT_SECRET", ""), }, } } func getEnv(key string, defaultVal string) string { if value, exists := os.LookupEnv(key); exists { return value } return defaultVal }
package sdk import ( "testing" rmTesting "github.com/brigadecore/brigade/sdk/v3/internal/restmachinery/testing" // nolint: lll "github.com/stretchr/testify/require" ) func TestNewCoreClient(t *testing.T) { client, ok := NewCoreClient( rmTesting.TestAPIAddress, rmTesting.TestAPIToken, nil, ).(*coreClient) require.True(t, ok) require.NotNil(t, client.projectsClient) require.Equal(t, client.projectsClient, client.Projects()) require.NotNil(t, client.eventsClient) require.Equal(t, client.eventsClient, client.Events()) require.NotNil(t, client.substrateClient) require.Equal(t, client.substrateClient, client.Substrate()) }
package main import ( "demo-api-go/api" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/", api.Root) router.Run(":9000") }
package main import ( "context" "encoding/json" "fmt" "golang.org/x/oauth2" "golang.org/x/oauth2/google" "google.golang.org/api/gmail/v1" "io/ioutil" "log" "net/http" "os" "path/filepath" ) const ( ClientSecretFileName = "client_secret.json" CachedTokentFileName = "gmail-access.json" ) // Based on https://developers.google.com/gmail/api/quickstart/go type GmailAuthenticator struct { credentialsDir string ctx context.Context config *oauth2.Config } func NewGmailAuthenticator(appDir string) *GmailAuthenticator { credentialsDir := filepath.Join(appDir, ".credentials") ctx := context.Background() b, err := ioutil.ReadFile(filepath.Join(credentialsDir, ClientSecretFileName)) if err != nil { log.Fatalf("Unable to read client secret file: %v", err) } // If modifying these scopes, delete your previously saved credentials // at ~/.credentials/gmail-go-quickstart.json config, err := google.ConfigFromJSON(b, gmail.GmailModifyScope) if err != nil { log.Fatalf("Unable to parse client secret file to config: %v", err) } return &GmailAuthenticator{credentialsDir: credentialsDir, ctx: ctx, config: config} } // getClient uses a Context and Config to retrieve a Token // then generate a Client. It returns the generated Client. func (a *GmailAuthenticator) getClient() *http.Client { cacheFilePath := filepath.Join(a.credentialsDir, CachedTokentFileName) token, err := a.tokenFromFile(cacheFilePath) if err != nil { token = a.getTokenFromWeb() saveToken(cacheFilePath, token) } return a.config.Client(a.ctx, token) } // getTokenFromWeb uses Config to request a Token. // It returns the retrieved Token. func (a *GmailAuthenticator) getTokenFromWeb() *oauth2.Token { authURL := a.config.AuthCodeURL("state-token", oauth2.AccessTypeOffline) fmt.Printf("Go to the following link in your browser then type the "+ "authorization code: \n%v\n", authURL) var code string if _, err := fmt.Scan(&code); err != nil { log.Fatalf("Unable to read authorization code %v", err) } tok, err := a.config.Exchange(context.TODO(), code) if err != nil { log.Fatalf("Unable to retrieve token from web %v", err) } return tok } func (a *GmailAuthenticator) tokenFromFile(file string) (*oauth2.Token, error) { f, err := os.Open(file) if err != nil { return nil, err } t := &oauth2.Token{} err = json.NewDecoder(f).Decode(t) defer f.Close() return t, err } func saveToken(filePath string, token *oauth2.Token) { fmt.Printf("Saving credential filePath to: %s\n", filePath) f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { log.Fatalf("Unable to cache oauth token: %v", err) } defer f.Close() json.NewEncoder(f).Encode(token) }
package model import "time" // UserDetail 用户详情 type UserDetail struct { Unionid string `json:"unionid"` // 员工在当前开发者企业账号范围内的唯一标识,系统生成,固定值,不会改变 Name string `json:"name"` // 员工名字 Tel string `json:"tel"` // 分机号(仅限企业内部开发调用) WorkPlace string `json:"workPlace"` // 办公地点 Remark string `json:"remark"` // 备注 Mobile string `json:"mobile"` // 手机号码 Email string `json:"email"` // 员工的电子邮箱 OrgEmail string `json:"orgEmail"` // 员工的企业邮箱,如果员工已经开通了企业邮箱,接口会返回,否则不会返回 Active bool `json:"active"` // 是否已经激活,true表示已激活,false表示未激活 OrderInDepts string `json:"orderInDepts"` // 在对应的部门中的排序,Map结构的json字符串,key是部门的Id,value是人员在这个部门的排序值 IsAdmin bool `json:"isAdmin"` // 是否为企业的老板,true表示是,false表示不是 IsLeaderInDepts string `json:"isLeaderInDepts"` // 在对应的部门中是否为主管:Map结构的json字符串,key是部门的Id,value是人员在这个部门中是否为主管,true表示是,false表示不是 IsHide bool `json:"isHide"` // 是否号码隐藏,true表示隐藏,false表示不隐藏 Department []int64 `json:"department"` // 成员所属部门id列表 Position string `json:"position"` // 职位信息 Avatar string `json:"avatar"` // 头像url HiredDate time.Time `json:"hiredDate"` // 入职时间。Unix时间戳 (在OA后台通讯录中的员工基础信息中维护过入职时间才会返回) Jobnumber string `json:"jobnumber"` // 员工工号 IsSenior bool `json:"isSenior"` // 是否是高管 StateCode string `json:"stateCode"` // 国家地区码 Extattr JSON `json:"extattr"` // 扩展属性,可以设置多种属性 // (手机上最多显示10个扩展属性,具体显示哪些属性,请到OA管理后台->设置->通讯录信息设置和OA管理后台->设置->手机端显示信息设置)。 // 该字段的值支持链接类型填写,同时链接支持变量通配符自动替换,目前支持通配符有:userid,corpid。 // 示例: [工位地址](http://www.dingtalk.com?userid=#userid#&corpid=#corpid#) } // UserRoles 用户详情角色 type UserRoles struct { UserDetail Roles []*RoleItem `json:"roles"` // 用户所在角色列表 } // UserItem 成员信息 type UserItem struct { UserID string `json:"userid"` // 员工id Name string `json:"name"` // 成员名称 } // UserItemsList 成员列表 type UserItemsList struct { HasMore bool `json:"hasMore"` // 在分页查询时返回,代表是否还有下一页更多数据 Items []*UserItem `json:"userlist"` // 成员列表 } // UserDetail2 用户详情 type UserDetail2 struct { UserID string `json:"userid"` // Unionid string `json:"unionid"` // 员工在当前开发者企业账号范围内的唯一标识,系统生成,固定值,不会改变 Name string `json:"name"` // 员工名字 Tel string `json:"tel"` // 分机号(仅限企业内部开发调用) WorkPlace string `json:"workPlace"` // 办公地点 Remark string `json:"remark"` // 备注 Mobile string `json:"mobile"` // 手机号码 Email string `json:"email"` // 员工的电子邮箱 OrgEmail string `json:"orgEmail"` // 员工的企业邮箱,如果员工已经开通了企业邮箱,接口会返回,否则不会返回 Active bool `json:"active"` // 是否已经激活,true表示已激活,false表示未激活 Order int64 `json:"order"` // 表示人员在此部门中的排序,列表是按order的倒序排列输出的,即从大到小排列输出的 (钉钉管理后台里面调整了顺序的话order才有值) IsAdmin bool `json:"isAdmin"` // 是否为企业的老板,true表示是,false表示不是 IsBoss bool `json:"isBoss"` // 是否为企业的老板,true表示是,false表示不是 IsLeader bool `json:"isLeader"` // 是否是部门的主管,true表示是,false表示不是 IsHide bool `json:"isHide"` // 是否号码隐藏,true表示隐藏,false表示不隐藏 Department []int64 `json:"department"` // 成员所属部门id列表 Position string `json:"position"` // 职位信息 Avatar string `json:"avatar"` // 头像url HiredDate time.Time `json:"hiredDate"` // 入职时间。Unix时间戳 (在OA后台通讯录中的员工基础信息中维护过入职时间才会返回) Jobnumber string `json:"jobnumber"` // 员工工号 StateCode string `json:"stateCode"` // 国家地区码 Extattr JSON `json:"extattr"` // 扩展属性,可以设置多种属性 // (手机上最多显示10个扩展属性,具体显示哪些属性,请到OA管理后台->设置->通讯录信息设置和OA管理后台->设置->手机端显示信息设置)。 // 该字段的值支持链接类型填写,同时链接支持变量通配符自动替换,目前支持通配符有:userid,corpid。 // 示例: [工位地址](http://www.dingtalk.com?userid=#userid#&corpid=#corpid#) } // UserDetailList 成员列表 type UserDetailList struct { HasMore bool `json:"hasMore"` // 在分页查询时返回,代表是否还有下一页更多数据 Items []*UserDetail2 `json:"userlist"` // 成员列表 } // AdminItem 管理员项 type AdminItem struct { SysLevel int `json:"sys_level"` // 管理员角色,1表示主管理员,2表示子管理员 UserID string `json:"userid"` // 员工id } // User 用户 type User struct { Lang *string `json:"lang"` // 通讯录语言 (默认zh_CN另外支持en_US) UserID *string `json:"userid"` // 员工在当前企业内的唯一标识,也称staffId。可由企业在创建时指定,并代表一定含义比如工号,创建后不可修改,企业内必须唯一。 长度为1~64个字符,如果不传,服务器将自动生成一个userid。 Name *string `json:"name"` // 员工名字 OrderInDepts *JSON `json:"orderInDepts"` // 在对应的部门中的排序, Map结构的json字符串,key是部门的Id, value是人员在这个部门的排序值 Department []*int64 `json:"department"` // 数组类型,数组里面值为整型,成员所属部门id列表 Position *string `json:"position"` // 职位信息 长度为0~64个字符 Mobile *string `json:"mobile"` // 手机号码 Tel *string `json:"tel"` // 分机号(仅限企业内部开发调用) WorkPlace *string `json:"workPlace"` // 办公地点 长度为0~50个字符 Remark *string `json:"remark"` // 备注 长度为0~1000个字符 Email *string `json:"email"` // 员工的电子邮箱 长度为0~64个字符。企业内必须唯一,不可重复 OrgEmail *string `json:"orgEmail"` // 员工的企业邮箱,员工的企业邮箱已开通,才能增加此字段, 否则会报错 Jobnumber *string `json:"jobnumber"` // 员工工号 IsHide *bool `json:"isHide"` // 是否号码隐藏,true表示隐藏,false表示不隐藏 IsSenior *bool `json:"isSenior"` // 是否高管模式, true表示是,false表示不是。 HiredDate *time.Time `json:"hiredDate"` // 入职时间。Unix时间戳 (在OA后台通讯录中的员工基础信息中维护过入职时间才会返回) Extattr *JSON `json:"extattr"` // 扩展属性,可以设置多种属性 // (手机上最多显示10个扩展属性,具体显示哪些属性,请到OA管理后台->设置->通讯录信息设置和OA管理后台->设置->手机端显示信息设置)。 // 该字段的值支持链接类型填写,同时链接支持变量通配符自动替换,目前支持通配符有:userid,corpid。 // 示例: [工位地址](http://www.dingtalk.com?userid=#userid#&corpid=#corpid#) }
/** * @author liangbo * @email liangbogopher87@gmail.com * @date 2017/9/24 20:41 */ package utils import ( "fmt" "strings" "strconv" ) type ErrCode int const ( //需要返回http500的错误码 OKCode ErrCode = 0 InternalErrorCode ErrCode = 1 DbErrCode ErrCode = 2 CacheErrCode ErrCode = 3 DecodeErrCode ErrCode = 4 //400以后禁用 UserNotFoundCode ErrCode = 100 //直接抛给用户的错误码 ParameterErrCode ErrCode = 501 // 参数异常 PhoneRepeatErrCode ErrCode = 502 // 电话号码重复 HighFrequencyErrCode ErrCode = 503 // 验证码请求频率太快 DayMaxTimeErrCode ErrCode = 504 // 验证码每天次数 VerifyCodeWrong ErrCode = 505 // 验证码错误 VerifyCodeSendErrCode ErrCode = 506 // 验证码发送失败 MaxUserError ErrCode = 9999 ) type InternalError struct { Code ErrCode Error_info error } func NewInternalError(code ErrCode, err error) error { //if code < UserNotFoundCode && code > ErrCode(0) { // stack := stack(3) // Logger.Error("PANIC: %v\n%v", err, string(stack)) // CheckError(&InternalError{Code: ErrCode(code), Error_info: err}) //} //panic(err) return &InternalError{Code: ErrCode(code), Error_info: err} } func NewInternalErrorByStr(code ErrCode, err string) error { //if code < UserNotFoundCode && code > ErrCode(0) { // CheckError(&InternalError{Code: ErrCode(code), Error_info: fmt.Errorf(err)}) //} //panic(err) return &InternalError{Code: ErrCode(code), Error_info: fmt.Errorf(err)} } func NewInternalErrByStrDefault(code ErrCode) error { var err_str string //var ok bool //if err_str, ok = ErrStr[code]; !ok { // err_str = fmt.Sprintf("error code is %d", code) //} //if code < UserNotFoundCode && code > ErrCode(0) { // CheckError(&InternalError{Code: ErrCode(code), Error_info: fmt.Errorf(err_str)}) //} //panic(err) return &InternalError{Code: ErrCode(code), Error_info: fmt.Errorf(err_str)} } func (err *InternalError) Error() string { return fmt.Sprintf("%d:%s", err.Code, err.Error_info) } func IsUserErr(original_err error) (bool, int, string) { infos := strings.Split(original_err.Error(), ":") if len(infos) < 2 { return false, 0, infos[0] } code, err := strconv.Atoi(infos[0]) if nil != err { return false, 0, infos[1] } if code >= int(UserNotFoundCode) && code <= int(MaxUserError) { return true, code, infos[1] } return false, 0, infos[1] } func GetErrInfo(original_err error) string { if original_err == nil { return "" } var code int var info string fmt.Sscanf(original_err.Error(), "%d:%s", &code, &info) return info } func GetErrCode(original_err error) ErrCode { if original_err == nil { return 0 } var code int var info string fmt.Sscanf(original_err.Error(), "%d:%s", &code, &info) return ErrCode(code) }
package i18n /* this file only define msgids ,i18n msg content is in ui : ui/src/core/library/locale */ const ServerInternalError = "error.serverInternal" const BadRequestData = "error.badRequestData" const NoPermission = "error.noPermission" const TeamNotExist = "error.teamNotExist" const UserNotExist = "error.userNotExist" const PasswordIncorrect = "error.passwordIncorrect" const FolderNotExist = "error.folderNotExist" const TargetAlreadyExist = "error.targetAlreadyExist" const UserNameOrPasswordEmpty = "error.userNameOrPasswordEmpty" const TeamAlreadyExist = "error.teamAlreadyExist"
// Package main - package main import ( "fmt" "github.com/shanehowearth/concurrency_in_go/pipeline" ) func main() { done := make(chan interface{}) defer close(done) intStream := pipeline.Generator(done, 1, 2, 3, 4) p := pipeline.Multiply(done, pipeline.Add(done, pipeline.Multiply(done, intStream, 2), 1), 2) for v := range p { fmt.Println(v) } }
package main import ( "log" ) func hanoi(l []int,x,y,z string){ length := len(l) if length == 1{ log.Printf("move %d from %s to %s",l[0],x,z) }else{ hanoi(l[:length-1],x,z,y) log.Printf("move %d from %s to %s",l[length-1],x,z) hanoi(l[:length-1],y,x,z) } } func main(){ l := []int{1,2,3,4,5,6,7} hanoi(l,"x","y","z") log.Println("check") l2 := []int{1,2,3,4} hanoi(l2,"x","y","z") }
/* * Copyright (c) 2018 Juniper Networks, Inc. All rights reserved. * * file: run_test.go * details: Deals with the setup and teardown for Unit Tests for msghandler package * */ package msghandler import ( "log" "os" "testing" opts "github.com/Juniper/collector/flow-translator/options" ) func VerifyError(name string, t *testing.T, expected interface{}, result interface{}) { if expected != result { t.Errorf("%s failed, expected '%v', got '%v'", name, expected, result) } } func setup() { InitMockData() opts.Verbose = true opts.Logger = log.New(os.Stderr, "[jFlow] ", log.Ldate|log.Ltime) } func shutdown(retCode int) { log.Println("Test Done!!!") os.Exit(retCode) } func TestMain(m *testing.M) { setup() retCode := m.Run() shutdown(retCode) }
package processes import ( "os/exec" ) type Worker interface { Kill() GetStopChan() chan bool } type worker struct { killWorkersChan chan bool killWaitChan chan bool stopChan chan bool } func (w *worker) Kill() { w.killWorkersChan <- true <-w.killWaitChan } func (w *worker) GetStopChan() chan bool { return w.stopChan } func Run(cmd string, args ...string) (Worker, error) { w := &worker{make(chan bool, 1), make(chan bool, 1), make(chan bool, 1)} errChan := make(chan error, 1) go func() { command := exec.Command(cmd, args...) waitChan := make(chan error) err := command.Start() errChan <- err if err != nil { return } go func() { for { select { case <-w.killWorkersChan: command.Process.Kill() case err := <-waitChan: w.stopChan <- err == nil w.killWaitChan <- true break } } }() waitChan <- command.Wait() }() return w, <-errChan }
//+build linux,arm package main import ( "net" "os" ) var ( hostname string addr string ) func initService() { hostname, _ = os.Hostname() if hostname == "" { hostname = "RaspberryPi" } hostname += ":" if conn, err := net.Dial("udp", "google.com:80"); err != nil { addr = "127.0.0.1" } else { addr = conn.LocalAddr().String() for i := 0; i < len(addr); i++ { if addr[i] == ':' { addr = addr[:i] break } } } }
package main import ( "flag" "fmt" "log" "net/http" "github.com/shvetsiya/distribkv/db" ) var ( dbLocation = flag.String("db-location", "", "The path to bold db") httpAddr = flag.String("http-addr", "127.0.0.1:8080", "http host and port") ) func parseFlags() { flag.Parse() if *dbLocation == "" { log.Fatal("must provide db location") } } func main() { parseFlags() db, close, err := db.NewDatabase(*dbLocation) if err != nil { log.Fatalf("NewDatabase(%q): v", *dbLocation, err) } defer close() http.HandleFunc("/get", func(w http.ResponseWriter, r *http.Request) { r.ParseForm() key := r.Form.Get("key") value, err := db.GetKey(key) fmt.Fprintf(w, "Value = %q, err = %v\n", value, err) }) http.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) { r.ParseForm() key := r.Form.Get("key") value := r.Form.Get("value") err := db.SetKey(key, []byte(value)) fmt.Fprintf(w, "Error = %v\n", err) }) log.Fatal(http.ListenAndServe(*httpAddr, nil)) }
package beacon import ( "bytes" "crypto/sha256" "encoding/binary" "encoding/json" "errors" "path" "sync" bolt "github.com/coreos/bbolt" "github.com/nikkolasg/slog" ) // store contains all the definitions and implementation of the logic that // stores and loads beacon signatures. At the moment of writing, it consists of // a boltdb key/value database store. // Beacon holds the randomness as well as the info to verify it. type Beacon struct { // PreviousSig is the previous signature generated PreviousSig []byte // Round is the round number this beacon is tied to Round uint64 // Signature is the BLS deterministic signature over Round || PreviousRand Signature []byte } // GetSignature returns the signature of this beacon. Needed for // retro-compatibility func (b *Beacon) GetSignature() []byte { return b.Signature } // GetPreviousSig returns the signature of the previous beacon. Needed for // retro-compatibility. func (b *Beacon) GetPreviousSig() []byte { return b.PreviousSig } // Message returns a slice of bytes as the message to sign or to verify // alongside a beacon signature. func Message(prevSig []byte, round uint64) []byte { var buff bytes.Buffer buff.Write(roundToBytes(round)) buff.Write(prevSig) h := sha256.New() h.Write(buff.Bytes()) return h.Sum(nil) } // Store is an interface to store Beacons packets where they can also be // retrieved to be delivered to end clients. type Store interface { Len() int Put(*Beacon) error Last() (*Beacon, error) Get(round uint64) (*Beacon, error) // XXX Misses a delete function Close() } // boldStore implements the Store interface using the kv storage boltdb (native // golang implementation). Internally, Beacons are stored as JSON-encoded in the // db file. type boltStore struct { sync.Mutex db *bolt.DB len int } var bucketName = []byte("beacons") // BoltFileName is the name of the file boltdb writes to const BoltFileName = "drand.db" // NewBoltStore returns a Store implementation using the boltdb storage engine. func NewBoltStore(folder string, opts *bolt.Options) (Store, error) { dbPath := path.Join(folder, BoltFileName) db, err := bolt.Open(dbPath, 0660, opts) if err != nil { return nil, err } // create the bucket already err = db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists(bucketName) return err }) return &boltStore{ db: db, }, err } func (b *boltStore) Len() int { return b.len } func (b *boltStore) Close() { if err := b.db.Close(); err != nil { slog.Debugf("boltdb store: %s", err) } slog.Debugf("beacon: boltdb store closed.") } // Put implements the Store interface. WARNING: It does NOT verify that this // beacon is not already saved in the database or not. func (b *boltStore) Put(beacon *Beacon) error { err := b.db.Update(func(tx *bolt.Tx) error { bucket := tx.Bucket(bucketName) key := roundToBytes(beacon.Round) buff, err := json.Marshal(beacon) if err != nil { return err } return bucket.Put(key, buff) }) if err != nil { return err } b.Lock() b.len++ b.Unlock() return nil } // ErrNoBeaconSaved is the error returned when no beacon have been saved in the // database yet. var ErrNoBeaconSaved = errors.New("no beacon saved in db") // Last returns the last beacon signature saved into the db func (b *boltStore) Last() (*Beacon, error) { var beacon *Beacon err := b.db.Update(func(tx *bolt.Tx) error { bucket := tx.Bucket(bucketName) cursor := bucket.Cursor() _, v := cursor.Last() if v == nil { return ErrNoBeaconSaved } b := &Beacon{} if err := json.Unmarshal(v, b); err != nil { return err } beacon = b return nil }) return beacon, err } // Get returns the beacon saved at this round func (b *boltStore) Get(round uint64) (*Beacon, error) { var beacon *Beacon err := b.db.Update(func(tx *bolt.Tx) error { bucket := tx.Bucket(bucketName) v := bucket.Get(roundToBytes(round)) if v == nil { return ErrNoBeaconSaved } b := &Beacon{} if err := json.Unmarshal(v, b); err != nil { return err } beacon = b return nil }) return beacon, err } type cbStore struct { Store cb func(*Beacon) } // NewCallbackStore returns a Store that calls the given callback in a goroutine // each time a new Beacon is saved into the given store. It does not call the // callback if there has been any errors while saving the beacon. func NewCallbackStore(s Store, cb func(*Beacon)) Store { return &cbStore{Store: s, cb: cb} } func (c *cbStore) Put(b *Beacon) error { if err := c.Store.Put(b); err != nil { return err } go c.cb(b) return nil } func roundToBytes(r uint64) []byte { var buff bytes.Buffer binary.Write(&buff, binary.BigEndian, r) return buff.Bytes() }
package main import ( "fmt" "os" "golang.org/x/sys/unix" ) func do_bind_mount(s, t string) error { err := unix.Mount(s, t, "", unix.MS_BIND, "") if err != nil { fmt.Printf("bind-mount error received: %v\n", err) return err } return nil } func do_remount_ro(s, t string) error { err := unix.Mount(s, t, "", unix.MS_BIND|unix.MS_REMOUNT|unix.MS_RDONLY, "") if err != nil { fmt.Printf("RO remount error received: %v\n", err) return err } return nil } func do_remount_rw(s, t string) error { err := unix.Mount(s, t, "", unix.MS_BIND|unix.MS_REMOUNT, "") if err != nil { fmt.Printf("RW remount error received: %v\n", err) return err } return nil } func usage() { fmt.Printf("\nUsage: mount_syscall <bind | ro-remount | rw-remount> <source> <target>\n\n") } func main() { args := os.Args[1:] if len(args) != 3 { fmt.Printf("\nNumber of arguments received: %d, expected: %d\n", len(args), 3) usage() os.Exit(1) } var err error if args[0] == "bind" { err = do_bind_mount(args[1], args[2]) } else if args[0] == "ro-remount" { err = do_remount_ro(args[1], args[2]) } else if args[0] == "rw-remount" { err = do_remount_rw(args[1], args[2]) } else { fmt.Printf("Unsupported command option: %s\n", args[0]) err = fmt.Errorf("Unsupported command option: %s", args[0]) } if err != nil { os.Exit(1) } }
// Copyright 2018, 2021 Tamás Gulácsi. All rights reserved. // // SPDX-License-Identifier: Apache-2.0 package plsqlparser import ( "fmt" "log" "strings" "unicode" plsql "github.com/UNO-SOFT/plsql-parser/plsql" "github.com/antlr/antlr4/runtime/Go/antlr" ) //go:generate mkdir -p plsql //go:generate sh -c "[ -e antlr-4.9.2-complete.jar ] || wget https://www.antlr.org/download/antlr-4.9.2-complete.jar" //go:generate sh -c "[ -e PlSqlLexer.g4 ] || wget https://github.com/antlr/grammars-v4/raw/master/sql/plsql/PlSqlLexer.g4" //go:generate sh -c "[ -e PlSqlParser.g4 ] || wget https://github.com/antlr/grammars-v4/raw/master/sql/plsql/PlSqlParser.g4" //go:generate java -jar antlr-4.9.2-complete.jar -Dlanguage=Go -o plsql/ PlSqlLexer.g4 PlSqlParser.g4 //go:generate sed -i -e "s/self\\./p./; s/PlSqlLexerBase/PlSqlBaseLexer/" plsql/plsql_lexer.go //go:generate sed -i -e "s/self\\./p./; s/p\\.isVersion/p.IsVersion/; s/PlSqlParserBase/PlSqlBaseParser/" plsql/plsql_parser.go //go:generate sh -c "[ -e ./plsql/plsql_base_lexer.go ] || curl https://github.com/antlr/grammars-v4/raw/master/sql/plsql/Go/plsql_base_lexer.go | sed -e '/self/d; /input/ s/l\\.input/l.GetInputStream()/' >plsql/plsql_base_lexer.go" //go:generate sh -c "[ -e ./plsql/plsql_base_parser.go ] || (cd plsql && wget https://github.com/antlr/grammars-v4/raw/master/sql/plsql/Go/plsql_base_parser.go)" type ( ErrorListener = antlr.ErrorListener Tree = antlr.Tree ) // Export functionality of plsql package. var ( // NewPlSqlLexer is a copy of plsql.NewPlSqlLexer NewPlSqlLexer = plsql.NewPlSqlLexer // NewPlSqlParser is a copy of plsql.NewPlSqlParser NewPlSqlParser = plsql.NewPlSqlParser ) // NewPlSqlStringLexer returns a new *PlSqlLexer with an input stream set to the given text. func NewPlSqlStringLexer(text string) *plsql.PlSqlLexer { return plsql.NewPlSqlLexer(antlr.NewInputStream(text)) } // NewPlSqlLexerParser returns a new *PlSqlParser, including a PlSqlLexer with the given text. func NewPlSqlLexerParser(text string) *plsql.PlSqlParser { input := antlr.NewInputStream(text) if input == nil { panic("input is nil") } lexer := plsql.NewPlSqlLexer(input) stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel) // Create the Parser parser := plsql.NewPlSqlParser(stream) parser.BuildParseTrees = true return parser } // NewPlSqlParserListener returns a *BaseWalkListener with the DefaultErrorListener set. func NewPlSqlParserListener() *BaseWalkListener { return &BaseWalkListener{DefaultErrorListener: antlr.NewDefaultErrorListener()} } // ParseToConvertMap parses the text into a ConvertMap (INSERT INTO with SELECT statements only). func ParseToConvertMap(text string) (ConvertMap, error) { // Setup the input (which this parser expects to be uppercased). text = strings.TrimPrefix(upper(strings.TrimSpace(text)), "INSERT ") parser := NewPlSqlLexerParser(text) // Finally walk the tree wl := &iiWalkListener{BaseWalkListener: BaseWalkListener{DefaultErrorListener: antlr.NewDefaultErrorListener()}} parser.AddErrorListener(wl) tree := parser.Single_table_insert() antlr.ParseTreeWalkerDefault.Walk(wl, tree) if wl.Err == nil { return wl.ConvertMap, nil } return wl.ConvertMap, fmt.Errorf("%s: %w", text, wl.Err) } // BaseWalkListener is a minimal Walk Listener. type BaseWalkListener struct { *plsql.BasePlSqlParserListener *antlr.DefaultErrorListener Ambiguity [][2]int Err *Errors } // Walk the given Tree, with the optional parser's ErrorListener set to wl. func (wl *BaseWalkListener) Walk(tree Tree, parser interface{ AddErrorListener(ErrorListener) }) error { if parser != nil { parser.AddErrorListener(wl) } antlr.ParseTreeWalkerDefault.Walk(wl, tree) return wl.Err } func (wl *BaseWalkListener) AddError(err error) { if err != nil { if wl.Err == nil { wl.Err = new(Errors) } wl.Err.Append(err) } } //func (wl *BaseWalkListener) EnterEveryRule(ctx antlr.ParserRuleContext) { //fmt.Println("ENTER", ctx.GetStart()) //} //func (wl *BaseWalkListener) ExitEveryRule(ctx antlr.ParserRuleContext) { //fmt.Println("EXIT", ctx.GetStop()) //} type iiWalkListener struct { BaseWalkListener ConvertMap enterSelect antlr.Token } func (wl *iiWalkListener) ReportAmbiguity(recognizer antlr.Parser, dfa *antlr.DFA, startIndex, stopIndex int, exact bool, ambigAlts *antlr.BitSet, configs antlr.ATNConfigSet) { //log.Printf("AMBIGUITY at %d:%d", startIndex, stopIndex) wl.Ambiguity = append(wl.Ambiguity, [2]int{startIndex, stopIndex}) } func (wl *iiWalkListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol interface{}, line, column int, msg string, e antlr.RecognitionException) { wl.AddError(fmt.Errorf("%d:%d: %s (%v): %w", line, column, msg, e, wl.Err)) } func (wl *iiWalkListener) ExitExpressions(ctx *plsql.ExpressionsContext) { if wl.Values != nil { return } for _, expr := range ctx.AllExpression() { wl.Values = append(wl.Values, tokenChunk(expr)) } } func (wl *iiWalkListener) ExitInsert_into_clause(ctx *plsql.Insert_into_clauseContext) { wl.InsertInto = ctxChunk(ctx) if wl.Table != "" { return } wl.Table = ctx.General_table_ref().GetText() for _, col := range ctx.INTO().GetChildren() { log.Printf("col: %s %#v", col, col) //wl.Fields = append(wl.Fields, tokenChunk(col.GetPayload())) } } func ctxChunk(ctx interface { GetStart() antlr.Token GetStop() antlr.Token }) Chunk { t := Chunk{Start: ctx.GetStart().GetStart(), Stop: ctx.GetStop().GetStop()} t.Text = ctx.GetStart().GetInputStream().GetText(t.Start, t.Stop) return t } func tokenChunk(token interface { GetStart() antlr.Token GetStop() antlr.Token GetText() string }) Chunk { return Chunk{Start: token.GetStart().GetStart(), Stop: token.GetStop().GetStop(), Text: token.GetText()} } func (wl *iiWalkListener) ExitSelect_list_elements(ctx *plsql.Select_list_elementsContext) { if ctx.GetStart() == nil || ctx.GetStop() == nil || ctx.GetStart().GetInputStream() == nil { return } if wl.Select == nil { wl.Select = &selectStmt{} } else if wl.Select.From != nil { return } defer func() { if r := recover(); r != nil { if err, ok := r.(error); ok && err != nil { wl.AddError(err) } } }() t := ctxChunk(ctx) wl.Select.Values = append(wl.Select.Values, t) if strings.HasPrefix(t.Text, "CASE ") { if i := strings.LastIndexByte(t.Text, ' '); i >= 0 && strings.HasSuffix(t.Text[:i], "END") { t.Text = t.Text[i+1:] } } wl.Select.Aliases = append(wl.Select.Aliases, t) } func (wl *iiWalkListener) EnterSelect_statement(ctx *plsql.Select_statementContext) { if wl.enterSelect == nil { wl.enterSelect = ctx.GetStart() } } func (wl *iiWalkListener) ExitSelect_statement(ctx *plsql.Select_statementContext) { if wl.Select == nil { wl.Select = &selectStmt{} } wl.Select.Chunk = Chunk{Start: wl.enterSelect.GetStart(), Stop: ctx.GetStop().GetStop()} wl.Select.Text = ctx.GetStart().GetInputStream().GetText(wl.Select.Chunk.Start, wl.Select.Chunk.Stop) } func (wl *iiWalkListener) ExitColumn_alias(ctx *plsql.Column_aliasContext) { wl.Select.Aliases[len(wl.Select.Aliases)-1] = ctxChunk(ctx) } func (wl *iiWalkListener) ExitFrom_clause(ctx *plsql.From_clauseContext) { if wl.Select == nil { wl.Select = &selectStmt{} } else if wl.Select.From != nil { return } wl.Select.From = []TableWithAlias{} // not nil for _, tbl := range ctx.Table_ref_list().(*plsql.Table_ref_listContext).AllTable_ref() { tbl := tbl.(*plsql.Table_refContext) aux := tbl.Table_ref_aux().(*plsql.Table_ref_auxContext) name := aux.Table_ref_aux_internal().GetText() var alias string if a := aux.Table_alias(); a != nil { alias = a.GetText() } wl.Select.From = append(wl.Select.From, TableWithAlias{Table: name, Alias: alias}) } } func upper(text string) string { var inString bool return strings.Map(func(r rune) rune { if r == '\'' { inString = !inString return r } if inString { return r } return unicode.ToUpper(r) }, text) } var _ = error((*Errors)(nil)) // Errors implements the "error" interface, and holds several errors. type Errors struct { slice []error } func (es *Errors) Append(err error) { if err != nil { es.slice = append(es.slice, err) } } func (es *Errors) Error() string { if es == nil || len(es.slice) == 0 { return "" } var buf strings.Builder var notFirst bool for _, e := range es.slice { if e == nil { continue } if notFirst { buf.WriteByte('\n') } else { notFirst = true } buf.WriteString(e.Error()) } return buf.String() }
package kfdef import ( "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" ) const ( // KubeflowLabel represents Label for kfctl deployed resource KubeflowLabel = "app.kubernetes.io/managed-by" ) var ( // watchedResources contains all resources we will watch and reconcile when changed watchedResources = []schema.GroupVersionKind{ {Group: "apps", Version: "v1", Kind: "StatefulSet"}, {Group: "apps", Version: "v1", Kind: "Deployment"}, {Group: "apps", Version: "v1", Kind: "DaemonSet"}, {Group: "extensions", Version: "v1beta1", Kind: "Ingress"}, {Group: "extensions", Version: "v1beta1", Kind: "Deployment"}, {Group: "", Version: "v1", Kind: "Service"}, {Group: "", Version: "v1", Kind: "ConfigMap"}, {Group: "", Version: "v1", Kind: "PersistentVolumeClaim"}, {Group: "", Version: "v1", Kind: "Secret"}, {Group: "", Version: "v1", Kind: "ServiceAccount"}, {Group: "rbac.authorization.k8s.io", Version: "v1beta1", Kind: "RoleBinding"}, {Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "RoleBinding"}, {Group: "rbac.authorization.k8s.io", Version: "v1beta1", Kind: "Role"}, {Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "Role"}, {Group: "admissionregistration.k8s.io", Version: "v1beta1", Kind: "MutatingWebhookConfiguration"}, {Group: "admissionregistration.k8s.io", Version: "v1beta1", Kind: "ValidatingWebhookConfiguration"}, {Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRole"}, {Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRoleBinding"}, {Group: "apiextensions.k8s.io", Version: "v1beta1", Kind: "CustomResourceDefinition"}, } // kfdefUIDMap maps the UID to KfDef Name kfdefUIDMap = map[types.UID]types.NamespacedName{} )
package main import ( "time" "github.com/henrylee2cn/teleport" ) func main() { teleport.GraceSignal() teleport.SetShutdown(time.Second*20, nil, nil) var cfg = &teleport.PeerConfig{ ReadTimeout: time.Minute * 3, WriteTimeout: time.Minute * 3, TlsCertFile: "", TlsKeyFile: "", SlowCometDuration: time.Millisecond * 500, DefaultCodec: "json", DefaultGzipLevel: 5, PrintBody: false, } var peer = teleport.NewPeer(cfg) peer.PushRouter.Reg(new(Push)) { var sess, err = peer.Dial("127.0.0.1:9090", "simple_server:9090") if err != nil { teleport.Panicf("%v", err) } var reply interface{} var pullcmd = sess.Pull( "/group/home/test?peer_id=client9090", map[string]interface{}{"conn_port": 9090}, &reply, ) if pullcmd.Xerror != nil { teleport.Fatalf("pull error: %v", pullcmd.Xerror.Error()) } teleport.Infof("9090reply: %#v", reply) } { var sess, err = peer.Dial("127.0.0.1:9091") if err != nil { teleport.Panicf("%v", err) } var reply interface{} var pullcmd = sess.Pull( "/group/home/test_unknown?peer_id=client9091", map[string]interface{}{"conn_port": 9091}, &reply, ) if pullcmd.Xerror != nil { teleport.Fatalf("pull error: %v", pullcmd.Xerror.Error()) } teleport.Infof("9091reply test_unknown: %#v", reply) } } // Push controller type Push struct { teleport.PushCtx } // Test handler func (p *Push) Test(args *map[string]interface{}) { teleport.Infof("receive push(%s):\nargs: %#v\nquery: %#v\n", p.Ip(), args, p.Query()) }
package pbengine import ( "bytes" "log" "os" "strings" "text/template" "github.com/vanishs/gwsrpc/swg" ) const tempgwsrpclits = `'use strict'; /// <reference path="../../typings/index.d.ts"/> {{ range $key, $value := .FileDatas }}/// <reference path="./{{$value.PackageName}}/{{$value.PackageName}}.d.ts"/> {{ end }} import uws from 'umdwebsocket'; import ProtoBuf from 'protobufjs'; export type OnOpenCallback = () => void; export type OnCloseCallback = () => void; {{ range $key, $value := .FileDatas }}export interface IMSG{{$value.PackageName}} { OnServiceRestart(): void; } {{ end }} export class GwsrpcStream<T> { constructor(private rpccall: RPCCALL) { } recv(): Promise<T> { return new Promise((resolve, reject) => { this.rpccall.resolve = resolve; this.rpccall.reject = reject; }); } } enum RPCSTATUS { OK = 0, ERR, CLOSE, } export class RPCCALL { resolve: any; reject: any; to: any; rpcid: number; stream: any;//GwsrpcStream } export class GwsrpCli { {{ range $key, $value := .FileDatas }}public Builder{{$value.PackageName}}: {{$value.PackageName}}.ProtoBufBuilder; {{ end }} {{ range $key, $value := .FileDatas }}private _{{$value.PackageName}}ServiceID: string = ''; {{ end }} {{ range $key, $value := .FileDatas }}private _MSG{{$value.PackageName}}: IMSG{{$value.PackageName}}; {{ end }} private _isConnect: boolean = false; private _printable: string = '{{.Js94Char}}'; private _zeroSizeArrayBuffer: ArrayBuffer; private _processid: string; private _rpccall: any; // key=string value=RPCCALL private _onOpen: OnOpenCallback; private _onClose: OnCloseCallback; private _ws: uws; // private _PopoInterval; {{ range $key, $value := .FileDatas }}private _{{$value.PackageName}}PROTO: string = {{$value.PbPROTObackquote}}; {{ end }} constructor() { this.sendRPCStream; this._rpccall = {}; this._zeroSizeArrayBuffer = new ArrayBuffer(0); this._processid = this.idgen(); {{ range $key, $value := .FileDatas }}this.Builder{{$value.PackageName}} = <{{$value.PackageName}}.ProtoBufBuilder><any>ProtoBuf.loadProto(this._{{$value.PackageName}}PROTO).build('{{$value.PackageName}}'); {{ end }} }; connect(addr: string, reconnectMaxTimeS: number, {{ range $key, $value := .FileDatas }}MSG{{$value.PackageName}}: IMSG{{$value.PackageName}}, {{ end }} onOpen: OnOpenCallback, onClose: OnCloseCallback) { this._onOpen = onOpen; this._onClose = onClose; {{ range $key, $value := .FileDatas }}this._MSG{{$value.PackageName}} = MSG{{$value.PackageName}}; {{ end }} this._ws = new uws(addr, 'V2', reconnectMaxTimeS, (data) => { this.onMessage(<ArrayBuffer>data); }, () => { this.onOpen(); }, () => { this.onClose(); }, () => { this.onError(); } ); // this._PopoInterval = setInterval(() => { // if (this._isConnect === true) { // let ab = this.makeArrayBuffer(65535, this._processid, this._zeroSizeArrayBuffer); // this._ws.send(ab); // } // }, 30 * 1000); } {{ range $key, $value := .FileDatas }}{{ range $key2, $value2 := $value.RPCDatas }}// {{$value2.Comment}} {{if eq $value2.Gwstype 0}}{{$value2.Name}}(argrequest: {{$value.PackageName}}.{{$value2.In}}Message, timeoutMs: number): Promise<{{$value.PackageName}}.{{$value2.Out}}> { return new Promise((resolve, reject) => { let buf = argrequest.toArrayBuffer(); this.sendRPC({{$value2.Index}}, buf, timeoutMs, resolve, reject); }); } {{ end }} {{if eq $value2.Gwstype 1}}{{$value2.Name}}(argrequest: {{$value.PackageName}}.{{$value2.In}}Message, timeoutMs: number): Promise<GwsrpcStream<{{$value.PackageName}}.{{$value2.Out}}>> { return new Promise((resolve, reject) => { let buf = argrequest.toArrayBuffer(); this.sendRPCStream({{$value2.Index}}, buf, timeoutMs, resolve, reject); }); } {{ end }} {{ end }}{{ end }} private sendRPC(rpcid: number, buf: ArrayBuffer, toMs: number, resolve, reject: any) { if (this._isConnect === false) { reject("ws is disconnect:rpcid:"+rpcid); return; } let id = this.idgen(); let to: any = null; if(0!==toMs){ to = setTimeout(() => { if (id in this._rpccall) { this._ws.reset(); } }, toMs); } let rc = new RPCCALL; rc.resolve = resolve; rc.reject = reject; rc.to = to; rc.rpcid = rpcid; rc.stream = null; this._rpccall[id] = rc; let ab = this.makeArrayBuffer(rpcid, id, buf); this._ws.send(ab); } private sendRPCStream(rpcid: number, buf: ArrayBuffer, toMs: number, resolve, reject: any) { if (this._isConnect === false) { reject("ws is disconnect:rpcid:" + rpcid); return; } let id = this.idgen(); let to: any = null; if(0!==toMs){ to = setTimeout(() => { if (id in this._rpccall) { this._ws.reset(); } }, toMs); } let rc = new RPCCALL; rc.resolve = null; rc.reject = null; rc.to = to; rc.rpcid = rpcid; rc.stream = new GwsrpcStream(rc); this._rpccall[id] = rc; let ab = this.makeArrayBuffer(rpcid, id, buf); this._ws.send(ab); resolve(rc.stream); } private idgen(): string { let text = ''; for (let i = 0; i < 20; i++) { text += this._printable.charAt(Math.floor(Math.random() * this._printable.length)); } return text; } private ascii2bytearray(str: string, bytearray: Uint8Array) { for (let i = 0, strLen = str.length; i < strLen; i++) { bytearray[i] = str.charCodeAt(i); } } private bytearray2ascii(bytearray: Uint8Array) { let str = ''; for (let i = 0, bufLen = bytearray.length; i < bufLen; i++) { str = str.concat(String.fromCharCode(bytearray[i])); } return str; } private makeArrayBuffer(cmd: number, seq: string, payload: ArrayBuffer): ArrayBuffer { let ab = new ArrayBuffer(22 + payload.byteLength); let cmd2ua = new Uint16Array(ab, 0, 1); let seq2ua = new Uint8Array(ab, 2, 20); cmd2ua[0] = cmd; this.ascii2bytearray(seq, seq2ua); if (0 !== payload.byteLength) { let payload2ua = new Uint8Array(payload); let ab2ua2move = new Uint8Array(ab, 22, payload.byteLength); ab2ua2move.set(payload2ua); } return ab; } private addSpace(str: string, length: number) { return new Array(length - str.length + 1).join(' ') + str; } private onMessage(buf: ArrayBuffer) { let cmd = new Uint8Array(buf, 0, 1); let seq = new Uint8Array(buf, 1, 20); let seqStr = this.bytearray2ascii(seq); if (255 === cmd[0]) { // cmd=255 ServiceRestart let serviceID = new Uint8Array(buf, 21, 20); let serviceIDstr = this.bytearray2ascii(serviceID); {{ range $key, $value := .FileDatas }}if (seqStr === this.addSpace('{{$value.PackageName}}', 20)) { if (this._{{$value.PackageName}}ServiceID !== serviceIDstr) { this._{{$value.PackageName}}ServiceID = serviceIDstr; this._MSG{{$value.PackageName}}.OnServiceRestart(); } return; } {{ end }} return; } else { if (seqStr in this._rpccall) { let rc = <RPCCALL>this._rpccall[seqStr]; let s; switch (rc.rpcid) { {{ range $key, $value := .FileDatas }}{{ range $key2, $value2 := $value.RPCDatas }}case {{$value2.Index}}: s = this.Builder{{$value.PackageName}}.{{$value2.Out}}.decode(buf.slice(21)); break; {{ end }}{{ end }} } if (RPCSTATUS.OK === cmd[0]) { if (null === rc.stream) { if(null!==rc.to){clearTimeout(rc.to);} delete this._rpccall[seqStr]; } if (rc.resolve !== null) { rc.resolve(s); rc.resolve = null; rc.reject = null; } } else if (RPCSTATUS.CLOSE === cmd[0]) { if(null!==rc.to){clearTimeout(rc.to);} delete this._rpccall[seqStr]; if (rc.resolve !== null) { rc.resolve(null); rc.resolve = null; rc.reject = null; } } else { if(null!==rc.to){clearTimeout(rc.to);} delete this._rpccall[seqStr]; if (rc.reject !== null) { rc.reject("gwsrpc recv err:rpcid:" + rc.rpcid); rc.resolve = null; rc.reject = null; } } } } } private onOpen() { let ab = this.makeArrayBuffer(65535, this._processid, this._zeroSizeArrayBuffer); this._ws.send(ab); this._isConnect = true; this._onOpen(); } private onError() { // } private onClose() { for (let index in this._rpccall) { if (this._rpccall[index].to !== null) { clearTimeout(this._rpccall[index].to); } if (this._rpccall[index].reject != null) { this._rpccall[index].reject("websocket disconnect!"); } } this._rpccall={}; if (false === this._isConnect) { return; } this._isConnect = false; this._onClose(); } } ` func gwsrpclits(newfn string) { t := template.New("t1") t, _ = t.Parse(tempgwsrpclits) f, err := os.OpenFile(newfn, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) if err != nil { log.Fatalln(err) } defer f.Close() var doc bytes.Buffer err = t.Execute(&doc, swg.Top) if err != nil { log.Fatalln(err) } str := doc.String() str = strings.Replace(str, "\n \n", "\n", -1) str = strings.Replace(str, "\n \n", "\n", -1) str = strings.Replace(str, "\n \n", "\n", -1) str = strings.Replace(str, "\n \n", "\n", -1) str = strings.Replace(str, "\n \n", "\n", -1) str = strings.Replace(str, "\n \n", "\n", -1) str = strings.Replace(str, "\n \n", "\n", -1) str = strings.Replace(str, "\n\t\n", "\n", -1) str = strings.Replace(str, "\n\t\t\n", "\n", -1) str = strings.Replace(str, "\n\t\t\t\n", "\n", -1) str = strings.Replace(str, "\n\t\t\t\t\t\n", "\n", -1) str = strings.Replace(str, "\n\t\t\t\t\t\t\n", "\n", -1) f.Write([]byte(str)) }
package pagerduty_test import ( "fmt" . "github.com/danryan/go-pagerduty/pagerduty" "net/http" "reflect" "testing" ) func TestUser_marshal(t *testing.T) { testJSONMarshal(t, &User{}, "{}") u := &User{ ID: "ABCDEF", Name: "Bill Williams", Email: "bill.williams@example.com", UserURL: "/users/ABCDEF", ContactMethods: []Contact{ Contact{ ID: "PNB9UG1", Label: "Mobile", Address: "4072559655", UserID: "PSXBF4M", Type: "SMS", CountryCode: 1, PhoneNumber: "4072559655", Enabled: true, }, }, } want := `{ "id": "ABCDEF", "name": "Bill Williams", "email": "bill.williams@example.com", "user_url": "/users/ABCDEF", "contact_methods" : [ { "id": "PNB9UG1", "label": "Mobile", "address": "4072559655", "user_id": "PSXBF4M", "type": "SMS", "country_code": 1, "phone_number": "4072559655", "enabled": true } ] }` testJSONMarshal(t, u, want) } func TestUsersService_Get(t *testing.T) { setup() defer teardown() mux.HandleFunc("/users/u", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") fmt.Fprint(w, `{"id": "ABCDEF"}`) }) user, _, err := client.Users.Get("u") if err != nil { t.Errorf("Users.Get returned error: %v", err) } want := &User{ID: "ABCDEF"} if !reflect.DeepEqual(user, want) { t.Errorf("Users.Get returned %+v, want %%+v", user, want) } }
package installer import ( "strings" "github.com/wx13/genesis" ) // Task is the most fundamental Doer. It consists of just a single module. // All other Doers contain tasks at their deepest levels (i.e. only a Task // can contain a module directly. type Task struct { genesis.Module } func (task Task) Files() []string { if task.Module == nil { return []string{} } return task.Module.Files() } func (task Task) Status() (genesis.Status, error) { id := task.Module.ID() if SkipID(id) != "do" { return genesis.StatusUnknown, nil } desc := strings.Split(id, "\n")[0] PrintHeader(id, desc) status, msg, err := task.Module.Status() if err != nil || status == genesis.StatusFail { ReportFail(msg, err) return status, err } if status == genesis.StatusUnknown { ReportUnknown(msg, err) return status, nil } if status == genesis.StatusPass { ReportPass(msg, err) return status, nil } return genesis.StatusUnknown, nil } func (task Task) Do() (bool, error) { id := task.ID() if SkipID(id) != "do" { return false, nil } desc := strings.Split(id, "\n")[0] PrintHeader(id, desc) // If status is passing, then we don't have // to do anything. status, msg, err := task.Module.Status() if status == genesis.StatusPass { ReportPass(msg, err) return false, nil } // Otherwise, run the installer. msg, err = task.Install() if err != nil { ReportFail(msg, err) return false, err } // Check results. status, msg2, err := task.Module.Status() if status == genesis.StatusFail { ReportFail(msg2, err) return false, err } ReportDone(msg, err) return true, err } func (task Task) Undo() (bool, error) { id := task.ID() if SkipID(id) != "do" { return false, nil } desc := strings.Split(id, "\n")[0] PrintHeader(id, desc) status, msg, err := task.Module.Status() if err != nil { ReportFail(msg, err) return false, err } if status == genesis.StatusFail { ReportPass(msg, err) return false, nil } msg, err = task.Remove() if err != nil { ReportFail(msg, err) return false, err } ReportPass(msg, err) return true, nil }
package create /*import ( "bytes" "encoding/base64" "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" "strings" "testing" "time" cloudpkg "github.com/devspace-cloud/devspace/pkg/devspace/cloud" cloudconfig "github.com/devspace-cloud/devspace/pkg/devspace/cloud/config" cloudlatest "github.com/devspace-cloud/devspace/pkg/devspace/cloud/config/versions/latest" "github.com/devspace-cloud/devspace/pkg/devspace/cloud/token" "github.com/devspace-cloud/devspace/pkg/util/log" "github.com/devspace-cloud/devspace/pkg/util/survey" "gotest.tools/assert" ) type customGraphqlClient struct { responses []interface{} } func (q *customGraphqlClient) GrapqhlRequest(p *cloudpkg.Provider, request string, vars map[string]interface{}, response interface{}) error { if len(q.responses) == 0 { return fmt.Errorf("Custom graphQL server error") } currentResponse := q.responses[0] q.responses = q.responses[1:] errorResponse, isError := currentResponse.(error) if isError { return errorResponse } buf, err := json.Marshal(currentResponse) if err != nil { panic(fmt.Sprintf("Cannot encode response. %d responses left", len(q.responses))) } json.NewDecoder(bytes.NewReader(buf)).Decode(&response) return nil } type createSpaceTestCase struct { name string graphQLResponses []interface{} providerList []*cloudlatest.Provider args []string answers []string activeFlag bool providerFlag string clusterFlag string expectedErr string } func TestRunCreateSpace(t *testing.T) { claimAsJSON, _ := json.Marshal(token.ClaimSet{ Expiration: time.Now().Add(time.Hour).Unix(), }) validEncodedClaim := base64.URLEncoding.EncodeToString(claimAsJSON) for strings.HasSuffix(string(validEncodedClaim), "=") { validEncodedClaim = strings.TrimSuffix(validEncodedClaim, "=") } testCases := []createSpaceTestCase{ createSpaceTestCase{ name: "Provider doesn't Exist", providerFlag: "Doesn'tExist", providerList: []*cloudlatest.Provider{ &cloudlatest.Provider{ Name: "SomeProvider", }, }, expectedErr: "Cloud provider not found! Did you run `devspace add provider [url]`? Existing cloud providers: SomeProvider ", }, createSpaceTestCase{ name: "Projects can't be retrieved", providerFlag: "SomeProvider", providerList: []*cloudlatest.Provider{ &cloudlatest.Provider{ Name: "SomeProvider", Key: "someKey", }, }, expectedErr: "get projects: Custom graphQL server error", }, createSpaceTestCase{ name: "New project can't be created", providerFlag: "SomeProvider", providerList: []*cloudlatest.Provider{ &cloudlatest.Provider{ Name: "SomeProvider", Key: "someKey", }, }, graphQLResponses: []interface{}{ struct { Projects []*cloudlatest.Project `json:"project"` }{ Projects: []*cloudlatest.Project{}, }, }, expectedErr: "Custom graphQL server error", }, createSpaceTestCase{ name: "Unparsable cluster name", providerFlag: "SomeProvider", providerList: []*cloudlatest.Provider{ &cloudlatest.Provider{ Name: "SomeProvider", Key: "someKey", }, }, graphQLResponses: []interface{}{ struct { Projects []*cloudlatest.Project `json:"project"` }{Projects: []*cloudlatest.Project{&cloudlatest.Project{}}}, }, clusterFlag: "a:b:c", expectedErr: "Error parsing cluster name a:b:c: Expected : only once", }, createSpaceTestCase{ name: "Can't get clusters", providerFlag: "SomeProvider", providerList: []*cloudlatest.Provider{ &cloudlatest.Provider{ Name: "SomeProvider", Key: "someKey", }, }, graphQLResponses: []interface{}{ struct { Projects []*cloudlatest.Project `json:"project"` }{Projects: []*cloudlatest.Project{&cloudlatest.Project{}}}, }, expectedErr: "get clusters: Custom graphQL server error", }, createSpaceTestCase{ name: "No clusters", providerFlag: "SomeProvider", providerList: []*cloudlatest.Provider{ &cloudlatest.Provider{ Name: "SomeProvider", Key: "someKey", }, }, graphQLResponses: []interface{}{ struct { Projects []*cloudlatest.Project `json:"project"` }{Projects: []*cloudlatest.Project{&cloudlatest.Project{}}}, struct { Clusters []*cloudlatest.Cluster `json:"cluster"` }{Clusters: []*cloudlatest.Cluster{}}, }, expectedErr: "Cannot create space, because no cluster was found", }, createSpaceTestCase{ name: "Question 1 is not possible", providerFlag: "SomeProvider", providerList: []*cloudlatest.Provider{ &cloudlatest.Provider{ Name: "SomeProvider", Key: "someKey", Token: "." + validEncodedClaim + ".", }, }, graphQLResponses: []interface{}{ struct { Projects []*cloudlatest.Project `json:"project"` }{Projects: []*cloudlatest.Project{&cloudlatest.Project{}}}, struct { Clusters []*cloudlatest.Cluster `json:"cluster"` }{Clusters: []*cloudlatest.Cluster{ &cloudlatest.Cluster{Owner: &cloudlatest.Owner{}}, &cloudlatest.Cluster{}, }}, }, expectedErr: "Cannot ask question 'Which cluster should the space created in?' because logger level is too low", }, createSpaceTestCase{ name: "Question 2 is not possible", providerFlag: "SomeProvider", providerList: []*cloudlatest.Provider{ &cloudlatest.Provider{ Name: "SomeProvider", Key: "someKey", Token: "." + validEncodedClaim + ".", }, }, graphQLResponses: []interface{}{ struct { Projects []*cloudlatest.Project `json:"project"` }{Projects: []*cloudlatest.Project{&cloudlatest.Project{}}}, struct { Clusters []*cloudlatest.Cluster `json:"cluster"` }{Clusters: []*cloudlatest.Cluster{ &cloudlatest.Cluster{}, &cloudlatest.Cluster{}, }}, }, expectedErr: "Cannot ask question 'Which hosted DevSpace cluster should the space created in?' because logger level is too low", }, createSpaceTestCase{ name: "Select non existent cluster", providerFlag: "SomeProvider", providerList: []*cloudlatest.Provider{ &cloudlatest.Provider{ Name: "SomeProvider", Key: "someKey", Token: "." + validEncodedClaim + ".", }, }, graphQLResponses: []interface{}{ struct { Projects []*cloudlatest.Project `json:"project"` }{Projects: []*cloudlatest.Project{&cloudlatest.Project{}}}, struct { Clusters []*cloudlatest.Cluster `json:"cluster"` }{Clusters: []*cloudlatest.Cluster{ &cloudlatest.Cluster{}, &cloudlatest.Cluster{}, }}, }, answers: []string{"notthere"}, expectedErr: "No cluster selected", }, createSpaceTestCase{ name: "Space creation fails with server error", providerFlag: "SomeProvider", providerList: []*cloudlatest.Provider{ &cloudlatest.Provider{ Name: "SomeProvider", Key: "someKey", Token: "." + validEncodedClaim + ".", }, }, graphQLResponses: []interface{}{ struct { Projects []*cloudlatest.Project `json:"project"` }{Projects: []*cloudlatest.Project{&cloudlatest.Project{}}}, struct { Clusters []*cloudlatest.Cluster `json:"cluster"` }{Clusters: []*cloudlatest.Cluster{ &cloudlatest.Cluster{Owner: &cloudlatest.Owner{}}, }}, }, expectedErr: "create space: Custom graphQL server error", }, createSpaceTestCase{ name: "Get space fails after creation", providerFlag: "SomeProvider", providerList: []*cloudlatest.Provider{ &cloudlatest.Provider{ Name: "SomeProvider", Key: "someKey", Token: "." + validEncodedClaim + ".", }, }, graphQLResponses: []interface{}{ struct { Projects []*cloudlatest.Project `json:"project"` }{Projects: []*cloudlatest.Project{&cloudlatest.Project{}}}, struct { Clusters []*cloudlatest.Cluster `json:"cluster"` }{Clusters: []*cloudlatest.Cluster{ &cloudlatest.Cluster{Owner: &cloudlatest.Owner{}, Name: "cluster1"}, &cloudlatest.Cluster{Owner: &cloudlatest.Owner{}, Name: "cluster2"}, }}, struct { CreateSpace interface{} `json:"manager_createSpace"` }{CreateSpace: struct{ SpaceID int }{SpaceID: 1}}, }, answers: []string{"cluster1"}, expectedErr: "get space: Custom graphQL server error", }, createSpaceTestCase{ name: "Get serviceaccount fails after creation", providerFlag: "SomeProvider", providerList: []*cloudlatest.Provider{ &cloudlatest.Provider{ Name: "SomeProvider", Key: "someKey", Token: "." + validEncodedClaim + ".", }, }, graphQLResponses: []interface{}{ struct { Projects []*cloudlatest.Project `json:"project"` }{[]*cloudlatest.Project{&cloudlatest.Project{}}}, struct { Clusters []*cloudlatest.Cluster `json:"cluster"` }{[]*cloudlatest.Cluster{ &cloudlatest.Cluster{Owner: &cloudlatest.Owner{}, Name: "cluster1"}, &cloudlatest.Cluster{Name: "cluster2"}, }}, struct { CreateSpace interface{} `json:"manager_createSpace"` }{CreateSpace: struct{ SpaceID int }{SpaceID: 1}}, struct { Space interface{} `json:"space_by_pk"` }{ struct { KubeContext interface{} `json:"kube_context"` Owner interface{} `json:"account"` }{struct{Cluster interface{} `json:"cluster"`}{struct{}{}}, struct{}{}}, }, }, answers: []string{DevSpaceCloudHostedCluster}, expectedErr: "get serviceaccount: Custom graphQL server error", }, createSpaceTestCase{ name: "Undecodable CACert", providerFlag: "SomeProvider", providerList: []*cloudlatest.Provider{ &cloudlatest.Provider{ Name: "SomeProvider", Key: "someKey", Token: "." + validEncodedClaim + ".", }, }, graphQLResponses: []interface{}{ struct { Projects []*cloudlatest.Project `json:"project"` }{[]*cloudlatest.Project{&cloudlatest.Project{}}}, struct { Clusters []*cloudlatest.Cluster `json:"cluster"` }{[]*cloudlatest.Cluster{ &cloudlatest.Cluster{Name: "cluster2"}, &cloudlatest.Cluster{Name: "cluster3"}, }}, struct { CreateSpace interface{} `json:"manager_createSpace"` }{CreateSpace: struct{ SpaceID int }{SpaceID: 1}}, struct { Space interface{} `json:"space_by_pk"` }{ struct { KubeContext interface{} `json:"kube_context"` Owner interface{} `json:"account"` }{struct{Cluster interface{} `json:"cluster"`}{struct{}{}}, struct{}{}}, }, struct {ServiceAccount *cloudlatest.ServiceAccount `json:"manager_serviceAccount"`}{&cloudlatest.ServiceAccount{ CaCert: "undecodable", }}, }, answers: []string{"cluster2"}, expectedErr: "update kube context: illegal base64 data at input byte 8", }, } log.SetInstance(&log.DiscardLogger{PanicOnExit: true}) for _, testCase := range testCases { testRunCreateSpace(t, testCase) } } func testRunCreateSpace(t *testing.T, testCase createSpaceTestCase) { dir, err := ioutil.TempDir("", "test") if err != nil { t.Fatalf("Error creating temporary directory: %v", err) } dir, err = filepath.EvalSymlinks(dir) if err != nil { t.Fatal(err) } wdBackup, err := os.Getwd() if err != nil { t.Fatalf("Error getting current working directory: %v", err) } err = os.Chdir(dir) if err != nil { t.Fatalf("Error changing working directory: %v", err) } defer func() { //Delete temp folder err = os.Chdir(wdBackup) if err != nil { t.Fatalf("Error changing dir back: %v", err) } err = os.RemoveAll(dir) if err != nil { t.Fatalf("Error removing dir: %v", err) } }() cloudpkg.DefaultGraphqlClient = &customGraphqlClient{ responses: testCase.graphQLResponses, } providerConfig, err := cloudconfig.Load() assert.NilError(t, err, "Error getting provider config in testCase %s", testCase.name) providerConfig.Providers = testCase.providerList for _, answer := range testCase.answers { survey.SetNextAnswer(answer) } if len(testCase.args) == 0 { testCase.args = []string{""} } err = (&spaceCmd{ Active: testCase.activeFlag, Provider: testCase.providerFlag, Cluster: testCase.clusterFlag, }).RunCreateSpace(nil, testCase.args) if testCase.expectedErr == "" { assert.NilError(t, err, "Unexpected error in testCase %s.", testCase.name) } else { assert.Error(t, err, testCase.expectedErr, "Wrong or no error in testCase %s.", testCase.name) } } */
package singleton var instance ParamRepository = &RepositoryImpl{} func GetInstance() ParamRepository { return instance //return &RepositoryImpl{} } func (repository *RepositoryImpl) GetParam(id int) Param { return Param{Id: id} }
package g import ( "encoding/json" "time" "log" "github.com/Shopify/sarama" "github.com/open-falcon/falcon-plus/common/model" ) var ( SYS_TOPIC string = "SYS_MONITOR" ) func SendKafkaMetrics(metrics []*model.MetricValue) { var kafkaAddrs []string = Config().Kafka.Addrs SyncProducer(kafkaAddrs, metrics) } //同步消息模式 func SyncProducer(KfkAddr []string, metrics []*model.MetricValue) { config := sarama.NewConfig() config.Producer.Return.Successes = true config.Producer.Retry.Backoff = time.Duration(Config().Kafka.Timeout) * time.Second config.Producer.Retry.Max = Config().Kafka.Interval config.Producer.Return.Errors = true config.Producer.Timeout = time.Duration(Config().Kafka.Timeout) * time.Second p, err := sarama.NewSyncProducer(KfkAddr, config) if err != nil { log.Printf("sarama.NewSyncProducer err, message=%s \n", err) return } defer p.Close() metric, err := json.Marshal(metrics) if err != nil { log.Printf("marshal[%+v] failed fail: %v", metrics, err) } msg := &sarama.ProducerMessage{ Topic: SYS_TOPIC, Value: sarama.StringEncoder(metric), } part, offset, err := p.SendMessage(msg) if err != nil { log.Printf("send message(%s) err=%s \n", metric, err) } else { log.Printf("topic[%s] send success,partition=%d, offset=%d \n", SYS_TOPIC, part, offset) } }
package engine import ( "bishe/spider/config" "bishe/spider/fetcher" "bishe/spider/model" "errors" "fmt" "log" "regexp" "strconv" "time" ) func Run(tasklist []config.Task) { for len(tasklist) > 0 { t := time.Tick(30*time.Second) task := tasklist[0] tasklist = tasklist[1:] data, err := fetcher.Fetcher(task.Url) fmt.Printf("fetcher : %s\n", task.Url) <-t if err != nil { log.Printf("fetcher error :%s", err.Error()) continue } parseResult, err := task.Parse(data) if err != nil { log.Printf("parse error : %s", err.Error()) continue } // zhipin.PrintItem(parseResult.Item) if parseResult.IsStore { // 数据清洗 data, err := cleanData(parseResult.Item) if err != nil { log.Printf("data clean error: %s", err.Error()) } // 数据合格再进行存储 printNewData(data) err = model.Insert(data) if err != nil { log.Printf("DB store error: %s", err.Error()) } } if parseResult.Tasks == nil { continue } tasklist = append(parseResult.Tasks, tasklist...) } } // 数据清洗 // 将解析出来的数据进行进一步的整理 // Salary: 18k-35k => {low: 18000, avg: (35000 + 18000) / 2, high: 35000} // 根据工作年限划分招聘等级: // 经验不限:0; // 应届生:1; // 1年以内:2; // 1-3年:3; // 3-5年:4; // 5-10年:5; // 10年以上:6; // 缺失信息则为无效数据 func cleanData(oldData config.ZhiPiItem) (model.PositionInfo, error) { var newData = cleanMiss(oldData) // Salary清洗 salaryStr := oldData.Salary salaryRe := regexp.MustCompile(`([0-9]+)k-([0-9]+)k`) salarymatch := salaryRe.FindStringSubmatch(salaryStr) if len(salarymatch) < 2 { return newData, errors.New("invalid data") } low, _ := strconv.Atoi(salarymatch[1]) high, _ := strconv.Atoi(salarymatch[2]) salary := config.Salary{ Low:low*1000, Avg:(low + high)*1000/2, High:high*1000, } newData.Salary.Low, newData.Salary.Avg, newData.Salary.High = salary.Low, salary.Avg, salary.High // 划分招聘等级 switch oldData.WorkYear { case "经验不限": newData.Level = 0 case "应届生": newData.Level = 1 case "1年以内": newData.Level = 2 case "1-3年": newData.Level = 3 case "3-5年": newData.Level = 4 case "5-10年": newData.Level = 5 case "10年以上": newData.Level = 6 default: return newData, errors.New("level divide failed") } newData.WorkYear = oldData.WorkYear newData.Pid = oldData.Pid return newData, nil } // 缺失值检查 func cleanMiss(oldData config.ZhiPiItem) model.PositionInfo { var newData = model.PositionInfo{} isMiss := false if oldData.Positon != "" { newData.Positon = oldData.Positon } else { isMiss = true } if oldData.City != "" { newData.City = oldData.City } else { isMiss = true } if oldData.Education != "" { newData.Education = oldData.Education } else { isMiss = true } if oldData.CompanyName != "" { newData.CompanyName = oldData.CompanyName } else { isMiss = true } if oldData.FinanceStage != "" { newData.FinanceStage = oldData.FinanceStage } else { isMiss = true } if oldData.CompanySize != "" { newData.CompanySize = oldData.CompanySize } else { isMiss = true } if oldData.Industry != "" { newData.Industry = oldData.Industry } else { isMiss = true } if oldData.Location != "" { newData.Location = oldData.Location } else { isMiss = true } if oldData.Detail != "" { newData.Detail = oldData.Detail } else { isMiss = true } newData.IsMiss = isMiss return newData } func printNewData(item model.PositionInfo) { fmt.Println("{") fmt.Printf("Pid: %s,\n", item.Pid) fmt.Printf("Positon: %s,\n", item.Positon) fmt.Printf("Salary: %v,\n", item.Salary) fmt.Printf("City: %s,\n", item.City) fmt.Printf("WorkYear: %s,\n", item.WorkYear) fmt.Printf("WorkYear: %d,\n", item.Level) fmt.Printf("Education: %s,\n", item.Education) fmt.Printf("CompanyName: %s,\n", item.CompanyName) fmt.Printf("FinanceStage: %s,\n", item.FinanceStage) fmt.Printf("CompanySize: %s,\n", item.CompanySize) fmt.Printf("Industry: %s,\n", item.Industry) fmt.Printf("Detail: %s,\n", item.Detail) fmt.Printf("Location: %s,\n", item.Location) fmt.Printf("IsMiss: %v,\n", item.IsMiss) fmt.Println("}") }
package models import ( "fmt" "monitor/data" "monitor/responses" "sort" ) // GetAllActionNames return all action func (md *MonitorService) GetAllActionNames() ([]string, error) { res := []string{} // var res []string; fmt.Println("GetAllActionNames ") md.ActionDailyLog.Range(func(key, _ interface{}) bool { sKey := key.(string) res = append(res, sKey) // dailyStat := value.(*DayStat) return true }) sort.Strings(res) return res, nil } // GetAllRequestNames return all request func (md *MonitorService) GetAllRequestNames() ([]string, error) { res := []string{} md.RequestDailyLog.Range(func(key, _ interface{}) bool { sKey := key.(string) res = append(res, sKey) // dailyStat := value.(*DayStat) return true }) sort.Strings(res) return res, nil } // GetActionDataByHour return time action func (md *MonitorService) GetActionDataByHour(out *responses.ActionsDataByHours) { md.ActionDailyLog.Range(func(key, value interface{}) bool { // add key - value to sKey := key.(string) aDayStat := value.(*data.DayStat) out.HourData[sKey] = aDayStat.HourData //need to copy? fmt.Printf("action data of %s, %v \n", sKey, aDayStat.HourData) return true }) } // GetRequestDataByHour return time request func (md *MonitorService) GetRequestDataByHour(out *responses.ActionsDataByHours) { md.RequestDailyLog.Range(func(key, value interface{}) bool { // add key - value to sKey := key.(string) aDayStat := value.(*data.DayStat) out.HourData[sKey] = aDayStat.HourData //need to copy? fmt.Printf("action data of %s, %v \n", sKey, aDayStat.HourData) return true }) } // GetActionDataByMinute return time action func (md *MonitorService) GetActionDataByMinute(out *responses.ActionsDataByMinutes) { md.ActionDailyLog.Range(func(key, value interface{}) bool { // add key - value to sKey := key.(string) aDayStat := value.(*data.DayStat) out.HourData[sKey] = aDayStat.MinuteData //need to copy? fmt.Printf("action data of %s, %v \n", sKey, aDayStat.HourData) return true }) } // GetRequestDataByMinute return time request func (md *MonitorService) GetRequestDataByMinute(out *responses.ActionsDataByMinutes) { md.RequestDailyLog.Range(func(key, value interface{}) bool { // add key - value to sKey := key.(string) aDayStat := value.(*data.DayStat) out.HourData[sKey] = aDayStat.MinuteData //need to copy? fmt.Printf("action data of %s, %v \n", sKey, aDayStat.HourData) return true }) } // GetAllInfoForCharting get tất cả thông tin cơ bản cho vẽ biểu đồ func (md *MonitorService) GetAllInfoForCharting() (resp *data.AllInfoForChartingData) { fmt.Printf("[GetAllInfoForCharting] call \n") resp = &data.AllInfoForChartingData{ AllAction: make([]string, 0), AllRequest: make([]string, 0), TheAverageTimeMonitorData: &data.TheAverageTimeMonitorData{ TimeAction: make([]int64, 0), TimeRequest: make([]int64, 0), }, BestCountMonitorData: &data.BestCountMonitorData{ BestActionCount: make([]int64, 0), BestActionLabel: make([]string, 0), BestRequestCount: make([]int64, 0), BestRequestLabel: make([]string, 0), }, MonitorData: &data.MonitorData{ ActionDataCount: make([]int64, 0), ActionDataHours: make([]int64, 0), ActionDataByMinutes: make(map[string][24 * 60]data.SecondStat), ActionDataByHours: make(map[string][24]data.SecondStat), RequestDataCount: make([]int64, 0), RequestDataHours: make([]int64, 0), RequestDataByMinutes: make(map[string][24 * 60]data.SecondStat), RequestDataByHours: make(map[string][24]data.SecondStat), }, } resp.AllAction, _ = md.GetAllActionNames() resp.AllRequest, _ = md.GetAllRequestNames() //aResActionsMinuteData := make(map[string][24 * 60]data.SecondStat) md.ActionDailyLog.Range(func(key, value interface{}) bool { // add key - value to sKey := key.(string) aDayStat := value.(*data.DayStat) resp.MonitorData.ActionDataByMinutes[sKey] = aDayStat.MinuteData //need to copy? return true }) //aResRequestsMinuteData := make(map[string][24 * 60]data.SecondStat) md.RequestDailyLog.Range(func(key, value interface{}) bool { // add key - value to sKey := key.(string) aDayStat := value.(*data.DayStat) resp.MonitorData.RequestDataByMinutes[sKey] = aDayStat.MinuteData //need to copy? return true }) // aResActionsHour := make(map[string][24]data.SecondStat) md.ActionDailyLog.Range(func(key, value interface{}) bool { // add key - value to sKey := key.(string) aDayStat := value.(*data.DayStat) resp.MonitorData.ActionDataByHours[sKey] = aDayStat.HourData //need to copy? return true }) //aResRequestsHour := make(map[string][24]data.SecondStat) md.RequestDailyLog.Range(func(key, value interface{}) bool { // add key - value to sKey := key.(string) aDayStat := value.(*data.DayStat) resp.MonitorData.RequestDataByHours[sKey] = aDayStat.HourData //need to copy? return true }) for _, v := range resp.AllAction { lstHours := resp.MonitorData.ActionDataByHours[v] total := int64(0) totalTime := int64(0) for _, hours := range lstHours { total += int64(hours.TotalCount) totalTime += int64(hours.TotalTime) } resp.MonitorData.ActionDataCount = append(resp.MonitorData.ActionDataCount, total) resp.MonitorData.ActionDataHours = append(resp.MonitorData.ActionDataHours, totalTime) if total > 0 { resp.TheAverageTimeMonitorData.TimeAction = append(resp.TheAverageTimeMonitorData.TimeAction, totalTime/total) } else { resp.TheAverageTimeMonitorData.TimeAction = append(resp.TheAverageTimeMonitorData.TimeAction, 0) } } // lstDataRequestHours := make([]int64, 0) // lstDataRequest := make([]int64, 0) for _, v := range resp.AllRequest { lstHours := resp.MonitorData.RequestDataByHours[v] total := int64(0) totalTime := int64(0) for _, hours := range lstHours { total += int64(hours.TotalCount) totalTime += int64(hours.TotalTime) } resp.MonitorData.RequestDataCount = append(resp.MonitorData.RequestDataCount, total) resp.MonitorData.RequestDataHours = append(resp.MonitorData.RequestDataHours, totalTime) if total > 0 { resp.TheAverageTimeMonitorData.TimeRequest = append(resp.TheAverageTimeMonitorData.TimeRequest, totalTime/total) } else { resp.TheAverageTimeMonitorData.TimeRequest = append(resp.TheAverageTimeMonitorData.TimeRequest, 0) } } resp.BestCountMonitorData.BestActionLabel = make([]string, len(resp.AllAction)) resp.BestCountMonitorData.BestActionCount = make([]int64, len(resp.MonitorData.ActionDataCount)) resp.BestCountMonitorData.BestRequestLabel = make([]string, len(resp.AllRequest)) resp.BestCountMonitorData.BestRequestCount = make([]int64, len(resp.MonitorData.RequestDataCount)) copy(resp.BestCountMonitorData.BestActionLabel, resp.AllAction) copy(resp.BestCountMonitorData.BestActionCount, resp.MonitorData.ActionDataCount) copy(resp.BestCountMonitorData.BestRequestLabel, resp.AllRequest) copy(resp.BestCountMonitorData.BestRequestCount, resp.MonitorData.RequestDataCount) for i := 0; i < len(resp.BestCountMonitorData.BestActionCount)-1; i++ { for j := i + 1; j < len(resp.BestCountMonitorData.BestActionCount); j++ { if resp.BestCountMonitorData.BestActionCount[j] > resp.BestCountMonitorData.BestActionCount[i] { resp.BestCountMonitorData.BestActionCount[j], resp.BestCountMonitorData.BestActionCount[i] = resp.BestCountMonitorData.BestActionCount[i], resp.BestCountMonitorData.BestActionCount[j] resp.BestCountMonitorData.BestActionLabel[j], resp.BestCountMonitorData.BestActionLabel[i] = resp.BestCountMonitorData.BestActionLabel[i], resp.BestCountMonitorData.BestActionLabel[j] } } } for i := 0; i < len(resp.BestCountMonitorData.BestRequestCount)-1; i++ { for j := i + 1; j < len(resp.BestCountMonitorData.BestRequestCount); j++ { if resp.BestCountMonitorData.BestRequestCount[j] > resp.BestCountMonitorData.BestRequestCount[i] { resp.BestCountMonitorData.BestRequestCount[j], resp.BestCountMonitorData.BestRequestCount[i] = resp.BestCountMonitorData.BestRequestCount[i], resp.BestCountMonitorData.BestRequestCount[j] resp.BestCountMonitorData.BestRequestLabel[j], resp.BestCountMonitorData.BestRequestLabel[i] = resp.BestCountMonitorData.BestRequestLabel[i], resp.BestCountMonitorData.BestRequestLabel[j] } } } return }
package cos_test import ( "fmt" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" sut "github.com/rancher-sandbox/ele-testhelpers/vm" ) var _ = Describe("cOS Installer EFI tests", func() { var s *sut.SUT BeforeEach(func() { s = sut.NewSUT() s.EventuallyConnects() }) Context("Using efi", func() { // EFI variant tests is not able to set the boot order and there is no plan to let the user do so according to virtualbox // So we need to manually eject/insert the cd to force the boot order. CD inserted -> boot from cd, CD empty -> boot from disk BeforeEach(func() { // Assert we are booting from CD before running the tests By("Making sure we booted from CD") ExpectWithOffset(1, s.BootFrom()).To(Equal(sut.LiveCD)) out, err := s.Command("grep /dev/sr /etc/mtab") Expect(err).ToNot(HaveOccurred()) Expect(out).To(ContainSubstring("iso9660")) out, err = s.Command("df -h /") Expect(err).ToNot(HaveOccurred()) Expect(out).To(ContainSubstring("LiveOS_rootfs")) s.EmptyDisk("/dev/sda") _, _ = s.Command("sync") // squashfs comes from a command line flag at suite level if squashfs { By("Setting the squashfs recovery install") err = s.SendFile("../assets/squashed_recovery.yaml", "/etc/elemental/config.d/install_recovery.yaml", "0770") Expect(err).ToNot(HaveOccurred()) } }) AfterEach(func() { if CurrentSpecReport().Failed() { s.GatherAllLogs() } }) // Commented because there is only a single active test, hence restoring CD before // after rebooting is not needed. /*AfterEach(func() { if CurrentGinkgoTestDescription().Failed { s.GatherAllLogs() } // Store COS iso path s.SetCOSCDLocation() // Set Cos CD in the drive s.RestoreCOSCD() By("Reboot to make sure we boot from CD") s.Reboot() })*/ Context("partition layout tests", func() { Context("with partition layout", func() { It("performs a standard install", func() { err := s.SendFile("../assets/custom_partitions.yaml", "/etc/elemental/config.d/custom_partitions.yaml", "0770") By("Running the elemental install with a layout file") Expect(err).To(BeNil()) out, err := s.Command(s.ElementalCmd("install", "--part-table gpt", "/dev/sda")) fmt.Printf(out) Expect(err).To(BeNil()) Expect(out).To(ContainSubstring("Mounting disk partitions")) Expect(out).To(ContainSubstring("Partitioning device...")) Expect(out).To(ContainSubstring("Running after-install hook")) if squashfs { // Check the squashfs image is used as recovery Expect(out).To(ContainSubstring("Creating squashed image:")) } }) // This section of the test is flaky in our CI w/EFI. Commenting it out for the time being PIt("Forcing GPT", func() { err := s.SendFile("../assets/custom_partitions.yaml", "/etc/elemental/config.d/custom_partitions.yaml", "0770") By("Running the elemental install with a layout file") Expect(err).To(BeNil()) out, err := s.Command(s.ElementalCmd("install", "--force-gpt", "/dev/sda")) fmt.Printf(out) Expect(err).To(BeNil()) Expect(out).To(ContainSubstring("Installing GRUB..")) Expect(out).To(ContainSubstring("Mounting disk partitions")) Expect(out).To(ContainSubstring("Partitioning device...")) Expect(out).To(ContainSubstring("Running after-install hook")) if squashfs { // Check the squashfs image is used as recovery Expect(out).To(ContainSubstring("Creating squashed image:")) } // Remove iso so we boot directly from the disk s.EjectCOSCD() // Reboot so we boot into the just installed cos s.Reboot() By("Checking we booted from the installed cOS") ExpectWithOffset(1, s.BootFrom()).To(Equal(sut.Active)) // check partition values // Values have to match the yaml under ../assets/layout.yaml // That is the file that the installer uses so partitions should match those values disk := s.GetDiskLayout("/dev/sda") for _, part := range []sut.PartitionEntry{ { Label: "COS_STATE", Size: 8192, FsType: sut.Ext4, }, { Label: "COS_OEM", Size: 10, FsType: sut.Ext4, }, { Label: "COS_RECOVERY", Size: 4000, FsType: sut.Ext2, }, { Label: "COS_PERSISTENT", Size: 100, FsType: sut.Ext2, }, } { CheckPartitionValues(disk, part) } }) // Marked as pending to reduce the number of efi tests. VBox efi support is // not good enough to run extensive tests PIt("Not forcing GPT", func() { err := s.SendFile("../assets/custom_partitions.yaml", "/etc/elemental/config.d/custom_partitions.yaml", "0770") By("Running the elemental install with a layout file") Expect(err).To(BeNil()) out, err := s.Command(s.ElementalCmd("install", "/dev/sda")) Expect(err).To(BeNil()) Expect(out).To(ContainSubstring("Installing GRUB..")) Expect(out).To(ContainSubstring("Mounting disk partitions")) Expect(out).To(ContainSubstring("Partitioning device...")) Expect(out).To(ContainSubstring("Running after-install hook")) if squashfs { // Check the squashfs image is used as recovery Expect(out).To(ContainSubstring("Creating squashed image:")) } // Remove iso so we boot directly from the disk s.EjectCOSCD() // Reboot so we boot into the just installed cos s.Reboot() By("Checking we booted from the installed cOS") ExpectWithOffset(1, s.BootFrom()).To(Equal(sut.Active)) // check partition values // Values have to match the yaml under ../assets/layout.yaml // That is the file that the installer uses so partitions should match those values disk := s.GetDiskLayout("/dev/sda") for _, part := range []sut.PartitionEntry{ { Label: "COS_STATE", Size: 8192, FsType: sut.Ext4, }, { Label: "COS_OEM", Size: 10, FsType: sut.Ext4, }, { Label: "COS_RECOVERY", Size: 4000, FsType: sut.Ext2, }, { Label: "COS_PERSISTENT", Size: 100, FsType: sut.Ext2, }, } { CheckPartitionValues(disk, part) } }) }) }) // Marked as pending to reduce the number of efi tests. VBox efi support is // not good enough to run extensive tests PContext("install source tests", func() { It("from iso", func() { By("Running the elemental install") out, err := s.Command(s.ElementalCmd("install", "/dev/sda")) Expect(err).To(BeNil()) Expect(out).To(ContainSubstring("Installing GRUB..")) Expect(out).To(ContainSubstring("Mounting disk partitions")) Expect(out).To(ContainSubstring("Partitioning device...")) Expect(out).To(ContainSubstring("Running after-install hook")) if squashfs { // Check the squashfs image is used as recovery Expect(out).To(ContainSubstring("Creating squashed image:")) } // Remove iso so we boot directly from the disk s.EjectCOSCD() // Reboot so we boot into the just installed cos s.Reboot() By("Checking we booted from the installed cOS") ExpectWithOffset(1, s.BootFrom()).To(Equal(sut.Active)) }) PIt("from url", func() {}) It("from docker image", func() { By("Running the elemental install") out, err := s.Command(s.ElementalCmd("install", "--system.uri", fmt.Sprintf("docker:%s:cos-system-%s", s.GetArtifactsRepo(), s.TestVersion), "/dev/sda")) Expect(err).To(BeNil()) Expect(out).To(ContainSubstring("Installing GRUB..")) Expect(out).To(ContainSubstring("Mounting disk partitions")) Expect(out).To(ContainSubstring("Partitioning device...")) Expect(out).To(ContainSubstring("Running after-install hook")) if squashfs { // Check the squashfs image is used as recovery Expect(out).To(ContainSubstring("Creating squashed image:")) } s.EjectCOSCD() // Reboot so we boot into the just installed cos s.Reboot() By("Checking we booted from the installed cOS") ExpectWithOffset(1, s.BootFrom()).To(Equal(sut.Active)) Expect(s.GetOSRelease("VERSION")).To(Equal(s.TestVersion)) }) }) // Marked as pending to reduce the number of efi tests. VBox efi support is // not good enough to run extensive tests PContext("efi/gpt tests", func() { It("forces gpt", func() { By("Running the installer") out, err := s.Command(s.ElementalCmd("install", "--force-gpt", "/dev/sda")) Expect(err).To(BeNil()) Expect(out).To(ContainSubstring("Installing GRUB..")) Expect(out).To(ContainSubstring("Mounting disk partitions")) Expect(out).To(ContainSubstring("Partitioning device...")) Expect(out).To(ContainSubstring("Running after-install hook")) if squashfs { // Check the squashfs image is used as recovery Expect(out).To(ContainSubstring("Creating squashed image:")) } // Remove iso so we boot directly from the disk s.EjectCOSCD() // Reboot so we boot into the just installed cos s.Reboot() By("Checking we booted from the installed cOS") ExpectWithOffset(1, s.BootFrom()).To(Equal(sut.Active)) }) It("forces efi", func() { By("Running the installer") out, err := s.Command(s.ElementalCmd("install", "--force-efi", "/dev/sda")) Expect(err).To(BeNil()) Expect(out).To(ContainSubstring("Installing GRUB..")) Expect(out).To(ContainSubstring("Mounting disk partitions")) Expect(out).To(ContainSubstring("Partitioning device...")) Expect(out).To(ContainSubstring("Running after-install hook")) if squashfs { // Check the squashfs image is used as recovery Expect(out).To(ContainSubstring("Creating squashed image:")) } // Remove iso so we boot directly from the disk s.EjectCOSCD() // Reboot so we boot into the just installed cos s.Reboot() // We are on an efi system, should boot from active By("Checking we booted from Active partition") ExpectWithOffset(1, s.BootFrom()).To(Equal(sut.Active)) }) }) }) })
package problem0671 //TreeNode Definition for a binary tree node. type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func findSecondMinimumValue(root *TreeNode) int { if root == nil { return -1 } if root.Left == nil && root.Right == nil { return -1 } leftVal := root.Left.Val rightVal := root.Right.Val if leftVal == root.Val { leftVal = findSecondMinimumValue(root.Left) } if rightVal == root.Val { rightVal = findSecondMinimumValue(root.Right) } if leftVal != -1 && rightVal != -1 { return min(leftVal, rightVal) } if leftVal != -1 { return leftVal } return rightVal } func min(a, b int) int { if a > b { return b } return a }
package main import ( "fmt" "os" "os/exec" "os/signal" "syscall" ) var cmd = exec.Command("ping") func init() { cmd.Args = []string{"ping", "baidu.com"} cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr } func main() { signalChan := make(chan os.Signal, 1) // 2 & 15 signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM) go func() { sig := <-signalChan fmt.Printf("catch kubernetes signal: %v, stop cmd: %v", sig, cmd.Args) cmd.Process.Signal(os.Interrupt) }() if err := cmd.Run(); err != nil { fmt.Printf("Error running the /bin/sh command - %s\n", err) os.Exit(1) } }
package core import ( "bytes" "sort" "strings" "time" ) // TestResults describes a set of test results for a test target. type TestResults struct { NumTests int // Total number of test cases in the test target. Passed int // Number of tests that passed outright. Failed int // Number of tests that failed. ExpectedFailures int // Number of tests that were expected to fail (counts as a pass, but displayed differently) Skipped int // Number of tests skipped (also count as passes) Flakes int // Number of failed attempts to run the test Failures []TestFailure Passes []string Output string // Stdout / stderr from the test. Cached bool // True if the test results were retrieved from cache TimedOut bool // True if the test failed because we timed it out. Duration time.Duration // Length of time this test took } // TestFailure represents information about a test failure. type TestFailure struct { Name string // Name of failed test Type string // Type of failure, eg. type of exception raised Traceback string // Traceback Stdout string // Standard output during test Stderr string // Standard error during test } // Aggregate aggregates the given results into this one. func (results *TestResults) Aggregate(r *TestResults) { results.NumTests += r.NumTests results.Passed += r.Passed results.Failed += r.Failed results.ExpectedFailures += r.ExpectedFailures results.Skipped += r.Skipped results.Flakes += r.Flakes results.Failures = append(results.Failures, r.Failures...) results.Passes = append(results.Passes, r.Passes...) results.Duration += r.Duration // Output can't really be aggregated sensibly. } // A LineCoverage represents a single line of coverage, which can be in one of several states. // Note that Please doesn't support sub-line coverage at present. type LineCoverage uint8 // Constants representing the states that a single line can be in for coverage. const ( NotExecutable LineCoverage = iota // Line isn't executable (eg. comment, blank) Unreachable LineCoverage = iota // Line is executable but we've determined it can't be reached. So far not used. Uncovered LineCoverage = iota // Line is executable but isn't covered. Covered LineCoverage = iota // Line is executable and covered. ) var lineCoverageOutput = [...]rune{'N', 'X', 'U', 'C'} // Corresponds to ordering of enum. // TestCoverage implements a pretty simple coverage format; we record one int for each line // stating what its coverage is. type TestCoverage struct { Tests map[BuildLabel]map[string][]LineCoverage Files map[string][]LineCoverage } // Aggregate aggregates results from that coverage object into this one. func (coverage *TestCoverage) Aggregate(cov *TestCoverage) { if coverage.Tests == nil { coverage.Tests = map[BuildLabel]map[string][]LineCoverage{} } if coverage.Files == nil { coverage.Files = map[string][]LineCoverage{} } // Assume that tests are independent (will currently always be the case). for label, c := range cov.Tests { coverage.Tests[label] = c } // Files are more complex since multiple tests can cover the same file. // We take the best result for each line from each test. for filename, c := range cov.Files { coverage.Files[filename] = MergeCoverageLines(coverage.Files[filename], c) } } // MergeCoverageLines merges two sets of coverage results together, taking // the superset of the two results. func MergeCoverageLines(existing, coverage []LineCoverage) []LineCoverage { ret := make([]LineCoverage, len(existing)) copy(ret, existing) for i, line := range coverage { if i >= len(ret) { ret = append(ret, line) } else if coverage[i] > ret[i] { ret[i] = coverage[i] } } return ret } // OrderedFiles returns an ordered slice of all the files we have coverage information for. func (coverage *TestCoverage) OrderedFiles() []string { files := []string{} for file := range coverage.Files { if strings.HasPrefix(file, RepoRoot) { file = strings.TrimLeft(file[len(RepoRoot):], "/") } files = append(files, file) } sort.Strings(files) return files } // NewTestCoverage constructs and returns a new TestCoverage instance. func NewTestCoverage() TestCoverage { return TestCoverage{ Tests: map[BuildLabel]map[string][]LineCoverage{}, Files: map[string][]LineCoverage{}, } } // TestCoverageString produces a string representation of coverage for serialising to file so we don't // expose the internal enum values (ordering is important so we may want to insert // new ones later). This format happens to be the same as the one Phabricator uses, // which is mildly useful to us since we want to integrate with it anyway. See // https://secure.phabricator.com/book/phabricator/article/arcanist_coverage/ // for more detail of how it works. func TestCoverageString(lines []LineCoverage) string { var buffer bytes.Buffer for _, line := range lines { buffer.WriteRune(lineCoverageOutput[line]) } return buffer.String() }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-08-14 10:39 # @File : of_剑指_Offer_05_替换空格.go # @Description : # @Attention : */ package offer func replaceSpace(s string) string { bytes := make([]byte, 0) for i, j := 0, 0; i < len(s); { if s[i] == ' ' { bytes = append(bytes, '%', '2', '0') j += 3 } else { bytes = append(bytes, s[i]) j++ } i++ } return string(bytes) }
/* Copyright © 2020-2021 The k3d Author(s) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package client import ( "bufio" "context" "fmt" "net" "regexp" "runtime" rt "github.com/rancher/k3d/v4/pkg/runtimes" k3d "github.com/rancher/k3d/v4/pkg/types" "github.com/rancher/k3d/v4/pkg/util" log "github.com/sirupsen/logrus" ) var nsLookupAddressRegexp = regexp.MustCompile(`^Address:\s+(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$`) // GetHostIP returns the routable IP address to be able to access services running on the host system from inside the cluster. // This depends on the Operating System and the chosen Runtime. func GetHostIP(ctx context.Context, rtime rt.Runtime, cluster *k3d.Cluster) (net.IP, error) { // Docker Runtime if rtime == rt.Docker { log.Tracef("Runtime GOOS: %s", runtime.GOOS) // "native" Docker on Linux if runtime.GOOS == "linux" { ip, err := rtime.GetHostIP(ctx, cluster.Network.Name) if err != nil { return nil, err } return ip, nil } // Docker (for Desktop) on MacOS or Windows if runtime.GOOS == "windows" || runtime.GOOS == "darwin" { ip, err := resolveHostnameFromInside(ctx, rtime, cluster.Nodes[0], "host.docker.internal") if err != nil { return nil, err } return ip, nil } // Catch all other GOOS cases return nil, fmt.Errorf("GetHostIP only implemented for Linux, MacOS (Darwin) and Windows") } // Catch all other runtime selections return nil, fmt.Errorf("GetHostIP only implemented for the docker runtime") } func resolveHostnameFromInside(ctx context.Context, rtime rt.Runtime, node *k3d.Node, hostname string) (net.IP, error) { logreader, execErr := rtime.ExecInNodeGetLogs(ctx, node, []string{"sh", "-c", fmt.Sprintf("nslookup %s", hostname)}) if logreader == nil { if execErr != nil { return nil, execErr } return nil, fmt.Errorf("Failed to get logs from exec process") } submatches := map[string]string{} scanner := bufio.NewScanner(logreader) if scanner == nil { if execErr != nil { return nil, execErr } return nil, fmt.Errorf("Failed to scan logs for host IP: Could not create scanner from logreader") } if scanner != nil && execErr != nil { log.Debugln("Exec Process Failed, but we still got logs, so we're at least trying to get the IP from there...") log.Tracef("-> Exec Process Error was: %+v", execErr) } for scanner.Scan() { log.Tracef("Scanning Log Line '%s'", scanner.Text()) match := nsLookupAddressRegexp.FindStringSubmatch(scanner.Text()) if len(match) == 0 { continue } log.Tracef("-> Match(es): '%+v'", match) submatches = util.MapSubexpNames(nsLookupAddressRegexp.SubexpNames(), match) log.Tracef(" -> Submatch(es): %+v", submatches) break } if _, ok := submatches["ip"]; !ok { if execErr != nil { log.Errorln(execErr) } return nil, fmt.Errorf("Failed to read address for '%s' from nslookup response", hostname) } log.Debugf("Hostname '%s' -> Address '%s'", hostname, submatches["ip"]) return net.ParseIP(submatches["ip"]), nil }
package Data import ( "github.com/team-zf/framework/dal" "github.com/wuxia-server/login/Control" "github.com/wuxia-server/login/DataTable" ) func GetServerList() (serverList []*DataTable.Server) { serverList = make([]*DataTable.Server, 0) sqlstr := dal.MarshalGetSql(DataTable.NewServer()) rows, err := Control.GateDB.Query(sqlstr) defer rows.Close() if err == nil { for rows.Next() { server := DataTable.NewServer() rows.Scan( &server.Id, &server.Title, &server.Status, &server.Host, &server.Port, &server.ServiceTime, ) serverList = append(serverList, server) } } return } func GetServerById(serverId int64) (server *DataTable.Server) { server = DataTable.NewServer() sqlstr := dal.MarshalGetSql(server, "id") row := Control.GateDB.QueryRow(sqlstr, serverId) if row.Scan( &server.Id, &server.Title, &server.Status, &server.Host, &server.Port, &server.ServiceTime, ) != nil { server = nil } return }
// array. package main import ( "encoding/json" "fmt" ) type Node struct { Name string `json:"name"` Age int `json:"age"` } type Nodes []*Node func (p *Nodes) MarshalIndent() { b, err := json.MarshalIndent(p, "", " ") if err != nil { panic(err) } fmt.Printf("%s\n", b) } func main() { var v Nodes fmt.Printf("before append:") v.MarshalIndent() v = append(v, &Node{ Name: "foo", Age: 10, }) fmt.Printf("after append:") v.MarshalIndent() }
package main import ( "fmt" ) func Sqrt(x float64) float64 { y := x- (((x * x) - x) / 2 * x ) return y } func main() { fmt.Println(Sqrt(Sqrt(Sqrt(3)))) }
package api_test import ( "blog/app/common/jwt" "blog/bootstrap" "blog/config" "github.com/kataras/iris/v12/httptest" "testing" ) func init() { config.InitConfig("../../blog.yaml") } func TestUserInfo(t *testing.T) { app := bootstrap.Register() e := httptest.New(t, app) token, err := jwt.MakeToken(1, "admin", "1986410806@qq.com", "管理员") if err != nil { t.Error(err) } e.GET("/admin/v1/user"). WithHeader("Authorization", "Bearer "+token). Expect().Status(httptest.StatusOK). JSON().Object(). ValueEqual("errorCode", 0). ValueEqual("success", true) }
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package alpha import ( "bytes" "context" "encoding/json" "fmt" "io/ioutil" "strings" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" ) func (r *Note) validate() error { if err := dcl.ValidateExactlyOneOfFieldsSet([]string{"Vulnerability", "Build", "Image", "Package", "Deployment", "Discovery", "Attestation"}, r.Vulnerability, r.Build, r.Image, r.Package, r.Deployment, r.Discovery, r.Attestation); err != nil { return err } if err := dcl.Required(r, "name"); err != nil { return err } if err := dcl.RequiredParameter(r.Project, "Project"); err != nil { return err } if !dcl.IsEmptyValueIndirect(r.Vulnerability) { if err := r.Vulnerability.validate(); err != nil { return err } } if !dcl.IsEmptyValueIndirect(r.Build) { if err := r.Build.validate(); err != nil { return err } } if !dcl.IsEmptyValueIndirect(r.Image) { if err := r.Image.validate(); err != nil { return err } } if !dcl.IsEmptyValueIndirect(r.Package) { if err := r.Package.validate(); err != nil { return err } } if !dcl.IsEmptyValueIndirect(r.Discovery) { if err := r.Discovery.validate(); err != nil { return err } } if !dcl.IsEmptyValueIndirect(r.Deployment) { if err := r.Deployment.validate(); err != nil { return err } } if !dcl.IsEmptyValueIndirect(r.Attestation) { if err := r.Attestation.validate(); err != nil { return err } } return nil } func (r *NoteRelatedUrl) validate() error { return nil } func (r *NoteVulnerability) validate() error { if !dcl.IsEmptyValueIndirect(r.CvssV3) { if err := r.CvssV3.validate(); err != nil { return err } } return nil } func (r *NoteVulnerabilityDetails) validate() error { if err := dcl.Required(r, "affectedCpeUri"); err != nil { return err } if err := dcl.Required(r, "affectedPackage"); err != nil { return err } if !dcl.IsEmptyValueIndirect(r.AffectedVersionStart) { if err := r.AffectedVersionStart.validate(); err != nil { return err } } if !dcl.IsEmptyValueIndirect(r.AffectedVersionEnd) { if err := r.AffectedVersionEnd.validate(); err != nil { return err } } if !dcl.IsEmptyValueIndirect(r.FixedVersion) { if err := r.FixedVersion.validate(); err != nil { return err } } return nil } func (r *NoteVulnerabilityDetailsAffectedVersionStart) validate() error { if err := dcl.Required(r, "kind"); err != nil { return err } return nil } func (r *NoteVulnerabilityDetailsAffectedVersionEnd) validate() error { if err := dcl.Required(r, "kind"); err != nil { return err } return nil } func (r *NoteVulnerabilityDetailsFixedVersion) validate() error { if err := dcl.Required(r, "kind"); err != nil { return err } return nil } func (r *NoteVulnerabilityCvssV3) validate() error { return nil } func (r *NoteVulnerabilityWindowsDetails) validate() error { if err := dcl.Required(r, "cpeUri"); err != nil { return err } if err := dcl.Required(r, "name"); err != nil { return err } if err := dcl.Required(r, "fixingKbs"); err != nil { return err } return nil } func (r *NoteVulnerabilityWindowsDetailsFixingKbs) validate() error { return nil } func (r *NoteBuild) validate() error { if err := dcl.Required(r, "builderVersion"); err != nil { return err } if !dcl.IsEmptyValueIndirect(r.Signature) { if err := r.Signature.validate(); err != nil { return err } } return nil } func (r *NoteBuildSignature) validate() error { if err := dcl.Required(r, "signature"); err != nil { return err } return nil } func (r *NoteImage) validate() error { if err := dcl.Required(r, "resourceUrl"); err != nil { return err } if err := dcl.Required(r, "fingerprint"); err != nil { return err } if !dcl.IsEmptyValueIndirect(r.Fingerprint) { if err := r.Fingerprint.validate(); err != nil { return err } } return nil } func (r *NoteImageFingerprint) validate() error { if err := dcl.Required(r, "v1Name"); err != nil { return err } if err := dcl.Required(r, "v2Blob"); err != nil { return err } return nil } func (r *NotePackage) validate() error { if err := dcl.Required(r, "name"); err != nil { return err } return nil } func (r *NotePackageDistribution) validate() error { if err := dcl.Required(r, "cpeUri"); err != nil { return err } if !dcl.IsEmptyValueIndirect(r.LatestVersion) { if err := r.LatestVersion.validate(); err != nil { return err } } return nil } func (r *NotePackageDistributionLatestVersion) validate() error { if err := dcl.Required(r, "kind"); err != nil { return err } return nil } func (r *NoteDiscovery) validate() error { if err := dcl.Required(r, "analysisKind"); err != nil { return err } return nil } func (r *NoteDeployment) validate() error { if err := dcl.Required(r, "resourceUri"); err != nil { return err } return nil } func (r *NoteAttestation) validate() error { if !dcl.IsEmptyValueIndirect(r.Hint) { if err := r.Hint.validate(); err != nil { return err } } return nil } func (r *NoteAttestationHint) validate() error { if err := dcl.Required(r, "humanReadableName"); err != nil { return err } return nil } func (r *Note) basePath() string { params := map[string]interface{}{} return dcl.Nprintf("https://containeranalysis.googleapis.com/v1alpha1/", params) } func (r *Note) getURL(userBasePath string) (string, error) { nr := r.urlNormalized() params := map[string]interface{}{ "project": dcl.ValueOrEmptyString(nr.Project), "name": dcl.ValueOrEmptyString(nr.Name), } return dcl.URL("projects/{{project}}/notes/{{name}}", nr.basePath(), userBasePath, params), nil } func (r *Note) listURL(userBasePath string) (string, error) { nr := r.urlNormalized() params := map[string]interface{}{ "project": dcl.ValueOrEmptyString(nr.Project), } return dcl.URL("projects/{{project}}/notes", nr.basePath(), userBasePath, params), nil } func (r *Note) createURL(userBasePath string) (string, error) { nr := r.urlNormalized() params := map[string]interface{}{ "project": dcl.ValueOrEmptyString(nr.Project), "name": dcl.ValueOrEmptyString(nr.Name), } return dcl.URL("projects/{{project}}/notes?noteId={{name}}", nr.basePath(), userBasePath, params), nil } func (r *Note) deleteURL(userBasePath string) (string, error) { nr := r.urlNormalized() params := map[string]interface{}{ "project": dcl.ValueOrEmptyString(nr.Project), "name": dcl.ValueOrEmptyString(nr.Name), } return dcl.URL("projects/{{project}}/notes/{{name}}", nr.basePath(), userBasePath, params), nil } // noteApiOperation represents a mutable operation in the underlying REST // API such as Create, Update, or Delete. type noteApiOperation interface { do(context.Context, *Note, *Client) error } // newUpdateNoteUpdateNoteRequest creates a request for an // Note resource's UpdateNote update type by filling in the update // fields based on the intended state of the resource. func newUpdateNoteUpdateNoteRequest(ctx context.Context, f *Note, c *Client) (map[string]interface{}, error) { req := map[string]interface{}{} res := f _ = res if v := f.ShortDescription; !dcl.IsEmptyValueIndirect(v) { req["shortDescription"] = v } if v := f.LongDescription; !dcl.IsEmptyValueIndirect(v) { req["longDescription"] = v } if v, err := expandNoteRelatedUrlSlice(c, f.RelatedUrl, res); err != nil { return nil, fmt.Errorf("error expanding RelatedUrl into relatedUrl: %w", err) } else if v != nil { req["relatedUrl"] = v } if v := f.ExpirationTime; !dcl.IsEmptyValueIndirect(v) { req["expirationTime"] = v } if v := f.RelatedNoteNames; v != nil { req["relatedNoteNames"] = v } if v, err := expandNoteVulnerability(c, f.Vulnerability, res); err != nil { return nil, fmt.Errorf("error expanding Vulnerability into vulnerability: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { req["vulnerability"] = v } if v, err := expandNoteBuild(c, f.Build, res); err != nil { return nil, fmt.Errorf("error expanding Build into build: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { req["build"] = v } if v, err := expandNoteImage(c, f.Image, res); err != nil { return nil, fmt.Errorf("error expanding Image into image: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { req["image"] = v } if v, err := expandNotePackage(c, f.Package, res); err != nil { return nil, fmt.Errorf("error expanding Package into package: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { req["package"] = v } if v, err := expandNoteDiscovery(c, f.Discovery, res); err != nil { return nil, fmt.Errorf("error expanding Discovery into discovery: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { req["discovery"] = v } if v, err := expandNoteDeployment(c, f.Deployment, res); err != nil { return nil, fmt.Errorf("error expanding Deployment into deployment: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { req["deployment"] = v } if v, err := expandNoteAttestation(c, f.Attestation, res); err != nil { return nil, fmt.Errorf("error expanding Attestation into attestation: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { req["attestation"] = v } return req, nil } // marshalUpdateNoteUpdateNoteRequest converts the update into // the final JSON request body. func marshalUpdateNoteUpdateNoteRequest(c *Client, m map[string]interface{}) ([]byte, error) { return json.Marshal(m) } type updateNoteUpdateNoteOperation struct { // If the update operation has the REQUIRES_APPLY_OPTIONS trait, this will be populated. // Usually it will be nil - this is to prevent us from accidentally depending on apply // options, which should usually be unnecessary. ApplyOptions []dcl.ApplyOption FieldDiffs []*dcl.FieldDiff } // do creates a request and sends it to the appropriate URL. In most operations, // do will transcribe a subset of the resource into a request object and send a // PUT request to a single URL. func (op *updateNoteUpdateNoteOperation) do(ctx context.Context, r *Note, c *Client) error { _, err := c.GetNote(ctx, r) if err != nil { return err } u, err := r.updateURL(c.Config.BasePath, "UpdateNote") if err != nil { return err } req, err := newUpdateNoteUpdateNoteRequest(ctx, r, c) if err != nil { return err } c.Config.Logger.InfoWithContextf(ctx, "Created update: %#v", req) body, err := marshalUpdateNoteUpdateNoteRequest(c, req) if err != nil { return err } _, err = dcl.SendRequest(ctx, c.Config, "PATCH", u, bytes.NewBuffer(body), c.Config.RetryProvider) if err != nil { return err } return nil } func (c *Client) listNoteRaw(ctx context.Context, r *Note, pageToken string, pageSize int32) ([]byte, error) { u, err := r.urlNormalized().listURL(c.Config.BasePath) if err != nil { return nil, err } m := make(map[string]string) if pageToken != "" { m["pageToken"] = pageToken } if pageSize != NoteMaxPage { m["pageSize"] = fmt.Sprintf("%v", pageSize) } u, err = dcl.AddQueryParams(u, m) if err != nil { return nil, err } resp, err := dcl.SendRequest(ctx, c.Config, "GET", u, &bytes.Buffer{}, c.Config.RetryProvider) if err != nil { return nil, err } defer resp.Response.Body.Close() return ioutil.ReadAll(resp.Response.Body) } type listNoteOperation struct { Notes []map[string]interface{} `json:"notes"` Token string `json:"nextPageToken"` } func (c *Client) listNote(ctx context.Context, r *Note, pageToken string, pageSize int32) ([]*Note, string, error) { b, err := c.listNoteRaw(ctx, r, pageToken, pageSize) if err != nil { return nil, "", err } var m listNoteOperation if err := json.Unmarshal(b, &m); err != nil { return nil, "", err } var l []*Note for _, v := range m.Notes { res, err := unmarshalMapNote(v, c, r) if err != nil { return nil, m.Token, err } res.Project = r.Project l = append(l, res) } return l, m.Token, nil } func (c *Client) deleteAllNote(ctx context.Context, f func(*Note) bool, resources []*Note) error { var errors []string for _, res := range resources { if f(res) { // We do not want deleteAll to fail on a deletion or else it will stop deleting other resources. err := c.DeleteNote(ctx, res) if err != nil { errors = append(errors, err.Error()) } } } if len(errors) > 0 { return fmt.Errorf("%v", strings.Join(errors, "\n")) } else { return nil } } type deleteNoteOperation struct{} func (op *deleteNoteOperation) do(ctx context.Context, r *Note, c *Client) error { r, err := c.GetNote(ctx, r) if err != nil { if dcl.IsNotFound(err) { c.Config.Logger.InfoWithContextf(ctx, "Note not found, returning. Original error: %v", err) return nil } c.Config.Logger.WarningWithContextf(ctx, "GetNote checking for existence. error: %v", err) return err } u, err := r.deleteURL(c.Config.BasePath) if err != nil { return err } // Delete should never have a body body := &bytes.Buffer{} _, err = dcl.SendRequest(ctx, c.Config, "DELETE", u, body, c.Config.RetryProvider) if err != nil { return fmt.Errorf("failed to delete Note: %w", err) } // We saw a race condition where for some successful delete operation, the Get calls returned resources for a short duration. // This is the reason we are adding retry to handle that case. retriesRemaining := 10 dcl.Do(ctx, func(ctx context.Context) (*dcl.RetryDetails, error) { _, err := c.GetNote(ctx, r) if dcl.IsNotFound(err) { return nil, nil } if retriesRemaining > 0 { retriesRemaining-- return &dcl.RetryDetails{}, dcl.OperationNotDone{} } return nil, dcl.NotDeletedError{ExistingResource: r} }, c.Config.RetryProvider) return nil } // Create operations are similar to Update operations, although they do not have // specific request objects. The Create request object is the json encoding of // the resource, which is modified by res.marshal to form the base request body. type createNoteOperation struct { response map[string]interface{} } func (op *createNoteOperation) FirstResponse() (map[string]interface{}, bool) { return op.response, len(op.response) > 0 } func (op *createNoteOperation) do(ctx context.Context, r *Note, c *Client) error { c.Config.Logger.InfoWithContextf(ctx, "Attempting to create %v", r) u, err := r.createURL(c.Config.BasePath) if err != nil { return err } req, err := r.marshal(c) if err != nil { return err } resp, err := dcl.SendRequest(ctx, c.Config, "POST", u, bytes.NewBuffer(req), c.Config.RetryProvider) if err != nil { return err } o, err := dcl.ResponseBodyAsJSON(resp) if err != nil { return fmt.Errorf("error decoding response body into JSON: %w", err) } op.response = o if _, err := c.GetNote(ctx, r); err != nil { c.Config.Logger.WarningWithContextf(ctx, "get returned error: %v", err) return err } return nil } func (c *Client) getNoteRaw(ctx context.Context, r *Note) ([]byte, error) { u, err := r.getURL(c.Config.BasePath) if err != nil { return nil, err } resp, err := dcl.SendRequest(ctx, c.Config, "GET", u, &bytes.Buffer{}, c.Config.RetryProvider) if err != nil { return nil, err } defer resp.Response.Body.Close() b, err := ioutil.ReadAll(resp.Response.Body) if err != nil { return nil, err } return b, nil } func (c *Client) noteDiffsForRawDesired(ctx context.Context, rawDesired *Note, opts ...dcl.ApplyOption) (initial, desired *Note, diffs []*dcl.FieldDiff, err error) { c.Config.Logger.InfoWithContext(ctx, "Fetching initial state...") // First, let us see if the user provided a state hint. If they did, we will start fetching based on that. var fetchState *Note if sh := dcl.FetchStateHint(opts); sh != nil { if r, ok := sh.(*Note); !ok { c.Config.Logger.WarningWithContextf(ctx, "Initial state hint was of the wrong type; expected Note, got %T", sh) } else { fetchState = r } } if fetchState == nil { fetchState = rawDesired } // 1.2: Retrieval of raw initial state from API rawInitial, err := c.GetNote(ctx, fetchState) if rawInitial == nil { if !dcl.IsNotFound(err) { c.Config.Logger.WarningWithContextf(ctx, "Failed to retrieve whether a Note resource already exists: %s", err) return nil, nil, nil, fmt.Errorf("failed to retrieve Note resource: %v", err) } c.Config.Logger.InfoWithContext(ctx, "Found that Note resource did not exist.") // Perform canonicalization to pick up defaults. desired, err = canonicalizeNoteDesiredState(rawDesired, rawInitial) return nil, desired, nil, err } c.Config.Logger.InfoWithContextf(ctx, "Found initial state for Note: %v", rawInitial) c.Config.Logger.InfoWithContextf(ctx, "Initial desired state for Note: %v", rawDesired) // The Get call applies postReadExtract and so the result may contain fields that are not part of API version. if err := extractNoteFields(rawInitial); err != nil { return nil, nil, nil, err } // 1.3: Canonicalize raw initial state into initial state. initial, err = canonicalizeNoteInitialState(rawInitial, rawDesired) if err != nil { return nil, nil, nil, err } c.Config.Logger.InfoWithContextf(ctx, "Canonicalized initial state for Note: %v", initial) // 1.4: Canonicalize raw desired state into desired state. desired, err = canonicalizeNoteDesiredState(rawDesired, rawInitial, opts...) if err != nil { return nil, nil, nil, err } c.Config.Logger.InfoWithContextf(ctx, "Canonicalized desired state for Note: %v", desired) // 2.1: Comparison of initial and desired state. diffs, err = diffNote(c, desired, initial, opts...) return initial, desired, diffs, err } func canonicalizeNoteInitialState(rawInitial, rawDesired *Note) (*Note, error) { // TODO(magic-modules-eng): write canonicalizer once relevant traits are added. if !dcl.IsZeroValue(rawInitial.Vulnerability) { // Check if anything else is set. if dcl.AnySet(rawInitial.Build, rawInitial.Image, rawInitial.Package, rawInitial.Deployment, rawInitial.Discovery, rawInitial.Attestation) { rawInitial.Vulnerability = EmptyNoteVulnerability } } if !dcl.IsZeroValue(rawInitial.Build) { // Check if anything else is set. if dcl.AnySet(rawInitial.Vulnerability, rawInitial.Image, rawInitial.Package, rawInitial.Deployment, rawInitial.Discovery, rawInitial.Attestation) { rawInitial.Build = EmptyNoteBuild } } if !dcl.IsZeroValue(rawInitial.Image) { // Check if anything else is set. if dcl.AnySet(rawInitial.Vulnerability, rawInitial.Build, rawInitial.Package, rawInitial.Deployment, rawInitial.Discovery, rawInitial.Attestation) { rawInitial.Image = EmptyNoteImage } } if !dcl.IsZeroValue(rawInitial.Package) { // Check if anything else is set. if dcl.AnySet(rawInitial.Vulnerability, rawInitial.Build, rawInitial.Image, rawInitial.Deployment, rawInitial.Discovery, rawInitial.Attestation) { rawInitial.Package = EmptyNotePackage } } if !dcl.IsZeroValue(rawInitial.Deployment) { // Check if anything else is set. if dcl.AnySet(rawInitial.Vulnerability, rawInitial.Build, rawInitial.Image, rawInitial.Package, rawInitial.Discovery, rawInitial.Attestation) { rawInitial.Deployment = EmptyNoteDeployment } } if !dcl.IsZeroValue(rawInitial.Discovery) { // Check if anything else is set. if dcl.AnySet(rawInitial.Vulnerability, rawInitial.Build, rawInitial.Image, rawInitial.Package, rawInitial.Deployment, rawInitial.Attestation) { rawInitial.Discovery = EmptyNoteDiscovery } } if !dcl.IsZeroValue(rawInitial.Attestation) { // Check if anything else is set. if dcl.AnySet(rawInitial.Vulnerability, rawInitial.Build, rawInitial.Image, rawInitial.Package, rawInitial.Deployment, rawInitial.Discovery) { rawInitial.Attestation = EmptyNoteAttestation } } return rawInitial, nil } /* * Canonicalizers * * These are responsible for converting either a user-specified config or a * GCP API response to a standard format that can be used for difference checking. * */ func canonicalizeNoteDesiredState(rawDesired, rawInitial *Note, opts ...dcl.ApplyOption) (*Note, error) { if rawInitial == nil { // Since the initial state is empty, the desired state is all we have. // We canonicalize the remaining nested objects with nil to pick up defaults. rawDesired.Vulnerability = canonicalizeNoteVulnerability(rawDesired.Vulnerability, nil, opts...) rawDesired.Build = canonicalizeNoteBuild(rawDesired.Build, nil, opts...) rawDesired.Image = canonicalizeNoteImage(rawDesired.Image, nil, opts...) rawDesired.Package = canonicalizeNotePackage(rawDesired.Package, nil, opts...) rawDesired.Discovery = canonicalizeNoteDiscovery(rawDesired.Discovery, nil, opts...) rawDesired.Deployment = canonicalizeNoteDeployment(rawDesired.Deployment, nil, opts...) rawDesired.Attestation = canonicalizeNoteAttestation(rawDesired.Attestation, nil, opts...) return rawDesired, nil } canonicalDesired := &Note{} if dcl.PartialSelfLinkToSelfLink(rawDesired.Name, rawInitial.Name) { canonicalDesired.Name = rawInitial.Name } else { canonicalDesired.Name = rawDesired.Name } if dcl.StringCanonicalize(rawDesired.ShortDescription, rawInitial.ShortDescription) { canonicalDesired.ShortDescription = rawInitial.ShortDescription } else { canonicalDesired.ShortDescription = rawDesired.ShortDescription } if dcl.StringCanonicalize(rawDesired.LongDescription, rawInitial.LongDescription) { canonicalDesired.LongDescription = rawInitial.LongDescription } else { canonicalDesired.LongDescription = rawDesired.LongDescription } canonicalDesired.RelatedUrl = canonicalizeNoteRelatedUrlSlice(rawDesired.RelatedUrl, rawInitial.RelatedUrl, opts...) if dcl.IsZeroValue(rawDesired.ExpirationTime) || (dcl.IsEmptyValueIndirect(rawDesired.ExpirationTime) && dcl.IsEmptyValueIndirect(rawInitial.ExpirationTime)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. canonicalDesired.ExpirationTime = rawInitial.ExpirationTime } else { canonicalDesired.ExpirationTime = rawDesired.ExpirationTime } if dcl.StringArrayCanonicalize(rawDesired.RelatedNoteNames, rawInitial.RelatedNoteNames) { canonicalDesired.RelatedNoteNames = rawInitial.RelatedNoteNames } else { canonicalDesired.RelatedNoteNames = rawDesired.RelatedNoteNames } canonicalDesired.Vulnerability = canonicalizeNoteVulnerability(rawDesired.Vulnerability, rawInitial.Vulnerability, opts...) canonicalDesired.Build = canonicalizeNoteBuild(rawDesired.Build, rawInitial.Build, opts...) canonicalDesired.Image = canonicalizeNoteImage(rawDesired.Image, rawInitial.Image, opts...) canonicalDesired.Package = canonicalizeNotePackage(rawDesired.Package, rawInitial.Package, opts...) canonicalDesired.Discovery = canonicalizeNoteDiscovery(rawDesired.Discovery, rawInitial.Discovery, opts...) canonicalDesired.Deployment = canonicalizeNoteDeployment(rawDesired.Deployment, rawInitial.Deployment, opts...) canonicalDesired.Attestation = canonicalizeNoteAttestation(rawDesired.Attestation, rawInitial.Attestation, opts...) if dcl.NameToSelfLink(rawDesired.Project, rawInitial.Project) { canonicalDesired.Project = rawInitial.Project } else { canonicalDesired.Project = rawDesired.Project } if canonicalDesired.Vulnerability != nil { // Check if anything else is set. if dcl.AnySet(rawDesired.Build, rawDesired.Image, rawDesired.Package, rawDesired.Deployment, rawDesired.Discovery, rawDesired.Attestation) { canonicalDesired.Vulnerability = EmptyNoteVulnerability } } if canonicalDesired.Build != nil { // Check if anything else is set. if dcl.AnySet(rawDesired.Vulnerability, rawDesired.Image, rawDesired.Package, rawDesired.Deployment, rawDesired.Discovery, rawDesired.Attestation) { canonicalDesired.Build = EmptyNoteBuild } } if canonicalDesired.Image != nil { // Check if anything else is set. if dcl.AnySet(rawDesired.Vulnerability, rawDesired.Build, rawDesired.Package, rawDesired.Deployment, rawDesired.Discovery, rawDesired.Attestation) { canonicalDesired.Image = EmptyNoteImage } } if canonicalDesired.Package != nil { // Check if anything else is set. if dcl.AnySet(rawDesired.Vulnerability, rawDesired.Build, rawDesired.Image, rawDesired.Deployment, rawDesired.Discovery, rawDesired.Attestation) { canonicalDesired.Package = EmptyNotePackage } } if canonicalDesired.Deployment != nil { // Check if anything else is set. if dcl.AnySet(rawDesired.Vulnerability, rawDesired.Build, rawDesired.Image, rawDesired.Package, rawDesired.Discovery, rawDesired.Attestation) { canonicalDesired.Deployment = EmptyNoteDeployment } } if canonicalDesired.Discovery != nil { // Check if anything else is set. if dcl.AnySet(rawDesired.Vulnerability, rawDesired.Build, rawDesired.Image, rawDesired.Package, rawDesired.Deployment, rawDesired.Attestation) { canonicalDesired.Discovery = EmptyNoteDiscovery } } if canonicalDesired.Attestation != nil { // Check if anything else is set. if dcl.AnySet(rawDesired.Vulnerability, rawDesired.Build, rawDesired.Image, rawDesired.Package, rawDesired.Deployment, rawDesired.Discovery) { canonicalDesired.Attestation = EmptyNoteAttestation } } return canonicalDesired, nil } func canonicalizeNoteNewState(c *Client, rawNew, rawDesired *Note) (*Note, error) { if dcl.IsEmptyValueIndirect(rawNew.Name) && dcl.IsEmptyValueIndirect(rawDesired.Name) { rawNew.Name = rawDesired.Name } else { if dcl.PartialSelfLinkToSelfLink(rawDesired.Name, rawNew.Name) { rawNew.Name = rawDesired.Name } } if dcl.IsEmptyValueIndirect(rawNew.ShortDescription) && dcl.IsEmptyValueIndirect(rawDesired.ShortDescription) { rawNew.ShortDescription = rawDesired.ShortDescription } else { if dcl.StringCanonicalize(rawDesired.ShortDescription, rawNew.ShortDescription) { rawNew.ShortDescription = rawDesired.ShortDescription } } if dcl.IsEmptyValueIndirect(rawNew.LongDescription) && dcl.IsEmptyValueIndirect(rawDesired.LongDescription) { rawNew.LongDescription = rawDesired.LongDescription } else { if dcl.StringCanonicalize(rawDesired.LongDescription, rawNew.LongDescription) { rawNew.LongDescription = rawDesired.LongDescription } } if dcl.IsEmptyValueIndirect(rawNew.RelatedUrl) && dcl.IsEmptyValueIndirect(rawDesired.RelatedUrl) { rawNew.RelatedUrl = rawDesired.RelatedUrl } else { rawNew.RelatedUrl = canonicalizeNewNoteRelatedUrlSlice(c, rawDesired.RelatedUrl, rawNew.RelatedUrl) } if dcl.IsEmptyValueIndirect(rawNew.ExpirationTime) && dcl.IsEmptyValueIndirect(rawDesired.ExpirationTime) { rawNew.ExpirationTime = rawDesired.ExpirationTime } else { } if dcl.IsEmptyValueIndirect(rawNew.CreateTime) && dcl.IsEmptyValueIndirect(rawDesired.CreateTime) { rawNew.CreateTime = rawDesired.CreateTime } else { } if dcl.IsEmptyValueIndirect(rawNew.UpdateTime) && dcl.IsEmptyValueIndirect(rawDesired.UpdateTime) { rawNew.UpdateTime = rawDesired.UpdateTime } else { } if dcl.IsEmptyValueIndirect(rawNew.RelatedNoteNames) && dcl.IsEmptyValueIndirect(rawDesired.RelatedNoteNames) { rawNew.RelatedNoteNames = rawDesired.RelatedNoteNames } else { if dcl.StringArrayCanonicalize(rawDesired.RelatedNoteNames, rawNew.RelatedNoteNames) { rawNew.RelatedNoteNames = rawDesired.RelatedNoteNames } } if dcl.IsEmptyValueIndirect(rawNew.Vulnerability) && dcl.IsEmptyValueIndirect(rawDesired.Vulnerability) { rawNew.Vulnerability = rawDesired.Vulnerability } else { rawNew.Vulnerability = canonicalizeNewNoteVulnerability(c, rawDesired.Vulnerability, rawNew.Vulnerability) } if dcl.IsEmptyValueIndirect(rawNew.Build) && dcl.IsEmptyValueIndirect(rawDesired.Build) { rawNew.Build = rawDesired.Build } else { rawNew.Build = canonicalizeNewNoteBuild(c, rawDesired.Build, rawNew.Build) } if dcl.IsEmptyValueIndirect(rawNew.Image) && dcl.IsEmptyValueIndirect(rawDesired.Image) { rawNew.Image = rawDesired.Image } else { rawNew.Image = canonicalizeNewNoteImage(c, rawDesired.Image, rawNew.Image) } if dcl.IsEmptyValueIndirect(rawNew.Package) && dcl.IsEmptyValueIndirect(rawDesired.Package) { rawNew.Package = rawDesired.Package } else { rawNew.Package = canonicalizeNewNotePackage(c, rawDesired.Package, rawNew.Package) } if dcl.IsEmptyValueIndirect(rawNew.Discovery) && dcl.IsEmptyValueIndirect(rawDesired.Discovery) { rawNew.Discovery = rawDesired.Discovery } else { rawNew.Discovery = canonicalizeNewNoteDiscovery(c, rawDesired.Discovery, rawNew.Discovery) } if dcl.IsEmptyValueIndirect(rawNew.Deployment) && dcl.IsEmptyValueIndirect(rawDesired.Deployment) { rawNew.Deployment = rawDesired.Deployment } else { rawNew.Deployment = canonicalizeNewNoteDeployment(c, rawDesired.Deployment, rawNew.Deployment) } if dcl.IsEmptyValueIndirect(rawNew.Attestation) && dcl.IsEmptyValueIndirect(rawDesired.Attestation) { rawNew.Attestation = rawDesired.Attestation } else { rawNew.Attestation = canonicalizeNewNoteAttestation(c, rawDesired.Attestation, rawNew.Attestation) } rawNew.Project = rawDesired.Project return rawNew, nil } func canonicalizeNoteRelatedUrl(des, initial *NoteRelatedUrl, opts ...dcl.ApplyOption) *NoteRelatedUrl { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteRelatedUrl{} if dcl.StringCanonicalize(des.Url, initial.Url) || dcl.IsZeroValue(des.Url) { cDes.Url = initial.Url } else { cDes.Url = des.Url } if dcl.StringCanonicalize(des.Label, initial.Label) || dcl.IsZeroValue(des.Label) { cDes.Label = initial.Label } else { cDes.Label = des.Label } return cDes } func canonicalizeNoteRelatedUrlSlice(des, initial []NoteRelatedUrl, opts ...dcl.ApplyOption) []NoteRelatedUrl { if des == nil { return initial } if len(des) != len(initial) { items := make([]NoteRelatedUrl, 0, len(des)) for _, d := range des { cd := canonicalizeNoteRelatedUrl(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteRelatedUrl, 0, len(des)) for i, d := range des { cd := canonicalizeNoteRelatedUrl(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteRelatedUrl(c *Client, des, nw *NoteRelatedUrl) *NoteRelatedUrl { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteRelatedUrl while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.Url, nw.Url) { nw.Url = des.Url } if dcl.StringCanonicalize(des.Label, nw.Label) { nw.Label = des.Label } return nw } func canonicalizeNewNoteRelatedUrlSet(c *Client, des, nw []NoteRelatedUrl) []NoteRelatedUrl { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteRelatedUrl for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteRelatedUrlNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteRelatedUrl(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteRelatedUrlSlice(c *Client, des, nw []NoteRelatedUrl) []NoteRelatedUrl { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteRelatedUrl for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteRelatedUrl(c, &d, &n)) } return items } func canonicalizeNoteVulnerability(des, initial *NoteVulnerability, opts ...dcl.ApplyOption) *NoteVulnerability { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteVulnerability{} if dcl.IsZeroValue(des.CvssScore) || (dcl.IsEmptyValueIndirect(des.CvssScore) && dcl.IsEmptyValueIndirect(initial.CvssScore)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.CvssScore = initial.CvssScore } else { cDes.CvssScore = des.CvssScore } if dcl.IsZeroValue(des.Severity) || (dcl.IsEmptyValueIndirect(des.Severity) && dcl.IsEmptyValueIndirect(initial.Severity)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Severity = initial.Severity } else { cDes.Severity = des.Severity } cDes.Details = canonicalizeNoteVulnerabilityDetailsSlice(des.Details, initial.Details, opts...) cDes.CvssV3 = canonicalizeNoteVulnerabilityCvssV3(des.CvssV3, initial.CvssV3, opts...) cDes.WindowsDetails = canonicalizeNoteVulnerabilityWindowsDetailsSlice(des.WindowsDetails, initial.WindowsDetails, opts...) if dcl.IsZeroValue(des.SourceUpdateTime) || (dcl.IsEmptyValueIndirect(des.SourceUpdateTime) && dcl.IsEmptyValueIndirect(initial.SourceUpdateTime)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.SourceUpdateTime = initial.SourceUpdateTime } else { cDes.SourceUpdateTime = des.SourceUpdateTime } return cDes } func canonicalizeNoteVulnerabilitySlice(des, initial []NoteVulnerability, opts ...dcl.ApplyOption) []NoteVulnerability { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NoteVulnerability, 0, len(des)) for _, d := range des { cd := canonicalizeNoteVulnerability(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteVulnerability, 0, len(des)) for i, d := range des { cd := canonicalizeNoteVulnerability(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteVulnerability(c *Client, des, nw *NoteVulnerability) *NoteVulnerability { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteVulnerability while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } nw.Details = canonicalizeNewNoteVulnerabilityDetailsSlice(c, des.Details, nw.Details) nw.CvssV3 = canonicalizeNewNoteVulnerabilityCvssV3(c, des.CvssV3, nw.CvssV3) nw.WindowsDetails = canonicalizeNewNoteVulnerabilityWindowsDetailsSlice(c, des.WindowsDetails, nw.WindowsDetails) return nw } func canonicalizeNewNoteVulnerabilitySet(c *Client, des, nw []NoteVulnerability) []NoteVulnerability { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteVulnerability for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteVulnerabilityNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteVulnerability(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteVulnerabilitySlice(c *Client, des, nw []NoteVulnerability) []NoteVulnerability { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteVulnerability for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteVulnerability(c, &d, &n)) } return items } func canonicalizeNoteVulnerabilityDetails(des, initial *NoteVulnerabilityDetails, opts ...dcl.ApplyOption) *NoteVulnerabilityDetails { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteVulnerabilityDetails{} if dcl.StringCanonicalize(des.SeverityName, initial.SeverityName) || dcl.IsZeroValue(des.SeverityName) { cDes.SeverityName = initial.SeverityName } else { cDes.SeverityName = des.SeverityName } if dcl.StringCanonicalize(des.Description, initial.Description) || dcl.IsZeroValue(des.Description) { cDes.Description = initial.Description } else { cDes.Description = des.Description } if dcl.StringCanonicalize(des.PackageType, initial.PackageType) || dcl.IsZeroValue(des.PackageType) { cDes.PackageType = initial.PackageType } else { cDes.PackageType = des.PackageType } if dcl.StringCanonicalize(des.AffectedCpeUri, initial.AffectedCpeUri) || dcl.IsZeroValue(des.AffectedCpeUri) { cDes.AffectedCpeUri = initial.AffectedCpeUri } else { cDes.AffectedCpeUri = des.AffectedCpeUri } if dcl.StringCanonicalize(des.AffectedPackage, initial.AffectedPackage) || dcl.IsZeroValue(des.AffectedPackage) { cDes.AffectedPackage = initial.AffectedPackage } else { cDes.AffectedPackage = des.AffectedPackage } cDes.AffectedVersionStart = canonicalizeNoteVulnerabilityDetailsAffectedVersionStart(des.AffectedVersionStart, initial.AffectedVersionStart, opts...) cDes.AffectedVersionEnd = canonicalizeNoteVulnerabilityDetailsAffectedVersionEnd(des.AffectedVersionEnd, initial.AffectedVersionEnd, opts...) if dcl.StringCanonicalize(des.FixedCpeUri, initial.FixedCpeUri) || dcl.IsZeroValue(des.FixedCpeUri) { cDes.FixedCpeUri = initial.FixedCpeUri } else { cDes.FixedCpeUri = des.FixedCpeUri } if dcl.StringCanonicalize(des.FixedPackage, initial.FixedPackage) || dcl.IsZeroValue(des.FixedPackage) { cDes.FixedPackage = initial.FixedPackage } else { cDes.FixedPackage = des.FixedPackage } cDes.FixedVersion = canonicalizeNoteVulnerabilityDetailsFixedVersion(des.FixedVersion, initial.FixedVersion, opts...) if dcl.BoolCanonicalize(des.IsObsolete, initial.IsObsolete) || dcl.IsZeroValue(des.IsObsolete) { cDes.IsObsolete = initial.IsObsolete } else { cDes.IsObsolete = des.IsObsolete } if dcl.IsZeroValue(des.SourceUpdateTime) || (dcl.IsEmptyValueIndirect(des.SourceUpdateTime) && dcl.IsEmptyValueIndirect(initial.SourceUpdateTime)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.SourceUpdateTime = initial.SourceUpdateTime } else { cDes.SourceUpdateTime = des.SourceUpdateTime } return cDes } func canonicalizeNoteVulnerabilityDetailsSlice(des, initial []NoteVulnerabilityDetails, opts ...dcl.ApplyOption) []NoteVulnerabilityDetails { if des == nil { return initial } if len(des) != len(initial) { items := make([]NoteVulnerabilityDetails, 0, len(des)) for _, d := range des { cd := canonicalizeNoteVulnerabilityDetails(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteVulnerabilityDetails, 0, len(des)) for i, d := range des { cd := canonicalizeNoteVulnerabilityDetails(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteVulnerabilityDetails(c *Client, des, nw *NoteVulnerabilityDetails) *NoteVulnerabilityDetails { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteVulnerabilityDetails while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.SeverityName, nw.SeverityName) { nw.SeverityName = des.SeverityName } if dcl.StringCanonicalize(des.Description, nw.Description) { nw.Description = des.Description } if dcl.StringCanonicalize(des.PackageType, nw.PackageType) { nw.PackageType = des.PackageType } if dcl.StringCanonicalize(des.AffectedCpeUri, nw.AffectedCpeUri) { nw.AffectedCpeUri = des.AffectedCpeUri } if dcl.StringCanonicalize(des.AffectedPackage, nw.AffectedPackage) { nw.AffectedPackage = des.AffectedPackage } nw.AffectedVersionStart = canonicalizeNewNoteVulnerabilityDetailsAffectedVersionStart(c, des.AffectedVersionStart, nw.AffectedVersionStart) nw.AffectedVersionEnd = canonicalizeNewNoteVulnerabilityDetailsAffectedVersionEnd(c, des.AffectedVersionEnd, nw.AffectedVersionEnd) if dcl.StringCanonicalize(des.FixedCpeUri, nw.FixedCpeUri) { nw.FixedCpeUri = des.FixedCpeUri } if dcl.StringCanonicalize(des.FixedPackage, nw.FixedPackage) { nw.FixedPackage = des.FixedPackage } nw.FixedVersion = canonicalizeNewNoteVulnerabilityDetailsFixedVersion(c, des.FixedVersion, nw.FixedVersion) if dcl.BoolCanonicalize(des.IsObsolete, nw.IsObsolete) { nw.IsObsolete = des.IsObsolete } return nw } func canonicalizeNewNoteVulnerabilityDetailsSet(c *Client, des, nw []NoteVulnerabilityDetails) []NoteVulnerabilityDetails { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteVulnerabilityDetails for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteVulnerabilityDetailsNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteVulnerabilityDetails(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteVulnerabilityDetailsSlice(c *Client, des, nw []NoteVulnerabilityDetails) []NoteVulnerabilityDetails { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteVulnerabilityDetails for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteVulnerabilityDetails(c, &d, &n)) } return items } func canonicalizeNoteVulnerabilityDetailsAffectedVersionStart(des, initial *NoteVulnerabilityDetailsAffectedVersionStart, opts ...dcl.ApplyOption) *NoteVulnerabilityDetailsAffectedVersionStart { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteVulnerabilityDetailsAffectedVersionStart{} if dcl.IsZeroValue(des.Epoch) || (dcl.IsEmptyValueIndirect(des.Epoch) && dcl.IsEmptyValueIndirect(initial.Epoch)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Epoch = initial.Epoch } else { cDes.Epoch = des.Epoch } if dcl.StringCanonicalize(des.Name, initial.Name) || dcl.IsZeroValue(des.Name) { cDes.Name = initial.Name } else { cDes.Name = des.Name } if dcl.StringCanonicalize(des.Revision, initial.Revision) || dcl.IsZeroValue(des.Revision) { cDes.Revision = initial.Revision } else { cDes.Revision = des.Revision } if dcl.IsZeroValue(des.Kind) || (dcl.IsEmptyValueIndirect(des.Kind) && dcl.IsEmptyValueIndirect(initial.Kind)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Kind = initial.Kind } else { cDes.Kind = des.Kind } if dcl.StringCanonicalize(des.FullName, initial.FullName) || dcl.IsZeroValue(des.FullName) { cDes.FullName = initial.FullName } else { cDes.FullName = des.FullName } return cDes } func canonicalizeNoteVulnerabilityDetailsAffectedVersionStartSlice(des, initial []NoteVulnerabilityDetailsAffectedVersionStart, opts ...dcl.ApplyOption) []NoteVulnerabilityDetailsAffectedVersionStart { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NoteVulnerabilityDetailsAffectedVersionStart, 0, len(des)) for _, d := range des { cd := canonicalizeNoteVulnerabilityDetailsAffectedVersionStart(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteVulnerabilityDetailsAffectedVersionStart, 0, len(des)) for i, d := range des { cd := canonicalizeNoteVulnerabilityDetailsAffectedVersionStart(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteVulnerabilityDetailsAffectedVersionStart(c *Client, des, nw *NoteVulnerabilityDetailsAffectedVersionStart) *NoteVulnerabilityDetailsAffectedVersionStart { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteVulnerabilityDetailsAffectedVersionStart while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.Name, nw.Name) { nw.Name = des.Name } if dcl.StringCanonicalize(des.Revision, nw.Revision) { nw.Revision = des.Revision } if dcl.StringCanonicalize(des.FullName, nw.FullName) { nw.FullName = des.FullName } return nw } func canonicalizeNewNoteVulnerabilityDetailsAffectedVersionStartSet(c *Client, des, nw []NoteVulnerabilityDetailsAffectedVersionStart) []NoteVulnerabilityDetailsAffectedVersionStart { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteVulnerabilityDetailsAffectedVersionStart for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteVulnerabilityDetailsAffectedVersionStartNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteVulnerabilityDetailsAffectedVersionStart(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteVulnerabilityDetailsAffectedVersionStartSlice(c *Client, des, nw []NoteVulnerabilityDetailsAffectedVersionStart) []NoteVulnerabilityDetailsAffectedVersionStart { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteVulnerabilityDetailsAffectedVersionStart for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteVulnerabilityDetailsAffectedVersionStart(c, &d, &n)) } return items } func canonicalizeNoteVulnerabilityDetailsAffectedVersionEnd(des, initial *NoteVulnerabilityDetailsAffectedVersionEnd, opts ...dcl.ApplyOption) *NoteVulnerabilityDetailsAffectedVersionEnd { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteVulnerabilityDetailsAffectedVersionEnd{} if dcl.IsZeroValue(des.Epoch) || (dcl.IsEmptyValueIndirect(des.Epoch) && dcl.IsEmptyValueIndirect(initial.Epoch)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Epoch = initial.Epoch } else { cDes.Epoch = des.Epoch } if dcl.StringCanonicalize(des.Name, initial.Name) || dcl.IsZeroValue(des.Name) { cDes.Name = initial.Name } else { cDes.Name = des.Name } if dcl.StringCanonicalize(des.Revision, initial.Revision) || dcl.IsZeroValue(des.Revision) { cDes.Revision = initial.Revision } else { cDes.Revision = des.Revision } if dcl.IsZeroValue(des.Kind) || (dcl.IsEmptyValueIndirect(des.Kind) && dcl.IsEmptyValueIndirect(initial.Kind)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Kind = initial.Kind } else { cDes.Kind = des.Kind } if dcl.StringCanonicalize(des.FullName, initial.FullName) || dcl.IsZeroValue(des.FullName) { cDes.FullName = initial.FullName } else { cDes.FullName = des.FullName } return cDes } func canonicalizeNoteVulnerabilityDetailsAffectedVersionEndSlice(des, initial []NoteVulnerabilityDetailsAffectedVersionEnd, opts ...dcl.ApplyOption) []NoteVulnerabilityDetailsAffectedVersionEnd { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NoteVulnerabilityDetailsAffectedVersionEnd, 0, len(des)) for _, d := range des { cd := canonicalizeNoteVulnerabilityDetailsAffectedVersionEnd(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteVulnerabilityDetailsAffectedVersionEnd, 0, len(des)) for i, d := range des { cd := canonicalizeNoteVulnerabilityDetailsAffectedVersionEnd(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteVulnerabilityDetailsAffectedVersionEnd(c *Client, des, nw *NoteVulnerabilityDetailsAffectedVersionEnd) *NoteVulnerabilityDetailsAffectedVersionEnd { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteVulnerabilityDetailsAffectedVersionEnd while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.Name, nw.Name) { nw.Name = des.Name } if dcl.StringCanonicalize(des.Revision, nw.Revision) { nw.Revision = des.Revision } if dcl.StringCanonicalize(des.FullName, nw.FullName) { nw.FullName = des.FullName } return nw } func canonicalizeNewNoteVulnerabilityDetailsAffectedVersionEndSet(c *Client, des, nw []NoteVulnerabilityDetailsAffectedVersionEnd) []NoteVulnerabilityDetailsAffectedVersionEnd { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteVulnerabilityDetailsAffectedVersionEnd for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteVulnerabilityDetailsAffectedVersionEndNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteVulnerabilityDetailsAffectedVersionEnd(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteVulnerabilityDetailsAffectedVersionEndSlice(c *Client, des, nw []NoteVulnerabilityDetailsAffectedVersionEnd) []NoteVulnerabilityDetailsAffectedVersionEnd { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteVulnerabilityDetailsAffectedVersionEnd for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteVulnerabilityDetailsAffectedVersionEnd(c, &d, &n)) } return items } func canonicalizeNoteVulnerabilityDetailsFixedVersion(des, initial *NoteVulnerabilityDetailsFixedVersion, opts ...dcl.ApplyOption) *NoteVulnerabilityDetailsFixedVersion { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteVulnerabilityDetailsFixedVersion{} if dcl.IsZeroValue(des.Epoch) || (dcl.IsEmptyValueIndirect(des.Epoch) && dcl.IsEmptyValueIndirect(initial.Epoch)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Epoch = initial.Epoch } else { cDes.Epoch = des.Epoch } if dcl.StringCanonicalize(des.Name, initial.Name) || dcl.IsZeroValue(des.Name) { cDes.Name = initial.Name } else { cDes.Name = des.Name } if dcl.StringCanonicalize(des.Revision, initial.Revision) || dcl.IsZeroValue(des.Revision) { cDes.Revision = initial.Revision } else { cDes.Revision = des.Revision } if dcl.IsZeroValue(des.Kind) || (dcl.IsEmptyValueIndirect(des.Kind) && dcl.IsEmptyValueIndirect(initial.Kind)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Kind = initial.Kind } else { cDes.Kind = des.Kind } if dcl.StringCanonicalize(des.FullName, initial.FullName) || dcl.IsZeroValue(des.FullName) { cDes.FullName = initial.FullName } else { cDes.FullName = des.FullName } return cDes } func canonicalizeNoteVulnerabilityDetailsFixedVersionSlice(des, initial []NoteVulnerabilityDetailsFixedVersion, opts ...dcl.ApplyOption) []NoteVulnerabilityDetailsFixedVersion { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NoteVulnerabilityDetailsFixedVersion, 0, len(des)) for _, d := range des { cd := canonicalizeNoteVulnerabilityDetailsFixedVersion(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteVulnerabilityDetailsFixedVersion, 0, len(des)) for i, d := range des { cd := canonicalizeNoteVulnerabilityDetailsFixedVersion(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteVulnerabilityDetailsFixedVersion(c *Client, des, nw *NoteVulnerabilityDetailsFixedVersion) *NoteVulnerabilityDetailsFixedVersion { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteVulnerabilityDetailsFixedVersion while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.Name, nw.Name) { nw.Name = des.Name } if dcl.StringCanonicalize(des.Revision, nw.Revision) { nw.Revision = des.Revision } if dcl.StringCanonicalize(des.FullName, nw.FullName) { nw.FullName = des.FullName } return nw } func canonicalizeNewNoteVulnerabilityDetailsFixedVersionSet(c *Client, des, nw []NoteVulnerabilityDetailsFixedVersion) []NoteVulnerabilityDetailsFixedVersion { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteVulnerabilityDetailsFixedVersion for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteVulnerabilityDetailsFixedVersionNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteVulnerabilityDetailsFixedVersion(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteVulnerabilityDetailsFixedVersionSlice(c *Client, des, nw []NoteVulnerabilityDetailsFixedVersion) []NoteVulnerabilityDetailsFixedVersion { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteVulnerabilityDetailsFixedVersion for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteVulnerabilityDetailsFixedVersion(c, &d, &n)) } return items } func canonicalizeNoteVulnerabilityCvssV3(des, initial *NoteVulnerabilityCvssV3, opts ...dcl.ApplyOption) *NoteVulnerabilityCvssV3 { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteVulnerabilityCvssV3{} if dcl.IsZeroValue(des.BaseScore) || (dcl.IsEmptyValueIndirect(des.BaseScore) && dcl.IsEmptyValueIndirect(initial.BaseScore)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.BaseScore = initial.BaseScore } else { cDes.BaseScore = des.BaseScore } if dcl.IsZeroValue(des.ExploitabilityScore) || (dcl.IsEmptyValueIndirect(des.ExploitabilityScore) && dcl.IsEmptyValueIndirect(initial.ExploitabilityScore)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.ExploitabilityScore = initial.ExploitabilityScore } else { cDes.ExploitabilityScore = des.ExploitabilityScore } if dcl.IsZeroValue(des.ImpactScore) || (dcl.IsEmptyValueIndirect(des.ImpactScore) && dcl.IsEmptyValueIndirect(initial.ImpactScore)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.ImpactScore = initial.ImpactScore } else { cDes.ImpactScore = des.ImpactScore } if dcl.IsZeroValue(des.AttackVector) || (dcl.IsEmptyValueIndirect(des.AttackVector) && dcl.IsEmptyValueIndirect(initial.AttackVector)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.AttackVector = initial.AttackVector } else { cDes.AttackVector = des.AttackVector } if dcl.IsZeroValue(des.AttackComplexity) || (dcl.IsEmptyValueIndirect(des.AttackComplexity) && dcl.IsEmptyValueIndirect(initial.AttackComplexity)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.AttackComplexity = initial.AttackComplexity } else { cDes.AttackComplexity = des.AttackComplexity } if dcl.IsZeroValue(des.PrivilegesRequired) || (dcl.IsEmptyValueIndirect(des.PrivilegesRequired) && dcl.IsEmptyValueIndirect(initial.PrivilegesRequired)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.PrivilegesRequired = initial.PrivilegesRequired } else { cDes.PrivilegesRequired = des.PrivilegesRequired } if dcl.IsZeroValue(des.UserInteraction) || (dcl.IsEmptyValueIndirect(des.UserInteraction) && dcl.IsEmptyValueIndirect(initial.UserInteraction)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.UserInteraction = initial.UserInteraction } else { cDes.UserInteraction = des.UserInteraction } if dcl.IsZeroValue(des.Scope) || (dcl.IsEmptyValueIndirect(des.Scope) && dcl.IsEmptyValueIndirect(initial.Scope)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Scope = initial.Scope } else { cDes.Scope = des.Scope } if dcl.IsZeroValue(des.ConfidentialityImpact) || (dcl.IsEmptyValueIndirect(des.ConfidentialityImpact) && dcl.IsEmptyValueIndirect(initial.ConfidentialityImpact)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.ConfidentialityImpact = initial.ConfidentialityImpact } else { cDes.ConfidentialityImpact = des.ConfidentialityImpact } if dcl.IsZeroValue(des.IntegrityImpact) || (dcl.IsEmptyValueIndirect(des.IntegrityImpact) && dcl.IsEmptyValueIndirect(initial.IntegrityImpact)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.IntegrityImpact = initial.IntegrityImpact } else { cDes.IntegrityImpact = des.IntegrityImpact } if dcl.IsZeroValue(des.AvailabilityImpact) || (dcl.IsEmptyValueIndirect(des.AvailabilityImpact) && dcl.IsEmptyValueIndirect(initial.AvailabilityImpact)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.AvailabilityImpact = initial.AvailabilityImpact } else { cDes.AvailabilityImpact = des.AvailabilityImpact } return cDes } func canonicalizeNoteVulnerabilityCvssV3Slice(des, initial []NoteVulnerabilityCvssV3, opts ...dcl.ApplyOption) []NoteVulnerabilityCvssV3 { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NoteVulnerabilityCvssV3, 0, len(des)) for _, d := range des { cd := canonicalizeNoteVulnerabilityCvssV3(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteVulnerabilityCvssV3, 0, len(des)) for i, d := range des { cd := canonicalizeNoteVulnerabilityCvssV3(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteVulnerabilityCvssV3(c *Client, des, nw *NoteVulnerabilityCvssV3) *NoteVulnerabilityCvssV3 { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteVulnerabilityCvssV3 while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } return nw } func canonicalizeNewNoteVulnerabilityCvssV3Set(c *Client, des, nw []NoteVulnerabilityCvssV3) []NoteVulnerabilityCvssV3 { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteVulnerabilityCvssV3 for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteVulnerabilityCvssV3NewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteVulnerabilityCvssV3(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteVulnerabilityCvssV3Slice(c *Client, des, nw []NoteVulnerabilityCvssV3) []NoteVulnerabilityCvssV3 { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteVulnerabilityCvssV3 for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteVulnerabilityCvssV3(c, &d, &n)) } return items } func canonicalizeNoteVulnerabilityWindowsDetails(des, initial *NoteVulnerabilityWindowsDetails, opts ...dcl.ApplyOption) *NoteVulnerabilityWindowsDetails { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteVulnerabilityWindowsDetails{} if dcl.StringCanonicalize(des.CpeUri, initial.CpeUri) || dcl.IsZeroValue(des.CpeUri) { cDes.CpeUri = initial.CpeUri } else { cDes.CpeUri = des.CpeUri } if dcl.StringCanonicalize(des.Name, initial.Name) || dcl.IsZeroValue(des.Name) { cDes.Name = initial.Name } else { cDes.Name = des.Name } if dcl.StringCanonicalize(des.Description, initial.Description) || dcl.IsZeroValue(des.Description) { cDes.Description = initial.Description } else { cDes.Description = des.Description } cDes.FixingKbs = canonicalizeNoteVulnerabilityWindowsDetailsFixingKbsSlice(des.FixingKbs, initial.FixingKbs, opts...) return cDes } func canonicalizeNoteVulnerabilityWindowsDetailsSlice(des, initial []NoteVulnerabilityWindowsDetails, opts ...dcl.ApplyOption) []NoteVulnerabilityWindowsDetails { if des == nil { return initial } if len(des) != len(initial) { items := make([]NoteVulnerabilityWindowsDetails, 0, len(des)) for _, d := range des { cd := canonicalizeNoteVulnerabilityWindowsDetails(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteVulnerabilityWindowsDetails, 0, len(des)) for i, d := range des { cd := canonicalizeNoteVulnerabilityWindowsDetails(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteVulnerabilityWindowsDetails(c *Client, des, nw *NoteVulnerabilityWindowsDetails) *NoteVulnerabilityWindowsDetails { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteVulnerabilityWindowsDetails while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.CpeUri, nw.CpeUri) { nw.CpeUri = des.CpeUri } if dcl.StringCanonicalize(des.Name, nw.Name) { nw.Name = des.Name } if dcl.StringCanonicalize(des.Description, nw.Description) { nw.Description = des.Description } nw.FixingKbs = canonicalizeNewNoteVulnerabilityWindowsDetailsFixingKbsSlice(c, des.FixingKbs, nw.FixingKbs) return nw } func canonicalizeNewNoteVulnerabilityWindowsDetailsSet(c *Client, des, nw []NoteVulnerabilityWindowsDetails) []NoteVulnerabilityWindowsDetails { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteVulnerabilityWindowsDetails for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteVulnerabilityWindowsDetailsNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteVulnerabilityWindowsDetails(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteVulnerabilityWindowsDetailsSlice(c *Client, des, nw []NoteVulnerabilityWindowsDetails) []NoteVulnerabilityWindowsDetails { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteVulnerabilityWindowsDetails for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteVulnerabilityWindowsDetails(c, &d, &n)) } return items } func canonicalizeNoteVulnerabilityWindowsDetailsFixingKbs(des, initial *NoteVulnerabilityWindowsDetailsFixingKbs, opts ...dcl.ApplyOption) *NoteVulnerabilityWindowsDetailsFixingKbs { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteVulnerabilityWindowsDetailsFixingKbs{} if dcl.StringCanonicalize(des.Name, initial.Name) || dcl.IsZeroValue(des.Name) { cDes.Name = initial.Name } else { cDes.Name = des.Name } if dcl.StringCanonicalize(des.Url, initial.Url) || dcl.IsZeroValue(des.Url) { cDes.Url = initial.Url } else { cDes.Url = des.Url } return cDes } func canonicalizeNoteVulnerabilityWindowsDetailsFixingKbsSlice(des, initial []NoteVulnerabilityWindowsDetailsFixingKbs, opts ...dcl.ApplyOption) []NoteVulnerabilityWindowsDetailsFixingKbs { if des == nil { return initial } if len(des) != len(initial) { items := make([]NoteVulnerabilityWindowsDetailsFixingKbs, 0, len(des)) for _, d := range des { cd := canonicalizeNoteVulnerabilityWindowsDetailsFixingKbs(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteVulnerabilityWindowsDetailsFixingKbs, 0, len(des)) for i, d := range des { cd := canonicalizeNoteVulnerabilityWindowsDetailsFixingKbs(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteVulnerabilityWindowsDetailsFixingKbs(c *Client, des, nw *NoteVulnerabilityWindowsDetailsFixingKbs) *NoteVulnerabilityWindowsDetailsFixingKbs { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteVulnerabilityWindowsDetailsFixingKbs while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.Name, nw.Name) { nw.Name = des.Name } if dcl.StringCanonicalize(des.Url, nw.Url) { nw.Url = des.Url } return nw } func canonicalizeNewNoteVulnerabilityWindowsDetailsFixingKbsSet(c *Client, des, nw []NoteVulnerabilityWindowsDetailsFixingKbs) []NoteVulnerabilityWindowsDetailsFixingKbs { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteVulnerabilityWindowsDetailsFixingKbs for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteVulnerabilityWindowsDetailsFixingKbsNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteVulnerabilityWindowsDetailsFixingKbs(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteVulnerabilityWindowsDetailsFixingKbsSlice(c *Client, des, nw []NoteVulnerabilityWindowsDetailsFixingKbs) []NoteVulnerabilityWindowsDetailsFixingKbs { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteVulnerabilityWindowsDetailsFixingKbs for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteVulnerabilityWindowsDetailsFixingKbs(c, &d, &n)) } return items } func canonicalizeNoteBuild(des, initial *NoteBuild, opts ...dcl.ApplyOption) *NoteBuild { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteBuild{} if dcl.StringCanonicalize(des.BuilderVersion, initial.BuilderVersion) || dcl.IsZeroValue(des.BuilderVersion) { cDes.BuilderVersion = initial.BuilderVersion } else { cDes.BuilderVersion = des.BuilderVersion } cDes.Signature = canonicalizeNoteBuildSignature(des.Signature, initial.Signature, opts...) return cDes } func canonicalizeNoteBuildSlice(des, initial []NoteBuild, opts ...dcl.ApplyOption) []NoteBuild { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NoteBuild, 0, len(des)) for _, d := range des { cd := canonicalizeNoteBuild(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteBuild, 0, len(des)) for i, d := range des { cd := canonicalizeNoteBuild(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteBuild(c *Client, des, nw *NoteBuild) *NoteBuild { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteBuild while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.BuilderVersion, nw.BuilderVersion) { nw.BuilderVersion = des.BuilderVersion } nw.Signature = canonicalizeNewNoteBuildSignature(c, des.Signature, nw.Signature) return nw } func canonicalizeNewNoteBuildSet(c *Client, des, nw []NoteBuild) []NoteBuild { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteBuild for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteBuildNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteBuild(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteBuildSlice(c *Client, des, nw []NoteBuild) []NoteBuild { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteBuild for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteBuild(c, &d, &n)) } return items } func canonicalizeNoteBuildSignature(des, initial *NoteBuildSignature, opts ...dcl.ApplyOption) *NoteBuildSignature { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteBuildSignature{} if dcl.StringCanonicalize(des.PublicKey, initial.PublicKey) || dcl.IsZeroValue(des.PublicKey) { cDes.PublicKey = initial.PublicKey } else { cDes.PublicKey = des.PublicKey } if dcl.StringCanonicalize(des.Signature, initial.Signature) || dcl.IsZeroValue(des.Signature) { cDes.Signature = initial.Signature } else { cDes.Signature = des.Signature } if dcl.StringCanonicalize(des.KeyId, initial.KeyId) || dcl.IsZeroValue(des.KeyId) { cDes.KeyId = initial.KeyId } else { cDes.KeyId = des.KeyId } if dcl.IsZeroValue(des.KeyType) || (dcl.IsEmptyValueIndirect(des.KeyType) && dcl.IsEmptyValueIndirect(initial.KeyType)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.KeyType = initial.KeyType } else { cDes.KeyType = des.KeyType } return cDes } func canonicalizeNoteBuildSignatureSlice(des, initial []NoteBuildSignature, opts ...dcl.ApplyOption) []NoteBuildSignature { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NoteBuildSignature, 0, len(des)) for _, d := range des { cd := canonicalizeNoteBuildSignature(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteBuildSignature, 0, len(des)) for i, d := range des { cd := canonicalizeNoteBuildSignature(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteBuildSignature(c *Client, des, nw *NoteBuildSignature) *NoteBuildSignature { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteBuildSignature while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.PublicKey, nw.PublicKey) { nw.PublicKey = des.PublicKey } if dcl.StringCanonicalize(des.Signature, nw.Signature) { nw.Signature = des.Signature } if dcl.StringCanonicalize(des.KeyId, nw.KeyId) { nw.KeyId = des.KeyId } return nw } func canonicalizeNewNoteBuildSignatureSet(c *Client, des, nw []NoteBuildSignature) []NoteBuildSignature { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteBuildSignature for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteBuildSignatureNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteBuildSignature(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteBuildSignatureSlice(c *Client, des, nw []NoteBuildSignature) []NoteBuildSignature { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteBuildSignature for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteBuildSignature(c, &d, &n)) } return items } func canonicalizeNoteImage(des, initial *NoteImage, opts ...dcl.ApplyOption) *NoteImage { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteImage{} if dcl.StringCanonicalize(des.ResourceUrl, initial.ResourceUrl) || dcl.IsZeroValue(des.ResourceUrl) { cDes.ResourceUrl = initial.ResourceUrl } else { cDes.ResourceUrl = des.ResourceUrl } cDes.Fingerprint = canonicalizeNoteImageFingerprint(des.Fingerprint, initial.Fingerprint, opts...) return cDes } func canonicalizeNoteImageSlice(des, initial []NoteImage, opts ...dcl.ApplyOption) []NoteImage { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NoteImage, 0, len(des)) for _, d := range des { cd := canonicalizeNoteImage(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteImage, 0, len(des)) for i, d := range des { cd := canonicalizeNoteImage(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteImage(c *Client, des, nw *NoteImage) *NoteImage { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteImage while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.ResourceUrl, nw.ResourceUrl) { nw.ResourceUrl = des.ResourceUrl } nw.Fingerprint = canonicalizeNewNoteImageFingerprint(c, des.Fingerprint, nw.Fingerprint) return nw } func canonicalizeNewNoteImageSet(c *Client, des, nw []NoteImage) []NoteImage { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteImage for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteImageNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteImage(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteImageSlice(c *Client, des, nw []NoteImage) []NoteImage { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteImage for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteImage(c, &d, &n)) } return items } func canonicalizeNoteImageFingerprint(des, initial *NoteImageFingerprint, opts ...dcl.ApplyOption) *NoteImageFingerprint { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteImageFingerprint{} if dcl.StringCanonicalize(des.V1Name, initial.V1Name) || dcl.IsZeroValue(des.V1Name) { cDes.V1Name = initial.V1Name } else { cDes.V1Name = des.V1Name } if dcl.StringArrayCanonicalize(des.V2Blob, initial.V2Blob) { cDes.V2Blob = initial.V2Blob } else { cDes.V2Blob = des.V2Blob } return cDes } func canonicalizeNoteImageFingerprintSlice(des, initial []NoteImageFingerprint, opts ...dcl.ApplyOption) []NoteImageFingerprint { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NoteImageFingerprint, 0, len(des)) for _, d := range des { cd := canonicalizeNoteImageFingerprint(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteImageFingerprint, 0, len(des)) for i, d := range des { cd := canonicalizeNoteImageFingerprint(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteImageFingerprint(c *Client, des, nw *NoteImageFingerprint) *NoteImageFingerprint { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteImageFingerprint while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.V1Name, nw.V1Name) { nw.V1Name = des.V1Name } if dcl.StringArrayCanonicalize(des.V2Blob, nw.V2Blob) { nw.V2Blob = des.V2Blob } if dcl.StringCanonicalize(des.V2Name, nw.V2Name) { nw.V2Name = des.V2Name } return nw } func canonicalizeNewNoteImageFingerprintSet(c *Client, des, nw []NoteImageFingerprint) []NoteImageFingerprint { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteImageFingerprint for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteImageFingerprintNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteImageFingerprint(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteImageFingerprintSlice(c *Client, des, nw []NoteImageFingerprint) []NoteImageFingerprint { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteImageFingerprint for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteImageFingerprint(c, &d, &n)) } return items } func canonicalizeNotePackage(des, initial *NotePackage, opts ...dcl.ApplyOption) *NotePackage { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NotePackage{} if dcl.StringCanonicalize(des.Name, initial.Name) || dcl.IsZeroValue(des.Name) { cDes.Name = initial.Name } else { cDes.Name = des.Name } cDes.Distribution = canonicalizeNotePackageDistributionSlice(des.Distribution, initial.Distribution, opts...) return cDes } func canonicalizeNotePackageSlice(des, initial []NotePackage, opts ...dcl.ApplyOption) []NotePackage { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NotePackage, 0, len(des)) for _, d := range des { cd := canonicalizeNotePackage(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NotePackage, 0, len(des)) for i, d := range des { cd := canonicalizeNotePackage(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNotePackage(c *Client, des, nw *NotePackage) *NotePackage { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NotePackage while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.Name, nw.Name) { nw.Name = des.Name } nw.Distribution = canonicalizeNewNotePackageDistributionSlice(c, des.Distribution, nw.Distribution) return nw } func canonicalizeNewNotePackageSet(c *Client, des, nw []NotePackage) []NotePackage { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NotePackage for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNotePackageNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNotePackage(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNotePackageSlice(c *Client, des, nw []NotePackage) []NotePackage { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NotePackage for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNotePackage(c, &d, &n)) } return items } func canonicalizeNotePackageDistribution(des, initial *NotePackageDistribution, opts ...dcl.ApplyOption) *NotePackageDistribution { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NotePackageDistribution{} if dcl.StringCanonicalize(des.CpeUri, initial.CpeUri) || dcl.IsZeroValue(des.CpeUri) { cDes.CpeUri = initial.CpeUri } else { cDes.CpeUri = des.CpeUri } if dcl.IsZeroValue(des.Architecture) || (dcl.IsEmptyValueIndirect(des.Architecture) && dcl.IsEmptyValueIndirect(initial.Architecture)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Architecture = initial.Architecture } else { cDes.Architecture = des.Architecture } cDes.LatestVersion = canonicalizeNotePackageDistributionLatestVersion(des.LatestVersion, initial.LatestVersion, opts...) if dcl.StringCanonicalize(des.Maintainer, initial.Maintainer) || dcl.IsZeroValue(des.Maintainer) { cDes.Maintainer = initial.Maintainer } else { cDes.Maintainer = des.Maintainer } if dcl.StringCanonicalize(des.Url, initial.Url) || dcl.IsZeroValue(des.Url) { cDes.Url = initial.Url } else { cDes.Url = des.Url } if dcl.StringCanonicalize(des.Description, initial.Description) || dcl.IsZeroValue(des.Description) { cDes.Description = initial.Description } else { cDes.Description = des.Description } return cDes } func canonicalizeNotePackageDistributionSlice(des, initial []NotePackageDistribution, opts ...dcl.ApplyOption) []NotePackageDistribution { if des == nil { return initial } if len(des) != len(initial) { items := make([]NotePackageDistribution, 0, len(des)) for _, d := range des { cd := canonicalizeNotePackageDistribution(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NotePackageDistribution, 0, len(des)) for i, d := range des { cd := canonicalizeNotePackageDistribution(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNotePackageDistribution(c *Client, des, nw *NotePackageDistribution) *NotePackageDistribution { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NotePackageDistribution while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.CpeUri, nw.CpeUri) { nw.CpeUri = des.CpeUri } nw.LatestVersion = canonicalizeNewNotePackageDistributionLatestVersion(c, des.LatestVersion, nw.LatestVersion) if dcl.StringCanonicalize(des.Maintainer, nw.Maintainer) { nw.Maintainer = des.Maintainer } if dcl.StringCanonicalize(des.Url, nw.Url) { nw.Url = des.Url } if dcl.StringCanonicalize(des.Description, nw.Description) { nw.Description = des.Description } return nw } func canonicalizeNewNotePackageDistributionSet(c *Client, des, nw []NotePackageDistribution) []NotePackageDistribution { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NotePackageDistribution for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNotePackageDistributionNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNotePackageDistribution(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNotePackageDistributionSlice(c *Client, des, nw []NotePackageDistribution) []NotePackageDistribution { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NotePackageDistribution for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNotePackageDistribution(c, &d, &n)) } return items } func canonicalizeNotePackageDistributionLatestVersion(des, initial *NotePackageDistributionLatestVersion, opts ...dcl.ApplyOption) *NotePackageDistributionLatestVersion { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NotePackageDistributionLatestVersion{} if dcl.IsZeroValue(des.Epoch) || (dcl.IsEmptyValueIndirect(des.Epoch) && dcl.IsEmptyValueIndirect(initial.Epoch)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Epoch = initial.Epoch } else { cDes.Epoch = des.Epoch } if dcl.StringCanonicalize(des.Name, initial.Name) || dcl.IsZeroValue(des.Name) { cDes.Name = initial.Name } else { cDes.Name = des.Name } if dcl.StringCanonicalize(des.Revision, initial.Revision) || dcl.IsZeroValue(des.Revision) { cDes.Revision = initial.Revision } else { cDes.Revision = des.Revision } if dcl.IsZeroValue(des.Kind) || (dcl.IsEmptyValueIndirect(des.Kind) && dcl.IsEmptyValueIndirect(initial.Kind)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.Kind = initial.Kind } else { cDes.Kind = des.Kind } if dcl.StringCanonicalize(des.FullName, initial.FullName) || dcl.IsZeroValue(des.FullName) { cDes.FullName = initial.FullName } else { cDes.FullName = des.FullName } return cDes } func canonicalizeNotePackageDistributionLatestVersionSlice(des, initial []NotePackageDistributionLatestVersion, opts ...dcl.ApplyOption) []NotePackageDistributionLatestVersion { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NotePackageDistributionLatestVersion, 0, len(des)) for _, d := range des { cd := canonicalizeNotePackageDistributionLatestVersion(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NotePackageDistributionLatestVersion, 0, len(des)) for i, d := range des { cd := canonicalizeNotePackageDistributionLatestVersion(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNotePackageDistributionLatestVersion(c *Client, des, nw *NotePackageDistributionLatestVersion) *NotePackageDistributionLatestVersion { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NotePackageDistributionLatestVersion while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.Name, nw.Name) { nw.Name = des.Name } if dcl.StringCanonicalize(des.Revision, nw.Revision) { nw.Revision = des.Revision } if dcl.StringCanonicalize(des.FullName, nw.FullName) { nw.FullName = des.FullName } return nw } func canonicalizeNewNotePackageDistributionLatestVersionSet(c *Client, des, nw []NotePackageDistributionLatestVersion) []NotePackageDistributionLatestVersion { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NotePackageDistributionLatestVersion for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNotePackageDistributionLatestVersionNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNotePackageDistributionLatestVersion(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNotePackageDistributionLatestVersionSlice(c *Client, des, nw []NotePackageDistributionLatestVersion) []NotePackageDistributionLatestVersion { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NotePackageDistributionLatestVersion for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNotePackageDistributionLatestVersion(c, &d, &n)) } return items } func canonicalizeNoteDiscovery(des, initial *NoteDiscovery, opts ...dcl.ApplyOption) *NoteDiscovery { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteDiscovery{} if dcl.IsZeroValue(des.AnalysisKind) || (dcl.IsEmptyValueIndirect(des.AnalysisKind) && dcl.IsEmptyValueIndirect(initial.AnalysisKind)) { // Desired and initial values are equivalent, so set canonical desired value to initial value. cDes.AnalysisKind = initial.AnalysisKind } else { cDes.AnalysisKind = des.AnalysisKind } return cDes } func canonicalizeNoteDiscoverySlice(des, initial []NoteDiscovery, opts ...dcl.ApplyOption) []NoteDiscovery { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NoteDiscovery, 0, len(des)) for _, d := range des { cd := canonicalizeNoteDiscovery(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteDiscovery, 0, len(des)) for i, d := range des { cd := canonicalizeNoteDiscovery(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteDiscovery(c *Client, des, nw *NoteDiscovery) *NoteDiscovery { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteDiscovery while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } return nw } func canonicalizeNewNoteDiscoverySet(c *Client, des, nw []NoteDiscovery) []NoteDiscovery { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteDiscovery for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteDiscoveryNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteDiscovery(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteDiscoverySlice(c *Client, des, nw []NoteDiscovery) []NoteDiscovery { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteDiscovery for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteDiscovery(c, &d, &n)) } return items } func canonicalizeNoteDeployment(des, initial *NoteDeployment, opts ...dcl.ApplyOption) *NoteDeployment { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteDeployment{} if dcl.StringArrayCanonicalize(des.ResourceUri, initial.ResourceUri) { cDes.ResourceUri = initial.ResourceUri } else { cDes.ResourceUri = des.ResourceUri } return cDes } func canonicalizeNoteDeploymentSlice(des, initial []NoteDeployment, opts ...dcl.ApplyOption) []NoteDeployment { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NoteDeployment, 0, len(des)) for _, d := range des { cd := canonicalizeNoteDeployment(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteDeployment, 0, len(des)) for i, d := range des { cd := canonicalizeNoteDeployment(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteDeployment(c *Client, des, nw *NoteDeployment) *NoteDeployment { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteDeployment while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringArrayCanonicalize(des.ResourceUri, nw.ResourceUri) { nw.ResourceUri = des.ResourceUri } return nw } func canonicalizeNewNoteDeploymentSet(c *Client, des, nw []NoteDeployment) []NoteDeployment { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteDeployment for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteDeploymentNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteDeployment(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteDeploymentSlice(c *Client, des, nw []NoteDeployment) []NoteDeployment { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteDeployment for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteDeployment(c, &d, &n)) } return items } func canonicalizeNoteAttestation(des, initial *NoteAttestation, opts ...dcl.ApplyOption) *NoteAttestation { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteAttestation{} cDes.Hint = canonicalizeNoteAttestationHint(des.Hint, initial.Hint, opts...) return cDes } func canonicalizeNoteAttestationSlice(des, initial []NoteAttestation, opts ...dcl.ApplyOption) []NoteAttestation { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NoteAttestation, 0, len(des)) for _, d := range des { cd := canonicalizeNoteAttestation(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteAttestation, 0, len(des)) for i, d := range des { cd := canonicalizeNoteAttestation(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteAttestation(c *Client, des, nw *NoteAttestation) *NoteAttestation { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteAttestation while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } nw.Hint = canonicalizeNewNoteAttestationHint(c, des.Hint, nw.Hint) return nw } func canonicalizeNewNoteAttestationSet(c *Client, des, nw []NoteAttestation) []NoteAttestation { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteAttestation for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteAttestationNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteAttestation(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteAttestationSlice(c *Client, des, nw []NoteAttestation) []NoteAttestation { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteAttestation for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteAttestation(c, &d, &n)) } return items } func canonicalizeNoteAttestationHint(des, initial *NoteAttestationHint, opts ...dcl.ApplyOption) *NoteAttestationHint { if des == nil { return initial } if des.empty { return des } if initial == nil { return des } cDes := &NoteAttestationHint{} if dcl.StringCanonicalize(des.HumanReadableName, initial.HumanReadableName) || dcl.IsZeroValue(des.HumanReadableName) { cDes.HumanReadableName = initial.HumanReadableName } else { cDes.HumanReadableName = des.HumanReadableName } return cDes } func canonicalizeNoteAttestationHintSlice(des, initial []NoteAttestationHint, opts ...dcl.ApplyOption) []NoteAttestationHint { if dcl.IsEmptyValueIndirect(des) { return initial } if len(des) != len(initial) { items := make([]NoteAttestationHint, 0, len(des)) for _, d := range des { cd := canonicalizeNoteAttestationHint(&d, nil, opts...) if cd != nil { items = append(items, *cd) } } return items } items := make([]NoteAttestationHint, 0, len(des)) for i, d := range des { cd := canonicalizeNoteAttestationHint(&d, &initial[i], opts...) if cd != nil { items = append(items, *cd) } } return items } func canonicalizeNewNoteAttestationHint(c *Client, des, nw *NoteAttestationHint) *NoteAttestationHint { if des == nil { return nw } if nw == nil { if dcl.IsEmptyValueIndirect(des) { c.Config.Logger.Info("Found explicitly empty value for NoteAttestationHint while comparing non-nil desired to nil actual. Returning desired object.") return des } return nil } if dcl.StringCanonicalize(des.HumanReadableName, nw.HumanReadableName) { nw.HumanReadableName = des.HumanReadableName } return nw } func canonicalizeNewNoteAttestationHintSet(c *Client, des, nw []NoteAttestationHint) []NoteAttestationHint { if des == nil { return nw } // Find the elements in des that are also in nw and canonicalize them. Remove matched elements from nw. var items []NoteAttestationHint for _, d := range des { matchedIndex := -1 for i, n := range nw { if diffs, _ := compareNoteAttestationHintNewStyle(&d, &n, dcl.FieldName{}); len(diffs) == 0 { matchedIndex = i break } } if matchedIndex != -1 { items = append(items, *canonicalizeNewNoteAttestationHint(c, &d, &nw[matchedIndex])) nw = append(nw[:matchedIndex], nw[matchedIndex+1:]...) } } // Also include elements in nw that are not matched in des. items = append(items, nw...) return items } func canonicalizeNewNoteAttestationHintSlice(c *Client, des, nw []NoteAttestationHint) []NoteAttestationHint { if des == nil { return nw } // Lengths are unequal. A diff will occur later, so we shouldn't canonicalize. // Return the original array. if len(des) != len(nw) { return nw } var items []NoteAttestationHint for i, d := range des { n := nw[i] items = append(items, *canonicalizeNewNoteAttestationHint(c, &d, &n)) } return items } // The differ returns a list of diffs, along with a list of operations that should be taken // to remedy them. Right now, it does not attempt to consolidate operations - if several // fields can be fixed with a patch update, it will perform the patch several times. // Diffs on some fields will be ignored if the `desired` state has an empty (nil) // value. This empty value indicates that the user does not care about the state for // the field. Empty fields on the actual object will cause diffs. // TODO(magic-modules-eng): for efficiency in some resources, add batching. func diffNote(c *Client, desired, actual *Note, opts ...dcl.ApplyOption) ([]*dcl.FieldDiff, error) { if desired == nil || actual == nil { return nil, fmt.Errorf("nil resource passed to diff - always a programming error: %#v, %#v", desired, actual) } c.Config.Logger.Infof("Diff function called with desired state: %v", desired) c.Config.Logger.Infof("Diff function called with actual state: %v", actual) var fn dcl.FieldName var newDiffs []*dcl.FieldDiff // New style diffs. if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Name")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.ShortDescription, actual.ShortDescription, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("ShortDescription")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.LongDescription, actual.LongDescription, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("LongDescription")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.RelatedUrl, actual.RelatedUrl, dcl.DiffInfo{ObjectFunction: compareNoteRelatedUrlNewStyle, EmptyObject: EmptyNoteRelatedUrl, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("RelatedUrl")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.ExpirationTime, actual.ExpirationTime, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("ExpirationTime")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.CreateTime, actual.CreateTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("CreateTime")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.UpdateTime, actual.UpdateTime, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("UpdateTime")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.RelatedNoteNames, actual.RelatedNoteNames, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("RelatedNoteNames")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.Vulnerability, actual.Vulnerability, dcl.DiffInfo{ObjectFunction: compareNoteVulnerabilityNewStyle, EmptyObject: EmptyNoteVulnerability, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Vulnerability")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.Build, actual.Build, dcl.DiffInfo{ObjectFunction: compareNoteBuildNewStyle, EmptyObject: EmptyNoteBuild, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Build")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.Image, actual.Image, dcl.DiffInfo{ObjectFunction: compareNoteImageNewStyle, EmptyObject: EmptyNoteImage, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Image")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.Package, actual.Package, dcl.DiffInfo{ObjectFunction: compareNotePackageNewStyle, EmptyObject: EmptyNotePackage, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Package")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.Discovery, actual.Discovery, dcl.DiffInfo{ObjectFunction: compareNoteDiscoveryNewStyle, EmptyObject: EmptyNoteDiscovery, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Discovery")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.Deployment, actual.Deployment, dcl.DiffInfo{ObjectFunction: compareNoteDeploymentNewStyle, EmptyObject: EmptyNoteDeployment, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Deployment")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.Attestation, actual.Attestation, dcl.DiffInfo{ObjectFunction: compareNoteAttestationNewStyle, EmptyObject: EmptyNoteAttestation, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Attestation")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } if ds, err := dcl.Diff(desired.Project, actual.Project, dcl.DiffInfo{Type: "ReferenceType", OperationSelector: dcl.RequiresRecreate()}, fn.AddNest("Project")); len(ds) != 0 || err != nil { if err != nil { return nil, err } newDiffs = append(newDiffs, ds...) } newDiffs = analyzeNoteDiff(desired, actual, newDiffs) if len(newDiffs) > 0 { c.Config.Logger.Infof("Diff function found diffs: %v", newDiffs) } return newDiffs, nil } func compareNoteRelatedUrlNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteRelatedUrl) if !ok { desiredNotPointer, ok := d.(NoteRelatedUrl) if !ok { return nil, fmt.Errorf("obj %v is not a NoteRelatedUrl or *NoteRelatedUrl", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteRelatedUrl) if !ok { actualNotPointer, ok := a.(NoteRelatedUrl) if !ok { return nil, fmt.Errorf("obj %v is not a NoteRelatedUrl", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.Url, actual.Url, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Url")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Label, actual.Label, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Label")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteVulnerabilityNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteVulnerability) if !ok { desiredNotPointer, ok := d.(NoteVulnerability) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerability or *NoteVulnerability", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteVulnerability) if !ok { actualNotPointer, ok := a.(NoteVulnerability) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerability", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.CvssScore, actual.CvssScore, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("CvssScore")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Severity, actual.Severity, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Severity")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Details, actual.Details, dcl.DiffInfo{ObjectFunction: compareNoteVulnerabilityDetailsNewStyle, EmptyObject: EmptyNoteVulnerabilityDetails, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Details")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.CvssV3, actual.CvssV3, dcl.DiffInfo{ObjectFunction: compareNoteVulnerabilityCvssV3NewStyle, EmptyObject: EmptyNoteVulnerabilityCvssV3, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("CvssV3")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.WindowsDetails, actual.WindowsDetails, dcl.DiffInfo{ObjectFunction: compareNoteVulnerabilityWindowsDetailsNewStyle, EmptyObject: EmptyNoteVulnerabilityWindowsDetails, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("WindowsDetails")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.SourceUpdateTime, actual.SourceUpdateTime, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("SourceUpdateTime")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteVulnerabilityDetailsNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteVulnerabilityDetails) if !ok { desiredNotPointer, ok := d.(NoteVulnerabilityDetails) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityDetails or *NoteVulnerabilityDetails", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteVulnerabilityDetails) if !ok { actualNotPointer, ok := a.(NoteVulnerabilityDetails) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityDetails", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.SeverityName, actual.SeverityName, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("SeverityName")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Description, actual.Description, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Description")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.PackageType, actual.PackageType, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("PackageType")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.AffectedCpeUri, actual.AffectedCpeUri, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("AffectedCpeUri")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.AffectedPackage, actual.AffectedPackage, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("AffectedPackage")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.AffectedVersionStart, actual.AffectedVersionStart, dcl.DiffInfo{ObjectFunction: compareNoteVulnerabilityDetailsAffectedVersionStartNewStyle, EmptyObject: EmptyNoteVulnerabilityDetailsAffectedVersionStart, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("AffectedVersionStart")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.AffectedVersionEnd, actual.AffectedVersionEnd, dcl.DiffInfo{ObjectFunction: compareNoteVulnerabilityDetailsAffectedVersionEndNewStyle, EmptyObject: EmptyNoteVulnerabilityDetailsAffectedVersionEnd, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("AffectedVersionEnd")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.FixedCpeUri, actual.FixedCpeUri, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("FixedCpeUri")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.FixedPackage, actual.FixedPackage, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("FixedPackage")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.FixedVersion, actual.FixedVersion, dcl.DiffInfo{ObjectFunction: compareNoteVulnerabilityDetailsFixedVersionNewStyle, EmptyObject: EmptyNoteVulnerabilityDetailsFixedVersion, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("FixedVersion")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.IsObsolete, actual.IsObsolete, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("IsObsolete")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.SourceUpdateTime, actual.SourceUpdateTime, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("SourceUpdateTime")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteVulnerabilityDetailsAffectedVersionStartNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteVulnerabilityDetailsAffectedVersionStart) if !ok { desiredNotPointer, ok := d.(NoteVulnerabilityDetailsAffectedVersionStart) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityDetailsAffectedVersionStart or *NoteVulnerabilityDetailsAffectedVersionStart", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteVulnerabilityDetailsAffectedVersionStart) if !ok { actualNotPointer, ok := a.(NoteVulnerabilityDetailsAffectedVersionStart) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityDetailsAffectedVersionStart", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.Epoch, actual.Epoch, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Epoch")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Revision, actual.Revision, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Revision")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Kind, actual.Kind, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Kind")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.FullName, actual.FullName, dcl.DiffInfo{ServerDefault: true, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("FullName")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteVulnerabilityDetailsAffectedVersionEndNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteVulnerabilityDetailsAffectedVersionEnd) if !ok { desiredNotPointer, ok := d.(NoteVulnerabilityDetailsAffectedVersionEnd) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityDetailsAffectedVersionEnd or *NoteVulnerabilityDetailsAffectedVersionEnd", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteVulnerabilityDetailsAffectedVersionEnd) if !ok { actualNotPointer, ok := a.(NoteVulnerabilityDetailsAffectedVersionEnd) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityDetailsAffectedVersionEnd", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.Epoch, actual.Epoch, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Epoch")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Revision, actual.Revision, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Revision")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Kind, actual.Kind, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Kind")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.FullName, actual.FullName, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("FullName")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteVulnerabilityDetailsFixedVersionNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteVulnerabilityDetailsFixedVersion) if !ok { desiredNotPointer, ok := d.(NoteVulnerabilityDetailsFixedVersion) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityDetailsFixedVersion or *NoteVulnerabilityDetailsFixedVersion", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteVulnerabilityDetailsFixedVersion) if !ok { actualNotPointer, ok := a.(NoteVulnerabilityDetailsFixedVersion) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityDetailsFixedVersion", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.Epoch, actual.Epoch, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Epoch")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Revision, actual.Revision, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Revision")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Kind, actual.Kind, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Kind")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.FullName, actual.FullName, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("FullName")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteVulnerabilityCvssV3NewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteVulnerabilityCvssV3) if !ok { desiredNotPointer, ok := d.(NoteVulnerabilityCvssV3) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityCvssV3 or *NoteVulnerabilityCvssV3", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteVulnerabilityCvssV3) if !ok { actualNotPointer, ok := a.(NoteVulnerabilityCvssV3) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityCvssV3", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.BaseScore, actual.BaseScore, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("BaseScore")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.ExploitabilityScore, actual.ExploitabilityScore, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("ExploitabilityScore")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.ImpactScore, actual.ImpactScore, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("ImpactScore")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.AttackVector, actual.AttackVector, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("AttackVector")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.AttackComplexity, actual.AttackComplexity, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("AttackComplexity")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.PrivilegesRequired, actual.PrivilegesRequired, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("PrivilegesRequired")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.UserInteraction, actual.UserInteraction, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("UserInteraction")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Scope, actual.Scope, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Scope")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.ConfidentialityImpact, actual.ConfidentialityImpact, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("ConfidentialityImpact")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.IntegrityImpact, actual.IntegrityImpact, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("IntegrityImpact")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.AvailabilityImpact, actual.AvailabilityImpact, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("AvailabilityImpact")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteVulnerabilityWindowsDetailsNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteVulnerabilityWindowsDetails) if !ok { desiredNotPointer, ok := d.(NoteVulnerabilityWindowsDetails) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityWindowsDetails or *NoteVulnerabilityWindowsDetails", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteVulnerabilityWindowsDetails) if !ok { actualNotPointer, ok := a.(NoteVulnerabilityWindowsDetails) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityWindowsDetails", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.CpeUri, actual.CpeUri, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("CpeUri")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Description, actual.Description, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Description")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.FixingKbs, actual.FixingKbs, dcl.DiffInfo{ObjectFunction: compareNoteVulnerabilityWindowsDetailsFixingKbsNewStyle, EmptyObject: EmptyNoteVulnerabilityWindowsDetailsFixingKbs, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("FixingKbs")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteVulnerabilityWindowsDetailsFixingKbsNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteVulnerabilityWindowsDetailsFixingKbs) if !ok { desiredNotPointer, ok := d.(NoteVulnerabilityWindowsDetailsFixingKbs) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityWindowsDetailsFixingKbs or *NoteVulnerabilityWindowsDetailsFixingKbs", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteVulnerabilityWindowsDetailsFixingKbs) if !ok { actualNotPointer, ok := a.(NoteVulnerabilityWindowsDetailsFixingKbs) if !ok { return nil, fmt.Errorf("obj %v is not a NoteVulnerabilityWindowsDetailsFixingKbs", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Url, actual.Url, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Url")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteBuildNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteBuild) if !ok { desiredNotPointer, ok := d.(NoteBuild) if !ok { return nil, fmt.Errorf("obj %v is not a NoteBuild or *NoteBuild", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteBuild) if !ok { actualNotPointer, ok := a.(NoteBuild) if !ok { return nil, fmt.Errorf("obj %v is not a NoteBuild", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.BuilderVersion, actual.BuilderVersion, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("BuilderVersion")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Signature, actual.Signature, dcl.DiffInfo{ObjectFunction: compareNoteBuildSignatureNewStyle, EmptyObject: EmptyNoteBuildSignature, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Signature")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteBuildSignatureNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteBuildSignature) if !ok { desiredNotPointer, ok := d.(NoteBuildSignature) if !ok { return nil, fmt.Errorf("obj %v is not a NoteBuildSignature or *NoteBuildSignature", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteBuildSignature) if !ok { actualNotPointer, ok := a.(NoteBuildSignature) if !ok { return nil, fmt.Errorf("obj %v is not a NoteBuildSignature", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.PublicKey, actual.PublicKey, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("PublicKey")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Signature, actual.Signature, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Signature")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.KeyId, actual.KeyId, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("KeyId")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.KeyType, actual.KeyType, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("KeyType")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteImageNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteImage) if !ok { desiredNotPointer, ok := d.(NoteImage) if !ok { return nil, fmt.Errorf("obj %v is not a NoteImage or *NoteImage", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteImage) if !ok { actualNotPointer, ok := a.(NoteImage) if !ok { return nil, fmt.Errorf("obj %v is not a NoteImage", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.ResourceUrl, actual.ResourceUrl, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("ResourceUrl")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Fingerprint, actual.Fingerprint, dcl.DiffInfo{ObjectFunction: compareNoteImageFingerprintNewStyle, EmptyObject: EmptyNoteImageFingerprint, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Fingerprint")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteImageFingerprintNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteImageFingerprint) if !ok { desiredNotPointer, ok := d.(NoteImageFingerprint) if !ok { return nil, fmt.Errorf("obj %v is not a NoteImageFingerprint or *NoteImageFingerprint", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteImageFingerprint) if !ok { actualNotPointer, ok := a.(NoteImageFingerprint) if !ok { return nil, fmt.Errorf("obj %v is not a NoteImageFingerprint", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.V1Name, actual.V1Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("V1Name")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.V2Blob, actual.V2Blob, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("V2Blob")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.V2Name, actual.V2Name, dcl.DiffInfo{OutputOnly: true, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("V2Name")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNotePackageNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NotePackage) if !ok { desiredNotPointer, ok := d.(NotePackage) if !ok { return nil, fmt.Errorf("obj %v is not a NotePackage or *NotePackage", d) } desired = &desiredNotPointer } actual, ok := a.(*NotePackage) if !ok { actualNotPointer, ok := a.(NotePackage) if !ok { return nil, fmt.Errorf("obj %v is not a NotePackage", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Distribution, actual.Distribution, dcl.DiffInfo{ObjectFunction: compareNotePackageDistributionNewStyle, EmptyObject: EmptyNotePackageDistribution, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Distribution")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNotePackageDistributionNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NotePackageDistribution) if !ok { desiredNotPointer, ok := d.(NotePackageDistribution) if !ok { return nil, fmt.Errorf("obj %v is not a NotePackageDistribution or *NotePackageDistribution", d) } desired = &desiredNotPointer } actual, ok := a.(*NotePackageDistribution) if !ok { actualNotPointer, ok := a.(NotePackageDistribution) if !ok { return nil, fmt.Errorf("obj %v is not a NotePackageDistribution", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.CpeUri, actual.CpeUri, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("CpeUri")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Architecture, actual.Architecture, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Architecture")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.LatestVersion, actual.LatestVersion, dcl.DiffInfo{ObjectFunction: compareNotePackageDistributionLatestVersionNewStyle, EmptyObject: EmptyNotePackageDistributionLatestVersion, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("LatestVersion")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Maintainer, actual.Maintainer, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Maintainer")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Url, actual.Url, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Url")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Description, actual.Description, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Description")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNotePackageDistributionLatestVersionNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NotePackageDistributionLatestVersion) if !ok { desiredNotPointer, ok := d.(NotePackageDistributionLatestVersion) if !ok { return nil, fmt.Errorf("obj %v is not a NotePackageDistributionLatestVersion or *NotePackageDistributionLatestVersion", d) } desired = &desiredNotPointer } actual, ok := a.(*NotePackageDistributionLatestVersion) if !ok { actualNotPointer, ok := a.(NotePackageDistributionLatestVersion) if !ok { return nil, fmt.Errorf("obj %v is not a NotePackageDistributionLatestVersion", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.Epoch, actual.Epoch, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Epoch")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Name, actual.Name, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Name")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Revision, actual.Revision, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Revision")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.Kind, actual.Kind, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Kind")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } if ds, err := dcl.Diff(desired.FullName, actual.FullName, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("FullName")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteDiscoveryNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteDiscovery) if !ok { desiredNotPointer, ok := d.(NoteDiscovery) if !ok { return nil, fmt.Errorf("obj %v is not a NoteDiscovery or *NoteDiscovery", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteDiscovery) if !ok { actualNotPointer, ok := a.(NoteDiscovery) if !ok { return nil, fmt.Errorf("obj %v is not a NoteDiscovery", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.AnalysisKind, actual.AnalysisKind, dcl.DiffInfo{Type: "EnumType", OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("AnalysisKind")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteDeploymentNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteDeployment) if !ok { desiredNotPointer, ok := d.(NoteDeployment) if !ok { return nil, fmt.Errorf("obj %v is not a NoteDeployment or *NoteDeployment", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteDeployment) if !ok { actualNotPointer, ok := a.(NoteDeployment) if !ok { return nil, fmt.Errorf("obj %v is not a NoteDeployment", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.ResourceUri, actual.ResourceUri, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("ResourceUri")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteAttestationNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteAttestation) if !ok { desiredNotPointer, ok := d.(NoteAttestation) if !ok { return nil, fmt.Errorf("obj %v is not a NoteAttestation or *NoteAttestation", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteAttestation) if !ok { actualNotPointer, ok := a.(NoteAttestation) if !ok { return nil, fmt.Errorf("obj %v is not a NoteAttestation", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.Hint, actual.Hint, dcl.DiffInfo{ObjectFunction: compareNoteAttestationHintNewStyle, EmptyObject: EmptyNoteAttestationHint, OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("Hint")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } func compareNoteAttestationHintNewStyle(d, a interface{}, fn dcl.FieldName) ([]*dcl.FieldDiff, error) { var diffs []*dcl.FieldDiff desired, ok := d.(*NoteAttestationHint) if !ok { desiredNotPointer, ok := d.(NoteAttestationHint) if !ok { return nil, fmt.Errorf("obj %v is not a NoteAttestationHint or *NoteAttestationHint", d) } desired = &desiredNotPointer } actual, ok := a.(*NoteAttestationHint) if !ok { actualNotPointer, ok := a.(NoteAttestationHint) if !ok { return nil, fmt.Errorf("obj %v is not a NoteAttestationHint", a) } actual = &actualNotPointer } if ds, err := dcl.Diff(desired.HumanReadableName, actual.HumanReadableName, dcl.DiffInfo{OperationSelector: dcl.TriggersOperation("updateNoteUpdateNoteOperation")}, fn.AddNest("HumanReadableName")); len(ds) != 0 || err != nil { if err != nil { return nil, err } diffs = append(diffs, ds...) } return diffs, nil } // urlNormalized returns a copy of the resource struct with values normalized // for URL substitutions. For instance, it converts long-form self-links to // short-form so they can be substituted in. func (r *Note) urlNormalized() *Note { normalized := dcl.Copy(*r).(Note) normalized.Name = dcl.SelfLinkToName(r.Name) normalized.ShortDescription = dcl.SelfLinkToName(r.ShortDescription) normalized.LongDescription = dcl.SelfLinkToName(r.LongDescription) normalized.Project = dcl.SelfLinkToName(r.Project) return &normalized } func (r *Note) updateURL(userBasePath, updateName string) (string, error) { nr := r.urlNormalized() if updateName == "UpdateNote" { fields := map[string]interface{}{ "project": dcl.ValueOrEmptyString(nr.Project), "name": dcl.ValueOrEmptyString(nr.Name), } return dcl.URL("projects/{{project}}/notes/{{name}}", nr.basePath(), userBasePath, fields), nil } return "", fmt.Errorf("unknown update name: %s", updateName) } // marshal encodes the Note resource into JSON for a Create request, and // performs transformations from the resource schema to the API schema if // necessary. func (r *Note) marshal(c *Client) ([]byte, error) { m, err := expandNote(c, r) if err != nil { return nil, fmt.Errorf("error marshalling Note: %w", err) } return json.Marshal(m) } // unmarshalNote decodes JSON responses into the Note resource schema. func unmarshalNote(b []byte, c *Client, res *Note) (*Note, error) { var m map[string]interface{} if err := json.Unmarshal(b, &m); err != nil { return nil, err } return unmarshalMapNote(m, c, res) } func unmarshalMapNote(m map[string]interface{}, c *Client, res *Note) (*Note, error) { flattened := flattenNote(c, m, res) if flattened == nil { return nil, fmt.Errorf("attempted to flatten empty json object") } return flattened, nil } // expandNote expands Note into a JSON request object. func expandNote(c *Client, f *Note) (map[string]interface{}, error) { m := make(map[string]interface{}) res := f _ = res if v, err := dcl.DeriveField("projects/%s/notes/%s", f.Name, dcl.SelfLinkToName(f.Project), dcl.SelfLinkToName(f.Name)); err != nil { return nil, fmt.Errorf("error expanding Name into name: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["name"] = v } if v := f.ShortDescription; dcl.ValueShouldBeSent(v) { m["shortDescription"] = v } if v := f.LongDescription; dcl.ValueShouldBeSent(v) { m["longDescription"] = v } if v, err := expandNoteRelatedUrlSlice(c, f.RelatedUrl, res); err != nil { return nil, fmt.Errorf("error expanding RelatedUrl into relatedUrl: %w", err) } else if v != nil { m["relatedUrl"] = v } if v := f.ExpirationTime; dcl.ValueShouldBeSent(v) { m["expirationTime"] = v } if v := f.RelatedNoteNames; v != nil { m["relatedNoteNames"] = v } if v, err := expandNoteVulnerability(c, f.Vulnerability, res); err != nil { return nil, fmt.Errorf("error expanding Vulnerability into vulnerability: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["vulnerability"] = v } if v, err := expandNoteBuild(c, f.Build, res); err != nil { return nil, fmt.Errorf("error expanding Build into build: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["build"] = v } if v, err := expandNoteImage(c, f.Image, res); err != nil { return nil, fmt.Errorf("error expanding Image into image: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["image"] = v } if v, err := expandNotePackage(c, f.Package, res); err != nil { return nil, fmt.Errorf("error expanding Package into package: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["package"] = v } if v, err := expandNoteDiscovery(c, f.Discovery, res); err != nil { return nil, fmt.Errorf("error expanding Discovery into discovery: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["discovery"] = v } if v, err := expandNoteDeployment(c, f.Deployment, res); err != nil { return nil, fmt.Errorf("error expanding Deployment into deployment: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["deployment"] = v } if v, err := expandNoteAttestation(c, f.Attestation, res); err != nil { return nil, fmt.Errorf("error expanding Attestation into attestation: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["attestation"] = v } if v, err := dcl.EmptyValue(); err != nil { return nil, fmt.Errorf("error expanding Project into project: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["project"] = v } return m, nil } // flattenNote flattens Note from a JSON request object into the // Note type. func flattenNote(c *Client, i interface{}, res *Note) *Note { m, ok := i.(map[string]interface{}) if !ok { return nil } if len(m) == 0 { return nil } resultRes := &Note{} resultRes.Name = dcl.FlattenString(m["name"]) resultRes.ShortDescription = dcl.FlattenString(m["shortDescription"]) resultRes.LongDescription = dcl.FlattenString(m["longDescription"]) resultRes.RelatedUrl = flattenNoteRelatedUrlSlice(c, m["relatedUrl"], res) resultRes.ExpirationTime = dcl.FlattenString(m["expirationTime"]) resultRes.CreateTime = dcl.FlattenString(m["createTime"]) resultRes.UpdateTime = dcl.FlattenString(m["updateTime"]) resultRes.RelatedNoteNames = dcl.FlattenStringSlice(m["relatedNoteNames"]) resultRes.Vulnerability = flattenNoteVulnerability(c, m["vulnerability"], res) resultRes.Build = flattenNoteBuild(c, m["build"], res) resultRes.Image = flattenNoteImage(c, m["image"], res) resultRes.Package = flattenNotePackage(c, m["package"], res) resultRes.Discovery = flattenNoteDiscovery(c, m["discovery"], res) resultRes.Deployment = flattenNoteDeployment(c, m["deployment"], res) resultRes.Attestation = flattenNoteAttestation(c, m["attestation"], res) resultRes.Project = dcl.FlattenString(m["project"]) return resultRes } // expandNoteRelatedUrlMap expands the contents of NoteRelatedUrl into a JSON // request object. func expandNoteRelatedUrlMap(c *Client, f map[string]NoteRelatedUrl, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteRelatedUrl(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteRelatedUrlSlice expands the contents of NoteRelatedUrl into a JSON // request object. func expandNoteRelatedUrlSlice(c *Client, f []NoteRelatedUrl, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteRelatedUrl(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteRelatedUrlMap flattens the contents of NoteRelatedUrl from a JSON // response object. func flattenNoteRelatedUrlMap(c *Client, i interface{}, res *Note) map[string]NoteRelatedUrl { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteRelatedUrl{} } if len(a) == 0 { return map[string]NoteRelatedUrl{} } items := make(map[string]NoteRelatedUrl) for k, item := range a { items[k] = *flattenNoteRelatedUrl(c, item.(map[string]interface{}), res) } return items } // flattenNoteRelatedUrlSlice flattens the contents of NoteRelatedUrl from a JSON // response object. func flattenNoteRelatedUrlSlice(c *Client, i interface{}, res *Note) []NoteRelatedUrl { a, ok := i.([]interface{}) if !ok { return []NoteRelatedUrl{} } if len(a) == 0 { return []NoteRelatedUrl{} } items := make([]NoteRelatedUrl, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteRelatedUrl(c, item.(map[string]interface{}), res)) } return items } // expandNoteRelatedUrl expands an instance of NoteRelatedUrl into a JSON // request object. func expandNoteRelatedUrl(c *Client, f *NoteRelatedUrl, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } m := make(map[string]interface{}) if v := f.Url; !dcl.IsEmptyValueIndirect(v) { m["url"] = v } if v := f.Label; !dcl.IsEmptyValueIndirect(v) { m["label"] = v } return m, nil } // flattenNoteRelatedUrl flattens an instance of NoteRelatedUrl from a JSON // response object. func flattenNoteRelatedUrl(c *Client, i interface{}, res *Note) *NoteRelatedUrl { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteRelatedUrl{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteRelatedUrl } r.Url = dcl.FlattenString(m["url"]) r.Label = dcl.FlattenString(m["label"]) return r } // expandNoteVulnerabilityMap expands the contents of NoteVulnerability into a JSON // request object. func expandNoteVulnerabilityMap(c *Client, f map[string]NoteVulnerability, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteVulnerability(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteVulnerabilitySlice expands the contents of NoteVulnerability into a JSON // request object. func expandNoteVulnerabilitySlice(c *Client, f []NoteVulnerability, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteVulnerability(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteVulnerabilityMap flattens the contents of NoteVulnerability from a JSON // response object. func flattenNoteVulnerabilityMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerability { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerability{} } if len(a) == 0 { return map[string]NoteVulnerability{} } items := make(map[string]NoteVulnerability) for k, item := range a { items[k] = *flattenNoteVulnerability(c, item.(map[string]interface{}), res) } return items } // flattenNoteVulnerabilitySlice flattens the contents of NoteVulnerability from a JSON // response object. func flattenNoteVulnerabilitySlice(c *Client, i interface{}, res *Note) []NoteVulnerability { a, ok := i.([]interface{}) if !ok { return []NoteVulnerability{} } if len(a) == 0 { return []NoteVulnerability{} } items := make([]NoteVulnerability, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerability(c, item.(map[string]interface{}), res)) } return items } // expandNoteVulnerability expands an instance of NoteVulnerability into a JSON // request object. func expandNoteVulnerability(c *Client, f *NoteVulnerability, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.CvssScore; !dcl.IsEmptyValueIndirect(v) { m["cvssScore"] = v } if v := f.Severity; !dcl.IsEmptyValueIndirect(v) { m["severity"] = v } if v, err := expandNoteVulnerabilityDetailsSlice(c, f.Details, res); err != nil { return nil, fmt.Errorf("error expanding Details into details: %w", err) } else if v != nil { m["details"] = v } if v, err := expandNoteVulnerabilityCvssV3(c, f.CvssV3, res); err != nil { return nil, fmt.Errorf("error expanding CvssV3 into cvssV3: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["cvssV3"] = v } if v, err := expandNoteVulnerabilityWindowsDetailsSlice(c, f.WindowsDetails, res); err != nil { return nil, fmt.Errorf("error expanding WindowsDetails into windowsDetails: %w", err) } else if v != nil { m["windowsDetails"] = v } if v := f.SourceUpdateTime; !dcl.IsEmptyValueIndirect(v) { m["sourceUpdateTime"] = v } return m, nil } // flattenNoteVulnerability flattens an instance of NoteVulnerability from a JSON // response object. func flattenNoteVulnerability(c *Client, i interface{}, res *Note) *NoteVulnerability { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteVulnerability{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteVulnerability } r.CvssScore = dcl.FlattenDouble(m["cvssScore"]) r.Severity = flattenNoteVulnerabilitySeverityEnum(m["severity"]) r.Details = flattenNoteVulnerabilityDetailsSlice(c, m["details"], res) r.CvssV3 = flattenNoteVulnerabilityCvssV3(c, m["cvssV3"], res) r.WindowsDetails = flattenNoteVulnerabilityWindowsDetailsSlice(c, m["windowsDetails"], res) r.SourceUpdateTime = dcl.FlattenString(m["sourceUpdateTime"]) return r } // expandNoteVulnerabilityDetailsMap expands the contents of NoteVulnerabilityDetails into a JSON // request object. func expandNoteVulnerabilityDetailsMap(c *Client, f map[string]NoteVulnerabilityDetails, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteVulnerabilityDetails(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteVulnerabilityDetailsSlice expands the contents of NoteVulnerabilityDetails into a JSON // request object. func expandNoteVulnerabilityDetailsSlice(c *Client, f []NoteVulnerabilityDetails, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteVulnerabilityDetails(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteVulnerabilityDetailsMap flattens the contents of NoteVulnerabilityDetails from a JSON // response object. func flattenNoteVulnerabilityDetailsMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityDetails { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityDetails{} } if len(a) == 0 { return map[string]NoteVulnerabilityDetails{} } items := make(map[string]NoteVulnerabilityDetails) for k, item := range a { items[k] = *flattenNoteVulnerabilityDetails(c, item.(map[string]interface{}), res) } return items } // flattenNoteVulnerabilityDetailsSlice flattens the contents of NoteVulnerabilityDetails from a JSON // response object. func flattenNoteVulnerabilityDetailsSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityDetails { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityDetails{} } if len(a) == 0 { return []NoteVulnerabilityDetails{} } items := make([]NoteVulnerabilityDetails, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityDetails(c, item.(map[string]interface{}), res)) } return items } // expandNoteVulnerabilityDetails expands an instance of NoteVulnerabilityDetails into a JSON // request object. func expandNoteVulnerabilityDetails(c *Client, f *NoteVulnerabilityDetails, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } m := make(map[string]interface{}) if v := f.SeverityName; !dcl.IsEmptyValueIndirect(v) { m["severityName"] = v } if v := f.Description; !dcl.IsEmptyValueIndirect(v) { m["description"] = v } if v := f.PackageType; !dcl.IsEmptyValueIndirect(v) { m["packageType"] = v } if v := f.AffectedCpeUri; !dcl.IsEmptyValueIndirect(v) { m["affectedCpeUri"] = v } if v := f.AffectedPackage; !dcl.IsEmptyValueIndirect(v) { m["affectedPackage"] = v } if v, err := expandNoteVulnerabilityDetailsAffectedVersionStart(c, f.AffectedVersionStart, res); err != nil { return nil, fmt.Errorf("error expanding AffectedVersionStart into affectedVersionStart: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["affectedVersionStart"] = v } if v, err := expandNoteVulnerabilityDetailsAffectedVersionEnd(c, f.AffectedVersionEnd, res); err != nil { return nil, fmt.Errorf("error expanding AffectedVersionEnd into affectedVersionEnd: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["affectedVersionEnd"] = v } if v := f.FixedCpeUri; !dcl.IsEmptyValueIndirect(v) { m["fixedCpeUri"] = v } if v := f.FixedPackage; !dcl.IsEmptyValueIndirect(v) { m["fixedPackage"] = v } if v, err := expandNoteVulnerabilityDetailsFixedVersion(c, f.FixedVersion, res); err != nil { return nil, fmt.Errorf("error expanding FixedVersion into fixedVersion: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["fixedVersion"] = v } if v := f.IsObsolete; !dcl.IsEmptyValueIndirect(v) { m["isObsolete"] = v } if v := f.SourceUpdateTime; !dcl.IsEmptyValueIndirect(v) { m["sourceUpdateTime"] = v } return m, nil } // flattenNoteVulnerabilityDetails flattens an instance of NoteVulnerabilityDetails from a JSON // response object. func flattenNoteVulnerabilityDetails(c *Client, i interface{}, res *Note) *NoteVulnerabilityDetails { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteVulnerabilityDetails{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteVulnerabilityDetails } r.SeverityName = dcl.FlattenString(m["severityName"]) r.Description = dcl.FlattenString(m["description"]) r.PackageType = dcl.FlattenString(m["packageType"]) r.AffectedCpeUri = dcl.FlattenString(m["affectedCpeUri"]) r.AffectedPackage = dcl.FlattenString(m["affectedPackage"]) r.AffectedVersionStart = flattenNoteVulnerabilityDetailsAffectedVersionStart(c, m["affectedVersionStart"], res) r.AffectedVersionEnd = flattenNoteVulnerabilityDetailsAffectedVersionEnd(c, m["affectedVersionEnd"], res) r.FixedCpeUri = dcl.FlattenString(m["fixedCpeUri"]) r.FixedPackage = dcl.FlattenString(m["fixedPackage"]) r.FixedVersion = flattenNoteVulnerabilityDetailsFixedVersion(c, m["fixedVersion"], res) r.IsObsolete = dcl.FlattenBool(m["isObsolete"]) r.SourceUpdateTime = dcl.FlattenString(m["sourceUpdateTime"]) return r } // expandNoteVulnerabilityDetailsAffectedVersionStartMap expands the contents of NoteVulnerabilityDetailsAffectedVersionStart into a JSON // request object. func expandNoteVulnerabilityDetailsAffectedVersionStartMap(c *Client, f map[string]NoteVulnerabilityDetailsAffectedVersionStart, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteVulnerabilityDetailsAffectedVersionStart(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteVulnerabilityDetailsAffectedVersionStartSlice expands the contents of NoteVulnerabilityDetailsAffectedVersionStart into a JSON // request object. func expandNoteVulnerabilityDetailsAffectedVersionStartSlice(c *Client, f []NoteVulnerabilityDetailsAffectedVersionStart, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteVulnerabilityDetailsAffectedVersionStart(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteVulnerabilityDetailsAffectedVersionStartMap flattens the contents of NoteVulnerabilityDetailsAffectedVersionStart from a JSON // response object. func flattenNoteVulnerabilityDetailsAffectedVersionStartMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityDetailsAffectedVersionStart { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityDetailsAffectedVersionStart{} } if len(a) == 0 { return map[string]NoteVulnerabilityDetailsAffectedVersionStart{} } items := make(map[string]NoteVulnerabilityDetailsAffectedVersionStart) for k, item := range a { items[k] = *flattenNoteVulnerabilityDetailsAffectedVersionStart(c, item.(map[string]interface{}), res) } return items } // flattenNoteVulnerabilityDetailsAffectedVersionStartSlice flattens the contents of NoteVulnerabilityDetailsAffectedVersionStart from a JSON // response object. func flattenNoteVulnerabilityDetailsAffectedVersionStartSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityDetailsAffectedVersionStart { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityDetailsAffectedVersionStart{} } if len(a) == 0 { return []NoteVulnerabilityDetailsAffectedVersionStart{} } items := make([]NoteVulnerabilityDetailsAffectedVersionStart, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityDetailsAffectedVersionStart(c, item.(map[string]interface{}), res)) } return items } // expandNoteVulnerabilityDetailsAffectedVersionStart expands an instance of NoteVulnerabilityDetailsAffectedVersionStart into a JSON // request object. func expandNoteVulnerabilityDetailsAffectedVersionStart(c *Client, f *NoteVulnerabilityDetailsAffectedVersionStart, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.Epoch; !dcl.IsEmptyValueIndirect(v) { m["epoch"] = v } if v := f.Name; !dcl.IsEmptyValueIndirect(v) { m["name"] = v } if v := f.Revision; !dcl.IsEmptyValueIndirect(v) { m["revision"] = v } if v := f.Kind; !dcl.IsEmptyValueIndirect(v) { m["kind"] = v } if v := f.FullName; !dcl.IsEmptyValueIndirect(v) { m["fullName"] = v } return m, nil } // flattenNoteVulnerabilityDetailsAffectedVersionStart flattens an instance of NoteVulnerabilityDetailsAffectedVersionStart from a JSON // response object. func flattenNoteVulnerabilityDetailsAffectedVersionStart(c *Client, i interface{}, res *Note) *NoteVulnerabilityDetailsAffectedVersionStart { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteVulnerabilityDetailsAffectedVersionStart{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteVulnerabilityDetailsAffectedVersionStart } r.Epoch = dcl.FlattenInteger(m["epoch"]) r.Name = dcl.FlattenString(m["name"]) r.Revision = dcl.FlattenString(m["revision"]) r.Kind = flattenNoteVulnerabilityDetailsAffectedVersionStartKindEnum(m["kind"]) r.FullName = dcl.FlattenString(m["fullName"]) return r } // expandNoteVulnerabilityDetailsAffectedVersionEndMap expands the contents of NoteVulnerabilityDetailsAffectedVersionEnd into a JSON // request object. func expandNoteVulnerabilityDetailsAffectedVersionEndMap(c *Client, f map[string]NoteVulnerabilityDetailsAffectedVersionEnd, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteVulnerabilityDetailsAffectedVersionEnd(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteVulnerabilityDetailsAffectedVersionEndSlice expands the contents of NoteVulnerabilityDetailsAffectedVersionEnd into a JSON // request object. func expandNoteVulnerabilityDetailsAffectedVersionEndSlice(c *Client, f []NoteVulnerabilityDetailsAffectedVersionEnd, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteVulnerabilityDetailsAffectedVersionEnd(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteVulnerabilityDetailsAffectedVersionEndMap flattens the contents of NoteVulnerabilityDetailsAffectedVersionEnd from a JSON // response object. func flattenNoteVulnerabilityDetailsAffectedVersionEndMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityDetailsAffectedVersionEnd { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityDetailsAffectedVersionEnd{} } if len(a) == 0 { return map[string]NoteVulnerabilityDetailsAffectedVersionEnd{} } items := make(map[string]NoteVulnerabilityDetailsAffectedVersionEnd) for k, item := range a { items[k] = *flattenNoteVulnerabilityDetailsAffectedVersionEnd(c, item.(map[string]interface{}), res) } return items } // flattenNoteVulnerabilityDetailsAffectedVersionEndSlice flattens the contents of NoteVulnerabilityDetailsAffectedVersionEnd from a JSON // response object. func flattenNoteVulnerabilityDetailsAffectedVersionEndSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityDetailsAffectedVersionEnd { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityDetailsAffectedVersionEnd{} } if len(a) == 0 { return []NoteVulnerabilityDetailsAffectedVersionEnd{} } items := make([]NoteVulnerabilityDetailsAffectedVersionEnd, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityDetailsAffectedVersionEnd(c, item.(map[string]interface{}), res)) } return items } // expandNoteVulnerabilityDetailsAffectedVersionEnd expands an instance of NoteVulnerabilityDetailsAffectedVersionEnd into a JSON // request object. func expandNoteVulnerabilityDetailsAffectedVersionEnd(c *Client, f *NoteVulnerabilityDetailsAffectedVersionEnd, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.Epoch; !dcl.IsEmptyValueIndirect(v) { m["epoch"] = v } if v := f.Name; !dcl.IsEmptyValueIndirect(v) { m["name"] = v } if v := f.Revision; !dcl.IsEmptyValueIndirect(v) { m["revision"] = v } if v := f.Kind; !dcl.IsEmptyValueIndirect(v) { m["kind"] = v } if v := f.FullName; !dcl.IsEmptyValueIndirect(v) { m["fullName"] = v } return m, nil } // flattenNoteVulnerabilityDetailsAffectedVersionEnd flattens an instance of NoteVulnerabilityDetailsAffectedVersionEnd from a JSON // response object. func flattenNoteVulnerabilityDetailsAffectedVersionEnd(c *Client, i interface{}, res *Note) *NoteVulnerabilityDetailsAffectedVersionEnd { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteVulnerabilityDetailsAffectedVersionEnd{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteVulnerabilityDetailsAffectedVersionEnd } r.Epoch = dcl.FlattenInteger(m["epoch"]) r.Name = dcl.FlattenString(m["name"]) r.Revision = dcl.FlattenString(m["revision"]) r.Kind = flattenNoteVulnerabilityDetailsAffectedVersionEndKindEnum(m["kind"]) r.FullName = dcl.FlattenString(m["fullName"]) return r } // expandNoteVulnerabilityDetailsFixedVersionMap expands the contents of NoteVulnerabilityDetailsFixedVersion into a JSON // request object. func expandNoteVulnerabilityDetailsFixedVersionMap(c *Client, f map[string]NoteVulnerabilityDetailsFixedVersion, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteVulnerabilityDetailsFixedVersion(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteVulnerabilityDetailsFixedVersionSlice expands the contents of NoteVulnerabilityDetailsFixedVersion into a JSON // request object. func expandNoteVulnerabilityDetailsFixedVersionSlice(c *Client, f []NoteVulnerabilityDetailsFixedVersion, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteVulnerabilityDetailsFixedVersion(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteVulnerabilityDetailsFixedVersionMap flattens the contents of NoteVulnerabilityDetailsFixedVersion from a JSON // response object. func flattenNoteVulnerabilityDetailsFixedVersionMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityDetailsFixedVersion { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityDetailsFixedVersion{} } if len(a) == 0 { return map[string]NoteVulnerabilityDetailsFixedVersion{} } items := make(map[string]NoteVulnerabilityDetailsFixedVersion) for k, item := range a { items[k] = *flattenNoteVulnerabilityDetailsFixedVersion(c, item.(map[string]interface{}), res) } return items } // flattenNoteVulnerabilityDetailsFixedVersionSlice flattens the contents of NoteVulnerabilityDetailsFixedVersion from a JSON // response object. func flattenNoteVulnerabilityDetailsFixedVersionSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityDetailsFixedVersion { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityDetailsFixedVersion{} } if len(a) == 0 { return []NoteVulnerabilityDetailsFixedVersion{} } items := make([]NoteVulnerabilityDetailsFixedVersion, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityDetailsFixedVersion(c, item.(map[string]interface{}), res)) } return items } // expandNoteVulnerabilityDetailsFixedVersion expands an instance of NoteVulnerabilityDetailsFixedVersion into a JSON // request object. func expandNoteVulnerabilityDetailsFixedVersion(c *Client, f *NoteVulnerabilityDetailsFixedVersion, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.Epoch; !dcl.IsEmptyValueIndirect(v) { m["epoch"] = v } if v := f.Name; !dcl.IsEmptyValueIndirect(v) { m["name"] = v } if v := f.Revision; !dcl.IsEmptyValueIndirect(v) { m["revision"] = v } if v := f.Kind; !dcl.IsEmptyValueIndirect(v) { m["kind"] = v } if v := f.FullName; !dcl.IsEmptyValueIndirect(v) { m["fullName"] = v } return m, nil } // flattenNoteVulnerabilityDetailsFixedVersion flattens an instance of NoteVulnerabilityDetailsFixedVersion from a JSON // response object. func flattenNoteVulnerabilityDetailsFixedVersion(c *Client, i interface{}, res *Note) *NoteVulnerabilityDetailsFixedVersion { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteVulnerabilityDetailsFixedVersion{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteVulnerabilityDetailsFixedVersion } r.Epoch = dcl.FlattenInteger(m["epoch"]) r.Name = dcl.FlattenString(m["name"]) r.Revision = dcl.FlattenString(m["revision"]) r.Kind = flattenNoteVulnerabilityDetailsFixedVersionKindEnum(m["kind"]) r.FullName = dcl.FlattenString(m["fullName"]) return r } // expandNoteVulnerabilityCvssV3Map expands the contents of NoteVulnerabilityCvssV3 into a JSON // request object. func expandNoteVulnerabilityCvssV3Map(c *Client, f map[string]NoteVulnerabilityCvssV3, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteVulnerabilityCvssV3(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteVulnerabilityCvssV3Slice expands the contents of NoteVulnerabilityCvssV3 into a JSON // request object. func expandNoteVulnerabilityCvssV3Slice(c *Client, f []NoteVulnerabilityCvssV3, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteVulnerabilityCvssV3(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteVulnerabilityCvssV3Map flattens the contents of NoteVulnerabilityCvssV3 from a JSON // response object. func flattenNoteVulnerabilityCvssV3Map(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityCvssV3 { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityCvssV3{} } if len(a) == 0 { return map[string]NoteVulnerabilityCvssV3{} } items := make(map[string]NoteVulnerabilityCvssV3) for k, item := range a { items[k] = *flattenNoteVulnerabilityCvssV3(c, item.(map[string]interface{}), res) } return items } // flattenNoteVulnerabilityCvssV3Slice flattens the contents of NoteVulnerabilityCvssV3 from a JSON // response object. func flattenNoteVulnerabilityCvssV3Slice(c *Client, i interface{}, res *Note) []NoteVulnerabilityCvssV3 { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityCvssV3{} } if len(a) == 0 { return []NoteVulnerabilityCvssV3{} } items := make([]NoteVulnerabilityCvssV3, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityCvssV3(c, item.(map[string]interface{}), res)) } return items } // expandNoteVulnerabilityCvssV3 expands an instance of NoteVulnerabilityCvssV3 into a JSON // request object. func expandNoteVulnerabilityCvssV3(c *Client, f *NoteVulnerabilityCvssV3, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.BaseScore; !dcl.IsEmptyValueIndirect(v) { m["baseScore"] = v } if v := f.ExploitabilityScore; !dcl.IsEmptyValueIndirect(v) { m["exploitabilityScore"] = v } if v := f.ImpactScore; !dcl.IsEmptyValueIndirect(v) { m["impactScore"] = v } if v := f.AttackVector; !dcl.IsEmptyValueIndirect(v) { m["attackVector"] = v } if v := f.AttackComplexity; !dcl.IsEmptyValueIndirect(v) { m["attackComplexity"] = v } if v := f.PrivilegesRequired; !dcl.IsEmptyValueIndirect(v) { m["privilegesRequired"] = v } if v := f.UserInteraction; !dcl.IsEmptyValueIndirect(v) { m["userInteraction"] = v } if v := f.Scope; !dcl.IsEmptyValueIndirect(v) { m["scope"] = v } if v := f.ConfidentialityImpact; !dcl.IsEmptyValueIndirect(v) { m["confidentialityImpact"] = v } if v := f.IntegrityImpact; !dcl.IsEmptyValueIndirect(v) { m["integrityImpact"] = v } if v := f.AvailabilityImpact; !dcl.IsEmptyValueIndirect(v) { m["availabilityImpact"] = v } return m, nil } // flattenNoteVulnerabilityCvssV3 flattens an instance of NoteVulnerabilityCvssV3 from a JSON // response object. func flattenNoteVulnerabilityCvssV3(c *Client, i interface{}, res *Note) *NoteVulnerabilityCvssV3 { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteVulnerabilityCvssV3{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteVulnerabilityCvssV3 } r.BaseScore = dcl.FlattenDouble(m["baseScore"]) r.ExploitabilityScore = dcl.FlattenDouble(m["exploitabilityScore"]) r.ImpactScore = dcl.FlattenDouble(m["impactScore"]) r.AttackVector = flattenNoteVulnerabilityCvssV3AttackVectorEnum(m["attackVector"]) r.AttackComplexity = flattenNoteVulnerabilityCvssV3AttackComplexityEnum(m["attackComplexity"]) r.PrivilegesRequired = flattenNoteVulnerabilityCvssV3PrivilegesRequiredEnum(m["privilegesRequired"]) r.UserInteraction = flattenNoteVulnerabilityCvssV3UserInteractionEnum(m["userInteraction"]) r.Scope = flattenNoteVulnerabilityCvssV3ScopeEnum(m["scope"]) r.ConfidentialityImpact = flattenNoteVulnerabilityCvssV3ConfidentialityImpactEnum(m["confidentialityImpact"]) r.IntegrityImpact = flattenNoteVulnerabilityCvssV3IntegrityImpactEnum(m["integrityImpact"]) r.AvailabilityImpact = flattenNoteVulnerabilityCvssV3AvailabilityImpactEnum(m["availabilityImpact"]) return r } // expandNoteVulnerabilityWindowsDetailsMap expands the contents of NoteVulnerabilityWindowsDetails into a JSON // request object. func expandNoteVulnerabilityWindowsDetailsMap(c *Client, f map[string]NoteVulnerabilityWindowsDetails, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteVulnerabilityWindowsDetails(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteVulnerabilityWindowsDetailsSlice expands the contents of NoteVulnerabilityWindowsDetails into a JSON // request object. func expandNoteVulnerabilityWindowsDetailsSlice(c *Client, f []NoteVulnerabilityWindowsDetails, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteVulnerabilityWindowsDetails(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteVulnerabilityWindowsDetailsMap flattens the contents of NoteVulnerabilityWindowsDetails from a JSON // response object. func flattenNoteVulnerabilityWindowsDetailsMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityWindowsDetails { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityWindowsDetails{} } if len(a) == 0 { return map[string]NoteVulnerabilityWindowsDetails{} } items := make(map[string]NoteVulnerabilityWindowsDetails) for k, item := range a { items[k] = *flattenNoteVulnerabilityWindowsDetails(c, item.(map[string]interface{}), res) } return items } // flattenNoteVulnerabilityWindowsDetailsSlice flattens the contents of NoteVulnerabilityWindowsDetails from a JSON // response object. func flattenNoteVulnerabilityWindowsDetailsSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityWindowsDetails { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityWindowsDetails{} } if len(a) == 0 { return []NoteVulnerabilityWindowsDetails{} } items := make([]NoteVulnerabilityWindowsDetails, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityWindowsDetails(c, item.(map[string]interface{}), res)) } return items } // expandNoteVulnerabilityWindowsDetails expands an instance of NoteVulnerabilityWindowsDetails into a JSON // request object. func expandNoteVulnerabilityWindowsDetails(c *Client, f *NoteVulnerabilityWindowsDetails, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } m := make(map[string]interface{}) if v := f.CpeUri; !dcl.IsEmptyValueIndirect(v) { m["cpeUri"] = v } if v := f.Name; !dcl.IsEmptyValueIndirect(v) { m["name"] = v } if v := f.Description; !dcl.IsEmptyValueIndirect(v) { m["description"] = v } if v, err := expandNoteVulnerabilityWindowsDetailsFixingKbsSlice(c, f.FixingKbs, res); err != nil { return nil, fmt.Errorf("error expanding FixingKbs into fixingKbs: %w", err) } else if v != nil { m["fixingKbs"] = v } return m, nil } // flattenNoteVulnerabilityWindowsDetails flattens an instance of NoteVulnerabilityWindowsDetails from a JSON // response object. func flattenNoteVulnerabilityWindowsDetails(c *Client, i interface{}, res *Note) *NoteVulnerabilityWindowsDetails { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteVulnerabilityWindowsDetails{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteVulnerabilityWindowsDetails } r.CpeUri = dcl.FlattenString(m["cpeUri"]) r.Name = dcl.FlattenString(m["name"]) r.Description = dcl.FlattenString(m["description"]) r.FixingKbs = flattenNoteVulnerabilityWindowsDetailsFixingKbsSlice(c, m["fixingKbs"], res) return r } // expandNoteVulnerabilityWindowsDetailsFixingKbsMap expands the contents of NoteVulnerabilityWindowsDetailsFixingKbs into a JSON // request object. func expandNoteVulnerabilityWindowsDetailsFixingKbsMap(c *Client, f map[string]NoteVulnerabilityWindowsDetailsFixingKbs, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteVulnerabilityWindowsDetailsFixingKbs(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteVulnerabilityWindowsDetailsFixingKbsSlice expands the contents of NoteVulnerabilityWindowsDetailsFixingKbs into a JSON // request object. func expandNoteVulnerabilityWindowsDetailsFixingKbsSlice(c *Client, f []NoteVulnerabilityWindowsDetailsFixingKbs, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteVulnerabilityWindowsDetailsFixingKbs(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteVulnerabilityWindowsDetailsFixingKbsMap flattens the contents of NoteVulnerabilityWindowsDetailsFixingKbs from a JSON // response object. func flattenNoteVulnerabilityWindowsDetailsFixingKbsMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityWindowsDetailsFixingKbs { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityWindowsDetailsFixingKbs{} } if len(a) == 0 { return map[string]NoteVulnerabilityWindowsDetailsFixingKbs{} } items := make(map[string]NoteVulnerabilityWindowsDetailsFixingKbs) for k, item := range a { items[k] = *flattenNoteVulnerabilityWindowsDetailsFixingKbs(c, item.(map[string]interface{}), res) } return items } // flattenNoteVulnerabilityWindowsDetailsFixingKbsSlice flattens the contents of NoteVulnerabilityWindowsDetailsFixingKbs from a JSON // response object. func flattenNoteVulnerabilityWindowsDetailsFixingKbsSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityWindowsDetailsFixingKbs { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityWindowsDetailsFixingKbs{} } if len(a) == 0 { return []NoteVulnerabilityWindowsDetailsFixingKbs{} } items := make([]NoteVulnerabilityWindowsDetailsFixingKbs, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityWindowsDetailsFixingKbs(c, item.(map[string]interface{}), res)) } return items } // expandNoteVulnerabilityWindowsDetailsFixingKbs expands an instance of NoteVulnerabilityWindowsDetailsFixingKbs into a JSON // request object. func expandNoteVulnerabilityWindowsDetailsFixingKbs(c *Client, f *NoteVulnerabilityWindowsDetailsFixingKbs, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } m := make(map[string]interface{}) if v := f.Name; !dcl.IsEmptyValueIndirect(v) { m["name"] = v } if v := f.Url; !dcl.IsEmptyValueIndirect(v) { m["url"] = v } return m, nil } // flattenNoteVulnerabilityWindowsDetailsFixingKbs flattens an instance of NoteVulnerabilityWindowsDetailsFixingKbs from a JSON // response object. func flattenNoteVulnerabilityWindowsDetailsFixingKbs(c *Client, i interface{}, res *Note) *NoteVulnerabilityWindowsDetailsFixingKbs { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteVulnerabilityWindowsDetailsFixingKbs{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteVulnerabilityWindowsDetailsFixingKbs } r.Name = dcl.FlattenString(m["name"]) r.Url = dcl.FlattenString(m["url"]) return r } // expandNoteBuildMap expands the contents of NoteBuild into a JSON // request object. func expandNoteBuildMap(c *Client, f map[string]NoteBuild, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteBuild(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteBuildSlice expands the contents of NoteBuild into a JSON // request object. func expandNoteBuildSlice(c *Client, f []NoteBuild, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteBuild(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteBuildMap flattens the contents of NoteBuild from a JSON // response object. func flattenNoteBuildMap(c *Client, i interface{}, res *Note) map[string]NoteBuild { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteBuild{} } if len(a) == 0 { return map[string]NoteBuild{} } items := make(map[string]NoteBuild) for k, item := range a { items[k] = *flattenNoteBuild(c, item.(map[string]interface{}), res) } return items } // flattenNoteBuildSlice flattens the contents of NoteBuild from a JSON // response object. func flattenNoteBuildSlice(c *Client, i interface{}, res *Note) []NoteBuild { a, ok := i.([]interface{}) if !ok { return []NoteBuild{} } if len(a) == 0 { return []NoteBuild{} } items := make([]NoteBuild, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteBuild(c, item.(map[string]interface{}), res)) } return items } // expandNoteBuild expands an instance of NoteBuild into a JSON // request object. func expandNoteBuild(c *Client, f *NoteBuild, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.BuilderVersion; !dcl.IsEmptyValueIndirect(v) { m["builderVersion"] = v } if v, err := expandNoteBuildSignature(c, f.Signature, res); err != nil { return nil, fmt.Errorf("error expanding Signature into signature: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["signature"] = v } return m, nil } // flattenNoteBuild flattens an instance of NoteBuild from a JSON // response object. func flattenNoteBuild(c *Client, i interface{}, res *Note) *NoteBuild { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteBuild{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteBuild } r.BuilderVersion = dcl.FlattenString(m["builderVersion"]) r.Signature = flattenNoteBuildSignature(c, m["signature"], res) return r } // expandNoteBuildSignatureMap expands the contents of NoteBuildSignature into a JSON // request object. func expandNoteBuildSignatureMap(c *Client, f map[string]NoteBuildSignature, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteBuildSignature(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteBuildSignatureSlice expands the contents of NoteBuildSignature into a JSON // request object. func expandNoteBuildSignatureSlice(c *Client, f []NoteBuildSignature, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteBuildSignature(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteBuildSignatureMap flattens the contents of NoteBuildSignature from a JSON // response object. func flattenNoteBuildSignatureMap(c *Client, i interface{}, res *Note) map[string]NoteBuildSignature { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteBuildSignature{} } if len(a) == 0 { return map[string]NoteBuildSignature{} } items := make(map[string]NoteBuildSignature) for k, item := range a { items[k] = *flattenNoteBuildSignature(c, item.(map[string]interface{}), res) } return items } // flattenNoteBuildSignatureSlice flattens the contents of NoteBuildSignature from a JSON // response object. func flattenNoteBuildSignatureSlice(c *Client, i interface{}, res *Note) []NoteBuildSignature { a, ok := i.([]interface{}) if !ok { return []NoteBuildSignature{} } if len(a) == 0 { return []NoteBuildSignature{} } items := make([]NoteBuildSignature, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteBuildSignature(c, item.(map[string]interface{}), res)) } return items } // expandNoteBuildSignature expands an instance of NoteBuildSignature into a JSON // request object. func expandNoteBuildSignature(c *Client, f *NoteBuildSignature, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.PublicKey; !dcl.IsEmptyValueIndirect(v) { m["publicKey"] = v } if v := f.Signature; !dcl.IsEmptyValueIndirect(v) { m["signature"] = v } if v := f.KeyId; !dcl.IsEmptyValueIndirect(v) { m["keyId"] = v } if v := f.KeyType; !dcl.IsEmptyValueIndirect(v) { m["keyType"] = v } return m, nil } // flattenNoteBuildSignature flattens an instance of NoteBuildSignature from a JSON // response object. func flattenNoteBuildSignature(c *Client, i interface{}, res *Note) *NoteBuildSignature { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteBuildSignature{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteBuildSignature } r.PublicKey = dcl.FlattenString(m["publicKey"]) r.Signature = dcl.FlattenString(m["signature"]) r.KeyId = dcl.FlattenString(m["keyId"]) r.KeyType = flattenNoteBuildSignatureKeyTypeEnum(m["keyType"]) return r } // expandNoteImageMap expands the contents of NoteImage into a JSON // request object. func expandNoteImageMap(c *Client, f map[string]NoteImage, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteImage(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteImageSlice expands the contents of NoteImage into a JSON // request object. func expandNoteImageSlice(c *Client, f []NoteImage, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteImage(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteImageMap flattens the contents of NoteImage from a JSON // response object. func flattenNoteImageMap(c *Client, i interface{}, res *Note) map[string]NoteImage { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteImage{} } if len(a) == 0 { return map[string]NoteImage{} } items := make(map[string]NoteImage) for k, item := range a { items[k] = *flattenNoteImage(c, item.(map[string]interface{}), res) } return items } // flattenNoteImageSlice flattens the contents of NoteImage from a JSON // response object. func flattenNoteImageSlice(c *Client, i interface{}, res *Note) []NoteImage { a, ok := i.([]interface{}) if !ok { return []NoteImage{} } if len(a) == 0 { return []NoteImage{} } items := make([]NoteImage, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteImage(c, item.(map[string]interface{}), res)) } return items } // expandNoteImage expands an instance of NoteImage into a JSON // request object. func expandNoteImage(c *Client, f *NoteImage, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.ResourceUrl; !dcl.IsEmptyValueIndirect(v) { m["resourceUrl"] = v } if v, err := expandNoteImageFingerprint(c, f.Fingerprint, res); err != nil { return nil, fmt.Errorf("error expanding Fingerprint into fingerprint: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["fingerprint"] = v } return m, nil } // flattenNoteImage flattens an instance of NoteImage from a JSON // response object. func flattenNoteImage(c *Client, i interface{}, res *Note) *NoteImage { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteImage{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteImage } r.ResourceUrl = dcl.FlattenString(m["resourceUrl"]) r.Fingerprint = flattenNoteImageFingerprint(c, m["fingerprint"], res) return r } // expandNoteImageFingerprintMap expands the contents of NoteImageFingerprint into a JSON // request object. func expandNoteImageFingerprintMap(c *Client, f map[string]NoteImageFingerprint, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteImageFingerprint(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteImageFingerprintSlice expands the contents of NoteImageFingerprint into a JSON // request object. func expandNoteImageFingerprintSlice(c *Client, f []NoteImageFingerprint, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteImageFingerprint(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteImageFingerprintMap flattens the contents of NoteImageFingerprint from a JSON // response object. func flattenNoteImageFingerprintMap(c *Client, i interface{}, res *Note) map[string]NoteImageFingerprint { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteImageFingerprint{} } if len(a) == 0 { return map[string]NoteImageFingerprint{} } items := make(map[string]NoteImageFingerprint) for k, item := range a { items[k] = *flattenNoteImageFingerprint(c, item.(map[string]interface{}), res) } return items } // flattenNoteImageFingerprintSlice flattens the contents of NoteImageFingerprint from a JSON // response object. func flattenNoteImageFingerprintSlice(c *Client, i interface{}, res *Note) []NoteImageFingerprint { a, ok := i.([]interface{}) if !ok { return []NoteImageFingerprint{} } if len(a) == 0 { return []NoteImageFingerprint{} } items := make([]NoteImageFingerprint, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteImageFingerprint(c, item.(map[string]interface{}), res)) } return items } // expandNoteImageFingerprint expands an instance of NoteImageFingerprint into a JSON // request object. func expandNoteImageFingerprint(c *Client, f *NoteImageFingerprint, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.V1Name; !dcl.IsEmptyValueIndirect(v) { m["v1Name"] = v } if v := f.V2Blob; v != nil { m["v2Blob"] = v } return m, nil } // flattenNoteImageFingerprint flattens an instance of NoteImageFingerprint from a JSON // response object. func flattenNoteImageFingerprint(c *Client, i interface{}, res *Note) *NoteImageFingerprint { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteImageFingerprint{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteImageFingerprint } r.V1Name = dcl.FlattenString(m["v1Name"]) r.V2Blob = dcl.FlattenStringSlice(m["v2Blob"]) r.V2Name = dcl.FlattenString(m["v2Name"]) return r } // expandNotePackageMap expands the contents of NotePackage into a JSON // request object. func expandNotePackageMap(c *Client, f map[string]NotePackage, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNotePackage(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNotePackageSlice expands the contents of NotePackage into a JSON // request object. func expandNotePackageSlice(c *Client, f []NotePackage, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNotePackage(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNotePackageMap flattens the contents of NotePackage from a JSON // response object. func flattenNotePackageMap(c *Client, i interface{}, res *Note) map[string]NotePackage { a, ok := i.(map[string]interface{}) if !ok { return map[string]NotePackage{} } if len(a) == 0 { return map[string]NotePackage{} } items := make(map[string]NotePackage) for k, item := range a { items[k] = *flattenNotePackage(c, item.(map[string]interface{}), res) } return items } // flattenNotePackageSlice flattens the contents of NotePackage from a JSON // response object. func flattenNotePackageSlice(c *Client, i interface{}, res *Note) []NotePackage { a, ok := i.([]interface{}) if !ok { return []NotePackage{} } if len(a) == 0 { return []NotePackage{} } items := make([]NotePackage, 0, len(a)) for _, item := range a { items = append(items, *flattenNotePackage(c, item.(map[string]interface{}), res)) } return items } // expandNotePackage expands an instance of NotePackage into a JSON // request object. func expandNotePackage(c *Client, f *NotePackage, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.Name; !dcl.IsEmptyValueIndirect(v) { m["name"] = v } if v, err := expandNotePackageDistributionSlice(c, f.Distribution, res); err != nil { return nil, fmt.Errorf("error expanding Distribution into distribution: %w", err) } else if v != nil { m["distribution"] = v } return m, nil } // flattenNotePackage flattens an instance of NotePackage from a JSON // response object. func flattenNotePackage(c *Client, i interface{}, res *Note) *NotePackage { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NotePackage{} if dcl.IsEmptyValueIndirect(i) { return EmptyNotePackage } r.Name = dcl.FlattenString(m["name"]) r.Distribution = flattenNotePackageDistributionSlice(c, m["distribution"], res) return r } // expandNotePackageDistributionMap expands the contents of NotePackageDistribution into a JSON // request object. func expandNotePackageDistributionMap(c *Client, f map[string]NotePackageDistribution, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNotePackageDistribution(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNotePackageDistributionSlice expands the contents of NotePackageDistribution into a JSON // request object. func expandNotePackageDistributionSlice(c *Client, f []NotePackageDistribution, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNotePackageDistribution(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNotePackageDistributionMap flattens the contents of NotePackageDistribution from a JSON // response object. func flattenNotePackageDistributionMap(c *Client, i interface{}, res *Note) map[string]NotePackageDistribution { a, ok := i.(map[string]interface{}) if !ok { return map[string]NotePackageDistribution{} } if len(a) == 0 { return map[string]NotePackageDistribution{} } items := make(map[string]NotePackageDistribution) for k, item := range a { items[k] = *flattenNotePackageDistribution(c, item.(map[string]interface{}), res) } return items } // flattenNotePackageDistributionSlice flattens the contents of NotePackageDistribution from a JSON // response object. func flattenNotePackageDistributionSlice(c *Client, i interface{}, res *Note) []NotePackageDistribution { a, ok := i.([]interface{}) if !ok { return []NotePackageDistribution{} } if len(a) == 0 { return []NotePackageDistribution{} } items := make([]NotePackageDistribution, 0, len(a)) for _, item := range a { items = append(items, *flattenNotePackageDistribution(c, item.(map[string]interface{}), res)) } return items } // expandNotePackageDistribution expands an instance of NotePackageDistribution into a JSON // request object. func expandNotePackageDistribution(c *Client, f *NotePackageDistribution, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } m := make(map[string]interface{}) if v := f.CpeUri; !dcl.IsEmptyValueIndirect(v) { m["cpeUri"] = v } if v := f.Architecture; !dcl.IsEmptyValueIndirect(v) { m["architecture"] = v } if v, err := expandNotePackageDistributionLatestVersion(c, f.LatestVersion, res); err != nil { return nil, fmt.Errorf("error expanding LatestVersion into latestVersion: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["latestVersion"] = v } if v := f.Maintainer; !dcl.IsEmptyValueIndirect(v) { m["maintainer"] = v } if v := f.Url; !dcl.IsEmptyValueIndirect(v) { m["url"] = v } if v := f.Description; !dcl.IsEmptyValueIndirect(v) { m["description"] = v } return m, nil } // flattenNotePackageDistribution flattens an instance of NotePackageDistribution from a JSON // response object. func flattenNotePackageDistribution(c *Client, i interface{}, res *Note) *NotePackageDistribution { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NotePackageDistribution{} if dcl.IsEmptyValueIndirect(i) { return EmptyNotePackageDistribution } r.CpeUri = dcl.FlattenString(m["cpeUri"]) r.Architecture = flattenNotePackageDistributionArchitectureEnum(m["architecture"]) r.LatestVersion = flattenNotePackageDistributionLatestVersion(c, m["latestVersion"], res) r.Maintainer = dcl.FlattenString(m["maintainer"]) r.Url = dcl.FlattenString(m["url"]) r.Description = dcl.FlattenString(m["description"]) return r } // expandNotePackageDistributionLatestVersionMap expands the contents of NotePackageDistributionLatestVersion into a JSON // request object. func expandNotePackageDistributionLatestVersionMap(c *Client, f map[string]NotePackageDistributionLatestVersion, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNotePackageDistributionLatestVersion(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNotePackageDistributionLatestVersionSlice expands the contents of NotePackageDistributionLatestVersion into a JSON // request object. func expandNotePackageDistributionLatestVersionSlice(c *Client, f []NotePackageDistributionLatestVersion, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNotePackageDistributionLatestVersion(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNotePackageDistributionLatestVersionMap flattens the contents of NotePackageDistributionLatestVersion from a JSON // response object. func flattenNotePackageDistributionLatestVersionMap(c *Client, i interface{}, res *Note) map[string]NotePackageDistributionLatestVersion { a, ok := i.(map[string]interface{}) if !ok { return map[string]NotePackageDistributionLatestVersion{} } if len(a) == 0 { return map[string]NotePackageDistributionLatestVersion{} } items := make(map[string]NotePackageDistributionLatestVersion) for k, item := range a { items[k] = *flattenNotePackageDistributionLatestVersion(c, item.(map[string]interface{}), res) } return items } // flattenNotePackageDistributionLatestVersionSlice flattens the contents of NotePackageDistributionLatestVersion from a JSON // response object. func flattenNotePackageDistributionLatestVersionSlice(c *Client, i interface{}, res *Note) []NotePackageDistributionLatestVersion { a, ok := i.([]interface{}) if !ok { return []NotePackageDistributionLatestVersion{} } if len(a) == 0 { return []NotePackageDistributionLatestVersion{} } items := make([]NotePackageDistributionLatestVersion, 0, len(a)) for _, item := range a { items = append(items, *flattenNotePackageDistributionLatestVersion(c, item.(map[string]interface{}), res)) } return items } // expandNotePackageDistributionLatestVersion expands an instance of NotePackageDistributionLatestVersion into a JSON // request object. func expandNotePackageDistributionLatestVersion(c *Client, f *NotePackageDistributionLatestVersion, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.Epoch; !dcl.IsEmptyValueIndirect(v) { m["epoch"] = v } if v := f.Name; !dcl.IsEmptyValueIndirect(v) { m["name"] = v } if v := f.Revision; !dcl.IsEmptyValueIndirect(v) { m["revision"] = v } if v := f.Kind; !dcl.IsEmptyValueIndirect(v) { m["kind"] = v } if v := f.FullName; !dcl.IsEmptyValueIndirect(v) { m["fullName"] = v } return m, nil } // flattenNotePackageDistributionLatestVersion flattens an instance of NotePackageDistributionLatestVersion from a JSON // response object. func flattenNotePackageDistributionLatestVersion(c *Client, i interface{}, res *Note) *NotePackageDistributionLatestVersion { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NotePackageDistributionLatestVersion{} if dcl.IsEmptyValueIndirect(i) { return EmptyNotePackageDistributionLatestVersion } r.Epoch = dcl.FlattenInteger(m["epoch"]) r.Name = dcl.FlattenString(m["name"]) r.Revision = dcl.FlattenString(m["revision"]) r.Kind = flattenNotePackageDistributionLatestVersionKindEnum(m["kind"]) r.FullName = dcl.FlattenString(m["fullName"]) return r } // expandNoteDiscoveryMap expands the contents of NoteDiscovery into a JSON // request object. func expandNoteDiscoveryMap(c *Client, f map[string]NoteDiscovery, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteDiscovery(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteDiscoverySlice expands the contents of NoteDiscovery into a JSON // request object. func expandNoteDiscoverySlice(c *Client, f []NoteDiscovery, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteDiscovery(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteDiscoveryMap flattens the contents of NoteDiscovery from a JSON // response object. func flattenNoteDiscoveryMap(c *Client, i interface{}, res *Note) map[string]NoteDiscovery { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteDiscovery{} } if len(a) == 0 { return map[string]NoteDiscovery{} } items := make(map[string]NoteDiscovery) for k, item := range a { items[k] = *flattenNoteDiscovery(c, item.(map[string]interface{}), res) } return items } // flattenNoteDiscoverySlice flattens the contents of NoteDiscovery from a JSON // response object. func flattenNoteDiscoverySlice(c *Client, i interface{}, res *Note) []NoteDiscovery { a, ok := i.([]interface{}) if !ok { return []NoteDiscovery{} } if len(a) == 0 { return []NoteDiscovery{} } items := make([]NoteDiscovery, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteDiscovery(c, item.(map[string]interface{}), res)) } return items } // expandNoteDiscovery expands an instance of NoteDiscovery into a JSON // request object. func expandNoteDiscovery(c *Client, f *NoteDiscovery, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.AnalysisKind; !dcl.IsEmptyValueIndirect(v) { m["analysisKind"] = v } return m, nil } // flattenNoteDiscovery flattens an instance of NoteDiscovery from a JSON // response object. func flattenNoteDiscovery(c *Client, i interface{}, res *Note) *NoteDiscovery { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteDiscovery{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteDiscovery } r.AnalysisKind = flattenNoteDiscoveryAnalysisKindEnum(m["analysisKind"]) return r } // expandNoteDeploymentMap expands the contents of NoteDeployment into a JSON // request object. func expandNoteDeploymentMap(c *Client, f map[string]NoteDeployment, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteDeployment(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteDeploymentSlice expands the contents of NoteDeployment into a JSON // request object. func expandNoteDeploymentSlice(c *Client, f []NoteDeployment, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteDeployment(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteDeploymentMap flattens the contents of NoteDeployment from a JSON // response object. func flattenNoteDeploymentMap(c *Client, i interface{}, res *Note) map[string]NoteDeployment { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteDeployment{} } if len(a) == 0 { return map[string]NoteDeployment{} } items := make(map[string]NoteDeployment) for k, item := range a { items[k] = *flattenNoteDeployment(c, item.(map[string]interface{}), res) } return items } // flattenNoteDeploymentSlice flattens the contents of NoteDeployment from a JSON // response object. func flattenNoteDeploymentSlice(c *Client, i interface{}, res *Note) []NoteDeployment { a, ok := i.([]interface{}) if !ok { return []NoteDeployment{} } if len(a) == 0 { return []NoteDeployment{} } items := make([]NoteDeployment, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteDeployment(c, item.(map[string]interface{}), res)) } return items } // expandNoteDeployment expands an instance of NoteDeployment into a JSON // request object. func expandNoteDeployment(c *Client, f *NoteDeployment, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.ResourceUri; v != nil { m["resourceUri"] = v } return m, nil } // flattenNoteDeployment flattens an instance of NoteDeployment from a JSON // response object. func flattenNoteDeployment(c *Client, i interface{}, res *Note) *NoteDeployment { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteDeployment{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteDeployment } r.ResourceUri = dcl.FlattenStringSlice(m["resourceUri"]) return r } // expandNoteAttestationMap expands the contents of NoteAttestation into a JSON // request object. func expandNoteAttestationMap(c *Client, f map[string]NoteAttestation, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteAttestation(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteAttestationSlice expands the contents of NoteAttestation into a JSON // request object. func expandNoteAttestationSlice(c *Client, f []NoteAttestation, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteAttestation(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteAttestationMap flattens the contents of NoteAttestation from a JSON // response object. func flattenNoteAttestationMap(c *Client, i interface{}, res *Note) map[string]NoteAttestation { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteAttestation{} } if len(a) == 0 { return map[string]NoteAttestation{} } items := make(map[string]NoteAttestation) for k, item := range a { items[k] = *flattenNoteAttestation(c, item.(map[string]interface{}), res) } return items } // flattenNoteAttestationSlice flattens the contents of NoteAttestation from a JSON // response object. func flattenNoteAttestationSlice(c *Client, i interface{}, res *Note) []NoteAttestation { a, ok := i.([]interface{}) if !ok { return []NoteAttestation{} } if len(a) == 0 { return []NoteAttestation{} } items := make([]NoteAttestation, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteAttestation(c, item.(map[string]interface{}), res)) } return items } // expandNoteAttestation expands an instance of NoteAttestation into a JSON // request object. func expandNoteAttestation(c *Client, f *NoteAttestation, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v, err := expandNoteAttestationHint(c, f.Hint, res); err != nil { return nil, fmt.Errorf("error expanding Hint into hint: %w", err) } else if !dcl.IsEmptyValueIndirect(v) { m["hint"] = v } return m, nil } // flattenNoteAttestation flattens an instance of NoteAttestation from a JSON // response object. func flattenNoteAttestation(c *Client, i interface{}, res *Note) *NoteAttestation { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteAttestation{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteAttestation } r.Hint = flattenNoteAttestationHint(c, m["hint"], res) return r } // expandNoteAttestationHintMap expands the contents of NoteAttestationHint into a JSON // request object. func expandNoteAttestationHintMap(c *Client, f map[string]NoteAttestationHint, res *Note) (map[string]interface{}, error) { if f == nil { return nil, nil } items := make(map[string]interface{}) for k, item := range f { i, err := expandNoteAttestationHint(c, &item, res) if err != nil { return nil, err } if i != nil { items[k] = i } } return items, nil } // expandNoteAttestationHintSlice expands the contents of NoteAttestationHint into a JSON // request object. func expandNoteAttestationHintSlice(c *Client, f []NoteAttestationHint, res *Note) ([]map[string]interface{}, error) { if f == nil { return nil, nil } items := []map[string]interface{}{} for _, item := range f { i, err := expandNoteAttestationHint(c, &item, res) if err != nil { return nil, err } items = append(items, i) } return items, nil } // flattenNoteAttestationHintMap flattens the contents of NoteAttestationHint from a JSON // response object. func flattenNoteAttestationHintMap(c *Client, i interface{}, res *Note) map[string]NoteAttestationHint { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteAttestationHint{} } if len(a) == 0 { return map[string]NoteAttestationHint{} } items := make(map[string]NoteAttestationHint) for k, item := range a { items[k] = *flattenNoteAttestationHint(c, item.(map[string]interface{}), res) } return items } // flattenNoteAttestationHintSlice flattens the contents of NoteAttestationHint from a JSON // response object. func flattenNoteAttestationHintSlice(c *Client, i interface{}, res *Note) []NoteAttestationHint { a, ok := i.([]interface{}) if !ok { return []NoteAttestationHint{} } if len(a) == 0 { return []NoteAttestationHint{} } items := make([]NoteAttestationHint, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteAttestationHint(c, item.(map[string]interface{}), res)) } return items } // expandNoteAttestationHint expands an instance of NoteAttestationHint into a JSON // request object. func expandNoteAttestationHint(c *Client, f *NoteAttestationHint, res *Note) (map[string]interface{}, error) { if dcl.IsEmptyValueIndirect(f) { return nil, nil } m := make(map[string]interface{}) if v := f.HumanReadableName; !dcl.IsEmptyValueIndirect(v) { m["humanReadableName"] = v } return m, nil } // flattenNoteAttestationHint flattens an instance of NoteAttestationHint from a JSON // response object. func flattenNoteAttestationHint(c *Client, i interface{}, res *Note) *NoteAttestationHint { m, ok := i.(map[string]interface{}) if !ok { return nil } r := &NoteAttestationHint{} if dcl.IsEmptyValueIndirect(i) { return EmptyNoteAttestationHint } r.HumanReadableName = dcl.FlattenString(m["humanReadableName"]) return r } // flattenNoteVulnerabilitySeverityEnumMap flattens the contents of NoteVulnerabilitySeverityEnum from a JSON // response object. func flattenNoteVulnerabilitySeverityEnumMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilitySeverityEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilitySeverityEnum{} } if len(a) == 0 { return map[string]NoteVulnerabilitySeverityEnum{} } items := make(map[string]NoteVulnerabilitySeverityEnum) for k, item := range a { items[k] = *flattenNoteVulnerabilitySeverityEnum(item.(interface{})) } return items } // flattenNoteVulnerabilitySeverityEnumSlice flattens the contents of NoteVulnerabilitySeverityEnum from a JSON // response object. func flattenNoteVulnerabilitySeverityEnumSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilitySeverityEnum { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilitySeverityEnum{} } if len(a) == 0 { return []NoteVulnerabilitySeverityEnum{} } items := make([]NoteVulnerabilitySeverityEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilitySeverityEnum(item.(interface{}))) } return items } // flattenNoteVulnerabilitySeverityEnum asserts that an interface is a string, and returns a // pointer to a *NoteVulnerabilitySeverityEnum with the same value as that string. func flattenNoteVulnerabilitySeverityEnum(i interface{}) *NoteVulnerabilitySeverityEnum { s, ok := i.(string) if !ok { return nil } return NoteVulnerabilitySeverityEnumRef(s) } // flattenNoteVulnerabilityDetailsAffectedVersionStartKindEnumMap flattens the contents of NoteVulnerabilityDetailsAffectedVersionStartKindEnum from a JSON // response object. func flattenNoteVulnerabilityDetailsAffectedVersionStartKindEnumMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityDetailsAffectedVersionStartKindEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityDetailsAffectedVersionStartKindEnum{} } if len(a) == 0 { return map[string]NoteVulnerabilityDetailsAffectedVersionStartKindEnum{} } items := make(map[string]NoteVulnerabilityDetailsAffectedVersionStartKindEnum) for k, item := range a { items[k] = *flattenNoteVulnerabilityDetailsAffectedVersionStartKindEnum(item.(interface{})) } return items } // flattenNoteVulnerabilityDetailsAffectedVersionStartKindEnumSlice flattens the contents of NoteVulnerabilityDetailsAffectedVersionStartKindEnum from a JSON // response object. func flattenNoteVulnerabilityDetailsAffectedVersionStartKindEnumSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityDetailsAffectedVersionStartKindEnum { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityDetailsAffectedVersionStartKindEnum{} } if len(a) == 0 { return []NoteVulnerabilityDetailsAffectedVersionStartKindEnum{} } items := make([]NoteVulnerabilityDetailsAffectedVersionStartKindEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityDetailsAffectedVersionStartKindEnum(item.(interface{}))) } return items } // flattenNoteVulnerabilityDetailsAffectedVersionStartKindEnum asserts that an interface is a string, and returns a // pointer to a *NoteVulnerabilityDetailsAffectedVersionStartKindEnum with the same value as that string. func flattenNoteVulnerabilityDetailsAffectedVersionStartKindEnum(i interface{}) *NoteVulnerabilityDetailsAffectedVersionStartKindEnum { s, ok := i.(string) if !ok { return nil } return NoteVulnerabilityDetailsAffectedVersionStartKindEnumRef(s) } // flattenNoteVulnerabilityDetailsAffectedVersionEndKindEnumMap flattens the contents of NoteVulnerabilityDetailsAffectedVersionEndKindEnum from a JSON // response object. func flattenNoteVulnerabilityDetailsAffectedVersionEndKindEnumMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityDetailsAffectedVersionEndKindEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityDetailsAffectedVersionEndKindEnum{} } if len(a) == 0 { return map[string]NoteVulnerabilityDetailsAffectedVersionEndKindEnum{} } items := make(map[string]NoteVulnerabilityDetailsAffectedVersionEndKindEnum) for k, item := range a { items[k] = *flattenNoteVulnerabilityDetailsAffectedVersionEndKindEnum(item.(interface{})) } return items } // flattenNoteVulnerabilityDetailsAffectedVersionEndKindEnumSlice flattens the contents of NoteVulnerabilityDetailsAffectedVersionEndKindEnum from a JSON // response object. func flattenNoteVulnerabilityDetailsAffectedVersionEndKindEnumSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityDetailsAffectedVersionEndKindEnum { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityDetailsAffectedVersionEndKindEnum{} } if len(a) == 0 { return []NoteVulnerabilityDetailsAffectedVersionEndKindEnum{} } items := make([]NoteVulnerabilityDetailsAffectedVersionEndKindEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityDetailsAffectedVersionEndKindEnum(item.(interface{}))) } return items } // flattenNoteVulnerabilityDetailsAffectedVersionEndKindEnum asserts that an interface is a string, and returns a // pointer to a *NoteVulnerabilityDetailsAffectedVersionEndKindEnum with the same value as that string. func flattenNoteVulnerabilityDetailsAffectedVersionEndKindEnum(i interface{}) *NoteVulnerabilityDetailsAffectedVersionEndKindEnum { s, ok := i.(string) if !ok { return nil } return NoteVulnerabilityDetailsAffectedVersionEndKindEnumRef(s) } // flattenNoteVulnerabilityDetailsFixedVersionKindEnumMap flattens the contents of NoteVulnerabilityDetailsFixedVersionKindEnum from a JSON // response object. func flattenNoteVulnerabilityDetailsFixedVersionKindEnumMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityDetailsFixedVersionKindEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityDetailsFixedVersionKindEnum{} } if len(a) == 0 { return map[string]NoteVulnerabilityDetailsFixedVersionKindEnum{} } items := make(map[string]NoteVulnerabilityDetailsFixedVersionKindEnum) for k, item := range a { items[k] = *flattenNoteVulnerabilityDetailsFixedVersionKindEnum(item.(interface{})) } return items } // flattenNoteVulnerabilityDetailsFixedVersionKindEnumSlice flattens the contents of NoteVulnerabilityDetailsFixedVersionKindEnum from a JSON // response object. func flattenNoteVulnerabilityDetailsFixedVersionKindEnumSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityDetailsFixedVersionKindEnum { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityDetailsFixedVersionKindEnum{} } if len(a) == 0 { return []NoteVulnerabilityDetailsFixedVersionKindEnum{} } items := make([]NoteVulnerabilityDetailsFixedVersionKindEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityDetailsFixedVersionKindEnum(item.(interface{}))) } return items } // flattenNoteVulnerabilityDetailsFixedVersionKindEnum asserts that an interface is a string, and returns a // pointer to a *NoteVulnerabilityDetailsFixedVersionKindEnum with the same value as that string. func flattenNoteVulnerabilityDetailsFixedVersionKindEnum(i interface{}) *NoteVulnerabilityDetailsFixedVersionKindEnum { s, ok := i.(string) if !ok { return nil } return NoteVulnerabilityDetailsFixedVersionKindEnumRef(s) } // flattenNoteVulnerabilityCvssV3AttackVectorEnumMap flattens the contents of NoteVulnerabilityCvssV3AttackVectorEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3AttackVectorEnumMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityCvssV3AttackVectorEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityCvssV3AttackVectorEnum{} } if len(a) == 0 { return map[string]NoteVulnerabilityCvssV3AttackVectorEnum{} } items := make(map[string]NoteVulnerabilityCvssV3AttackVectorEnum) for k, item := range a { items[k] = *flattenNoteVulnerabilityCvssV3AttackVectorEnum(item.(interface{})) } return items } // flattenNoteVulnerabilityCvssV3AttackVectorEnumSlice flattens the contents of NoteVulnerabilityCvssV3AttackVectorEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3AttackVectorEnumSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityCvssV3AttackVectorEnum { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityCvssV3AttackVectorEnum{} } if len(a) == 0 { return []NoteVulnerabilityCvssV3AttackVectorEnum{} } items := make([]NoteVulnerabilityCvssV3AttackVectorEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityCvssV3AttackVectorEnum(item.(interface{}))) } return items } // flattenNoteVulnerabilityCvssV3AttackVectorEnum asserts that an interface is a string, and returns a // pointer to a *NoteVulnerabilityCvssV3AttackVectorEnum with the same value as that string. func flattenNoteVulnerabilityCvssV3AttackVectorEnum(i interface{}) *NoteVulnerabilityCvssV3AttackVectorEnum { s, ok := i.(string) if !ok { return nil } return NoteVulnerabilityCvssV3AttackVectorEnumRef(s) } // flattenNoteVulnerabilityCvssV3AttackComplexityEnumMap flattens the contents of NoteVulnerabilityCvssV3AttackComplexityEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3AttackComplexityEnumMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityCvssV3AttackComplexityEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityCvssV3AttackComplexityEnum{} } if len(a) == 0 { return map[string]NoteVulnerabilityCvssV3AttackComplexityEnum{} } items := make(map[string]NoteVulnerabilityCvssV3AttackComplexityEnum) for k, item := range a { items[k] = *flattenNoteVulnerabilityCvssV3AttackComplexityEnum(item.(interface{})) } return items } // flattenNoteVulnerabilityCvssV3AttackComplexityEnumSlice flattens the contents of NoteVulnerabilityCvssV3AttackComplexityEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3AttackComplexityEnumSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityCvssV3AttackComplexityEnum { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityCvssV3AttackComplexityEnum{} } if len(a) == 0 { return []NoteVulnerabilityCvssV3AttackComplexityEnum{} } items := make([]NoteVulnerabilityCvssV3AttackComplexityEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityCvssV3AttackComplexityEnum(item.(interface{}))) } return items } // flattenNoteVulnerabilityCvssV3AttackComplexityEnum asserts that an interface is a string, and returns a // pointer to a *NoteVulnerabilityCvssV3AttackComplexityEnum with the same value as that string. func flattenNoteVulnerabilityCvssV3AttackComplexityEnum(i interface{}) *NoteVulnerabilityCvssV3AttackComplexityEnum { s, ok := i.(string) if !ok { return nil } return NoteVulnerabilityCvssV3AttackComplexityEnumRef(s) } // flattenNoteVulnerabilityCvssV3PrivilegesRequiredEnumMap flattens the contents of NoteVulnerabilityCvssV3PrivilegesRequiredEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3PrivilegesRequiredEnumMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityCvssV3PrivilegesRequiredEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityCvssV3PrivilegesRequiredEnum{} } if len(a) == 0 { return map[string]NoteVulnerabilityCvssV3PrivilegesRequiredEnum{} } items := make(map[string]NoteVulnerabilityCvssV3PrivilegesRequiredEnum) for k, item := range a { items[k] = *flattenNoteVulnerabilityCvssV3PrivilegesRequiredEnum(item.(interface{})) } return items } // flattenNoteVulnerabilityCvssV3PrivilegesRequiredEnumSlice flattens the contents of NoteVulnerabilityCvssV3PrivilegesRequiredEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3PrivilegesRequiredEnumSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityCvssV3PrivilegesRequiredEnum { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityCvssV3PrivilegesRequiredEnum{} } if len(a) == 0 { return []NoteVulnerabilityCvssV3PrivilegesRequiredEnum{} } items := make([]NoteVulnerabilityCvssV3PrivilegesRequiredEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityCvssV3PrivilegesRequiredEnum(item.(interface{}))) } return items } // flattenNoteVulnerabilityCvssV3PrivilegesRequiredEnum asserts that an interface is a string, and returns a // pointer to a *NoteVulnerabilityCvssV3PrivilegesRequiredEnum with the same value as that string. func flattenNoteVulnerabilityCvssV3PrivilegesRequiredEnum(i interface{}) *NoteVulnerabilityCvssV3PrivilegesRequiredEnum { s, ok := i.(string) if !ok { return nil } return NoteVulnerabilityCvssV3PrivilegesRequiredEnumRef(s) } // flattenNoteVulnerabilityCvssV3UserInteractionEnumMap flattens the contents of NoteVulnerabilityCvssV3UserInteractionEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3UserInteractionEnumMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityCvssV3UserInteractionEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityCvssV3UserInteractionEnum{} } if len(a) == 0 { return map[string]NoteVulnerabilityCvssV3UserInteractionEnum{} } items := make(map[string]NoteVulnerabilityCvssV3UserInteractionEnum) for k, item := range a { items[k] = *flattenNoteVulnerabilityCvssV3UserInteractionEnum(item.(interface{})) } return items } // flattenNoteVulnerabilityCvssV3UserInteractionEnumSlice flattens the contents of NoteVulnerabilityCvssV3UserInteractionEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3UserInteractionEnumSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityCvssV3UserInteractionEnum { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityCvssV3UserInteractionEnum{} } if len(a) == 0 { return []NoteVulnerabilityCvssV3UserInteractionEnum{} } items := make([]NoteVulnerabilityCvssV3UserInteractionEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityCvssV3UserInteractionEnum(item.(interface{}))) } return items } // flattenNoteVulnerabilityCvssV3UserInteractionEnum asserts that an interface is a string, and returns a // pointer to a *NoteVulnerabilityCvssV3UserInteractionEnum with the same value as that string. func flattenNoteVulnerabilityCvssV3UserInteractionEnum(i interface{}) *NoteVulnerabilityCvssV3UserInteractionEnum { s, ok := i.(string) if !ok { return nil } return NoteVulnerabilityCvssV3UserInteractionEnumRef(s) } // flattenNoteVulnerabilityCvssV3ScopeEnumMap flattens the contents of NoteVulnerabilityCvssV3ScopeEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3ScopeEnumMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityCvssV3ScopeEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityCvssV3ScopeEnum{} } if len(a) == 0 { return map[string]NoteVulnerabilityCvssV3ScopeEnum{} } items := make(map[string]NoteVulnerabilityCvssV3ScopeEnum) for k, item := range a { items[k] = *flattenNoteVulnerabilityCvssV3ScopeEnum(item.(interface{})) } return items } // flattenNoteVulnerabilityCvssV3ScopeEnumSlice flattens the contents of NoteVulnerabilityCvssV3ScopeEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3ScopeEnumSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityCvssV3ScopeEnum { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityCvssV3ScopeEnum{} } if len(a) == 0 { return []NoteVulnerabilityCvssV3ScopeEnum{} } items := make([]NoteVulnerabilityCvssV3ScopeEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityCvssV3ScopeEnum(item.(interface{}))) } return items } // flattenNoteVulnerabilityCvssV3ScopeEnum asserts that an interface is a string, and returns a // pointer to a *NoteVulnerabilityCvssV3ScopeEnum with the same value as that string. func flattenNoteVulnerabilityCvssV3ScopeEnum(i interface{}) *NoteVulnerabilityCvssV3ScopeEnum { s, ok := i.(string) if !ok { return nil } return NoteVulnerabilityCvssV3ScopeEnumRef(s) } // flattenNoteVulnerabilityCvssV3ConfidentialityImpactEnumMap flattens the contents of NoteVulnerabilityCvssV3ConfidentialityImpactEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3ConfidentialityImpactEnumMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityCvssV3ConfidentialityImpactEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityCvssV3ConfidentialityImpactEnum{} } if len(a) == 0 { return map[string]NoteVulnerabilityCvssV3ConfidentialityImpactEnum{} } items := make(map[string]NoteVulnerabilityCvssV3ConfidentialityImpactEnum) for k, item := range a { items[k] = *flattenNoteVulnerabilityCvssV3ConfidentialityImpactEnum(item.(interface{})) } return items } // flattenNoteVulnerabilityCvssV3ConfidentialityImpactEnumSlice flattens the contents of NoteVulnerabilityCvssV3ConfidentialityImpactEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3ConfidentialityImpactEnumSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityCvssV3ConfidentialityImpactEnum { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityCvssV3ConfidentialityImpactEnum{} } if len(a) == 0 { return []NoteVulnerabilityCvssV3ConfidentialityImpactEnum{} } items := make([]NoteVulnerabilityCvssV3ConfidentialityImpactEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityCvssV3ConfidentialityImpactEnum(item.(interface{}))) } return items } // flattenNoteVulnerabilityCvssV3ConfidentialityImpactEnum asserts that an interface is a string, and returns a // pointer to a *NoteVulnerabilityCvssV3ConfidentialityImpactEnum with the same value as that string. func flattenNoteVulnerabilityCvssV3ConfidentialityImpactEnum(i interface{}) *NoteVulnerabilityCvssV3ConfidentialityImpactEnum { s, ok := i.(string) if !ok { return nil } return NoteVulnerabilityCvssV3ConfidentialityImpactEnumRef(s) } // flattenNoteVulnerabilityCvssV3IntegrityImpactEnumMap flattens the contents of NoteVulnerabilityCvssV3IntegrityImpactEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3IntegrityImpactEnumMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityCvssV3IntegrityImpactEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityCvssV3IntegrityImpactEnum{} } if len(a) == 0 { return map[string]NoteVulnerabilityCvssV3IntegrityImpactEnum{} } items := make(map[string]NoteVulnerabilityCvssV3IntegrityImpactEnum) for k, item := range a { items[k] = *flattenNoteVulnerabilityCvssV3IntegrityImpactEnum(item.(interface{})) } return items } // flattenNoteVulnerabilityCvssV3IntegrityImpactEnumSlice flattens the contents of NoteVulnerabilityCvssV3IntegrityImpactEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3IntegrityImpactEnumSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityCvssV3IntegrityImpactEnum { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityCvssV3IntegrityImpactEnum{} } if len(a) == 0 { return []NoteVulnerabilityCvssV3IntegrityImpactEnum{} } items := make([]NoteVulnerabilityCvssV3IntegrityImpactEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityCvssV3IntegrityImpactEnum(item.(interface{}))) } return items } // flattenNoteVulnerabilityCvssV3IntegrityImpactEnum asserts that an interface is a string, and returns a // pointer to a *NoteVulnerabilityCvssV3IntegrityImpactEnum with the same value as that string. func flattenNoteVulnerabilityCvssV3IntegrityImpactEnum(i interface{}) *NoteVulnerabilityCvssV3IntegrityImpactEnum { s, ok := i.(string) if !ok { return nil } return NoteVulnerabilityCvssV3IntegrityImpactEnumRef(s) } // flattenNoteVulnerabilityCvssV3AvailabilityImpactEnumMap flattens the contents of NoteVulnerabilityCvssV3AvailabilityImpactEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3AvailabilityImpactEnumMap(c *Client, i interface{}, res *Note) map[string]NoteVulnerabilityCvssV3AvailabilityImpactEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteVulnerabilityCvssV3AvailabilityImpactEnum{} } if len(a) == 0 { return map[string]NoteVulnerabilityCvssV3AvailabilityImpactEnum{} } items := make(map[string]NoteVulnerabilityCvssV3AvailabilityImpactEnum) for k, item := range a { items[k] = *flattenNoteVulnerabilityCvssV3AvailabilityImpactEnum(item.(interface{})) } return items } // flattenNoteVulnerabilityCvssV3AvailabilityImpactEnumSlice flattens the contents of NoteVulnerabilityCvssV3AvailabilityImpactEnum from a JSON // response object. func flattenNoteVulnerabilityCvssV3AvailabilityImpactEnumSlice(c *Client, i interface{}, res *Note) []NoteVulnerabilityCvssV3AvailabilityImpactEnum { a, ok := i.([]interface{}) if !ok { return []NoteVulnerabilityCvssV3AvailabilityImpactEnum{} } if len(a) == 0 { return []NoteVulnerabilityCvssV3AvailabilityImpactEnum{} } items := make([]NoteVulnerabilityCvssV3AvailabilityImpactEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteVulnerabilityCvssV3AvailabilityImpactEnum(item.(interface{}))) } return items } // flattenNoteVulnerabilityCvssV3AvailabilityImpactEnum asserts that an interface is a string, and returns a // pointer to a *NoteVulnerabilityCvssV3AvailabilityImpactEnum with the same value as that string. func flattenNoteVulnerabilityCvssV3AvailabilityImpactEnum(i interface{}) *NoteVulnerabilityCvssV3AvailabilityImpactEnum { s, ok := i.(string) if !ok { return nil } return NoteVulnerabilityCvssV3AvailabilityImpactEnumRef(s) } // flattenNoteBuildSignatureKeyTypeEnumMap flattens the contents of NoteBuildSignatureKeyTypeEnum from a JSON // response object. func flattenNoteBuildSignatureKeyTypeEnumMap(c *Client, i interface{}, res *Note) map[string]NoteBuildSignatureKeyTypeEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteBuildSignatureKeyTypeEnum{} } if len(a) == 0 { return map[string]NoteBuildSignatureKeyTypeEnum{} } items := make(map[string]NoteBuildSignatureKeyTypeEnum) for k, item := range a { items[k] = *flattenNoteBuildSignatureKeyTypeEnum(item.(interface{})) } return items } // flattenNoteBuildSignatureKeyTypeEnumSlice flattens the contents of NoteBuildSignatureKeyTypeEnum from a JSON // response object. func flattenNoteBuildSignatureKeyTypeEnumSlice(c *Client, i interface{}, res *Note) []NoteBuildSignatureKeyTypeEnum { a, ok := i.([]interface{}) if !ok { return []NoteBuildSignatureKeyTypeEnum{} } if len(a) == 0 { return []NoteBuildSignatureKeyTypeEnum{} } items := make([]NoteBuildSignatureKeyTypeEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteBuildSignatureKeyTypeEnum(item.(interface{}))) } return items } // flattenNoteBuildSignatureKeyTypeEnum asserts that an interface is a string, and returns a // pointer to a *NoteBuildSignatureKeyTypeEnum with the same value as that string. func flattenNoteBuildSignatureKeyTypeEnum(i interface{}) *NoteBuildSignatureKeyTypeEnum { s, ok := i.(string) if !ok { return nil } return NoteBuildSignatureKeyTypeEnumRef(s) } // flattenNotePackageDistributionArchitectureEnumMap flattens the contents of NotePackageDistributionArchitectureEnum from a JSON // response object. func flattenNotePackageDistributionArchitectureEnumMap(c *Client, i interface{}, res *Note) map[string]NotePackageDistributionArchitectureEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NotePackageDistributionArchitectureEnum{} } if len(a) == 0 { return map[string]NotePackageDistributionArchitectureEnum{} } items := make(map[string]NotePackageDistributionArchitectureEnum) for k, item := range a { items[k] = *flattenNotePackageDistributionArchitectureEnum(item.(interface{})) } return items } // flattenNotePackageDistributionArchitectureEnumSlice flattens the contents of NotePackageDistributionArchitectureEnum from a JSON // response object. func flattenNotePackageDistributionArchitectureEnumSlice(c *Client, i interface{}, res *Note) []NotePackageDistributionArchitectureEnum { a, ok := i.([]interface{}) if !ok { return []NotePackageDistributionArchitectureEnum{} } if len(a) == 0 { return []NotePackageDistributionArchitectureEnum{} } items := make([]NotePackageDistributionArchitectureEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNotePackageDistributionArchitectureEnum(item.(interface{}))) } return items } // flattenNotePackageDistributionArchitectureEnum asserts that an interface is a string, and returns a // pointer to a *NotePackageDistributionArchitectureEnum with the same value as that string. func flattenNotePackageDistributionArchitectureEnum(i interface{}) *NotePackageDistributionArchitectureEnum { s, ok := i.(string) if !ok { return nil } return NotePackageDistributionArchitectureEnumRef(s) } // flattenNotePackageDistributionLatestVersionKindEnumMap flattens the contents of NotePackageDistributionLatestVersionKindEnum from a JSON // response object. func flattenNotePackageDistributionLatestVersionKindEnumMap(c *Client, i interface{}, res *Note) map[string]NotePackageDistributionLatestVersionKindEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NotePackageDistributionLatestVersionKindEnum{} } if len(a) == 0 { return map[string]NotePackageDistributionLatestVersionKindEnum{} } items := make(map[string]NotePackageDistributionLatestVersionKindEnum) for k, item := range a { items[k] = *flattenNotePackageDistributionLatestVersionKindEnum(item.(interface{})) } return items } // flattenNotePackageDistributionLatestVersionKindEnumSlice flattens the contents of NotePackageDistributionLatestVersionKindEnum from a JSON // response object. func flattenNotePackageDistributionLatestVersionKindEnumSlice(c *Client, i interface{}, res *Note) []NotePackageDistributionLatestVersionKindEnum { a, ok := i.([]interface{}) if !ok { return []NotePackageDistributionLatestVersionKindEnum{} } if len(a) == 0 { return []NotePackageDistributionLatestVersionKindEnum{} } items := make([]NotePackageDistributionLatestVersionKindEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNotePackageDistributionLatestVersionKindEnum(item.(interface{}))) } return items } // flattenNotePackageDistributionLatestVersionKindEnum asserts that an interface is a string, and returns a // pointer to a *NotePackageDistributionLatestVersionKindEnum with the same value as that string. func flattenNotePackageDistributionLatestVersionKindEnum(i interface{}) *NotePackageDistributionLatestVersionKindEnum { s, ok := i.(string) if !ok { return nil } return NotePackageDistributionLatestVersionKindEnumRef(s) } // flattenNoteDiscoveryAnalysisKindEnumMap flattens the contents of NoteDiscoveryAnalysisKindEnum from a JSON // response object. func flattenNoteDiscoveryAnalysisKindEnumMap(c *Client, i interface{}, res *Note) map[string]NoteDiscoveryAnalysisKindEnum { a, ok := i.(map[string]interface{}) if !ok { return map[string]NoteDiscoveryAnalysisKindEnum{} } if len(a) == 0 { return map[string]NoteDiscoveryAnalysisKindEnum{} } items := make(map[string]NoteDiscoveryAnalysisKindEnum) for k, item := range a { items[k] = *flattenNoteDiscoveryAnalysisKindEnum(item.(interface{})) } return items } // flattenNoteDiscoveryAnalysisKindEnumSlice flattens the contents of NoteDiscoveryAnalysisKindEnum from a JSON // response object. func flattenNoteDiscoveryAnalysisKindEnumSlice(c *Client, i interface{}, res *Note) []NoteDiscoveryAnalysisKindEnum { a, ok := i.([]interface{}) if !ok { return []NoteDiscoveryAnalysisKindEnum{} } if len(a) == 0 { return []NoteDiscoveryAnalysisKindEnum{} } items := make([]NoteDiscoveryAnalysisKindEnum, 0, len(a)) for _, item := range a { items = append(items, *flattenNoteDiscoveryAnalysisKindEnum(item.(interface{}))) } return items } // flattenNoteDiscoveryAnalysisKindEnum asserts that an interface is a string, and returns a // pointer to a *NoteDiscoveryAnalysisKindEnum with the same value as that string. func flattenNoteDiscoveryAnalysisKindEnum(i interface{}) *NoteDiscoveryAnalysisKindEnum { s, ok := i.(string) if !ok { return nil } return NoteDiscoveryAnalysisKindEnumRef(s) } // This function returns a matcher that checks whether a serialized resource matches this resource // in its parameters (as defined by the fields in a Get, which definitionally define resource // identity). This is useful in extracting the element from a List call. func (r *Note) matcher(c *Client) func([]byte) bool { return func(b []byte) bool { cr, err := unmarshalNote(b, c, r) if err != nil { c.Config.Logger.Warning("failed to unmarshal provided resource in matcher.") return false } nr := r.urlNormalized() ncr := cr.urlNormalized() c.Config.Logger.Infof("looking for %v\nin %v", nr, ncr) if nr.Project == nil && ncr.Project == nil { c.Config.Logger.Info("Both Project fields null - considering equal.") } else if nr.Project == nil || ncr.Project == nil { c.Config.Logger.Info("Only one Project field is null - considering unequal.") return false } else if *nr.Project != *ncr.Project { return false } if nr.Name == nil && ncr.Name == nil { c.Config.Logger.Info("Both Name fields null - considering equal.") } else if nr.Name == nil || ncr.Name == nil { c.Config.Logger.Info("Only one Name field is null - considering unequal.") return false } else if *nr.Name != *ncr.Name { return false } return true } } type noteDiff struct { // The diff should include one or the other of RequiresRecreate or UpdateOp. RequiresRecreate bool UpdateOp noteApiOperation FieldName string // used for error logging } func convertFieldDiffsToNoteDiffs(config *dcl.Config, fds []*dcl.FieldDiff, opts []dcl.ApplyOption) ([]noteDiff, error) { opNamesToFieldDiffs := make(map[string][]*dcl.FieldDiff) // Map each operation name to the field diffs associated with it. for _, fd := range fds { for _, ro := range fd.ResultingOperation { if fieldDiffs, ok := opNamesToFieldDiffs[ro]; ok { fieldDiffs = append(fieldDiffs, fd) opNamesToFieldDiffs[ro] = fieldDiffs } else { config.Logger.Infof("%s required due to diff: %v", ro, fd) opNamesToFieldDiffs[ro] = []*dcl.FieldDiff{fd} } } } var diffs []noteDiff // For each operation name, create a noteDiff which contains the operation. for opName, fieldDiffs := range opNamesToFieldDiffs { // Use the first field diff's field name for logging required recreate error. diff := noteDiff{FieldName: fieldDiffs[0].FieldName} if opName == "Recreate" { diff.RequiresRecreate = true } else { apiOp, err := convertOpNameToNoteApiOperation(opName, fieldDiffs, opts...) if err != nil { return diffs, err } diff.UpdateOp = apiOp } diffs = append(diffs, diff) } return diffs, nil } func convertOpNameToNoteApiOperation(opName string, fieldDiffs []*dcl.FieldDiff, opts ...dcl.ApplyOption) (noteApiOperation, error) { switch opName { case "updateNoteUpdateNoteOperation": return &updateNoteUpdateNoteOperation{FieldDiffs: fieldDiffs}, nil default: return nil, fmt.Errorf("no such operation with name: %v", opName) } } func extractNoteFields(r *Note) error { vVulnerability := r.Vulnerability if vVulnerability == nil { // note: explicitly not the empty object. vVulnerability = &NoteVulnerability{} } if err := extractNoteVulnerabilityFields(r, vVulnerability); err != nil { return err } if !dcl.IsEmptyValueIndirect(vVulnerability) { r.Vulnerability = vVulnerability } vBuild := r.Build if vBuild == nil { // note: explicitly not the empty object. vBuild = &NoteBuild{} } if err := extractNoteBuildFields(r, vBuild); err != nil { return err } if !dcl.IsEmptyValueIndirect(vBuild) { r.Build = vBuild } vImage := r.Image if vImage == nil { // note: explicitly not the empty object. vImage = &NoteImage{} } if err := extractNoteImageFields(r, vImage); err != nil { return err } if !dcl.IsEmptyValueIndirect(vImage) { r.Image = vImage } vPackage := r.Package if vPackage == nil { // note: explicitly not the empty object. vPackage = &NotePackage{} } if err := extractNotePackageFields(r, vPackage); err != nil { return err } if !dcl.IsEmptyValueIndirect(vPackage) { r.Package = vPackage } vDiscovery := r.Discovery if vDiscovery == nil { // note: explicitly not the empty object. vDiscovery = &NoteDiscovery{} } if err := extractNoteDiscoveryFields(r, vDiscovery); err != nil { return err } if !dcl.IsEmptyValueIndirect(vDiscovery) { r.Discovery = vDiscovery } vDeployment := r.Deployment if vDeployment == nil { // note: explicitly not the empty object. vDeployment = &NoteDeployment{} } if err := extractNoteDeploymentFields(r, vDeployment); err != nil { return err } if !dcl.IsEmptyValueIndirect(vDeployment) { r.Deployment = vDeployment } vAttestation := r.Attestation if vAttestation == nil { // note: explicitly not the empty object. vAttestation = &NoteAttestation{} } if err := extractNoteAttestationFields(r, vAttestation); err != nil { return err } if !dcl.IsEmptyValueIndirect(vAttestation) { r.Attestation = vAttestation } return nil } func extractNoteRelatedUrlFields(r *Note, o *NoteRelatedUrl) error { return nil } func extractNoteVulnerabilityFields(r *Note, o *NoteVulnerability) error { vCvssV3 := o.CvssV3 if vCvssV3 == nil { // note: explicitly not the empty object. vCvssV3 = &NoteVulnerabilityCvssV3{} } if err := extractNoteVulnerabilityCvssV3Fields(r, vCvssV3); err != nil { return err } if !dcl.IsEmptyValueIndirect(vCvssV3) { o.CvssV3 = vCvssV3 } return nil } func extractNoteVulnerabilityDetailsFields(r *Note, o *NoteVulnerabilityDetails) error { vAffectedVersionStart := o.AffectedVersionStart if vAffectedVersionStart == nil { // note: explicitly not the empty object. vAffectedVersionStart = &NoteVulnerabilityDetailsAffectedVersionStart{} } if err := extractNoteVulnerabilityDetailsAffectedVersionStartFields(r, vAffectedVersionStart); err != nil { return err } if !dcl.IsEmptyValueIndirect(vAffectedVersionStart) { o.AffectedVersionStart = vAffectedVersionStart } vAffectedVersionEnd := o.AffectedVersionEnd if vAffectedVersionEnd == nil { // note: explicitly not the empty object. vAffectedVersionEnd = &NoteVulnerabilityDetailsAffectedVersionEnd{} } if err := extractNoteVulnerabilityDetailsAffectedVersionEndFields(r, vAffectedVersionEnd); err != nil { return err } if !dcl.IsEmptyValueIndirect(vAffectedVersionEnd) { o.AffectedVersionEnd = vAffectedVersionEnd } vFixedVersion := o.FixedVersion if vFixedVersion == nil { // note: explicitly not the empty object. vFixedVersion = &NoteVulnerabilityDetailsFixedVersion{} } if err := extractNoteVulnerabilityDetailsFixedVersionFields(r, vFixedVersion); err != nil { return err } if !dcl.IsEmptyValueIndirect(vFixedVersion) { o.FixedVersion = vFixedVersion } return nil } func extractNoteVulnerabilityDetailsAffectedVersionStartFields(r *Note, o *NoteVulnerabilityDetailsAffectedVersionStart) error { return nil } func extractNoteVulnerabilityDetailsAffectedVersionEndFields(r *Note, o *NoteVulnerabilityDetailsAffectedVersionEnd) error { return nil } func extractNoteVulnerabilityDetailsFixedVersionFields(r *Note, o *NoteVulnerabilityDetailsFixedVersion) error { return nil } func extractNoteVulnerabilityCvssV3Fields(r *Note, o *NoteVulnerabilityCvssV3) error { return nil } func extractNoteVulnerabilityWindowsDetailsFields(r *Note, o *NoteVulnerabilityWindowsDetails) error { return nil } func extractNoteVulnerabilityWindowsDetailsFixingKbsFields(r *Note, o *NoteVulnerabilityWindowsDetailsFixingKbs) error { return nil } func extractNoteBuildFields(r *Note, o *NoteBuild) error { vSignature := o.Signature if vSignature == nil { // note: explicitly not the empty object. vSignature = &NoteBuildSignature{} } if err := extractNoteBuildSignatureFields(r, vSignature); err != nil { return err } if !dcl.IsEmptyValueIndirect(vSignature) { o.Signature = vSignature } return nil } func extractNoteBuildSignatureFields(r *Note, o *NoteBuildSignature) error { return nil } func extractNoteImageFields(r *Note, o *NoteImage) error { vFingerprint := o.Fingerprint if vFingerprint == nil { // note: explicitly not the empty object. vFingerprint = &NoteImageFingerprint{} } if err := extractNoteImageFingerprintFields(r, vFingerprint); err != nil { return err } if !dcl.IsEmptyValueIndirect(vFingerprint) { o.Fingerprint = vFingerprint } return nil } func extractNoteImageFingerprintFields(r *Note, o *NoteImageFingerprint) error { return nil } func extractNotePackageFields(r *Note, o *NotePackage) error { return nil } func extractNotePackageDistributionFields(r *Note, o *NotePackageDistribution) error { vLatestVersion := o.LatestVersion if vLatestVersion == nil { // note: explicitly not the empty object. vLatestVersion = &NotePackageDistributionLatestVersion{} } if err := extractNotePackageDistributionLatestVersionFields(r, vLatestVersion); err != nil { return err } if !dcl.IsEmptyValueIndirect(vLatestVersion) { o.LatestVersion = vLatestVersion } return nil } func extractNotePackageDistributionLatestVersionFields(r *Note, o *NotePackageDistributionLatestVersion) error { return nil } func extractNoteDiscoveryFields(r *Note, o *NoteDiscovery) error { return nil } func extractNoteDeploymentFields(r *Note, o *NoteDeployment) error { return nil } func extractNoteAttestationFields(r *Note, o *NoteAttestation) error { vHint := o.Hint if vHint == nil { // note: explicitly not the empty object. vHint = &NoteAttestationHint{} } if err := extractNoteAttestationHintFields(r, vHint); err != nil { return err } if !dcl.IsEmptyValueIndirect(vHint) { o.Hint = vHint } return nil } func extractNoteAttestationHintFields(r *Note, o *NoteAttestationHint) error { return nil } func postReadExtractNoteFields(r *Note) error { vVulnerability := r.Vulnerability if vVulnerability == nil { // note: explicitly not the empty object. vVulnerability = &NoteVulnerability{} } if err := postReadExtractNoteVulnerabilityFields(r, vVulnerability); err != nil { return err } if !dcl.IsEmptyValueIndirect(vVulnerability) { r.Vulnerability = vVulnerability } vBuild := r.Build if vBuild == nil { // note: explicitly not the empty object. vBuild = &NoteBuild{} } if err := postReadExtractNoteBuildFields(r, vBuild); err != nil { return err } if !dcl.IsEmptyValueIndirect(vBuild) { r.Build = vBuild } vImage := r.Image if vImage == nil { // note: explicitly not the empty object. vImage = &NoteImage{} } if err := postReadExtractNoteImageFields(r, vImage); err != nil { return err } if !dcl.IsEmptyValueIndirect(vImage) { r.Image = vImage } vPackage := r.Package if vPackage == nil { // note: explicitly not the empty object. vPackage = &NotePackage{} } if err := postReadExtractNotePackageFields(r, vPackage); err != nil { return err } if !dcl.IsEmptyValueIndirect(vPackage) { r.Package = vPackage } vDiscovery := r.Discovery if vDiscovery == nil { // note: explicitly not the empty object. vDiscovery = &NoteDiscovery{} } if err := postReadExtractNoteDiscoveryFields(r, vDiscovery); err != nil { return err } if !dcl.IsEmptyValueIndirect(vDiscovery) { r.Discovery = vDiscovery } vDeployment := r.Deployment if vDeployment == nil { // note: explicitly not the empty object. vDeployment = &NoteDeployment{} } if err := postReadExtractNoteDeploymentFields(r, vDeployment); err != nil { return err } if !dcl.IsEmptyValueIndirect(vDeployment) { r.Deployment = vDeployment } vAttestation := r.Attestation if vAttestation == nil { // note: explicitly not the empty object. vAttestation = &NoteAttestation{} } if err := postReadExtractNoteAttestationFields(r, vAttestation); err != nil { return err } if !dcl.IsEmptyValueIndirect(vAttestation) { r.Attestation = vAttestation } return nil } func postReadExtractNoteRelatedUrlFields(r *Note, o *NoteRelatedUrl) error { return nil } func postReadExtractNoteVulnerabilityFields(r *Note, o *NoteVulnerability) error { vCvssV3 := o.CvssV3 if vCvssV3 == nil { // note: explicitly not the empty object. vCvssV3 = &NoteVulnerabilityCvssV3{} } if err := extractNoteVulnerabilityCvssV3Fields(r, vCvssV3); err != nil { return err } if !dcl.IsEmptyValueIndirect(vCvssV3) { o.CvssV3 = vCvssV3 } return nil } func postReadExtractNoteVulnerabilityDetailsFields(r *Note, o *NoteVulnerabilityDetails) error { vAffectedVersionStart := o.AffectedVersionStart if vAffectedVersionStart == nil { // note: explicitly not the empty object. vAffectedVersionStart = &NoteVulnerabilityDetailsAffectedVersionStart{} } if err := extractNoteVulnerabilityDetailsAffectedVersionStartFields(r, vAffectedVersionStart); err != nil { return err } if !dcl.IsEmptyValueIndirect(vAffectedVersionStart) { o.AffectedVersionStart = vAffectedVersionStart } vAffectedVersionEnd := o.AffectedVersionEnd if vAffectedVersionEnd == nil { // note: explicitly not the empty object. vAffectedVersionEnd = &NoteVulnerabilityDetailsAffectedVersionEnd{} } if err := extractNoteVulnerabilityDetailsAffectedVersionEndFields(r, vAffectedVersionEnd); err != nil { return err } if !dcl.IsEmptyValueIndirect(vAffectedVersionEnd) { o.AffectedVersionEnd = vAffectedVersionEnd } vFixedVersion := o.FixedVersion if vFixedVersion == nil { // note: explicitly not the empty object. vFixedVersion = &NoteVulnerabilityDetailsFixedVersion{} } if err := extractNoteVulnerabilityDetailsFixedVersionFields(r, vFixedVersion); err != nil { return err } if !dcl.IsEmptyValueIndirect(vFixedVersion) { o.FixedVersion = vFixedVersion } return nil } func postReadExtractNoteVulnerabilityDetailsAffectedVersionStartFields(r *Note, o *NoteVulnerabilityDetailsAffectedVersionStart) error { return nil } func postReadExtractNoteVulnerabilityDetailsAffectedVersionEndFields(r *Note, o *NoteVulnerabilityDetailsAffectedVersionEnd) error { return nil } func postReadExtractNoteVulnerabilityDetailsFixedVersionFields(r *Note, o *NoteVulnerabilityDetailsFixedVersion) error { return nil } func postReadExtractNoteVulnerabilityCvssV3Fields(r *Note, o *NoteVulnerabilityCvssV3) error { return nil } func postReadExtractNoteVulnerabilityWindowsDetailsFields(r *Note, o *NoteVulnerabilityWindowsDetails) error { return nil } func postReadExtractNoteVulnerabilityWindowsDetailsFixingKbsFields(r *Note, o *NoteVulnerabilityWindowsDetailsFixingKbs) error { return nil } func postReadExtractNoteBuildFields(r *Note, o *NoteBuild) error { vSignature := o.Signature if vSignature == nil { // note: explicitly not the empty object. vSignature = &NoteBuildSignature{} } if err := extractNoteBuildSignatureFields(r, vSignature); err != nil { return err } if !dcl.IsEmptyValueIndirect(vSignature) { o.Signature = vSignature } return nil } func postReadExtractNoteBuildSignatureFields(r *Note, o *NoteBuildSignature) error { return nil } func postReadExtractNoteImageFields(r *Note, o *NoteImage) error { vFingerprint := o.Fingerprint if vFingerprint == nil { // note: explicitly not the empty object. vFingerprint = &NoteImageFingerprint{} } if err := extractNoteImageFingerprintFields(r, vFingerprint); err != nil { return err } if !dcl.IsEmptyValueIndirect(vFingerprint) { o.Fingerprint = vFingerprint } return nil } func postReadExtractNoteImageFingerprintFields(r *Note, o *NoteImageFingerprint) error { return nil } func postReadExtractNotePackageFields(r *Note, o *NotePackage) error { return nil } func postReadExtractNotePackageDistributionFields(r *Note, o *NotePackageDistribution) error { vLatestVersion := o.LatestVersion if vLatestVersion == nil { // note: explicitly not the empty object. vLatestVersion = &NotePackageDistributionLatestVersion{} } if err := extractNotePackageDistributionLatestVersionFields(r, vLatestVersion); err != nil { return err } if !dcl.IsEmptyValueIndirect(vLatestVersion) { o.LatestVersion = vLatestVersion } return nil } func postReadExtractNotePackageDistributionLatestVersionFields(r *Note, o *NotePackageDistributionLatestVersion) error { return nil } func postReadExtractNoteDiscoveryFields(r *Note, o *NoteDiscovery) error { return nil } func postReadExtractNoteDeploymentFields(r *Note, o *NoteDeployment) error { return nil } func postReadExtractNoteAttestationFields(r *Note, o *NoteAttestation) error { vHint := o.Hint if vHint == nil { // note: explicitly not the empty object. vHint = &NoteAttestationHint{} } if err := extractNoteAttestationHintFields(r, vHint); err != nil { return err } if !dcl.IsEmptyValueIndirect(vHint) { o.Hint = vHint } return nil } func postReadExtractNoteAttestationHintFields(r *Note, o *NoteAttestationHint) error { return nil }
// Copyright 2020 The Reed Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. package vmcommon func BuildP2PKHScript(publicKeyHash []byte) []byte { var script []byte script = append(script, byte(OpDup)) script = append(script, byte(OpHash256)) script = append(script, byte(OpPushData32)) script = append(script, publicKeyHash...) script = append(script, byte(OpEqualVerify)) script = append(script, byte(OpCheckSig)) return script }
/* Description People are different. Some secretly read magazines full of interesting girls' pictures, others create an A-bomb in their cellar, others like using Windows, and some like difficult mathematical games. Latest marketing research shows, that this market segment was so far underestimated and that there is lack of such games. This kind of game was thus included into the KOKODáKH. The rules follow: Each player chooses two numbers Ai and Bi and writes them on a slip of paper. Others cannot see the numbers. In a given moment all players show their numbers to the others. The goal is to determine the sum of all expressions AiBi from all players including oneself and determine the remainder after division by a given number M. The winner is the one who first determines the correct result. According to the players' experience it is possible to increase the difficulty by choosing higher numbers. You should write a program that calculates the result and is able to find out who won the game. Input The input consists of Z assignments. The number of them is given by the single positive integer Z appearing on the first line of input. Then the assignements follow. Each assignement begins with line containing an integer M (1 <= M <= 45000). The sum will be divided by this number. Next line contains number of players H (1 <= H <= 45000). Next exactly H lines follow. On each line, there are exactly two numbers Ai and Bi separated by space. Both numbers cannot be equal zero at the same time. Output For each assingnement there is the only one line of output. On this line, there is a number, the result of expression (A1^B1 + A2^B2 + ... + AH^BH) mod M. Sample Input 3 16 4 2 3 3 4 4 5 5 6 36123 1 2374859 3029382 17 1 3 18132 Sample Output 2 13195 13 Source CTU Open 1999 */ package main import "math/big" func main() { assert(raise([]int64{2, 3, 4, 5}, []int64{3, 4, 5, 6}, 16) == 2) assert(raise([]int64{2374859}, []int64{3029382}, 36123) == 13195) assert(raise([]int64{3}, []int64{18132}, 17) == 13) } func assert(x bool) { if !x { panic("assertion failed") } } func raise(a, b []int64, m int64) int64 { d := big.NewInt(m) r := new(big.Int) for i := range a { x := big.NewInt(a[i]) p := big.NewInt(b[i]) x.Exp(x, p, d) r.Add(r, x) r.Mod(r, d) } return r.Int64() }
/* Copyright 2021 CodeNotary, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package immuc import ( "context" "errors" "fmt" "strconv" "strings" "github.com/codenotary/immudb/pkg/api/schema" "github.com/codenotary/immudb/pkg/client" ) var ( errZeroTxID = errors.New("tx id cannot be 0 (should be bigger than 0)") ) func (i *immuc) GetTxByID(args []string) (string, error) { id, err := strconv.ParseUint(args[0], 10, 64) if err != nil { return "", fmt.Errorf(" \"%v\" is not a valid id number", args[0]) } if id == 0 { return "", errZeroTxID } ctx := context.Background() tx, err := i.Execute(func(immuClient client.ImmuClient) (interface{}, error) { return immuClient.TxByID(ctx, id) }) if err != nil { if strings.Contains(err.Error(), "NotFound") { return fmt.Sprintf("no item exists in id:%v", id), nil } rpcerrors := strings.SplitAfter(err.Error(), "=") if len(rpcerrors) > 1 { return rpcerrors[len(rpcerrors)-1], nil } return "", err } return PrintTx(tx.(*schema.Tx), false), nil } func (i *immuc) VerifiedGetTxByID(args []string) (string, error) { id, err := strconv.ParseUint(args[0], 10, 64) if err != nil { return "", fmt.Errorf(" \"%v\" is not a valid id number", args[0]) } if id == 0 { return "", errZeroTxID } ctx := context.Background() tx, err := i.Execute(func(immuClient client.ImmuClient) (interface{}, error) { return immuClient.VerifiedTxByID(ctx, id) }) if err != nil { if strings.Contains(err.Error(), "NotFound") { return fmt.Sprintf("no item exists in id:%v", id), nil } rpcerrors := strings.SplitAfter(err.Error(), "=") if len(rpcerrors) > 1 { return rpcerrors[len(rpcerrors)-1], nil } return "", err } return PrintTx(tx.(*schema.Tx), true), nil } func (i *immuc) Get(args []string) (string, error) { key := []byte(args[0]) ctx := context.Background() response, err := i.Execute(func(immuClient client.ImmuClient) (interface{}, error) { return immuClient.Get(ctx, key) }) if err != nil { if strings.Contains(err.Error(), "NotFound") { return fmt.Sprintf("key not found: %v ", string(key)), nil } rpcerrors := strings.SplitAfter(err.Error(), "=") if len(rpcerrors) > 1 { return rpcerrors[len(rpcerrors)-1], nil } return "", err } entry := response.(*schema.Entry) return PrintKV(entry.Key, entry.Value, entry.Tx, false, i.valueOnly), nil } func (i *immuc) VerifiedGet(args []string) (string, error) { key := []byte(args[0]) ctx := context.Background() response, err := i.Execute(func(immuClient client.ImmuClient) (interface{}, error) { return immuClient.VerifiedGet(ctx, key) }) if err != nil { if strings.Contains(err.Error(), "NotFound") { return fmt.Sprintf("key not found: %v ", string(key)), nil } rpcerrors := strings.SplitAfter(err.Error(), "=") if len(rpcerrors) > 1 { return rpcerrors[len(rpcerrors)-1], nil } return "", err } entry := response.(*schema.Entry) return PrintKV(entry.Key, entry.Value, entry.Tx, true, i.valueOnly), nil }
package server import ( "context" "fmt" "time" "github.com/danielkvist/botio/proto" "github.com/golang/protobuf/ptypes/empty" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // AddCommand tries to add a received command to the Server's database. It returns a non-nil error // if something went wrong or if the context was cancelled. func (s *server) AddCommand(ctx context.Context, cmd *proto.BotCommand) (*empty.Empty, error) { start := time.Now() select { case <-ctx.Done(): return &empty.Empty{}, status.Error(codes.Canceled, ctx.Err().Error()) default: if err := s.db.Add(cmd); err != nil { s.logError( "db", "Add", err.Error(), fmt.Sprintf("add BotCommand %q: %q failed", cmd.GetCmd().GetCommand(), cmd.GetResp().GetResponse()), ) return &empty.Empty{}, status.Error(codes.Internal, "error while adding command") } } s.logInfo( "server", "AddCommand", fmt.Sprintf("BotCommand %q: %q added successfully", cmd.GetCmd().GetCommand(), cmd.GetResp().GetResponse()), time.Since(start), ) return &empty.Empty{}, nil } // GetCommand tries to get the specified command from the Server's database. It returns a non-nil error // if something went wrong or if the context was cancelled. func (s *server) GetCommand(ctx context.Context, cmd *proto.Command) (*proto.BotCommand, error) { var c *proto.BotCommand var err error start := time.Now() select { case <-ctx.Done(): return &proto.BotCommand{}, status.Error(codes.Canceled, ctx.Err().Error()) default: if ok := s.inCache(cmd); !ok { c, err = s.db.Get(cmd) if err != nil { s.logError( "db", "Get", err.Error(), fmt.Sprintf("get BotCommand %q failed", cmd.GetCommand()), ) return &proto.BotCommand{}, status.Error(codes.Internal, "error while getting command") } if err := s.cache.Add(c); err != nil { s.logError( "cache", "Add", err.Error(), fmt.Sprintf("add BotCommand %q: %q failed", c.GetCmd().GetCommand(), c.GetResp().GetResponse()), ) } } else { c, err = s.cache.Get(cmd) if err != nil { s.logError( "cache", "Get", err.Error(), fmt.Sprintf("get BotCommand %q failed", cmd.GetCommand()), ) return &proto.BotCommand{}, status.Error(codes.Internal, "error while getting command") } } } s.logInfo( "server", "GetCommand", fmt.Sprintf("BotCommand %q gotten successfully", c.GetCmd().GetCommand()), time.Since(start), ) return c, nil } // ListCommands tries to get all the commands from the Server's database. It returns a non-nil error // if something went wrong or if the context was cancelled. func (s *server) ListCommands(ctx context.Context, _ *empty.Empty) (*proto.BotCommands, error) { var commands *proto.BotCommands var err error start := time.Now() select { case <-ctx.Done(): return &proto.BotCommands{}, status.Error(codes.Canceled, ctx.Err().Error()) default: commands, err = s.db.GetAll() if err != nil { s.logError( "db", "GetAll", err.Error(), "get BotCommands failed", ) return &proto.BotCommands{}, status.Error(codes.Internal, "error while getting commands") } } s.logInfo( "server", "ListCommands", "BotCommands gotten successfully", time.Since(start), ) return commands, nil } // UpdateCommand tries to update the specified command to the Server's database. It returns a non-nil error // if something went wrong or if the context was cancelled. func (s *server) UpdateCommand(ctx context.Context, cmd *proto.BotCommand) (*empty.Empty, error) { start := time.Now() select { case <-ctx.Done(): return &empty.Empty{}, status.Error(codes.Canceled, ctx.Err().Error()) default: if ok := s.inCache(cmd.GetCmd()); ok { if err := s.cache.Remove(cmd.GetCmd()); err != nil { s.logError( "cache", "Remove", err.Error(), fmt.Sprintf("remove BotCommand %q failed", cmd.GetCmd().GetCommand()), ) } } if err := s.db.Update(cmd); err != nil { s.logError( "db", "Update", err.Error(), fmt.Sprintf("update BotCommand %q: %q failed", cmd.GetCmd().GetCommand(), cmd.GetResp().GetResponse()), ) return &empty.Empty{}, status.Error(codes.Internal, "error while updating command") } } s.logInfo( "server", "UpdateCommand", fmt.Sprintf("BotCommand %q: %q updated successfully", cmd.GetCmd().GetCommand(), cmd.GetResp().GetResponse()), time.Since(start), ) return &empty.Empty{}, nil } // DeleteCommand tries to remove the specified command from the Server's database. It returns a non-nil error // if something went wrong or if the context was cancelled. func (s *server) DeleteCommand(ctx context.Context, cmd *proto.Command) (*empty.Empty, error) { start := time.Now() select { case <-ctx.Done(): return &empty.Empty{}, status.Error(codes.Canceled, ctx.Err().Error()) default: if ok := s.inCache(cmd); ok { if err := s.cache.Remove(cmd); err != nil { s.logError( "cache", "Remove", err.Error(), fmt.Sprintf("remove BotCommand %q failed", cmd.GetCommand()), ) } } if err := s.db.Remove(cmd); err != nil { s.logError( "db", "Remove", err.Error(), fmt.Sprintf("remove BotCommand %q failed", cmd.GetCommand()), ) return &empty.Empty{}, status.Error(codes.Internal, "error while removing command") } } s.logInfo( "server", "DeleteCommand", fmt.Sprintf("BotCommand %q removed successfully", cmd.GetCommand()), time.Since(start), ) return &empty.Empty{}, nil } func (s *server) inCache(cmd *proto.Command) bool { if _, err := s.cache.Get(cmd); err != nil { return false } return true }
package settings import ( "flag" envcfg "github.com/wealthworks/envflagset" ) var ( EmailDomain string EmailCheck bool SMTP struct { Enabled bool Host string Port int SenderName string SenderEmail string SenderPassword string } LDAP struct { Hosts string Base string BindDN string Password string Filter string } Session struct { Name string Domain string Secret string MaxAge int // cookie maxAge } HttpListen string BaseURL string PwdSecret string Backend struct{ DSN string } SentryDSN string Root string FS string CommonFormat string Debug bool UserLifetime int // secends, user online time TokenGen struct { // JWT config Method string // disuse Key string } CacheSize int CacheLifetime uint WechatCorpID string WechatContactSecret string WechatPortalSecret string WechatPortalAgentID int ) var ( fs *flag.FlagSet ) func init() { fs = envcfg.New(NAME, buildVersion) fs.StringVar(&LDAP.Hosts, "ldap-hosts", "ldap://localhost:389", "ldap hostname") fs.StringVar(&LDAP.Base, "ldap-base", "", "ldap base") fs.StringVar(&LDAP.BindDN, "ldap-bind-dn", "", "ldap bind dn") fs.StringVar(&LDAP.Password, "ldap-pass", "", "ldap bind password") fs.StringVar(&LDAP.Filter, "ldap-user-filter", "(objectclass=inetOrgPerson)", "ldap search filter") fs.StringVar(&HttpListen, "http-listen", "localhost:5000", "bind address and port") fs.StringVar(&BaseURL, "baseurl", "http://localhost:5000", "url base for self host") fs.StringVar(&PwdSecret, "password-secret", "very secret", "the secret of password reset") fs.StringVar(&Session.Name, "sess-name", "staff_sess", "session name") fs.StringVar(&Session.Domain, "sess-domain", "", "session domain") fs.StringVar(&Session.Secret, "sess-secret", "very-secret", "session secret") fs.IntVar(&Session.MaxAge, "sess-maxage", 86400*7, "session cookie life time (in seconds)") fs.IntVar(&UserLifetime, "user-life", 2500, "user online life time (in seconds)") fs.StringVar(&Backend.DSN, "backend-dsn", "postgres://staffio@localhost/staffio?sslmode=disable", "database dsn string for backend") fs.StringVar(&SentryDSN, "sentry-dsn", "", "SENTRY_DSN") fs.StringVar(&Root, "root", "./", "app root directory") fs.StringVar(&FS, "fs", "bind", "file system [bind | local]") fs.StringVar(&CommonFormat, "cn-fmt", "{sn}{gn}", "common name format, sn=surname, gn=given name") fs.StringVar(&TokenGen.Key, "tokengen-key", "", "HMAC key for token generater") fs.StringVar(&EmailDomain, "email-domain", "example.net", "default email domain") fs.BoolVar(&EmailCheck, "email-check", false, "check email unseen") fs.BoolVar(&SMTP.Enabled, "smtp-enabled", true, "enable smtp") fs.StringVar(&SMTP.Host, "smtp-host", "", "") fs.IntVar(&SMTP.Port, "smtp-port", 465, "") fs.StringVar(&SMTP.SenderName, "smtp-sender-name", "Notification", "") fs.StringVar(&SMTP.SenderEmail, "smtp-sender-email", "", "") fs.StringVar(&SMTP.SenderPassword, "smtp-sender-password", "", "") fs.BoolVar(&Debug, "debug", false, "app in debug mode") fs.IntVar(&CacheSize, "cache-size", 512*1024, "cache size") fs.UintVar(&CacheLifetime, "cache-life", 60, "cache lifetime in seconds") fs.StringVar(&WechatCorpID, "wechat-corpid", "", "wechat corpId") fs.StringVar(&WechatContactSecret, "wechat-contact-secret", "", "wechat secret of contacts") fs.StringVar(&WechatPortalSecret, "wechat-portal-secret", "", "wechat secret of portal(oauth)") fs.IntVar(&WechatPortalAgentID, "wechat-portal-agentid", 0, "wechat agentId of portal(oauth)") } func Parse() { envcfg.Parse() }
/* Copyright 2021 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package api import ( "encoding/json" "errors" "os" "path/filepath" "strings" "time" "sigs.k8s.io/yaml" "github.com/oam-dev/kubevela/apis/core.oam.dev/common" "github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1" "github.com/oam-dev/kubevela/pkg/builtin" cmdutil "github.com/oam-dev/kubevela/pkg/utils/util" "github.com/oam-dev/kubevela/references/appfile/template" ) // error msg used in Appfile var ( ErrImageNotDefined = errors.New("image not defined") ) // DefaultAppfilePath defines the default file path that used by `vela up` command const ( DefaultJSONAppfilePath = "./vela.json" DefaultAppfilePath = "./vela.yaml" DefaultUnknowFormatAppfilePath = "./Appfile" ) // AppFile defines the spec of KubeVela Appfile type AppFile struct { Name string `json:"name"` CreateTime time.Time `json:"createTime,omitempty"` UpdateTime time.Time `json:"updateTime,omitempty"` Services map[string]Service `json:"services"` Secrets map[string]string `json:"secrets,omitempty"` initialized bool } // NewAppFile init an empty AppFile struct func NewAppFile() *AppFile { return &AppFile{ Services: make(map[string]Service), Secrets: make(map[string]string), } } // Load will load appfile from default path func Load() (*AppFile, error) { if _, err := os.Stat(DefaultAppfilePath); err == nil { return LoadFromFile(DefaultAppfilePath) } if _, err := os.Stat(DefaultJSONAppfilePath); err == nil { return LoadFromFile(DefaultJSONAppfilePath) } return LoadFromFile(DefaultUnknowFormatAppfilePath) } // JSONToYaml will convert JSON format appfile to yaml and load the AppFile struct func JSONToYaml(data []byte, appFile *AppFile) (*AppFile, error) { j, e := yaml.JSONToYAML(data) if e != nil { return nil, e } err := yaml.Unmarshal(j, appFile) if err != nil { return nil, err } return appFile, nil } // LoadFromFile will read the file and load the AppFile struct func LoadFromFile(filename string) (*AppFile, error) { b, err := os.ReadFile(filepath.Clean(filename)) if err != nil { return nil, err } return LoadFromBytes(b) } // LoadFromBytes will load AppFile from bytes func LoadFromBytes(b []byte) (*AppFile, error) { af := NewAppFile() var err error if json.Valid(b) { af, err = JSONToYaml(b, af) } else { err = yaml.Unmarshal(b, af) } if err != nil { return nil, err } return af, nil } // ExecuteAppfileTasks will execute built-in tasks(such as image builder, etc.) and generate locally executed application func (app *AppFile) ExecuteAppfileTasks(io cmdutil.IOStreams) error { if app.initialized { return nil } for name, svc := range app.Services { newSvc, err := builtin.RunBuildInTasks(svc, io) if err != nil { return err } app.Services[name] = newSvc } app.initialized = true return nil } // ConvertToApplication renders Appfile into Application, Scopes and other K8s Resources. func (app *AppFile) ConvertToApplication(namespace string, io cmdutil.IOStreams, tm template.Manager, silence bool) (*v1beta1.Application, error) { if err := app.ExecuteAppfileTasks(io); err != nil { if strings.Contains(err.Error(), "'image' : not found") { return nil, ErrImageNotDefined } return nil, err } // auxiliaryObjects currently include OAM Scope Custom Resources and ConfigMaps servApp := new(v1beta1.Application) servApp.SetNamespace(namespace) servApp.SetName(app.Name) servApp.Spec.Components = []common.ApplicationComponent{} if !silence { io.Infof("parsing application components") } for serviceName, svc := range app.GetServices() { comp, err := svc.RenderServiceToApplicationComponent(tm, serviceName) if err != nil { return nil, err } servApp.Spec.Components = append(servApp.Spec.Components, comp) } servApp.SetGroupVersionKind(v1beta1.SchemeGroupVersion.WithKind("Application")) return servApp, nil }
package deletespot import ( "net/http" "github.com/doniacld/outdoorsight/internal/endpointdef" "github.com/doniacld/outdoorsight/internal/endpoints" ) // DeleteSpotMeta holds the endpoint information var DeleteSpotMeta = endpointdef.New( "DeleteSpotDetails", "/spots/{"+endpoints.ParamSpotName+"}", http.MethodDelete, http.StatusNoContent, ) // DeleteSpotRequest is the request structure type DeleteSpotRequest struct { SpotName string `json:"spotName"` } // DeleteSpotResponse holds the response structure type DeleteSpotResponse struct {}
package geo import ( "fmt" "log" "math" "math/rand" "sync" "test/broker" "test/proto" "time" ) type XY struct { X int Y int } type GeoService struct { name string locationMu sync.RWMutex location XY activeWorkers int stop chan chan struct{} broker broker.Broker producer <-chan broker.Message } func NewGeoService() *GeoService { service := &GeoService{ randomGeoName(), sync.RWMutex{}, randomXY(), 0, make(chan chan struct{}), nil, nil, } service.PrintInfo() return service } func (gs *GeoService) PrintInfo() { gs.locationMu.RLock() defer gs.locationMu.RUnlock() log.Printf("Geo service %s location is %v", gs.name, gs.location) } func (gs *GeoService) GetName() string { return gs.name } func (gs *GeoService) UpdateLocation() { gs.locationMu.Lock() gs.location = randomXY() gs.locationMu.Unlock() gs.PrintInfo() } func (gs *GeoService) Distance(point XY) float64 { gs.locationMu.RLock() defer gs.locationMu.RUnlock() return math.Sqrt(math.Pow(float64(gs.location.X-point.X), 2) - math.Pow(float64(gs.location.Y-point.Y), 2)) } func (gs *GeoService) Start(b broker.Broker, producer <-chan broker.Message) { gs.broker = b gs.producer = producer gs.activeWorkers = 2 go gs.pinger() go gs.receiver() } func (gs *GeoService) pinger() { t := time.NewTicker(broker.ServicePingInterval) for { select { case <-t.C: if gs.broker != nil { _, err := gs.broker.Send(broker.Message{MessageType: broker.TypePing, From: gs.GetName()}) if err != nil { log.Println(err) } } case ch := <-gs.stop: close(ch) return } } } func (gs *GeoService) receiver() { for { select { case msg := <-gs.producer: _, ok := msg.Payload.(proto.UpdateLocationRequest) if ok { gs.UpdateLocation() continue } req, ok := msg.Payload.(proto.GetDistanceRequest) if ok { dist := gs.Distance(XY{req.PointX, req.PointY}) err := gs.broker.Response(broker.Message{ MessageType: broker.TypeDirectResponse, From: gs.GetName(), To: msg.From, Payload: proto.GetDistanceResponse{Distance: &dist}, ID: msg.ID, }) if err != nil { log.Println(err) } } case ch := <-gs.stop: close(ch) return } } } func (gs *GeoService) Stop() { for i := 0; i < gs.activeWorkers; i++ { ch := make(chan struct{}) gs.stop <- ch <-ch } } func randomGeoName() string { return fmt.Sprintf("geo-%d", rand.Intn(900)) } func randomXY() XY { return XY{ rand.Intn(2001) - 1000, rand.Intn(2001) - 1000, } }
package states import ( "context" "encoding/json" "errors" "fmt" "time" derrors "github.com/direktiv/direktiv/pkg/flow/errors" "github.com/direktiv/direktiv/pkg/model" "github.com/direktiv/direktiv/pkg/util" "github.com/google/uuid" ) func init() { RegisterState(model.StateTypeGetter, Getter) } type getterLogic struct { *model.GetterState Instance } func Getter(instance Instance, state model.State) (Logic, error) { getter, ok := state.(*model.GetterState) if !ok { return nil, derrors.NewInternalError(errors.New("bad state object")) } sl := new(getterLogic) sl.Instance = instance sl.GetterState = getter return sl, nil } func (logic *getterLogic) Run(ctx context.Context, wakedata []byte) (*Transition, error) { err := scheduleOnce(logic, wakedata) if err != nil { return nil, err } var vars []VariableSelector var ptrs []string m := make(map[string]interface{}) for idx, v := range logic.Variables { key := "" var selector VariableSelector x, err := jqOne(logic.GetInstanceData(), v.Key) if err != nil { return nil, err } if x != nil { if str, ok := x.(string); ok { key = str } } if key == "" { return nil, derrors.NewCatchableError(ErrCodeJQNotString, "failed to evaluate key as a string for variable at index [%v]", idx) } if ok := util.MatchesVarRegex(key); !ok { return nil, derrors.NewCatchableError(ErrCodeInvalidVariableKey, "variable key must match regex: %s (got: %s)", util.RegexPattern, key) } as := key if v.As != "" { as = v.As } selector.Key = key selector.Scope = v.Scope switch v.Scope { case "": selector.Scope = util.VarScopeInstance fallthrough case util.VarScopeInstance: fallthrough case util.VarScopeThread: fallthrough case util.VarScopeWorkflow: fallthrough case util.VarScopeFileSystem: fallthrough case util.VarScopeNamespace: vars = append(vars, selector) ptrs = append(ptrs, as) case util.VarScopeSystem: value, err := valueForSystem(key, logic.Instance) if err != nil { return nil, derrors.NewInternalError(err) } m[as] = value default: return nil, derrors.NewInternalError(errors.New("invalid scope")) } } results, err := logic.GetVariables(ctx, vars) if err != nil { return nil, err } for idx := range results { result := results[idx] as := ptrs[idx] var x interface{} x = nil if len(result.Data) != 0 { err = json.Unmarshal(result.Data, &x) if err != nil { x = result.Data } } m[as] = x } err = logic.StoreData("var", m) if err != nil { return nil, derrors.NewInternalError(err) } return &Transition{ Transform: logic.Transform, NextState: logic.Transition, }, nil } func valueForSystem(key string, instance Instance) (interface{}, error) { var ret interface{} switch key { case "instance": ret = instance.GetInstanceID() case "uuid": ret = uuid.New().String() case "epoch": ret = time.Now().UTC().Unix() default: return nil, fmt.Errorf("unknown system key %s", key) } return ret, nil }
package zecutil import ( "errors" "fmt" "github.com/btcsuite/btcd/txscript" "github.com/btcsuite/btcutil" ) func PayToAddrScript(addr btcutil.Address) ([]byte, error) { var script []byte var err error script, err = txscript.PayToAddrScript(addr) if err == nil { return script, nil } const nilAddrErrStr = "unable to generate payment script for nil address" switch addr := addr.(type) { case *ZecAddressPubKeyHash: if addr == nil { return nil, errors.New(nilAddrErrStr) } return payToPubKeyHashScript(addr.ScriptAddress()) case *ZecAddressScriptHash: if addr == nil { return nil, errors.New(nilAddrErrStr) } return payToScriptHashScript(addr.ScriptAddress()) } return nil, fmt.Errorf("unable to generate payment script for unsupported address type %T", addr) } // payToPubKeyHashScript creates a new script to pay a transaction // output to a 20-byte pubkey hash. It is expected that the input is a valid // hash. func payToPubKeyHashScript(pubKeyHash []byte) ([]byte, error) { return txscript.NewScriptBuilder().AddOp(txscript.OP_DUP).AddOp(txscript.OP_HASH160). AddData(pubKeyHash).AddOp(txscript.OP_EQUALVERIFY).AddOp(txscript.OP_CHECKSIG). Script() } // payToScriptHashScript creates a new script to pay a transaction output to a // script hash. It is expected that the input is a valid hash. func payToScriptHashScript(scriptHash []byte) ([]byte, error) { return txscript.NewScriptBuilder().AddOp(txscript.OP_HASH160).AddData(scriptHash). AddOp(txscript.OP_EQUAL).Script() }
/** * blog_service * @author liuzhen * @Description * @version 1.0.0 2021/1/29 17:46 */ package service import ( "backend/src/module" "backend/src/repository" "backend/src/utils" "reflect" ) // 保存博客 func AddBlog(param module.Blog) ResponseBody { if utils.IsBlank(param.Title) { return NewCustomErrorResponseBody("标题不能为空") } if utils.IsBlank(param.Summary) { return NewCustomErrorResponseBody("摘要不能为空") } if param.CategoryId < 1 || utils.IsBlank(param.TagIds) { return NewCustomErrorResponseBody("参数不完整") } repository.Create(&param) return NewSimpleSuccessResponseBody() } // 获取博客 func GetBlogById(blogId uint) ResponseBody { var blog module.Blog repository.FindById(&blog, blogId) if reflect.DeepEqual(blog, module.Blog{}) { return NewParamErrorResponseBody() } return NewSuccessResponseBody(blog) } // 修改博客 func UpdateBlog(param module.Blog) ResponseBody { var blog module.Blog repository.FindById(&blog, param.Id) if reflect.DeepEqual(blog, module.Blog{}) { return NewParamErrorResponseBody() } if !utils.IsBlank(param.Title) { blog.Title = param.Title } if !utils.IsBlank(param.Summary) { blog.Summary = param.Summary } if !utils.IsBlank(param.Contend) { blog.Contend = param.Contend } if param.CategoryId > 0 { blog.CategoryId = param.CategoryId } if !utils.IsBlank(param.TagIds) { blog.TagIds = param.TagIds } if !utils.IsBlank(param.ImageUrl) { blog.ImageUrl = param.ImageUrl } repository.Save(&blog) return NewSimpleSuccessResponseBody() } // 删除博客 func DeleteBlog(blogId uint) ResponseBody { var blog module.Blog repository.FindById(&blog, blogId) if reflect.DeepEqual(blog, module.Blog{}) { return NewParamErrorResponseBody() } repository.Delete(&blog) return NewSimpleSuccessResponseBody() }
package leetcode import ( "reflect" "testing" ) func TestSortArrayByParity(t *testing.T) { if !reflect.DeepEqual(sortArrayByParity([]int{3, 1, 2, 4}), []int{4, 2, 1, 3}) { t.Fatal() } }
package conv import ( "testing" "github.com/stretchr/testify/assert" ) func TestDecode(t *testing.T) { data := []struct { in string expect string }{ {expect: "あいうえお", in: "杮杮杮柿柿柿杮杮杮柿柿柿柿柿柿杮杮柿柿柿柿柿杮柿杮杮杮柿柿柿杮杮杮柿柿柿柿柿柿杮杮柿柿柿柿杮柿柿杮杮杮柿柿柿杮杮杮柿柿柿柿柿柿杮杮柿柿柿柿杮杮柿杮杮杮柿柿柿杮杮杮柿柿柿柿柿柿杮杮柿柿柿杮柿柿柿杮杮杮柿柿柿杮杮杮柿柿柿柿柿柿杮杮柿柿柿杮柿杮柿"}, {expect: "abc", in: "柿杮杮柿柿柿柿杮柿杮杮柿柿柿杮柿柿杮杮柿柿柿杮杮"}, } as := assert.New(t) for _, v := range data { res, err := Decode(v.in) as.NoError(err) as.Equal(v.expect, res) } } func TestDecodeError(t *testing.T) { data := []string{ "000", "柿", "こけら", "柿杮杮柿柿柿柿", } for _, v := range data { _, err := Decode(v) assert.Error(t, err) } }
package impl import ( "fmt" "github.com/techone577/blogging-go/model" "xorm.io/xorm" ) type postStorage struct { db *xorm.Engine } func NewPostStorage(db *xorm.Engine) *postStorage { return &postStorage{db: db} } func (p *postStorage) QueryByPostID(id string) (*model.PostInfo, error) { var post model.PostInfo _, err := p.db.Table(model.PostTableName()).Where("post_id = ? and del_flag = ? and release_flag = ?", id, 0, 1).Get(&post) return &post, err } func (p *postStorage) QueryPreviousPost(pkId int) (*model.PostInfo, error) { var post model.PostInfo innerSql := fmt.Sprintf("select min(id) from %s where id > %d", model.PostTableName(), pkId) sql := fmt.Sprintf("select * from %s where del_flag = 0 and release_flag = 1 and id in (%s)", model.PostTableName(), innerSql) _, err := p.db.SQL(sql).Get(&post) return &post, err } func (p *postStorage) QueryNextPost(pkId int) (*model.PostInfo, error) { var post model.PostInfo innerSql := fmt.Sprintf("select max(id) from %s where id < %d", model.PostTableName(), pkId) sql := fmt.Sprintf("select * from %s where del_flag = 0 and release_flag = 1 and id in (%s)", model.PostTableName(), innerSql) _, err := p.db.SQL(sql).Get(&post) return &post, err } func (p *postStorage) QueryByPaging(page, pageSize, releaseFlag, delFlag int) ([]model.PostInfo, int64, error) { var posts []model.PostInfo s := p.db.Table(model.PostTableName()).Where("release_flag = ? and del_flag = ?", releaseFlag, delFlag) total, err := s.Count() if err != nil { return nil, 0, err } err = s.Limit(pageSize, (page-1)*pageSize).Desc("id").Find(&posts) return posts, total, err } func (p *postStorage) QueryPassageByPassageId(id string) (model.PassageInfo, error) { var pa model.PassageInfo _, err := p.db.Table(model.PassageTableName()).Where("del_flag = ? and passage_id = ?", 0, id).Get(&pa) return pa, err }
package rest import ( "github.com/jinmukeji/jiujiantang-services/pkg/rest" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/device/v1" "github.com/kataras/iris/v12" ) // Device 设备 type Device struct { ClientID string `json:"client_id"` SN string `json:"sn"` Model string `json:"model"` Mac string `json:"mac"` } // UserUsedDevice 用户使用的设备 func (h *webHandler) UserUsedDevice(ctx iris.Context) { userID, err := ctx.Params().GetInt("user_id") if err != nil { writeError(ctx, wrapError(ErrInvalidValue, "", err), false) return } req := new(proto.UserGetUsedDevicesRequest) req.UserId = int32(userID) resp, errUserGetUsedDevices := h.rpcDeviceSvc.UserGetUsedDevices(newRPCContext(ctx), req) if errUserGetUsedDevices != nil { writeRpcInternalError(ctx, errUserGetUsedDevices, false) return } devices := make([]Device, len(resp.Devices)) for idx, device := range resp.Devices { devices[idx] = Device{ ClientID: device.ClientId, SN: device.Sn, Model: device.Model, Mac: device.Mac, } } rest.WriteOkJSON(ctx, devices) }
// output table with results from Github search package main import ( "fmt" "io/ioutil" "log" "os" "os/exec" "sort" "strconv" "time" "github.com/fatih/color" "github.com/vlad-belogrudov/gopl/pkg/github" ) func readText() (string, error) { f, err := ioutil.TempFile("", "issue") if err != nil { return "", err } filename := f.Name() if err = f.Close(); err != nil { return "", err } defer os.Remove(filename) editor := os.Getenv("EDITOR") fmt.Printf("opening %s with %s\n", filename, editor) if len(editor) == 0 { return "", fmt.Errorf("EDITOR is not set") } cmd := exec.Command(editor, filename) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout if err := cmd.Run(); err != nil { return "", err } fmt.Println("reading") text, err := ioutil.ReadFile(filename) if err != nil { return "", err } return string(text), nil } func search(terms []string) error { result, err := github.SearchIssues(terms) if err != nil { return err } fmt.Printf("%d titles:\n", result.TotalCount) sort.Slice(result.Items, func(i, j int) bool { return result.Items[i].CreatedAt.After(result.Items[j].CreatedAt) }) this_month := true this_year := true color.Green("#### less than month ago ####") for _, item := range result.Items { if this_month { if time.Since(item.CreatedAt).Hours() > 24*30 { this_month = false color.Yellow("#### less than year ago ####") } } if this_year { if time.Since(item.CreatedAt).Hours() > 24*365 { this_year = false color.Red("#### more than year ago ####") } } fmt.Printf("#%-5d %s %s %20.20s %.55q\n", item.Number, item.CreatedAt.Format("2006-01-02"), item.State, item.User.Login, item.Title) } return nil } func getToken() (string, error) { const userPassVar = "GHUSERPASS" login, ok := os.LookupEnv(userPassVar) if !ok { return "", fmt.Errorf("%s is not set", userPassVar) } return login, nil } func create(repo, title, text string) error { token, err := getToken() if err != nil { return err } if len(text) == 0 { if text, err = readText(); err != nil { return err } } issue, err := github.CreateIssue(token, repo, title, text) if err != nil { return err } fmt.Printf("Created issue %d at %s (state: %s)\n", issue.Number, issue.CreatedAt, issue.State) return nil } func show(repo string, number int) error { issue, err := github.GetIssue(repo, number) if err != nil { return err } fmt.Printf("Number: %d\n", issue.Number) fmt.Printf("Title: %s\n", issue.Title) fmt.Printf("Created at: %s\n", issue.CreatedAt) fmt.Printf("Created by: %s\n", issue.User.Login) fmt.Printf("State: %s\n", issue.State) fmt.Printf("URL: %s\n", issue.HTMLURL) fmt.Printf("Text: %s\n", issue.Body) for _, comment := range issue.Comments { fmt.Println("### Comment:") fmt.Printf("\tCreated at: %s\n", comment.CreatedAt) fmt.Printf("\tCreated by: %s\n", comment.User.Login) fmt.Printf("\tText: %s\n", comment.Body) } return nil } func close(repo string, number int) error { token, err := getToken() if err != nil { return err } if err := github.CloseIssue(token, repo, number); err != nil { return err } fmt.Printf("Closed issue %d at %s\n", number, repo) return nil } func update(repo string, number int, title string) error { token, err := getToken() if err != nil { return err } if err := github.UpdateIssue(token, repo, number, title); err != nil { return err } fmt.Printf("Updated issue %d at %s\n", number, repo) return nil } func comment(repo string, number int, text string) error { token, err := getToken() if err != nil { return err } if len(text) == 0 { if text, err = readText(); err != nil { return err } } if err := github.CreateComment(token, repo, number, text); err != nil { return err } fmt.Printf("Commented issue %d at %s\n", number, repo) return nil } func help() { log.Fatalln("Usage: issues <create|update|comment|close|search|show> [optinal terms]") } func main() { if len(os.Args) < 2 { help() } var err error switch os.Args[1] { case "search": err = search(os.Args[2:]) case "create": if len(os.Args) != 5 { log.Fatalln("need additional arguments - full repo name, title, text.\n", "Text can be empty string to open external editor.") } err = create(os.Args[2], os.Args[3], os.Args[4]) case "close": if len(os.Args) != 4 { log.Fatalln("need additional arguments - full repo name and issue number.") } var number int number, err = strconv.Atoi(os.Args[3]) if err != nil { break } err = close(os.Args[2], number) case "show": if len(os.Args) != 4 { log.Fatalln("need additional arguments - full repo name and issue number.") } var number int number, err = strconv.Atoi(os.Args[3]) if err != nil { break } err = show(os.Args[2], number) case "update": if len(os.Args) != 5 { log.Fatalln("need additional arguments - full repo name, issue number and new title.") } var number int number, err = strconv.Atoi(os.Args[3]) if err != nil { break } err = update(os.Args[2], number, os.Args[4]) case "comment": if len(os.Args) != 5 { log.Fatalln("need additional arguments - full repo name, issue number and comment.\n", "Comment can be empty string to open external editor.") } var number int number, err = strconv.Atoi(os.Args[3]) if err != nil { break } err = comment(os.Args[2], number, os.Args[4]) default: help() } if err != nil { log.Fatalln(err) } }
package model // 角色,资源中间表 type RoleResource struct { Id int RoleId int ResourceId int } // Assign permission to role // Id: roleId // Enable: grant permission // Disable: revoke permission type RolePrivilege struct { Id int `json:"id" bind:"required,min=1"` Enable []int `json:"enable" binding:"required"` Disable []int `json:"disable" binding:"required"` } type ResourceInfo struct { Id int `json:"id"` Name string `json:"name"` App string `json:"app"` // AppId string `json:"appid"` } // Get belong to role's permission // Result include route and interface type ResBelongRole struct { Menu []ResourceInfo `json:"menus"` Inter []ResourceInfo `json:"interfaces"` }
package token type TokenType string type Token struct { Type TokenType Literal string } const ( ILLEGAL TokenType = "ILLEGAL" EOF TokenType = "EOF" // Identifiers and literals. IDENT TokenType = "IDENT" INT TokenType = "INT" // Operators. ASSIGN TokenType = "=" PLUS TokenType = "+" // Delimiters. COMMA TokenType = "," SEMICOLON TokenType = ";" LPAREN TokenType = "(" RPAREN TokenType = ")" LBRACE TokenType = "{" RBRACE TokenType = "}" // Keywords. FUNCTION TokenType = "FUNCTION" LET TokenType = "LET" ) var keywords = map[string]TokenType{ "fn": FUNCTION, "let": LET, } func LookupIdent(ident string) TokenType { if tok, ok := keywords[ident]; ok { return tok } return IDENT }
package pxc import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" api "github.com/Percona-Lab/percona-xtradb-cluster-operator/pkg/apis/pxc/v1alpha1" "github.com/Percona-Lab/percona-xtradb-cluster-operator/pkg/pxc/app/statefulset" ) func (h *PXC) StatefulSet(sfs api.StatefulApp, podSpec *api.PodSpec, cr *api.PerconaXtraDBCluster) (*appsv1.StatefulSet, error) { var fsgroup *int64 if h.serverVersion.Platform == api.PlatformKubernetes { var tp int64 = 1001 fsgroup = &tp } pod := corev1.PodSpec{ SecurityContext: &corev1.PodSecurityContext{ SupplementalGroups: []int64{99}, FSGroup: fsgroup, }, } var err error appC := sfs.AppContainer(podSpec, cr.Spec.SecretsName) appC.Resources, err = sfs.Resources(podSpec.Resources) if err != nil { return nil, err } pod.Containers = append(pod.Containers, appC) if cr.Spec.PMM.Enabled { pod.Containers = append(pod.Containers, sfs.PMMContainer(cr.Spec.PMM, cr.Spec.SecretsName)) } switch sfs.(type) { case *statefulset.Node: pod.Volumes = []corev1.Volume{ getConfigVolumes(), } } ls := sfs.Lables() obj := sfs.StatefulSet() pvcs, err := sfs.PVCs(podSpec.VolumeSpec) if err != nil { return nil, err } obj.Spec = appsv1.StatefulSetSpec{ Replicas: &podSpec.Size, Selector: &metav1.LabelSelector{ MatchLabels: ls, }, ServiceName: ls["component"], Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: ls, }, Spec: pod, }, VolumeClaimTemplates: pvcs, } addOwnerRefToObject(obj, asOwner(cr)) return obj, nil } func getConfigVolumes() corev1.Volume { vol1 := corev1.Volume{ Name: "config-volume", } vol1.ConfigMap = &corev1.ConfigMapVolumeSource{} vol1.ConfigMap.Name = appName t := true vol1.ConfigMap.Optional = &t return vol1 }
package utils import ( "fmt" "gin-vue-admin/global" "github.com/gwpp/alidayu-go" "github.com/gwpp/alidayu-go/request" ) func SendShotMessage(phone, code string) error { client := alidayu.NewTopClient(global.GVA_CONFIG.Dayu.Appkey, global.GVA_CONFIG.Dayu.SecretKey) req := request.NewAlibabaAliqinFcSmsNumSendRequest() req.Extend = "normal" req.SmsFreeSignName = global.GVA_CONFIG.Dayu.SignName req.RecNum = phone req.SmsTemplateCode = "SMS_4395149" req.SmsParam = fmt.Sprintf(`{"code":"%s", "product":"人才盘点工具"}`, code) response, err := client.Execute(req) global.GVA_LOG.Info(response) if err != nil { global.GVA_LOG.Error("验证码发送失败!", err) return err } return nil }
// Copyright (c) 2019 Leonardo Faoro. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package cloudKMS makes it easy to interact with GCP's CloudKMS service. package cloudKMS import ( "context" "crypto/ecdsa" "crypto/sha256" "crypto/x509" "encoding/asn1" "encoding/base64" "encoding/pem" "fmt" "math/big" "net/http" "github.com/pkg/errors" "golang.org/x/oauth2/google" "google.golang.org/api/cloudkms/v1" "github.com/lfaoro/pkg/logger" "github.com/lfaoro/pkg/security" ) // Assumes you have the "GOOGLE_APPLICATION_CREDENTIALS" environment // variable setup in your environment with access to the Cloud KMS service. // // Authentication documentation: https://cloud.google.com/docs/authentication/getting-started // Go client library: https://cloud.google.com/kms/docs/reference/libraries#client-libraries-install-go // // Remember to create a KeyRing and CryptoKey. // Documentation: https://cloud.google.com/kms/docs/creating-keys // // Cloud KMS pricing: https://cloud.google.com/kms/pricing // type cloudKMS struct { ProjectID string LocationID string KeyRingID string CryptoKeyID string SigningKeyID string authedClient *http.Client service *cloudkms.Service } // validate interface conformity. var _ security.Cryptor = cloudKMS{} var log = logger.New("[crypter] ") // New makes a crypto.Cryptor. func New(projectID, locationID, keyRingID, cryptoKeyID string) security.Cryptor { ctx := context.Background() authedClient, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope) if err != nil { log.Fatal(err) } kmsService, err := cloudkms.New(authedClient) if err != nil { log.Fatal(err) } kms := cloudKMS{ ProjectID: projectID, LocationID: locationID, KeyRingID: keyRingID, CryptoKeyID: cryptoKeyID, SigningKeyID: cryptoKeyID + "_sign", authedClient: authedClient, service: kmsService, } return kms } // Encrypt attempts to successfully encrypt the plainText. func (kms cloudKMS) Encrypt(plainText []byte) ([]byte, error) { parentName := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s", kms.ProjectID, kms.LocationID, kms.KeyRingID, kms.CryptoKeyID) req := &cloudkms.EncryptRequest{ Plaintext: base64.StdEncoding.EncodeToString(plainText), } res, err := kms.service.Projects.Locations.KeyRings.CryptoKeys.Encrypt(parentName, req).Do() if err != nil { return []byte{}, err } return []byte(res.Ciphertext), nil } // Decrypt attempts to successfully decrypt the cipherText. func (kms cloudKMS) Decrypt(cipherText []byte) ([]byte, error) { parentName := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s", kms.ProjectID, kms.LocationID, kms.KeyRingID, kms.CryptoKeyID) req := &cloudkms.DecryptRequest{ Ciphertext: base64.StdEncoding.EncodeToString(cipherText), } res, err := kms.service.Projects.Locations.KeyRings.CryptoKeys.Decrypt(parentName, req).Do() if err != nil { return nil, err } return base64.StdEncoding.DecodeString(res.Plaintext) } // Sign will sign a plaintext message using an asymmetric private key. // example keyName: "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1" // // DON't USE: not production ready func (kms cloudKMS) Sign(message []byte) ([]byte, error) { var err error kmsService, err := cloudkms.New(kms.authedClient) if err != nil { return nil, err } // Find the digest of the message. digest := sha256.New() digest.Write(message) parentName := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s", kms.ProjectID, kms.LocationID, kms.KeyRingID, kms.CryptoKeyID) // Build the signing request. req := &cloudkms.AsymmetricSignRequest{ Digest: &cloudkms.Digest{ Sha256: string(digest.Sum(nil)), }, } // Call the API. res, err := kmsService.Projects.Locations.KeyRings.CryptoKeys.CryptoKeyVersions.AsymmetricSign(parentName, req).Do() if err != nil { return nil, fmt.Errorf("asymmetric sign request failed: %+v", err) } return base64.StdEncoding.DecodeString(res.Signature) } // verifySignatureEC will verify that an 'EC_SIGN_P256_SHA256' signature is valid for a given message. // example keyName: "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1" // // DON't USE: not production ready func (kms cloudKMS) Verify(signature, message []byte) error { var err error kmsService, err := cloudkms.New(kms.authedClient) if err != nil { return err } parentName := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s", kms.ProjectID, kms.LocationID, kms.KeyRingID, kms.CryptoKeyID) // Retrieve the public key from KMS. res, err := kmsService.Projects.Locations.KeyRings.CryptoKeys.CryptoKeyVersions.GetPublicKey(parentName).Do() if err != nil { return fmt.Errorf("failed to fetch public key: %+v", err) } // Parse the key. block, _ := pem.Decode([]byte(res.Pem)) abstractKey, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return fmt.Errorf("failed to parse public key: %+v", err) } ecKey, ok := abstractKey.(*ecdsa.PublicKey) if !ok { return fmt.Errorf("key '%s' is not EC", abstractKey) } // Verify Elliptic Curve signature. var parsedSig struct{ R, S *big.Int } _, err = asn1.Unmarshal(signature, &parsedSig) if err != nil { return fmt.Errorf("failed to parse signature bytes: %+v", err) } hash := sha256.New() hash.Write(message) digest := hash.Sum(nil) if !ecdsa.Verify(ecKey, digest, parsedSig.R, parsedSig.S) { return errors.New("signature verification failed") } return nil }
package main import "testing" func TestP104(t *testing.T) { ans := 329468 v := solve() if v != ans { t.Errorf("p104: %v\tExpected: %v", v, ans) } }
package cache import ( "container/list" "time" ) type EvictType string const ( LRU EvictType = "lru" ARC = "arc" ) const ( DefaultSize = 100 ) // Cache is the interface for LRU/ARC cache. type Cache interface { // Set key-value pair with an expiration. Set(key, value interface{}, expire time.Duration) // Get value from the cache by the key. Get(key interface{}) (interface{}, bool) // GetOrLoad gets value from the cache or load by loader. GetOrLoad(key interface{}, loader LoaderFunc) (interface{}, error) // Peek returns value without updating the "recently used"-ness of the key. Peek(key interface{}) (interface{}, bool) // Del the specified key from the cache. Del(key interface{}) bool // Contain checks if a key exists in the cache. Contain(key interface{}) bool // Len returns the number of items in the cache. Len(withoutExpired ...bool) int // Keys returns a slice of the keys in the cache. Keys(withoutExpired ...bool) []interface{} // Purge clears the cache entities. Purge() } func New(evictType EvictType, opts ...Option) (c Cache) { // b := base{ size: DefaultSize, evictList: list.New(), } for _, o := range opts { o(&b) } b.items = make(map[interface{}]*list.Element, b.size+1) // switch evictType { case LRU: c = &LRUCache{ base: &b, } default: return nil } // b.loaderLock = syncLocker{ cache: c, m: make(map[interface{}]*caller), } return c }
// Copyright 2018 Kuei-chun Chen. All rights reserved. package util import ( "math/rand" "strconv" "strings" "time" "go.mongodb.org/mongo-driver/bson" ) var ( locations = []string{"US-NY", "US-GA", "US-IL", "US-TX", "US-CA", "US-WA"} ) // FavoritesSchema - type FavoritesSchema struct { ID string `json:"_id" bson:"_id"` FavoriteBook string `json:"favoriteBook" bson:"favoriteBook"` FavoriteCity string `json:"favoriteCity" bson:"favoriteCity"` FavoriteMovie string `json:"favoriteMovie" bson:"favoriteMovie"` FavoriteMusic string `json:"favoriteMusic" bson:"favoriteMusic"` FavoriteSport string `json:"favoriteSport" bson:"favoriteSport"` } // FavoritesDoc - type FavoritesDoc struct { Sports []string Music []string Cities []string Books []string Movies []string } // GetDemoDoc returns a demo document func GetDemoDoc() bson.M { var n = len(Favorites.Sports) favoriteSports := []string{Favorites.Sports[rand.Intn(n)], Favorites.Sports[rand.Intn(n)], Favorites.Sports[rand.Intn(n)]} favoriteSports = unique(append(favoriteSports, Favorites.Sports[0:3]...), 3) n = len(Favorites.Music) favoriteMusic := []string{Favorites.Music[rand.Intn(n)], Favorites.Music[rand.Intn(n)], Favorites.Music[rand.Intn(n)]} favoriteMusic = unique(append(favoriteMusic, Favorites.Music[0:3]...), 3) n = len(Favorites.Cities) favoriteCities := []string{Favorites.Cities[rand.Intn(n)], Favorites.Cities[rand.Intn(n)], Favorites.Cities[rand.Intn(n)]} favoriteCities = unique(append(favoriteCities, Favorites.Cities[0:3]...), 3) n = len(Favorites.Books) x := rand.Intn(n) favoriteBooks := []string{Favorites.Books[x], Favorites.Books[rand.Intn(n)], Favorites.Books[rand.Intn(n)]} favoriteBooks = unique(append(favoriteBooks, Favorites.Books[0:3]...), 3) n = len(Favorites.Movies) favoriteMovies := []string{Favorites.Movies[rand.Intn(n)], Favorites.Movies[rand.Intn(n)], Favorites.Movies[rand.Intn(n)]} favoriteMovies = unique(append(favoriteMovies, Favorites.Movies[0:3]...), 3) favoritesList := []bson.M{ {"sport": favoriteSports[0], "music": favoriteMusic[0], "city": favoriteCities[0], "book": favoriteBooks[0], "movie": favoriteMovies[0]}, {"sport": favoriteSports[1], "music": favoriteMusic[1], "city": favoriteCities[1], "book": favoriteBooks[1], "movie": favoriteMovies[1]}, {"sport": favoriteSports[2], "music": favoriteMusic[2], "city": favoriteCities[2], "book": favoriteBooks[2], "movie": favoriteMovies[2]}, } favoritesKVList := []bson.M{} for i := 0; i < 3; i++ { favoritesKVList = append(favoritesKVList, bson.M{ "level": int32(i + 1), "categories": []bson.M{ {"key": "sport", "value": favoriteSports[i]}, {"key": "music", "value": favoriteMusic[i]}, {"key": "city", "value": favoriteCities[i]}, {"key": "book", "value": favoriteBooks[i]}, {"key": "movie", "value": favoriteMovies[i]}, }}) } favoritesKVSet := []bson.M{} favoritesKVSet = append(favoritesKVSet, bson.M{"key": "sport", "value": favoriteSports}) favoritesKVSet = append(favoritesKVSet, bson.M{"key": "music", "value": favoriteMusic}) favoritesKVSet = append(favoritesKVSet, bson.M{"key": "city", "value": favoriteCities}) favoritesKVSet = append(favoritesKVSet, bson.M{"key": "book", "value": favoriteBooks}) favoritesKVSet = append(favoritesKVSet, bson.M{"key": "movie", "value": favoriteMovies}) email := GetEmailAddress() s := strings.Split(strings.Split(email, "@")[0], ".") doc := bson.M{ "location": locations[rand.Intn(len(locations))], "_search": strconv.FormatInt(rand.Int63(), 16), "email": email, "firstName": s[0], "lastName": s[2], "favoritesAll": bson.M{ "sports": favoriteSports, "musics": favoriteMusic, "cities": favoriteCities, "books": favoriteBooks, "movies": favoriteMovies, }, "favoritesList": favoritesList, "favoritesKVList": favoritesKVList, "favoritesKVSet": favoritesKVSet, "favoriteBookId": 1100 + x, "favoriteBook": favoriteBooks[0], "favoriteBooks": favoriteBooks, "favoriteCity": favoriteCities[0], "favoriteCities": favoriteCities, "favoriteMovie": favoriteMovies[0], "favoriteMovies": favoriteMovies, "favoriteMusic": favoriteMusic[0], "favoriteMusics": favoriteMusic, "favoriteSport": favoriteSports[0], "favoriteSports": favoriteSports, "number": rand.Intn(1000), "numbers": []int{rand.Intn(1000), rand.Intn(1000), rand.Intn(1000), rand.Intn(1000), rand.Intn(1000)}, "ts": time.Now(), } return doc } func unique(s []string, n int) []string { arr := make(map[string]bool, len(s)) us := make([]string, len(arr)) for _, elem := range s { if len(elem) != 0 { if !arr[elem] { us = append(us, elem) arr[elem] = true } } } return us[:n] } // Favorites constance var Favorites = FavoritesDoc{ Sports: []string{"Baseball", "Boxing", "Dodgeball", "Figure skating", "Football", "Horse racing", "Mountaineering", "Skateboard", "Ski", "Soccer"}, Music: []string{"Blues", "Classical", "Country", "Easy Listening", "Electronic", "Hip Pop", "Jazz", "Opera", "Soul", "Rock"}, Cities: []string{"Atlanta", "Bangkok", "Beijing", "London", "Paris", "Singapore", "New York", "Istanbul", "Dubai", "Taipei"}, Books: []string{"Journey to the West", "The Lord of the Rings", "In Search of Lost Time", "Don Quixote", "Ulysses", "The Great Gatsby", "Moby Dick", "Hamlet", "War and Peace", "The Odyssey"}, Movies: []string{"The Godfather", "The Shawshank Redemption", "Schindler's List", "Raging Bull", "Casablanca", "Citizen Kane", "Gone with the Wind", "The Wizard of Oz", "One Flew Over the Cuckoo's Nest", "Lawrence of Arabia"}, }
package nominetuk var NominetUkObjects = []string{ "urn:ietf:params:xml:ns:domain-1.0", "urn:ietf:params:xml:ns:contact-1.0", "urn:ietf:params:xml:ns:host-1.0"} var NominetUkExtensions = []string{ "http://www.nominet.org.uk/epp/xml/contact-nom-ext-1.0", "http://www.nominet.org.uk/epp/xml/domain-nom-ext-1.2", "http://www.nominet.org.uk/epp/xml/nom-data-quality-1.1", "http://www.nominet.org.uk/epp/xml/nom-direct-rights-1.0", "http://www.nominet.org.uk/epp/xml/std-contact-id-1.0", "http://www.nominet.org.uk/epp/xml/std-fork-1.0", "http://www.nominet.org.uk/epp/xml/std-handshake-1.0", "http://www.nominet.org.uk/epp/xml/std-list-1.0", "http://www.nominet.org.uk/epp/xml/std-locks-1.0", "http://www.nominet.org.uk/epp/xml/std-notifications-1.2", "http://www.nominet.org.uk/epp/xml/std-release-1.0", "http://www.nominet.org.uk/epp/xml/std-unrenew-1.0", "http://www.nominet.org.uk/epp/xml/std-warning-1.1"}
package main import ( "bytes" "fmt" "github.com/stretchr/testify/assert" "io" "net/http" "net/http/httptest" "strings" "testing" ) func TestInvalidJsonReturnsUnmarshalError(t *testing.T) { t.Parallel() assert := assert.New(t) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _, err := fmt.Fprintf(w, `{"invalid}}`) assert.Nil(err) })) defer ts.Close() host := Host{URL: ts.URL} _, err := host.RequestHostStatus() assert.True(strings.Contains(err.Error(), ErrUnmarshal.Error())) } func TestGettingHostStatusSetsRequestsCount(t *testing.T) { t.Parallel() assert := assert.New(t) tests := []struct { expRequestsCount uint }{ {12345}, {56789}, } for _, tt := range tests { t.Run(string(tt.expRequestsCount), func(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _, err := fmt.Fprintf(w, `{"requests_count": %d}`, tt.expRequestsCount) assert.Nil(err) })) defer ts.Close() host := Host{URL: ts.URL} status, err := host.RequestHostStatus() assert.Nil(err) assert.Equal(tt.expRequestsCount, status.RequestsCount) }) } } func TestGettingHostStatusSetsApplication(t *testing.T) { t.Parallel() assert := assert.New(t) tests := []struct { expApplication string }{ {"app1"}, {"app2"}, } for _, tt := range tests { t.Run(tt.expApplication, func(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _, err := fmt.Fprintf(w, `{"application": "%s"}`, tt.expApplication) assert.Nil(err) })) defer ts.Close() host := Host{URL: ts.URL} status, err := host.RequestHostStatus() assert.Nil(err) assert.Equal(tt.expApplication, status.Application) }) } } func TestGettingHostStatusSetsVersion(t *testing.T) { t.Parallel() assert := assert.New(t) tests := []struct { expVersion string }{ {"ver1.2"}, {"v5"}, } for _, tt := range tests { t.Run(tt.expVersion, func(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _, err := fmt.Fprintf(w, `{"Version": "%s"}`, tt.expVersion) assert.Nil(err) })) defer ts.Close() host := Host{URL: ts.URL} status, err := host.RequestHostStatus() assert.Nil(err) assert.Equal(tt.expVersion, status.Version) }) } } func TestGettingHostStatusSetsErrorCount(t *testing.T) { t.Parallel() assert := assert.New(t) tests := []struct { expErrorCount uint }{ {12345}, {56789}, } for _, tt := range tests { t.Run(string(tt.expErrorCount), func(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _, err := fmt.Fprintf(w, `{"error_count": %d}`, tt.expErrorCount) assert.Nil(err) })) defer ts.Close() host := Host{URL: ts.URL} status, err := host.RequestHostStatus() assert.Nil(err) assert.Equal(tt.expErrorCount, status.ErrorCount) }) } } func TestGettingHostStatusSetsSuccessCount(t *testing.T) { t.Parallel() assert := assert.New(t) tests := []struct { expSuccessCount uint }{ {12345}, {56789}, } for _, tt := range tests { t.Run(string(tt.expSuccessCount), func(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") _, err := fmt.Fprintf(w, `{"success_count": %d}`, tt.expSuccessCount) assert.Nil(err) })) defer ts.Close() host := Host{URL: ts.URL} status, err := host.RequestHostStatus() assert.Nil(err) assert.Equal(tt.expSuccessCount, status.SuccessCount) }) } } type TestReadCloser struct{ data []byte } func (rc TestReadCloser) Read(p []byte) (int, error) { r := bytes.NewReader(rc.data) n, err := r.Read(p) if err != nil { return 0, err } return n, io.EOF } func (rc TestReadCloser) Close() error { return nil } func TestGettingHostsTrimsWhiteSpace(t *testing.T) { t.Parallel() assert := assert.New(t) tests := []struct { name string hosts string expSlice []string }{ {"leading_space", " host1\n host2", []string{"host1", "host2"}}, {"trailing_space", "host1 \nhost2 ", []string{"host1", "host2"}}, {"extra_space", " host1 \n host2 ", []string{"host1", "host2"}}, {"empty_lines", " host1 \n \n \n host2 \n ", []string{"host1", "host2"}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { b := []byte(tt.hosts) testRC := TestReadCloser{data: b} hosts, err := ReadAllHosts(testRC) assert.Nil(err) assert.Equal(tt.expSlice, hosts) }) } } func TestHostURLCreation(t *testing.T) { t.Parallel() assert := assert.New(t) tests := []struct { rootURL string host string expURL string }{ {"http://some.root.com", "host1", "http://some.root.com/host1/status"}, {"http://root.com", "host2", "http://root.com/host2/status"}, {"http://root.com:80", "host3", "http://root.com:80/host3/status"}, } for _, tt := range tests { t.Run(tt.host, func(t *testing.T) { url, err := HostStatusURL(tt.rootURL, tt.host) assert.Nil(err) assert.Equal(tt.expURL, url) }) } }
package process import "fmt" // 用户的管理操作 // 比如对在线用户的管理 type ClientMgr struct { onlineUsers map[int]*UserProcessor } var ( clientMgr *ClientMgr ) // 完成初始化, 切片不初始化,不能使用 func init() { clientMgr = &ClientMgr{ onlineUsers: make(map[int]*UserProcessor, 1024), } } // 一个 ClientProcessor 实例,就对应一个登录的用户 func (p *ClientMgr) AddClient(userId int, client *UserProcessor) { p.onlineUsers[userId] = client } func (p *ClientMgr) GetClient(userId int) (client *UserProcessor, err error) { client, ok := p.onlineUsers[userId] if !ok { err = fmt.Errorf("id= %d 的用户,不存在..", userId) return } return } func (p *ClientMgr) GetAllUsers() map[int]*UserProcessor { return p.onlineUsers } // 当有一个用户离线后,就从 onlineUsers 切片中删除掉 func (p *ClientMgr) DelClient(userId int) { delete(p.onlineUsers, userId) }
package grpc import ( "context" "crypto/tls" "crypto/x509" "github.com/allabout/cloud-run-sdk/util" "google.golang.org/grpc" "google.golang.org/grpc/credentials" ) // addr 127.0.0.1:443 func NewTLSConn(ctx context.Context, addr string, opts ...grpc.DialOption) (*grpc.ClientConn, error) { systemRoots, err := x509.SystemCertPool() if err != nil { return nil, err } cred := credentials.NewTLS(&tls.Config{ RootCAs: systemRoots, }) idToken, err := util.GetIDToken(addr) if err != nil { return nil, err } opts = append([]grpc.DialOption{ grpc.WithAuthority(addr), grpc.WithTransportCredentials(cred), grpc.WithUnaryInterceptor(AuthInterceptor(idToken))}, opts..., ) return grpc.DialContext(ctx, addr, opts...) }
/* Copyright (c) 2017 GigaSpaces Technologies Ltd. All rights reserved Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Executions executions - Handle workflow executions cancel: Cancel a workflow execution [manager only]. Not Implemented. get: Retrieve execution information [manager only]. Not Implemented. list: List deployment executions [manager only]. cfy-go executions list cfy-go executions list -deployment deployment Paggination by: `-offset`: the number of resources to skip. `-size`: the max size of the result subset to receive. start: Execute a workflow [manager only]. Partially implemented, you can set params only as json string. cfy-go executions start uninstall -deployment deployment */ package main import ( "fmt" cloudify "github.com/cloudify-incubator/cloudify-rest-go-client/cloudify" utils "github.com/cloudify-incubator/cloudify-rest-go-client/cloudify/utils" "log" ) func executionsOptions(args, options []string) int { defaultError := "list/start subcommand is required" if len(args) < 3 { fmt.Println(defaultError) return 1 } switch args[2] { case "list": { operFlagSet := basicOptions("executions list") var deployment string operFlagSet.StringVar(&deployment, "deployment", "", "The unique identifier for the deployment") operFlagSet.Parse(options) params := parsePagination(operFlagSet, options) if deployment != "" { params["deployment_id"] = deployment } cl := getClient() executions, err := cl.GetExecutions(params) if err != nil { log.Printf("Cloudify error: %s\n", err.Error()) return 1 } lines := make([][]string, len(executions.Items)) for pos, execution := range executions.Items { lines[pos] = make([]string, 8) lines[pos][0] = execution.ID lines[pos][1] = execution.WorkflowID lines[pos][2] = execution.Status lines[pos][3] = execution.DeploymentID lines[pos][4] = execution.CreatedAt lines[pos][5] = execution.ErrorMessage lines[pos][6] = execution.Tenant lines[pos][7] = execution.CreatedBy } utils.PrintTable([]string{ "id", "workflow_id", "status", "deployment_id", "created_at", "error", "tenant_name", "created_by", }, lines) fmt.Printf("Showed %d+%d/%d results. Use offset/size for get more.\n", executions.Metadata.Pagination.Offset, len(executions.Items), executions.Metadata.Pagination.Total) } case "start": { operFlagSet := basicOptions("executions start <workflow id>") if len(args) < 4 { fmt.Println("Workflow Id required") return 1 } var deployment string var jsonParams string operFlagSet.StringVar(&deployment, "deployment", "", "The unique identifier for the deployment") operFlagSet.StringVar(&jsonParams, "params", "{}", "The json params string") operFlagSet.Parse(options) var exec cloudify.ExecutionPost exec.WorkflowID = args[3] exec.DeploymentID = deployment exec.SetJSONParameters(jsonParams) cl := getClient() execution, err := cl.PostExecution(exec) if err != nil { log.Printf("Cloudify error: %s\n", err.Error()) return 1 } lines := make([][]string, 1) lines[0] = make([]string, 8) lines[0][0] = execution.ID lines[0][1] = execution.WorkflowID lines[0][2] = execution.Status lines[0][3] = execution.DeploymentID lines[0][4] = execution.CreatedAt lines[0][5] = execution.ErrorMessage lines[0][6] = execution.Tenant lines[0][7] = execution.CreatedBy utils.PrintTable([]string{ "id", "workflow_id", "status", "deployment_id", "created_at", "error", "tenant_name", "created_by", }, lines) } default: { fmt.Println(defaultError) return 1 } } return 0 }
/* Package gosnowth contains an IRONdb client library written in Go. Examples can be found at github.com/circonus-labs/gosnowth/tree/master/examples */ package gosnowth
package model type ErrorDetails struct { // Specific error code Code *int32 `json:"code,omitempty"` // Error group name Category string `json:"category,omitempty"` // Detailed error message Text string `json:"text,omitempty"` // Information if the encoding could potentially succeed when retrying. RetryHint RetryHint `json:"retryHint,omitempty"` }
package main import ( "fmt" ) func variadic1(sl1 ...int) int { total := 0 for _, val := range sl1 { total += val } return total } func multiVariadic2(slice ...[][]int) int { // pass twoDimensional slice into a variadic function var total int = 0 for _, row := range slice { for i := 0; i < len(row); i++ { for j := 0; j < len(row[i]); j++ { total += row[i][j] } } } return total } func main() { fmt.Println("Enter your 3 number") sl1 := make([]int, 3) for i := 0; i < 3; i++ { fmt.Scanf("%d", &sl1[i]) } res := variadic1(sl1...) // send slice fmt.Println(res) fmt.Println("multidimentional slice ") sl2 := make([][]int, 3) for i := 0; i < 3; i++ { sl2[i] = make([]int, 2) for j := 0; j < 2; j++ { fmt.Scanf("%d", &sl2[i][j]) } } // pass twoDimensional slice into a variadic function var res2 int = multiVariadic2(sl2) fmt.Println("sum is ", res2) }
package main import ( "fmt" "github.com/hajimehoshi/ebiten/v2" "github.com/hajimehoshi/ebiten/v2/ebitenutil" "go1/utils" _ "image/png" "log" "math/rand" ) type EdgeBehaviour int type GameWorld struct { name string screenWidth int screenHeight int maxAngle int minSprites int maxSprites int angleOfRotation int bigSpriteGrowth int smallSpriteGrowth int spriteCount int showInfo bool speedFactor int rebound EdgeBehaviour } var world GameWorld const ( Rebound EdgeBehaviour = iota PassThrough ) var spriteImage *ebiten.Image type Sprite struct { spriteWidth int spriteHeight int x int y int vx int vy int angle int rotation int xRand int yRand int } type Sprites struct { sprites []*Sprite num int } type Game struct { touchIDs []ebiten.TouchID sprites Sprites op ebiten.DrawImageOptions initialised bool } func spriteSpeed(factor int, fixed bool) (int, int) { if fixed { return factor, factor } x := 2*rand.Intn(2) - 1 y := 2*rand.Intn(2) - 1 xSpeedVariation := 2*rand.Intn(factor) + 1 ySpeedVariation := 2*rand.Intn(factor) + 1 x *= xSpeedVariation y *= ySpeedVariation return x, y } func init() { img, _, err := ebitenutil.NewImageFromFile("amber-orb.png") if err != nil { log.Fatal(err) } w, h := img.Size() spriteImage = ebiten.NewImage(w, h) drawOptions := &ebiten.DrawImageOptions{} spriteImage.DrawImage(img, drawOptions) } func (s *Sprite) DealWithScreenEdges(behave EdgeBehaviour) { if behave == Rebound { if s.x < 0 { s.x = -s.x s.vx = -s.vx } else if mx := world.screenWidth - s.spriteWidth; mx <= s.x { s.x = world.screenWidth - s.spriteWidth s.vx = -s.vx } if s.y < 0 { s.y = -s.y s.vy = -s.vy } else if my := world.screenHeight - s.spriteHeight; my <= s.y { s.y = world.screenHeight - s.spriteHeight s.vy = -s.vy } } else if behave == PassThrough { if s.x < -s.spriteWidth { s.x = world.screenWidth } else if s.x > world.screenWidth+s.spriteWidth { s.x = 0 } if s.y < -s.spriteHeight { s.y = world.screenHeight } else if s.y > world.screenHeight+s.spriteHeight { s.y = 0 } } } func (s *Sprite) Update() { // Update the sprites position and angle. s.x += s.vx s.y += s.vy s.DealWithScreenEdges(world.rebound) s.angle += world.angleOfRotation * s.rotation if s.angle == world.maxAngle { s.angle = 0 } } func (sprite *Sprites) Update() { for i := 0; i < sprite.num; i++ { sprite.sprites[i].Update() } } func (game *Game) init() { defer func() { game.initialised = true }() game.sprites.sprites = make([]*Sprite, world.maxSprites) game.sprites.num = world.spriteCount for i := range game.sprites.sprites { w, h := spriteImage.Size() x, y := rand.Intn(world.screenWidth-w), rand.Intn(world.screenHeight-h) r := utils.PlusOrMinus() vx, vy := spriteSpeed(world.speedFactor, false) a := rand.Intn(world.maxAngle) game.sprites.sprites[i] = &Sprite{ spriteWidth: w, spriteHeight: h, x: x, y: y, vx: vx, vy: vy, angle: a, rotation: r, } } } func (game *Game) Update() error { if !game.initialised { game.init() } if ebiten.IsKeyPressed(ebiten.KeyQ) { world.speedFactor += 1 } if ebiten.IsKeyPressed(ebiten.KeyA) { world.speedFactor -= 1 } if ebiten.IsKeyPressed(ebiten.KeyArrowUp) { game.sprites.num += world.smallSpriteGrowth if world.maxSprites < game.sprites.num { game.sprites.num = world.maxSprites } } if ebiten.IsKeyPressed(ebiten.KeyArrowRight) { game.sprites.num += world.bigSpriteGrowth if world.maxSprites < game.sprites.num { game.sprites.num = world.maxSprites } } if ebiten.IsKeyPressed(ebiten.KeyArrowLeft) { game.sprites.num -= world.bigSpriteGrowth if game.sprites.num < world.minSprites { game.sprites.num = world.minSprites } } if ebiten.IsKeyPressed(ebiten.KeyArrowDown) { game.sprites.num -= world.smallSpriteGrowth if game.sprites.num < world.minSprites { game.sprites.num = world.minSprites } } game.sprites.Update() return nil } func (game *Game) DisplayInformation(showInfo bool, screen *ebiten.Image) { if showInfo { msg := fmt.Sprintf("TPS: %0.2f\nFPS: %0.1f\nNum of sprites: %d", ebiten.CurrentTPS(), ebiten.CurrentFPS(), game.sprites.num) ebitenutil.DebugPrint(screen, msg) } } func (game *Game) Draw(screen *ebiten.Image) { // Draw each sprite. // DrawImage can be called many times, but in the implementation, // the actual draw call to GPU is very few since these calls satisfy // some conditions e.game. all the rendering sources and targets are same. // For more detail, see: // https://pkg.go.dev/github.com/hajimehoshi/ebiten/v2#Image.DrawImage //w, h := spriteImage.Size() for i := 0; i < game.sprites.num; i++ { s := game.sprites.sprites[i] game.op.GeoM.Reset() //game.op.GeoM.Translate(-float64(w)/2, -float64(h)/2) //game.op.GeoM.Rotate(2 * math.Pi * float64(s.angle) / maxAngle) //game.op.GeoM.Translate(float64(w)/2, float64(h)/2) game.op.GeoM.Translate(float64(s.x), float64(s.y)) screen.DrawImage(spriteImage, &game.op) } game.DisplayInformation(world.showInfo, screen) } func (game *Game) Layout(outsideWidth, outsideHeight int) (int, int) { return world.screenWidth, world.screenHeight } func main() { println("Starting the app") world = GameWorld{ name: "world", screenWidth: 1600, screenHeight: 1000, maxAngle: 360, minSprites: 1, maxSprites: 50000, angleOfRotation: 16, bigSpriteGrowth: 50, smallSpriteGrowth: 1, spriteCount: 3, showInfo: true, speedFactor: 10, rebound: PassThrough, } ebiten.SetWindowSize(world.screenWidth, world.screenHeight) ebiten.SetWindowTitle("Sprite handling") ebiten.SetWindowResizable(true) if err := ebiten.RunGame(&Game{}); err != nil { log.Fatal(err) } }
package main // TODO : CRUD handlers/server/RPA could be a standalone package // we could have a structure that only link him what to do with every action // Or not // Could be really handy to make improvements on all the RPAs // TODO : RPA => move handlers.go, routes.go, router.go, error.go, logger.go in RPA package (rpa-service) // TODO : User => move user.go in User package (Yes I know, it's already in, do this with places) (rpa-entity + user) // TODO : Storage => evaluate the possibility to agnosticize storage in a RPAStock package (rpa-storage) // TODO : Storage => config files and such things could be set on load // TODO : Main => could be splitted in previous mentionned packages needing config files // TODO : RPA => Starting to look like CRUD war // TODO : Main => Actions focused : config storage, define actions, config handlers, config routes, starting service, eating popcorn import ( "encoding/json" "io" "io/ioutil" "net/http" "github.com/gorilla/mux" ) // TODO : RPA Standalone package could have a type struct with function // TODO : RPA Standalone package could allow user to specify functions in this type // TODO : Leaving the question of anonymous functions with anonymous types // TODO : using interface{} as an anonymous (void *) type, don't know if its leggit // TODO : Use a not defined yet type instead ? "Entry" for example, with a cast in the caller package // TODO : maaah we are not going anywhere, time to bed // TODO : hmmmmmm interfaces looks great might check this //type Action struct { // Read func (string) (interface{}, error) // Create func (interface{}) (interface{}, error) // Update func (interface{}, string) (interface{}, error) // Search func (interface{}) (interface{}, error) // Delete func (string) (interface{}, error) //} //var actions Actions // TODO : RPA standalone package could have an initialisation function (would init be possible ?, config ? called during initialisation ? // TODO : RPA standalone package could have this kind of modification // TODO : using interface{} as an anonymous (void *) type, don't know if its leggit //func Read(w http.ResponseWriter, r *http.Request, fr (string) (interface{}, error)) { func UserRead(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) var userId string userId = vars["userId"] // TODO : RPA standalone package could have this kind of modification // entry, e := fr(userId) // entry, e := actions.Read(userId) user, e := StorageFindUser(userId) if e { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(user); err != nil { panic(err) } return } // If we didn't find it, 404 w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusNotFound) if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil { panic(err) } } /* Test with this curl command: curl -H "Content-Type: application/json" -d '{"name":"New User"}' http://localhost:8080/todos */ func UserCreate(w http.ResponseWriter, r *http.Request) { var user User body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576)) if err != nil { panic(err) } if err := r.Body.Close(); err != nil { panic(err) } if err := json.Unmarshal(body, &user); err != nil { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(422) // unprocessable entity if err := json.NewEncoder(w).Encode(err); err != nil { panic(err) } return } /* TODO print and return error */ t, e := StorageCreateUser(user) if e != nil { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusConflict) // cannot be treated if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusConflict, Text: e.Error()}); err != nil { panic(err) } return } w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusCreated) if err := json.NewEncoder(w).Encode(t); err != nil { panic(err) } } func UserUpdate(w http.ResponseWriter, r *http.Request) { var userId string var user User vars := mux.Vars(r) userId = vars["userId"] body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576)) if err != nil { panic(err) } if err := r.Body.Close(); err != nil { panic(err) } if err := json.Unmarshal(body, &user); err != nil { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(422) // unprocessable entity if err := json.NewEncoder(w).Encode(err); err != nil { panic(err) } return } /* TODO print and return error */ t, e := StorageUpdateUser(user, userId) if e != nil { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusConflict) // cannot be treated if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusConflict, Text: e.Error()}); err != nil { panic(err) } return } w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(t); err != nil { panic(err) } } func UserSearch(w http.ResponseWriter, r *http.Request) { var user User body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576)) if err != nil { panic(err) } if err := r.Body.Close(); err != nil { panic(err) } if err := json.Unmarshal(body, &user); err != nil { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(422) // unprocessable entity if err := json.NewEncoder(w).Encode(err); err != nil { panic(err) } return } /* TODO print and return error */ t, e := StorageSearchUser(user) if e != nil { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusNotFound) // cannot be treated if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusConflict, Text: e.Error()}); err != nil { panic(err) } return } w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(t); err != nil { panic(err) } } func UserDelete(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) var userId string userId = vars["userId"] e := StorageDeleteUser(userId) if e == nil { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(""); err != nil { panic(err) } return } // If we didn't find it, 404 w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusNotFound) if err := json.NewEncoder(w).Encode(jsonErr{Code: http.StatusNotFound, Text: "Not Found"}); err != nil { panic(err) } }
package main import ( "fmt" "os" "syscall" "github.com/mortawe/go-containerized/src/nsexec" "github.com/mortawe/go-containerized/src/nsnet" "github.com/mortawe/go-containerized/src/nsopts" ) func main() { opts := nsopts.NewOpts() if !opts.Validate() { opts.Help() os.Exit(1) } // invoke self exec to isolate hostname and fs from host system cmd := nsexec.Command("nsInit", opts.GetRootfs(), opts.GetHostname()) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.SysProcAttr = &syscall.SysProcAttr{ Cloneflags: syscall.CLONE_NEWNS | syscall.CLONE_NEWUTS | syscall.CLONE_NEWIPC | syscall.CLONE_NEWPID | syscall.CLONE_NEWNET | syscall.CLONE_NEWUSER, UidMappings: []syscall.SysProcIDMap{ { ContainerID: 0, HostID: os.Getuid(), Size: 1, }, }, GidMappings: []syscall.SysProcIDMap{ { ContainerID: 0, HostID: os.Getgid(), Size: 1, }, }, } if err := cmd.Start(); err != nil { fmt.Printf("Error invoking self exec - %s\n", err) os.Exit(1) } pid := fmt.Sprintf("%d", cmd.Process.Pid) // creating network bridge and veths between host system and container if err := nsnet.InvokeNetsetgo(opts.GetNetsetgo(), pid); err != nil { fmt.Printf("Error running netsetgo - %s\n", err) os.Exit(1) } if err := cmd.Wait(); err != nil { fmt.Printf("Error waiting for invoked self - %s\n", err) os.Exit(1) } }
package router import ( "github.com/gorilla/mux" "net/http" quoteHandler "quote_wall/handler" ) func HandleRequest() { handler := mux.NewRouter(); handler.HandleFunc("/store", quoteHandler.SaveQuote()).Methods("POST") handler.HandleFunc("/store", quoteHandler.GetQuote()).Methods("GET") handler.PathPrefix("/").Handler(http.FileServer(http.Dir("./public"))); http.Handle("/", handler); }
package unit type ActiveState int const ( ActiveStateError ActiveState = iota - 1 ActiveStateInactive ActiveStateActive ActiveStateDeactivating ActiveStateActivating ActiveStateReloading ActiveStateFailed ) var MapActiveState = map[string]ActiveState{ "inactive": ActiveStateInactive, "active": ActiveStateActive, "deactivating": ActiveStateDeactivating, "activating": ActiveStateActivating, "reloading": ActiveStateReloading, "failed": ActiveStateFailed, }
package connrt import ( "github.com/gookit/event" "github.com/prometheus/client_golang/prometheus" ) // Metrics var metricConnectionsTotal = prometheus.NewCounter(prometheus.CounterOpts{ Name: "conndetect_connections_total", Help: "Total number of connections detected", }) type MetricsCounter struct { Node } func NewMetricsCounter(eventManager event.ManagerFace) *MetricsCounter { counter := &MetricsCounter{ Node: Node{eventManager: eventManager}, } eventManager.On("newConnection", event.ListenerFunc(counter.Handle)) return counter } func (c *MetricsCounter) Handle(e event.Event) error { switch e.Name() { case "newConnection": metricConnectionsTotal.Inc() } return nil } func init() { prometheus.MustRegister(metricConnectionsTotal) }
/* 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. */ //Controllers // //Controllers (pkg/controller) use events (pkg/events) to eventually trigger //reconcile requests. They may be constructed manually, but are often //constructed with a Builder (pkg/builder), which eases the wiring of event //sources (pkg/source), like Kubernetes API object changes, to event handlers //(pkg/handler), like "enqueue a reconcile request for the object owner". //Predicates (pkg/predicate) can be used to filter which events actually //trigger reconciles. There are pre-written utilities for the common cases, and //interfaces and helpers for advanced cases. package controllers import ( // Core GoLang contexts "context" "fmt" "strings" "time" // 3rd party and SIG contexts "github.com/go-logr/logr" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/reconcile" "k8s.io/client-go/tools/record" // Local Operator contexts cnatv1alpha1 "example/api/v1alpha1" ) //Reconcilers // // // //Controller logic is implemented in terms of Reconcilers (pkg/reconcile). //A Reconciler implements a function which takes a reconcile Request containing //the name and namespace of the object to reconcile, reconciles the object, //and returns a Response or an error indicating whether to requeue for a //second round of processing. // AtReconciler reconciles a At object type AtReconciler struct { //Clients and Caches // //Reconcilers use Clients (pkg/client) to access API objects. The default //client provided by the manager reads from a local shared cache (pkg/cache) //and writes directly to the API server, but clients can be constructed that //only talk to the API server, without a cache. The Cache will auto-populate //with watched objects, as well as when other structured objects are //requested. The default split client does not promise to invalidate the cache //during writes (nor does it promise sequential create/get coherence), and code //should not assume a get immediately following a create/update will return //the updated resource. Caches may also have indexes, which can be created via //a FieldIndexer (pkg/client) obtained from the manager. Indexes can used to //quickly and easily look up all objects with certain fields set. Reconcilers //may retrieve event recorders (pkg/recorder) to emit events using the //manager. client.Client Log logr.Logger // Schemes // // Clients, Caches, and many other things in Kubernetes use Schemes // (pkg/scheme) to associate Go types to Kubernetes API Kinds // (Group-Version-Kinds, to be specific). Scheme *runtime.Scheme // EventRecorder knows how to record events on behalf of an EventSource. Recorder record.EventRecorder } // 定义调谐器所需要的权限 包含 ats 以及 deployment 等的权限 // 这些权限的注释会自动生成rbac的yaml文件 // 更多参考 https://book.kubebuilder.io/reference/markers.html // +kubebuilder:rbac:groups=cnat.my.domain,resources=ats,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=cnat.my.domain,resources=ats/status,verbs=get;update;patch // +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=apps,resources=deployments/status,verbs=get;update;patch // Reconcilers 的Reconcile方法 // Reconciler performs a full reconciliation for the object referred to by the Request. // The Controller will requeue the Request to be processed again if an error is non-nil or // Result.Requeue is true, otherwise upon completion it will remove the work from the queue. // ctrl.Request // Request contains the information necessary to reconcile a Kubernetes object. This includes the // information to uniquely identify the object - its Name and Namespace. // ctrl.Result == reconcile.Result // Result contains the result of a Reconciler invocation. //type Result struct { // // Requeue tells the Controller to requeue the reconcile key. Defaults to false. // Requeue bool // // // RequeueAfter if greater than 0, tells the Controller to requeue the reconcile key after the Duration. // // Implies that Requeue is true, there is no need to set Requeue to true at the same time as RequeueAfter. // RequeueAfter time.Duration //} func (r *AtReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) { _ = context.Background() logger := r.Log.WithValues("namespace", req.NamespacedName, "at", req.Name) logger.Info("== Reconciling At") // 实例化一个空的资源对象,指针类型 instance := &cnatv1alpha1.At{} // 通过 AtReconciler 的get方法通过k8s client 来获取相关的资源对象 // 在给定的namespace获取 cnatv1alpha1.At 对象 // 因为r是指针,获取完成就放到缓存了,不用期待返回值 // Get retrieves an obj for the given object key from the Kubernetes Cluster. // obj must be a struct pointer so that obj can be updated with the response // returned by the Server. // 执行完成后,从apiserver获取cnatv1alpha1.At{} 就会填充相关的字段 因为他是指针类型 err := r.Get(context.TODO(), req.NamespacedName, instance) if err != nil { if errors.IsNotFound(err) { return reconcile.Result{}, nil } return reconcile.Result{}, nil } // 因为是指针类型,因此可以进行相关的字段填充 if instance.Status.Phase == "" { instance.Status.Phase = cnatv1alpha1.PhasePending } switch instance.Status.Phase { case cnatv1alpha1.PhasePending: logger.Info("Phase: Pending") logger.Info("checking schedules", "target", instance.Spec.Schedule) d, err := timeUntilSchedule(instance.Spec.Schedule) if err != nil { logger.Error(err, "schedule paring failre") return ctrl.Result{}, nil } logger.Info("schedule paring successed", "result", fmt.Sprintf("diff=%v", d)) if d > 0 { return ctrl.Result{RequeueAfter: d}, nil } logger.Info("it is time", "ready to run ", instance.Spec.Command) instance.Status.Phase = cnatv1alpha1.PhaseRunning r.Recorder.Event(instance, "Normal", "PhaseChange", cnatv1alpha1.PhasePending) case cnatv1alpha1.PhaseRunning: logger.Info("Phase: runing") pod := newPodForCR(instance) // 将pod资源归到at实例名下 // Package controllerutil contains utility functions for working with and implementing Controllers. // SetControllerReference sets owner as a Controller OwnerReference on controlled. // This is used for garbage collection of the controlled object and for // reconciling the owner object on changes to controlled (with a Watch + EnqueueRequestForOwner). // Since only one OwnerReference can be a controller, it returns an error if // there is another OwnerReference with Controller flag set. if err := controllerutil.SetControllerReference(instance, pod, r.Scheme); err != nil { return reconcile.Result{}, nil } found := &corev1.Pod{} err := r.Get(context.TODO(), types.NamespacedName{Name: pod.Name, Namespace: pod.Namespace}, found) if err != nil && errors.IsNotFound(err) { err = r.Create(context.TODO(), pod) if err != nil { return reconcile.Result{}, err } logger.Info("pod start", "name", pod.Name) } else if err != nil { return reconcile.Result{}, err } else if found.Status.Phase == corev1.PodFailed || found.Status.Phase == corev1.PodSucceeded { logger.Info("container termiaing", "reason", found.Status.Reason, "message", found.Status.Message) instance.Status.Phase = cnatv1alpha1.PhaseDone } else { return reconcile.Result{}, nil } r.Recorder.Event(instance, "Running", "PhaseChange", cnatv1alpha1.PhaseRunning) case cnatv1alpha1.PhaseDone: logger.Info("Phase: done") r.Recorder.Event(instance, "Done", "PhaseChange", cnatv1alpha1.PhaseDone) return reconcile.Result{}, nil default: logger.Info("NOP") return reconcile.Result{}, nil } // Update the At instance, setting the status to the respective phase: err = r.Status().Update(context.TODO(), instance) if err != nil { return reconcile.Result{}, err } return ctrl.Result{}, nil } // 创建集群的基础资源对象 pod func newPodForCR(cr *cnatv1alpha1.At) *corev1.Pod { labels := map[string]string{ "app": cr.Name, } return &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: cr.Name + "-pod", Namespace: cr.Namespace, Labels: labels, }, Spec: corev1.PodSpec{ Containers: []corev1.Container{ { Name: "busybox", Image: "busybox", Command: strings.Split(cr.Spec.Command, " "), }, }, RestartPolicy: corev1.RestartPolicyOnFailure, }, } } // timeUntilSchedule parses the schedule string and returns the time until the schedule. // When it is overdue, the duration is negative. func timeUntilSchedule(schedule string) (time.Duration, error) { now := time.Now().UTC() layout := "2006-01-02T15:04:05Z" // 根据时间格式解析出执行的时间 s, err := time.Parse(layout, schedule) if err != nil { return time.Duration(0), err } return s.Sub(now), nil } // 向manager注册 // 传入实例化后的mgr func (r *AtReconciler) SetupWithManager(mgr ctrl.Manager) error { // NewControllerManagedBy 方法接收mgr参数 返回一个 Builder // 构造器提供创建controller的接口 // 下面通过一些 builder 的方法来进行controller的配置 // // builder provides wraps other controller-runtime libraries and exposes simple // patterns for building common Controllers. // ControllerManagedBy returns a new controller builder that will be started by the provided Manager return ctrl.NewControllerManagedBy(mgr). // // // For defines //1 the type of Object being *reconciled*, //2 configures the ControllerManagedBy to respond to create / delete / update events by *reconciling the object*. // 参数接收一个资源对象结构体 返回 *builder // 控制器调协的对象是哪个 For(&cnatv1alpha1.At{}). // Owns defines //1 types of Objects being *generated* by the ControllerManagedBy, //2 configures the ControllerManagedBy to respond to create / delete / update events by *reconciling the owner object*. // 控制器管理的对象是哪个 接收事件的对象是哪个 Owns(&cnatv1alpha1.At{}). // pod也被该控制器管理以及接收事件 // 控制器管理的对象是哪个 接收事件的对象是哪个 Owns(&corev1.Pod{}). // Complete builds the Application ControllerManagedBy. // 将 Reconcilers 注册到controller里面 Complete(r) }
/* Copyright 2016 Padduck, LLC 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 utils import ( "github.com/gorilla/websocket" ) type WebSocketManager interface { Register(ws *websocket.Conn) Write(msg []byte) (n int, e error) } type wsManager struct { sockets []websocket.Conn } func CreateWSManager() WebSocketManager { return &wsManager{sockets: make([]websocket.Conn, 0)} } func (ws *wsManager) Register(conn *websocket.Conn) { ws.sockets = append(ws.sockets, *conn) } func (ws *wsManager) Write(msg []byte) (n int, e error) { invalid := make([]int, 0) for k, v := range ws.sockets { err := v.WriteMessage(websocket.TextMessage, msg) if err != nil { invalid = append(invalid, k) } } if len(invalid) > 0 { for b := range invalid { if len(ws.sockets) == 1 { ws.sockets = make([]websocket.Conn, 0) } else { ws.sockets = append(ws.sockets[:b], ws.sockets[b+1:]...) } } } n = len(msg) return }
package repository import "github.com/octokit/go-octokit/octokit" type Repository interface { Nwo() string Issues(string, string) ([]octokit.Issue, error) PullRequests(string, string) ([]octokit.PullRequest, error) }
package p2 import ( "bufio" "fmt" "os" "regexp" "strconv" ) func isPolicySatisfied(min int32, max int32, c int32, pwd string) bool { prop1 := int32(pwd[min]) == c prop2 := int32(pwd[max]) == c return prop1 != prop2 } func driver() int { filename := fmt.Sprintf("p2.input") fp, fpe := os.Open(filename) if fpe != nil { panic(fpe) } defer fp.Close() valid := 0 bufReader := bufio.NewScanner(fp) for bufReader.Scan() { input := bufReader.Text() matcher := regexp.MustCompile(`([0-9]+)-([0-9]+)\ ([a-z]):\ ([a-z]+)`) matchedComponents := matcher.FindStringSubmatch(input)[1:] min, _ := strconv.Atoi(matchedComponents[0]) max, _ := strconv.Atoi(matchedComponents[1]) c := []rune(matchedComponents[2])[0] pwd := matchedComponents[3] if isPolicySatisfied(int32(min)-1, int32(max)-1, c, pwd) { valid++ } } return valid }
package main import ( "context" "time" "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter10/channels" ) func main() { ch := make(chan string) done := make(chan bool) ctx := context.Background() ctx, cancel := context.WithCancel(ctx) defer cancel() go channels.Printer(ctx, ch) go channels.Sender(ch, done) time.Sleep(2 * time.Second) done <- true cancel() time.Sleep(3 * time.Second) }
package main import ( "encoding/json" "io/ioutil" "net/http" ) type responseJSON struct { Status bool `json:"status"` Message string `json:"message"` } type appConfig struct { Port string Host string } func sendSimpleResponse(w http.ResponseWriter, status bool, message string) { json.NewEncoder(w).Encode( responseJSON{ Status: status, Message: message, }) } func readConf(conf string) appConfig { data, err := ioutil.ReadFile(conf) if err != nil { panic(err) } obj := appConfig{} err = json.Unmarshal(data, &obj) if err != nil { panic(err) } return obj }
package handler import ( "context" "github.com/stretchr/testify/assert" "testing" ) func TestHandler_CheckInet(t *testing.T) { _, err := h.CheckInet(context.Background()) assert.NoError(t, err) } func TestHandler_CheckInetRound(t *testing.T) { err := h.CheckInetRound(context.Background()) assert.NoError(t, err) err = h.CheckInetRound(context.Background()) err = h.CheckInetRound(context.Background()) }
// Copyright 2022 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package util import ( "time" "go.uber.org/atomic" ) var ( // MinSchedulerInterval is the minimum interval between two scheduling. MinSchedulerInterval = atomic.NewDuration(200 * time.Millisecond) // MaxOverclockCount is the maximum number of overclock goroutine. MaxOverclockCount = int32(1) ) // GoroutinePool is a pool interface type GoroutinePool interface { ReleaseAndWait() Tune(size int32) LastTunerTs() time.Time Cap() int32 Running() int32 Name() string GetOriginConcurrency() int32 } // PoolContainer is a pool container type PoolContainer struct { Pool GoroutinePool Component Component } // Component is ID for difference component type Component int const ( // UNKNOWN is for unknown component. It is only for test UNKNOWN Component = iota // DDL is for ddl component DDL // DistTask is for disttask component. DistTask // CheckTable is for admin check table component. CheckTable )
// Write a program that // - launches 10 goroutines // - each goroutine adds 10 numbers to a channel // - pull the numbers off the channel and print them package main import "fmt" func main() { c := make(chan int) const totalGoroutines = 2 const counter = 10 for i := 0; i < totalGoroutines; i++ { go write(i, counter, c) } for i := 0; i < totalGoroutines*counter; i++ { fmt.Println(<-c) } } func write(s, n int, c chan<- int) { for i := s * 10; i < s*10+n; i++ { c <- i } }
package env import ( "os" "path/filepath" "time" ) var ( WDA_USB_DRIVER = os.Getenv("WDA_USB_DRIVER") WDA_LOCAL_PORT = os.Getenv("WDA_LOCAL_PORT") WDA_LOCAL_MJPEG_PORT = os.Getenv("WDA_LOCAL_MJPEG_PORT") VEDEM_IMAGE_URL = os.Getenv("VEDEM_IMAGE_URL") VEDEM_IMAGE_AK = os.Getenv("VEDEM_IMAGE_AK") VEDEM_IMAGE_SK = os.Getenv("VEDEM_IMAGE_SK") DISABLE_GA = os.Getenv("DISABLE_GA") DISABLE_SENTRY = os.Getenv("DISABLE_SENTRY") PYPI_INDEX_URL = os.Getenv("PYPI_INDEX_URL") PATH = os.Getenv("PATH") ) const ( ResultsDirName = "results" ScreenshotsDirName = "screenshots" ) var ( RootDir string ResultsDir string ResultsPath string ScreenShotsPath string StartTime = time.Now() StartTimeStr = StartTime.Format("20060102150405") ) func init() { var err error RootDir, err = os.Getwd() if err != nil { panic(err) } ResultsDir = filepath.Join(ResultsDirName, StartTimeStr) ResultsPath = filepath.Join(RootDir, ResultsDir) ScreenShotsPath = filepath.Join(ResultsPath, ScreenshotsDirName) }
package main import ( "os" _ "github.com/lib/pq" httplib "gitlab.com/semestr-6/projekt-grupowy/backend/go-libs/http-lib" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/attributes" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/categories" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/configuration" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/energy_resources" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/files" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/units" ) func main() { getEnv() routes := getRoutes() addEndpoints(routes) httplib.DeclareNewRouterWithAuthorizationAndStart(routes) } func getEnv() { configuration.ConnectionString = os.Getenv("CONN_STR") } func getRoutes() (routes httplib.Routes) { routes = append(routes, attributes.GetRoutes()...) routes = append(routes, categories.GetRoutes()...) routes = append(routes, energy_resources.GetRoutes()...) routes = append(routes, files.GetRoutes()...) //routes = append(routes, resources.GetRoutes()...) routes = append(routes, units.GetRoutes()...) return }
package latest // Version is the version of the providers config const Version = "v1beta1" // Config holds all the different providers and their configuration type Config struct { Version string `yaml:"version,omitempty"` Default string `yaml:"default,omitempty"` Providers []*Provider `yaml:"providers,omitempty"` } // Provider describes the struct to hold the cloud configuration type Provider struct { Name string `yaml:"name,omitempty"` Host string `yaml:"host,omitempty"` // Key is used to obtain a token from the auth server Key string `yaml:"key,omitempty"` // Token is the actual authorization bearer Token string `yaml:"token,omitempty"` ClusterKey map[int]string `yaml:"clusterKeys,omitempty"` // These are the cached space tokens Spaces map[int]*SpaceCache `yaml:"spaces,omitempty"` } // SpaceCache holds the information for a specific space type SpaceCache struct { Space *Space `yaml:"space"` ServiceAccount *ServiceAccount `yaml:"serviceAccount"` // The kube context KubeContext string `yaml:"kubeContext"` // Expires specifies when the token will expire LastResume int64 `yaml:"lastResume,omitempty"` Expires int64 `yaml:"expires,omitempty"` } // Space holds the information about a space in the cloud type Space struct { SpaceID int `yaml:"spaceID"` Name string `yaml:"name"` Namespace string `yaml:"namespace"` Owner *Owner `yaml:"account"` ProviderName string `yaml:"providerName"` Cluster *Cluster `yaml:"cluster"` Created string `yaml:"created"` } // ServiceAccount holds the information about a service account for a certain space type ServiceAccount struct { SpaceID int `yaml:"spaceID"` Namespace string `yaml:"namespace"` CaCert string `yaml:"caCert"` Server string `yaml:"server"` Token string `yaml:"token"` } // Project is the type that holds the project information type Project struct { ProjectID int `json:"id"` OwnerID int `json:"owner_id"` Cluster *Cluster `json:"cluster"` Name string `json:"name"` } // Cluster is the type that holds the cluster information type Cluster struct { ClusterID int `json:"id"` Server *string `json:"server"` Owner *Owner `json:"account"` Name string `json:"name"` EncryptToken bool `json:"encrypt_token"` CreatedAt *string `json:"created_at"` } // Owner holds the information about a certain type Owner struct { OwnerID int `json:"id"` Name string `json:"name"` } // ClusterUser is the type that golds the cluster user information type ClusterUser struct { ClusterUserID int `json:"id"` AccountID int `json:"account_id"` ClusterID int `json:"cluster_id"` IsAdmin bool `json:"is_admin"` } // Registry is the type that holds the docker image registry information type Registry struct { RegistryID int `json:"id"` URL string `json:"url"` }
package models import ( "database/sql" "time" ) type AddressForm struct { IP string `json:"ip_address" gorm:"type:varchar(15);not null"` Mac string `json:"mac" gorm:"type:varchar(17);not null"` Hostname string `json:"hostname" gorm:"type:varchar(255)"` Reserved bool `json:"reserved" gorm:"type:bool"` PoolID sql.NullInt32 `json:"pool_id" gorm:"type:int(11)"` } type Address struct { ID int `json:"id" gorm:"primary_key"` AddressForm CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` DeletedAt *time.Time `json:"deleted_at,omitempty"` }