text
stringlengths
11
4.05M
package main import ( _ "github.com/go-sql-driver/mysql" "context" "github.com/moyrne/tebot/configs" "github.com/moyrne/tebot/internal/analyze" "github.com/moyrne/tebot/internal/database" "github.com/moyrne/tebot/internal/logs" "github.com/moyrne/tebot/internal/service/api" "github.com/moyrne/tebot/internal/service/commands" "log" ) func main() { if err := configs.LoadConfig(); err != nil { log.Fatalln("read config error", err) } writer, err := logs.FileWriter() if err != nil { log.Fatalln("new file writer error", err) } defer writer.Close() logs.Init(writer) if err := database.ConnectMySQL(); err != nil { logs.Panic("db connect", "error", err) } analyze.SyncReply(context.Background()) if err := database.ConnectRedis(); err != nil { logs.Panic("redis connect", "error", err) } go commands.StartCQHTTP() r := api.NewRouter() if err := r.Run("127.0.0.1:7771"); err != nil { logs.Panic("service run", "error", err) } }
package _670_Maximum_Swap import ( "math" ) func maximumSwap(num int) int { var ( currMax int maxPos int pos1, pos2 int l = []int{} ret int ) for i := 0; num != 0; i++ { n := num % 10 l = append(l, n) if n > currMax { currMax = n maxPos = i } if n < currMax { pos1 = i pos2 = maxPos } num = num / 10 } // 交换 l[pos1], l[pos2] = l[pos2], l[pos1] // 求和 for i, n := range l { ret += int(math.Pow(10, float64(i))) * n } return ret }
package daos import ( "github.com/google/uuid" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" "github.com/go-gnss/data/cmd/database/models" ) func GetObservation(id uuid.UUID) (*models.Observation, error) { // This should be in config package db, err := gorm.Open("sqlite3", "../test.db") if err != nil { return nil, err } defer db.Close() obs := models.Observation{SatelliteData: []models.SatelliteData{}} err = db.First(&obs, "id = ?", id). Preload("SignalData"). Related(&obs.SatelliteData). Error return &obs, err } func GetObservations() (*[]models.Observation, error) { // This should be in config package db, err := gorm.Open("sqlite3", "../test.db") if err != nil { return nil, err } defer db.Close() obs := []models.Observation{} err = db.Find(&obs).Error for i, _ := range obs { db.Model(obs[i]).Preload("SignalData").Related(&obs[i].SatelliteData) } return &obs, err } func PutObservation(obs *models.Observation) (id uuid.UUID, err error) { // This should be in config package db, err := gorm.Open("sqlite3", "../test.db") if err != nil { panic(err) } defer db.Close() obs.ID = uuid.New() db.Create(&obs) return obs.ID, nil }
package emulator type ConditionCodes struct { z uint8 s uint8 p uint8 cy uint8 ac uint8 pad uint8 //uint8_t z:1 //uint8_t s:1; //uint8_t p:1; //uint8_t cy:1; //uint8_t ac:1; //uint8_t pad:3; } type State8080 struct { a uint8 b uint8 c uint8 d uint8 e uint8 h uint8 l uint8 sp uint16 pc uint16 memory *[]uint8 cc ConditionCodes int_enable uint8 } func UnimplementedInstruction(state *State8080) { panic("Error: Unimplemented instruction\n") } //func Emulate8080Op(state *State8080) int { // var opcode *uint8 // opcode = state.memory[state.pc] //}
package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup wg.Add(2) go fun1(&wg) go fun2(&wg) fmt.Println("开始等待") wg.Wait() fmt.Println("解除阻塞") } func fun1(wg *sync.WaitGroup) { for i := 0; i < 1000; i++ { fmt.Println("[---func1----", i) } wg.Done() } func fun2(wg *sync.WaitGroup) { defer wg.Done() for j := 0; j < 1000; j++ { fmt.Println("----func2-----", j) } }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/5/29 4:53 下午 # @File : linked_list_cycle_ii.go # @Description : 给定一个链表,返回链表开始入环的第一个节点。如果链表无环,则返回null。 为了表示给定链表中的环, 我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。 说明:不允许修改给定的链表。 进阶: 你是否可以使用 O(1) 空间解决此题? # @Attention : */ package v2 func detectCycle(head *ListNode) *ListNode { if head == nil || head.Next == nil { return nil } fast := head.Next slow := head for nil != fast && fast.Next != nil { if fast == slow { fast=head slow=slow.Next for nil != slow { if fast == slow { return slow } slow = slow.Next fast = fast.Next } } fast = fast.Next.Next slow = slow.Next } return nil }
/* * @lc app=leetcode.cn id=1460 lang=golang * * [1460] 通过翻转子数组使两个数组相等 */ // @lc code=start package main func canBeEqual(target []int, arr []int) bool { count := make(map[int]int) for i := 0; i < len(target); i++ { count[target[i]] += 1 } for i := 0; i < len(arr); i++ { count[arr[i]] -= 1 if count[arr[i]] < 0 { return false } } return true } // @lc code=end
package main import "fmt" type Node struct { next *Node val int } func main() { //처음 root의 노드 var root *Node root = &Node{nil, 0} //Node.next에 nil이 있는 node를 가리키는 것을 tail 노드 var tail *Node tail = root var want_end int fmt.Print("몇 번째까지 추가를 원하나요? : ") fmt.Scanf("%d", &want_end) for i := 1; i <= want_end; i++ { tail = AddNode(tail, i*10) } PrintAllNode(root) LastNode(root) } func AddNode(node *Node, val int) *Node { var tail *Node tail = &Node{nil, val} node.next = tail return tail } func PrintAllNode(root *Node) { var i int for i = 0; root.next != nil; i++ { fmt.Printf("노드의 위치 : %d, 노드값 : %d\n", i, root.val) root = root.next } fmt.Printf("노드의 위치 : %d, 노드값 : %d\n", i, root.val) } func LastNode(root *Node) { var tail *Node tail = root for tail.next != nil { tail = tail.next } if tail.next == nil { fmt.Printf("마지막 노드 값 : %d\n", tail.val) } }
package cache import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "os" "testing" "time" redis "gopkg.in/redis.v3" "github.com/kataras/iris" // you could use that library now to do http testing: "github.com/kataras/iris/httptest" ) const ( irisSrvWithMemoryStore = "127.0.0.1:1234" irisSrvWithRedisStore = "127.0.0.1:1235" redisService = "127.0.0.1:6379" sleepTime = time.Duration(2) * time.Second ) var cacheConfig = Config{ AutoRemove: false, CacheTimeDuration: time.Duration(5) * time.Minute, ContentType: ContentTypeJSON, IrisGzipEnabled: false, } type dummy struct { Name string `json:"name"` } func setupMemoryStoreIrisSrv() { engine := iris.New() c := NewCacheHF(cacheConfig, NewInMemoryStore()) engine.Use(c) engine.Get("/json", func(ctx iris.Context) { <-time.After(sleepTime) ctx.JSON(dummy{"test"}) }) go engine.Run(iris.Addr(irisSrvWithMemoryStore), iris.WithoutStartupLog, iris.WithoutVersionChecker, iris.WithoutServerError(iris.ErrServerClosed)) <-time.After(time.Duration(1350 * time.Millisecond)) } func setupRedisStoreIrisSrv() { engine := iris.New() redisClient := redis.NewClient(&redis.Options{Addr: redisService}) if err := redisClient.Ping().Err(); err != nil { panic(err) } redisClient.FlushDb() c := NewCacheHF(cacheConfig, NewRedisStore(redisClient)) engine.Use(c) engine.Get("/json", func(ctx iris.Context) { <-time.After(sleepTime) ctx.JSON(dummy{"test"}) }) go engine.Run(iris.Addr(irisSrvWithRedisStore), iris.WithoutStartupLog, iris.WithoutVersionChecker, iris.WithoutServerError(iris.ErrServerClosed)) <-time.After(time.Duration(1350 * time.Millisecond)) } func TestMain(m *testing.M) { // spawn web servers setupMemoryStoreIrisSrv() setupRedisStoreIrisSrv() // run the tests os.Exit(m.Run()) } func TestNonCachedMemoryStoreRequest(t *testing.T) { if err := doRequest(irisSrvWithMemoryStore); err != nil { t.Fatal(err) return } } func TestCachedMemoryStoreRequest(t *testing.T) { s := time.Now() if err := doRequest(irisSrvWithMemoryStore); err != nil { t.Fatal(err) return } // check if the request was slower than the sleep time if time.Now().Sub(s) > sleepTime+200*time.Millisecond { t.Fatal("cached request was slower than non cached request") return } } func TestNonCachedRedisStoreRequest(t *testing.T) { if err := doRequest(irisSrvWithRedisStore); err != nil { t.Fatal(err) return } } func TestCachedRedisStoreRequest(t *testing.T) { s := time.Now() if err := doRequest(irisSrvWithRedisStore); err != nil { t.Fatal(err) return } // check if the request was slower than the sleep time, // these numbers are not always percise, especially in services like travis, so give it time. if time.Now().Sub(s) > sleepTime+200*time.Millisecond { t.Fatal("cached request was slower than non cached request") return } } func BenchmarkCachedMemoryStoreResponse(b *testing.B) { for i := 0; i < b.N; i++ { doRequestWithoutParsing(irisSrvWithMemoryStore) } } func BenchmarkCachedRedisStoreResponse(b *testing.B) { for i := 0; i < b.N; i++ { doRequestWithoutParsing(irisSrvWithRedisStore) } } func doRequest(url string) error { res, err := http.Get(fmt.Sprintf("http://%s/json", url)) if err != nil { return err } buf, err := ioutil.ReadAll(res.Body) if err != nil { return err } obj := &dummy{} err = json.Unmarshal(buf, obj) if err != nil { return err } if obj.Name != "test" { return errors.New("name doesn't match origin name") } return nil } func doRequestWithoutParsing(url string) error { _, err := http.Get(fmt.Sprintf("http://%s/json", url)) return err }
package c43_dsa_from_nonce import ( "bytes" "crypto/sha1" "math/big" "testing" "github.com/vodafon/cryptopals/set1/c1_hex_to_base64" ) func TestSing(t *testing.T) { dsa := NewDSA() msg := []byte("Some text") r, s := dsa.Sign(msg) ver := dsa.Verify(msg, r, s) if !ver { t.Errorf("Incorrect result. Expected true, got false\n") } ver = dsa.Verify(msg[1:], r, s) if ver { t.Errorf("Incorrect result. Expected false, got true\n") } } func TestRecoverX(t *testing.T) { dsa := NewDSA() msg := []byte("Some text") r, s, k := dsa.signK(msg) hmH := sha1.Sum(msg) hm := new(big.Int).SetBytes(hmH[:]) x := RecoverX(hm, r, s, dsa.Q, k) if x.Cmp(dsa.x) != 0 { t.Errorf("Incorrect result. Expected %x, got %x\n", dsa.x, x) } } func TestBruteK1(t *testing.T) { dsa := NewDSA() dsa.MaxK = big.NewInt(2 << 15) // 2**16 msg := []byte("Some text") r, s := dsa.Sign(msg) exp := dsa.x dsa.x = big.NewInt(0) x, err := dsa.BruteK(msg, r, s) if err != nil { t.Fatalf("BruteK error: %s\n", err) } if x.Cmp(exp) != 0 { t.Errorf("Incorrect result. Expected %x, got %x\n", exp, x) } } func TestBruteK2(t *testing.T) { dsa := NewDSA() dsa.MaxK = big.NewInt(2 << 15) // 2**16 dsa.Y.SetString("84ad4719d044495496a3201c8ff484feb45b962e7302e56a392aee4abab3e4bdebf2955b4736012f21a08084056b19bcd7fee56048e004e44984e2f411788efdc837a0d2e5abb7b555039fd243ac01f0fb2ed1dec568280ce678e931868d23eb095fde9d3779191b8c0299d6e07bbb283e6633451e535c45513b2d33c99ea17", 16) msg := []byte("For those that envy a MC it can be hazardous to your health\nSo be friendly, a matter of life and death, just like a etch-a-sketch\n") r, _ := new(big.Int).SetString("548099063082341131477253921760299949438196259240", 10) s, _ := new(big.Int).SetString("857042759984254168557880549501802188789837994940", 10) dsa.x = big.NewInt(0) x, err := dsa.BruteK(msg, r, s) if err != nil { t.Fatalf("BruteK error: %s\n", err) } hex := c1_hex_to_base64.EncodeHex(x.Bytes()) sum := sha1.Sum(hex) res := c1_hex_to_base64.EncodeHex(sum[:]) exp := []byte("0954edd5e0afe5542a4adf012611a91912a3ec16") if !bytes.Equal(exp, res) { t.Errorf("Incorrect result. Expected %q, got %q\n", exp, res) } }
package main func SockMerchant(n int, socks []int) int { maxIndex := getMax(socks, n) helper := make([]int, maxIndex+1) for _, sock := range socks { helper[sock]++ } var sum int for _, help := range helper { sum += help / 2 } return sum } func getMax(slice []int, length int) int { max := 0 for i := 0; i < length; i++ { if slice[i] > max { max = slice[i] } } return max }
package v3 import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "mime/multipart" "net/http" "net/url" "os" "strings" ) type ImgurClient struct { ClientId string ClientSecret string AccessToken string ExpiresIn int64 TokenType string RefreshToken string AccountUsername string AccountId int64 http.Client } const API_BASE = "https://api.imgur.com/3" const UPLOAD_IMAGE = API_BASE + "/image" const AUTH = "https://api.imgur.com/oauth2/authorize" const TOKEN = "https://api.imgur.com/oauth2/token" func NewClient(key, secret, accessToken, refreshToken string) *ImgurClient { return &ImgurClient{ ClientId: key, ClientSecret: secret, AccessToken: accessToken, RefreshToken: refreshToken, } } func (cl ImgurClient) AnonymousUpload(path string) (ImgurResponse, error) { var err error = nil ir := ImgurResponse{} auth_header := []string{"Client-ID " + cl.ClientId} req, err := cl.newFileUploadRequest( UPLOAD_IMAGE, nil, "image", "./test.png", ) req.Header.Add("Authorization", strings.Join(auth_header, " ")) response, err := cl.Do(req) if err != nil { return ir, err } defer response.Body.Close() body, err := ioutil.ReadAll(response.Body) err = json.Unmarshal(body, &ir) if err != nil { return ir, err } return ir, err } func (cl *ImgurClient) GetAuthorizationUrl(authType string) string { return fmt.Sprintf("%s?client_id=%s&response_type=%s", AUTH, cl.ClientId, authType) } func (cl *ImgurClient) Authorize(pin, authType string) (ImgurAuthResponse, error) { ir := ImgurAuthResponse{} v := url.Values{} v.Set("client_id", cl.ClientId) v.Set("client_secret", cl.ClientSecret) v.Set("grant_type", authType) v.Set("pin", pin) response, err := cl.PostForm(TOKEN, v) if response.StatusCode == 200 { defer response.Body.Close() body, _ := ioutil.ReadAll(response.Body) err = json.Unmarshal(body, &ir) } else { err = errors.New(fmt.Sprintf("ImgurClient#Authorize: Status code: %d, authtype: %s", response.StatusCode, authType)) } return ir, err } func (cl *ImgurClient) Refresh() error { ir := ImgurAuthResponse{} vals := url.Values{} vals.Add("refresh_token", cl.RefreshToken) vals.Add("client_id", cl.ClientId) vals.Add("client_secret", cl.ClientSecret) vals.Add("grant_type", "refresh_token") response, err := cl.PostForm(TOKEN, vals) if response.StatusCode == 200 { defer response.Body.Close() body, _ := ioutil.ReadAll(response.Body) err = json.Unmarshal(body, &ir) cl.AccessToken = ir.AccessToken fmt.Printf("%v\n", ir) fmt.Println(cl) } else { err = errors.New(fmt.Sprintf("ImgurClient#Authorize: Status code: %d, authtype: refresh_token", response.StatusCode)) } return err } func (cl *ImgurClient) prepareRequest(method, uri string) (*http.Request, error) { path := fmt.Sprintf("%s/%s", API_BASE, uri) req, err := http.NewRequest(method, path, nil) req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", cl.AccessToken)) return req, err } // Creates a new file upload http request with optional extra params func (cl *ImgurClient) newFileUploadRequest( uri string, params map[string]string, fileParam, path string, ) (*http.Request, error) { file, err := os.Open(path) if err != nil { return nil, err } fileContents, err := ioutil.ReadAll(file) if err != nil { return nil, err } fi, err := file.Stat() if err != nil { return nil, err } file.Close() body := new(bytes.Buffer) writer := multipart.NewWriter(body) part, err := writer.CreateFormFile(fileParam, fi.Name()) if err != nil { return nil, err } part.Write(fileContents) for key, val := range params { _ = writer.WriteField(key, val) } err = writer.Close() if err != nil { return nil, err } req, err := http.NewRequest("POST", uri, body) req.Header.Add("Content-Type", writer.FormDataContentType()) return req, err }
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "os" "text/template" ) type chapter struct { Title string `json:"title"` Story []string `json:"story"` Options []option `json:"options"` } type option struct { Text string `json:"text"` Arc string `json:"arc"` } type storyHandler struct { Chapters map[string]chapter Template *template.Template } func (s storyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { path := r.URL.Path[1:] if path == "" { http.Redirect(w, r, "/intro", 301) return } chapter := s.Chapters[path] s.Template.Execute(w, chapter) } func jsonHandler() map[string]chapter { jsonFile, _ := os.Open("stories.json") defer jsonFile.Close() byteValue, _ := ioutil.ReadAll(jsonFile) var chapters map[string]chapter json.Unmarshal(byteValue, &chapters) return chapters } func main() { tmpl, _ := template.ParseFiles("sample.html") chapters := jsonHandler() handler := storyHandler{ Chapters: chapters, Template: tmpl, } fmt.Println("Listening on port 8080") http.ListenAndServe(":8080", handler) }
package forms // Type of map to hold validation error messages for form fields. // Map that maps a field name to the slice of error messages. // There might be multiple errors for a single field: length limit, blank, etc type errors map[string][]string // Add method to add error message for a given field. func (e errors) Add(field, message string) { e[field] = append(e[field], message) } // Get method to retrieve the first error message for a given field. func (e errors) Get(field string) string { es := e[field] if len(es) == 0 { return "" } return es[0] }
package main import ( "errors" "fmt" "os" "flag" "strings" ) const ( DEFAULT_SESSION_TOKEN_DURATION = int64(60 * 60) DEFAULT_AWS_REGION = "eu-central-1" DEFAULT_ONELOGIN_REGION = "us" ) func dieOnError(err error, message string) { if err != nil { fmt.Fprintf(os.Stderr, "%s: %v\n", message, err) os.Exit(1) } } func checkStringFlagNotEmpty(name string, f *string) { if f == nil || *f == "" { fmt.Fprintf(os.Stderr, "Missing mandatory parameter: %s\n\n", name) flag.Usage() os.Exit(1) } } func printAvailableRoles(assertion *SamlAssertion) { availableRoles := assertion.Parse() if availableRoles == nil { dieOnError(errors.New("No role avaiable to assume into"), "Error assuming roles") } fmt.Println("Available roles:") for role := range availableRoles { fmt.Println(role) } } func main() { // set up command line flags roleArns := flag.String("role-arn", "", "AWS role arn to assume into, separate by comma to assume multiple roles at once") profileName := flag.String("profile", "", "Write this AWS CLI profile, defaults to role name, separate by comma to assume multiple roles at once") duration := flag.Int64("duration", DEFAULT_SESSION_TOKEN_DURATION, "Token duration in seconds for target profile") awsRegion := flag.String("region", DEFAULT_AWS_REGION, "AWS region") username := flag.String("username", "", "onelogin user name") password := flag.String("password", "", "onelogin password") oneloginRegion := flag.String("onelogin-region", DEFAULT_ONELOGIN_REGION, "onelogin region, us/eu") mfaCode := flag.String("mfa-code", "", "MFA code") flag.Parse() checkStringFlagNotEmpty("username", username) checkStringFlagNotEmpty("password", password) checkStringFlagNotEmpty("mfa-code", mfaCode) client, err := NewOneloginClient(CLIENT_ID, CLIENT_SECRET, *oneloginRegion) dieOnError(err, "Error creating onelogin client") assertion, err := client.GetSamlAssertion(APP_ID, SUBDOMAIN, *username, *password, *mfaCode) dieOnError(err, "Error getting SAML assertion") fmt.Println("Successfully logged into onelogin") if *roleArns == "" { printAvailableRoles(assertion) } else { profileNames := strings.Split(*profileName, ",") for i, roleArn := range strings.Split(*roleArns, ",") { creds, err := AssumeRoleWithSaml(assertion, roleArn, *duration) dieOnError(err, "Error assuming AWS role") if *profileName == "" || i >= len(profileNames) { WriteProfile(creds, strings.SplitN(roleArn, "/", 2)[1], *awsRegion) } else { WriteProfile(creds, profileNames[i], *awsRegion) } } } }
package logServer import ( "bytes" "fmt" "os" "path/filepath" "strings" "time" ) // LogWriter is a structure to handle with file type LogWriter struct { logFileName string logFileDir string writeBuffer bytes.Buffer } // SetPath will set dir and file name func (w *LogWriter) SetPath(dir, fileName string) { w.logFileDir, w.logFileName = dir, fileName } // BufferSize will get current buffer size func (w *LogWriter) BufferSize() int { return w.writeBuffer.Len() } // Flush will flush buffer to file and return file size func (w *LogWriter) Flush() int64 { logFilePath := filepath.Join(w.logFileDir, w.logFileName) file, err := os.OpenFile(logFilePath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0777) if err != nil { fmt.Println("Open file:", logFilePath, " error:", err) return -1 } defer file.Close() _, err = w.writeBuffer.WriteTo(file) if err != nil { fmt.Println("buffer WriteTo() error:", err) return -1 } fileInfo, err := file.Stat() if err != nil { fmt.Println("get file info error:", err) return -1 } return fileInfo.Size() } // PushToBuffer will push string to buffer func (w *LogWriter) PushToBuffer(s string) { _, err := w.writeBuffer.WriteString(s) if err != nil { fmt.Println("buffer WriteString() error:", err) } } // SplitFile will rename current log file with timestamp func (w *LogWriter) SplitFile() { logFilePath := filepath.Join(w.logFileDir, w.logFileName) _, err := os.Stat(logFilePath) if os.IsNotExist(err) { return } t := time.Now().Format(time.RFC3339) timestamp := strings.Replace(t, ":", "-", -1) newPath := logFilePath + timestamp err = os.Rename(logFilePath, newPath) if err != nil { fmt.Println("os Rename() error:", err) return } }
package twitter import ( "log" "strings" "github.com/kyokomi/slackbot/plugins" ) type plugin struct { accessToken string } func (r plugin) CheckMessage(_ plugins.BotEvent, message string) (bool, string) { return strings.Contains(message, "いーすん画像"), message } func (r plugin) DoAction(event plugins.BotEvent, message string) bool { if r.accessToken == "" { token, err := newAccessToken("", "") if err != nil { log.Println(err) return true } r.accessToken = token } imageURLs, err := searchImages(r.accessToken, "イストワール", 1) if err != nil { log.Println(err) return true } for _, imageURL := range imageURLs { event.Reply(imageURL) } return false } func (p *plugin) Help() string { return `twitter: いーすん画像表示 いーすん画像: ネプテューヌシリーズの画像をTwitterから検索する。 ` } var _ plugins.BotMessagePlugin = (*plugin)(nil)
package printer import ( "strings" "github.com/davyxu/tabtoy/v2/i18n" "github.com/davyxu/tabtoy/v2/model" ) type TableIndex struct { Index *model.FieldDescriptor // 表头里的索引 Row *model.FieldDescriptor // 索引的数据 } type Globals struct { Version string InputFileList []interface{} ParaMode bool ProtoVersion int LuaEnumIntValue bool LuaTabHeader string GenCSSerailizeCode bool PackageName string Path string HasReadExportType bool ServerOut string ClientOut string Printers []*PrinterContext CombineStructName string // 不包含路径, 用作 *model.FileDescriptor // 类型信息.用于添加各种导出结构 tableByName map[string]*model.Table // 防止table重名 Tables []*model.Table // 数据信息.表格数据 GlobalIndexes []TableIndex // 类型信息.全局索引 CombineStruct *model.Descriptor // 类型信息.Combine结构体 BuildID string } func (self *Globals) PreExport() bool { // 当合并结构名没有指定时, 对于代码相关的输出器, 要报错 if self.CombineStructName == "" && self.hasAnyPrinter(".proto", ".cs") { log.Errorf("%s", i18n.String(i18n.Globals_CombineNameLost)) return false } // 添加XXConfig全局结构 self.CombineStruct.Name = self.CombineStructName self.CombineStruct.Kind = model.DescriptorKind_Struct self.CombineStruct.Usage = model.DescriptorUsage_CombineStruct self.FileDescriptor.Name = self.CombineStructName self.FileDescriptor.Add(self.CombineStruct) return true } func (self *Globals) hasAnyPrinter(exts ...string) bool { for _, ext := range exts { for _, p := range self.Printers { if p.name == ext { return true } } } return false } func (self *Globals) AddOutputType(name string, outfile string, class int) { if p, ok := printerByExt[name]; ok { self.Printers = append(self.Printers, &PrinterContext{ p: p, outFile: outfile, name: name, class: class, }) } else { panic("output type not found:" + name) } } func GetOuputName(name string) string { name = strings.Replace(name, ".xlsx", "", 1) name = strings.Replace(name, ".csv", "", 1) return name + ".lua" } func (self *Globals) Print() bool { log.Infof("==========%s==========", i18n.String(i18n.Globals_OutputCombineData)) for _, p := range self.Printers { if !p.Start(self) { return false } } return true } func (self *Globals) AddTypes(localFD *model.FileDescriptor) bool { // 有表格里描述的包名不一致, 无法合成最终的文件 if self.Pragma.GetString("Package") == "" { self.Pragma.SetString("Package", localFD.Pragma.GetString("Package")) } // else if self.Pragma.GetString("Package") != localFD.Pragma.GetString("Package") { // log.Errorf("%s, '%s' '%s'", i18n.String(i18n.Globals_PackageNameDiff), localFD.Pragma.GetString("TableName"), self.Pragma.GetString("TableType")) // return false // } // 将行定义结构也添加到文件中 for _, d := range localFD.Descriptors { if !self.FileDescriptor.Add(d) { log.Errorf("%s, %s", i18n.String(i18n.Globals_DuplicateTypeName), d.Name) return false } } return true } // 合并每个表带的类型 func (self *Globals) AddContent(tab *model.Table) bool { localFD := tab.LocalFD if _, ok := self.tableByName[localFD.Name]; ok { log.Errorf("%s, '%s'", i18n.String(i18n.Globals_TableNameDuplicated), localFD.Name) return false } // 表的全局类型信息与合并信息一致 tab.GlobalFD = self.FileDescriptor self.tableByName[localFD.Name] = tab self.Tables = append(self.Tables, tab) // 每个表在结构体里的字段 rowFD := model.NewFieldDescriptor() rowFD.Name = localFD.Name rowFD.Type = model.FieldType_Struct rowFD.Complex = localFD.RowDescriptor() rowFD.IsRepeated = true rowFD.Order = int32(len(self.CombineStruct.Fields) + 1) // 去掉注释中的回车,避免代码生成错误 rowFD.Comment = strings.Replace(localFD.Name, "\n", " ", -1) self.CombineStruct.Add(rowFD, self.Fdmap) if localFD.RowDescriptor() == nil { panic("row field null:" + localFD.Name) } for _, d := range localFD.Descriptors { // 非行类型的, 全部忽略 if d.Usage != model.DescriptorUsage_RowType { continue } for _, indexFD := range d.Indexes { key := TableIndex{ Row: rowFD, Index: indexFD, } self.GlobalIndexes = append(self.GlobalIndexes, key) } } return true } func NewGlobals() *Globals { self := &Globals{ tableByName: make(map[string]*model.Table), FileDescriptor: model.NewFileDescriptor(), CombineStruct: model.NewDescriptor(), } return self }
package handler import ( "net/http" "newfeed/flatform/newfeed" "github.com/gin-gonic/gin" ) func NewFeedGet(feed *newfeed.Repo) gin.HandlerFunc { return func(c *gin.Context) { results := feed.GetAll() c.JSON(http.StatusOK, results) } }
// Copyright (C) 2019 rameshvk. All rights reserved. // Use of this source code is governed by a MIT-style license // that can be found in the LICENSE file. package code import ( "go/ast" "strconv" ) // Creates a root scope object func RootScope() *Scope { var s *Scope return s.New() } // Scope tracks all used variable names // // It also allows stashing arbitrary "context" type Scope struct { Stash map[interface{}]interface{} Vars map[string]ast.Node Parent *Scope } // New creates a new nested scope func (s *Scope) New() *Scope { return &Scope{ Stash: map[interface{}]interface{}{}, Vars: map[string]ast.Node{}, Parent: s, } } // LookupStash looks up the stash (up the parent chain) for a key func (s *Scope) LookupStash(key interface{}) (interface{}, bool) { if s == nil { return nil, false } if v, ok := s.Stash[key]; ok { return v, ok } return s.Parent.LookupStash(key) } // LookupVar looks up the scope chain to find a variable with the given name func (s *Scope) LookupVar(name string) (ast.Node, bool) { if s == nil { return nil, false } if v, ok := s.Vars[name]; ok { return v, ok } return s.Parent.LookupVar(name) } // PickName picks a unique name with the given prefix func (s *Scope) PickName(prefix string) string { if prefix == "" { prefix = "gogox" } name, idx := prefix, 2 for { if _, ok := s.LookupVar(name); !ok { return name } name = prefix + strconv.Itoa(idx) idx++ } }
package main import ( "fmt" "reflect" "strings" ) type student struct { Name string `ini:"name"` Age int `ini:"age"` } type stu struct { NAME string AGE int } //s为指针类型变量,函数中要改变值必须传指针 func setstudent(s interface{}, m map[string]interface{}) { v := reflect.ValueOf(s).Elem() //求变量中字段数量 for i := 0; i < v.NumField(); i++ { //查询tag名 tname := v.Type().Field(i).Tag.Get("ini") //查询key名 kname := v.Type().Field(i).Name //如果没有tag名,那么假定tag名为小写的key名 if tname == "" { tname = strings.ToLower(v.Type().Field(i).Name) } //如果map中有tag名对应的字段,则赋值 if value, ok := m[tname]; ok { //比较map中的字段类型和s变量中的字段类型是否相同 if reflect.ValueOf(value).Type() == v.FieldByName(kname).Type() { v.FieldByName(kname).Set(reflect.ValueOf(value)) } } } } func main() { var a student var b = map[string]interface{}{"name": "xiaoming", "age": 18} setstudent(&a, b) fmt.Printf("a=%#v\n", a) var c stu setstudent(&c, b) fmt.Printf("c=%#v\n", c) }
package myaccessory import ( "github.com/brutella/hc/accessory" "github.com/brutella/hc/service" ) type BridgeStatus struct { *accessory.Accessory BridgingState *service.BridgingState } func NewBridgeStatus(info accessory.Info) *BridgeStatus { acc := BridgeStatus{} acc.Accessory = accessory.New(info, accessory.TypeBridge) acc.BridgingState = service.NewBridgingState() acc.BridgingState.Reachable.SetValue(true) acc.AddService(acc.BridgingState.Service) return &acc }
/* The package server provides the HTTP server that makes the Comment Parsing service as a RESTful service */ package server import ( "net/http" "commentparser/logging" "commentparser/models" "commentparser/services" "encoding/json" "errors" "github.com/gorilla/mux" "io/ioutil" "net/url" "strings" "time" ) // this is the model representing the configuration options that the server uses type Configuration struct { Development bool // true if the application is in development mode, false in production Address string // the address to bind the server to LogName string // path to log to GoogleCloudProjectID string // the google cloud project ID GoogleCloudCredFile string // google cloud API credentials file } // POST "/parse" // Extract the comments where comments contains the specified tokens in the // provided package name, the body should be a models.CommentParsingRequest func ParseAction( writer http.ResponseWriter, body []byte, logging logging.Logging) ErrorPkg { var err error var request models.CommentParsingRequest err = json.Unmarshal(body, &request) if err != nil { return ErrorWithCodeSantized(400, err) } if len(request.PackageName) < 1 { return ErrorWithCodeSantized( 400, errors.New("The parameter `PackageName` cannot be empty")) } if len(request.Tokens) < 1 { return ErrorWithCodeSantized( 400, errors.New("The parameter `Tokens` cannot be empty")) } resObj, err := services.ExtractRelevantComments(request, logging) if err != nil { return Error(err) } res, err := json.Marshal(resObj) if err != nil { return Error(err) } writer.Write(res) return ErrorPkg{} } // GET "/" // Extract the comments where comments contains the specified tokens in the // provided package name func IndexAction( writer http.ResponseWriter, values url.Values, logging logging.Logging) ErrorPkg { qPackage := values.Get("package") qTokens := values.Get("tokens") if len(qPackage) < 1 { return ErrorWithCodeSantized(400, errors.New("the query must contain the parameter `package`")) } if len(qTokens) < 1 { return ErrorWithCodeSantized(400, errors.New("the query must contain the parameter `tokens`")) } request := models.CommentParsingRequest{ PackageName: qPackage, Tokens: strings.Split(qTokens, ","), } resObj, err := services.ExtractRelevantComments(request, logging) if err != nil { return Error(err) } res, err := json.Marshal(resObj) if err != nil { return Error(err) } writer.Write(res) return ErrorPkg{} } // Represents a POST action that handles a request body type apiPostAction func(w http.ResponseWriter, body []byte, logging logging.Logging) ErrorPkg // Represents a GET action that handles a request body type apiGetAction func(w http.ResponseWriter, values url.Values, logging logging.Logging) ErrorPkg // Mask errors and log them at the top level func (config *Configuration) errorHandle( err error, writer http.ResponseWriter, logging logging.Logging) bool { if err != nil { errorString := err.Error() logging.Error(errorString) if !config.Development { errorString = "An internal server has occurred, please contact support@corporate.biz" } http.Error(writer, errorString, 500) return true } return false } // Mask errors in an ErrorPkg and log them at the top level func (config *Configuration) errorPkgHandle( err ErrorPkg, writer http.ResponseWriter, logging logging.Logging) bool { if err.Error() { errorString := err.innerError.Error() logging.Error(errorString) if !config.Development && err.httpStatus == 500 && !err.isSanitized { errorString = "An internal server has occurred, please contact support@corporate.biz" } http.Error(writer, errorString, err.httpStatus) return true } return false } // Mask errors and log them at the top level // also the central point to measure Http performance func baseGetHandler( hander apiGetAction, config Configuration, logging logging.Logging, measurement Measurement) http.HandlerFunc { return func(writer http.ResponseWriter, request *http.Request) { if request.Method == "GET" { start := time.Now() err := hander(writer, request.URL.Query(), logging) measurement.Log(request.URL.Path, time.Since(start).Nanoseconds()/1000000) if config.errorPkgHandle(err, writer, logging) { return } } else { http.Error(writer, "Unsupported HTTP method", 422) } } } // basic handling for all actions will withhold the actual error message // if not in Development mode func basePostHandler( handler apiPostAction, config Configuration, logging logging.Logging, measurement Measurement) http.HandlerFunc { return func(writer http.ResponseWriter, request *http.Request) { if request.Method == "POST" { requestBody, err := ioutil.ReadAll(request.Body) defer request.Body.Close() if config.errorHandle(err, writer, logging) { return } start := time.Now() errPkg := handler(writer, requestBody, logging) measurement.Log(request.URL.Path, time.Since(start).Nanoseconds()/1000000) if config.errorPkgHandle(errPkg, writer, logging) { return } } else { http.Error(writer, "Unsupported HTTP method", 422) } } } // common settings for all Post routes func commonPostRouteSetup(routes ...*mux.Route) { for _, route := range routes { route. Methods("POST"). Headers("Content-Type", "application/json") } } // common settings for all Get routes func commonGetRouteSetup(routes ...*mux.Route) { for _, route := range routes { route. Methods("GET") } } // This is the entry point for the server application, will start a server that provides comment parsing // as a REST-ful service func CommentParserHttpServer( config Configuration, logging logging.Logging, measurement Measurement) error { router := mux.NewRouter().StrictSlash(true) commonPostRouteSetup( router.HandleFunc("/parse", basePostHandler(ParseAction, config, logging, measurement)), ) commonGetRouteSetup( router.HandleFunc("/", baseGetHandler(IndexAction, config, logging, measurement)), ) http.Handle("/", router) srv := &http.Server{ Handler: router, Addr: config.Address, WriteTimeout: 15 * time.Second, ReadTimeout: 15 * time.Second, } srvError := srv.ListenAndServe() logging.Critical(srvError.Error()) return nil }
package rules /* integration test for rules. This separate pkg needed to not create an import cycle between config and rules */ import ( "gopkg.in/yaml.v2" "io/ioutil" "reflect" "sort" "testing" _ "github.com/tumblr/docker-registry-pruner/internal/pkg/testing" "github.com/tumblr/docker-registry-pruner/pkg/config" "github.com/tumblr/docker-registry-pruner/pkg/registry" "github.com/tumblr/docker-registry-pruner/pkg/rules" ) func manifestObjectsToManifests(objs []*manifestObject) []*registry.Manifest { ms := []*registry.Manifest{} for _, o := range objs { m := mkmanifest(o.Name, o.Tag, o.DaysOld, o.Labels) ms = append(ms, m) } return ms } // testConfig is a configuration that defines a set of test. It is comprised of: // * SourceManifests: all Manifests that will be parsed into a registry.Manifest via mkmanifest. These are source material for the test suite // * Tests: List of `testCase` type testConfig struct { SourceFile string Manifests []*registry.Manifest SourceManifests []*manifestObject `yaml:"source_manifests"` Tests []testCase `yaml:"tests"` } // manifestObject will be parsed from test configs, and then pumped into mkmanifest() // to turn it into a registry.Manifest. type manifestObject struct { Name string Tag string DaysOld int64 `yaml:"days_old"` Labels map[string]string `yaml:"labels"` } // testCase is a struct to define a specific test case. It is comprised of: // * Config: the yaml config that contains the Rule sets // * Expected: The map[repo][]tags that the rest should produce from the testConfig.Manifests as input type testCase struct { Config string `yaml:"config"` Expected struct { Keep map[string][]string `yaml:"keep"` Delete map[string][]string `yaml:"delete"` } `yaml:"expected"` } func loadTestConfig(cfg string) (*testConfig, error) { d, err := ioutil.ReadFile(cfg) if err != nil { return nil, err } tc := testConfig{} err = yaml.Unmarshal(d, &tc) if err != nil { return nil, err } tc.SourceFile = cfg tc.Manifests = manifestObjectsToManifests(tc.SourceManifests) return &tc, nil } func TestMatching(t *testing.T) { tc, err := loadTestConfig("test/fixtures/manifest_tests/manifest_matching_1.yaml") if err != nil { t.Error(err) t.FailNow() } for _, test := range tc.Tests { // sort any expected tag sets for _, tags := range test.Expected.Keep { sort.Strings(tags) } for _, tags := range test.Expected.Delete { sort.Strings(tags) } t.Logf("%s: loading rules from %s", tc.SourceFile, test.Config) cfg, err := config.LoadFromFile(test.Config) if err != nil { t.Error(err) t.FailNow() } t.Logf("%s: Loaded %d rules from %s (%d manifests)", tc.SourceFile, len(cfg.Rules), test.Config, len(tc.Manifests)) selectors := rules.RulesToSelectors(cfg.Rules) matchedManifests := map[string][]string{} for _, manifest := range tc.Manifests { if rules.MatchAny(selectors, manifest) { if matchedManifests[manifest.Name] == nil { matchedManifests[manifest.Name] = []string{} } matchedManifests[manifest.Name] = append(matchedManifests[manifest.Name], manifest.Tag) sort.Strings(matchedManifests[manifest.Name]) } } if !reflect.DeepEqual(test.Expected.Keep, matchedManifests) { t.Errorf("%s: (rules %s) expected matching tags to be %v but got %v", tc.SourceFile, test.Config, test.Expected.Keep, matchedManifests) t.FailNow() } } } func TestFilterRepoTags(t *testing.T) { tc, err := loadTestConfig("test/fixtures/manifest_tests/filter_repo_tags.yaml") if err != nil { t.Error(err) t.FailNow() } for _, test := range tc.Tests { // sort any expected tag sets for _, tags := range test.Expected.Keep { sort.Strings(tags) } for _, tags := range test.Expected.Keep { sort.Strings(tags) } t.Logf("%s: loading rules from %s", tc.SourceFile, test.Config) cfg, err := config.LoadFromFile(test.Config) if err != nil { t.Error(err) t.FailNow() } selectors := rules.RulesToSelectors(cfg.Rules) actualManifests := rules.FilterManifests(tc.Manifests, selectors) // construct a map[string]map[string][]string from actualManifests to aid in comparison actualManifestsTags := map[string][]string{} for repo, ms := range actualManifests { actualManifestsTags[repo] = []string{} for _, m := range ms { actualManifestsTags[repo] = append(actualManifestsTags[repo], m.Tag) } sort.Strings(actualManifestsTags[repo]) } if !reflect.DeepEqual(test.Expected.Keep, actualManifestsTags) { t.Errorf("%s: (rules %s) expected matching tags to be:\n%v\nbut got:\n%v", tc.SourceFile, test.Config, test.Expected.Keep, actualManifestsTags) t.FailNow() } } }
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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 argocd import ( "context" "fmt" "net/http" "github.com/gorilla/mux" "github.com/pkg/errors" "github.com/Tencent/bk-bcs/bcs-common/common/blog" "github.com/Tencent/bk-bcs/bcs-common/pkg/auth/iam" mw "github.com/Tencent/bk-bcs/bcs-scenarios/bcs-gitops-manager/pkg/proxy/argocd/middleware" ) // * addinational stream path, application wrapper // GET:/api/v1/stream/applications?projects={projects},获取event事件流,强制启用projects // GET:/api/v1/stream/applications/{name}/resource-tree,指定资源树事件流 // StreamPlugin for internal streaming type StreamPlugin struct { *mux.Router appHandler *AppPlugin middleware mw.MiddlewareInterface } // Init all project sub path handler // project plugin is a subRouter, all path registered is relative func (plugin *StreamPlugin) Init() error { // done(DeveloperJim): GET /api/v1/stream/applications?projects={projects} plugin.Path("").Methods("GET").Queries("projects", "{projects}"). Handler(plugin.middleware.HttpWrapper(plugin.projectViewHandler)) // done(DeveloperJim): GET /api/v1/stream/applications/{name}/resource-tree plugin.Path("/{name}/resource-tree").Methods("GET"). Handler(plugin.middleware.HttpWrapper(plugin.appHandler.applicationViewsHandler)) blog.Infof("argocd stream applications plugin init successfully") return nil } func (plugin *StreamPlugin) projectViewHandler(ctx context.Context, r *http.Request) *mw.HttpResponse { projects := r.URL.Query()["projects"] if len(projects) == 0 { return mw.ReturnErrorResponse(http.StatusBadRequest, fmt.Errorf("query param 'projects' cannot be empty")) } for i := range projects { projectName := projects[i] _, statusCode, err := plugin.middleware.CheckProjectPermission(ctx, projectName, iam.ProjectView) if statusCode != http.StatusOK { return mw.ReturnErrorResponse(statusCode, errors.Wrapf(err, "check project '%s' permission failed", projectName)) } } return mw.ReturnArgoReverse() }
//go:build wasm && js && webclient package main import ( "bytes" "encoding/json" "errors" "log" "net/http" "strconv" "strings" "syscall/js" "time" "github.com/ekotlikoff/gochess/internal/model" matchserver "github.com/ekotlikoff/gochess/internal/server/backend/match" gateway "github.com/ekotlikoff/gochess/internal/server/frontend" ) var ( debug bool = true ctp string = "application/json" ) func (cm *ClientModel) initController() { cm.document.Call("addEventListener", "mousemove", cm.genMouseMove(), false) cm.document.Call("addEventListener", "touchmove", cm.genTouchMove(), false) cm.document.Call("addEventListener", "mouseup", cm.genMouseUp(), false) cm.document.Call("addEventListener", "touchend", cm.genTouchEnd(), false) cm.document.Call("addEventListener", "mousedown", cm.genGlobalOnTouchStart(), false) cm.document.Call("addEventListener", "touchstart", cm.genGlobalOnTouchStart(), false) cm.board.Call("addEventListener", "contextmenu", js.FuncOf(preventDefault), false) js.Global().Set("beginMatchmaking", cm.genBeginMatchmaking()) js.Global().Set("resign", cm.genResign()) js.Global().Set("draw", cm.genDraw()) js.Global().Set("onclick", cm.genGlobalOnclick()) cm.document.Call("getElementById", "gameover_modal_close").Set("onclick", cm.genCloseModalOnClick()) } func (cm *ClientModel) checkForSession() { resp, err := cm.client.Get("session") if err == nil { defer resp.Body.Close() } if err != nil || resp.StatusCode != 200 { log.Println("No session found") return } sessionResponse := gateway.SessionResponse{} err = json.NewDecoder(resp.Body).Decode(&sessionResponse) if err != nil { log.Println(err) } cm.document.Call("getElementById", "username").Set("value", sessionResponse.Credentials.Username) cm.SetPlayerName(sessionResponse.Credentials.Username) cm.SetHasSession(true) if sessionResponse.InMatch { log.Println("Rejoining match") cm.handleRejoinMatch(sessionResponse.Match) } } func (cm *ClientModel) genMouseDown() js.Func { return js.FuncOf(func(this js.Value, i []js.Value) interface{} { if len(i) > 0 && !cm.GetIsMouseDown() { i[0].Call("preventDefault") cm.handleClickStart(this, i[0]) } return 0 }) } func (cm *ClientModel) genTouchStart() js.Func { return js.FuncOf(func(this js.Value, i []js.Value) interface{} { if len(i) > 0 && !cm.GetIsMouseDown() { i[0].Call("preventDefault") touch := i[0].Get("touches").Index(0) cm.handleClickStart(this, touch) } return 0 }) } func (cm *ClientModel) genGlobalOnclick() js.Func { return js.FuncOf(func(this js.Value, i []js.Value) interface{} { gameoverModal := cm.document.Call("getElementById", "gameover_modal") if i[0].Get("target").Equal(gameoverModal) { cm.closeGameoverModal() } return 0 }) } func (cm *ClientModel) genGlobalOnTouchStart() js.Func { return js.FuncOf(func(this js.Value, i []js.Value) interface{} { promotionWindow := cm.GetPromotionWindow() if promotionWindow.Truthy() { promotionWindow.Call("remove") cm.SetPromotionWindow(js.Undefined()) } return 0 }) } func (cm *ClientModel) genCloseModalOnClick() js.Func { return js.FuncOf(func(this js.Value, i []js.Value) interface{} { cm.closeGameoverModal() return 0 }) } func (cm *ClientModel) closeGameoverModal() { removeClass(cm.document.Call("getElementById", "gameover_modal"), "gameover_modal") addClass(cm.document.Call("getElementById", "gameover_modal"), "hidden") cm.viewSetMatchMakingControls() cm.viewClearMatchDetails() cm.SetGameType(Local) cm.SetIsMatched(false) cm.ResetRemoteMatchModel() cm.resetGame() } func (cm *ClientModel) handleClickStart( this js.Value, event js.Value) { cm.LockMouseDown() cm.SetDraggingElement(this) positionOriginal, err := cm.getGamePositionFromPieceElement(this) if err != nil { log.Println("ERROR: Issue getting position from element,", err) return } cm.positionOriginal = positionOriginal cm.SetDraggingPiece(cm.positionOriginal) if cm.GetDraggingPiece() == nil { if debug { log.Println("ERROR: Clicked a piece that is not on the board") log.Println(cm.positionOriginal) log.Println(cm.GetBoardString()) } cm.UnlockMouseDown() return } addClass(cm.GetDraggingElement(), "dragging") cm.SetDraggingOriginalTransform( cm.GetDraggingElement().Get("style").Get("transform")) } func (cm *ClientModel) getGamePositionFromPieceElement( piece js.Value) (model.Position, error) { className := piece.Get("className").String() classElements := strings.Split(className, " ") for i := range classElements { if strings.Contains(classElements[i], "square") { posString := strings.Split(classElements[i], "-")[1] x, err := strconv.Atoi(string(posString[0])) y, err := strconv.Atoi(string(posString[1])) if err != nil { return model.Position{}, err } x-- y-- if cm.GetPlayerColor() == model.Black { x = 7 - x y = 7 - y } return model.Position{uint8(x), uint8(y)}, nil } } return model.Position{}, errors.New("Unable to convert class to position: " + className) } func (cm *ClientModel) genMouseMove() js.Func { return js.FuncOf(func(this js.Value, i []js.Value) interface{} { i[0].Call("preventDefault") cm.handleMoveEvent(i[0]) return 0 }) } func (cm *ClientModel) genTouchMove() js.Func { return js.FuncOf(func(this js.Value, i []js.Value) interface{} { i[0].Call("preventDefault") touch := i[0].Get("touches").Index(0) cm.handleMoveEvent(touch) return 0 }) } func (cm *ClientModel) handleMoveEvent(moveEvent js.Value) { if cm.GetIsMouseDown() { cm.viewDragPiece(cm.GetDraggingElement(), moveEvent) } } func (cm *ClientModel) genMouseUp() js.Func { return js.FuncOf(func(this js.Value, i []js.Value) interface{} { if cm.GetIsMouseDown() && len(i) > 0 { i[0].Call("preventDefault") cm.handleClickEnd(i[0]) } return 0 }) } func (cm *ClientModel) genTouchEnd() js.Func { return js.FuncOf(func(this js.Value, i []js.Value) interface{} { if cm.GetIsMouseDown() && len(i) > 0 { i[0].Call("preventDefault") touch := i[0].Get("changedTouches").Index(0) cm.handleClickEnd(touch) } return 0 }) } func (cm *ClientModel) handleClickEnd(event js.Value) { cm.UnlockMouseDown() elDragging := cm.GetDraggingElement() _, _, _, _, gridX, gridY := cm.getEventMousePosition(event) newPosition := cm.getPositionFromGrid(uint8(gridX), uint8(gridY)) pieceDragging := cm.GetDraggingPiece() var promoteTo *model.PieceType moveRequest := model.MoveRequest{cm.positionOriginal, model.Move{ int8(newPosition.File) - int8(cm.positionOriginal.File), int8(newPosition.Rank) - int8(cm.positionOriginal.Rank)}, promoteTo, } if pieceDragging.PieceType == model.Pawn && ((cm.positionOriginal.Rank == 1 && cm.game.Turn() == model.Black) || (cm.positionOriginal.Rank == 6 && cm.game.Turn() == model.White)) && (newPosition.Rank == 0 || newPosition.Rank == 7) { cm.viewCreatePromotionWindow( int(newPosition.File), int(newPosition.Rank)) elDragging.Get("style").Set("transform", cm.GetDraggingOriginalTransform()) cm.isMouseDown = false cm.SetPromotionMoveRequest(moveRequest) return } cm.handleMove(moveRequest) } func (cm *ClientModel) handleMove( moveRequest model.MoveRequest) { newPosition := model.Position{ File: uint8(int8(moveRequest.Position.File) + moveRequest.Move.X), Rank: uint8(int8(moveRequest.Position.Rank) + moveRequest.Move.Y), } elDragging := cm.GetDraggingElement() cm.SetDraggingElement(js.Undefined()) if cm.gameType == Local || cm.playerColor == cm.game.Turn() { go func() { cm.takeMove(moveRequest, newPosition, elDragging) elDragging.Get("style").Set("transform", cm.GetDraggingOriginalTransform()) removeClass(elDragging, "dragging") }() } else { elDragging.Get("style").Set("transform", cm.GetDraggingOriginalTransform()) removeClass(elDragging, "dragging") } } func (cm *ClientModel) takeMove( moveRequest model.MoveRequest, newPos model.Position, elMoving js.Value) { err := cm.MakeMove(moveRequest) if err == nil { cm.ClearRequestedDraw() cm.viewHandleMove(moveRequest, newPos, elMoving) } else { if debug { log.Println(err) } return } if cm.GetGameType() == Remote { if cm.backendType == HttpBackend { movePayloadBuf := new(bytes.Buffer) json.NewEncoder(movePayloadBuf).Encode(moveRequest) resp, err := retryWrapper( func() (*http.Response, error) { pathname := js.Global().Get("location").Get("pathname").String() return cm.client.Post(pathname+"http/sync", ctp, movePayloadBuf) }, "POST http/sync", 0, func() { cm.remoteGameEnd() }, ) if err != nil { log.Println("FATAL: Failed to send move to server: ", err) return } defer resp.Body.Close() if resp.StatusCode != 200 { // TODO handle strange case where local accepts the // move but remote does not. log.Println("FATAL: We do not expect a remote rejection when local move succeeds") return } } else if cm.backendType == WebsocketBackend { message := matchserver.WebsocketRequest{ WebsocketRequestType: matchserver.RequestSyncT, RequestSync: moveRequest, } jsonMsg, _ := json.Marshal(message) cm.GetWSConn().Call("send", string(jsonMsg)) } } } func (cm *ClientModel) listenForSyncUpdateHttp() { for true { select { case <-cm.remoteMatchModel.endRemoteGameChan: return default: } resp, err := retryWrapper( func() (*http.Response, error) { pathname := js.Global().Get("location").Get("pathname").String() return cm.client.Get(pathname + "http/sync") }, "GET http/sync", 0, func() { cm.remoteGameEnd() }, ) if err != nil { return } defer resp.Body.Close() if resp.StatusCode == 200 { opponentMove := model.MoveRequest{} json.NewDecoder(resp.Body).Decode(&opponentMove) cm.handleSyncUpdate(opponentMove) } } } func (cm *ClientModel) handleSyncUpdate(opponentMove model.MoveRequest) { err := cm.MakeMove(opponentMove) if err != nil { log.Println("FATAL: We do not expect an invalid move from the opponent.") return } cm.ClearRequestedDraw() newPos := model.Position{ opponentMove.Position.File + uint8(opponentMove.Move.X), opponentMove.Position.Rank + uint8(opponentMove.Move.Y), } originalPosClass := getPositionClass(opponentMove.Position, cm.GetPlayerColor()) elements := cm.document.Call("getElementsByClassName", originalPosClass) elMoving := elements.Index(0) cm.viewHandleMove(opponentMove, newPos, elMoving) } func (cm *ClientModel) listenForAsyncUpdateHttp() { for true { select { case <-cm.remoteMatchModel.endRemoteGameChan: return default: } resp, err := retryWrapper( func() (*http.Response, error) { pathname := js.Global().Get("location").Get("pathname").String() return cm.client.Get(pathname + "http/async") }, "http/async", 0, func() { cm.remoteGameEnd() }, ) if err != nil { return } defer resp.Body.Close() if resp.StatusCode == 200 { asyncResponse := matchserver.ResponseAsync{} json.NewDecoder(resp.Body).Decode(&asyncResponse) cm.handleResponseAsync(asyncResponse) } } } func (cm *ClientModel) handleResponseAsync( responseAsync matchserver.ResponseAsync) { if responseAsync.GameOver { cm.remoteGameEnd() winType := "" if responseAsync.Resignation { winType = "resignation" } else if responseAsync.Draw { winType = "draw" cm.ClearRequestedDraw() } else if responseAsync.Timeout { winType = "timeout" } else { winType = "mate" } log.Println("Winner:", responseAsync.Winner, "by", winType) cm.viewSetGameOver(responseAsync.Winner, winType) return } else if responseAsync.RequestToDraw { log.Println("Requested draw") cm.SetRequestedDraw(cm.GetOpponentColor(), !cm.GetRequestedDraw(cm.GetOpponentColor())) } else if responseAsync.Matched { cm.SetPlayerColor(responseAsync.MatchDetails.Color) cm.SetOpponentName(responseAsync.MatchDetails.OpponentName) cm.SetMaxTimeMs(responseAsync.MatchDetails.MaxTimeMs) cm.handleStartMatch() } } func (cm *ClientModel) handleResponseSync(responseSync matchserver.ResponseSync) { if responseSync.MoveSuccess { cm.SetPlayerElapsedMs(cm.playerColor, int64(responseSync.ElapsedMs)) cm.SetPlayerElapsedMs(cm.GetOpponentColor(), int64(responseSync.ElapsedMsOpponent)) } } func (cm *ClientModel) genBeginMatchmaking() js.Func { return js.FuncOf(func(this js.Value, i []js.Value) interface{} { if !cm.GetIsMatchmaking() && !cm.GetIsMatched() { go cm.lookForMatch() } return 0 }) } func (cm *ClientModel) genResign() js.Func { return js.FuncOf(func(this js.Value, i []js.Value) interface{} { requestBuf := new(bytes.Buffer) request := matchserver.RequestAsync{Resign: true} json.NewEncoder(requestBuf).Encode(request) if cm.backendType == HttpBackend { pathname := js.Global().Get("location").Get("pathname").String() go cm.client.Post(pathname+"http/async", ctp, requestBuf) } else if cm.backendType == WebsocketBackend { message := matchserver.WebsocketRequest{ WebsocketRequestType: matchserver.RequestAsyncT, RequestAsync: request, } jsonMsg, _ := json.Marshal(message) cm.GetWSConn().Call("send", string(jsonMsg)) } return 0 }) } func (cm *ClientModel) genDraw() js.Func { return js.FuncOf(func(this js.Value, i []js.Value) interface{} { go cm.sendDraw() return 0 }) } func (cm *ClientModel) sendDraw() { requestBuf := new(bytes.Buffer) request := matchserver.RequestAsync{RequestToDraw: true} json.NewEncoder(requestBuf).Encode(request) if cm.backendType == HttpBackend { pathname := js.Global().Get("location").Get("pathname").String() _, err := cm.client.Post(pathname+"http/async", ctp, requestBuf) if err != nil { return } } else if cm.backendType == WebsocketBackend { message := matchserver.WebsocketRequest{ WebsocketRequestType: matchserver.RequestAsyncT, RequestAsync: request, } jsonMsg, _ := json.Marshal(message) cm.GetWSConn().Call("send", string(jsonMsg)) } cm.SetRequestedDraw(cm.GetPlayerColor(), !cm.GetRequestedDraw(cm.GetPlayerColor())) } func (cm *ClientModel) lookForMatch() { cm.SetIsMatchmaking(true) cm.buttonBeginLoading( cm.document.Call("getElementById", "beginMatchmakingButton")) if !cm.GetHasSession() { username := cm.document.Call( "getElementById", "username").Get("value").String() credentialsBuf := new(bytes.Buffer) credentials := gateway.Credentials{username} json.NewEncoder(credentialsBuf).Encode(credentials) resp, err := cm.client.Post("session", ctp, credentialsBuf) if err == nil { resp.Body.Close() } if err != nil || resp.StatusCode != 200 { log.Println("Error starting session") cm.GetButtonLoader().Call("remove") cm.SetIsMatchmaking(false) return } cm.SetPlayerName(username) cm.SetHasSession(true) } var err error if cm.backendType == HttpBackend { err = cm.httpMatch() if err == nil { go cm.listenForSyncUpdateHttp() go cm.listenForAsyncUpdateHttp() } } else if cm.backendType == WebsocketBackend { err = cm.wsMatch() } if err != nil { cm.GetButtonLoader().Call("remove") } } func (cm *ClientModel) handleStartMatch() { cm.resetGame() // - TODO once matched briefly display matched icon? cm.SetGameType(Remote) cm.SetIsMatched(true) cm.SetIsMatchmaking(false) cm.GetButtonLoader().Call("remove") cm.remoteMatchModel.endRemoteGameChan = make(chan bool, 0) cm.viewSetMatchControls() go cm.matchDetailsUpdateLoop() } func (cm *ClientModel) handleRejoinMatch(match gateway.CurrentMatch) { myColor := model.Black opponentName := match.WhiteName if opponentName == cm.GetPlayerName() { myColor = model.White opponentName = match.BlackName } cm.SetPlayerColor(myColor) cm.SetOpponentName(opponentName) cm.SetMaxTimeMs(match.MaxTimeMs) cm.SetPlayerElapsedMs(model.Black, match.MaxTimeMs-match.BlackRemainingTimeMs) cm.SetPlayerElapsedMs(model.White, match.MaxTimeMs-match.WhiteRemainingTimeMs) cm.resetGameWithInProgressGame(match) cm.SetGameType(Remote) cm.SetIsMatched(true) cm.SetIsMatchmaking(false) cm.remoteMatchModel.endRemoteGameChan = make(chan bool, 0) cm.viewSetMatchControls() if cm.backendType == WebsocketBackend { err := cm.wsConnect() if err != nil { cm.SetIsMatched(false) cm.SetIsMatchmaking(false) cm.resetGame() } else { go cm.matchDetailsUpdateLoop() } } else if cm.backendType == HttpBackend { go cm.matchDetailsUpdateLoop() go cm.listenForSyncUpdateHttp() go cm.listenForAsyncUpdateHttp() } } func (cm *ClientModel) httpMatch() error { _, err := retryWrapper( func() (*http.Response, error) { pathname := js.Global().Get("location").Get("pathname").String() return cm.client.Get(pathname + "http/match") }, "http/match", 200, func() { cm.SetIsMatchmaking(false) cm.GetButtonLoader().Call("remove") }, ) if err != nil { return err } return nil } func (cm *ClientModel) wsMatch() error { var err error if cm.GetWSConn().Equal(js.Undefined()) { err = cm.wsConnect() } if err == nil { message := matchserver.WebsocketRequest{ WebsocketRequestType: matchserver.RequestAsyncT, RequestAsync: matchserver.RequestAsync{Match: true}, } jsonMsg, _ := json.Marshal(message) cm.GetWSConn().Call("send", string(jsonMsg)) } else { cm.SetIsMatchmaking(false) cm.GetButtonLoader().Call("remove") } return err } func (cm *ClientModel) wsConnect() error { pathname := js.Global().Get("location").Get("pathname").String() scheme := "ws" if cm.tls { scheme = "wss" } u := scheme + "://" + cm.origin + pathname + "ws" ws := js.Global().Get("WebSocket").New(u) retries := 0 maxRetries := 100 for true { if ws.Get("readyState").Equal(js.Global().Get("WebSocket").Get("OPEN")) { cm.SetWSConn(ws) if debug { log.Println("Websocket connection successfully initiated") go cm.wsListener() } return nil } time.Sleep(100 * time.Millisecond) retries++ if retries > maxRetries { log.Println("ERROR: Error opening websocket connection") return errors.New("Error opening websocket connection") } } return nil } func (cm *ClientModel) wsListener() { ws := cm.GetWSConn() ws.Set("onmessage", js.FuncOf(func(this js.Value, args []js.Value) interface{} { jsonString := args[0].Get("data").String() if debug { log.Println(jsonString) } message := matchserver.WebsocketResponse{} json.Unmarshal([]byte(jsonString), &message) switch message.WebsocketResponseType { case matchserver.OpponentPlayedMoveT: cm.handleSyncUpdate(message.OpponentPlayedMove) case matchserver.ResponseSyncT: cm.handleResponseSync(message.ResponseSync) case matchserver.ResponseAsyncT: cm.handleResponseAsync(message.ResponseAsync) } return nil })) } func (cm *ClientModel) matchDetailsUpdateLoop() { for true { cm.viewSetMatchDetails() time.Sleep(100 * time.Millisecond) select { case <-cm.remoteMatchModel.endRemoteGameChan: return default: } turn := cm.game.Turn() cm.AddPlayerElapsedMs(turn, 100) } } func (cm *ClientModel) getEventMousePosition(event js.Value) ( int, int, int, int, int, int) { rect := cm.board.Call("getBoundingClientRect") width := rect.Get("right").Int() - rect.Get("left").Int() height := rect.Get("bottom").Int() - rect.Get("top").Int() squareWidth := width / 8 squareHeight := height / 8 x := event.Get("clientX").Int() - rect.Get("left").Int() gridX := x / squareWidth if x > width || gridX > 7 { x = width gridX = 7 } else if x < 0 || gridX < 0 { x = 0 gridX = 0 } y := event.Get("clientY").Int() - rect.Get("top").Int() gridY := y / squareHeight if y > height || gridY > 7 { y = height gridY = 7 } else if y < 0 || gridY < 0 { y = 0 gridY = 0 } return x, y, squareWidth, squareHeight, gridX, gridY } // To flip black to be on the bottom we do two things, everything is flipped // in the view (see getPositionClass), and everything is flipped onClick here. func (cm *ClientModel) getPositionFromGrid( gridX uint8, gridY uint8) model.Position { if cm.GetPlayerColor() == model.White { return model.Position{uint8(gridX), uint8(7 - gridY)} } else { return model.Position{uint8(7 - gridX), uint8(gridY)} } } func preventDefault(this js.Value, i []js.Value) interface{} { if len(i) > 0 { i[0].Call("preventDefault") } return 0 } func (cm *ClientModel) resetGame() { game := model.NewGame() cm.SetGame(game) cm.viewClearBoard() cm.viewInitBoard(cm.playerColor) } func (cm *ClientModel) resetGameWithInProgressGame( match gateway.CurrentMatch) { game := model.NewCustomGame(match.Board, match.BlackKing, match.WhiteKing, match.PositionHistory, match.BlackPieces, match.WhitePieces, match.Turn, match.GameOver, match.Result, match.PreviousMove, match.PreviousMover, match.TurnsSinceCaptureOrPawnMove) cm.SetGame(game) cm.viewClearBoard() cm.viewInitBoard(cm.playerColor) } func retryWrapper(f func() (*http.Response, error), uri string, successCode int, onMaxRetries func()) (*http.Response, error) { retries := 0 maxRetries := 5 for true { resp, err := f() if err != nil || (resp.StatusCode != successCode && successCode != 0) { log.Println(err) time.Sleep(500 * time.Millisecond) retries++ if retries >= maxRetries { log.Printf("Reached maxRetries on uri=%s retries=%d", uri, maxRetries) onMaxRetries() return nil, err } } else { return resp, nil } } return nil, nil } func (cm *ClientModel) remoteGameEnd() { select { case <-cm.remoteMatchModel.endRemoteGameChan: return default: close(cm.remoteMatchModel.endRemoteGameChan) cm.viewSetGameOver("", "error") } }
package main import "fmt" func main() { // function map1() map2() } func map1() { // map คล้าย dict ใน python x := make(map[string]string) x["TH"] = "Thailand" x["JP"] = "Japan" x["EN"] = "England" fmt.Println(x["TH"]) } func map2() { y := map[string]string{ "TH": "Thailand", "JP": "Japan", } fmt.Println(y) }
// The MIT License (MIT) // // Copyright (c) 2016 Aya Tokikaze // // 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 main import ( "bufio" "fmt" "os" "strings" flags "github.com/jessevdk/go-flags" ) const ( cliName = "oui" cliDescription = "search vender information for OUI(Organizationally Unique Identifier)" version = "v0.3.0-dev" ) // MAC stract is MAC Address date format type MAC struct { Registry string Hex string OrgName string OrgAddress string } // list options type Options struct { Verbose bool `short:"v" long:"verbose" description:"print detailed information"` Input bool `short:"i" long:"input" description:"use standard input"` Version bool `long:"version" description:"print oui version"` Org bool `short:"o" long:"org" description:"search organization to OUI"` } func main() { var opt Options var mac string var res MAC sc := bufio.NewScanner(os.Stdin) f := flags.NewParser(&opt, flags.Default) f.Name = "oui" f.Usage = "<ADDRESS> [OPTION]" args, _ := f.Parse() if opt.Version { fmt.Printf("%s version %s\n", cliName, version) os.Exit(0) } if len(args) == 0 { if os.Args[1] == "-h" { os.Exit(0) } if !opt.Input { f.WriteHelp(os.Stdout) os.Exit(1) } } data := InitMalData() if opt.Input && sc.Scan() { mac = sc.Text() } else { mac = args[0] } mac = strings.Replace(mac, ":", "", -1) mac = strings.Replace(mac, "-", "", -1) if opt.Org { for i := range data { if strings.Contains(strings.ToUpper(data[i].OrgName), strings.ToUpper(args[0])) { fmt.Printf("%s:%s:%s %s\n", data[i].Hex[0:2], data[i].Hex[2:4], data[i].Hex[4:6], data[i].OrgName) } } os.Exit(0) } for i := range data { if data[i].Hex == strings.ToUpper(mac[0:6]) { res = data[i] break } } if opt.Verbose { split := []string{mac[0:2], mac[2:4], mac[4:6]} fmt.Printf("OUI/%s : %s\n", res.Registry, strings.Join(split, "-")) fmt.Printf("Organization : %s\n", res.OrgName) fmt.Printf("Address : %s\n", res.OrgAddress) } else { fmt.Println(res.OrgName) } }
package main import ( "bufio" "compress/gzip" "crypto/sha256" "encoding/hex" "fmt" "hash/fnv" "log" "net/http" "os" "path" "strings" ) const ( entries = 10000 shaSuffix = ".sha256" ) var stories = map[uint32]string{} func handler(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { fmt.Fprintf(w, `<html> <title>Fake content with sha</title> <p>This site generates fake content based deterministically based on the URL. It also serves ".sha256sum" files based on that content.</p> <p>The content has been generated with <a href="github.com/mb-14/gomarkov">github.com/mb-14/gomarkov</a></p> <p>The sources for this tool is available at <a href="http://github.com/mkmik/fakesha">http://github.com/mkmik/fakesha</a></p> `) return } ext := path.Ext(r.URL.Path) base := strings.TrimSuffix(r.URL.Path, shaSuffix) n := hash(base) s := stories[n] if ext == shaSuffix { h := sha256.New() fmt.Fprintln(h, s) x := hex.NewEncoder(w) fmt.Fprintf(x, "%s", h.Sum(nil)) fmt.Fprintf(w, " %s\n", path.Base(base)) } else { fmt.Fprintln(w, s) } } func hash(s string) uint32 { h := fnv.New32a() h.Write([]byte(s)) return h.Sum32() % entries } func load() error { f, err := os.Open("stories.txt.gz") if err != nil { return err } g, err := gzip.NewReader(f) if err != nil { return err } scanner := bufio.NewScanner(g) for scanner.Scan() { s := scanner.Text() n := hash(s) stories[n] = s } if err := scanner.Err(); err != nil { log.Fatal(err) } return nil } func main() { if err := load(); err != nil { log.Fatal(err) } http.HandleFunc("/", handler) port := os.Getenv("PORT") if port == "" { port = "8080" } log.Printf("Listening on port %s\n", port) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil)) }
package main import ( "fmt" ) func main() { //<<<<<<< HEAD //<<<<<<< HEAD // fmt.Println("Hello, world and world") fmt.Println("Прывитанне КРАИНА") //<<<<<<< HEAD fmt.Println("Привет МИР!") //======= fmt.Println("привет мир!") fmt.Println("Merhaba, Baris!") //>>>>>>> feature //======= fmt.Println("HELLO, WORLD!!!") //>>>>>>> hotfix //======= fmt.Println("HELLO, WORLD!") //>>>>>>> hotfix2 fmt.Println("ZERO") } //relase 1.0
// Copyright 2020 MongoDB Inc // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build e2e atlas,metrics package atlas_test import ( "encoding/json" "os" "os/exec" "testing" "github.com/mongodb/go-client-mongodb-atlas/mongodbatlas" ) func TestMetrics(t *testing.T) { const metricsEntity = "metrics" clusterName, err := deployCluster() if err != nil { t.Fatalf("unexpected error: %v", err) } hostname, err := getHostnameAndPort() if err != nil { t.Fatalf("unexpected error: %v", err) } cliPath, err := cli() if err != nil { t.Fatalf("unexpected error: %v", err) } t.Run("processes", func(t *testing.T) { cmd := exec.Command(cliPath, atlasEntity, metricsEntity, "processes", hostname, "--granularity=PT30M", "--period=P1DT12H") cmd.Env = os.Environ() resp, err := cmd.CombinedOutput() if err != nil { t.Fatalf("unexpected error: %v", err) } metrics := &mongodbatlas.ProcessMeasurements{} err = json.Unmarshal(resp, &metrics) if err != nil { t.Fatalf("unexpected error: %v", err) } if metrics.Measurements == nil { t.Errorf("there are no measurements") } if len(metrics.Measurements) == 0 { t.Errorf("got=%#v\nwant=%#v\n", 0, "len(metrics.Measurements) > 0") } }) t.Run("databases list", func(t *testing.T) { cmd := exec.Command(cliPath, atlasEntity, metricsEntity, "databases", "list", hostname) cmd.Env = os.Environ() resp, err := cmd.CombinedOutput() if err != nil { t.Fatalf("unexpected error: %v", err) } databases := &mongodbatlas.ProcessDatabasesResponse{} err = json.Unmarshal(resp, &databases) if err != nil { t.Fatalf("unexpected error: %v", err) } if databases.TotalCount != 2 { t.Errorf("got=%#v\nwant=%#v\n", databases.TotalCount, 2) } }) t.Run("disks list", func(t *testing.T) { cmd := exec.Command(cliPath, atlasEntity, metricsEntity, "disks", "list", hostname) cmd.Env = os.Environ() resp, err := cmd.CombinedOutput() if err != nil { t.Fatalf("unexpected error: %v", err) } disks := &mongodbatlas.ProcessDisksResponse{} err = json.Unmarshal(resp, &disks) if err != nil { t.Fatalf("unexpected error: %v", err) } if disks.TotalCount != 1 { t.Errorf("got=%#v\nwant=%#v\n", disks.TotalCount, 1) } }) t.Run("disks describe", func(t *testing.T) { cmd := exec.Command(cliPath, atlasEntity, metricsEntity, "disks", "describe", hostname, "data", "--granularity=PT30M", "--period=P1DT12H") cmd.Env = os.Environ() resp, err := cmd.CombinedOutput() if err != nil { t.Fatalf("unexpected error: %v", err) } metrics := &mongodbatlas.ProcessDiskMeasurements{} err = json.Unmarshal(resp, &metrics) if err != nil { t.Fatalf("unexpected error: %v", err) } if metrics.Measurements == nil { t.Errorf("there are no measurements") } if len(metrics.Measurements) == 0 { t.Errorf("got=%#v\nwant=%#v\n", 0, "len(metrics.Measurements) > 0") } }) if err := deleteCluster(clusterName); err != nil { t.Fatalf("unexpected error: %s", err) } }
package main import ( "crypto/hmac" "crypto/sha512" "encoding/base64" "encoding/hex" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "golang.org/x/crypto/scrypt" ) type Status struct { Code int `json:"code"` Name string `json:"name"` Desc string `json:"desc"` Fields map[string]string `json:"fields"` } type GetSaltResult struct { Status `json:"status"` Salt string `json:"salt"` CSRFToken string `json:"csrf_token"` LoginSession string `json:"login_session"` } func main() { var urlString string var url *url.URL email := "MyEmail" password := []byte("MyPassword") // Get Salt urlString = "https://keybase.io/_/api/1.0/getsalt.json" url, _ = url.Parse(urlString) q := url.Query() q.Set("email_or_username", email) url.RawQuery = q.Encode() resp, _ := http.Get(url.String()) result := &GetSaltResult{} decoder := json.NewDecoder(resp.Body) _ = decoder.Decode(result) // crypto salt, _ := hex.DecodeString(result.Salt) loginSession, _ := base64.StdEncoding.DecodeString(result.LoginSession) skey, _ := scrypt.Key(password, salt, 32768, 8, 1, 224) pwh := skey[192:224] mac := hmac.New(sha512.New, loginSession) mac.Write(pwh) // Login urlString = "https://keybase.io/_/api/1.0/login.json" url, _ = url.Parse(urlString) q = url.Query() q.Set("email_or_username", email) q.Set("hmac_pwh", hex.EncodeToString(mac.Sum(nil))) q.Set("login_session", base64.StdEncoding.EncodeToString(loginSession)) q.Set("csrf_token", result.CSRFToken) resp, _ = http.PostForm(url.String(), q) contents, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(contents)) }
package api import ( "database/sql" "fmt" "net/http" "strconv" "time" "github.com/arxdsilva/olist/record" "github.com/arxdsilva/olist/bill" "github.com/labstack/echo" ) // Bill calculates a specific bill of a subscriber // If a month is not specified, It'll be the last // closed month // month and year are strings of integers // Responses: // 200 OK // 400 Bad Request // 500 Internal Server Error func (s *Server) Bill(c echo.Context) (err error) { sub := c.Param("subscriber") month := c.QueryParam("month") year := c.QueryParam("year") if (month == "") || (year == "") { if m := int(time.Now().Month()); m == 1 { month = "12" year = string(strconv.Itoa(time.Now().Year() - 1)) } else { month = string(strconv.Itoa(int(time.Now().Month() - 1))) year = string(strconv.Itoa(time.Now().Year())) } } bill := bill.New(month, year, sub) storedBill, err := s.Storage.BillFromID(bill.ID) // bill already exists if err == nil { calls, err := s.Storage.CallsFromBillID(storedBill.ID) if err != nil { return echo.NewHTTPError(http.StatusInternalServerError, err.Error()) } storedBill.Calls = calls return c.JSON(http.StatusOK, storedBill) } if err != sql.ErrNoRows { return echo.NewHTTPError(http.StatusBadRequest, err.Error()) } // create new bill records, err := s.Storage.RecordsFromBill(bill) if err != nil { return echo.NewHTTPError(http.StatusInternalServerError, err.Error()) } m, err := strconv.Atoi(month) if err != nil { return echo.NewHTTPError(http.StatusBadRequest, err.Error()) } bill.ID = fmt.Sprintf("%s%v%s", sub, month, year) calls, err := callsFromRecords(records, m, bill.ID) if err != nil { return echo.NewHTTPError(http.StatusInternalServerError, err.Error()) } bill.Calls = calls err = s.Storage.SaveCalls(calls) if err != nil { return echo.NewHTTPError(http.StatusInternalServerError, err.Error()) } bill.CalculateTotalPrice() err = s.Storage.SaveBill(bill) if err != nil { return echo.NewHTTPError(http.StatusInternalServerError, err.Error()) } return c.JSON(http.StatusOK, bill) } func callsFromRecords(rs []record.Record, monthOfReference int, billID string) (cs []bill.Call, err error) { f := filterRecordsPeriod(rs, monthOfReference) for _, v := range f { c, errC := callFromRecords(v) if errC != nil { return nil, errC } c.BillID = billID cs = append(cs, c) } return } func callFromRecords(rs []record.Record) (c bill.Call, err error) { buff := make(map[string]record.Record) for _, v := range rs { buff[v.Type] = v } startTime, err := time.Parse(time.RFC3339, buff["start"].TimeStamp) if err != nil { return } endTime, err := time.Parse(time.RFC3339, buff["end"].TimeStamp) if err != nil { return } price, err := bill.Calculate(startTime, endTime) if err != nil { return } duration := endTime.Sub(startTime) c.CallPrice = price c.CallStartDate = startTime.Day() c.Destination = buff["start"].Destination c.CallStartTime = startTime.Format(time.Kitchen) c.CallDuration = duration.String() return } func filterRecordsPeriod(rs []record.Record, monthOfReference int) (rFiltered map[string][]record.Record) { rFiltered = make(map[string][]record.Record) recordsMap := make(map[string][]record.Record) for _, r := range rs { recordsMap[r.CallID] = append(recordsMap[r.CallID], r) } for k, v := range recordsMap { if (v[0].Type == "end") && (v[0].Month == monthOfReference) { rFiltered[k] = append(rFiltered[k], v[0]) rFiltered[k] = append(rFiltered[k], v[1]) } else if (v[1].Type == "end") && (v[1].Month == monthOfReference) { rFiltered[k] = append(rFiltered[k], v[0]) rFiltered[k] = append(rFiltered[k], v[1]) } } return }
package cli import ( "fmt" "github.com/DataDrake/cli-ng/v2/cmd" p2p "github.com/notassigned/p2p-tools/libp2p" "github.com/sirupsen/logrus" ) var Provide = cmd.Sub{ Name: "provide", Alias: "pvd", Short: "Advertise content on the DHT", Args: &ProvideArgs{}, Run: ProvideRun, } type ProvideArgs struct { Key string `desc:"String to advertise on the DHT"` } func ProvideRun(r *cmd.Root, c *cmd.Sub) { if r.Flags.(*GlobalFlags).Log { logrus.SetLevel(logrus.DebugLevel) } node := p2p.NewP2P() fmt.Println("Node ID:", node.Host.ID().Pretty()) fmt.Println("Providing", c.Args.(*ProvideArgs).Key) node.Advertise(c.Args.(*ProvideArgs).Key) select {} //wait forever }
/* Copyright © 2021 SUSE 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 platform import ( "fmt" "net" "os/exec" "regexp" "strings" "github.com/Microsoft/go-winio" "github.com/linuxkit/virtsock/pkg/hvsock" ) // DefaultEndpoint is the platform-specific location that dockerd listens on by // default. const DefaultEndpoint = "npipe:////./pipe/docker_engine" // ErrListenerClosed is the error that is returned when we attempt to call // Accept() on a closed listener. var ErrListenerClosed = winio.ErrPipeListenerClosed // MakeDialer computes the dial function. func MakeDialer(port uint32) (func() (net.Conn, error), error) { vmGuid, err := probeVMGUID(port) if err != nil { return nil, fmt.Errorf("could not detect WSL2 VM: %w", err) } dial := func() (net.Conn, error) { conn, err := dialHvsock(vmGuid, port) if err != nil { return nil, err } return conn, nil } return dial, nil } // dialHvsock creates a net.Conn to a Hyper-V VM running Linux with the given // GUID, listening on the given vsock port. func dialHvsock(vmGuid hvsock.GUID, port uint32) (net.Conn, error) { // go-winio doesn't implement DialHvsock(), but luckily LinuxKit has an // implementation. We still need go-winio to convert port to GUID. svcGuid, err := hvsock.GUIDFromString(winio.VsockServiceID(port).String()) if err != nil { return nil, fmt.Errorf("could not parse Hyper-V service GUID: %w", err) } addr := hvsock.Addr{ VMID: vmGuid, ServiceID: svcGuid, } conn, err := hvsock.Dial(addr) if err != nil { return nil, fmt.Errorf("could not dial Hyper-V socket: %w", err) } return conn, nil } // Listen on the given Windows named pipe endpoint. func Listen(endpoint string) (net.Listener, error) { const prefix = "npipe://" if !strings.HasPrefix(endpoint, prefix) { return nil, fmt.Errorf("endpoint %s does not start with protocol %s", endpoint, prefix) } listener, err := winio.ListenPipe(endpoint[len(prefix):], nil) if err != nil { return nil, fmt.Errorf("could not listen on %s: %w", endpoint, err) } return listener, nil } // ParseBindString parses a HostConfig.Binds entry, returning the (<host-src> or // <volume-name>), <container-dest>, and (optional) <options>. Additionally, it // also returns a boolean indicating if the first argument is a host path. func ParseBindString(input string) (string, string, string, bool) { // Windows names can be one of a few things: // C:\foo\bar colon is possible after the drive letter // \\?\C:\foo\bar colon is possible after the drive letter // \\server\share\foo no colons are allowed // \\.\pipe\foo no colons are allowed // Luckily, we only have Linux dockerd, so we only have to worry about // Windows-style paths (that may contain colons) in the first part. // pathPattern is a RE for the first two options above. pathPattern := regexp.MustCompile(`^(?:\\\\\?\\)?.:[^:]*`) match := pathPattern.FindString(input) if match == "" { // The first part is a volume name, a pipe, or other non-path thing. firstIndex := strings.Index(input, ":") lastIndex := strings.LastIndex(input, ":") if firstIndex == lastIndex { return input[:firstIndex], input[firstIndex+1:], "", false } return input[:firstIndex], input[firstIndex+1 : lastIndex], input[lastIndex+1:], false } else { // The first part is a path. rest := input[len(match)+1:] index := strings.LastIndex(rest, ":") if index > -1 { return match, rest[:index], rest[index+1:], true } return match, rest, "", true } } func isSlash(input string, indices ...int) bool { for _, i := range indices { if len(input) <= i || (input[i] != '/' && input[i] != '\\') { return false } } return true } func IsAbsolutePath(input string) bool { if len(input) > 2 && input[1] == ':' && isSlash(input, 2) { // C:\ return true } if len(input) > 6 && isSlash(input, 0, 1, 3) && input[2] == '?' && input[5] == ':' { // \\?\C:\ return true } return false } // TranslatePathFromClient converts a client path to a path that can be used by // the docker daemon. func TranslatePathFromClient(windowsPath string) (string, error) { // TODO: See if we can do something faster than shelling out. cmd := exec.Command("wsl", "--distribution", "rancher-desktop", "--exec", "/bin/wslpath", "-a", "-u", windowsPath) output, err := cmd.Output() if err != nil { return "", fmt.Errorf("error getting WSL path: %w", err) } return strings.TrimSpace(string(output)), nil }
package store import ( "time" ) type Transaction struct { ID string `sql:"type:uuid"` AccountID string `sql:"type:uuid,notnull"` Account *Account Amount int32 `sql:",notnull"` Title string `sql:",notnull"` OriginalTitle string `sql:",notnull"` Description string `sql:",notnull"` CategoryID *string `sql:"type:uuid"` Category *Category Date time.Time `sql:",notnull"` TransactionType string `sql:",notnull"` CreatedAt time.Time `sql:",notnull"` UpdatedAt time.Time `sql:",notnull"` }
//go:generate mockery -dir . -name PaymentConfigReader -output ./mocks -filename config_reader.go package datastore import ( "context" "github.com/imrenagi/go-payment/subscription" "github.com/imrenagi/go-payment" "github.com/imrenagi/go-payment/config" "github.com/imrenagi/go-payment/gateway/midtrans" "github.com/imrenagi/go-payment/invoice" ) // MidtransTransactionStatusRepository is an interface for // the storage of midtrans transaction status. type MidtransTransactionStatusRepository interface { Save(ctx context.Context, status *midtrans.TransactionStatus) error FindByOrderID(ctx context.Context, orderID string) (*midtrans.TransactionStatus, error) } // InvoiceRepository is an interface for invoice storage type InvoiceRepository interface { FindByNumber(ctx context.Context, number string) (*invoice.Invoice, error) Save(ctx context.Context, invoice *invoice.Invoice) error } // PaymentConfigReader is interface for reading payment configuration type PaymentConfigReader interface { FindByPaymentType(ctx context.Context, paymentType payment.PaymentType, opts ...payment.Option) (config.FeeConfigReader, error) FindAll(ctx context.Context) (*config.PaymentConfig, error) } // SubscriptionRepository is an interface for subscription store type SubscriptionRepository interface { Save(ctx context.Context, subs *subscription.Subscription) error FindByNumber(ctx context.Context, number string) (*subscription.Subscription, error) }
package carbon import ( "fmt" uuid "github.com/satori/go.uuid" "github.com/stretchr/testify/assert" "github.com/teploff/otus/hw_6/utils" "io/ioutil" "os" "testing" ) var workDirectoryPath, _ = os.Getwd() // TestCase checking invalid passed limit & offset arguments func TestIncorrectInput(t *testing.T) { srcUUID := uuid.NewV4() destUUID := uuid.NewV4() srcFilePath := fmt.Sprintf(workDirectoryPath+"/%s", srcUUID) destFilePath := fmt.Sprintf(workDirectoryPath+"/%s", destUUID) inputData := []struct { src, dest string offset, limit int64 }{ {srcFilePath, destFilePath, 0, -5}, {srcFilePath, destFilePath, -5, 0}, } for _, data := range inputData { _, err := NewCarbon(data.src, data.dest, data.offset, data.limit) assert.Error(t, err) assert.Equal(t, errorInvalidValue, err) } } // TestCase checking that source file doesn't exist func TestSrsFileNotFound(t *testing.T) { srcUUID := uuid.NewV4() destUUID := uuid.NewV4() srcFilePath := fmt.Sprintf(workDirectoryPath+"/%s", srcUUID) destFilePath := fmt.Sprintf(workDirectoryPath+"/%s", destUUID) offset := int64(0) limit := int64(10) _, err := NewCarbon(srcFilePath, destFilePath, offset, limit) assert.Error(t, err) } // TestCase checking that all source file payload is copied func TestCopyAllPayload(t *testing.T) { srcUUID := uuid.NewV4() destUUID := uuid.NewV4() srcFilePath := fmt.Sprintf(workDirectoryPath+"/%s", srcUUID) destFilePath := fmt.Sprintf(workDirectoryPath+"/%s", destUUID) srcPayload := []byte("some bytes") err := utils.WriteFile(srcFilePath, srcPayload) assert.NoError(t, err) c, err := NewCarbon(srcFilePath, destFilePath, 0, 0) assert.NoError(t, err) err = c.Copy() copyPayload, err := ioutil.ReadFile(destFilePath) // прочитать весь файл по имени assert.NoError(t, err) assert.Equal(t, srcPayload, copyPayload) _ = os.Remove(srcFilePath) _ = os.Remove(destFilePath) } // TestCase checking that empty file is copied to another func TestCopyAllPayloadFromEmptyFile(t *testing.T) { srcUUID := uuid.NewV4() destUUID := uuid.NewV4() srcFilePath := fmt.Sprintf(workDirectoryPath+"/%s", srcUUID) destFilePath := fmt.Sprintf(workDirectoryPath+"/%s", destUUID) srcPayload := []byte("") _ = utils.WriteFile(srcFilePath, srcPayload) c, err := NewCarbon(srcFilePath, destFilePath, 0, 5) assert.NoError(t, err) err = c.Copy() assert.NoError(t, err) copyPayload, err := ioutil.ReadFile(destFilePath) // прочитать весь файл по имени assert.NoError(t, err) assert.Equal(t, srcPayload, copyPayload) _ = os.Remove(srcFilePath) _ = os.Remove(destFilePath) } // TestCase checking that all source file payload is copied with unit offset func TestCopyWithUnitOffset(t *testing.T) { srcUUID := uuid.NewV4() destUUID := uuid.NewV4() srcFilePath := fmt.Sprintf(workDirectoryPath+"/%s", srcUUID) destFilePath := fmt.Sprintf(workDirectoryPath+"/%s", destUUID) srcPayload := []byte("1234567890") _ = utils.WriteFile(srcFilePath, srcPayload) c, err := NewCarbon(srcFilePath, destFilePath, 1, 10) assert.NoError(t, err) err = c.Copy() assert.NoError(t, err) copyPayload, err := ioutil.ReadFile(destFilePath) // прочитать весь файл по имени assert.NoError(t, err) assert.Equal(t, []byte("234567890"), copyPayload) _ = os.Remove(srcFilePath) _ = os.Remove(destFilePath) } // TestCase checking that all source file payload is copied with offset func TestCopyWithOffset(t *testing.T) { srcUUID := uuid.NewV4() destUUID := uuid.NewV4() srcFilePath := fmt.Sprintf(workDirectoryPath+"/%s", srcUUID) destFilePath := fmt.Sprintf(workDirectoryPath+"/%s", destUUID) srcPayload := []byte("12345678901234567890123456789012345678901234567890") _ = utils.WriteFile(srcFilePath, srcPayload) c, err := NewCarbon(srcFilePath, destFilePath, 10, 0) assert.NoError(t, err) err = c.Copy() assert.NoError(t, err) copyPayload, err := ioutil.ReadFile(destFilePath) // прочитать весь файл по имени assert.NoError(t, err) assert.Equal(t, []byte("1234567890123456789012345678901234567890"), copyPayload) _ = os.Remove(srcFilePath) _ = os.Remove(destFilePath) }
package handler import ( "encoding/json" "time" "github.com/gorilla/websocket" "github.com/sirupsen/logrus" ) const ( // Time allowed to write a message to the peer. writeWait = 10 * time.Second // Time allowed to read the next pong message from the peer. pongWait = 60 * time.Second // Send pings to peer with this period. Must be less than pongWait. pingPeriod = (pongWait * 9) / 10 // Maximum message size allowed from peer. maxMessageSize = 1024 * 1024 // Max room size maxRoomSize = 100 ) // Client is a middleman between the websocket connection and the hub. type Client struct { hub *Hub // Identity id string // The websocket connection. conn *websocket.Conn // Buffered channel of outbound messages. send chan []byte // Room channel event rchan chan wsRoomActionMessage // Room rooms []string // Logger logger *logrus.Logger } // remove every message and shutdown after 1 minutes func (c *Client) clean() { c.rooms = nil close(c.send) close(c.rchan) } // roomPump pumps action for channel and process one by one func (c *Client) roomPump() { for msg := range c.rchan { if msg.Join { for i := 0; i < len(msg.Ids); i++ { id := msg.Ids[i] c.join(id) } } if msg.Leave { for i := 0; i < len(msg.Ids); i++ { id := msg.Ids[i] c.leave(id) } } } } // readPump pumps messages from the websocket connection to the hub. // // The application runs readPump in a per-connection goroutine. The application // ensures that there is at most one reader on a connection by executing all // reads from this goroutine. func (c *Client) readPump() { defer func() { c.hub.unregister <- c c.conn.Close() }() c.conn.SetReadLimit(maxMessageSize) c.conn.SetReadDeadline(time.Now().Add(pongWait)) c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil }) for { _, message, err := c.conn.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { c.logger.Error(err) } break } go c.processMsg(message) } } // writePump pumps messages from the hub to the websocket connection. // // A goroutine running writePump is started for each connection. The // application ensures that there is at most one writer to a connection by // executing all writes from this goroutine. func (c *Client) writePump() { ticker := time.NewTicker(pingPeriod) defer func() { ticker.Stop() c.conn.Close() }() for { select { case message, ok := <-c.send: c.conn.SetWriteDeadline(time.Now().Add(writeWait)) if !ok { // The hub closed the channel. c.conn.WriteMessage(websocket.CloseMessage, []byte{}) return } if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil { return } case <-ticker.C: c.conn.SetWriteDeadline(time.Now().Add(writeWait)) if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil { return } } } } func (c *Client) welcome() { welMsg := wsWelcomeMessage{ ClientId: c.id, } b, _ := json.Marshal(welMsg) msg := wsMessage{ Type: "welcome", Raw: b, } b, _ = json.Marshal(msg) c.broadcastMsg(b) } func (c *Client) join(roomId string) { n := len(c.rooms) joined := false for i := 0; i < n; i++ { if c.rooms[i] == roomId { joined = true } } if !joined { c.rooms = append(c.rooms, roomId) } } func (c *Client) leave(roomId string) { n := len(c.rooms) r := make([]string, 0) for i := 0; i < n; i++ { if c.rooms[i] != roomId { r = append(r, c.rooms[i]) } } c.rooms = r } func (c *Client) exist(roomId string) bool { n := len(c.rooms) for i := 0; i < n; i++ { if c.rooms[i] == roomId { return true } } return false } func (c *Client) sendMsg(message []byte) { c.hub.directMsg <- wsDirectMessage{ c: c, message: message, } } func (c *Client) sendMsgToRoom(roomId string, message []byte) { c.hub.sendMsgToRoom(roomId, message) } func (c *Client) broadcastMsg(msg []byte) { c.hub.broadcastMsg(msg) } func (c *Client) sendIdentityMsg() { clientId := wsIdentityMessage{ ClientId: c.id, } b, _ := json.Marshal(clientId) msg := wsMessage{ Type: msgIdentity, Raw: b, } b, _ = json.Marshal(msg) go c.sendMsg(b) } func (c *Client) processRoomActionMsg(message wsMessage) { rMsg := wsRoomActionMessage{} if err := json.Unmarshal(message.Raw, &rMsg); err != nil { return } if message.Type == msgJoinRoom { rMsg.Join = true } if message.Type == msgLeaveRoom { rMsg.Leave = true } // process leave/join c.rchan <- rMsg // prepare message to send to each group rMsg.MemberId = c.id msgType := msgJoinRoom if rMsg.Leave { msgType = msgLeaveRoom } // Loop and send mesage for each room for _, roomId := range rMsg.Ids { rMsg.Ids = []string{roomId} b, _ := json.Marshal(rMsg) m := wsMessage{ Type: msgType, Raw: b, } r, _ := json.Marshal(&m) c.sendMsgToRoom(roomId, r) // if message type is leave, emit to this guy if msgType == msgLeaveRoom { c.sendMsg(r) } } } func (c *Client) processChatMsg(message []byte) { for _, roomId := range c.rooms { if roomId != c.id { go c.sendMsgToRoom(roomId, message) } } } func (c *Client) processOfferMsg(msg wsMessage) { offer := wsOfferMessage{} if err := json.Unmarshal(msg.Raw, &offer); err != nil { c.logger.Error(err) return } targetId := offer.TargetID offer.TargetID = c.id b, _ := json.Marshal(offer) m := wsMessage{ Type: "offer", Raw: b, } b, _ = json.Marshal(m) c.sendMsgToRoom(targetId, b) } func (c *Client) processAnswerMsg(msg wsMessage) { answer := wsAnswerMessage{} if err := json.Unmarshal(msg.Raw, &answer); err != nil { c.logger.Error(err) return } targetId := answer.TargetID answer.TargetID = c.id b, _ := json.Marshal(answer) m := wsMessage{ Type: "answer", Raw: b, } b, _ = json.Marshal(m) c.sendMsgToRoom(targetId, b) } func (c *Client) processIceCandidateMsg(msg wsMessage) { candidate := wsIceCandidateMessage{} if err := json.Unmarshal(msg.Raw, &candidate); err != nil { c.logger.Error(err) return } targetId := candidate.TargetID candidate.TargetID = c.id b, _ := json.Marshal(candidate) m := wsMessage{ Type: "icecandidate", Raw: b, } b, _ = json.Marshal(m) c.sendMsgToRoom(targetId, b) } func (c *Client) processJoinVideoCallMsg(msg wsMessage) { j := wsJoinRoomVideoCallMessage{} if err := json.Unmarshal(msg.Raw, &j); err != nil { c.logger.Error(err) return } j.MemberId = c.id b, _ := json.Marshal(wsJoinRoomVideoCallMessage{ RoomId: j.RoomId, MemberId: c.id, }) b, _ = json.Marshal(wsMessage{ Type: msgJoinRoomVideoCall, Raw: b, }) c.sendMsgToRoom(j.RoomId, b) } // process message from readPump func (c *Client) processMsg(message []byte) { msg := wsMessage{} if err := json.Unmarshal(message, &msg); err != nil { c.logger.Error(err) return } // Handle chat message, broadcast room if msg.Type == msgChat { c.processChatMsg(message) } // Handle room action if msg.Type == msgJoinRoom || msg.Type == msgLeaveRoom { c.processRoomActionMsg(msg) } // Handle join room video call if msg.Type == msgJoinRoomVideoCall { c.processJoinVideoCallMsg(msg) } // Handle RTC message if msg.Type == msgOffer { c.processOfferMsg(msg) } if msg.Type == msgAnswer { c.processAnswerMsg(msg) } if msg.Type == msgIceCandidate { c.processIceCandidateMsg(msg) } }
package main import ( "encoding/csv" "io" "loger" "os" "reflect" "strconv" ) type StaticData interface { GetPathName() string //! 获取路径名 GetName() string //!获取命名 } type StaticDataMgr struct { csvLst map[string]StaticData } func (self *StaticDataMgr) Init() { self.csvLst = make(map[string]StaticData) } func (self *StaticDataMgr) Add(data StaticData) { self.csvLst[data.GetName()] = data } func CloneType(obj interface{}) interface{} { newObj := reflect.New(reflect.TypeOf(obj).Elem()).Elem() return newObj.Addr().Interface() } func (self *StaticDataMgr) Parse() { for _, v := range self.csvLst { file, err := os.Open(v.GetPathName()) if err != nil { loger.Fatal("open csv file failed. Error: %s", err.Error()) } reader := csv.NewReader(file) lineNumber := 0 for { record, err := reader.Read() if err != nil { if err == io.EOF { break } loger.Fatal("read csv error. Error: %s", err.Error()) } if lineNumber > 0 { //! 创建一个新的无值结构体 newData := CloneType(v) //! 使用反射机制来进行接口赋值 ref := reflect.ValueOf(newData).Elem() for i := 0; i < ref.NumField(); i++ { value := ref.Field(i) valueType := value.Kind() if valueType == reflect.Int { data, _ := strconv.ParseInt(record[i], 10, 64) value.SetInt(data) } else if valueType == reflect.String { data := record[i] value.SetString(data) } } loger.Info("%v", newData) } lineNumber++ } file.Close() } } func TestLoadCsv() { //! 打开csv文件 file, err := os.Open("test.csv") if err != nil { loger.Error("open csv file failed. Error: %s", err.Error()) return } defer file.Close() reader := csv.NewReader(file) for { record, err := reader.Read() if err == io.EOF { break } else if err != nil { loger.Error("read csv error. Error: %s", err.Error()) return } loger.Info("record: %v", record) } } func TestParseCsv() { type TestData struct { ID int64 Name string Level int Money int } file, err := os.Open("test.csv") if err != nil { loger.Error("open csv file failed. Error: %s", err.Error()) return } defer file.Close() reader := csv.NewReader(file) lineNumber := 0 for { record, err := reader.Read() if err == io.EOF { break } else if err != nil { loger.Error("read csv error. Error: %s", err.Error()) return } if lineNumber > 0 { //! 遍历字符串slice,取出数据 var data TestData data.ID, _ = strconv.ParseInt(record[0], 10, 64) data.Name = record[1] data.Level, _ = strconv.Atoi(record[2]) data.Money, _ = strconv.Atoi(record[3]) loger.Info("%v", data) } lineNumber++ } }
package node import ( "fmt" "sync" "github.com/sherifabdlnaby/prism/app/component" "github.com/sherifabdlnaby/prism/pkg/job" "github.com/sherifabdlnaby/prism/pkg/payload" "github.com/sherifabdlnaby/prism/pkg/response" "go.uber.org/zap" ) type createAsyncFunc func(nodeID ID, j job.Job) (*job.Job, error) //Node A Node in the pipeline type Node struct { ID ID async bool nexts []Next core core createAsyncJob createAsyncFunc resource *component.Resource logger zap.SugaredLogger activeJobs sync.WaitGroup receiveJobChan <-chan job.Job } type ID string // Start starts this Node and all its next nodes to start receiving jobs // By starting all next nodes, start async request handler, and start receiving jobs func (n *Node) Start() error { // Start next nodes for _, value := range n.nexts { err := value.Start() if err != nil { return err } } go n.serve() return nil } //Stop Stop this Node and stop all its next nodes. func (n *Node) Stop() error { //wait jobs to finish n.activeJobs.Wait() for _, value := range n.nexts { // close this next-node chan close(value.JobChan) // tell this next-node to stop which in turn will close all its next(s) too. err := value.Stop() if err != nil { return err } } return nil } func (n *Node) serve() { for j := range n.receiveJobChan { if n.async { go n.HandleJobAsync(j) } else { go n.HandleJob(j) } } } func (n *Node) HandleJobAsync(j job.Job) { // if Node is set async, convert to async process if n.async { asyncJob, err := n.createAsyncJob(n.ID, j) if err != nil { j.ResponseChan <- response.Error(err) return } j = *asyncJob } n.HandleJob(j) } func (n *Node) HandleJob(j job.Job) { n.activeJobs.Add(1) n.process(j) n.activeJobs.Done() } // process process according to its type stream/bytes func (n *Node) process(j job.Job) { // Start Job according to process payload core switch j.Payload.(type) { case payload.Bytes: n.core.process(j) case payload.Stream: n.core.processStream(j) default: // This theoretically shouldn't happen j.ResponseChan <- response.Error(fmt.Errorf("invalid process payload type, must be payload.Bytes or payload.Stream")) } }
///////////////////////////////////////////////////////////////////// // arataca89@gmail.com // 20210417 // // func ReplaceAll(s, old, new string) string // // Retorna uma cópia de s substituindo todas as ocorrências de old // por new. // Se old é "" new é inserido na posição 0 e depois de cada caracter. // package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.ReplaceAll("oink oink oink", "oink", "moo")) fmt.Println(strings.ReplaceAll("oink oink oink", "", "-moo-")) } // Saída: // moo moo moo // -moo-o-moo-i-moo-n-moo-k-moo- -moo-o-moo-i-moo-n-moo-k-moo- -moo-o-moo-i-moo-n-moo-k-moo-
package main import ( // "fmt" ) func (this *Application) ProjectCreateAction(args []string) { // projectKey := cmdline.ArgumentValue("projectKey") // summary := cmdline.ArgumentValue("summary") // log.Printf("projectKey = %s summary = %s", projectKey, summary) // p := new(client.Project) // p.PKey = projectKey // p.Summary = summary // Create comment // _, err1 := this.Client.CreateProject(p) // if err1 != nil { // fmt.Printf("Unable to create project: %v\n", err1) // os.Exit(1) // } // fmt.Printf("Project create is complete.\n") }
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package serviceaffinity import ( "context" "reflect" "sort" "testing" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/kubernetes/pkg/scheduler/apis/config" framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1" fakeframework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1/fake" "k8s.io/kubernetes/pkg/scheduler/internal/cache" ) func TestServiceAffinity(t *testing.T) { selector := map[string]string{"foo": "bar"} labels1 := map[string]string{ "region": "r1", "zone": "z11", } labels2 := map[string]string{ "region": "r1", "zone": "z12", } labels3 := map[string]string{ "region": "r2", "zone": "z21", } labels4 := map[string]string{ "region": "r2", "zone": "z22", } node1 := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine1", Labels: labels1}} node2 := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine2", Labels: labels2}} node3 := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine3", Labels: labels3}} node4 := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine4", Labels: labels4}} node5 := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine5", Labels: labels4}} tests := []struct { name string pod *v1.Pod pods []*v1.Pod services []*v1.Service node *v1.Node labels []string res framework.Code }{ { name: "nothing scheduled", pod: new(v1.Pod), node: &node1, labels: []string{"region"}, res: framework.Success, }, { name: "pod with region label match", pod: &v1.Pod{Spec: v1.PodSpec{NodeSelector: map[string]string{"region": "r1"}}}, node: &node1, labels: []string{"region"}, res: framework.Success, }, { name: "pod with region label mismatch", pod: &v1.Pod{Spec: v1.PodSpec{NodeSelector: map[string]string{"region": "r2"}}}, node: &node1, labels: []string{"region"}, res: framework.Unschedulable, }, { name: "service pod on same node", pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: selector}}, pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine1"}, ObjectMeta: metav1.ObjectMeta{Labels: selector}}}, node: &node1, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}}}, labels: []string{"region"}, res: framework.Success, }, { name: "service pod on different node, region match", pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: selector}}, pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Labels: selector}}}, node: &node1, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}}}, labels: []string{"region"}, res: framework.Success, }, { name: "service pod on different node, region mismatch", pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: selector}}, pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: metav1.ObjectMeta{Labels: selector}}}, node: &node1, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}}}, labels: []string{"region"}, res: framework.Unschedulable, }, { name: "service in different namespace, region mismatch", pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: selector, Namespace: "ns1"}}, pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: metav1.ObjectMeta{Labels: selector, Namespace: "ns1"}}}, node: &node1, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}, ObjectMeta: metav1.ObjectMeta{Namespace: "ns2"}}}, labels: []string{"region"}, res: framework.Success, }, { name: "pod in different namespace, region mismatch", pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: selector, Namespace: "ns1"}}, pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: metav1.ObjectMeta{Labels: selector, Namespace: "ns2"}}}, node: &node1, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}, ObjectMeta: metav1.ObjectMeta{Namespace: "ns1"}}}, labels: []string{"region"}, res: framework.Success, }, { name: "service and pod in same namespace, region mismatch", pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: selector, Namespace: "ns1"}}, pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine3"}, ObjectMeta: metav1.ObjectMeta{Labels: selector, Namespace: "ns1"}}}, node: &node1, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}, ObjectMeta: metav1.ObjectMeta{Namespace: "ns1"}}}, labels: []string{"region"}, res: framework.Unschedulable, }, { name: "service pod on different node, multiple labels, not all match", pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: selector}}, pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine2"}, ObjectMeta: metav1.ObjectMeta{Labels: selector}}}, node: &node1, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}}}, labels: []string{"region", "zone"}, res: framework.Unschedulable, }, { name: "service pod on different node, multiple labels, all match", pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: selector}}, pods: []*v1.Pod{{Spec: v1.PodSpec{NodeName: "machine5"}, ObjectMeta: metav1.ObjectMeta{Labels: selector}}}, node: &node4, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector}}}, labels: []string{"region", "zone"}, res: framework.Success, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { nodes := []*v1.Node{&node1, &node2, &node3, &node4, &node5} snapshot := cache.NewSnapshot(test.pods, nodes) p := &ServiceAffinity{ sharedLister: snapshot, serviceLister: fakeframework.ServiceLister(test.services), args: config.ServiceAffinityArgs{ AffinityLabels: test.labels, }, } state := framework.NewCycleState() if s := p.PreFilter(context.Background(), state, test.pod); !s.IsSuccess() { t.Errorf("PreFilter failed: %v", s.Message()) } nodeInfo := mustGetNodeInfo(t, snapshot, test.node.Name) status := p.Filter(context.Background(), state, test.pod, nodeInfo) if status.Code() != test.res { t.Errorf("Status mismatch. got: %v, want: %v", status.Code(), test.res) } }) } } func TestServiceAffinityScore(t *testing.T) { labels1 := map[string]string{ "foo": "bar", "baz": "blah", } labels2 := map[string]string{ "bar": "foo", "baz": "blah", } zone1 := map[string]string{ "zone": "zone1", } zone1Rack1 := map[string]string{ "zone": "zone1", "rack": "rack1", } zone1Rack2 := map[string]string{ "zone": "zone1", "rack": "rack2", } zone2 := map[string]string{ "zone": "zone2", } zone2Rack1 := map[string]string{ "zone": "zone2", "rack": "rack1", } nozone := map[string]string{ "name": "value", } zone0Spec := v1.PodSpec{ NodeName: "machine01", } zone1Spec := v1.PodSpec{ NodeName: "machine11", } zone2Spec := v1.PodSpec{ NodeName: "machine21", } labeledNodes := map[string]map[string]string{ "machine01": nozone, "machine02": nozone, "machine11": zone1, "machine12": zone1, "machine21": zone2, "machine22": zone2, } nodesWithZoneAndRackLabels := map[string]map[string]string{ "machine01": nozone, "machine02": nozone, "machine11": zone1Rack1, "machine12": zone1Rack2, "machine21": zone2Rack1, "machine22": zone2Rack1, } tests := []struct { pod *v1.Pod pods []*v1.Pod nodes map[string]map[string]string services []*v1.Service labels []string expectedList framework.NodeScoreList name string }{ { pod: new(v1.Pod), nodes: labeledNodes, labels: []string{"zone"}, expectedList: []framework.NodeScore{{Name: "machine11", Score: framework.MaxNodeScore}, {Name: "machine12", Score: framework.MaxNodeScore}, {Name: "machine21", Score: framework.MaxNodeScore}, {Name: "machine22", Score: framework.MaxNodeScore}, {Name: "machine01", Score: 0}, {Name: "machine02", Score: 0}}, name: "nothing scheduled", }, { pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, pods: []*v1.Pod{{Spec: zone1Spec}}, nodes: labeledNodes, labels: []string{"zone"}, expectedList: []framework.NodeScore{{Name: "machine11", Score: framework.MaxNodeScore}, {Name: "machine12", Score: framework.MaxNodeScore}, {Name: "machine21", Score: framework.MaxNodeScore}, {Name: "machine22", Score: framework.MaxNodeScore}, {Name: "machine01", Score: 0}, {Name: "machine02", Score: 0}}, name: "no services", }, { pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, pods: []*v1.Pod{{Spec: zone1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels2}}}, nodes: labeledNodes, labels: []string{"zone"}, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: map[string]string{"key": "value"}}}}, expectedList: []framework.NodeScore{{Name: "machine11", Score: framework.MaxNodeScore}, {Name: "machine12", Score: framework.MaxNodeScore}, {Name: "machine21", Score: framework.MaxNodeScore}, {Name: "machine22", Score: framework.MaxNodeScore}, {Name: "machine01", Score: 0}, {Name: "machine02", Score: 0}}, name: "different services", }, { pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, pods: []*v1.Pod{ {Spec: zone0Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels2}}, {Spec: zone1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels2}}, {Spec: zone2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, }, nodes: labeledNodes, labels: []string{"zone"}, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []framework.NodeScore{{Name: "machine11", Score: framework.MaxNodeScore}, {Name: "machine12", Score: framework.MaxNodeScore}, {Name: "machine21", Score: 0}, {Name: "machine22", Score: 0}, {Name: "machine01", Score: 0}, {Name: "machine02", Score: 0}}, name: "three pods, one service pod", }, { pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, pods: []*v1.Pod{ {Spec: zone1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels2}}, {Spec: zone1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: zone2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, }, nodes: labeledNodes, labels: []string{"zone"}, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []framework.NodeScore{{Name: "machine11", Score: 50}, {Name: "machine12", Score: 50}, {Name: "machine21", Score: 50}, {Name: "machine22", Score: 50}, {Name: "machine01", Score: 0}, {Name: "machine02", Score: 0}}, name: "three pods, two service pods on different machines", }, { pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: labels1, Namespace: metav1.NamespaceDefault}}, pods: []*v1.Pod{ {Spec: zone1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: zone1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1, Namespace: metav1.NamespaceDefault}}, {Spec: zone2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: zone2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1, Namespace: "ns1"}}, }, nodes: labeledNodes, labels: []string{"zone"}, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}, ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceDefault}}}, expectedList: []framework.NodeScore{{Name: "machine11", Score: 0}, {Name: "machine12", Score: 0}, {Name: "machine21", Score: framework.MaxNodeScore}, {Name: "machine22", Score: framework.MaxNodeScore}, {Name: "machine01", Score: 0}, {Name: "machine02", Score: 0}}, name: "three service label match pods in different namespaces", }, { pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, pods: []*v1.Pod{ {Spec: zone1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels2}}, {Spec: zone1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: zone2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: zone2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, }, nodes: labeledNodes, labels: []string{"zone"}, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []framework.NodeScore{{Name: "machine11", Score: 66}, {Name: "machine12", Score: 66}, {Name: "machine21", Score: 33}, {Name: "machine22", Score: 33}, {Name: "machine01", Score: 0}, {Name: "machine02", Score: 0}}, name: "four pods, three service pods", }, { pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, pods: []*v1.Pod{ {Spec: zone1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels2}}, {Spec: zone1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: zone2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, }, nodes: labeledNodes, labels: []string{"zone"}, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: map[string]string{"baz": "blah"}}}}, expectedList: []framework.NodeScore{{Name: "machine11", Score: 33}, {Name: "machine12", Score: 33}, {Name: "machine21", Score: 66}, {Name: "machine22", Score: 66}, {Name: "machine01", Score: 0}, {Name: "machine02", Score: 0}}, name: "service with partial pod label matches", }, { pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, pods: []*v1.Pod{ {Spec: zone0Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: zone1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: zone2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: zone2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, }, nodes: labeledNodes, labels: []string{"zone"}, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []framework.NodeScore{{Name: "machine11", Score: 75}, {Name: "machine12", Score: 75}, {Name: "machine21", Score: 50}, {Name: "machine22", Score: 50}, {Name: "machine01", Score: 0}, {Name: "machine02", Score: 0}}, name: "service pod on non-zoned node", }, { pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, pods: []*v1.Pod{ {Spec: zone0Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels2}}, {Spec: zone1Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, {Spec: zone2Spec, ObjectMeta: metav1.ObjectMeta{Labels: labels1}}, }, nodes: nodesWithZoneAndRackLabels, labels: []string{"zone", "rack"}, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: labels1}}}, expectedList: []framework.NodeScore{{Name: "machine11", Score: 25}, {Name: "machine12", Score: 75}, {Name: "machine21", Score: 25}, {Name: "machine22", Score: 25}, {Name: "machine01", Score: 0}, {Name: "machine02", Score: 0}}, name: "three pods, two service pods, with rack label", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { nodes := makeLabeledNodeList(test.nodes) snapshot := cache.NewSnapshot(test.pods, nodes) serviceLister := fakeframework.ServiceLister(test.services) p := &ServiceAffinity{ sharedLister: snapshot, serviceLister: serviceLister, args: config.ServiceAffinityArgs{ AntiAffinityLabelsPreference: test.labels, }, } state := framework.NewCycleState() var gotList framework.NodeScoreList for _, n := range makeLabeledNodeList(test.nodes) { score, status := p.Score(context.Background(), state, test.pod, n.Name) if !status.IsSuccess() { t.Errorf("unexpected error: %v", status) } gotList = append(gotList, framework.NodeScore{Name: n.Name, Score: score}) } status := p.ScoreExtensions().NormalizeScore(context.Background(), state, test.pod, gotList) if !status.IsSuccess() { t.Errorf("unexpected error: %v", status) } // sort the two lists to avoid failures on account of different ordering sortNodeScoreList(test.expectedList) sortNodeScoreList(gotList) if !reflect.DeepEqual(test.expectedList, gotList) { t.Errorf("expected %#v, got %#v", test.expectedList, gotList) } }) } } func TestPreFilterStateAddRemovePod(t *testing.T) { var label1 = map[string]string{ "region": "r1", "zone": "z11", } var label2 = map[string]string{ "region": "r1", "zone": "z12", } var label3 = map[string]string{ "region": "r2", "zone": "z21", } selector1 := map[string]string{"foo": "bar"} tests := []struct { name string pendingPod *v1.Pod addedPod *v1.Pod existingPods []*v1.Pod nodes []*v1.Node services []*v1.Service }{ { name: "no anti-affinity or service affinity exist", pendingPod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "pending", Labels: selector1}, }, existingPods: []*v1.Pod{ {ObjectMeta: metav1.ObjectMeta{Name: "p1", Labels: selector1}, Spec: v1.PodSpec{NodeName: "nodeA"}, }, {ObjectMeta: metav1.ObjectMeta{Name: "p2"}, Spec: v1.PodSpec{NodeName: "nodeC"}, }, }, addedPod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "addedPod", Labels: selector1}, Spec: v1.PodSpec{NodeName: "nodeB"}, }, nodes: []*v1.Node{ {ObjectMeta: metav1.ObjectMeta{Name: "nodeA", Labels: label1}}, {ObjectMeta: metav1.ObjectMeta{Name: "nodeB", Labels: label2}}, {ObjectMeta: metav1.ObjectMeta{Name: "nodeC", Labels: label3}}, }, }, { name: "metadata service-affinity data are updated correctly after adding and removing a pod", pendingPod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "pending", Labels: selector1}, }, existingPods: []*v1.Pod{ {ObjectMeta: metav1.ObjectMeta{Name: "p1", Labels: selector1}, Spec: v1.PodSpec{NodeName: "nodeA"}, }, {ObjectMeta: metav1.ObjectMeta{Name: "p2"}, Spec: v1.PodSpec{NodeName: "nodeC"}, }, }, addedPod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "addedPod", Labels: selector1}, Spec: v1.PodSpec{NodeName: "nodeB"}, }, services: []*v1.Service{{Spec: v1.ServiceSpec{Selector: selector1}}}, nodes: []*v1.Node{ {ObjectMeta: metav1.ObjectMeta{Name: "nodeA", Labels: label1}}, {ObjectMeta: metav1.ObjectMeta{Name: "nodeB", Labels: label2}}, {ObjectMeta: metav1.ObjectMeta{Name: "nodeC", Labels: label3}}, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { // getMeta creates predicate meta data given the list of pods. getState := func(pods []*v1.Pod) (*ServiceAffinity, *framework.CycleState, *preFilterState, *cache.Snapshot) { snapshot := cache.NewSnapshot(pods, test.nodes) p := &ServiceAffinity{ sharedLister: snapshot, serviceLister: fakeframework.ServiceLister(test.services), } cycleState := framework.NewCycleState() preFilterStatus := p.PreFilter(context.Background(), cycleState, test.pendingPod) if !preFilterStatus.IsSuccess() { t.Errorf("prefilter failed with status: %v", preFilterStatus) } plState, err := getPreFilterState(cycleState) if err != nil { t.Errorf("failed to get metadata from cycleState: %v", err) } return p, cycleState, plState, snapshot } sortState := func(plState *preFilterState) *preFilterState { sort.SliceStable(plState.matchingPodList, func(i, j int) bool { return plState.matchingPodList[i].Name < plState.matchingPodList[j].Name }) sort.SliceStable(plState.matchingPodServices, func(i, j int) bool { return plState.matchingPodServices[i].Name < plState.matchingPodServices[j].Name }) return plState } // allPodsState is the state produced when all pods, including test.addedPod are given to prefilter. _, _, plStateAllPods, _ := getState(append(test.existingPods, test.addedPod)) // state is produced for test.existingPods (without test.addedPod). ipa, state, plState, snapshot := getState(test.existingPods) // clone the state so that we can compare it later when performing Remove. plStateOriginal, _ := plState.Clone().(*preFilterState) // Add test.addedPod to state1 and verify it is equal to allPodsState. nodeInfo := mustGetNodeInfo(t, snapshot, test.addedPod.Spec.NodeName) if err := ipa.AddPod(context.Background(), state, test.pendingPod, test.addedPod, nodeInfo); err != nil { t.Errorf("error adding pod to preFilterState: %v", err) } if !reflect.DeepEqual(sortState(plStateAllPods), sortState(plState)) { t.Errorf("State is not equal, got: %v, want: %v", plState, plStateAllPods) } // Remove the added pod pod and make sure it is equal to the original state. if err := ipa.RemovePod(context.Background(), state, test.pendingPod, test.addedPod, nodeInfo); err != nil { t.Errorf("error removing pod from preFilterState: %v", err) } if !reflect.DeepEqual(sortState(plStateOriginal), sortState(plState)) { t.Errorf("State is not equal, got: %v, want: %v", plState, plStateOriginal) } }) } } func TestPreFilterStateClone(t *testing.T) { source := &preFilterState{ matchingPodList: []*v1.Pod{ {ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}, {ObjectMeta: metav1.ObjectMeta{Name: "pod2"}}, }, matchingPodServices: []*v1.Service{ {ObjectMeta: metav1.ObjectMeta{Name: "service1"}}, }, } clone := source.Clone() if clone == source { t.Errorf("Clone returned the exact same object!") } if !reflect.DeepEqual(clone, source) { t.Errorf("Copy is not equal to source!") } } func makeLabeledNodeList(nodeMap map[string]map[string]string) []*v1.Node { nodes := make([]*v1.Node, 0, len(nodeMap)) for nodeName, labels := range nodeMap { nodes = append(nodes, &v1.Node{ObjectMeta: metav1.ObjectMeta{Name: nodeName, Labels: labels}}) } return nodes } func sortNodeScoreList(out framework.NodeScoreList) { sort.Slice(out, func(i, j int) bool { if out[i].Score == out[j].Score { return out[i].Name < out[j].Name } return out[i].Score < out[j].Score }) } func mustGetNodeInfo(t *testing.T, snapshot *cache.Snapshot, name string) *framework.NodeInfo { t.Helper() nodeInfo, err := snapshot.NodeInfos().Get(name) if err != nil { t.Fatal(err) } return nodeInfo } func TestPreFilterDisabled(t *testing.T) { pod := &v1.Pod{} nodeInfo := framework.NewNodeInfo() node := v1.Node{} nodeInfo.SetNode(&node) p := &ServiceAffinity{ args: config.ServiceAffinityArgs{ AffinityLabels: []string{"region"}, }, } cycleState := framework.NewCycleState() gotStatus := p.Filter(context.Background(), cycleState, pod, nodeInfo) wantStatus := framework.NewStatus(framework.Error, `error reading "PreFilterServiceAffinity" from cycleState: not found`) if !reflect.DeepEqual(gotStatus, wantStatus) { t.Errorf("status does not match: %v, want: %v", gotStatus, wantStatus) } }
package handler import ( "application/session" "application/config" "application/route" "database/sql" "net/http" ) const ( COOKIE_NAME = "sessionId" ) type Handler struct { Route *route.Route Config *config.Config Session *session.Session DB *sql.DB } func (h *Handler) ServeHTTP(res http.ResponseWriter, req *http.Request) { switch path := req.URL.Path; path { case "/api/user": h.Route.User(res, req, h.Session, h.DB, COOKIE_NAME) case "/api/login": h.Route.Login(res, req, h.Session, h.DB, COOKIE_NAME) case "/api/logout": h.Route.Logout(res, req, h.Session, h.DB, COOKIE_NAME) default: } }
package godebug //godebug:annotatefile import ( "bytes" "context" "flag" "fmt" "go/ast" "io" "io/ioutil" "math/rand" "os" "os/exec" "path/filepath" "runtime" "strings" "sync" "time" "github.com/jmigpin/editor/core/godebug/debug" "github.com/jmigpin/editor/util/goutil" "github.com/jmigpin/editor/util/osutil" ) type Cmd struct { Client *Client NoModules bool // not in go.mod modules Dir string // "" will use current dir Stdout io.Writer Stderr io.Writer annset *AnnotatorSet tmpDir string tmpBuiltFile string // file built and exec'd start struct { cancel context.CancelFunc waitg sync.WaitGroup serverErr error } flags struct { mode struct { run bool test bool build bool connect bool } verbose bool filename string work bool output string // ex: -o filename toolExec string // ex: "wine" will run "wine args..." dirs []string files []string address string // build/connect env []string // build syncSend bool otherArgs []string runArgs []string } } func NewCmd() *Cmd { cmd := &Cmd{ annset: NewAnnotatorSet(), Stdout: os.Stdout, Stderr: os.Stderr, } return cmd } //------------ func (cmd *Cmd) Printf(format string, a ...interface{}) (int, error) { return fmt.Fprintf(cmd.Stdout, format, a...) } //------------ func (cmd *Cmd) Start(ctx context.Context, args []string) (done bool, _ error) { // parse arguments done, err := cmd.parseArgs(args) if done || err != nil { return done, err } // absolute dir if u, err := filepath.Abs(cmd.Dir); err == nil { cmd.Dir = u } // setup nomodules if !cmd.NoModules && cmd.detectNoModules() { cmd.NoModules = true } if cmd.flags.verbose { cmd.Printf("nomodules=%v\n", cmd.NoModules) } // tmp dir for building if cmd.NoModules { d := "editor_godebug_gopath_work" tmpDir, err := ioutil.TempDir(os.TempDir(), d) if err != nil { return true, err } cmd.tmpDir = tmpDir } else { d := "editor_godebug_mod_work" // The fixed directory will improve the file sync performance since modules require the whole directory to be there (not like gopath) // TODO: will have problems running more then one debug session in different editor sessions //d += "_"+md5.Sum([]byte(cmd.Dir)) //tmpDir := filepath.Join(os.TempDir(), d) tmpDir, err := ioutil.TempDir(os.TempDir(), d) if err != nil { return true, err } cmd.tmpDir = tmpDir } // print tmp dir if work flag is present if cmd.flags.work { fmt.Fprintf(cmd.Stdout, "work: %v\n", cmd.tmpDir) } m := &cmd.flags.mode if m.run || m.test || m.build { debug.SyncSend = cmd.flags.syncSend setupServerNetAddr(cmd.flags.address) err := cmd.initAndAnnotate(ctx) if err != nil { return true, err } } // just building: inform the address used in the binary if m.build { fmt.Fprintf(cmd.Stdout, "build: %v (builtin address: %v, %v)\n", cmd.tmpBuiltFile, debug.ServerNetwork, debug.ServerAddress, ) return true, err } if m.run || m.test || m.connect { err = cmd.startServerClient(ctx) return false, err } return false, nil } //------------ func (cmd *Cmd) Wait() error { cmd.start.waitg.Wait() cmd.start.cancel() // ensure resources are cleared return cmd.start.serverErr } //------------ func (cmd *Cmd) initAndAnnotate(ctx context.Context) error { files := NewFiles(cmd.annset.FSet) // not in cmd.* to allow early GC files.Dir = cmd.Dir files.Add(cmd.flags.files...) files.Add(cmd.flags.dirs...) mainFilename := files.absFilename(cmd.flags.filename) ctx2, cancel := context.WithCancel(ctx) defer cancel() var wg sync.WaitGroup // pre-build without annotations for better errors (result is ignored) wg.Add(1) var preBuildErr error go func() { defer wg.Done() if err := cmd.preBuild(ctx2, mainFilename, cmd.flags.mode.test); err != nil { preBuildErr = err cancel() // early cancel } }() // continue with init and annotate wg.Add(1) var err2 error go func() { defer wg.Done() if err := cmd.initAndAnnotate2(ctx2, files, mainFilename); err != nil { err2 = err } }() wg.Wait() // send only the prebuild error if it happens if preBuildErr != nil { return preBuildErr } return err2 } func (cmd *Cmd) initAndAnnotate2(ctx context.Context, files *Files, mainFilename string) error { err := files.Do(ctx, mainFilename, cmd.flags.mode.test, cmd.NoModules, cmd.environ()) if err != nil { return err } if cmd.flags.verbose { files.verbose(cmd) } // copy for filename := range files.copyFilenames { dst := cmd.tmpDirBasedFilename(filename) if err := mkdirAllCopyFileSync(filename, dst); err != nil { return err } } for filename := range files.modFilenames { dst := cmd.tmpDirBasedFilename(filename) if err := mkdirAllCopyFileSync(filename, dst); err != nil { return err } } // annotate for filename := range files.annFilenames { dst := cmd.tmpDirBasedFilename(filename) typ := files.annTypes[filename] astFile, err := files.fullAstFile(filename) if err != nil { return err } if err := cmd.annset.AnnotateAstFile(astFile, typ); err != nil { return err } if err := cmd.mkdirAllWriteAstFile(dst, astFile); err != nil { return err } } // write config file after annotations if err := cmd.writeGoDebugConfigFilesToTmpDir(); err != nil { return err } // create testmain file if cmd.flags.mode.test && !cmd.annset.InsertedExitIn.TestMain { if err := cmd.writeTestMainFilesToTmpDir(); err != nil { return err } } // main must have exit inserted if !cmd.flags.mode.test && !cmd.annset.InsertedExitIn.Main { return fmt.Errorf("have not inserted debug exit in main()") } if !cmd.NoModules { if err := SetupGoMods(ctx, cmd, files, mainFilename, cmd.flags.mode.test); err != nil { return err } } return cmd.doBuild(ctx, mainFilename, cmd.flags.mode.test) } func (cmd *Cmd) doBuild(ctx context.Context, mainFilename string, tests bool) error { filename := cmd.filenameForBuild(mainFilename, tests) filenameAtTmp := cmd.tmpDirBasedFilename(filename) // create parent dirs if err := os.MkdirAll(filepath.Dir(filenameAtTmp), 0755); err != nil { return err } // build filenameAtTmpOut, err := cmd.runBuildCmd(ctx, filenameAtTmp, tests) if err != nil { return err } // move filename to working dir filenameWork := filepath.Join(cmd.Dir, filepath.Base(filenameAtTmpOut)) // move filename to output option if cmd.flags.output != "" { o := cmd.flags.output if !filepath.IsAbs(o) { o = filepath.Join(cmd.Dir, o) } filenameWork = o } if err := os.Rename(filenameAtTmpOut, filenameWork); err != nil { return err } // keep moved filename that will run in working dir for later cleanup cmd.tmpBuiltFile = filenameWork return nil } func (cmd *Cmd) filenameForBuild(mainFilename string, tests bool) string { if tests { // final filename will include extension replacement with "_godebug" return filepath.Join(cmd.Dir, "pkgtest") } return mainFilename } // pre-build without annotations for better errors (result is ignored) func (cmd *Cmd) preBuild(ctx context.Context, mainFilename string, tests bool) error { filename := cmd.filenameForBuild(mainFilename, tests) filenameOut, err := cmd.runBuildCmd(ctx, filename, tests) defer os.Remove(filenameOut) // ensure removal even on error if err != nil { return err } return nil } //------------ func (cmd *Cmd) startServerClient(ctx context.Context) error { // server/client context to cancel the other when one of them ends ctx2, cancel := context.WithCancel(ctx) cmd.start.cancel = cancel // arguments (TODO: review normalize...) w := normalizeFilenameForExec(cmd.tmpBuiltFile) args := []string{w} if cmd.flags.mode.test { args = append(args, cmd.flags.runArgs...) } else { args = append(args, cmd.flags.otherArgs...) } // toolexec if cmd.flags.toolExec != "" { args = append([]string{cmd.flags.toolExec}, args...) } // start server var serverCmd *exec.Cmd if !cmd.flags.mode.connect { u, err := cmd.startCmd(ctx2, cmd.Dir, args, nil) if err != nil { // cmd.Wait() won't be called, need to clear resources cmd.start.cancel() return err } serverCmd = u // output cmd pid fmt.Fprintf(cmd.Stdout, "# pid %d\n", serverCmd.Process.Pid) } // setup address to connect to if cmd.flags.mode.connect && cmd.flags.address != "" { debug.ServerNetwork = "tcp" debug.ServerAddress = cmd.flags.address } // start client (blocking connect) client, err := NewClient(ctx2) if err != nil { // cmd.Wait() won't be called, need to clear resources cmd.start.cancel() return err } cmd.Client = client // from this point, cmd.Wait() clears resources from cmd.start.cancel // server done if serverCmd != nil { cmd.start.waitg.Add(1) go func() { defer cmd.start.waitg.Done() // wait for server to finish cmd.start.serverErr = serverCmd.Wait() }() } // client done cmd.start.waitg.Add(1) go func() { defer cmd.start.waitg.Done() cmd.Client.Wait() // wait for client to finish }() // ensure client stops on context cancel (only for connect mode) if cmd.flags.mode.connect { go func() { select { case <-ctx.Done(): _ = cmd.Client.Close() } }() } return nil } //------------ func (cmd *Cmd) RequestFileSetPositions() error { msg := &debug.ReqFilesDataMsg{} encoded, err := debug.EncodeMessage(msg) if err != nil { return err } _, err = cmd.Client.Conn.Write(encoded) return err } func (cmd *Cmd) RequestStart() error { msg := &debug.ReqStartMsg{} encoded, err := debug.EncodeMessage(msg) if err != nil { return err } _, err = cmd.Client.Conn.Write(encoded) return err } //------------ func (cmd *Cmd) tmpDirBasedFilename(filename string) string { // remove volume name v := filepath.VolumeName(filename) if len(v) > 0 { filename = filename[len(v):] } if cmd.NoModules { // trim filename when inside a src dir //_, rest := goutil.ExtractSrcDir(filename) rhs := trimAtFirstSrcDir(filename) return filepath.Join(cmd.tmpDir, "src", rhs) } //// based on pkg path (TODO: not the same as module path) //u, ok := cmd.files.pkgPathDir(filename) //if ok { // return filepath.Join(cmd.tmpDir, u) //} // just replicate on tmp dir return filepath.Join(cmd.tmpDir, filename) } func trimAtFirstSrcDir(filename string) string { v := filename w := []string{} for { base := filepath.Base(v) if base == "src" { return filepath.Join(w...) // trimmed } w = append([]string{base}, w...) v = filepath.Dir(v) if v == "/" || v == "." { break } } return filename } //------------ func (cmd *Cmd) environ() []string { env := os.Environ() // add cmd line env vars for _, s := range cmd.flags.env { env = append(env, s) } // gopath (after cmd line env vars) if s, ok := cmd.environGoPath(); ok { env = append(env, s) } //env = append(env, //"GOPROXY=off", //"GOPROXY=direct", //"GOSUMDB=off", //) return env } func (cmd *Cmd) environGoPath() (string, bool) { if !cmd.NoModules { return "", false } goPath := []string{} // add tmpdir to gopath to give priority to the annotated files goPath = append(goPath, cmd.tmpDir) // add cmd line env vars prefix := "GOPATH=" for _, s := range cmd.flags.env { if strings.HasPrefix(s, prefix) { a := filepath.SplitList(s[len(prefix):]) goPath = append(goPath, a...) } } // add already defined gopath goPath = append(goPath, goutil.GoPath()...) // build gopath string s := "GOPATH=" + goutil.JoinPathLists(goPath...) return s, true } //------------ func (cmd *Cmd) detectNoModules() bool { // cmd line env flag for _, s := range cmd.flags.env { if s == "GO111MODULE=off" { return true } } // environment v := os.Getenv("GO111MODULE") if v == "off" { return true } // auto: if it can't find a go.mod, it is off if _, ok := goutil.FindGoMod(cmd.Dir); !ok { return true } return false } //------------ func (cmd *Cmd) Cleanup() { // cleanup unix socket in case of bad stop if debug.ServerNetwork == "unix" { if err := os.Remove(debug.ServerAddress); err != nil { if !os.IsNotExist(err) { cmd.Printf("cleanup err: %v\n", err) } } } if cmd.flags.work { // don't cleanup work dir } else { if cmd.tmpDir != "" { if err := os.RemoveAll(cmd.tmpDir); err != nil { cmd.Printf("cleanup err: %v\n", err) } } } if cmd.tmpBuiltFile != "" && !cmd.flags.mode.build { if err := os.Remove(cmd.tmpBuiltFile); err != nil { if !os.IsNotExist(err) { cmd.Printf("cleanup err: %v\n", err) } } } } //------------ func (cmd *Cmd) runBuildCmd(ctx context.Context, filename string, tests bool) (string, error) { filenameOut := cmd.execName(filename) args := []string{} if tests { args = []string{ osutil.GoExec(), "test", "-c", // compile binary but don't run // TODO: faster dummy pre-builts? // "-toolexec", "", // don't run asm? "-o", filenameOut, } args = append(args, cmd.flags.otherArgs...) } else { args = []string{ osutil.GoExec(), "build", "-o", filenameOut, } // insert otherargs before filename last arg: allows all "go build" to be used after the filename // TODO: accept -gobuild.* args? if cmd.flags.mode.build { args = append(args, cmd.flags.otherArgs...) } // filename is last arg args = append(args, filename) } dir := filepath.Dir(filenameOut) if cmd.flags.verbose { cmd.Printf("runBuildCmd: dir=%v\n", dir) } err := cmd.runCmd(ctx, dir, args, cmd.environ()) if err != nil { err = fmt.Errorf("runBuildCmd: %v", err) } return filenameOut, err } func (cmd *Cmd) execName(name string) string { return replaceExt(name, osutil.ExecName("_godebug")) } //------------ func (cmd *Cmd) runCmd(ctx context.Context, dir string, args, env []string) error { // ctx with early cancel for startcmd to clear inner goroutine resource ctx2, cancel := context.WithCancel(ctx) defer cancel() ecmd, err := cmd.startCmd(ctx2, dir, args, env) if err != nil { return err } return ecmd.Wait() } func (cmd *Cmd) startCmd(ctx context.Context, dir string, args, env []string) (*exec.Cmd, error) { cargs := osutil.ShellRunArgs(args...) ecmd := osutil.ExecCmdCtxWithAttr(ctx, cargs[0], cargs[1:]...) ecmd.Env = env ecmd.Dir = dir ecmd.Stdout = cmd.Stdout ecmd.Stderr = cmd.Stderr if err := ecmd.Start(); err != nil { return nil, err } // ensure kill to child processes on context cancel // the ctx must be cancelable, otherwise it might kill the process on start go func() { select { case <-ctx.Done(): _ = osutil.KillExecCmd(ecmd) } }() return ecmd, nil } //------------ func (cmd *Cmd) mkdirAllWriteAstFile(filename string, astFile *ast.File) error { buf := &bytes.Buffer{} if err := cmd.annset.Print(buf, astFile); err != nil { return err } return mkdirAllWriteFile(filename, buf.Bytes()) } //------------ func (cmd *Cmd) writeGoDebugConfigFilesToTmpDir() error { { // godebugconfig pkg: config.go filename := filepath.Join(GoDebugConfigFilepath, "config.go") src := cmd.annset.ConfigContent() filenameAtTmp := cmd.tmpDirBasedFilename(filename) if err := mkdirAllWriteFile(filenameAtTmp, []byte(src)); err != nil { return err } } if !cmd.NoModules { // godebugconfig pkg: go.mod filename := filepath.Join(GoDebugConfigFilepath, "go.mod") src := cmd.annset.ConfigGoModuleContent() filenameAtTmp2 := cmd.tmpDirBasedFilename(filename) if err := mkdirAllWriteFile(filenameAtTmp2, []byte(src)); err != nil { return err } } { // debug pkg (pack into a file and add to godebugconfig pkg) for _, fp := range DebugFilePacks() { filename := filepath.Join(DebugFilepath, fp.Name) filenameAtTmp := cmd.tmpDirBasedFilename(filename) if err := mkdirAllWriteFile(filenameAtTmp, []byte(fp.Data)); err != nil { return err } } } return nil } func (cmd *Cmd) writeTestMainFilesToTmpDir() error { u := cmd.annset.TestMainSources() for i, tms := range u { name := fmt.Sprintf("godebug_testmain%v_test.go", i) filename := filepath.Join(tms.Dir, name) filenameAtTmp := cmd.tmpDirBasedFilename(filename) return mkdirAllWriteFile(filenameAtTmp, []byte(tms.Src)) } return nil } //------------ func (cmd *Cmd) parseArgs(args []string) (done bool, _ error) { if len(args) > 0 { switch args[0] { case "run": cmd.flags.mode.run = true return cmd.parseRunArgs(args[1:]) case "test": cmd.flags.mode.test = true return cmd.parseTestArgs(args[1:]) case "build": cmd.flags.mode.build = true return cmd.parseBuildArgs(args[1:]) case "connect": cmd.flags.mode.connect = true return cmd.parseConnectArgs(args[1:]) } } fmt.Fprint(cmd.Stderr, cmdUsage()) return true, nil } func (cmd *Cmd) parseRunArgs(args []string) (done bool, _ error) { f := &flag.FlagSet{} f.SetOutput(cmd.Stderr) cmd.dirsFlag(f) cmd.filesFlag(f) cmd.workFlag(f) cmd.verboseFlag(f) cmd.toolExecFlag(f) cmd.syncSendFlag(f) cmd.envFlag(f) if err := f.Parse(args); err != nil { if err == flag.ErrHelp { return true, nil } return true, err } cmd.flags.otherArgs = f.Args() if len(cmd.flags.otherArgs) > 0 { cmd.flags.filename = cmd.flags.otherArgs[0] cmd.flags.otherArgs = cmd.flags.otherArgs[1:] } return false, nil } func (cmd *Cmd) parseTestArgs(args []string) (done bool, _ error) { f := &flag.FlagSet{} f.SetOutput(cmd.Stderr) cmd.dirsFlag(f) cmd.filesFlag(f) cmd.workFlag(f) cmd.verboseFlag(f) cmd.toolExecFlag(f) cmd.syncSendFlag(f) cmd.envFlag(f) run := f.String("run", "", "run test") verboseTests := f.Bool("v", false, "verbose tests") if err := f.Parse(args); err != nil { if err == flag.ErrHelp { return true, nil } return true, err } cmd.flags.otherArgs = f.Args() // set test run flag at other flags to pass to the test exec if *run != "" { a := []string{"-test.run", *run} cmd.flags.runArgs = append(a, cmd.flags.runArgs...) } // verbose if *verboseTests { a := []string{"-test.v"} cmd.flags.runArgs = append(a, cmd.flags.runArgs...) } return false, nil } func (cmd *Cmd) parseBuildArgs(args []string) (done bool, _ error) { f := &flag.FlagSet{} f.SetOutput(cmd.Stderr) cmd.dirsFlag(f) cmd.filesFlag(f) cmd.workFlag(f) cmd.verboseFlag(f) cmd.syncSendFlag(f) cmd.envFlag(f) addr := f.String("addr", "", "address to serve from, built into the binary") f.StringVar(&cmd.flags.output, "o", "", "output filename (default: ${filename}_godebug") if err := f.Parse(args); err != nil { if err == flag.ErrHelp { return true, nil } return true, err } cmd.flags.address = *addr cmd.flags.otherArgs = f.Args() if len(cmd.flags.otherArgs) > 0 { cmd.flags.filename = cmd.flags.otherArgs[0] cmd.flags.otherArgs = cmd.flags.otherArgs[1:] } return false, nil } func (cmd *Cmd) parseConnectArgs(args []string) (done bool, _ error) { f := &flag.FlagSet{} f.SetOutput(cmd.Stderr) addr := f.String("addr", "", "address to connect to, built into the binary") cmd.toolExecFlag(f) if err := f.Parse(args); err != nil { if err == flag.ErrHelp { f.SetOutput(cmd.Stderr) f.PrintDefaults() return true, nil } return true, err } cmd.flags.address = *addr return false, nil } //------------ func (cmd *Cmd) workFlag(fs *flag.FlagSet) { fs.BoolVar(&cmd.flags.work, "work", false, "print workdir and don't cleanup on exit") } func (cmd *Cmd) verboseFlag(fs *flag.FlagSet) { fs.BoolVar(&cmd.flags.verbose, "verbose", false, "verbose godebug") } func (cmd *Cmd) syncSendFlag(fs *flag.FlagSet) { fs.BoolVar(&cmd.flags.syncSend, "syncsend", false, "Don't send msgs in chunks (slow). Useful to get msgs before a crash.") } func (cmd *Cmd) toolExecFlag(fs *flag.FlagSet) { fs.StringVar(&cmd.flags.toolExec, "toolexec", "", "execute cmd, useful to run a tool with the output file (ex: wine outputfilename") } func (cmd *Cmd) dirsFlag(fs *flag.FlagSet) { fn := func(s string) error { cmd.flags.dirs = splitCommaList(s) return nil } rf := &runFnFlag{fn} fs.Var(rf, "dirs", "comma-separated `string` of directories to annotate") } func (cmd *Cmd) filesFlag(fs *flag.FlagSet) { fn := func(s string) error { cmd.flags.files = splitCommaList(s) return nil } rf := &runFnFlag{fn} fs.Var(rf, "files", "comma-separated `string` of files to annotate") } func (cmd *Cmd) envFlag(fs *flag.FlagSet) { fn := func(s string) error { cmd.flags.env = filepath.SplitList(s) return nil } rf := &runFnFlag{fn} usage := fmt.Sprintf("`string` with env variables (ex: \"GOOS=os%c...\"'", filepath.ListSeparator) fs.Var(rf, "env", usage) } //------------ type runFnFlag struct { fn func(string) error } func (v runFnFlag) String() string { return "" } func (v runFnFlag) Set(s string) error { return v.fn(s) } //------------ func cmdUsage() string { return `Usage: GoDebug <command> [arguments] The commands are: run build and run program with godebug data test test packages compiled with godebug data build build binary with godebug data (allows remote debug) connect connect to a binary built with godebug data (allows remote debug) Examples: GoDebug -help GoDebug run -help GoDebug run main.go -arg1 -arg2 GoDebug run -dirs=dir1,dir2 -files=f1.go,f2.go main.go -arg1 -arg2 GoDebug test -help GoDebug test GoDebug test -run mytest GoDebug build -addr=:8080 main.go GoDebug connect -addr=:8080 ` } //------------ func mkdirAllWriteFile(filename string, src []byte) error { if err := os.MkdirAll(filepath.Dir(filename), 0770); err != nil { return err } return ioutil.WriteFile(filename, []byte(src), 0660) } func mkdirAllCopyFile(src, dst string) error { if err := os.MkdirAll(filepath.Dir(dst), 0770); err != nil { return err } return copyFile(src, dst) } func copyFile(src, dst string) error { from, err := os.Open(src) if err != nil { return err } defer from.Close() to, err := os.Create(dst) if err != nil { return err } defer to.Close() _, err = io.Copy(to, from) return err } //------------ func mkdirAllCopyFileSync(src, dst string) error { // must exist in src info1, err := os.Stat(src) if os.IsNotExist(err) { return fmt.Errorf("not found in src: %v", src) } // already exists in dest with same modification time info2, err := os.Stat(dst) if !os.IsNotExist(err) { // compare modification time in src if info2.ModTime().Equal(info1.ModTime()) { return nil } } if err := mkdirAllCopyFile(src, dst); err != nil { return err } // set modtime equal to src to avoid copy next time t := info1.ModTime().Local() return os.Chtimes(dst, t, t) } //------------ func replaceExt(filename, ext string) string { // remove extension tmp := filename ext2 := filepath.Ext(tmp) if len(ext2) > 0 { tmp = tmp[:len(tmp)-len(ext2)] } // add new extension return tmp + ext } func normalizeFilenameForExec(filename string) string { if filepath.IsAbs(filename) { return filename } // TODO: review if !strings.HasPrefix(filename, "./") { return "./" + filename } return filename } //------------ func splitCommaList(val string) []string { a := strings.Split(val, ",") u := []string{} for _, s := range a { // don't add empty strings s := strings.TrimSpace(s) if s == "" { continue } u = append(u, s) } return u } //------------ func setupServerNetAddr(addr string) { if addr != "" { debug.ServerNetwork = "tcp" debug.ServerAddress = addr return } // generate address: allows multiple editors to run debug sessions at the same time. seed := time.Now().UnixNano() + int64(os.Getpid()) ra := rand.New(rand.NewSource(seed)) min, max := 27000, 65535 port := min + ra.Intn(max-min) // depend on the desired "target" (can't use runtime.GOOS) goOs := os.Getenv("GOOS") if goOs == "" { goOs = runtime.GOOS } switch goOs { case "linux": debug.ServerNetwork = "unix" p := "editor_godebug.sock" + fmt.Sprintf("%v", port) debug.ServerAddress = filepath.Join(os.TempDir(), p) default: debug.ServerNetwork = "tcp" debug.ServerAddress = fmt.Sprintf("127.0.0.1:%v", port) } }
package main import ( "encoding/json" "log" "net/http" //"bitbucket.org/emicklei/dollar" ) func main() { http.Handle("/", http.FileServer(http.Dir("."))) http.HandleFunc("/recognize", doRecognize) log.Println("dollar test available on http://localhost:8080") log.Fatal(http.ListenAndServe(":8080", nil)) } func doRecognize(w http.ResponseWriter, req *http.Request) { // read points from the request body var list [][]float64 json.NewDecoder(req.Body).Decode(&list) defer req.Body.Close() log.Printf("%#v", list) }
package graphQL import ( "fmt" "github.com/graphql-go/graphql" _ "github.com/jinzhu/gorm/dialects/mssql" "github.com/radyatamaa/loyalti-go-echo/src/domain/model" "github.com/radyatamaa/loyalti-go-echo/src/domain/repository" ) type Song model.Song func MerchantResolver(p graphql.ResolveParams) (interface{}, error) { page, ok := p.Args["page"].(int) size, sip := p.Args["size"].(int) email, mail := p.Args["email"].(string) sort, tap := p.Args["sort"].(int) merchantid, id := p.Args["id"].(int) if ok && sip && tap{ var pages *int = &page var sizes *int = &size var sorts *int = &sort merchant := repository.GetMerchant(pages, sizes, sorts, nil, nil) fmt.Println(merchant) return merchant, nil } else if ok && sip && mail { var pages *int = &page var sizes *int = &size var emails *string = &email merchant := repository.GetMerchant(pages,sizes,nil,emails,nil) return merchant,nil } else if ok && sip && id{ var pages *int = &page var sizes *int = &size var merchantid *int = &merchantid merchant := repository.GetMerchant(pages,sizes,nil,nil,merchantid) return merchant, nil } else if ok && sip { var pages *int = &page var sizes *int = &size merchant := repository.GetMerchant(pages,sizes,nil,nil,nil) return merchant,nil } merchant := repository.GetMerchant(nil, nil, nil, nil, nil) fmt.Println(merchant) return merchant, nil } func MerchantCategoryResolver(p graphql.ResolveParams) (interface{}, error) { page,ok := p.Args["page"].(int) size,sip := p.Args["size"].(int) sort,top := p.Args["sort"].(int) if ok && sip && top{ var pages *int = &page var sizes *int = &size var sorts *int = &sort category := repository.GetCategory(pages, sizes, sorts) fmt.Println(category) return category,nil } category := repository.GetCategory(nil,nil, nil) return category, nil } func MerchantCardTypeResolver(p graphql.ResolveParams) (interface{}, error) { page,ok := p.Args["page"].(int) size, sip := p.Args["size"].(int) sort, top := p.Args["sort"].(int) if ok && sip && top{ var pages *int = &page var sizes *int = &size var sorts *int = &sort card := repository.GetCardType(pages, sizes, sorts) fmt.Println(card) return card, nil } card := repository.GetCardType(nil,nil, nil) return card, nil } func SocialMediaResolver(p graphql.ResolveParams) (interface{}, error) { page,ok := p.Args["page"].(int) size,sip := p.Args["size"].(int) sort,top := p.Args["sort"].(int) if ok && sip && top{ var pages *int = &page var sizes *int = &size var sorts *int = &sort sosmed := repository.GetSocialMedia(pages, sizes, sorts) fmt.Println(sosmed) return sosmed,nil } sosmed := repository.GetSocialMedia(nil, nil, nil) return sosmed, nil } func ProvinceResolver (p graphql.ResolveParams) (interface{}, error){ page, ok := p.Args["page"].(int) size, sip := p.Args["size"].(int) sort, top := p.Args["sort"].(int) if ok && sip && top { var pages *int = &page var sizes *int = &size var sorts *int = &sort province := repository.GetProvince(pages, sizes, sorts) fmt.Println(province) return province, nil } province := repository.GetProvince(nil, nil, nil) return province, nil } func CityResolver (p graphql.ResolveParams) (interface{}, error){ page, ok := p.Args["page"].(int) size, sip := p.Args["size"].(int) sort, top := p.Args["sort"].(int) if ok && sip && top { var pages *int = &page var sizes *int = &size var sorts *int = &sort province := repository.GetCity(pages, sizes, sorts) fmt.Println(province) return province, nil } province := repository.GetCity(nil, nil, nil) return province, nil } func SpecialProgramResolver(p graphql.ResolveParams) (interface{}, error) { page,ok := p.Args["page"].(int) size,sip := p.Args["size"].(int) sort,deh := p.Args["sort"].(int) category,cat := p.Args["category"].(int) detail,id := p.Args["id"].(int) if ok && sip && deh && cat { fmt.Println("12345") var pagination *int = &page var sizing *int = &size var category *int = &category var sorting *int = &sort special := repository.GetSpecialProgram(pagination,sizing,sorting,category, nil) //fmt.Println(program) return special,nil }else if ok && sip && deh { fmt.Println("5678") var pages *int = &page var sizes *int = &size var sorts *int = &sort //var cats *int = &category special := repository.GetSpecialProgram(pages, sizes, sorts,nil, nil) //fmt.Println(program) return special,nil } else if ok && sip { fmt.Println("7890") var paging *int = &page var sizing *int = &size special := repository.GetSpecialProgram(paging, sizing, nil, nil, nil) //fmt.Println(program) return special,nil } else if id { var detail *int = &detail special := repository.GetSpecialProgram(nil, nil,nil,nil, detail) return special, nil } special := repository.GetSpecialProgram(nil,nil, nil, nil, nil) return special, nil } //program function func ProgramResolver(p graphql.ResolveParams) (interface{}, error) { page,ok := p.Args["page"].(int) size,sip := p.Args["size"].(int) sort,deh := p.Args["sort"].(int) category, cat := p.Args["category"].(int) detail, id := p.Args["id"].(int) if ok && sip && deh && cat { var pagination *int = &page var sizing *int = &size var category *int = &category var sorting *int = &sort program := repository.GetProgram(pagination,sizing,sorting,category,nil) //fmt.Println(program) return program,nil }else if ok && sip && deh { var pages *int = &page var sizes *int = &size var sorts *int = &sort //var cats *int = &category program := repository.GetProgram(pages, sizes, sorts,nil,nil) //fmt.Println(program) return program,nil } else if ok && sip { var paging *int = &page var sizing *int = &size program := repository.GetProgram(paging, sizing, nil, nil,nil) //fmt.Println(program) return program,nil } else if id { var detail *int = &detail program := repository.GetProgram(nil,nil,nil,nil, detail) return program,nil } program := repository.GetProgram(nil,nil, nil, nil,nil) return program, nil } func OutletResolver(p graphql.ResolveParams) (interface{}, error) { page, ok := p.Args["page"].(int) size, sip := p.Args["size"].(int) id, top := p.Args["id"].(int) email, mail := p.Args["email"].(string) if ok && sip && top && mail{ var pages *int = &page var sizes *int = &size var merchant_id *int = &id var emails *string = &email outlet := repository.GetOutlet(pages, sizes, merchant_id, emails) fmt.Println(outlet) return outlet,nil } else if ok && sip && mail { var paging *int = &page var sizing *int = &size var emails *string = &email outlet := repository.GetOutlet(paging, sizing, nil, emails) return outlet, nil } else if ok && sip && top{ var paging *int = &page var sizing *int = &size var merchant *int = &id outlet := repository.GetOutlet(paging, sizing, merchant, nil) return outlet,nil } else if ok && sip{ var paging *int = &page var sizing *int = &size outlet := repository.GetOutlet(paging, sizing, nil, nil) return outlet,nil } outlet := repository.GetOutlet(nil,nil, nil, nil) return outlet, nil } func EmployeeResolver(p graphql.ResolveParams) (interface{}, error) { page,ok := p.Args["page"].(int) size,sip := p.Args["size"].(int) sort, top := p.Args["id"].(int) if ok && sip && top{ var pages *int = &page var sizes *int = &size var sorts *int = &sort employee := repository.GetEmployee(pages, sizes, sorts) fmt.Println(employee) return employee,nil } else if ok && sip{ var paging *int = &page var sizing *int = &size var sorting *int = &sort employee := repository.GetEmployee(paging, sizing, sorting) return employee,nil } employee := repository.GetEmployee(nil,nil, nil) return employee, nil } func TotalPointResolver(p graphql.ResolveParams)(interface{}, error){ id := p.Args["id"].(int) pay := p.Args["pay"].(int) pin := p.Args["pin"].(string) outletid := p.Args["outletid"].(string) cardtype := p.Args["cardtype"].(string) var ids int = id var pays int = pay var pins string = pin var outletids string = outletid var cardtypes string = cardtype total := repository.TotalPoint(ids, pays, pins, outletids, cardtypes) return total, nil } func TotalChopResolver(p graphql.ResolveParams)(interface{}, error){ id := p.Args["id"].(int) pay := p.Args["pay"].(int) pin := p.Args["pin"].(string) outletid := p.Args["outletid"].(string) cardtype := p.Args["cardtype"].(string) var ids int = id var pays int = pay var pins string = pin var outletids string = outletid var cardtypes string = cardtype total := repository.TotalChop(ids, pays, pins, outletids, cardtypes) return total, nil } //func MerchantCardMemberResolver(p graphql.ResolveParams)(interface{}, error){ // fmt.Println("masuk ke resolver member") // program_id := p.Args["program_id"].(int) // var program_ids int = program_id // card := repository.GetCardMember(program_ids) // fmt.Println(card) // return card, nil //} func TransactionResolver (p graphql.ResolveParams)(interface{}, error){ page, ok := p.Args["page"].(int) size, sip := p.Args["size"].(int) sort, top := p.Args["sort"].(int) outletid, tap := p.Args["outletid"].(string) if ok && sip && top && tap{ var pages *int = &page var sizes *int = &size var sorts *int = &sort var outletids *string = &outletid transaction := repository.GetTransaction(pages, sizes, sorts, outletids) fmt.Println(transaction) return transaction, nil } transaction := repository.GetTransaction(nil, nil, nil, nil) return transaction, nil } func SongResolver(p graphql.ResolveParams) (interface{}, error) { users := []Song{ Song{ ID: "1", Album: "ts-fearless", Title: "Fearless", Duration: "4:01", Type: "song", }, Song{ ID: "2", Album: "ts-fearless", Title: "Fifteen", Duration: "4:54", Type: "song", }, } return users, nil //return nil, nil } func CardResolver(p graphql.ResolveParams) (interface{}, error) { fmt.Println("masuk ke resolver card") page,ok := p.Args["page"].(int) size,sip := p.Args["size"].(int) id, top := p.Args["id"].(int) card_type, tipe := p.Args["card_type"].(string) var outlet []model.Card if (card_type == "Member"){ fmt.Println("masuk ke if member") outlet = repository.GetCardMember(id) } fmt.Println("keluar dari if member") if ok && sip && top && tipe{ fmt.Println("masuk ke if pertama") var pages *int = &page var sizes *int = &size var top *int = &id var types *string = &card_type outlet := repository.GetCardMerchant(pages, sizes, top, types) return outlet, nil } else if ok && sip && top{ fmt.Println("masuk ke if kedua") var pages *int = &page var sizes *int = &size var card_id *int = &id outlet := repository.GetCardMerchant(pages, sizes, card_id,nil) fmt.Println(outlet) return outlet,nil } else if ok && sip{ fmt.Println("masuk ke if ketiga") var paging *int = &page var sizing *int = &size outlet := repository.GetCardMerchant(paging, sizing, nil, nil) return outlet,nil } fmt.Println("lewat semua") //outlet := repository.GetCardMerchant(nil,nil, nil, nil) return outlet, nil } func VoucherResolver (p graphql.ResolveParams) (interface{}, error) { page, ok := p.Args["page"].(int) size, sip := p.Args["size"].(int) sort, top := p.Args["sort"].(int) merchant_id, tap := p.Args["merchant_id"].(int) if ok && sip && top && tap{ var pages *int = &page var sizes *int = &size var sorts *int = &sort var merchant_ids *int = &merchant_id voucher := repository.GetVoucher(pages, sizes, sorts, merchant_ids) fmt.Println(voucher) return voucher, nil } voucher := repository.GetVoucher(nil, nil, nil, nil) return voucher, nil } //func MerchantResolve() { // //}
package dbinstance import ( "context" "encoding/json" "errors" "fmt" "strings" "time" "github.com/kloeckner-i/db-operator/pkg/utils/gcloud" "github.com/kloeckner-i/db-operator/pkg/utils/kci" "github.com/sirupsen/logrus" "golang.org/x/oauth2/google" sqladmin "google.golang.org/api/sqladmin/v1beta4" ) // Gsql represents a google sql instance type Gsql struct { Name string Config string User string Password string } func getSqladminService(ctx context.Context) (*sqladmin.Service, error) { oauthClient, err := google.DefaultClient(ctx, sqladmin.CloudPlatformScope) if err != nil { logrus.Errorf("failed to get google auth client %s", err) return nil, err } sqladminService, err := sqladmin.New(oauthClient) if err != nil { logrus.Debugf("error occurs during getting sqladminService %s", err) return nil, err } return sqladminService, nil } func getGsqlInstance(name string) (*sqladmin.DatabaseInstance, error) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() sqladminService, err := getSqladminService(ctx) if err != nil { return nil, err } serviceaccount := gcloud.GetServiceAccount() rs, err := sqladminService.Instances.Get(serviceaccount.ProjectID, name).Context(ctx).Do() if err != nil { return nil, err } return rs, nil } func updateGsqlUser(instance, user, password string) error { logrus.Debugf("gsql user update - instance: %s, user: %s", instance, user) ctx, cancel := context.WithCancel(context.Background()) defer cancel() sqladminService, err := getSqladminService(ctx) if err != nil { return err } host := "%" rb := &sqladmin.User{ Password: password, } serviceaccount := gcloud.GetServiceAccount() project := serviceaccount.ProjectID resp, err := sqladminService.Users.Update(project, instance, user, rb).Host(host).Context(ctx).Do() if err != nil { return err } logrus.Debugf("user update api response: %#v", resp) return nil } func (ins *Gsql) verifyConfig() (*sqladmin.DatabaseInstance, error) { //require non empty name and config rb := &sqladmin.DatabaseInstance{} err := json.Unmarshal([]byte(ins.Config), rb) if err != nil { logrus.Errorf("can not verify config - %s", err) logrus.Debugf("%#v\n", []byte(ins.Config)) return nil, err } rb.Name = ins.Name return rb, nil } func (ins *Gsql) waitUntilRunnable() error { const delay = 30 time.Sleep(delay * time.Second) err := kci.Retry(10, 60*time.Second, func() error { instance, err := getGsqlInstance(ins.Name) if err != nil { return err } logrus.Debugf("waiting gsql instance %s state: %s", ins.Name, instance.State) if instance.State != "RUNNABLE" { return errors.New("gsql instance not ready yet") } return nil }) if err != nil { instance, err := getGsqlInstance(ins.Name) if err != nil { return err } return fmt.Errorf("gsql instance state not ready %s", instance.State) } return nil } func (ins *Gsql) create() error { logrus.Debugf("gsql instance create %s", ins.Name) request, err := ins.verifyConfig() if err != nil { return err } ctx, cancel := context.WithCancel(context.Background()) defer cancel() sqladminService, err := getSqladminService(ctx) if err != nil { return err } // Project ID of the project to which the newly created Cloud SQL instances should belong. serviceaccount := gcloud.GetServiceAccount() project := serviceaccount.ProjectID resp, err := sqladminService.Instances.Insert(project, request).Context(ctx).Do() if err != nil { logrus.Errorf("gsql instance insert error - %s", err) return err } logrus.Debugf("instance insert api response: %#v", resp) err = ins.waitUntilRunnable() if err != nil { return fmt.Errorf("gsql instance created but still not runnable - %s", err) } err = updateGsqlUser(ins.Name, ins.User, ins.Password) if err != nil { logrus.Errorf("gsql user update error - %s", err) return err } return nil } func (ins *Gsql) update() error { logrus.Debugf("gsql instance update %s", ins.Name) request, err := ins.verifyConfig() if err != nil { return err } ctx, cancel := context.WithCancel(context.Background()) defer cancel() sqladminService, err := getSqladminService(ctx) if err != nil { return err } // Project ID of the project to which the newly created Cloud SQL instances should belong. serviceaccount := gcloud.GetServiceAccount() project := serviceaccount.ProjectID resp, err := sqladminService.Instances.Patch(project, ins.Name, request).Context(ctx).Do() if err != nil { logrus.Errorf("gsql instance patch error - %s", err) return err } logrus.Debugf("instance patch api response: %#v", resp) err = ins.waitUntilRunnable() if err != nil { return fmt.Errorf("gsql instance updated but still not runnable - %s", err) } err = updateGsqlUser(ins.Name, ins.User, ins.Password) if err != nil { logrus.Errorf("gsql user update error - %s", err) return err } return nil } func (ins *Gsql) exist() error { _, err := getGsqlInstance(ins.Name) if err != nil { logrus.Debugf("gsql instance get failed %s", err) return err } return nil // instance exist } func (ins *Gsql) getInfoMap() (map[string]string, error) { instance, err := getGsqlInstance(ins.Name) if err != nil { return nil, err } data := map[string]string{ "DB_INSTANCE": instance.Name, "DB_CONN": instance.ConnectionName, "DB_PUBLIC_IP": getGsqlPublicIP(instance), "DB_PORT": determineGsqlPort(instance), "DB_VERSION": instance.DatabaseVersion, } return data, nil } func getGsqlPublicIP(instance *sqladmin.DatabaseInstance) string { for _, ip := range instance.IpAddresses { if ip.Type == "PRIMARY" { return ip.IpAddress } } return "-" } func determineGsqlPort(instance *sqladmin.DatabaseInstance) string { databaseVersion := strings.ToLower(instance.DatabaseVersion) if strings.Contains(databaseVersion, "postgres") { return "5432" } if strings.Contains(databaseVersion, "mysql") { return "3306" } return "-" }
package radio type SongServer interface { Search(query string) ([]Track, error) Track(id string) (Track, error) } type Tracks struct { Items []Track } type Track struct { Artists []Artist Name string ID string Album Album } type Album struct { Name string Images []Image } type Artist struct { Name string } type Image struct { Width int Height int URL string }
package main import ( "fmt" "os" "time" "github.com/urfave/cli" ) func main() { app := &cli.App{ Name: "release-cli", Usage: "Release in Pegasus's convention", Commands: []cli.Command{ *addCommand, *showCommand, *submitCommand, }, Action: func(c *cli.Context) error { return cli.ShowAppHelp(c) }, Compiled: time.Now(), HideVersion: true, } if err := app.Run(os.Args); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
/* * Copyright 2018-present Open Networking Foundation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package api import ( "context" "errors" "github.com/golang/protobuf/ptypes" "github.com/golang/protobuf/ptypes/empty" "github.com/opencord/voltha-go/rw_core/core/adapter" "github.com/opencord/voltha-go/rw_core/core/device" "github.com/opencord/voltha-lib-go/v4/pkg/kafka" "github.com/opencord/voltha-lib-go/v4/pkg/log" ic "github.com/opencord/voltha-protos/v4/go/inter_container" "github.com/opencord/voltha-protos/v4/go/voltha" ) // AdapterRequestHandlerProxy represent adapter request handler proxy attributes type AdapterRequestHandlerProxy struct { deviceMgr *device.Manager adapterMgr *adapter.Manager } // NewAdapterRequestHandlerProxy assigns values for adapter request handler proxy attributes and returns the new instance func NewAdapterRequestHandlerProxy(dMgr *device.Manager, aMgr *adapter.Manager) *AdapterRequestHandlerProxy { return &AdapterRequestHandlerProxy{ deviceMgr: dMgr, adapterMgr: aMgr, } } func (rhp *AdapterRequestHandlerProxy) Register(ctx context.Context, args []*ic.Argument) (*voltha.CoreInstance, error) { if len(args) < 3 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } adapter := &voltha.Adapter{} deviceTypes := &voltha.DeviceTypes{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "adapter": if err := ptypes.UnmarshalAny(arg.Value, adapter); err != nil { logger.Warnw(ctx, "cannot-unmarshal-adapter", log.Fields{"error": err}) return nil, err } case "deviceTypes": if err := ptypes.UnmarshalAny(arg.Value, deviceTypes); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-types", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "Register", log.Fields{"adapter": *adapter, "device-types": deviceTypes, "transaction-id": transactionID.Val}) return rhp.adapterMgr.RegisterAdapter(ctx, adapter, deviceTypes) } // GetDevice returns device info func (rhp *AdapterRequestHandlerProxy) GetDevice(ctx context.Context, args []*ic.Argument) (*voltha.Device, error) { if len(args) < 2 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } pID := &voltha.ID{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, pID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-ID", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "getDevice", log.Fields{"device-id": pID.Id, "transactionID": transactionID.Val}) // Get the device via the device manager device, err := rhp.deviceMgr.GetDevice(log.WithSpanFromContext(context.TODO(), ctx), pID) if err != nil { logger.Debugw(ctx, "get-device-failed", log.Fields{"device-id": pID.Id, "error": err}) } return device, err } // DeviceUpdate updates device using adapter data func (rhp *AdapterRequestHandlerProxy) DeviceUpdate(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 2 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } device := &voltha.Device{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device": if err := ptypes.UnmarshalAny(arg.Value, device); err != nil { logger.Warnw(ctx, "cannot-unmarshal-ID", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "DeviceUpdate", log.Fields{"device-id": device.Id, "transactionID": transactionID.Val}) if err := rhp.deviceMgr.UpdateDeviceUsingAdapterData(log.WithSpanFromContext(context.TODO(), ctx), device); err != nil { logger.Debugw(ctx, "unable-to-update-device-using-adapter-data", log.Fields{"error": err}) return nil, err } return &empty.Empty{}, nil } // GetChildDevice returns details of child device func (rhp *AdapterRequestHandlerProxy) GetChildDevice(ctx context.Context, args []*ic.Argument) (*voltha.Device, error) { if len(args) < 3 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } pID := &voltha.ID{} transactionID := &ic.StrType{} serialNumber := &ic.StrType{} onuID := &ic.IntType{} parentPortNo := &ic.IntType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, pID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-ID", log.Fields{"error": err}) return nil, err } case "serial_number": if err := ptypes.UnmarshalAny(arg.Value, serialNumber); err != nil { logger.Warnw(ctx, "cannot-unmarshal-ID", log.Fields{"error": err}) return nil, err } case "onu_id": if err := ptypes.UnmarshalAny(arg.Value, onuID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-ID", log.Fields{"error": err}) return nil, err } case "parent_port_no": if err := ptypes.UnmarshalAny(arg.Value, parentPortNo); err != nil { logger.Warnw(ctx, "cannot-unmarshal-ID", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "GetChildDevice", log.Fields{"parent-device-id": pID.Id, "args": args, "transactionID": transactionID.Val}) return rhp.deviceMgr.GetChildDevice(log.WithSpanFromContext(context.TODO(), ctx), pID.Id, serialNumber.Val, onuID.Val, parentPortNo.Val) } // GetChildDeviceWithProxyAddress returns details of child device with proxy address func (rhp *AdapterRequestHandlerProxy) GetChildDeviceWithProxyAddress(ctx context.Context, args []*ic.Argument) (*voltha.Device, error) { if len(args) < 2 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } proxyAddress := &voltha.Device_ProxyAddress{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "proxy_address": if err := ptypes.UnmarshalAny(arg.Value, proxyAddress); err != nil { logger.Warnw(ctx, "cannot-unmarshal-proxy-address", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "GetChildDeviceWithProxyAddress", log.Fields{"proxyAddress": proxyAddress, "transactionID": transactionID.Val}) return rhp.deviceMgr.GetChildDeviceWithProxyAddress(log.WithSpanFromContext(context.TODO(), ctx), proxyAddress) } // GetPorts returns the ports information of the device based on the port type. func (rhp *AdapterRequestHandlerProxy) GetPorts(ctx context.Context, args []*ic.Argument) (*voltha.Ports, error) { if len(args) < 3 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } deviceID := &voltha.ID{} pt := &ic.IntType{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, deviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case "port_type": if err := ptypes.UnmarshalAny(arg.Value, pt); err != nil { logger.Warnw(ctx, "cannot-unmarshal-porttype", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "GetPorts", log.Fields{"device-id": deviceID.Id, "portype": pt.Val, "transactionID": transactionID.Val}) return rhp.deviceMgr.GetPorts(log.WithSpanFromContext(context.TODO(), ctx), deviceID.Id, voltha.Port_PortType(pt.Val)) } // GetChildDevices gets all the child device IDs from the device passed as parameter func (rhp *AdapterRequestHandlerProxy) GetChildDevices(ctx context.Context, args []*ic.Argument) (*voltha.Devices, error) { if len(args) < 2 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } pID := &voltha.ID{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, pID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-ID", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "GetChildDevices", log.Fields{"device-id": pID.Id, "transactionID": transactionID.Val}) return rhp.deviceMgr.GetAllChildDevices(log.WithSpanFromContext(context.TODO(), ctx), pID.Id) } // ChildDeviceDetected is invoked when a child device is detected. The following parameters are expected: // {parent_device_id, parent_port_no, child_device_type, channel_id, vendor_id, serial_number) func (rhp *AdapterRequestHandlerProxy) ChildDeviceDetected(ctx context.Context, args []*ic.Argument) (*voltha.Device, error) { if len(args) < 5 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } pID := &voltha.ID{} portNo := &ic.IntType{} dt := &ic.StrType{} chnlID := &ic.IntType{} transactionID := &ic.StrType{} serialNumber := &ic.StrType{} vendorID := &ic.StrType{} onuID := &ic.IntType{} for _, arg := range args { switch arg.Key { case "parent_device_id": if err := ptypes.UnmarshalAny(arg.Value, pID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-parent-device-id", log.Fields{"error": err}) return nil, err } case "parent_port_no": if err := ptypes.UnmarshalAny(arg.Value, portNo); err != nil { logger.Warnw(ctx, "cannot-unmarshal-parent-port", log.Fields{"error": err}) return nil, err } case "child_device_type": if err := ptypes.UnmarshalAny(arg.Value, dt); err != nil { logger.Warnw(ctx, "cannot-unmarshal-child-device-type", log.Fields{"error": err}) return nil, err } case "channel_id": if err := ptypes.UnmarshalAny(arg.Value, chnlID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-channel-id", log.Fields{"error": err}) return nil, err } case "vendor_id": if err := ptypes.UnmarshalAny(arg.Value, vendorID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-vendor-id", log.Fields{"error": err}) return nil, err } case "serial_number": if err := ptypes.UnmarshalAny(arg.Value, serialNumber); err != nil { logger.Warnw(ctx, "cannot-unmarshal-serial-number", log.Fields{"error": err}) return nil, err } case "onu_id": if err := ptypes.UnmarshalAny(arg.Value, onuID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-onu-id", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "ChildDeviceDetected", log.Fields{"parent-device-id": pID.Id, "parentPortNo": portNo.Val, "deviceType": dt.Val, "channelID": chnlID.Val, "serialNumber": serialNumber.Val, "vendorID": vendorID.Val, "onuID": onuID.Val, "transactionID": transactionID.Val}) device, err := rhp.deviceMgr.ChildDeviceDetected(log.WithSpanFromContext(context.TODO(), ctx), pID.Id, portNo.Val, dt.Val, chnlID.Val, vendorID.Val, serialNumber.Val, onuID.Val) if err != nil { logger.Debugw(ctx, "child-detection-failed", log.Fields{"parent-device-id": pID.Id, "onuID": onuID.Val, "error": err}) } return device, err } // DeviceStateUpdate updates device status func (rhp *AdapterRequestHandlerProxy) DeviceStateUpdate(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 3 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } deviceID := &voltha.ID{} operStatus := &ic.IntType{} connStatus := &ic.IntType{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, deviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case "oper_status": if err := ptypes.UnmarshalAny(arg.Value, operStatus); err != nil { logger.Warnw(ctx, "cannot-unmarshal-operStatus", log.Fields{"error": err}) return nil, err } case "connect_status": if err := ptypes.UnmarshalAny(arg.Value, connStatus); err != nil { logger.Warnw(ctx, "cannot-unmarshal-connStatus", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "DeviceStateUpdate", log.Fields{"device-id": deviceID.Id, "oper-status": operStatus, "conn-status": connStatus, "transactionID": transactionID.Val}) if err := rhp.deviceMgr.UpdateDeviceStatus(log.WithSpanFromContext(context.TODO(), ctx), deviceID.Id, voltha.OperStatus_Types(operStatus.Val), voltha.ConnectStatus_Types(connStatus.Val)); err != nil { logger.Debugw(ctx, "unable-to-update-device-status", log.Fields{"error": err}) return nil, err } return &empty.Empty{}, nil } // ChildrenStateUpdate updates child device status func (rhp *AdapterRequestHandlerProxy) ChildrenStateUpdate(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 3 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } deviceID := &voltha.ID{} operStatus := &ic.IntType{} connStatus := &ic.IntType{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, deviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case "oper_status": if err := ptypes.UnmarshalAny(arg.Value, operStatus); err != nil { logger.Warnw(ctx, "cannot-unmarshal-operStatus", log.Fields{"error": err}) return nil, err } case "connect_status": if err := ptypes.UnmarshalAny(arg.Value, connStatus); err != nil { logger.Warnw(ctx, "cannot-unmarshal-connStatus", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "ChildrenStateUpdate", log.Fields{"device-id": deviceID.Id, "oper-status": operStatus, "conn-status": connStatus, "transactionID": transactionID.Val}) // When the enum is not set (i.e. -1), Go still convert to the Enum type with the value being -1 if err := rhp.deviceMgr.UpdateChildrenStatus(log.WithSpanFromContext(context.TODO(), ctx), deviceID.Id, voltha.OperStatus_Types(operStatus.Val), voltha.ConnectStatus_Types(connStatus.Val)); err != nil { logger.Debugw(ctx, "unable-to-update-children-status", log.Fields{"error": err}) return nil, err } return &empty.Empty{}, nil } // PortsStateUpdate updates the ports state related to the device func (rhp *AdapterRequestHandlerProxy) PortsStateUpdate(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 2 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } deviceID := &voltha.ID{} portTypeFilter := &ic.IntType{} operStatus := &ic.IntType{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, deviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case "port_type_filter": if err := ptypes.UnmarshalAny(arg.Value, portTypeFilter); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case "oper_status": if err := ptypes.UnmarshalAny(arg.Value, operStatus); err != nil { logger.Warnw(ctx, "cannot-unmarshal-operStatus", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "PortsStateUpdate", log.Fields{"device-id": deviceID.Id, "operStatus": operStatus, "transactionID": transactionID.Val}) if err := rhp.deviceMgr.UpdatePortsState(log.WithSpanFromContext(context.TODO(), ctx), deviceID.Id, uint32(portTypeFilter.Val), voltha.OperStatus_Types(operStatus.Val)); err != nil { logger.Debugw(ctx, "unable-to-update-ports-state", log.Fields{"error": err}) return nil, err } return &empty.Empty{}, nil } // PortStateUpdate updates the port state of the device func (rhp *AdapterRequestHandlerProxy) PortStateUpdate(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 3 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } deviceID := &voltha.ID{} portType := &ic.IntType{} portNo := &ic.IntType{} operStatus := &ic.IntType{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, deviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case "oper_status": if err := ptypes.UnmarshalAny(arg.Value, operStatus); err != nil { logger.Warnw(ctx, "cannot-unmarshal-operStatus", log.Fields{"error": err}) return nil, err } case "port_type": if err := ptypes.UnmarshalAny(arg.Value, portType); err != nil { logger.Warnw(ctx, "cannot-unmarshal-porttype", log.Fields{"error": err}) return nil, err } case "port_no": if err := ptypes.UnmarshalAny(arg.Value, portNo); err != nil { logger.Warnw(ctx, "cannot-unmarshal-portno", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "PortStateUpdate", log.Fields{"device-id": deviceID.Id, "operStatus": operStatus, "portType": portType, "portNo": portNo, "transactionID": transactionID.Val}) if err := rhp.deviceMgr.UpdatePortState(log.WithSpanFromContext(context.TODO(), ctx), deviceID.Id, voltha.Port_PortType(portType.Val), uint32(portNo.Val), voltha.OperStatus_Types(operStatus.Val)); err != nil { // If the error doesn't change behavior and is essentially ignored, it is not an error, it is a // warning. // TODO: VOL-2707 logger.Debugw(ctx, "unable-to-update-port-state", log.Fields{"error": err}) return nil, err } return &empty.Empty{}, nil } // DeleteAllPorts deletes all ports of device func (rhp *AdapterRequestHandlerProxy) DeleteAllPorts(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 3 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } deviceID := &voltha.ID{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, deviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "DeleteAllPorts", log.Fields{"device-id": deviceID.Id, "transactionID": transactionID.Val}) if err := rhp.deviceMgr.DeleteAllPorts(log.WithSpanFromContext(context.TODO(), ctx), deviceID.Id); err != nil { logger.Debugw(ctx, "unable-to-delete-ports", log.Fields{"error": err}) return nil, err } return &empty.Empty{}, nil } // GetDevicePort returns a single port func (rhp *AdapterRequestHandlerProxy) GetDevicePort(ctx context.Context, args []*ic.Argument) (*voltha.Port, error) { if len(args) < 3 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } deviceID := &voltha.ID{} portNo := &ic.IntType{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, deviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case "port_no": if err := ptypes.UnmarshalAny(arg.Value, portNo); err != nil { logger.Warnw(ctx, "cannot-unmarshal-port-no", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "GetDevicePort", log.Fields{"device-id": deviceID.Id, "portNo": portNo.Val, "transactionID": transactionID.Val}) return rhp.deviceMgr.GetDevicePort(log.WithSpanFromContext(context.TODO(), ctx), deviceID.Id, uint32(portNo.Val)) } // ListDevicePorts returns all ports belonging to the device func (rhp *AdapterRequestHandlerProxy) ListDevicePorts(ctx context.Context, args []*ic.Argument) (*voltha.Ports, error) { if len(args) < 2 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } deviceID := &voltha.ID{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, deviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "ListDevicePorts", log.Fields{"device-id": deviceID.Id, "transactionID": transactionID.Val}) return rhp.deviceMgr.ListDevicePorts(log.WithSpanFromContext(context.TODO(), ctx), deviceID) } // ChildDevicesLost indicates that a parent device is in a state (Disabled) where it cannot manage the child devices. // This will trigger the Core to disable all the child devices. func (rhp *AdapterRequestHandlerProxy) ChildDevicesLost(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 2 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } parentDeviceID := &voltha.ID{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "parent_device_id": if err := ptypes.UnmarshalAny(arg.Value, parentDeviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "ChildDevicesLost", log.Fields{"device-id": parentDeviceID.Id, "transactionID": transactionID.Val}) if err := rhp.deviceMgr.ChildDevicesLost(log.WithSpanFromContext(context.TODO(), ctx), parentDeviceID.Id); err != nil { logger.Debugw(ctx, "unable-to-disable-child-devices", log.Fields{"error": err}) return nil, err } return &empty.Empty{}, nil } // ChildDevicesDetected invoked by an adapter when child devices are found, typically after after a disable/enable sequence. // This will trigger the Core to Enable all the child devices of that parent. func (rhp *AdapterRequestHandlerProxy) ChildDevicesDetected(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 2 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } parentDeviceID := &voltha.ID{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "parent_device_id": if err := ptypes.UnmarshalAny(arg.Value, parentDeviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "ChildDevicesDetected", log.Fields{"parent-device-id": parentDeviceID.Id, "transactionID": transactionID.Val}) if err := rhp.deviceMgr.ChildDevicesDetected(log.WithSpanFromContext(context.TODO(), ctx), parentDeviceID.Id); err != nil { logger.Debugw(ctx, "child-devices-detection-failed", log.Fields{"parent-device-id": parentDeviceID.Id, "error": err}) return nil, err } return &empty.Empty{}, nil } // PortCreated adds port to device func (rhp *AdapterRequestHandlerProxy) PortCreated(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 3 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } deviceID := &voltha.ID{} port := &voltha.Port{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, deviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case "port": if err := ptypes.UnmarshalAny(arg.Value, port); err != nil { logger.Warnw(ctx, "cannot-unmarshal-port", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "PortCreated", log.Fields{"device-id": deviceID.Id, "port": port, "transactionID": transactionID.Val}) if err := rhp.deviceMgr.AddPort(log.WithSpanFromContext(context.TODO(), ctx), deviceID.Id, port); err != nil { logger.Debugw(ctx, "unable-to-add-port", log.Fields{"error": err}) return nil, err } return &empty.Empty{}, nil } // DevicePMConfigUpdate initializes the pm configs as defined by the adapter. func (rhp *AdapterRequestHandlerProxy) DevicePMConfigUpdate(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 2 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } pmConfigs := &voltha.PmConfigs{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_pm_config": if err := ptypes.UnmarshalAny(arg.Value, pmConfigs); err != nil { logger.Warnw(ctx, "cannot-unmarshal-pm-config", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "DevicePMConfigUpdate", log.Fields{"device-id": pmConfigs.Id, "configs": pmConfigs, "transactionID": transactionID.Val}) if err := rhp.deviceMgr.InitPmConfigs(log.WithSpanFromContext(context.TODO(), ctx), pmConfigs.Id, pmConfigs); err != nil { logger.Debugw(ctx, "unable-to-initialize-pm-configs", log.Fields{"error": err}) return nil, err } return &empty.Empty{}, nil } // PacketIn sends the incoming packet of device func (rhp *AdapterRequestHandlerProxy) PacketIn(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 4 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } deviceID := &voltha.ID{} portNo := &ic.IntType{} packet := &ic.Packet{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, deviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case "port": if err := ptypes.UnmarshalAny(arg.Value, portNo); err != nil { logger.Warnw(ctx, "cannot-unmarshal-port-no", log.Fields{"error": err}) return nil, err } case "packet": if err := ptypes.UnmarshalAny(arg.Value, packet); err != nil { logger.Warnw(ctx, "cannot-unmarshal-packet", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "PacketIn", log.Fields{"device-id": deviceID.Id, "port": portNo.Val, "packet": packet, "transactionID": transactionID.Val}) if err := rhp.deviceMgr.PacketIn(log.WithSpanFromContext(context.TODO(), ctx), deviceID.Id, uint32(portNo.Val), transactionID.Val, packet.Payload); err != nil { logger.Debugw(ctx, "unable-to-receive-packet-from-adapter", log.Fields{"error": err}) return nil, err } return &empty.Empty{}, nil } // UpdateImageDownload updates image download func (rhp *AdapterRequestHandlerProxy) UpdateImageDownload(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 2 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } deviceID := &voltha.ID{} img := &voltha.ImageDownload{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, deviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case "image_download": if err := ptypes.UnmarshalAny(arg.Value, img); err != nil { logger.Warnw(ctx, "cannot-unmarshal-imgaeDownload", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "UpdateImageDownload", log.Fields{"device-id": deviceID.Id, "image-download": img, "transactionID": transactionID.Val}) if err := rhp.deviceMgr.UpdateImageDownload(log.WithSpanFromContext(context.TODO(), ctx), deviceID.Id, img); err != nil { logger.Debugw(ctx, "unable-to-update-image-download", log.Fields{"error": err}) return nil, err } return &empty.Empty{}, nil } // ReconcileChildDevices reconciles child devices func (rhp *AdapterRequestHandlerProxy) ReconcileChildDevices(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 2 { logger.Warn(ctx, "invalid-number-of-args", log.Fields{"args": args}) err := errors.New("invalid-number-of-args") return nil, err } parentDeviceID := &voltha.ID{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "parent_device_id": if err := ptypes.UnmarshalAny(arg.Value, parentDeviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "ReconcileChildDevices", log.Fields{"parent-device-id": parentDeviceID.Id, "transactionID": transactionID.Val}) if err := rhp.deviceMgr.ReconcileChildDevices(log.WithSpanFromContext(context.TODO(), ctx), parentDeviceID.Id); err != nil { logger.Debugw(ctx, "unable-to-reconcile-child-devices", log.Fields{"error": err}) return nil, err } return &empty.Empty{}, nil } // DeviceReasonUpdate updates device reason func (rhp *AdapterRequestHandlerProxy) DeviceReasonUpdate(ctx context.Context, args []*ic.Argument) (*empty.Empty, error) { if len(args) < 2 { logger.Warn(ctx, "DeviceReasonUpdate: invalid-number-of-args", log.Fields{"args": args}) err := errors.New("DeviceReasonUpdate: invalid-number-of-args") return nil, err } deviceID := &voltha.ID{} reason := &ic.StrType{} transactionID := &ic.StrType{} for _, arg := range args { switch arg.Key { case "device_id": if err := ptypes.UnmarshalAny(arg.Value, deviceID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-device-id", log.Fields{"error": err}) return nil, err } case "device_reason": if err := ptypes.UnmarshalAny(arg.Value, reason); err != nil { logger.Warnw(ctx, "cannot-unmarshal-reason", log.Fields{"error": err}) return nil, err } case kafka.TransactionKey: if err := ptypes.UnmarshalAny(arg.Value, transactionID); err != nil { logger.Warnw(ctx, "cannot-unmarshal-transaction-ID", log.Fields{"error": err}) return nil, err } } } logger.Debugw(ctx, "DeviceReasonUpdate", log.Fields{"device-id": deviceID.Id, "reason": reason.Val, "transactionID": transactionID.Val}) if err := rhp.deviceMgr.UpdateDeviceReason(log.WithSpanFromContext(context.TODO(), ctx), deviceID.Id, reason.Val); err != nil { logger.Debugw(ctx, "unable-to-update-device-reason", log.Fields{"error": err}) return nil, err } return &empty.Empty{}, nil }
// Copyright 2019 Google 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 android // ImageInterface is implemented by modules that need to be split by the imageMutator. type ImageInterface interface { // ImageMutatorBegin is called before any other method in the ImageInterface. ImageMutatorBegin(ctx BaseModuleContext) // CoreVariantNeeded should return true if the module needs a core variant (installed on the system image). CoreVariantNeeded(ctx BaseModuleContext) bool // RamdiskVariantNeeded should return true if the module needs a ramdisk variant (installed on the // ramdisk partition). RamdiskVariantNeeded(ctx BaseModuleContext) bool // RecoveryVariantNeeded should return true if the module needs a recovery variant (installed on the // recovery partition). RecoveryVariantNeeded(ctx BaseModuleContext) bool // ExtraImageVariations should return a list of the additional variations needed for the module. After the // variants are created the SetImageVariation method will be called on each newly created variant with the // its variation. ExtraImageVariations(ctx BaseModuleContext) []string // SetImageVariation will be passed a newly created recovery variant of the module. ModuleBase implements // SetImageVariation, most module types will not need to override it, and those that do must call the // overridden method. Implementors of SetImageVariation must be careful to modify the module argument // and not the receiver. SetImageVariation(ctx BaseModuleContext, variation string, module Module) } const ( // CoreVariation is the variant used for framework-private libraries, or // SDK libraries. (which framework-private libraries can use), which // will be installed to the system image. CoreVariation string = "" // RecoveryVariation means a module to be installed to recovery image. RecoveryVariation string = "recovery" // RamdiskVariation means a module to be installed to ramdisk image. RamdiskVariation string = "ramdisk" ) // imageMutator creates variants for modules that implement the ImageInterface that // allow them to build differently for each partition (recovery, core, vendor, etc.). func imageMutator(ctx BottomUpMutatorContext) { if ctx.Os() != Android { return } if m, ok := ctx.Module().(ImageInterface); ok { m.ImageMutatorBegin(ctx) var variations []string if m.CoreVariantNeeded(ctx) { variations = append(variations, CoreVariation) } if m.RamdiskVariantNeeded(ctx) { variations = append(variations, RamdiskVariation) } if m.RecoveryVariantNeeded(ctx) { variations = append(variations, RecoveryVariation) } extraVariations := m.ExtraImageVariations(ctx) variations = append(variations, extraVariations...) if len(variations) == 0 { return } mod := ctx.CreateVariations(variations...) for i, v := range variations { mod[i].base().setImageVariation(v) m.SetImageVariation(ctx, v, mod[i]) } } }
package main import "fmt" func main() { n := 7 i := Fibo1(n) j := Fibo2(n) k := Fibo3(n) fmt.Printf("%v %v %v", i, j, k) } //递归实现 func Fibo1(n int) int { if n == 0 { return 0 } else if n == 1 { return 1 } else if n > 1 { return Fibo1(n-1) + Fibo1(n-2) } else { return -1 } } //迭代实现 func Fibo2(n int) int { if n < 0 { return -1 } else if n == 0 { return 0 } else if n <= 2 { return 1 } else { a, b := 1, 1 result := 0 for i := 3; i <= n; i++ { result = a + b a, b = b, result } return result } } //利用闭包 func Fibo3(n int) int { if n < 0 { return -1 } else { f := Fibonacci() result := 0 for i := 0; i < n; i++ { result = f() } return result } } func Fibonacci() func() int { a, b := 0, 1 return func() int { a, b = b, a+b return a } }
package codegen import ( "bufio" "context" "fmt" "reflect" "strconv" "strings" "github.com/lithammer/dedent" "github.com/moby/buildkit/client" "github.com/openllb/hlb/errdefs" "github.com/openllb/hlb/parser" "github.com/openllb/hlb/solver" "github.com/pkg/errors" ) type CodeGen struct { Debug Debugger cln *client.Client extraSolveOpts []solver.SolveOption } type CodeGenOption func(*CodeGen) error func WithDebugger(dbgr Debugger) CodeGenOption { return func(i *CodeGen) error { i.Debug = dbgr return nil } } func WithExtraSolveOpts(extraOpts []solver.SolveOption) CodeGenOption { return func(i *CodeGen) error { i.extraSolveOpts = append(i.extraSolveOpts, extraOpts...) return nil } } func New(cln *client.Client, opts ...CodeGenOption) (*CodeGen, error) { cg := &CodeGen{ Debug: NewNoopDebugger(), cln: cln, } for _, opt := range opts { err := opt(cg) if err != nil { return cg, err } } return cg, nil } type Target struct { Name string } func (cg *CodeGen) Generate(ctx context.Context, mod *parser.Module, targets []Target) (solver.Request, error) { var requests []solver.Request for i, target := range targets { _, ok := mod.Scope.Objects[target.Name] if !ok { return nil, fmt.Errorf("target %q is not defined in %s", target.Name, mod.Pos.Filename) } // Yield before compiling anything. err := cg.Debug(ctx, mod.Scope, mod, nil, nil) if err != nil { return nil, err } // Build expression for target. ie := parser.NewIdentExpr(target.Name) ie.Pos.Filename = "target" ie.Pos.Line = i // Every target has a return register. ret := NewRegister() err = cg.EmitIdentExpr(ctx, mod.Scope, ie, ie.Ident, nil, nil, nil, ret) if err != nil { return nil, err } request, err := ret.Request() if err != nil { return nil, err } requests = append(requests, request) } return solver.Parallel(requests...), nil } func (cg *CodeGen) EmitExpr(ctx context.Context, scope *parser.Scope, expr *parser.Expr, args []Value, opts Option, b *parser.Binding, ret Register) error { ctx = WithProgramCounter(ctx, expr) switch { case expr.FuncLit != nil: return cg.EmitFuncLit(ctx, scope, expr.FuncLit, b, ret) case expr.BasicLit != nil: return cg.EmitBasicLit(ctx, scope, expr.BasicLit, ret) case expr.CallExpr != nil: return cg.EmitCallExpr(ctx, scope, expr.CallExpr, ret) default: return errdefs.WithInternalErrorf(expr, "invalid expr") } } func (cg *CodeGen) EmitFuncLit(ctx context.Context, scope *parser.Scope, lit *parser.FuncLit, b *parser.Binding, ret Register) error { return cg.EmitBlock(ctx, scope, lit.Body, b, ret) } func (cg *CodeGen) EmitBasicLit(ctx context.Context, scope *parser.Scope, lit *parser.BasicLit, ret Register) error { switch { case lit.Decimal != nil: return ret.Set(*lit.Decimal) case lit.Numeric != nil: return ret.Set(int(lit.Numeric.Value)) case lit.Bool != nil: return ret.Set(*lit.Bool) case lit.Str != nil: return cg.EmitStringLit(ctx, scope, lit.Str, ret) case lit.RawString != nil: return ret.Set(lit.RawString.Text) case lit.Heredoc != nil: return cg.EmitHeredoc(ctx, scope, lit.Heredoc, ret) case lit.RawHeredoc != nil: return cg.EmitRawHeredoc(ctx, scope, lit.RawHeredoc, ret) default: return errdefs.WithInternalErrorf(lit, "invalid basic lit") } } func (cg *CodeGen) EmitStringLit(ctx context.Context, scope *parser.Scope, str *parser.StringLit, ret Register) error { var pieces []string for _, f := range str.Fragments { switch { case f.Escaped != nil: escaped := *f.Escaped if escaped[1] == '$' { pieces = append(pieces, "$") } else { value, _, _, err := strconv.UnquoteChar(escaped, '"') if err != nil { return err } pieces = append(pieces, string(value)) } case f.Interpolated != nil: exprRet := NewRegister() err := cg.EmitExpr(ctx, scope, f.Interpolated.Expr, nil, nil, nil, exprRet) if err != nil { return err } piece, err := exprRet.String() if err != nil { return err } pieces = append(pieces, piece) case f.Text != nil: pieces = append(pieces, *f.Text) } } return ret.Set(strings.Join(pieces, "")) } func (cg *CodeGen) EmitHeredoc(ctx context.Context, scope *parser.Scope, heredoc *parser.Heredoc, ret Register) error { var pieces []string for _, f := range heredoc.Fragments { switch { case f.Spaces != nil: pieces = append(pieces, *f.Spaces) case f.Escaped != nil: escaped := *f.Escaped if escaped[1] == '$' { pieces = append(pieces, "$") } else { pieces = append(pieces, escaped) } case f.Interpolated != nil: exprRet := NewRegister() err := cg.EmitExpr(ctx, scope, f.Interpolated.Expr, nil, nil, nil, exprRet) if err != nil { return err } piece, err := exprRet.String() if err != nil { return err } pieces = append(pieces, piece) case f.Text != nil: pieces = append(pieces, *f.Text) } } return emitHeredocPieces(heredoc.Start, heredoc.Terminate.Text, pieces, ret) } func emitHeredocPieces(start, terminate string, pieces []string, ret Register) error { // Build raw heredoc. raw := strings.Join(pieces, "") // Trim leading newlines and trailing newlines / tabs. raw = strings.TrimRight(strings.TrimLeft(raw, "\n"), "\n\t") switch strings.TrimSuffix(start, terminate) { case "<<-": // dedent return ret.Set(dedent.Dedent(raw)) case "<<~": // fold s := bufio.NewScanner(strings.NewReader(strings.TrimSpace(raw))) var lines []string for s.Scan() { lines = append(lines, strings.TrimSpace(s.Text())) } return ret.Set(strings.Join(lines, " ")) default: return ret.Set(raw) } } func (cg *CodeGen) EmitRawHeredoc(ctx context.Context, scope *parser.Scope, heredoc *parser.RawHeredoc, ret Register) error { var pieces []string for _, f := range heredoc.Fragments { switch { case f.Spaces != nil: pieces = append(pieces, *f.Spaces) case f.Text != nil: pieces = append(pieces, *f.Text) } } terminate := fmt.Sprintf("`%s`", heredoc.Terminate.Text) return emitHeredocPieces(heredoc.Start, terminate, pieces, ret) } func (cg *CodeGen) EmitCallExpr(ctx context.Context, scope *parser.Scope, call *parser.CallExpr, ret Register) error { ctx = WithFrame(ctx, Frame{call.Name}) // Yield before executing call expression. err := cg.Debug(ctx, scope, call.Name, ret, nil) if err != nil { return err } // No type hint for arg evaluation because the call.Name hasn't been resolved // yet, so codegen has no type information. args, err := cg.Evaluate(ctx, scope, parser.None, nil, call.Args()...) if err != nil { return err } for i, arg := range call.Args() { ctx = WithArg(ctx, i, arg) } return cg.EmitIdentExpr(ctx, scope, call.Name, call.Name.Ident, args, nil, nil, ret) } func (cg *CodeGen) EmitIdentExpr(ctx context.Context, scope *parser.Scope, ie *parser.IdentExpr, lookup *parser.Ident, args []Value, opts Option, b *parser.Binding, ret Register) error { ctx = WithProgramCounter(ctx, ie) obj := scope.Lookup(lookup.Text) if obj == nil { return errors.WithStack(errdefs.WithUndefinedIdent(lookup, nil)) } switch n := obj.Node.(type) { case *parser.BuiltinDecl: return cg.EmitBuiltinDecl(ctx, scope, n, args, opts, b, ret) case *parser.FuncDecl: return cg.EmitFuncDecl(ctx, n, args, nil, ret) case *parser.BindClause: return cg.EmitBinding(ctx, n.TargetBinding(lookup.Text), args, ret) case *parser.ImportDecl: importScope, ok := obj.Data.(*parser.Scope) if !ok { return errdefs.WithImportWithinImport(ie, obj.Ident) } return cg.EmitIdentExpr(ctx, importScope, ie, ie.Reference.Ident, args, opts, nil, ret) case *parser.Field: val, err := NewValue(obj.Data) if err != nil { return err } if val.Kind() != parser.Option || ret.Kind() != parser.Option { return ret.Set(val) } else { retOpts, err := ret.Option() if err != nil { return err } valOpts, err := val.Option() if err != nil { return err } return ret.Set(append(retOpts, valOpts...)) } default: return errdefs.WithInternalErrorf(n, "invalid resolved object") } } func (cg *CodeGen) EmitBuiltinDecl(ctx context.Context, scope *parser.Scope, bd *parser.BuiltinDecl, args []Value, opts Option, b *parser.Binding, ret Register) error { callable := bd.Callable(ReturnType(ctx)) if callable == nil { return errdefs.WithInternalErrorf(ProgramCounter(ctx), "unrecognized builtin `%s`", bd) } // Pass binding if available. if b != nil { ctx = WithBinding(ctx, b) } for _, opt := range cg.extraSolveOpts { opts = append(opts, opt) } var ( c = reflect.ValueOf(callable).MethodByName("Call") ins = []reflect.Value{ reflect.ValueOf(ctx), reflect.ValueOf(cg.cln), reflect.ValueOf(ret), reflect.ValueOf(opts), } ) // Handle variadic arguments separately. numIn := c.Type().NumIn() if c.Type().IsVariadic() { numIn -= 1 } expected := numIn - len(PrototypeIn) if len(args) < expected { return errdefs.WithInternalErrorf(ProgramCounter(ctx), "`%s` expected %d args, got %d", bd, expected, len(args)) } // Reflect regular arguments. for i := len(PrototypeIn); i < numIn; i++ { var ( param = c.Type().In(i) arg = args[i-len(PrototypeIn)] ) v, err := arg.Reflect(param) if err != nil { return err } ins = append(ins, v) } // Reflect variadic arguments. if c.Type().IsVariadic() { for i := numIn - len(PrototypeIn); i < len(args); i++ { param := c.Type().In(numIn).Elem() v, err := args[i].Reflect(param) if err != nil { return err } ins = append(ins, v) } } outs := c.Call(ins) if !outs[0].IsNil() { return WithBacktraceError(ctx, outs[0].Interface().(error)) } return nil } func (cg *CodeGen) EmitFuncDecl(ctx context.Context, fun *parser.FuncDecl, args []Value, b *parser.Binding, ret Register) error { ctx = WithProgramCounter(ctx, fun.Name) params := fun.Params.Fields() if len(params) != len(args) { name := fun.Name.Text if b != nil { name = b.Name.Text } return errdefs.WithInternalErrorf(ProgramCounter(ctx), "`%s` expected %d args, got %d", name, len(params), len(args)) } scope := parser.NewScope(fun, fun.Scope) for i, param := range params { if param.Modifier != nil { continue } scope.Insert(&parser.Object{ Kind: param.Kind(), Ident: param.Name, Node: param, Data: args[i], }) } // Yield before executing a function. err := cg.Debug(ctx, scope, fun.Name, ret, nil) if err != nil { return err } return cg.EmitBlock(ctx, scope, fun.Body, b, ret) } func (cg *CodeGen) EmitBinding(ctx context.Context, b *parser.Binding, args []Value, ret Register) error { return cg.EmitFuncDecl(ctx, b.Bind.Closure, args, b, ret) } func (cg *CodeGen) EmitBlock(ctx context.Context, scope *parser.Scope, block *parser.BlockStmt, b *parser.Binding, ret Register) error { ctx = WithReturnType(ctx, block.Kind()) for _, stmt := range block.Stmts() { var err error switch { case stmt.Call != nil: err = cg.EmitCallStmt(ctx, scope, stmt.Call, b, ret) case stmt.Expr != nil: err = cg.EmitExpr(ctx, scope, stmt.Expr.Expr, nil, nil, b, ret) default: return errdefs.WithInternalErrorf(stmt, "invalid stmt") } if err != nil { return err } } return nil } func (cg *CodeGen) EmitCallStmt(ctx context.Context, scope *parser.Scope, call *parser.CallStmt, b *parser.Binding, ret Register) error { ctx = WithFrame(ctx, Frame{call.Name}) // No type hint for arg evaluation because the call.Name hasn't been resolved // yet, so codegen has no type information. args, err := cg.Evaluate(ctx, scope, parser.None, nil, call.Args...) if err != nil { return err } for i, arg := range call.Args { ctx = WithArg(ctx, i, arg) } var opts Option if call.WithClause != nil { // Provide a type hint to avoid ambgiuous lookups. hint := parser.Kind(fmt.Sprintf("%s::%s", parser.Option, call.Name)) // WithClause provides option expressions access to the binding. values, err := cg.Evaluate(ctx, scope, hint, b, call.WithClause.Expr) if err != nil { return err } opts, err = values[0].Option() if err != nil { return err } } // Yield before executing the next call statement. if call.Breakpoint(ReturnType(ctx)) { var command []string for _, arg := range args { if arg.Kind() != parser.String { return errors.New("breakpoint args must be strings") } argStr, err := arg.String() if err != nil { return err } command = append(command, argStr) } if len(command) != 0 { opts = append(opts, breakpointCommand(command)) } } err = cg.Debug(ctx, scope, call.Name, ret, opts) if err != nil { return err } // Pass the binding if this is the matching CallStmt. var binding *parser.Binding if b != nil && call.BindClause == b.Bind { binding = b } return cg.EmitIdentExpr(ctx, scope, call.Name, call.Name.Ident, args, opts, binding, ret) } type breakpointCommand []string func (cg *CodeGen) Evaluate(ctx context.Context, scope *parser.Scope, hint parser.Kind, b *parser.Binding, exprs ...*parser.Expr) (values []Value, err error) { for _, expr := range exprs { ctx = WithProgramCounter(ctx, expr) ctx = WithReturnType(ctx, hint) // Evaluated expressions write to a new return register. ret := NewRegister() err = cg.EmitExpr(ctx, scope, expr, nil, nil, b, ret) if err != nil { return } values = append(values, ret) } return }
package main import "fmt" func main() { // 错误写法 //var m map[string]int //m["frank"] = 1 //fmt.Println(m) // 正确写法 var m2 = make(map[string]int) m2["height"] = 165 fmt.Println(m2) }
package memory_test import ( "testing" "github.com/stretchr/testify/assert" "github.com/disposedtrolley/goz/internal/memory" ) func TestMemoryRead(t *testing.T) { mem := memory.NewMemory([]byte{0xfe, 0xa2, 0x0d, 0x19, 0x00}) assert.Equal(t, uint8(0xfe), mem.ReadByte(0), "should read a byte") assert.Equal(t, uint8(0x00), mem.ReadByte(4), "should read a byte at the end of memory") assert.Equal(t, uint16(0xfea2), mem.ReadWord(0), "should read a word") assert.Equal(t, uint16(0x1900), mem.ReadWord(3), "should read a word at the end of memory") } func TestMemoryRead_OutOfBounds(t *testing.T) { mem := memory.NewMemory([]byte{0xfe, 0xa2, 0x0d, 0x19, 0x00}) assert.Panics(t, func() { mem.ReadWord(4) }, "should panic when reading a word from the last address") assert.Panics(t, func() { mem.ReadByte(5) }, "should panic when reading a byte past the end of memory") } func TestMemoryWrite(t *testing.T) { mem := memory.NewMemory([]byte{0xfe, 0xa2, 0x0d, 0x19, 0x00}) mem.WriteByte(0, 0xff) assert.Equal(t, byte(0xff), mem.ReadByte(0)) mem.WriteWord(3, 0xaabb) assert.Equal(t, uint16(0xaabb), mem.ReadWord(3)) } func TestMemoryWrite_OutOfBounds(t *testing.T) { mem := memory.NewMemory([]byte{0xfe, 0xa2, 0x0d, 0x19, 0x00}) assert.Panics(t, func() { mem.WriteWord(4, 0xffdd) }, "should panic when writing a word to the last address") assert.Panics(t, func() { mem.WriteByte(5, 0x11) }, "should panic when writing a byte past the end of memory") }
/* Forgotten languages (also known as extinct languages) are languages that are no longer in use. Such languages were, probably, widely used before and no one could have ever imagined that they will become extinct at some point. Unfortunately, that is what happened to them. On the happy side of things, a language may be dead, but some of its words may continue to be used in other languages. Using something called as the Internet, you have acquired a dictionary of N words of a forgotten language. Meanwhile, you also know K phrases used in modern languages. For each of the words of the forgotten language, your task is to determine whether the word is still in use in any of these K modern phrases or not. Input The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of a test case description contains two space separated positive integers N and K. The second line of the description contains N strings denoting a dictionary of the forgotten language. Each of the next K lines of the description starts with one positive integer L denoting the number of words in the corresponding phrase in modern languages. The integer is followed by L strings (not necessarily distinct) denoting the phrase. Output For each test case, output a single line containing N tokens (space-separated): if the ith word of the dictionary exists in at least one phrase in modern languages, then you should output YES as the ith token, otherwise NO. Constraints 1 ≤ T ≤ 20 1 ≤ N ≤ 100 1 ≤ K, L ≤ 50 1 ≤ length of any string in the input ≤ 5 */ package main import ( "fmt" "reflect" ) func main() { test( []string{"piygu", "ezyfo", "rzotm"}, [][]string{ {"piygu"}, {"tefwz", "tefwz", "piygu", "ezyfo", "tefwz", "piygu"}, }, []string{"YES", "YES", "NO"}, ) test( []string{"kssdy", "tjzhy", "ljzym", "kegqz"}, [][]string{ {"kegqz", "kegqz", "kegqz", "vxvyj"}, }, []string{"NO", "NO", "NO", "YES"}, ) } func assert(x bool) { if !x { panic("assertion failed") } } func test(w []string, p [][]string, r []string) { s := dictionary(w, p) fmt.Println(s) assert(reflect.DeepEqual(s, r)) } func dictionary(w []string, p [][]string) []string { m := make(map[string]int) for i := range p { for _, v := range p[i] { m[v]++ } } r := make([]string, len(w)) for i, v := range w { if m[v] >= 1 { r[i] = "YES" } else { r[i] = "NO" } } return r }
package caaa import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00600105 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.006.001.05 Document"` Message *AcceptorCancellationResponseV05 `xml:"AccptrCxlRspn"` } func (d *Document00600105) AddMessage() *AcceptorCancellationResponseV05 { d.Message = new(AcceptorCancellationResponseV05) return d.Message } // The AcceptorCancellationResponse message is sent by the acquirer (or its agent) to an acceptor (or its agent), to return the outcome of the cancellation request. If the response is positive, the acquirer has voided the financial data from the captured transaction. type AcceptorCancellationResponseV05 struct { // Cancellation response message management information. Header *iso20022.Header30 `xml:"Hdr"` // Information related to the cancellation response. CancellationResponse *iso20022.AcceptorCancellationResponse5 `xml:"CxlRspn"` // Trailer of the message containing a MAC. SecurityTrailer *iso20022.ContentInformationType15 `xml:"SctyTrlr,omitempty"` } func (a *AcceptorCancellationResponseV05) AddHeader() *iso20022.Header30 { a.Header = new(iso20022.Header30) return a.Header } func (a *AcceptorCancellationResponseV05) AddCancellationResponse() *iso20022.AcceptorCancellationResponse5 { a.CancellationResponse = new(iso20022.AcceptorCancellationResponse5) return a.CancellationResponse } func (a *AcceptorCancellationResponseV05) AddSecurityTrailer() *iso20022.ContentInformationType15 { a.SecurityTrailer = new(iso20022.ContentInformationType15) return a.SecurityTrailer }
// +build partners // Stub function for GuessMimeType. This is for partner-apps, where // the function is never actually called. We need the function to be // defined, or our build will fail. // // GuessMimeType is not used in partner apps because it relies on // external C libraries that partners probably will not have on their // machines. package platform var IsPartnerBuild = true func GuessMimeType(absPath string) (mimeType string, err error) { return "mime type disabled", nil } func GuessMimeTypeByBuffer(buf []byte) (mimeType string, err error) { return "mime type disabled", nil }
package model import ( "github.com/google/uuid" "gorm.io/gorm" ) type ChatUser struct { UUID string `gorm:"type: binary(36);"` Username string `gorm:"type:varchar(255)"` Password string `gorm:"type:varchar(255)"` } func (u *ChatUser) BeforeCreate(tx *gorm.DB) (err error) { //newUUID, err := uuid.NewUUID() u.UUID = uuid.NewString() return }
package main import ( "encoding/csv" "fmt" "io" "os" ) func main() { years := [9]string{"2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016"} for y := 0; y < len(years); y++ { fmt.Println("Leyendo archivo del", years[y]) file, err := os.Open("../data/" + years[y] + "/directorio_" + years[y] + ".csv") if err != nil { fmt.Println("Error:", err) return } defer file.Close() reader := csv.NewReader(file) reader.Comma = ';' for { record, err := reader.Read() if err == io.EOF { break } else if err != nil { fmt.Println("Error:", err) return } for i := 0; i < len(record); i++ { fmt.Println(i, ": ", record[i]) } break } fmt.Println("T: ") } }
/* ** description(""). ** copyright('Open_IM,www.Open_IM.io'). ** author("fg,Gordon@tuoyun.net"). ** time(2021/5/13 10:33). */ package logic import ( "Open_IM/pkg/common/config" kfk "Open_IM/pkg/common/kafka" "Open_IM/pkg/common/log" pbChat "Open_IM/pkg/proto/chat" pbRelay "Open_IM/pkg/proto/relay" "github.com/Shopify/sarama" "github.com/golang/protobuf/proto" ) type fcb func(msg []byte) type PushConsumerHandler struct { msgHandle map[string]fcb pushConsumerGroup *kfk.MConsumerGroup } func (ms *PushConsumerHandler) Init() { ms.msgHandle = make(map[string]fcb) ms.msgHandle[config.Config.Kafka.Ms2pschat.Topic] = ms.handleMs2PsChat ms.pushConsumerGroup = kfk.NewMConsumerGroup(&kfk.MConsumerGroupConfig{KafkaVersion: sarama.V0_10_2_0, OffsetsInitial: sarama.OffsetNewest, IsReturnErr: false}, []string{config.Config.Kafka.Ms2pschat.Topic}, config.Config.Kafka.Ms2pschat.Addr, config.Config.Kafka.ConsumerGroupID.MsgToPush) } func (ms *PushConsumerHandler) handleMs2PsChat(msg []byte) { log.InfoByKv("msg come from kafka And push!!!", "", "msg", string(msg)) pbData := pbChat.MsgSvrToPushSvrChatMsg{} if err := proto.Unmarshal(msg, &pbData); err != nil { log.ErrorByKv("push Unmarshal msg err", "", "msg", string(msg), "err", err.Error()) return } sendPbData := pbRelay.MsgToUserReq{} sendPbData.SendTime = pbData.SendTime sendPbData.OperationID = pbData.OperationID sendPbData.ServerMsgID = pbData.MsgID sendPbData.MsgFrom = pbData.MsgFrom sendPbData.ContentType = pbData.ContentType sendPbData.SessionType = pbData.SessionType sendPbData.RecvID = pbData.RecvID sendPbData.Content = pbData.Content sendPbData.SendID = pbData.SendID sendPbData.SenderNickName = pbData.SenderNickName sendPbData.SenderFaceURL = pbData.SenderFaceURL sendPbData.ClientMsgID = pbData.ClientMsgID sendPbData.PlatformID = pbData.PlatformID sendPbData.RecvSeq = pbData.RecvSeq //Call push module to send message to the user MsgToUser(&sendPbData, pbData.OfflineInfo, pbData.Options) } func (PushConsumerHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil } func (PushConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil } func (ms *PushConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error { for msg := range claim.Messages() { log.InfoByKv("kafka get info to mysql", "", "msgTopic", msg.Topic, "msgPartition", msg.Partition, "msg", string(msg.Value)) ms.msgHandle[msg.Topic](msg.Value) } return nil }
package static import ( "fmt" "net/http" "strings" ) type FilesServer struct { baseHRef string hsts bool } func NewFilesServer(baseHRef string, hsts bool) *FilesServer { return &FilesServer{baseHRef, hsts} } func (s *FilesServer) ServerFiles(w http.ResponseWriter, r *http.Request) { // If there is no stored static file, we'll redirect to the js app if Hash(strings.TrimLeft(r.URL.Path, "/")) == "" { r.URL.Path = "index.html" } if r.URL.Path == "index.html" { // hack to prevent ServerHTTP from giving us gzipped content which we can do our search-and-replace on r.Header.Del("Accept-Encoding") w = &responseRewriter{ResponseWriter: w, old: []byte(`<base href="/">`), new: []byte(fmt.Sprintf(`<base href="%s">`, s.baseHRef))} } w.Header().Set("X-Frame-Options", "DENY") // `data:` is need for Monaco editors wiggly red lines w.Header().Set("Content-Security-Policy", "default-src 'self' 'unsafe-inline'; img-src 'self' data:") if s.hsts { w.Header().Set("Strict-Transport-Security", "max-age=31536000") } // in my IDE (IntelliJ) the next line is red for some reason - but this is fine ServeHTTP(w, r) }
/* 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 server import ( "crypto/tls" "fmt" "net" "strconv" "strings" "github.com/codenotary/immudb/pkg/stream" "github.com/codenotary/immudb/embedded/store" "github.com/codenotary/immudb/pkg/auth" ) const SystemdbName = "systemdb" const DefaultdbName = "defaultdb" // Options server options list type Options struct { Dir string Network string Address string Port int MetricsPort int Config string Pidfile string Logfile string TLSConfig *tls.Config auth bool MaxRecvMsgSize int NoHistograms bool Detached bool MetricsServer bool WebServer bool WebServerPort int DevMode bool AdminPassword string `json:"-"` systemAdminDbName string defaultDbName string listener net.Listener usingCustomListener bool maintenance bool SigningKey string StoreOptions *store.Options StreamChunkSize int TokenExpiryTimeMin int PgsqlServer bool PgsqlServerPort int } // DefaultOptions returns default server options func DefaultOptions() *Options { return &Options{ Dir: "./data", Network: "tcp", Address: "0.0.0.0", Port: 3322, MetricsPort: 9497, WebServerPort: 8080, Config: "configs/immudb.toml", Pidfile: "", Logfile: "", TLSConfig: &tls.Config{}, auth: true, MaxRecvMsgSize: 1024 * 1024 * 32, // 32Mb NoHistograms: false, Detached: false, MetricsServer: true, WebServer: true, DevMode: false, AdminPassword: auth.SysAdminPassword, systemAdminDbName: SystemdbName, defaultDbName: DefaultdbName, usingCustomListener: false, maintenance: false, StoreOptions: DefaultStoreOptions(), StreamChunkSize: stream.DefaultChunkSize, TokenExpiryTimeMin: 1440, PgsqlServer: false, PgsqlServerPort: 5432, } } func DefaultStoreOptions() *store.Options { indexOptions := store.DefaultIndexOptions().WithRenewSnapRootAfter(0) return store.DefaultOptions(). WithIndexOptions(indexOptions). WithMaxLinearProofLen(0). WithMaxConcurrency(10). WithMaxValueLen(32 << 20) } // WithDir sets dir func (o *Options) WithDir(dir string) *Options { o.Dir = dir return o } // WithNetwork sets network func (o *Options) WithNetwork(network string) *Options { o.Network = network return o } // WithAddress sets address func (o *Options) WithAddress(address string) *Options { o.Address = address return o } // WithPort sets port func (o *Options) WithPort(port int) *Options { if port > 0 { o.Port = port } return o } // WithConfig sets config file name func (o *Options) WithConfig(config string) *Options { o.Config = config return o } // WithPidfile sets pid file func (o *Options) WithPidfile(pidfile string) *Options { o.Pidfile = pidfile return o } // WithLogfile sets logfile func (o *Options) WithLogfile(logfile string) *Options { o.Logfile = logfile return o } // WithTLS sets tls config func (o *Options) WithTLS(tls *tls.Config) *Options { o.TLSConfig = tls return o } // WithAuth sets auth func (o *Options) WithAuth(authEnabled bool) *Options { o.auth = authEnabled return o } func (o *Options) WithMaxRecvMsgSize(maxRecvMsgSize int) *Options { o.MaxRecvMsgSize = maxRecvMsgSize return o } // GetAuth gets auth func (o *Options) GetAuth() bool { if o.maintenance { return false } return o.auth } // WithNoHistograms disables collection of histograms metrics (e.g. query durations) func (o *Options) WithNoHistograms(noHistograms bool) *Options { o.NoHistograms = noHistograms return o } // WithDetached sets immudb to be run in background func (o *Options) WithDetached(detached bool) *Options { o.Detached = detached return o } func (o *Options) WithStoreOptions(storeOpts *store.Options) *Options { o.StoreOptions = storeOpts return o } // Bind returns bind address func (o *Options) Bind() string { return o.Address + ":" + strconv.Itoa(o.Port) } // MetricsBind return metrics bind address func (o *Options) MetricsBind() string { return o.Address + ":" + strconv.Itoa(o.MetricsPort) } // WebBind return bind address for the Web API/console func (o *Options) WebBind() string { return o.Address + ":" + strconv.Itoa(o.WebServerPort) } // String print options func (o *Options) String() string { rightPad := func(k string, v interface{}) string { return fmt.Sprintf("%-17s: %v", k, v) } opts := make([]string, 0, 17) opts = append(opts, "================ Config ================") opts = append(opts, rightPad("Data dir", o.Dir)) opts = append(opts, rightPad("Address", fmt.Sprintf("%s:%d", o.Address, o.Port))) if o.MetricsServer { opts = append(opts, rightPad("Metrics address", fmt.Sprintf("%s:%d/metrics", o.Address, o.MetricsPort))) } if o.Config != "" { opts = append(opts, rightPad("Config file", o.Config)) } if o.Pidfile != "" { opts = append(opts, rightPad("PID file", o.Pidfile)) } if o.Logfile != "" { opts = append(opts, rightPad("Log file", o.Logfile)) } opts = append(opts, rightPad("Max recv msg size", o.MaxRecvMsgSize)) opts = append(opts, rightPad("Auth enabled", o.auth)) opts = append(opts, rightPad("Dev mode", o.DevMode)) opts = append(opts, rightPad("Default database", o.defaultDbName)) opts = append(opts, rightPad("Maintenance mode", o.maintenance)) opts = append(opts, rightPad("Synced mode", o.StoreOptions.Synced)) opts = append(opts, "----------------------------------------") opts = append(opts, "Superadmin default credentials") opts = append(opts, rightPad(" Username", auth.SysAdminUsername)) opts = append(opts, rightPad(" Password", auth.SysAdminPassword)) opts = append(opts, "========================================") return strings.Join(opts, "\n") } // WithMetricsServer ... func (o *Options) WithMetricsServer(metricsServer bool) *Options { o.MetricsServer = metricsServer return o } // WithWebServer ... func (o *Options) WithWebServer(webServer bool) *Options { o.WebServer = webServer return o } // WithWebServerPort ... func (o *Options) WithWebServerPort(port int) *Options { if port > 0 { o.WebServerPort = port } return o } // WithDevMode ... func (o *Options) WithDevMode(devMode bool) *Options { o.DevMode = devMode return o } // WithAdminPassword ... func (o *Options) WithAdminPassword(adminPassword string) *Options { o.AdminPassword = adminPassword return o } //GetSystemAdminDbName returns the System database name func (o *Options) GetSystemAdminDbName() string { return o.systemAdminDbName } //GetDefaultDbName returns the default database name func (o *Options) GetDefaultDbName() string { return o.defaultDbName } // WithListener used usually to pass a bufered listener for testing purposes func (o *Options) WithListener(lis net.Listener) *Options { o.listener = lis o.usingCustomListener = true return o } // WithMaintenance sets maintenance mode func (o *Options) WithMaintenance(m bool) *Options { o.maintenance = m return o } // GetMaintenance gets maintenance mode func (o *Options) GetMaintenance() bool { return o.maintenance } // WithSigningKey sets signature private key func (o *Options) WithSigningKey(signingKey string) *Options { o.SigningKey = signingKey return o } // WithStreamChunkSize set the chunk size func (o *Options) WithStreamChunkSize(streamChunkSize int) *Options { o.StreamChunkSize = streamChunkSize return o } // WithTokenExpiryTime set authentication token expiration time in minutes func (o *Options) WithTokenExpiryTime(tokenExpiryTimeMin int) *Options { o.TokenExpiryTimeMin = tokenExpiryTimeMin return o } // PgsqlServerPort enable or disable pgsql server func (o *Options) WithPgsqlServer(enable bool) *Options { o.PgsqlServer = enable return o } // PgsqlServerPort sets pgdsql server port func (o *Options) WithPgsqlServerPort(port int) *Options { o.PgsqlServerPort = port return o }
package sync import ( "sync" "time" ) type Mutex struct { name string mutex *Semaphore lock *sync.Mutex } // NewMutex creates new mutex lock object // name of the mutex // callbackFunc is a release notification function. func NewMutex(name string, callbackFunc func(string)) *Mutex { return &Mutex{ name: name, lock: &sync.Mutex{}, mutex: NewSemaphore(name, 1, callbackFunc, LockTypeMutex), } } func (m *Mutex) getName() string { return m.name } func (m *Mutex) getLimit() int { return m.mutex.limit } func (m *Mutex) getCurrentHolders() []string { return m.mutex.getCurrentHolders() } func (m *Mutex) resize(n int) bool { return false } func (m *Mutex) release(key string) bool { m.lock.Lock() defer m.lock.Unlock() return m.mutex.release(key) } func (m *Mutex) acquire(holderKey string) bool { m.lock.Lock() defer m.lock.Unlock() return m.mutex.acquire(holderKey) } func (m *Mutex) addToQueue(holderKey string, priority int32, creationTime time.Time) { m.lock.Lock() defer m.lock.Unlock() m.mutex.addToQueue(holderKey, priority, creationTime) } func (m *Mutex) tryAcquire(holderKey string) (bool, string) { m.lock.Lock() defer m.lock.Unlock() return m.mutex.tryAcquire(holderKey) }
package otpauth import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "log" "os" "testing" ) var ( intToBytes Fixture zeroPaddingDigits6 Fixture zeroPaddingDigits8 Fixture decodeBase32 Fixture decodeBase32WithPadding Fixture encodeBase32 Fixture hmacHash Fixture hotpValue Fixture ) type Fixture struct { TestCases []testCase `json:"test_cases"` } type testCase struct { Value string Result string } func (tc *testCase) UnmarshalJSON(data []byte) error { var raw interface{} d := json.NewDecoder(bytes.NewReader(data)) d.UseNumber() if err := d.Decode(&raw); err != nil { return err } switch v := raw.(type) { case string: tc.Result = v case json.Number: tc.Result = v.String() case map[string]interface{}: res, ok := v["result"] if !ok { return errors.New("need result property") } switch r := res.(type) { case string: tc.Result = r case json.Number: tc.Result = r.String() default: return errors.New("invalid result property") } if val, ok := v["value"]; ok { switch v := val.(type) { case string: tc.Value = v case json.Number: tc.Value = v.String() default: } } default: tc = nil } return nil } func TestMain(m *testing.M) { log.Println("setup") var err error for _, f := range []struct { Fixture *Fixture Name string }{ {&intToBytes, "int_to_bytes"}, {&zeroPaddingDigits6, "zero_padding"}, {&zeroPaddingDigits8, "zero_padding_digits_8"}, {&decodeBase32, "decode_base32"}, {&decodeBase32WithPadding, "decode_base32_with_padding"}, {&encodeBase32, "encode_base32"}, {&hmacHash, "hmac_hash"}, {&hotpValue, "hotp_value"}, } { if *f.Fixture, err = readTestCaseJSON(f.Name); err != nil { log.Printf("Failed load fixture: testdata/%s.json, Error: %s\n", f.Name, err) } } code := m.Run() log.Println("teardown") os.Exit(code) } func readTestCaseJSON(name string) (f Fixture, err error) { b, err := ioutil.ReadFile(fmt.Sprintf("testdata/%s.json", name)) if err != nil { return } if err = json.Unmarshal(b, &f); err != nil { return } return f, nil }
/** * (c) 2014, Caoimhe Chaos <caoimhechaos@protonmail.com>, * Ancient Solutions. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Ancient Solutions nor the name of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ // Simple client library to connect to a single blubber store server. package blubberstore import ( "bufio" "crypto/tls" "crypto/x509" "errors" "io" "io/ioutil" "net" "net/http" "net/rpc" "github.com/caoimhechaos/go-urlconnection" ) // A client to connect to blubber servers. type BlubberRPCClient struct { config *tls.Config client *rpc.Client insecure bool } // A client to a blubber directory. type BlubberDirectoryClient struct { config *tls.Config client *rpc.Client insecure bool } /* Create a new generic RPC client connecting to the given server. uri should be an URI pointing to the desired server and port. cert, key and cacert should be the path of the X.509 client certificate, private key and CA certificate, respectively. The insecure flag can be used to disable encryption (only for testing and if the server is also running in insecure mode). */ func NewRPCClient(uri, cert, key, cacert string, insecure bool) ( *rpc.Client, *tls.Config, error) { var config *tls.Config = new(tls.Config) var conn net.Conn var err error if !insecure { var tlscert tls.Certificate var certdata []byte config.ClientAuth = tls.VerifyClientCertIfGiven config.MinVersion = tls.VersionTLS12 tlscert, err = tls.LoadX509KeyPair(cert, key) if err != nil { return nil, nil, errors.New("Unable to load X.509 key pair: " + err.Error()) } config.Certificates = append(config.Certificates, tlscert) config.BuildNameToCertificate() config.ClientCAs = x509.NewCertPool() certdata, err = ioutil.ReadFile(cacert) if err != nil { return nil, nil, errors.New("Error reading " + cacert + ": " + err.Error()) } if !config.ClientCAs.AppendCertsFromPEM(certdata) { return nil, nil, errors.New( "Unable to load the X.509 certificates from " + cacert) } // Configure client side encryption. config.RootCAs = config.ClientCAs } // Establish a TCP connection and start a TLS exchange. conn, err = urlconnection.Connect(uri) if err != nil { return nil, nil, errors.New("Error connecting to " + uri + ": " + err.Error()) } if !insecure { conn = tls.Client(conn, config) } // Start the RPC connection. _, err = io.WriteString(conn, "CONNECT "+rpc.DefaultRPCPath+" HTTP/1.0\r\n\r\n") if err != nil { return nil, nil, errors.New("Error requesting RPC channel to " + uri + ": " + err.Error()) } // Let's see what the server thinks about that. _, err = http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: "CONNECT"}) if err != nil { return nil, nil, errors.New("Error establishing RPC channel to " + uri + ": " + err.Error()) } return rpc.NewClient(conn), config, nil } /* Create a new blubber client connecting to the given server. uri should be an URI pointing to the desired server and port. cert, key and cacert should be the path of the X.509 client certificate, private key and CA certificate, respectively. The insecure flag can be used to disable encryption (only for testing and if the server is also running in insecure mode). */ func NewBlubberRPCClient(uri, cert, key, cacert string, insecure bool) ( *BlubberRPCClient, error) { var client *rpc.Client var config *tls.Config var err error client, config, err = NewRPCClient(uri, cert, key, cacert, insecure) if err != nil { return nil, err } return &BlubberRPCClient{ config: config, client: client, insecure: insecure, }, nil } /* Get the underlying RPC client from the connection. It can sometimes be helpful, e.g. if the remote interface is double-bound. */ func (self *BlubberRPCClient) GetRPCClient() *rpc.Client { return self.client } /* Send a blob to the server and store it under the given blob ID. If you want to submit data that is too large to fit into memory, use the HTTP client library instead. */ func (self *BlubberRPCClient) StoreBlob(data BlockWithData) ( err error) { var rid BlockId err = self.client.Call("BlubberService.StoreBlob", data, &rid) return } /* Retrieve all data contained in the specified blob. If you want to retrieve more data than will fit into memory, use the HTTP client library instead. */ func (self *BlubberRPCClient) RetrieveBlob(id BlockId) ( ret BlockWithData, err error) { err = self.client.Call("BlubberService.RetrieveBlob", id, &ret) return } /* Delete the blob with the given ID. */ func (self *BlubberRPCClient) DeleteBlob(id BlockId) error { var rid BlockId return self.client.Call("BlubberService.DeleteBlob", id, &rid) } /* Retrieve status information about the blob with the given ID. */ func (self *BlubberRPCClient) StatBlob(id BlockId) ( stat BlubberStat, err error) { err = self.client.Call("BlubberService.StatBlob", id, &stat) return } /* Instruct the server to copy the blob with the given ID from the given server. It will overwrite any local variants of the blob. */ func (self *BlubberRPCClient) CopyBlob(source BlockSource) error { var id BlockId return self.client.Call("BlubberService.CopyBlob", source, &id) } /* Create a new blubber directory client connecting to the given server. uri should be an URI pointing to the desired server and port. cert, key and cacert should be the path of the X.509 client certificate, private key and CA certificate, respectively. The insecure flag can be used to disable encryption (only for testing and if the server is also running in insecure mode). */ func NewBlubberDirectoryClient(uri, cert, key, cacert string, insecure bool) ( *BlubberDirectoryClient, error) { var client *rpc.Client var config *tls.Config var err error client, config, err = NewRPCClient(uri, cert, key, cacert, insecure) if err != nil { return nil, err } return &BlubberDirectoryClient{ config: config, client: client, insecure: insecure, }, nil } /* Report to the directory that the block with the given properties is now stored on the specified server. */ func (b *BlubberDirectoryClient) ReportBlob(report BlockReport) error { var id BlockId return b.client.Call("BlubberBlockDirectory.ReportBlob", report, &id) } /* Look up all the hosts currently known to hold the requested block. */ func (b *BlubberDirectoryClient) LookupBlob(id BlockId) (list *BlockHolderList, err error) { list = new(BlockHolderList) err = b.client.Call("BlubberBlockDirectory.LookupBlob", id, &list) return } /* Remove the given host from the holders of the blob. */ func (b *BlubberDirectoryClient) RemoveBlobHolder(rep BlockRemovalReport) error { var id BlockId return b.client.Call("BlubberBlockDirectory.RemoveBlobHolder", rep, &id) } /* Delete all block ownerships associated with the given host. This is very useful e.g. if a host goes down or data is lost on it. */ func (b *BlubberDirectoryClient) ExpireHost(hosts BlockHolderList) error { var rv BlockHolderList return b.client.Call("BlubberBlockDirectory.ExpireHost", hosts, &rv) } /* Get a list of all hosts known to own blocks. This is mostly used by the cleanup jobs. */ func (b *BlubberDirectoryClient) ListHosts() ( hosts *BlockHolderList, err error) { var mt Empty hosts = new(BlockHolderList) err = b.client.Call("BlubberBlockDirectory.ListHosts", mt, &hosts) return } /* Pick a number of hosts from the available list. This will try to pick hosts which hold less keys than the others. */ func (b *BlubberDirectoryClient) GetFreeHosts(freeHostReq FreeHostsRequest) ( servers *BlockHolderList, err error) { servers = new(BlockHolderList) err = b.client.Call("BlubberBlockDirectory.GetFreeHosts", freeHostReq, servers) return }
package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`\d+(?:st|nd|rd|th)`) src := "December 19th, 2018" dst := re.ReplaceAllStringFunc(src, func(in string) string { return in[:len(in)-2] }) fmt.Println(dst) }
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1beta1 import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" v1 "k8s.io/apimachinery/pkg/apis/testapigroup/v1" "k8s.io/apimachinery/pkg/runtime/schema" ) // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // SloopSpec defines the desired state of Sloop type SloopSpec struct { // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster // Important: Run "make" to regenerate code after modifying this file // Foo is an example field of Sloop. Edit Sloop_types.go to remove/update Foo string `json:"foo,omitempty"` Cpu string `json:"cpu,omitempty"` Memory string `json:"memory,omitempty"` Size *int32 `json:"size"` Image string `json:"image"` Resources corev1.ResourceRequirements `json:"resources,omitempty"` Envs []corev1.EnvVar `json:"envs,omitempty"` Ports []corev1.ServicePort `json:"ports,omitempty"` } // SloopStatus defines the observed state of Sloop type SloopStatus struct { // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster // Important: Run "make" to regenerate code after modifying this file } // +kubebuilder:object:root=true // Sloop is the Schema for the sloops API type Sloop struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec SloopSpec `json:"spec,omitempty"` Status SloopStatus `json:"status,omitempty"` } // +kubebuilder:object:root=true // SloopList contains a list of Sloop type SloopList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []Sloop `json:"items"` } func init() { SchemeBuilder.Register(&Sloop{}, &SloopList{}) } func NewDeploy(app *Sloop) *appsv1.Deployment { labels := map[string]string{"app": app.Name} selector := &metav1.LabelSelector{MatchLabels: labels} return &appsv1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: "apps/v1", Kind: "Deployment", }, ObjectMeta: metav1.ObjectMeta{ Name: app.Name, Namespace: app.Namespace, OwnerReferences: []metav1.OwnerReference{ *metav1.NewControllerRef(app, schema.GroupVersionKind{ Group: v1.SchemeGroupVersion.Group, Version: v1.SchemeGroupVersion.Version, Kind: "Sloop", }), }, }, Spec: appsv1.DeploymentSpec{ Replicas: app.Spec.Size, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: labels, }, Spec: corev1.PodSpec{ Containers: newContainers(app), }, }, Selector: selector, }, } } func newContainers(app *Sloop) []corev1.Container { containerPorts := []corev1.ContainerPort{} for _, svcPort := range app.Spec.Ports { cport := corev1.ContainerPort{} cport.ContainerPort = svcPort.TargetPort.IntVal containerPorts = append(containerPorts, cport) } return []corev1.Container{ { Name: app.Name, Image: app.Spec.Image, Resources: app.Spec.Resources, Ports: containerPorts, ImagePullPolicy: corev1.PullIfNotPresent, Env: app.Spec.Envs, }, } } func NewService(app *Sloop) *corev1.Service { return &corev1.Service { TypeMeta: metav1.TypeMeta { Kind: "Service", APIVersion: "v1", }, ObjectMeta: metav1.ObjectMeta{ Name: app.Name, Namespace: app.Namespace, OwnerReferences: []metav1.OwnerReference{ *metav1.NewControllerRef(app, schema.GroupVersionKind{ Group: v1.SchemeGroupVersion.Group, Version: v1.SchemeGroupVersion.Version, Kind: "Sloop", }), }, }, Spec: corev1.ServiceSpec{ Ports: app.Spec.Ports, Selector: map[string]string{ "app": app.Name, }, //Type: corev1.ServiceTypeNodePort, Type: corev1.ServiceType("ClusterIP"), }, } }
package main import "fmt" func plus(first int, second int) int { return first + second } func plusPlus(a, b, c int) int { return a + b + c } func main() { result := plus(1, 2) fmt.Println(result) result2 := plusPlus(1, 2, 3) fmt.Println(result2) }
// Package selectionsort provides implementation of selection sort package selectionsort import ( "github.com/lzcqd/sedgewick/chap2_sorting/sortable" ) func Sort(data sortable.Interface) { for i := 0; i < data.Len(); i++ { min := i for j := i + 1; j < data.Len(); j++ { if data.Less(j, min) { min = j } } data.Swap(i, min) } }
package Problem0476 func findComplement(num int) int { temp := num res := 0 for temp > 0 { temp >>= 1 res <<= 1 res++ } return res ^ num }
package main import ( "fmt" "log" "net/http" "github.com/cagnosolutions/adb" "github.com/cagnosolutions/web" ) var mux *web.Mux var tmpl *web.TmplCache var db *adb.DB func init() { db = adb.NewDB() db.AddStore("user") db.AddStore("personnelData") db.AddStore("company") mux = web.NewMux() tmpl = web.NewTmplCache() } func main() { mux.AddRoutes(login, register, logout, login_page, register_page) mux.AddSecureRoutes(PERFORM_ADMIN, performAdmin, performAdminPOST, performCompany, performCompanyView, performCompanySave) mux.AddSecureRoutes(PERFORM_ADMIN, index, employee_information, employee_overview, business_results_overview, business_results, job_information, job_information_overview) mux.AddSecureRoutes(PERFORM_ADMIN, course_registrations, job_canidates_overview, job_canidates, employee_profile, course_overview, course, course_sessions, career_planning, performance_reviews, accountability_reviews) fmt.Println("Listening on :9090") fmt.Println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Register Your Routes -=-=-=-=-=-=-=-=-=-=-=-=-=-=-") log.Fatal(http.ListenAndServe(":9090", mux)) }
package cmd const Version = "3.25.1"
package coinbase import ( "log" "os" "testing" ) // Initialize the client with mock mode enabled on rpc // All calls return the corresponding json response from the test_data files func initTestClient() Client { return apiKeyClientTest(os.Getenv("COINBASE_KEY"), os.Getenv("COINBASE_SECRET")) } // About Mock Tests: // All Mock Tests simulate requests to the coinbase API by returning the expected // return values from a file under the test_data folder. The values received from // the file are compared with the expected value given the marshaling of the JSON // executed correctly. func TestMockGetBalanceParse(t *testing.T) { c := initTestClient() amount, err := c.GetBalance() if err != nil { log.Fatal(err) } compareFloat(t, "GetBalanceParse", 36.62800000, amount) } func TestMockGetReceiveAddressParse(t *testing.T) { c := initTestClient() params := &AddressParams{} address, err := c.GenerateReceiveAddress(params) if err != nil { log.Fatal(err) } compareString(t, "GetReceiveAddressParse", "muVu2JZo8PbewBHRp6bpqFvVD87qvqEHWA", address) } func TestMockGetAllAddressesParse(t *testing.T) { c := initTestClient() params := &AddressesParams{} addresses, err := c.GetAllAddresses(params) if err != nil { log.Fatal(err) } compareString(t, "GetAllAddressesParse", "2013-05-09T23:07:08-07:00", addresses.Addresses[0].CreatedAt) compareString(t, "GetAllAddressesParse", "mwigfecvyG4MZjb6R5jMbmNcs7TkzhUaCj", addresses.Addresses[1].Address) compareInt(t, "GetAllAddressesParse", 1, int64(addresses.NumPages)) } func TestMockCreateButtonParse(t *testing.T) { c := initTestClient() params := &Button{} data, err := c.CreateButton(params) if err != nil { log.Fatal(err) } compareString(t, "CreateButtonParse", "93865b9cae83706ae59220c013bc0afd", data.Code) compareString(t, "CreateButtonParse", "Sample description", data.Description) } func TestMockSendMoneyParse(t *testing.T) { c := initTestClient() params := &TransactionParams{} data, err := c.SendMoney(params) if err != nil { log.Fatal(err) } compareString(t, "SendMoneyParse", "-1.23400000", data.Transaction.Amount.Amount) compareString(t, "SendMoneyParse", "37muSN5ZrukVTvyVh3mT5Zc5ew9L9CBare", data.Transaction.RecipientAddress) } func TestMockRequestMoneyParse(t *testing.T) { c := initTestClient() params := &TransactionParams{} data, err := c.RequestMoney(params) if err != nil { log.Fatal(err) } compareString(t, "RequestMoneyParse", "1.23400000", data.Transaction.Amount.Amount) compareString(t, "RequestMoneyParse", "5011f33df8182b142400000e", data.Transaction.Recipient.Id) } func TestMockResendRequestParse(t *testing.T) { c := initTestClient() data, err := c.ResendRequest("ID") if err != nil { log.Fatal(err) } compareBool(t, "ResendRequestParse", true, data) } func TestMockCancelRequestParse(t *testing.T) { c := initTestClient() data, err := c.CancelRequest("ID") if err != nil { log.Fatal(err) } compareBool(t, "CancelRequestParse", false, data) } func TestMockCompleteRequestParse(t *testing.T) { c := initTestClient() data, err := c.CompleteRequest("ID") if err != nil { log.Fatal(err) } compareString(t, "CancelRequestParse", "503c46a3f8182b106500009b", data.Transaction.Id) } func TestMockCreateOrderFromButtonCodeParse(t *testing.T) { c := initTestClient() data, err := c.CreateOrderFromButtonCode("ID") if err != nil { log.Fatal(err) } compareString(t, "CreateOrderFromButtonCodeParse", "7RTTRDVP", data.Id) compareString(t, "CreateOrderFromButtonCodeParse", "new", data.Status) } func TestMockCreateUserParse(t *testing.T) { c := initTestClient() data, err := c.CreateUser("test@email.com", "password") if err != nil { log.Fatal(err) } compareString(t, "CreateUser", "newuser@example.com", data.Email) compareString(t, "CreateUser", "501a3d22f8182b2754000011", data.Id) } func TestMockBuyParse(t *testing.T) { c := initTestClient() data, err := c.Buy(1000.0, true) if err != nil { log.Fatal(err) } compareString(t, "Buys", "2013-01-28T16:08:58-08:00", data.CreatedAt) compareString(t, "Buys", "USD", data.Fees.Bank.CurrencyIso) compareString(t, "Buys", "13.55", data.Subtotal.Amount) } func TestMockSellParse(t *testing.T) { c := initTestClient() data, err := c.Sell(1000.0) if err != nil { log.Fatal(err) } compareString(t, "Sells", "2013-01-28T16:32:35-08:00", data.CreatedAt) compareString(t, "Sells", "USD", data.Fees.Bank.CurrencyIso) compareString(t, "Sells", "13.50", data.Subtotal.Amount) } func TestMockGetContactsParse(t *testing.T) { c := initTestClient() params := &ContactsParams{ Page: 1, Limit: 5, } data, err := c.GetContacts(params) if err != nil { log.Fatal(err) } compareString(t, "GetContacts", "user1@example.com", data.Emails[0]) } func TestMockGetTransactionsParse(t *testing.T) { c := initTestClient() data, err := c.GetTransactions(1) if err != nil { log.Fatal(err) } compareInt(t, "GetTransactions", 2, data.TotalCount) compareString(t, "GetTransactions", "5018f833f8182b129c00002f", data.Transactions[0].Id) compareString(t, "GetTransactions", "-1.00000000", data.Transactions[1].Amount.Amount) } func TestMockGetOrdersParse(t *testing.T) { c := initTestClient() data, err := c.GetOrders(1) if err != nil { log.Fatal(err) } compareString(t, "GetOrders", "buy_now", data.Orders[0].Button.Type) compareInt(t, "GetOrders", int64(0), int64(data.Orders[0].Transaction.Confirmations)) } func TestMockGetTransfersParse(t *testing.T) { c := initTestClient() data, err := c.GetTransfers(1) if err != nil { log.Fatal(err) } compareString(t, "GetTransfers", "BTC", data.Transfers[0].Btc.Currency) compareInt(t, "GetTransfers", int64(1), int64(data.NumPages)) } func TestMockGetTransaction(t *testing.T) { c := initTestClient() data, err := c.GetTransaction("ID") if err != nil { log.Fatal(err) } compareString(t, "GetTransaction", "5018f833f8182b129c00002f", data.Id) compareString(t, "GetTransaction", "BTC", data.Amount.Currency) compareString(t, "GetTransaction", "User One", data.Recipient.Name) } func TestMockGetOrder(t *testing.T) { c := initTestClient() data, err := c.GetOrder("ID") if err != nil { log.Fatal(err) } compareString(t, "GetTransaction", "A7C52JQT", data.Id) compareString(t, "GetTransaction", "BTC", data.TotalBtc.CurrencyIso) compareString(t, "GetTransaction", "test", data.Button.Name) } func TestMockGetUser(t *testing.T) { c := initTestClient() data, err := c.GetUser() if err != nil { log.Fatal(err) } compareString(t, "GetTransaction", "512db383f8182bd24d000001", data.Id) compareString(t, "GetTransaction", "49.76000000", data.Balance.Amount) compareString(t, "GetTransaction", "Company Name, Inc.", data.Merchant.CompanyName) } func compareFloat(t *testing.T, prefix string, expected float64, got float64) { if expected != got { t.Errorf(`%s Expected %0.32f but got %0.32f`, prefix, expected, got) } } func compareInt(t *testing.T, prefix string, expected int64, got int64) { if expected != got { t.Errorf("%s Expected %d but got %d", prefix, expected, got) } } func compareString(t *testing.T, prefix string, expected string, got string) { if expected != got { t.Errorf("%s Expected '%s' but got '%s'", prefix, expected, got) } } func compareBool(t *testing.T, prefix string, expected bool, got bool) { if expected != got { t.Errorf("%s Expected '%t' but got '%t'", prefix, expected, got) } }
package main import ( "flag" "math/rand" "os" "time" "github.com/ovirt/csi-driver/internal/ovirt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/klog" "sigs.k8s.io/controller-runtime/pkg/client/config" "sigs.k8s.io/controller-runtime/pkg/manager" "github.com/ovirt/csi-driver/pkg/service" ) var ( endpoint = flag.String("endpoint", "unix:/csi/csi.sock", "CSI endpoint") namespace = flag.String("namespace", "", "Namespace to run the controllers on") ovirtConfigFilePath = flag.String("ovirt-conf", "", "Path to ovirt api config") nodeName = flag.String("node-name", "", "The node name - the node this pods runs on") ) func init() { flag.Set("logtostderr", "true") klog.InitFlags(flag.CommandLine) } func main() { flag.Parse() rand.Seed(time.Now().UnixNano()) handle() os.Exit(0) } func handle() { if service.VendorVersion == "" { klog.Fatalf("VendorVersion must be set at compile time") } klog.V(2).Infof("Driver vendor %v %v", service.VendorName, service.VendorVersion) ovirtClient, err := ovirt.NewClient() if err != nil { klog.Fatalf("Failed to initialize ovirt client %s", err) } // Get a config to talk to the apiserver restConfig, err := config.GetConfig() if err != nil { klog.Fatal(err) } opts := manager.Options{ Namespace: *namespace, } // Create a new Cmd to provide shared dependencies and start components mgr, err := manager.New(restConfig, opts) if err != nil { klog.Fatal(err) } // get the node object by name and pass the VM ID because it is the node // id from the storage perspective. It will be used for attaching disks var nodeId string clientSet, err := kubernetes.NewForConfig(restConfig) if err != nil { klog.Fatal(err) } if *nodeName != "" { get, err := clientSet.CoreV1().Nodes().Get(*nodeName, metav1.GetOptions{}) if err != nil { klog.Fatal(err) } nodeId = get.Status.NodeInfo.SystemUUID } driver := service.NewOvirtCSIDriver(ovirtClient, mgr.GetClient(), nodeId) driver.Run(*endpoint) }
package bigquery import ( "context" "errors" "fmt" "testing" "time" "cloud.google.com/go/bigquery" "github.com/google/uuid" "github.com/googleapis/google-cloud-go-testing/bigquery/bqiface" "github.com/odpf/optimus/models" "github.com/stretchr/testify/assert" ) func TestBigquery(t *testing.T) { testingContext := context.Background() testingProject := "project" testingDataset := "dataset" secret := "some_secret" projectSpec := models.ProjectSpec{ Secret: models.ProjectSecrets{{ Name: SecretName, Value: secret, }}, } t.Run("CreateResource", func(t *testing.T) { t.Run("should return error when secret not found", func(t *testing.T) { datasetLabels := map[string]string{ "application": "optimus", } bQDatasetMetadata := BQDatasetMetadata{ Labels: datasetLabels, } bQDatasetResource := BQDataset{ Project: testingProject, Dataset: testingDataset, Metadata: bQDatasetMetadata, } resourceSpec := models.ResourceSpec{ Spec: bQDatasetResource, Type: models.ResourceTypeDataset, } invalidProjectSpec := models.ProjectSpec{} resourceRequest := models.CreateResourceRequest{ Resource: resourceSpec, Project: invalidProjectSpec, } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) bq := BigQuery{} err := bq.CreateResource(testingContext, resourceRequest) assert.NotNil(t, err) }) t.Run("should return error when creating BQ client is failed", func(t *testing.T) { datasetLabels := map[string]string{ "application": "optimus", } bQDatasetMetadata := BQDatasetMetadata{ Labels: datasetLabels, } bQDatasetResource := BQDataset{ Project: testingProject, Dataset: testingDataset, Metadata: bQDatasetMetadata, } resourceSpec := models.ResourceSpec{ Spec: bQDatasetResource, Type: models.ResourceTypeDataset, } resourceRequest := models.CreateResourceRequest{ Resource: resourceSpec, Project: projectSpec, } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) bQClientFactory.On("New", testingContext, secret).Return(bQClient, errors.New("some error")) bq := BigQuery{ ClientFac: bQClientFactory, } err := bq.CreateResource(testingContext, resourceRequest) assert.NotNil(t, err) }) t.Run("should return error when the resource type is unsupported", func(t *testing.T) { datasetLabels := map[string]string{ "application": "optimus", } bQDatasetMetadata := BQDatasetMetadata{ Labels: datasetLabels, } bQDatasetResource := BQDataset{ Project: testingProject, Dataset: testingDataset, Metadata: bQDatasetMetadata, } resourceSpec := models.ResourceSpec{ Spec: bQDatasetResource, } resourceRequest := models.CreateResourceRequest{ Resource: resourceSpec, Project: projectSpec, } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) bQClientFactory.On("New", testingContext, secret).Return(bQClient, nil) bq := BigQuery{ ClientFac: bQClientFactory, } err := bq.CreateResource(testingContext, resourceRequest) assert.NotNil(t, err) }) }) t.Run("UpdateResource", func(t *testing.T) { t.Run("should return error when secret not found", func(t *testing.T) { datasetLabels := map[string]string{ "application": "optimus", } bQDatasetMetadata := BQDatasetMetadata{ Labels: datasetLabels, } bQDatasetResource := BQDataset{ Project: testingProject, Dataset: testingDataset, Metadata: bQDatasetMetadata, } resourceSpec := models.ResourceSpec{ Spec: bQDatasetResource, Type: models.ResourceTypeDataset, } invalidProjectSpec := models.ProjectSpec{} resourceRequest := models.UpdateResourceRequest{ Resource: resourceSpec, Project: invalidProjectSpec, } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) bq := BigQuery{} err := bq.UpdateResource(testingContext, resourceRequest) assert.NotNil(t, err) }) t.Run("should return error when creating BQ client is failed", func(t *testing.T) { datasetLabels := map[string]string{ "application": "optimus", } bQDatasetMetadata := BQDatasetMetadata{ Labels: datasetLabels, } bQDatasetResource := BQDataset{ Project: testingProject, Dataset: testingDataset, Metadata: bQDatasetMetadata, } resourceSpec := models.ResourceSpec{ Spec: bQDatasetResource, Type: models.ResourceTypeDataset, } resourceRequest := models.UpdateResourceRequest{ Resource: resourceSpec, Project: projectSpec, } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) bQClientFactory.On("New", testingContext, secret).Return(bQClient, errors.New("some error")) bq := BigQuery{ ClientFac: bQClientFactory, } err := bq.UpdateResource(testingContext, resourceRequest) assert.NotNil(t, err) }) t.Run("should return error when the resource type is unsupported", func(t *testing.T) { datasetLabels := map[string]string{ "application": "optimus", } bQDatasetMetadata := BQDatasetMetadata{ Labels: datasetLabels, } bQDatasetResource := BQDataset{ Project: testingProject, Dataset: testingDataset, Metadata: bQDatasetMetadata, } resourceSpec := models.ResourceSpec{ Spec: bQDatasetResource, } resourceRequest := models.UpdateResourceRequest{ Resource: resourceSpec, Project: projectSpec, } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) bQClientFactory.On("New", testingContext, secret).Return(bQClient, nil) bq := BigQuery{ ClientFac: bQClientFactory, } err := bq.UpdateResource(testingContext, resourceRequest) assert.NotNil(t, err) }) }) t.Run("ReadResource", func(t *testing.T) { t.Run("should return error when secret not found", func(t *testing.T) { datasetLabels := map[string]string{ "application": "optimus", } bQDatasetMetadata := BQDatasetMetadata{ Labels: datasetLabels, } bQDatasetResource := BQDataset{ Project: testingProject, Dataset: testingDataset, Metadata: bQDatasetMetadata, } resourceSpec := models.ResourceSpec{ Spec: bQDatasetResource, Type: models.ResourceTypeDataset, } invalidProjectSpec := models.ProjectSpec{} resourceRequest := models.ReadResourceRequest{ Resource: resourceSpec, Project: invalidProjectSpec, } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) bq := BigQuery{} resp, err := bq.ReadResource(testingContext, resourceRequest) assert.Equal(t, models.ResourceSpec{}, resp.Resource) assert.NotNil(t, err) }) t.Run("should return error when creating BQ client is failed", func(t *testing.T) { datasetLabels := map[string]string{ "application": "optimus", } bQDatasetMetadata := BQDatasetMetadata{ Labels: datasetLabels, } bQDatasetResource := BQDataset{ Project: testingProject, Dataset: testingDataset, Metadata: bQDatasetMetadata, } resourceSpec := models.ResourceSpec{ Spec: bQDatasetResource, Type: models.ResourceTypeDataset, } resourceRequest := models.ReadResourceRequest{ Resource: resourceSpec, Project: projectSpec, } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) bQClientFactory.On("New", testingContext, secret).Return(bQClient, errors.New("some error")) bq := BigQuery{ ClientFac: bQClientFactory, } resp, err := bq.ReadResource(testingContext, resourceRequest) assert.Equal(t, models.ResourceSpec{}, resp.Resource) assert.NotNil(t, err) }) t.Run("should return error when the resource type is unsupported", func(t *testing.T) { datasetLabels := map[string]string{ "application": "optimus", } bQDatasetMetadata := BQDatasetMetadata{ Labels: datasetLabels, } bQDatasetResource := BQDataset{ Project: testingProject, Dataset: testingDataset, Metadata: bQDatasetMetadata, } resourceSpec := models.ResourceSpec{ Spec: bQDatasetResource, } resourceRequest := models.ReadResourceRequest{ Resource: resourceSpec, Project: projectSpec, } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) bQClientFactory.On("New", testingContext, secret).Return(bQClient, nil) bq := BigQuery{ ClientFac: bQClientFactory, } resp, err := bq.ReadResource(testingContext, resourceRequest) assert.Equal(t, models.ResourceSpec{}, resp.Resource) assert.NotNil(t, err) }) }) t.Run("DeleteResource", func(t *testing.T) { t.Run("should return error when secret not found", func(t *testing.T) { datasetLabels := map[string]string{ "application": "optimus", } bQDatasetMetadata := BQDatasetMetadata{ Labels: datasetLabels, } bQDatasetResource := BQDataset{ Project: testingProject, Dataset: testingDataset, Metadata: bQDatasetMetadata, } resourceSpec := models.ResourceSpec{ Spec: bQDatasetResource, Type: models.ResourceTypeDataset, } invalidProjectSpec := models.ProjectSpec{} resourceRequest := models.DeleteResourceRequest{ Resource: resourceSpec, Project: invalidProjectSpec, } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) bq := BigQuery{} err := bq.DeleteResource(testingContext, resourceRequest) assert.NotNil(t, err) }) t.Run("should return error when creating BQ client is failed", func(t *testing.T) { datasetLabels := map[string]string{ "application": "optimus", } bQDatasetMetadata := BQDatasetMetadata{ Labels: datasetLabels, } bQDatasetResource := BQDataset{ Project: testingProject, Dataset: testingDataset, Metadata: bQDatasetMetadata, } resourceSpec := models.ResourceSpec{ Spec: bQDatasetResource, Type: models.ResourceTypeDataset, } resourceRequest := models.DeleteResourceRequest{ Resource: resourceSpec, Project: projectSpec, } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) bQClientFactory.On("New", testingContext, secret).Return(bQClient, errors.New("some error")) bq := BigQuery{ ClientFac: bQClientFactory, } err := bq.DeleteResource(testingContext, resourceRequest) assert.NotNil(t, err) }) t.Run("should return error when the resource type is unsupported", func(t *testing.T) { datasetLabels := map[string]string{ "application": "optimus", } bQDatasetMetadata := BQDatasetMetadata{ Labels: datasetLabels, } bQDatasetResource := BQDataset{ Project: testingProject, Dataset: testingDataset, Metadata: bQDatasetMetadata, } resourceSpec := models.ResourceSpec{ Spec: bQDatasetResource, } resourceRequest := models.DeleteResourceRequest{ Resource: resourceSpec, Project: projectSpec, } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) bQClientFactory.On("New", testingContext, secret).Return(bQClient, nil) bq := BigQuery{ ClientFac: bQClientFactory, } err := bq.DeleteResource(testingContext, resourceRequest) assert.NotNil(t, err) }) }) t.Run("BackupResource", func(t *testing.T) { t.Run("should not return error when resource supported", func(t *testing.T) { spec := BQTable{ Project: "project", Dataset: "dataset", Table: "table", } eTag := "unique ID" tableMetadata := &bigquery.TableMetadata{ Name: spec.Table, Schema: bigquery.Schema{ { Name: "message", Type: "STRING", }, { Name: "message_type", Type: "STRING", }, { Name: "recipient", Type: "STRING", Repeated: true, }, { Name: "time", Type: "TIME", }, }, Clustering: &bigquery.Clustering{ Fields: []string{"message_type"}, }, ETag: eTag, } resourceSpec := models.ResourceSpec{ Name: "project:dataset.table", Spec: spec, Type: models.ResourceTypeTable, } backupTime := time.Now() resourceRequest := models.BackupResourceRequest{ Resource: resourceSpec, BackupSpec: models.BackupRequest{ Project: projectSpec, Config: map[string]string{ BackupConfigTTL: "720h", BackupConfigDataset: "optimus_backup", BackupConfigPrefix: "backup", }, ID: uuid.Must(uuid.NewRandom()), }, BackupTime: backupTime, } destinationTable := BQTable{ Project: spec.Project, Dataset: resourceRequest.BackupSpec.Config[BackupConfigDataset], Table: fmt.Sprintf("backup_dataset_table_%s", resourceRequest.BackupSpec.ID), } resultURN := fmt.Sprintf(tableURNFormat, BigQuery{}.Name(), destinationTable.Project, destinationTable.Dataset, destinationTable.Table) datasetMetadata := bqiface.DatasetMetadata{ DatasetMetadata: bigquery.DatasetMetadata{ ETag: eTag, }, } toUpdate := bigquery.TableMetadataToUpdate{ ExpirationTime: resourceRequest.BackupTime.Add(time.Hour * 24 * 30), } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) bQDatasetHandle := new(BqDatasetMock) defer bQDatasetHandle.AssertExpectations(t) bQTable := new(BqTableMock) defer bQTable.AssertExpectations(t) bQCopier := new(BqCopierMock) defer bQCopier.AssertExpectations(t) bQJob := new(BqJobMock) defer bQJob.AssertExpectations(t) bQClientFactory.On("New", testingContext, secret).Return(bQClient, nil) //duplicate table bQClient.On("DatasetInProject", spec.Project, spec.Dataset).Return(bQDatasetHandle).Once() bQClient.On("DatasetInProject", destinationTable.Project, destinationTable.Dataset).Return(bQDatasetHandle).Once() bQDatasetHandle.On("Metadata", testingContext).Return(&datasetMetadata, nil) bQDatasetHandle.On("Table", spec.Table).Return(bQTable) bQDatasetHandle.On("Table", destinationTable.Table).Return(bQTable) bQTable.On("CopierFrom", []bqiface.Table{bQTable}).Return(bQCopier) bQCopier.On("Run", testingContext).Return(bQJob, nil) bQJob.On("Wait", testingContext).Return(&bigquery.JobStatus{}, nil) //update expiry bQTable.On("Metadata", testingContext).Return(tableMetadata, nil).Once() bQTable.On("Update", testingContext, toUpdate, eTag).Return(tableMetadata, nil) //verify bQTable.On("Metadata", testingContext).Return(tableMetadata, nil).Once() bq := BigQuery{ ClientFac: bQClientFactory, } resp, err := bq.BackupResource(testingContext, resourceRequest) assert.Nil(t, err) assert.Equal(t, resultURN, resp.ResultURN) assert.Equal(t, destinationTable, resp.ResultSpec) }) t.Run("should return error when resource is not supported", func(t *testing.T) { resourceSpec := models.ResourceSpec{ Name: "project:dataset.table", Spec: BQTable{ Project: "project", Dataset: "dataset", Table: "table", }, Type: models.ResourceTypeView, } resourceRequest := models.BackupResourceRequest{ Resource: resourceSpec, } bq := BigQuery{} resp, err := bq.BackupResource(testingContext, resourceRequest) assert.Equal(t, models.ErrUnsupportedResource, err) assert.Equal(t, models.BackupResourceResponse{}, resp) }) t.Run("should return error when datastore secret is not available", func(t *testing.T) { resourceSpec := models.ResourceSpec{ Name: "project:dataset.table", Spec: BQTable{ Project: "project", Dataset: "dataset", Table: "table", }, Type: models.ResourceTypeTable, } resourceRequest := models.BackupResourceRequest{ Resource: resourceSpec, BackupSpec: models.BackupRequest{ Project: models.ProjectSpec{ Secret: models.ProjectSecrets{{ Name: "other_secret", Value: secret, }}, }, }, } bq := BigQuery{} resp, err := bq.BackupResource(testingContext, resourceRequest) assert.Equal(t, fmt.Sprintf(errSecretNotFoundStr, SecretName, bq.Name()), err.Error()) assert.Equal(t, models.BackupResourceResponse{}, resp) }) t.Run("should return error when unable to create bq client", func(t *testing.T) { resourceSpec := models.ResourceSpec{ Name: "project:dataset.table", Spec: BQTable{ Project: "project", Dataset: "dataset", Table: "table", }, Type: models.ResourceTypeTable, } resourceRequest := models.BackupResourceRequest{ Resource: resourceSpec, BackupSpec: models.BackupRequest{ Project: models.ProjectSpec{ Secret: models.ProjectSecrets{{ Name: SecretName, Value: secret, }}, }, }, } bQClient := new(BqClientMock) defer bQClient.AssertExpectations(t) bQClientFactory := new(BQClientFactoryMock) defer bQClientFactory.AssertExpectations(t) errorMsg := "bq client failed" bQClientFactory.On("New", testingContext, secret).Return(bQClient, errors.New(errorMsg)) bq := BigQuery{ ClientFac: bQClientFactory, } resp, err := bq.BackupResource(testingContext, resourceRequest) assert.Equal(t, errorMsg, err.Error()) assert.Equal(t, models.BackupResourceResponse{}, resp) }) }) }
package problem0104 import "testing" func TestSolve(t *testing.T) { node1 := &TreeNode{Val: 3} node2 := &TreeNode{Val: 9} node3 := &TreeNode{Val: 20} node4 := &TreeNode{Val: 15} node5 := &TreeNode{Val: 7} node1.Left = node2 node1.Right = node3 node3.Left = node4 node3.Right = node5 t.Log(maxDepth(node1)) }
package camt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document02600105 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:camt.026.001.05 Document"` Message *UnableToApplyV05 `xml:"UblToApply"` } func (d *Document02600105) AddMessage() *UnableToApplyV05 { d.Message = new(UnableToApplyV05) return d.Message } // Scope // The Unable To Apply message is sent by a case creator or a case assigner to a case assignee. This message is used to initiate an investigation of a payment instruction that cannot be executed or reconciled. // Usage // The Unable To Apply case occurs in two situations: // - an agent cannot execute the payment instruction due to missing or incorrect information // - a creditor cannot reconcile the payment entry as it is received unexpectedly, or missing or incorrect information prevents reconciliation // The Unable To Apply message // - always follows the reverse route of the original payment instruction // - must be forwarded to the preceding agents in the payment processing chain, where appropriate // - covers one and only one payment instruction (or payment entry) at a time; if several payment instructions cannot be executed or several payment entries cannot be reconciled, then multiple Unable To Apply messages must be sent. // Depending on what stage the payment is and what has been done to it, for example incorrect routing, errors/omissions when processing the instruction or even the absence of any error, the unable to apply case may lead to a: // - Additional Payment Information message, sent to the case creator/case assigner, if a truncation or omission in a payment instruction prevented reconciliation. // - Request To Cancel Payment message, sent to the subsequent agent in the payment processing chain, if the original payment instruction has been incorrectly routed through the chain of agents (this also entails a new corrected payment instruction being issued). Prior to sending the payment cancellation request, the agent should first send a resolution indicating that a cancellation will follow (CWFW). // - Request To Modify Payment message, sent to the subsequent agent in the payment processing chain, if a truncation or omission has occurred during the processing of the original payment instruction. Prior to sending the modify payment request, the agent should first send a resolution indicating that a modification will follow (MWFW). // - Debit Authorisation Request message, sent to the case creator/case assigner, if the payment instruction has reached an incorrect creditor. // The UnableToApply message has the following main characteristics: // The case creator (the instructed party/creditor of a payment instruction) assigns a unique case identification and optionally the reason code for the Unable To Apply message. This information will be passed unchanged to all subsequent case assignees. // The case creator specifies the identification of the underlying payment instruction. This identification needs to be updated by the subsequent case assigner(s) in order to match the one used with their case assignee(s). // The Unable To Apply Justification element allows the assigner to indicate whether a specific element causes the unable to apply situation (incorrect element and/or mismatched element can be listed) or whether any supplementary information needs to be forwarded. type UnableToApplyV05 struct { // Identifies the assignment of an investigation case from an assigner to an assignee. // Usage: The Assigner must be the sender of this confirmation and the Assignee must be the receiver. Assignment *iso20022.CaseAssignment3 `xml:"Assgnmt"` // Identifies the investigation case. Case *iso20022.Case3 `xml:"Case"` // References the payment instruction or statement entry that a party is unable to execute or unable to reconcile. Underlying *iso20022.UnderlyingTransaction3Choice `xml:"Undrlyg"` // Explains the reason why the case creator is unable to apply the instruction. Justification *iso20022.UnableToApplyJustification3Choice `xml:"Justfn"` // Additional information that cannot be captured in the structured elements and/or any other specific block. SupplementaryData []*iso20022.SupplementaryData1 `xml:"SplmtryData,omitempty"` } func (u *UnableToApplyV05) AddAssignment() *iso20022.CaseAssignment3 { u.Assignment = new(iso20022.CaseAssignment3) return u.Assignment } func (u *UnableToApplyV05) AddCase() *iso20022.Case3 { u.Case = new(iso20022.Case3) return u.Case } func (u *UnableToApplyV05) AddUnderlying() *iso20022.UnderlyingTransaction3Choice { u.Underlying = new(iso20022.UnderlyingTransaction3Choice) return u.Underlying } func (u *UnableToApplyV05) AddJustification() *iso20022.UnableToApplyJustification3Choice { u.Justification = new(iso20022.UnableToApplyJustification3Choice) return u.Justification } func (u *UnableToApplyV05) AddSupplementaryData() *iso20022.SupplementaryData1 { newValue := new(iso20022.SupplementaryData1) u.SupplementaryData = append(u.SupplementaryData, newValue) return newValue }
package types import ( sdk "github.com/hashrs/blockchain/framework/chain-app/types" sdkerrors "github.com/hashrs/blockchain/framework/chain-app/types/errors" ) // RouterKey is used to route messages and queriers to the greeter module const RouterKey = "main-net" // MsgGreet defines the MsgGreet Message type MsgGreet struct { Body string // content of the greeting Sender sdk.AccAddress // account signing and sending the greeting Recipient sdk.AccAddress // account designated as recipient of the greeeting (not a signer) } // NewMsgGreet is a constructor function for MsgGreet func NewMsgGreet(sender sdk.AccAddress, body string, recipient sdk.AccAddress) MsgGreet { return MsgGreet{ Body: body, Sender: sender, Recipient: recipient, } } // Route should return the name of the module func (msg MsgGreet) Route() string { return RouterKey } // Type should return the action func (msg MsgGreet) Type() string { return "main-net" } // ValidateBasic runs stateless checks on the message func (msg MsgGreet) ValidateBasic() error { if msg.Recipient.Empty() { return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Recipient.String()) } if len(msg.Sender) == 0 || len(msg.Body) == 0 || len(msg.Recipient) == 0 { return sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "Sender, Recipient and/or Body cannot be empty") } return nil } // GetSigners returns the addresses of those required to sign the message func (msg MsgGreet) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Sender} } // GetSignBytes encodes the message for signing func (msg MsgGreet) GetSignBytes() []byte { return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) }
package main_test import ( "os" "encoding/json" "net/http" "net/url" "net/http/httptest" "testing" "io/ioutil" "fmt" "strings" "bytes" main "webserver" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" "golang.org/x/crypto/bcrypt" ) const testUser = "ben" const testPassword = "password" const testAdmin = "admin" const testAdminPwd = "welcome" func TestMain(m *testing.M) { os.Setenv("DB_DIALECT","sqlite3") os.Setenv("DB_URL", "test.db") fmt.Println("Environment variables set") hash, _ := bcrypt.GenerateFromPassword([]byte(testPassword),main.BcryptCost) adminhash, _ := bcrypt.GenerateFromPassword([]byte(testAdminPwd),main.BcryptCost) user := main.User{ UserName: testUser , Role:"user", Email: "user@test.com", PasswordHash: hash, } adminUser := main.User{ UserName: testAdmin, Role: "admin", Email: "user@test.com", PasswordHash: adminhash, } sub1 := main.Subscriber{ Name: "Donald Duck", Email: "donald@disney.com", } sub2 := main.Subscriber{ Name: "Mickey Mouse", Email: "mickey@disney.com", } // try to remove test.db _ = os.Remove("test.db") db, err := gorm.Open(os.Getenv("DB_DIALECT"), os.Getenv("DB_URL")) if err != nil { panic("failed to connect database") } defer db.Close() db.AutoMigrate(&main.User{}) db.AutoMigrate(&main.Subscriber{}) db.Create(&user) db.Create(&adminUser) db.Create(&sub1) db.Create(&sub2) main.DB = db retCode := m.Run() //myTeardownFunction() os.Exit(retCode) } func doLogin(user, password string) (*httptest.ResponseRecorder, error) { req, err := http.NewRequest("GET", "/login", nil) if err != nil { return nil, err } // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. rr := httptest.NewRecorder() handler := http.HandlerFunc(main.LoginHandler) req.SetBasicAuth(user,password) // Add our context to the request: note that WithContext returns a copy of // the request, which we must assign. //req = req.WithContext(ctx) handler.ServeHTTP(rr, req) return rr, nil } func getAdminPage(path, token string) (*httptest.ResponseRecorder, error) { return getPage(path, main.VerifyAdmin(main.StatusHandler), token) } func getUserPage(path, token string) (*httptest.ResponseRecorder, error) { return getPage(path, main.VerifyUser(main.StatusHandler), token) } func getPage(path string, h http.HandlerFunc, token string) (*httptest.ResponseRecorder, error) { req, err := http.NewRequest("GET", path, nil) if err != nil { return nil, err } req.Header["Authorization"] = []string{"Bearer " + token} rr := httptest.NewRecorder() handler := http.HandlerFunc(h) handler.ServeHTTP(rr, req) return rr, nil } func TestLoginHandler_ValidCredentialsSucceed(t *testing.T) { rr, err := doLogin(testUser, testPassword) if err != nil { t.Fatal(err) } // Check the status code is what we expect. if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } body, _ := ioutil.ReadAll(rr.Result().Body) token := string(body) // If the token is empty... if (token == "Unauthorized\n") { // If we get here, the required token is missing t.Errorf("no token received") return } } func TestLoginHandler_InvalidCredentialsFail(t *testing.T) { rr, err := doLogin(testUser, "wrong") if err != nil { t.Fatal(err) } // Check the status code is what we expect. if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) } body, _ := ioutil.ReadAll(rr.Result().Body) expected := "Unauthorized\n" // If the token is empty... if (string(body) != expected) { // If we get here, the required token is present (and should not be) t.Errorf("bad response for invalid user: Expected |%s|, got |%s|", expected, string(body)) return } } func TestValidateToken_ValidTokenSucceed(t *testing.T) { rr, err := doLogin(testUser, testPassword) if err != nil { t.Fatal(err) } if status := rr.Code; status != http.StatusOK { t.Errorf("login handler returned wrong status code: got %v want %v", status, http.StatusOK) } body, _ := ioutil.ReadAll(rr.Result().Body) token := string(body) rr, err = getUserPage("/user/", token) if status := rr.Code; status != http.StatusOK { t.Errorf("token handler returned wrong status code: got %v want %v", status, http.StatusOK) } } func TestValidateToken_InvalidTokenFail(t *testing.T) { rr, _ := getUserPage("/user/", "badtoken") if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("token handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) } } func TestRegisterUser_Succeed(t *testing.T) { form := url.Values{} form.Add("email", "newuser@test.com") form.Add("user", "newuser") form.Add("password", "newpassword") req, _ := http.NewRequest("POST", "/register", strings.NewReader(form.Encode())) req.Header.Add("Content-Type", "application/x-www-form-urlencoded") rr := httptest.NewRecorder() handler := http.HandlerFunc(main.RegisterHandler) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("register handler returned wrong status code: got %v want %v", status, http.StatusOK) } } func TestSubscribe_Succeed(t *testing.T) { sub := main.Subscriber{ Name: "John Doe", Email: "newuser@test.com", } js, _ := json.Marshal(&sub) req, _ := http.NewRequest("POST", "/subscribe", bytes.NewBuffer(js)) req.Header.Add("Content-Type", "application/json") rr := httptest.NewRecorder() handler := http.HandlerFunc(main.SubscribeHandler) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("subscribe handler returned wrong status code: got %v want %v", status, http.StatusOK) } } func TestVerifyAdmin_ValidTokenSucceed(t *testing.T) { rr, err := doLogin(testAdmin, testAdminPwd) if err != nil { t.Fatal(err) } if status := rr.Code; status != http.StatusOK { t.Errorf("login handler returned wrong status code: got %v want %v", status, http.StatusOK) } body, _ := ioutil.ReadAll(rr.Result().Body) token := string(body) rr, err = getAdminPage("/admin/", token) if status := rr.Code; status != http.StatusOK { t.Errorf("token handler returned wrong status code: got %v want %v", status, http.StatusOK) } } func TestVerifyAdmin_RegularUserFail(t *testing.T) { rr, err := doLogin(testUser, testPassword) if err != nil { t.Fatal(err) } if status := rr.Code; status != http.StatusOK { t.Errorf("login handler returned wrong status code: got %v want %v", status, http.StatusOK) } body, _ := ioutil.ReadAll(rr.Result().Body) token := string(body) rr, err = getAdminPage("/admin/", token) if status := rr.Code; status != http.StatusUnauthorized { t.Errorf("token handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) } } func TestListSubs_Success(t *testing.T) { rr, err := doLogin(testAdmin, testAdminPwd) if err != nil { t.Fatal(err) } if status := rr.Code; status != http.StatusOK { t.Errorf("login handler returned wrong status code: got %v want %v", status, http.StatusOK) } body, _ := ioutil.ReadAll(rr.Result().Body) token := string(body) rr, err = getPage("/admin/list_subs", main.VerifyAdmin(main.SubListHandler), token) if status := rr.Code; status != http.StatusOK { t.Errorf("token handler returned wrong status code: got %v want %v", status, http.StatusUnauthorized) } }
package secret const ( wink = 1 << iota doubleBlink closeYourEyes jump reverse ) var secretHandshakeMap = map[uint]string{ wink: "wink", doubleBlink: "double blink", closeYourEyes: "close your eyes", jump: "jump", } func Handshake(code uint) []string { handshake := []string{} for i := uint(1); i < reverse; i <<= 1 { if code & i != 0 { handshake = append(handshake, secretHandshakeMap[i]) } } if code & reverse != 0 { for i, j := 0, len(handshake) - 1; i < j; i, j = i + 1, j - 1 { handshake[i], handshake[j] = handshake[j], handshake[i] } } return handshake }
// Copyright 2015 CoreOS, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import "log" type tester struct { failures []failure cluster *cluster limit int } func (tt *tester) runLoop() { for i := 0; i < tt.limit; i++ { for j, f := range tt.failures { if err := tt.cluster.WaitHealth(); err != nil { log.Printf("etcd-tester: [round#%d case#%d] wait full health error: %v", i, j, err) if err := tt.cleanup(i, j); err != nil { log.Printf("etcd-tester: [round#%d case#%d] cleanup error: %v", i, j, err) return } continue } log.Printf("etcd-tester: [round#%d case#%d] start failure %s", i, j, f.Desc()) log.Printf("etcd-tester: [round#%d case#%d] start injecting failure...", i, j) if err := f.Inject(tt.cluster, i); err != nil { log.Printf("etcd-tester: [round#%d case#%d] injection error: %v", i, j, err) if err := tt.cleanup(i, j); err != nil { log.Printf("etcd-tester: [round#%d case#%d] cleanup error: %v", i, j, err) return } continue } log.Printf("etcd-tester: [round#%d case#%d] start recovering failure...", i, j) if err := f.Recover(tt.cluster, i); err != nil { log.Printf("etcd-tester: [round#%d case#%d] recovery error: %v", i, j, err) if err := tt.cleanup(i, j); err != nil { log.Printf("etcd-tester: [round#%d case#%d] cleanup error: %v", i, j, err) return } continue } log.Printf("etcd-tester: [round#%d case#%d] succeed!", i, j) } } } func (tt *tester) cleanup(i, j int) error { log.Printf("etcd-tester: [round#%d case#%d] cleaning up...", i, j) if err := tt.cluster.Cleanup(); err != nil { return err } return tt.cluster.Bootstrap() }
package main import ( "fmt" "github.com/liuzl/fmr" ) type TS struct { *fmr.TableState } func (t *TS) e(ts *TS) bool { if t == nil && ts == nil { return true } if (t != nil && ts == nil) || (t == nil && ts != nil) { return false } return false } func main() { var t *TS ret := t.e(t) fmt.Println(ret) var a, b interface{} fmt.Println(a == b) }
package main import ( "fmt" "hash/crc32" ) func main(){ h := crc32.NewIEEE() fmt.Println(h) fmt.Println(h.Sum32()) }
package birpc_test import ( "encoding/json" "io" "net" "testing" "github.com/tv42/birpc" "github.com/tv42/birpc/jsonmsg" ) type Request struct { Word string } type Reply struct { Length int } type LowLevelReply struct { Id uint64 `json:"id,string"` Result Reply `json:"result"` Error *birpc.Error `json:"error"` } type WordLength struct{} func (_ WordLength) Len(request *Request, reply *Reply) error { reply.Length = len(request.Word) return nil } // more than two arguments func (_ WordLength) OK(request *Request, reply *Reply, b bool) error { return nil } // wrong return type func (_ WordLength) Ignore1(request *Request, reply *Reply) bool { return false } // wrong number of return values func (_ WordLength) Ignore2(request *Request, reply *Reply) (error, bool) { return nil, false } // fewer than two arguments func (_ WordLength) Ignore3(int) error { return nil } // non-pointer for second argument func (_ WordLength) Ignore4(int, string) error { return nil } // this is here only to trigger a bug where all methods are thought to // be rpc methods func (_ WordLength) redHerring() { } func makeRegistry() *birpc.Registry { r := birpc.NewRegistry() r.RegisterService(WordLength{}) return r } const PALINDROME = `{"id": "42", "fn": "WordLength.Len", "args": {"Word": "saippuakauppias"}}` + "\n" func TestServerSimple(t *testing.T) { c, s := net.Pipe() defer c.Close() registry := makeRegistry() server := birpc.NewEndpoint(jsonmsg.NewCodec(s), registry) server_err := make(chan error) go func() { server_err <- server.Serve() }() io.WriteString(c, PALINDROME) var reply LowLevelReply dec := json.NewDecoder(c) if err := dec.Decode(&reply); err != nil && err != io.EOF { t.Fatalf("decode failed: %s", err) } t.Logf("reply msg: %#v", reply) if reply.Error != nil { t.Fatalf("unexpected error response: %v", reply.Error) } if reply.Result.Length != 15 { t.Fatalf("got wrong answer: %v", reply.Result.Length) } c.Close() err := <-server_err if err != io.EOF { t.Fatalf("unexpected error from ServeCodec: %v", err) } } func TestClient(t *testing.T) { c, s := net.Pipe() defer c.Close() registry := makeRegistry() server := birpc.NewEndpoint(jsonmsg.NewCodec(s), registry) server_err := make(chan error) go func() { server_err <- server.Serve() }() client := birpc.NewEndpoint(jsonmsg.NewCodec(c), nil) client_err := make(chan error) go func() { client_err <- client.Serve() }() // Synchronous calls args := &Request{"xyzzy"} reply := &Reply{} err := client.Call("WordLength.Len", args, reply) if err != nil { t.Errorf("unexpected error from call: %v", err.Error()) } if reply.Length != 5 { t.Fatalf("got wrong answer: %v", reply.Length) } // would panic if method was not ignored client.Call("WordLength.Ignore1", args, reply) c.Close() err = <-server_err if err != io.EOF { t.Fatalf("unexpected error from peer ServeCodec: %v", err) } err = <-client_err if err != io.ErrClosedPipe { t.Fatalf("unexpected error from local ServeCodec: %v", err) } } func TestClientNilResult(t *testing.T) { c, s := net.Pipe() defer c.Close() registry := makeRegistry() server := birpc.NewEndpoint(jsonmsg.NewCodec(s), registry) server_err := make(chan error) go func() { server_err <- server.Serve() }() client := birpc.NewEndpoint(jsonmsg.NewCodec(c), nil) client_err := make(chan error) go func() { client_err <- client.Serve() }() // Synchronous calls args := &Request{"xyzzy"} err := client.Call("WordLength.Len", args, nil) if err != nil { t.Errorf("unexpected error from call: %v", err.Error()) } c.Close() err = <-server_err if err != io.EOF { t.Fatalf("unexpected error from peer ServeCodec: %v", err) } err = <-client_err if err != io.ErrClosedPipe { t.Fatalf("unexpected error from local ServeCodec: %v", err) } } type EndpointPeer struct { seen *birpc.Endpoint } type nothing struct{} func (e *EndpointPeer) Poke(request *nothing, reply *nothing, endpoint *birpc.Endpoint) error { if e.seen != nil { panic("poke called twice") } e.seen = endpoint return nil } type EndpointPeer_LowLevelReply struct { Id uint64 `json:"id,string"` Result json.RawMessage `json:"result"` Error *birpc.Error `json:"error"` } func TestServerEndpointArg(t *testing.T) { peer := &EndpointPeer{} registry := birpc.NewRegistry() registry.RegisterService(peer) c, s := net.Pipe() defer c.Close() server := birpc.NewEndpoint(jsonmsg.NewCodec(s), registry) server_err := make(chan error) go func() { server_err <- server.Serve() }() io.WriteString(c, `{"id":"42","fn":"EndpointPeer.Poke","args":{}}`) var reply EndpointPeer_LowLevelReply dec := json.NewDecoder(c) if err := dec.Decode(&reply); err != nil && err != io.EOF { t.Fatalf("decode failed: %s", err) } t.Logf("reply msg: %#v", reply) if reply.Error != nil { t.Fatalf("unexpected error response: %v", reply.Error) } c.Close() err := <-server_err if err != io.EOF { t.Fatalf("unexpected error from ServeCodec: %v", err) } if peer.seen == nil { t.Fatalf("peer never saw a birpc.Endpoint") } }
package solver import ( "fmt" "math/rand" "os" "time" "github.com/Karocyt/Npupu/internal/sortedhashedtree" ) // ScoreFn type: heuristic functions prototype type ScoreFn func([]int, int, int) float32 var size int var goalKey string var goalMap map[int][2]int var finalGrid []int type counters struct { maxStates int totalOpenedStates int totalStates int startTime time.Time totalTime time.Duration } // Solver contains all variables required to solve the grid // Solver.Solution contains ordered states from the starting grid to the solved one type Solver struct { counters Name string openedStates *sortedhashedtree.SortedHashedTree fn ScoreFn depth int Solution chan []*gridState E error Stats chan counters } // Init initialize globals func Init(gridSize int, classic bool, input []int, randomSize int, shuffleCount int) (map[int][2]int, []int, []int) { rand.Seed(time.Now().UnixNano()) size = gridSize if input == nil { size = randomSize } goalKey, goalMap, finalGrid = makeGoalState(classic) if input == nil { input = pupuRand(shuffleCount) } else if !checkSolvy(input, classic) { fmt.Println("Pupu is not solvable :3") os.Exit(0) } return goalMap, finalGrid, input } // New initialize a new solverStruct, required to disciminate variables in multi-solving func New(grid []int, gridSize int, fn ScoreFn, name string) *Solver { solver := Solver{ counters: counters{}, Name: name, fn: fn, openedStates: sortedhashedtree.New(), Solution: make(chan []*gridState, 1), Stats: make(chan counters, 1), } state := newGrid(nil) state.grid = grid state.depth = 0 state.score = fn(grid, gridSize, 1) state.key = state.mapKey() state.id = 42 state.path = []int8{} solver.AppendState(&state) return &solver } // PrintStats does exactly what it says func PrintStats(stats counters) { fmt.Println("Total time elapsed:", stats.totalTime) fmt.Printf("Total states generated (time complexity): %d\n", stats.totalStates) fmt.Printf("Total states expanded: %d\n", stats.totalOpenedStates) fmt.Printf("Maximum states in the open set at once (space complexity): %d\n\n", stats.maxStates) } func makeGoalState(classic bool) (string, map[int][2]int, []int) { s := size nbPos := make(map[int][2]int) puzzle := make([]int, s*s) cur := 1 x := 0 ix := 1 y := 0 iy := 0 if classic { for cur < s*s { if x == s { y++ x = 0 } puzzle[x+y*s] = cur nbPos[cur] = [2]int{y, x} cur++ x++ } nbPos[0] = [2]int{y, x} puzzle[x+y*s] = 0 } else { for cur < s*s { puzzle[x+y*s] = cur nbPos[cur] = [2]int{y, x} cur++ if x+ix == s || x+ix < 0 || (ix != 0 && puzzle[x+ix+y*s] != 0) { iy = ix ix = 0 } else if y+iy == s || y+iy < 0 || (iy != 0 && puzzle[x+(y+iy)*s] != 0) { ix = -iy iy = 0 } x += ix y += iy } nbPos[0] = [2]int{y, x} puzzle[x+y*s] = 0 } return gridState{grid: puzzle}.mapKey(), nbPos, puzzle } // PrintRes prints. func (solver *Solver) PrintRes(solution []*gridState, success bool, stats counters, display bool) { if display { for _, step := range solution { fmt.Println(step) } } fmt.Printf("Solution using %s:\n\n", solver.Name) if success { fmt.Printf("Solution found: %d moves\n", len(solution)-1) } else { fmt.Println("This puzzle is not solvable") } PrintStats(stats) } // AppendState prout func (solver *Solver) AppendState(state *gridState) bool { return solver.openedStates.Insert(state.key, state, state.score) }
package main import "fmt" func main() { // 1、未使用的常亮可以编译通过 // const x = 123 // const y = 1.23 // fmt.Println(x) // 结论:为使用的常量可以编译通过,常量是一个简单值的表示符号, 在程序运行的时候不会被修改。 // 2、未初始化的常量的情况 // const ( // x uint16 = 120 // y // c // s = "abc" // z // ) // fmt.Printf("%T %v \n", y, y) // fmt.Printf("%T %v \n", z, z) // fmt.Printf("%T, %v \n", c, c) // 常量组中如果不指定类型和初始化的值,则与上一行的非空常量的右值相同 // 3、将 nil 分配给 string 类型的变量 // var x string = nil // if x == nil { // x = "default" // } // fmt.Println(x) // // 解析: 1、nil不能分配给string的变量。 若果只是想想赋值默认值, 可以修改代码如下: // var x string // if x == "" { // x = "default" // } // fmt.Println(x) }
package main import ( "github.com/gin-contrib/pprof" "github.com/gin-gonic/gin" "qqfav-service/config" "qqfav-service/filters" "qqfav-service/filters/auth" routeRegister "qqfav-service/routes" "net/http" //proxy "github.com/chenhg5/gin-reverseproxy" ) func initRouter() *gin.Engine { router := gin.New() router.LoadHTMLGlob(config.GetEnv().TemplatePath + "/*") // html模板 if config.GetEnv().Debug { pprof.Register(router) // 性能分析工具 } //router.Use(Cors()) //跨域 router.Use(gin.Logger()) router.Use(handleErrors()) // 错误处理 router.Use(filters.RegisterSession()) // 全局session router.Use(filters.RegisterCache()) // 全局cache router.Use(auth.RegisterGlobalAuthDriver("cookie", "web_auth")) // 全局auth cookie router.Use(auth.RegisterGlobalAuthDriver("jwt", "jwt_auth")) // 全局auth jwt router.NoRoute(func(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{ "code": 404, "msg": "找不到该路由", }) }) router.NoMethod(func(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{ "code": 404, "msg": "找不到该方法", }) }) routeRegister.RegisterApiRouter(router) // ReverseProxy //router.Use(proxy.ReverseProxy(map[string] string { // "http://www.qqfav.com:10070" : "localhost:8001", // "http://localhost:10070":"localhost:8002", //})) return router } func Cors() gin.HandlerFunc { return func(context *gin.Context) { method := context.Request.Method context.Header("Access-Control-Allow-Origin", "*") context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token") context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS") context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type") context.Header("Access-Control-Allow-Credentials", "true") if method == "OPTIONS" { context.AbortWithStatus(http.StatusNoContent) } context.Next() } }
package api import ( "net/http" "encoding/json" "io/ioutil" ); const API_BASE_URL = "https://www.kimonolabs.com/api/ck52w24s" const API_KEY_TCODE = "tEqeo1dz9ZfMuUvCeR55gM80kT6AkJzX" type TcodeResponse struct { Tcode string `json:"tcode"` Status string `json:"status"` } func GetTcode(ncode string) (string, error) { url := API_BASE_URL + "?apikey="+API_KEY_TCODE+"&ncode="+ncode+"&kimmodify=1" resp, err := http.Get(url) if(err == nil){ body, err := ioutil.ReadAll(resp.Body) if(err == nil) { var data TcodeResponse json.Unmarshal(body, &data) return data.Tcode,err } else { } } else { } return "",err } // get request to API
package main import "log" type ledger struct{} func (l *ledger) makeEntry(ID string, t string, a float64) { log.Printf("make ledger entry for account %s with %s type for amount %v", ID, t, a) }
package jpush type Audience struct { PushAudience interface{} //推送目标 AudienceInfo map[string][]string //推送标签/范围/注册id } const ( STag = "tag" //标签 STagAnd = "tag_and" //标签and SALias = "alias" //别名(暂时只使用这个) SRegistrationId = "registration_id" //注册id ) type ALias struct { Content []string } // AddAll 设置为广播 func (this *Audience) AddAll() (int, string) { this.PushAudience = "all" return 0, "" } func (this *Audience) AddAlias(userId []string) (int, string) { return this.Add(SALias, userId) } // Add 添加 // strType: 推送对象类型 tag,tag_and,alias,registration_id // return: int 0-添加成功,1-平台为all,无需添加 2-该平台已添加 3-不是三种平对之一 func (this *Audience) Add(strType string, userId []string) (int, string) { if this.PushAudience != nil { //判断是否为空,不为空,说明已有推送对象 switch this.PushAudience.(type) { case string: return 1, "广播" //广播 default: } } if this.AudienceInfo == nil { this.AudienceInfo = make(map[string][]string, 0) } var _, isExist = this.AudienceInfo[strType] if isExist { //判断是否已添加 for _, uvalue := range userId { for _, value := range this.AudienceInfo[strType] { if uvalue == value { return 2, "别名已添加!" } } } } for _, value := range userId { this.AudienceInfo[strType] = append(this.AudienceInfo[strType], value) } this.PushAudience = this.AudienceInfo return 0, "添加成功!" }
package intersect import ( "reflect" "sort" "testing" ) func Test_intersect(t *testing.T) { type args struct { nums1 []int nums2 []int } tests := []struct { name string args args want []int }{ // TODO: Add test cases. { name: "first", args: args{ nums1: []int{1, 2, 3, 4}, nums2: []int{0, 2, 4, 6}, }, want: []int{2, 4}, }, { name: "second", args: args{ nums1: []int{1, 2, 2, 4}, nums2: []int{0, 2, 2, 4}, }, want: []int{2, 2, 4}, }, { name: "third", args: args{ nums1: []int{1, 2, 3, 4}, nums2: []int{5, 6, 7, 8}, }, want: []int{}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := intersect(tt.args.nums1, tt.args.nums2) sort.Ints(got) sort.Ints(tt.want) if !reflect.DeepEqual(got, tt.want) { t.Errorf("intersect() = %v, want %v", got, tt.want) } }) } }
package main import ( "fmt" "github.com/shopspring/decimal" ) func main() { fmt.Println("decimal sample") price, err := decimal.NewFromString("136.02") if err != nil { panic(err) } quantity := decimal.NewFromInt(3) fee, _ := decimal.NewFromString(".035") taxRate, _ := decimal.NewFromString(".08875") subtotal := price.Mul(quantity) preTax := subtotal.Mul(fee.Add(decimal.NewFromFloat(1))) total := preTax.Mul(taxRate.Add(decimal.NewFromFloat(1))) fmt.Println("Subtotal:", subtotal) // Subtotal: 408.06 fmt.Println("Pre-tax:", preTax) // Pre-tax: 422.3421 fmt.Println("Taxes:", total.Sub(preTax)) // Taxes: 37.482861375 fmt.Println("Total:", total) // Total: 459.824961375 fmt.Println("Tax rate:", total.Sub(preTax).Div(preTax)) // Tax rate: 0.08875 fmt.Printf("total.String() : %s\n", total.String()) fmt.Printf("total.StringFixed(2): %s\n", total.StringFixed(2)) fmt.Printf("total.StringFixed(3): %s\n", total.StringFixed(3)) sum := decimal.NewFromInt(0) unit, err := decimal.NewFromString("0.1") if err != nil { panic(err) } var sumF float64 = 0 var unitF float64 = 0.1 for i := 0; i < 100; i++ { sum = sum.Add(unit) sumF += unitF } fmt.Printf("bigdecimal sum: %s\n", sum.String()) fmt.Println("float64 sum: ", sumF) }
package etcd import ( "context" "github.com/coreos/etcd/mvcc/mvccpb" "go.etcd.io/etcd/clientv3" "sync" "time" ) /* ETCD服务发现 */ type EtcdDiscovery struct { client *clientv3.Client services map[string]string // 注册的服务列表 lock sync.Mutex prefixName string // 服务名前缀 } /* 创建服务发现实例 */ func NewEtcdDiscovery(addrs []string, prefixName string) (*EtcdDiscovery, error) { client, err := clientv3.New(clientv3.Config{ Endpoints: addrs, DialTimeout: 5 * time.Second, }) if err != nil { return nil, err } disc := &EtcdDiscovery{ client: client, services: make(map[string]string, 0), prefixName: prefixName, } // 监听注册服务状态 err = disc.watcher(prefixName) if err != nil { return nil, err } return disc, nil } /* 获取注册的服务列表 */ func (e *EtcdDiscovery) GetServices() map[string]string { return e.services } /* 实时获取注册的服务 */ func (e *EtcdDiscovery) GetServicesNow() (map[string]string, error) { return e.get() } /* 释放资源 */ func (e *EtcdDiscovery) Destroy() (bool, error) { err := e.client.Close() if err != nil { return false, err } return true, nil } // 监听服务状态 func (e *EtcdDiscovery) watcher(prefixName string) error { // 获取注册的服务 services, err := e.get() if err != nil { return err } e.services = services go func() { for { select { case resp := <-e.client.Watch(context.Background(), prefixName, clientv3.WithPrefix()): if nil != resp.Err() { panic(resp.Err()) } for _, ev := range resp.Events { switch ev.Type { case mvccpb.PUT: e.putService(string(ev.Kv.Key), string(ev.Kv.Value)) case mvccpb.DELETE: e.removeService(string(ev.Kv.Key)) } } } } }() return nil } // 获取注册的服务 func (e *EtcdDiscovery) get() (map[string]string, error) { rsp, err := e.client.Get(context.Background(), e.prefixName, clientv3.WithPrefix()) if err != nil { return nil, err } services := make(map[string]string, 0) if rsp != nil && nil != rsp.Kvs { for _, v := range rsp.Kvs { if v != nil { services[string(v.Key)] = string(v.Value) } } } return services, nil } // 缓存服务 func (e *EtcdDiscovery) putService(key, val string) bool { e.lock.Lock() defer e.lock.Unlock() e.services[key] = val return true } // 清理服务 func (e *EtcdDiscovery) removeService(key string) bool { e.lock.Lock() defer e.lock.Unlock() delete(e.services, key) return true }
package object type ( Tag struct { ID uint String string } Tags []*Tag )
package models // //import ( // db "test/database" //) // //type Person struct { // Id int `json:"id" form:"id"` // Name string `json:"name" form:"name"` // Age int `json:"age" form:"age"` //} // //func (p *Person) AddPerson () (id int64, err error) { // rs, err := db.SqlDB.Exec("INSERT INTO test(name, age) VALUE (?, ?)", p.Name, p.Age) // if err != nil { // return // } // // id, err = rs.LastInsertId() // return //} // //func (p *Person) GetPerson () (person Person, err error) { // err = db.SqlDB.QueryRow("SELECT id,name,age FROM test WHERE id=?", p.Id).Scan(&person.Id, &person.Name, &person.Age) // // if err != nil { // return // } // return //} // //func (p *Person) GetPersons () (persons []Person, err error) { // persons = make([]Person, 0) // rows, err := db.SqlDB.Query("SELECT id,name,age FROM test") // if err != nil { // return // } // defer rows.Close() // for rows.Next(){ // var person Person // rows.Scan(&person.Id, &person.Name, &person.Age) // persons = append(persons, person) // } // if err = rows.Err(); err != nil { // return // } // return //} // //func (p *Person) ModPerson () (ra int64, err error) { // stmt, err := db.SqlDB.Prepare("UPDATE test SET name=?,age=? WHERE id=?") // defer stmt.Close() // if err != nil { // return // } // rs, err := stmt.Exec(p.Name, p.Age, p.Id) // if err != nil { // return // } // ra, err = rs.RowsAffected() // return //} // //func (p *Person) DelPerson () (ra int64, err error) { // stmt, err := db.SqlDB.Prepare("DELETE FROM test WHERE id=?") // defer stmt.Close() // if err != nil { // return // } // rs, err := stmt.Exec(p.Id) // if err != nil { // return // } // ra, err = rs.RowsAffected() // return //}
package nominetuk // Copy this file and place as credentials.go const ( Username = "Example" Password = "Example" )
// Copyright 2016 IBM Corporation // // 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 checker import ( "github.com/Sirupsen/logrus" "github.com/amalgam8/sidecar/config" "github.com/amalgam8/sidecar/router/clients" "github.com/amalgam8/sidecar/router/nginx" ) // Listener listens for events from Message Hub and updates NGINX type Listener interface { Start() error Stop() error } type listener struct { config *config.Config consumer Consumer nginx nginx.Nginx controller clients.Controller } // NewListener new Listener implementation func NewListener(config *config.Config, consumer Consumer, c clients.Controller, nginx nginx.Nginx) Listener { return &listener{ config: config, consumer: consumer, nginx: nginx, controller: c, } } // Start listens messages to arrive func (l *listener) Start() error { logrus.Info("Listening for messages") for { err := l.listenForUpdate() if err != nil { logrus.WithError(err).Error("Update failed") } } } // ListenForUpdate sleeps until an event indicating that the rules for this tenant have // changed. Once the event occurs we attempt to update our configuration. func (l *listener) listenForUpdate() error { var msgBytes []byte // Sleep until we receive an event indicating that the our rules have changed for { key, value, err := l.consumer.ReceiveEvent() msgBytes = value if err != nil { logrus.WithError(err).Error("Couldn't read from Kafka bus") return err } if key == l.config.Tenant.Token { logrus.WithFields(logrus.Fields{ "key": key, "value": string(msgBytes), }).Info("Tenant event received") break } } // Update our existing NGINX config if err := l.nginx.Update(msgBytes); err != nil { logrus.WithError(err).Error("Could not update NGINX config") return err } return nil } // Stop do any necessary cleanup func (l *listener) Stop() error { return nil }