text
stringlengths
11
4.05M
package main import ( "crypto/md5" "crypto/sha512" "encoding/base64" "encoding/xml" "fmt" "log" "os" "strings" "time" ) type PwdConfigLegacy struct { // legacy compatibility XMLName xml.Name `xml:"config"` Salt string `xml:"salt"` Site []struct { Name string `xml:"name,attr"` Url string `xml:"url,attr"` Id string `xml:"id"` Salt string `xml:"salt"` Length int `xml:"length"` pwd string } `xml:"site"` } func NewPwdConfigLegacy(filename string) (*PwdConfigLegacy, error) { r, err := os.OpenFile(filename, os.O_RDONLY, 0) if err != nil { return nil, err } defer r.Close() var config *PwdConfigLegacy if err := xml.NewDecoder(r).Decode(&config); err != nil { return nil, err } return config, nil } func (self *PwdConfigLegacy) Convert() *Engine { engine := &Engine{Configuration{time.Now().Unix(), self.Salt, nil}, make(map[string]*SiteConfig)} for i, _ := range self.Site { engine.Cache[self.Site[i].Name] = &SiteConfig{ Name: self.Site[i].Name, URL: self.Site[i].Url, Login: self.Site[i].Id, Salt: self.Site[i].Salt, Length: self.Site[i].Length, } } return engine } func (self *PwdConfigLegacy) GenPassword(idx int, pwd string) { md5Hash := md5.New() shaHash := sha512.New() pwd_salt := self.Salt md5Hash.Write([]byte(pwd + pwd_salt)) str := fmt.Sprintf("%x%s%s", md5Hash.Sum(nil), self.Site[idx].Id, self.Site[idx].Salt) shaHash.Write([]byte(str)) encLen := base64.StdEncoding.EncodedLen(len(shaHash.Sum(nil))) encBuf := make([]byte, encLen) base64.StdEncoding.Encode(encBuf, shaHash.Sum(nil)) encBuf = base64ToBase62(encBuf) length := self.Site[idx].Length self.Site[idx].pwd = string(encBuf[0:length]) } func (self *PwdConfigLegacy) GenAllPassword(password string) { for i := 0; i < len(self.Site); i++ { self.GenPassword(i, password) time.Sleep(1e7) } } func (self *PwdConfigLegacy) String() string { var s string for _, site := range self.Site { s += fmt.Sprintf(`[%s] %s %s %s `, site.Name, site.Url, site.Id, site.pwd) } return s } func (self *PwdConfigLegacy) SavePassword(filename, site_name string) { writer := os.Stdout if len(filename) > 0 { flag := os.O_WRONLY | os.O_CREATE | os.O_TRUNC file, err := os.OpenFile(filename, flag, 0666) if err != nil { log.Fatalf("Create file '%s' fail\n", filename) } defer file.Close() writer = file } if strings.HasSuffix(filename, ".csv") { for i := 0; i < len(self.Site); i++ { if site_name == "*all" || site_name == self.Site[i].Name { fmt.Fprintf(writer, `"%s","%s","%s","%s","%s"%s`, self.Site[i].Name, self.Site[i].Id, self.Site[i].pwd, self.Site[i].Url, "", "\n", ) } } } else { for i := 0; i < len(self.Site); i++ { if site_name == "*all" || site_name == self.Site[i].Name { fmt.Fprintf(writer, "%s\n", self.Site[i].Url) fmt.Fprintf(writer, " userid: %s\n", self.Site[i].Id) fmt.Fprintf(writer, " passwd: %s\n", self.Site[i].pwd) fmt.Fprintf(writer, "\n") } } } }
// Copyright (c) 2013-2014 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package base58 import ( "crypto/sha256" "errors" "sync" ) var bufPool = &sync.Pool{ New: func() interface{} { return make([]byte, 0) }, } // ErrChecksum indicates that the checksum of a check-encoded string does not verify against // the checksum. var ErrChecksum = errors.New("checksum error") // ErrInvalidFormat indicates that the check-encoded string has an invalid format. var ErrInvalidFormat = errors.New("invalid format: version and/or checksum bytes missing") // checksum: first four bytes of sha256^2 func checksum(input []byte) (cksum [4]byte) { h := sha256.Sum256(input) h2 := sha256.Sum256(h[:]) copy(cksum[:], h2[:4]) return } // CheckEncode prepends a version byte and appends a four byte checksum. func CheckEncode(input []byte, version []byte) string { b := make([]byte, 0, len(version)+len(input)+4) b = append(b, version[:]...) b = append(b, input[:]...) cksum := checksum(b) b = append(b, cksum[:]...) return Encode(b) } // CheckDecode decodes a string that was encoded with CheckEncode and verifies the checksum. // adapted to support multi-length version strings func CheckDecode(input string, vlen int, buf []byte) ([]byte, []byte, error) { decoded := Decode(input, buf) if len(decoded) < 4+vlen { return nil, nil, ErrInvalidFormat } version := decoded[0:vlen] var cksum [4]byte copy(cksum[:], decoded[len(decoded)-4:]) if checksum(decoded[:len(decoded)-4]) != cksum { return nil, nil, ErrChecksum } payload := decoded[vlen : len(decoded)-4] // result = append(result, payload...) return payload, version, nil }
package wallet import ( "encoding/hex" "testing" "time" "github.com/btcsuite/btcwallet/walletdb" "github.com/btcsuite/btcwallet/wtxmgr" "github.com/btcsuite/btcd/btcutil" ) var ( TstSerializedTx, _ = hex.DecodeString("010000000114d9ff358894c486b4ae11c2a8cf7851b1df64c53d2e511278eff17c22fb7373000000008c493046022100995447baec31ee9f6d4ec0e05cb2a44f6b817a99d5f6de167d1c75354a946410022100c9ffc23b64d770b0e01e7ff4d25fbc2f1ca8091053078a247905c39fce3760b601410458b8e267add3c1e374cf40f1de02b59213a82e1d84c2b94096e22e2f09387009c96debe1d0bcb2356ffdcf65d2a83d4b34e72c62eccd8490dbf2110167783b2bffffffff0280969800000000001976a914479ed307831d0ac19ebc5f63de7d5f1a430ddb9d88ac38bfaa00000000001976a914dadf9e3484f28b385ddeaa6c575c0c0d18e9788a88ac00000000") TstTx, _ = btcutil.NewTxFromBytes(TstSerializedTx) TstTxHash = TstTx.Hash() ) // TestLocateBirthdayBlock ensures we can properly map a block in the chain to a // timestamp. func TestLocateBirthdayBlock(t *testing.T) { t.Parallel() // We'll use test chains of 30 blocks with a duration between two // consecutive blocks being slightly greater than the largest margin // allowed by locateBirthdayBlock. Doing so lets us test the method more // effectively as there is only one block within the chain that can map // to a timestamp (this does not apply to the first and last blocks, // which can map to many timestamps beyond either end of chain). const ( numBlocks = 30 blockInterval = birthdayBlockDelta + 1 ) genesisTimestamp := chainParams.GenesisBlock.Header.Timestamp testCases := []struct { name string birthday time.Time birthdayHeight int32 }{ { name: "left-right-left-left", birthday: genesisTimestamp.Add(8 * blockInterval), birthdayHeight: 8, }, { name: "right-right-right-left", birthday: genesisTimestamp.Add(27 * blockInterval), birthdayHeight: 27, }, { name: "before start height", birthday: genesisTimestamp.Add(-blockInterval), birthdayHeight: 0, }, { name: "start height", birthday: genesisTimestamp, birthdayHeight: 0, }, { name: "end height", birthday: genesisTimestamp.Add(numBlocks * blockInterval), birthdayHeight: numBlocks - 1, }, { name: "after end height", birthday: genesisTimestamp.Add(2 * numBlocks * blockInterval), birthdayHeight: numBlocks - 1, }, } for _, testCase := range testCases { testCase := testCase success := t.Run(testCase.name, func(t *testing.T) { chainConn := createMockChainConn( chainParams.GenesisBlock, numBlocks, blockInterval, ) birthdayBlock, err := locateBirthdayBlock( chainConn, testCase.birthday, ) if err != nil { t.Fatalf("unable to locate birthday block: %v", err) } if birthdayBlock.Height != testCase.birthdayHeight { t.Fatalf("expected birthday block with height "+ "%d, got %d", testCase.birthdayHeight, birthdayBlock.Height) } }) if !success { break } } } // TestLabelTransaction tests labelling of transactions with invalid labels, // and failure to label a transaction when it already has a label. func TestLabelTransaction(t *testing.T) { t.Parallel() tests := []struct { name string // Whether the transaction should be known to the wallet. txKnown bool // Whether the test should write an existing label to disk. existingLabel bool // The overwrite parameter to call label transaction with. overwrite bool // The error we expect to be returned. expectedErr error }{ { name: "existing label, not overwrite", txKnown: true, existingLabel: true, overwrite: false, expectedErr: ErrTxLabelExists, }, { name: "existing label, overwritten", txKnown: true, existingLabel: true, overwrite: true, expectedErr: nil, }, { name: "no prexisting label, ok", txKnown: true, existingLabel: false, overwrite: false, expectedErr: nil, }, { name: "transaction unknown", txKnown: false, existingLabel: false, overwrite: false, expectedErr: ErrUnknownTransaction, }, } for _, test := range tests { test := test t.Run(test.name, func(t *testing.T) { t.Parallel() w, cleanup := testWallet(t) defer cleanup() // If the transaction should be known to the store, we // write txdetail to disk. if test.txKnown { rec, err := wtxmgr.NewTxRecord( TstSerializedTx, time.Now(), ) if err != nil { t.Fatal(err) } err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error { ns := tx.ReadWriteBucket( wtxmgrNamespaceKey, ) return w.TxStore.InsertTx( ns, rec, nil, ) }) if err != nil { t.Fatalf("could not insert tx: %v", err) } } // If we want to setup an existing label for the purpose // of the test, write one to disk. if test.existingLabel { err := w.LabelTransaction( *TstTxHash, "existing label", false, ) if err != nil { t.Fatalf("could not write label: %v", err) } } newLabel := "new label" err := w.LabelTransaction( *TstTxHash, newLabel, test.overwrite, ) if err != test.expectedErr { t.Fatalf("expected: %v, got: %v", test.expectedErr, err) } }) } }
package main import ( "fmt" "log" "github.com/alaaattya/recipy-admin-api/middlewares" "github.com/alaaattya/recipy-admin-api/requestHandlers" "github.com/gin-gonic/gin" "github.com/go-bongo/bongo" "github.com/spf13/viper" ) func main() { viper.SetConfigType("yaml") viper.SetConfigName("config") // name of config file (without extension) viper.AddConfigPath("./") err := viper.ReadInConfig() if err != nil { fmt.Println("Config file not found...") } config := &bongo.Config{ ConnectionString: viper.GetString("local.database.host"), Database: viper.GetString("local.database.dbName"), } connection, err := bongo.Connect(config) if err != nil { log.Fatal(err) } r := gin.New() r.Use(middlewares.Database(connection)) r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.GET("/recipy", requestHandlers.HandleCreateNewRecipy) r.Run(":3000") // listen and serve on 0.0.0.0:3000 }
package _264_Ugly_Number_2 func nthUglyNumber(n int) int { var ( u = make([]int, n) idx2, idx3, idx5 int k = 1 ) u[0] = 1 for k < n { u[k] = min(u[idx2]*2, u[idx3]*3, u[idx5]*5) if u[idx2]*2 == u[k] { idx2++ } if u[idx3]*3 == u[k] { idx3++ } if u[idx5]*5 == u[k] { idx5++ } k++ } return u[n-1] } func min(a, b, c int) int { var min int if a < b { min = a } else { min = b } if c < min { min = c } return min }
package robot import ( "github.com/ev3go/ev3dev" ) type Engine struct { motorLeft *ev3dev.TachoMotor motorRight *ev3dev.TachoMotor speedLeft int speedRight int speedLevel int } func (engine *Engine) Turn(correction int) { engine.speedLeft = (engine.speedLevel * engine.motorLeft.MaxSpeed() / 100) + correction engine.speedRight = (engine.speedLevel * engine.motorRight.MaxSpeed() / 100) - correction engine.Run() } func (engine *Engine) Go(direction int) { engine.speedLeft = (engine.speedLevel * engine.motorLeft.MaxSpeed() / 100) engine.speedRight = (engine.speedLevel * engine.motorRight.MaxSpeed() / 100) engine.Run() } func (engine *Engine) Run() { engine.motorLeft.SetSpeedSetpoint(engine.speedLeft).Command("run-forever") engine.motorRight.SetSpeedSetpoint(engine.speedRight).Command("run-forever") } func (engine *Engine) Stop() { engine.motorLeft.Command("stop") engine.motorRight.Command("stop") }
package main import "fmt" // 测试方法1 func test01() { fmt.Println("test01...") } // 测试方法2 func test02() { // 显示调用panic函数 panic("test02方法:发生panic异常...") } // 测试方法3 func test03() { fmt.Println("test03...") } // 程序当中,有些异常是致命的异常,出现之后会导致程序的中止运行 // 在go语言当中,panic异常,就是会导致程序的中止运行 func main() { // 调用测试方法 test01() test02() test03() // 结果为: // test01... // panic: test02方法:发生panic异常... // goroutine 1 [running]: // main.test02() // D:/Program/go/workspace_1.9.2/src/panic.go:13 +0x40 // main.main() // D:/Program/go/workspace_1.9.2/src/panic.go:27 +0x2c // exit status 2 // 可以发现当发生panic异常后,程序中止了运行 // 当数组发生下标越界时,同样是会报panic异常,只不过是内部封装好了的panic异常 arrs := [3]int{1, 2, 3} fmt.Println("arrs[3] = ", arrs[3]) // 报如下错误 // .\panic.go:45:32: invalid array index 3 (out of bounds for 3-element array) }
/* * @lc app=leetcode.cn id=213 lang=golang * * [213] 打家劫舍 II */ // @lc code=start package main import "fmt" func rob(nums []int) int { if len(nums) == 0 { return 0 } if len(nums) == 1 { return nums[0] } if len(nums) == 2 { return max(nums[0], nums[1]) } return max(myRob(nums[1:]), myRob(nums[0:len(nums)-1])) } func myRob(nums []int) int { // fmt.Println(nums) dp := make([]int, len(nums)) dp[0] = nums[0] dp[1] = max(nums[0], nums[1]) for i := 2; i < len(nums); i++ { dp[i] = max(dp[i-2] + nums[i], dp[i-1]) } return dp[len(nums)-1] } func max(x, y int) int { if x > y { return x } return y } // @lc code=end func main() { a := []int{2,3,2} // fmt.Printf("%d, %d\n", a, rob(a)) // a = []int{2,7,9,3,1} // fmt.Printf("%d, %d\n", a, rob(a)) a = []int{0,0} fmt.Printf("%d, %d\n", a, rob(a)) }
package teamusers import ( "time" ) const ( // TeamsCreateTeamUserEndpoint is a string representation of the current endpoint for creating team user TeamsCreateTeamUserEndpoint = "v1/teamUsers/createTeamUser" // TeamsUpdateTeamUserEndpoint is a string representation of the current endpoint for updating team user TeamsUpdateTeamUserEndpoint = "v1/teamUsers/updateTeamUser" // TeamsDeleteTeamUserEndpoint is a string representation of the current endpoint for deleting team user TeamsDeleteTeamUserEndpoint = "v1/teamUsers/deleteTeamUser" // TeamsGetTeamUserEndpoint is a string representation of the current endpoint for getting team users TeamsGetTeamUserEndpoint = "v1/teamUsers/getTeamUsers" ) // TeamUser is a representation of an Ion Channel Team User relationship within the system type TeamUser struct { ID string `json:"id"` TeamID string `json:"team_id"` UserID string `json:"user_id"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` DeletedAt time.Time `json:"deleted_at"` Status string `json:"status"` Role string `json:"role"` } // TeamUserRole contains information about a user's role on a team. type TeamUserRole struct { ID string `json:"id"` TeamID string `json:"team_id"` UserID string `json:"user_id"` Role string `json:"role"` Status string `json:"status"` Username string `json:"username"` Email string `json:"email"` LastActiveAt time.Time `json:"last_active_at"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` InvitedAt time.Time `json:"invited_at"` }
/* Taking each four digit number of an array in turn, return the number that you are on when all of the digits 0-9 have been discovered. If not all of the digits can be found, return "Missing digits!". Examples findAllDigits([5175, 4538, 2926, 5057, 6401, 4376, 2280, 6137, 8798, 9083]) ➞ 5057 // digits found: 517- 4-38 29-6 -0 findAllDigits([5719, 7218, 3989, 8161, 2676, 3847, 6896, 3370, 2363, 1381]) ➞ 3370 // digits found: 5719 -2-8 3--- --6- ---- --4- ---- ---0 findAllDigits([4883, 3876, 7769, 9846, 9546, 9634, 9696, 2832, 6822, 6868]) ➞ "Missing digits!" // digits found: 48-3 --76 ---9 ---- -5-- ---- ---- 2--- // 0 and 1 are missing Notes The digits can be discovered in any order. */ package main func main() { test(digits([]int{5175, 4538, 2926, 5057, 6401, 4376, 2280, 6137, 8798, 9083}), 5057) test(digits([]int{5719, 7218, 3989, 8161, 2676, 3847, 6896, 3370, 2363, 1381}), 3370) test(digits([]int{4883, 3876, 7769, 9846, 9546, 9634, 9696, 2832, 6822, 6868}), "Missing digits!") test(digits([]int{3129, 7689, 7449, 4389, 5855, 9670, 9245, 1291, 7367, 1810}), 9670) test(digits([]int{2758, 3737, 3349, 5118, 7004, 6106, 8868, 6687, 2510, 8911}), 6106) test(digits([]int{5343, 6743, 2922, 2423, 7050, 5116, 3992, 2707, 2435, 5251}), "Missing digits!") test(digits([]int{4169, 4511, 1498, 6945, 7959, 2666, 7872, 3217, 5408, 8662}), 5408) test(digits([]int{7985, 7130, 4625, 7392, 4933, 7163, 7130, 2145, 1596, 6188}), 4625) test(digits([]int{4823, 1049, 9555, 9466, 2191, 9316, 1105, 4489, 8318, 7081}), 7081) test(digits([]int{9827, 4405, 6317, 6086, 8091, 7800, 8365, 2544, 3402, 7248}), 6317) test(digits([]int{2227, 7262, 9322, 8967, 4807, 8708, 3317, 6543, 9522, 7106}), 6543) test(digits([]int{8452, 7326, 6786, 1893, 6546, 8714, 6699, 1361, 4891, 9797}), "Missing digits!") test(digits([]int{2627, 1146, 3964, 6280, 9759, 6188, 8917, 9375, 4012, 4217}), 9759) test(digits([]int{1291, 6903, 5887, 8914, 3906, 1465, 8452, 4909, 4143, 6921}), 8914) test(digits([]int{7433, 8245, 9603, 1446, 8158, 8756, 5066, 4996, 5233, 2856}), 1446) test(digits([]int{4661, 1207, 8411, 2010, 2092, 2441, 7885, 3810, 7433, 2034}), 3810) test(digits([]int{9429, 6519, 3795, 7924, 3042, 3425, 1371, 7194, 7680, 9007}), 7680) test(digits([]int{6621, 9480, 8239, 4542, 9772, 5108, 6872, 5057, 9477, 3602}), 9772) test(digits([]int{9701, 3828, 7183, 2727, 5212, 6721, 5413, 2351, 4237, 8207}), 5413) test(digits([]int{3914, 9923, 8187, 1657, 4271, 9538, 3759, 4543, 3438, 1943}), "Missing digits!") test(digits([]int{6572, 3752, 9661, 7017, 8139, 2596, 3054, 2730, 1350, 2483}), 3054) test(digits([]int{2102, 4519, 4229, 8347, 2019, 7342, 7181, 8977, 1339, 9988}), "Missing digits!") test(digits([]int{4467, 2849, 5706, 7330, 9488, 2529, 8837, 2256, 3975, 7311}), 7311) } func test(x, y interface{}) { assert(x == y) } func assert(x bool) { if !x { panic("assertion failed") } } func digits(a []int) interface{} { var h [10]int c := 0 for i, n := range a { if n < 0 { n = -n } for { j := n % 10 if h[j]++; h[j] == 1 { if c++; c >= len(h) { return a[i] } } if n /= 10; n == 0 { break } } } return "Missing digits!" }
package main import ( "bytes" "context" "fmt" "io/ioutil" "log" "os" "path" "time" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/gridfs" "go.mongodb.org/mongo-driver/mongo/options" ) func InitiateMongoClient() *mongo.Client { var err error var client *mongo.Client uri := "mongodb://localhost:27017" opts := options.Client() opts.ApplyURI(uri) opts.SetMaxPoolSize(5) if client, err = mongo.Connect(context.Background(), opts); err != nil { fmt.Println(err.Error()) } return client } func UploadFile(file, filename string) { data, err := ioutil.ReadFile(file) if err != nil { log.Fatal(err) } conn := InitiateMongoClient() bucket, err := gridfs.NewBucket( conn.Database("myfiles"), ) if err != nil { log.Fatal(err) os.Exit(1) } uploadStream, err := bucket.OpenUploadStream( filename, ) if err != nil { fmt.Println(err) os.Exit(1) } defer uploadStream.Close() fileSize, err := uploadStream.Write(data) if err != nil { log.Fatal(err) os.Exit(1) } log.Printf("Write file to DB was successful. File size: %d\n", fileSize) } func DownloadFile(fileName string) { conn := InitiateMongoClient() // For CRUD operations, here is an example db := conn.Database("myfiles") fsFiles := db.Collection("fs.files") ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) var results bson.M err := fsFiles.FindOne(ctx, bson.M{}).Decode(&results) if err != nil { log.Fatal(err) } // you can print out the results fmt.Println(results) bucket, _ := gridfs.NewBucket( db, ) var buf bytes.Buffer dStream, err := bucket.DownloadToStreamByName(fileName, &buf) if err != nil { log.Fatal(err) } fmt.Printf("File size to download: %v\n", dStream) ioutil.WriteFile(fileName, buf.Bytes(), 0600) } func main() { // Get os.Args values file := os.Args[1] //os.Args[1] = testfile.zip filename := path.Base(file) UploadFile(file, filename) // Uncomment the below line and comment the UploadFile above this line to download the file //DownloadFile(filename) }
package sort // CountSort 计数排序 // maxNumber 最大数,通过 MaxNumber 获取 func CountSort(arr *[]int, maxNumber int) { // 额外数组空间 ext := make([]int, maxNumber+1) // 遍历数组,开始计数 for _, v := range *arr { ext[v]++ } // 排序 var arrIdx int for i, v := range ext { // 如果不为0则存在arr中数i,切共v个i for v > 0 { (*arr)[arrIdx] = i arrIdx++ v-- } } } // MaxNumber 最大数组 func MaxNumber(arr []int) int { var tmp = arr[0] for _, v := range arr { if tmp < v { tmp = v } } return tmp }
// Copyright 2016 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 main // Event is a report of an event somewhere in the cluster. type Event struct { ApiVersion string `json:"apiVersion,omitempty"` Count int64 `json:"count,omitempty"` FirstTimestamp string `json:"firstTimestamp"` LastTimestamp string `json:"lastTimestamp"` InvolvedObject ObjectReference `json:"involvedObject"` Kind string `json:"kind,omitempty"` Message string `json:"message,omitempty"` Metadata Metadata `json:"metadata"` Reason string `json:"reason,omitempty"` Source EventSource `json:"source,omitempty"` Type string `json:"type,omitempty"` } // EventSource contains information for an event. type EventSource struct { Component string `json:"component,omitempty"` Host string `json:"host,omitempty"` } // ObjectReference contains enough information to let you inspect or modify // the referred object. type ObjectReference struct { ApiVersion string `json:"apiVersion,omitempty"` Kind string `json:"kind,omitempty"` Name string `json:"name,omitempty"` Namespace string `json:"namespace,omitempty"` Uid string `json:"uid"` } // PodList is a list of Pods. type PodList struct { ApiVersion string `json:"apiVersion"` Kind string `json:"kind"` Metadata ListMetadata `json:"metadata"` Items []Pod `json:"items"` } type PodWatchEvent struct { Type string `json:"type"` Object Pod `json:"object"` } type Pod struct { Kind string `json:"kind,omitempty"` Metadata Metadata `json:"metadata"` Spec PodSpec `json:"spec"` } type PodSpec struct { NodeName string `json:"nodeName"` Containers []Container `json:"containers"` } type Container struct { Name string `json:"name"` Resources ResourceRequirements `json:"resources"` } type ResourceRequirements struct { Limits ResourceList `json:"limits"` Requests ResourceList `json:"requests"` } type ResourceList map[string]string type Binding struct { ApiVersion string `json:"apiVersion"` Kind string `json:"kind"` Target Target `json:"target"` Metadata Metadata `json:"metadata"` } type Target struct { ApiVersion string `json:"apiVersion"` Kind string `json:"kind"` Name string `json:"name"` } type NodeList struct { ApiVersion string `json:"apiVersion"` Kind string `json:"kind"` Items []Node } type Node struct { Metadata Metadata `json:"metadata"` Status NodeStatus `json:"status"` } type NodeStatus struct { Capacity ResourceList `json:"capacity"` Allocatable ResourceList `json:"allocatable"` } type ListMetadata struct { ResourceVersion string `json:"resourceVersion"` } type Metadata struct { Name string `json:"name"` GenerateName string `json:"generateName"` ResourceVersion string `json:"resourceVersion"` Labels map[string]string `json:"labels"` Annotations map[string]string `json:"annotations"` Uid string `json:"uid"` }
package application import ( "errors" "github.com/charly3pins/eShop/domain" "github.com/charly3pins/eShop/domain/base" "github.com/gofrs/uuid" ) var ( ErrInvalidUserID = errors.New("invalid user id") ErrInvalidOrderID = errors.New("invalid order id") ErrOrderWithEmptyProducts = errors.New("order cannot have empty products") ErrOrderAlreadyProcessed = errors.New("order already processed") ) type OrderService struct { OrderRepository domain.OrderRepository } type ProductRequest struct { ID string Name string UnitPrice int Currency string Quantity int } type AddProductsToOrderRequest struct { UserID string OrderID string Products []ProductRequest } func (os OrderService) AddProductsToOrder(req AddProductsToOrderRequest) (domain.Order, error) { var o domain.Order reqUserID, err := uuid.FromString(req.UserID) if err != nil { return o, ErrInvalidUserID } if len(req.Products) == 0 { return o, ErrOrderWithEmptyProducts } if req.OrderID == "" { o, err = createOrder(os, req, reqUserID) } else { o, err = updateOrder(os, req) } return o, nil } func createOrder(os OrderService, req AddProductsToOrderRequest, reqUserID uuid.UUID) (domain.Order, error) { o := domain.NewOrder( os.OrderRepository.NextIdentity(), reqUserID, ) addProducts(&o, req.Products, os) if err := o.Validate(); err != nil { return o, err } oDB, err := os.OrderRepository.Create(o) if err != nil { return o, err } return oDB, nil } func updateOrder(os OrderService, req AddProductsToOrderRequest) (domain.Order, error) { var o domain.Order reqOrderID, err := uuid.FromString(req.OrderID) if err == nil { id := base.Identity{ID: uuid.NullUUID{UUID: reqOrderID, Valid: true}} oDB, err := os.OrderRepository.GetOrderByID(id) if err != nil { return o, err } if oDB == nil { return o, ErrInvalidOrderID } if oDB.Processed { return o, ErrOrderAlreadyProcessed } o = *oDB } addProducts(&o, req.Products, os) if err := o.Validate(); err != nil { return o, err } o, err = os.OrderRepository.Update(o) if err != nil { return o, err } return o, nil } func addProducts(o *domain.Order, products []ProductRequest, os OrderService) error { for _, p := range products { var id base.Identity if p.ID == "" { id = os.OrderRepository.NextIdentity() } else { pUUID, err := uuid.FromString(p.ID) if err != nil { return err } id.ID = uuid.NullUUID{UUID: pUUID, Valid: true} } err := o.AddProduct(id, p.Name, p.Currency, p.UnitPrice, p.Quantity) if err != nil { return err } } return nil }
package controller import ( "fmt" "sync" "time" // coreinformer "k8s.io/client-go/informers/core/v1" "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/util/wait" // "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" // "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/kubernetes" corelister "k8s.io/client-go/listers/core/v1" cache "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/workqueue" "k8s.io/klog" ) type VolumeController struct { cli *kubernetes.Clientset podLister corelister.PodLister podSynced cache.InformerSynced queue workqueue.RateLimitingInterface podToVolumes map[string]*volumeStatCalculator lock sync.Mutex } func NewVolumeController( cli *kubernetes.Clientset, podInformer cache.SharedIndexInformer, ) (*VolumeController, error) { vc := &VolumeController{ cli: cli, queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "Pods"), podToVolumes: make(map[string]*volumeStatCalculator), } vc.podLister = corelister.NewPodLister(podInformer.GetIndexer()) vc.podSynced = podInformer.HasSynced podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: vc.add, UpdateFunc: vc.update, DeleteFunc: vc.delete, }) return vc, nil } func (c *VolumeController) Run(stop <-chan struct{}) error { defer c.queue.ShutDown() klog.Infof("starting volume controller") klog.Infof("waiting for informer caches to sync") if ok := cache.WaitForCacheSync(stop, c.podSynced); !ok { return fmt.Errorf("failed to wait for caches to sync") } klog.Infof("starting workers") for i := 0; i < 2; i++ { go wait.Until(c.runWorker, time.Second, stop) } klog.Infof("started workers") <-stop klog.Infof("shuting down workers") return nil } func (c *VolumeController) runWorker() { for c.processNextWorkItem() { } } func (c *VolumeController) processNextWorkItem() bool { obj, shutdown := c.queue.Get() if shutdown { return false } // We wrap this block in a func so we can defer c.workqueue.Done. err := func(obj interface{}) error { // We call Done here so the workqueue knows we have finished // processing this item. We also must remember to call Forget if we // do not want this work item being re-queued. For example, we do // not call Forget if a transient error occurs, instead the item is // put back on the workqueue and attempted again after a back-off // period. defer c.queue.Done(obj) var key string var ok bool // We expect strings to come off the workqueue. These are of the // form namespace/name. We do this as the delayed nature of the // workqueue means the items in the informer cache may actually be // more up to date that when the item was initially put onto the // workqueue. if key, ok = obj.(string); !ok { // As the item in the workqueue is actually invalid, we call // Forget here else we'd go into a loop of attempting to // process a work item that is invalid. c.queue.Forget(obj) utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj)) return nil } // Run the syncHandler, passing it the namespace/name string of the // Foo resource to be synced. if err := c.syncHandler(key); err != nil { // Put the item back on the workqueue to handle any transient errors. c.queue.AddRateLimited(key) return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error()) } // Finally, if no error occurs we Forget this item so it does not // get queued again until another change happens. c.queue.Forget(obj) klog.Infof("Successfully synced '%s'", key) return nil }(obj) if err != nil { utilruntime.HandleError(err) return true } return true } func (c *VolumeController) syncHandler(key string) error { namespace, name, err := cache.SplitMetaNamespaceKey(key) if err != nil { utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key)) return nil } isDeletion := false pod, err := c.podLister.Pods(namespace).Get(name) if err != nil { if errors.IsNotFound(err) { // utilruntime.HandleError(fmt.Errorf("pod '%s' in work queue no longer exists", key)) klog.Infof("pod %s/%s is deleted", namespace, name) isDeletion = true } else { return err } } if isDeletion { if _, ok := c.podToVolumes[key]; ok { klog.Infof("delete pod %s/%s from volume controller", namespace, name) if err = c.deletePod(key); err != nil { klog.Errorf("delete pod %s/%s from volume controller failed, err: %v", namespace, name, err) return err } klog.Infof("delete pod %s/%s from volume controller succeeded", namespace, name) } return nil } err = c.addPod(pod, key) if err != nil { klog.Errorf("add pod %s/%s into volume controller failed, err: %v", pod.Namespace, pod.Name, err) return err } return nil } func (c *VolumeController) addPod(pod *v1.Pod, key string) error { if c.podExists(key) { klog.Infof("pod %s/%s has already been added into controller", pod.Namespace, pod.Name) return nil } provider, err := newVolumesMetricProvider(c.cli, pod) if err != nil { klog.Errorf("new volumeMetricProvider for pod [%s/%s] failed, err: %v", pod.Namespace, pod.Name, err) return err } calcultor := newVolumeStatCalculator(provider, time.Second, pod) klog.Infof("pod %s/%s is successfully added into controller", pod.Namespace, pod.Name) c.lock.Lock() defer c.lock.Unlock() if _, ok := c.podToVolumes[key]; !ok { c.podToVolumes[key] = calcultor.StartOnce() } return nil } func (c *VolumeController) deletePod(key string) error { if !c.podExists(key) { klog.Infof("pod [%s] is no longer in the controller", key) return nil } klog.Infof("pod [%s] is deleted from controller", key) c.lock.Lock() defer c.lock.Unlock() c.podToVolumes[key].StopOnce() delete(c.podToVolumes, key) return nil } func (c *VolumeController) podExists(key string) bool { c.lock.Lock() defer c.lock.Unlock() if _, ok := c.podToVolumes[key]; ok { return true } else { return false } } func (c *VolumeController) add(obj interface{}) { var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { // utilruntime.HandleError(err) klog.Error(err) return } klog.Infof("[ Add ] action: [%s]", key) c.queue.Add(key) } func (c *VolumeController) update(oldObj, newObj interface{}) { var key string var err error if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { // utilruntime.HandleError(err) klog.Error(err) return } // klog.Infof("[ Update ] action: [%s]", key) c.queue.Add(key) } func (c *VolumeController) delete(obj interface{}) { var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { // utilruntime.HandleError(err) klog.Error(err) return } klog.Infof("[ Delete ] action: [%s]", key) c.queue.Add(key) }
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package expression import ( "fmt" "testing" "github.com/pingcap/tidb/parser/ast" "github.com/pingcap/tidb/parser/model" "github.com/pingcap/tidb/parser/mysql" "github.com/pingcap/tidb/types" "github.com/pingcap/tidb/util/chunk" "github.com/pingcap/tidb/util/mock" "github.com/stretchr/testify/require" ) func TestColumn(t *testing.T) { ctx := mock.NewContext() col := &Column{RetType: types.NewFieldType(mysql.TypeLonglong), UniqueID: 1} require.True(t, col.Equal(nil, col)) require.False(t, col.Equal(nil, &Column{})) require.False(t, col.IsCorrelated()) require.True(t, col.Equal(nil, col.Decorrelate(nil))) marshal, err := col.MarshalJSON() require.NoError(t, err) require.EqualValues(t, []byte{0x22, 0x43, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x23, 0x31, 0x22}, marshal) intDatum := types.NewIntDatum(1) corCol := &CorrelatedColumn{Column: *col, Data: &intDatum} invalidCorCol := &CorrelatedColumn{Column: Column{}} schema := NewSchema(&Column{UniqueID: 1}) require.True(t, corCol.Equal(nil, corCol)) require.False(t, corCol.Equal(nil, invalidCorCol)) require.True(t, corCol.IsCorrelated()) require.False(t, corCol.ConstItem(nil)) require.True(t, corCol.Decorrelate(schema).Equal(nil, col)) require.True(t, invalidCorCol.Decorrelate(schema).Equal(nil, invalidCorCol)) intCorCol := &CorrelatedColumn{Column: Column{RetType: types.NewFieldType(mysql.TypeLonglong)}, Data: &intDatum} intVal, isNull, err := intCorCol.EvalInt(ctx, chunk.Row{}) require.Equal(t, int64(1), intVal) require.False(t, isNull) require.NoError(t, err) realDatum := types.NewFloat64Datum(1.2) realCorCol := &CorrelatedColumn{Column: Column{RetType: types.NewFieldType(mysql.TypeDouble)}, Data: &realDatum} realVal, isNull, err := realCorCol.EvalReal(ctx, chunk.Row{}) require.Equal(t, float64(1.2), realVal) require.False(t, isNull) require.NoError(t, err) decimalDatum := types.NewDecimalDatum(types.NewDecFromStringForTest("1.2")) decimalCorCol := &CorrelatedColumn{Column: Column{RetType: types.NewFieldType(mysql.TypeNewDecimal)}, Data: &decimalDatum} decVal, isNull, err := decimalCorCol.EvalDecimal(ctx, chunk.Row{}) require.Zero(t, decVal.Compare(types.NewDecFromStringForTest("1.2"))) require.False(t, isNull) require.NoError(t, err) stringDatum := types.NewStringDatum("abc") stringCorCol := &CorrelatedColumn{Column: Column{RetType: types.NewFieldType(mysql.TypeVarchar)}, Data: &stringDatum} strVal, isNull, err := stringCorCol.EvalString(ctx, chunk.Row{}) require.Equal(t, "abc", strVal) require.False(t, isNull) require.NoError(t, err) durationCorCol := &CorrelatedColumn{Column: Column{RetType: types.NewFieldType(mysql.TypeDuration)}, Data: &durationDatum} durationVal, isNull, err := durationCorCol.EvalDuration(ctx, chunk.Row{}) require.Zero(t, durationVal.Compare(duration)) require.False(t, isNull) require.NoError(t, err) timeDatum := types.NewTimeDatum(tm) timeCorCol := &CorrelatedColumn{Column: Column{RetType: types.NewFieldType(mysql.TypeDatetime)}, Data: &timeDatum} timeVal, isNull, err := timeCorCol.EvalTime(ctx, chunk.Row{}) require.Zero(t, timeVal.Compare(tm)) require.False(t, isNull) require.NoError(t, err) } func TestColumnHashCode(t *testing.T) { col1 := &Column{ UniqueID: 12, } require.EqualValues(t, []byte{0x1, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xc}, col1.HashCode(nil)) col2 := &Column{ UniqueID: 2, } require.EqualValues(t, []byte{0x1, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2}, col2.HashCode(nil)) } func TestColumn2Expr(t *testing.T) { cols := make([]*Column, 0, 5) for i := 0; i < 5; i++ { cols = append(cols, &Column{UniqueID: int64(i)}) } exprs := Column2Exprs(cols) for i := range exprs { require.True(t, exprs[i].Equal(nil, cols[i])) } } func TestColInfo2Col(t *testing.T) { col0, col1 := &Column{ID: 0}, &Column{ID: 1} cols := []*Column{col0, col1} colInfo := &model.ColumnInfo{ID: 0} res := ColInfo2Col(cols, colInfo) require.True(t, res.Equal(nil, col1)) colInfo.ID = 3 res = ColInfo2Col(cols, colInfo) require.Nil(t, res) } func TestIndexInfo2Cols(t *testing.T) { col0 := &Column{UniqueID: 0, ID: 0, RetType: types.NewFieldType(mysql.TypeLonglong)} col1 := &Column{UniqueID: 1, ID: 1, RetType: types.NewFieldType(mysql.TypeLonglong)} colInfo0 := &model.ColumnInfo{ID: 0, Name: model.NewCIStr("0")} colInfo1 := &model.ColumnInfo{ID: 1, Name: model.NewCIStr("1")} indexCol0, indexCol1 := &model.IndexColumn{Name: model.NewCIStr("0")}, &model.IndexColumn{Name: model.NewCIStr("1")} indexInfo := &model.IndexInfo{Columns: []*model.IndexColumn{indexCol0, indexCol1}} cols := []*Column{col0} colInfos := []*model.ColumnInfo{colInfo0} resCols, lengths := IndexInfo2PrefixCols(colInfos, cols, indexInfo) require.Len(t, resCols, 1) require.Len(t, lengths, 1) require.True(t, resCols[0].Equal(nil, col0)) cols = []*Column{col1} colInfos = []*model.ColumnInfo{colInfo1} resCols, lengths = IndexInfo2PrefixCols(colInfos, cols, indexInfo) require.Len(t, resCols, 0) require.Len(t, lengths, 0) cols = []*Column{col0, col1} colInfos = []*model.ColumnInfo{colInfo0, colInfo1} resCols, lengths = IndexInfo2PrefixCols(colInfos, cols, indexInfo) require.Len(t, resCols, 2) require.Len(t, lengths, 2) require.True(t, resCols[0].Equal(nil, col0)) require.True(t, resCols[1].Equal(nil, col1)) } func TestColHybird(t *testing.T) { ctx := mock.NewContext() // bit ft := types.NewFieldType(mysql.TypeBit) col := &Column{RetType: ft, Index: 0} input := chunk.New([]*types.FieldType{ft}, 1024, 1024) for i := 0; i < 1024; i++ { num, err := types.ParseBitStr(fmt.Sprintf("0b%b", i)) require.NoError(t, err) input.AppendBytes(0, num) } result := chunk.NewColumn(types.NewFieldType(mysql.TypeLonglong), 1024) require.Nil(t, col.VecEvalInt(ctx, input, result)) it := chunk.NewIterator4Chunk(input) for row, i := it.Begin(), 0; row != it.End(); row, i = it.Next(), i+1 { v, _, err := col.EvalInt(ctx, row) require.NoError(t, err) require.Equal(t, result.GetInt64(i), v) } // use a container which has the different field type with bit result = chunk.NewColumn(types.NewFieldType(mysql.TypeString), 1024) require.Nil(t, col.VecEvalInt(ctx, input, result)) for row, i := it.Begin(), 0; row != it.End(); row, i = it.Next(), i+1 { v, _, err := col.EvalInt(ctx, row) require.NoError(t, err) require.Equal(t, result.GetInt64(i), v) } // enum ft = types.NewFieldType(mysql.TypeEnum) col.RetType = ft input = chunk.New([]*types.FieldType{ft}, 1024, 1024) for i := 0; i < 1024; i++ { input.AppendEnum(0, types.Enum{Name: fmt.Sprintf("%v", i), Value: uint64(i)}) } result = chunk.NewColumn(types.NewFieldType(mysql.TypeString), 1024) require.Nil(t, col.VecEvalString(ctx, input, result)) it = chunk.NewIterator4Chunk(input) for row, i := it.Begin(), 0; row != it.End(); row, i = it.Next(), i+1 { v, _, err := col.EvalString(ctx, row) require.NoError(t, err) require.Equal(t, result.GetString(i), v) } // set ft = types.NewFieldType(mysql.TypeSet) col.RetType = ft input = chunk.New([]*types.FieldType{ft}, 1024, 1024) for i := 0; i < 1024; i++ { input.AppendSet(0, types.Set{Name: fmt.Sprintf("%v", i), Value: uint64(i)}) } result = chunk.NewColumn(types.NewFieldType(mysql.TypeString), 1024) require.Nil(t, col.VecEvalString(ctx, input, result)) it = chunk.NewIterator4Chunk(input) for row, i := it.Begin(), 0; row != it.End(); row, i = it.Next(), i+1 { v, _, err := col.EvalString(ctx, row) require.NoError(t, err) require.Equal(t, result.GetString(i), v) } } func TestInColumnArray(t *testing.T) { // normal case, col is in column array col0, col1 := &Column{ID: 0, UniqueID: 0}, &Column{ID: 1, UniqueID: 1} cols := []*Column{col0, col1} require.True(t, col0.InColumnArray(cols)) // abnormal case, col is not in column array require.False(t, col0.InColumnArray([]*Column{col1})) // abnormal case, input is nil require.False(t, col0.InColumnArray(nil)) } func TestGcColumnExprIsTidbShard(t *testing.T) { ctx := mock.NewContext() // abnormal case // nil, not tidb_shard require.False(t, GcColumnExprIsTidbShard(nil)) // `a = 1`, not tidb_shard ft := types.NewFieldType(mysql.TypeLonglong) col := &Column{RetType: ft, Index: 0} d1 := types.NewDatum(1) con := &Constant{Value: d1, RetType: ft} expr := NewFunctionInternal(ctx, ast.EQ, ft, col, con) require.False(t, GcColumnExprIsTidbShard(expr)) // normal case // tidb_shard(a) = 1 shardExpr := NewFunctionInternal(ctx, ast.TiDBShard, ft, col) require.True(t, GcColumnExprIsTidbShard(shardExpr)) }
package etcd import ( "sync" "context" "comm/registry" "github.com/coreos/etcd/client" ) type etcdRegistry struct { kapi client.KeysAPI nodes map[string]*registry.Service name string tag string sync.Mutex } func (r *etcdRegistry) Init() error { } func (r *etcdRegistry) Register(service *registry.Service, opts *registry.RegisterOptions) error { if len(s.Nodes) == 0 { return errors.New("Require at least one node") } var options registry.RegisterOptions for _, o := range opts { o(&options) } service := &registry.Service{ Name: s.Name, Version: s.Version, Metadata: s.Metadata, Endpoints: s.Endpoints, } ctx, cancel := context.WithTimeout(context.Background(), e.options.Timeout) defer cancel() _, err := e.client.Set(ctx, servicePath(s.Name), "", &etcd.SetOptions{PrevExist: etcd.PrevIgnore, Dir: true}) if err != nil && !strings.HasPrefix(err.Error(), "102: Not a file") { return err } for _, node := range s.Nodes { service.Nodes = []*registry.Node{node} _, err := e.client.Set(ctx, nodePath(service.Name, node.Id), encode(service), &etcd.SetOptions{TTL: options.TTL}) if err != nil { return err } } return nil } func (r *etcdRegistry) UnRegister(service *Service) error { } func (r *etcdRegistry) GetService(name string) *Service { } func (r *etcdRegistry) ListService() []*Service { } func (r *etcdRegistry) Watch(opts *WatchOptions) error { watcher := r.kapi.Watcher(r.tag, &client.WatcherOptions{ Recursive: true, }) for { resp, err := watcher.Next(context.Background()) if err != nil { log.Println(err) m.active = false continue } m.active = true switch resp.Action { case "set", "update": m.addNode(resp.Node.Key, resp.Node.Value) break case "expire", "delete": m.delNode(resp.Node.Key) break default: log.Println("watchme!!!", "resp ->", resp) } } }
package backend_model import "2021/yunsongcailu/yunsong_server/web/web_model" type BackendMenuModel struct { Id int64 MenuTitle string `xorm:"varchar(30)" json:"menu_title"` MenuIcon string `xorm:"varchar(50)" json:"menu_icon"` MenuSort int `xorm:"int" json:"menu_sort"` MenuPath string `xorm:"varchar(30)" json:"menu_path"` } type BackendCategoryModel struct { Id int64 MenuId int64 `xorm:"int index" json:"menu_id"` CategoryTitle string `xorm:"varchar(30)" json:"category_title"` CategoryIcon string `xorm:"varchar(50)" json:"category_icon"` CategorySort int `xorm:"int" json:"category_sort"` CategoryPath string `xorm:"varchar(50)" json:"category_path"` } type BackendMenuListModel struct { Menu BackendMenuModel MenuCategory []BackendCategoryModel } type WebMenuListModel struct { WebMenu web_model.MenuModel WebMenuCategories []web_model.CategoryModel }
package rest import ( "fmt" "net/url" "github.com/jinmukeji/jiujiantang-services/pkg/rest" proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1" "github.com/kataras/iris/v12" ) // SubmitRemarkReq 提交分析报告备注的 Request type SubmitRemarkReq struct { Remark string `json:"remark"` } // SubmitRemark 提交分析报告备注 func (h *handler) SubmitRemark(ctx iris.Context) { // url params recordID, err := ctx.Params().GetInt("record_id") if err != nil { writeError(ctx, wrapError(ErrInvalidValue, "", err), false) return } // Session session, err := h.getSession(ctx) // TODO: session 授权判断应该封装的 wrapper 之中处理 if err != nil || !session.Authorized || session.IsExpired { path := fmt.Sprintf("%s/app.html#/analysisreport?record_id=%d", h.WxH5ServerBase, recordID) redirectURL := fmt.Sprintf("%s/wx/oauth?redirect=%s", h.WxCallbackServerBase, url.QueryEscape(path)) writeSessionErrorJSON(ctx, redirectURL, err) return } // build rpc request req := new(proto.SubmitRemarkRequest) req.RecordId = int32(recordID) var remark SubmitRemarkReq err = ctx.ReadJSON(&remark) if err != nil { writeError(ctx, wrapError(ErrParsingRequestFailed, "", err), false) return } req.Remark = remark.Remark _, errResp := h.rpcSvc.SubmitRemark(newRPCContext(ctx), req) if errResp != nil { writeError(ctx, wrapError(ErrRPCInternal, "", errResp), false) return } rest.WriteOkJSON(ctx, nil) }
package ch05 import "errors" var errFindFirstRepeated = errors.New("not found") // Given a list of n elements, find the first repeated element func FindFirstRepeated(in []int) (int, error) { hmap := make(map[int]bool) for _, val := range in { if hmap[val] == true { return val, nil } else { hmap[val] = true } } return 0, errFindFirstRepeated }
package goteleport import ( "fmt" "github.com/parnurzeal/gorequest" "log" "strconv" "net/http" "io/ioutil" "encoding/json" ) func (t *Teleporter) clientListenForOutboundMessageBuffer(){ for { v, ok := <- t.out if !ok { continue } b, err := json.Marshal(v) if err != nil { log.Println(err) } m := Message{ MType:DATA, Payload:b, } url := fmt.Sprintf("http://%s", t.master) _, _, errs := gorequest.New().Post(url).SendStruct(m).End() if errs != nil { log.Println(errs) fmt.Println(errs) } } } func (t *Teleporter) clientListenForInboundMessageBuffer(){ http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { return } var m Message err = json.Unmarshal(b, &m) if err != nil{ fmt.Println(err) return } switch m.MType{ case DATA: t.in <- m.Payload } }) http.ListenAndServe(fmt.Sprintf(":%d", t.port), nil) } func (t *Teleporter) clientConnectToMaster(){ m := Message{ MType: PING, Payload:[]byte(strconv.Itoa(t.port)), } url := fmt.Sprintf("http://%s", t.master) _,_, errs := gorequest.New().Post(url).SendStruct(m).End() if errs != nil { log.Fatal(errs) } }
package main import ( "encoding/json" "fmt" "log" "net/http" "github.com/gorilla/mux" ) // Hello just a struct type Hello struct { Hello string } // Version a struct to show the version type Version struct { Version string } // our main function func main() { router := mux.NewRouter() router.HandleFunc("/hello", GetHello).Methods("GET") router.HandleFunc("/version", GetVersion).Methods("GET") fmt.Printf("%s\n", "Starting server on port 8000") log.Fatal(http.ListenAndServe(":8000", router)) } // GetHello return world func GetHello(w http.ResponseWriter, r *http.Request) { fmt.Printf("%s\n", "GetHello called") // create hello object hello := Hello{"world"} // to json js, err := json.Marshal(hello) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // return the response w.Header().Set("Content-Type", "application/json") w.Write(js) } // GetVersion return the current version of the app func GetVersion(w http.ResponseWriter, r *http.Request) { fmt.Printf("%s\n", "GetHello called") // create hello object version := Version{"1.1"} // to json js, err := json.Marshal(version) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // return the response w.Header().Set("Content-Type", "application/json") w.Write(js) }
package go_discovery import "fmt" package main import "fmt" func fac(n int) int { if n <= 0 { return 1 } return n * fac(n-1) } func facIter(n int) int { result := 1 for n > 0 { result *= n n-- } return result } func fac2(n int) int { result := 1 for i := 2; i <= n; i++ { fmt.Println("i is : ", i) result *= i } return result } func main() { fmt.Println("This is fac ", fac(4)) fmt.Println("This is facIter ", facIter(4)) fmt.Println("This is fac2 ", fac2(4)) // var a = 10 // b := "little" // b += " gophers" // fmt.Println(a, b) }
package main import ( "fmt" "time" ) /* Main func is executed by the main goroutine. Adding 'go' before call a func or a method causes the func is executed in a newly created go routine. */ func main() { //fmt.Println(fib(6)) // counter execution on a separate go routine go counter(1 * time.Second) // main go routine after X seconds will stop the application and all the goroutines abruptly terminated time.Sleep(3 * time.Second) fmt.Println() } /* Execute an infinite loop and inside it a loop that shows a single char every delay time passed as argument. */ func counter(delay time.Duration) { for { for _, r := range `1234567890` { fmt.Printf("\r%c/%d seconds", r,len(`1234567890`)) time.Sleep(delay) } } } // Computes a Fibonacci number (1,1,2,3,5,8...) func fib(x int) int { if x < 2 { fmt.Println("x:",x) return x } return fib(x-1) + fib(x-2) }
package object // Object represents values from our language in go type Object interface { Type() Type Inspect() string } // Type is used to determine the object variant type Type string const ( INTEGER_OBJ = "INTEGER" BOOLEAN_OBJ = "BOOLEAN" NULL_OBJ = "NULL" )
package error import ( "github.com/gin-gonic/gin" "yj-app/app/yjgframe/response" ) func Unauth(c *gin.Context) { response.BuildTpl(c, "error/unauth").WriteTpl() } func Error(c *gin.Context) { response.BuildTpl(c, "error/500").WriteTpl() } func NotFound(c *gin.Context) { response.BuildTpl(c, "error/404").WriteTpl() }
package kvs import "github.com/stretchr/testify/mock" type MockHaproxy struct { mock.Mock } func (_m *MockHaproxy) DeleteService(name string) error { ret := _m.Called(name) var r0 error if rf, ok := ret.Get(0).(func(string) error); ok { r0 = rf(name) } else { r0 = ret.Error(0) } return r0 } func (_m *MockHaproxy) DeleteUpstream(svcName string, id string) error { ret := _m.Called(svcName, id) var r0 error if rf, ok := ret.Get(0).(func(string, string) error); ok { r0 = rf(svcName, id) } else { r0 = ret.Error(0) } return r0 } func (_m *MockHaproxy) Domain(svcName string, domain string, port int) error { ret := _m.Called(svcName, domain, port) var r0 error if rf, ok := ret.Get(0).(func(string, string, int) error); ok { r0 = rf(svcName, domain, port) } else { r0 = ret.Error(0) } return r0 } func (_m *MockHaproxy) Init() error { ret := _m.Called() var r0 error if rf, ok := ret.Get(0).(func() error); ok { r0 = rf() } else { r0 = ret.Error(0) } return r0 } func (_m *MockHaproxy) Service(name string) (Service, error) { ret := _m.Called(name) var r0 Service if rf, ok := ret.Get(0).(func(string) Service); ok { r0 = rf(name) } else { r0 = ret.Get(0).(Service) } var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(name) } else { r1 = ret.Error(1) } return r0, r1 } func (_m *MockHaproxy) Services() ([]Service, error) { ret := _m.Called() var r0 []Service if rf, ok := ret.Get(0).(func() []Service); ok { r0 = rf() } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]Service) } } var r1 error if rf, ok := ret.Get(1).(func() error); ok { r1 = rf() } else { r1 = ret.Error(1) } return r0, r1 } func (_m *MockHaproxy) URLReg(svcName string, regex string, port int) error { ret := _m.Called(svcName, regex, port) var r0 error if rf, ok := ret.Get(0).(func(string, string, int) error); ok { r0 = rf(svcName, regex, port) } else { r0 = ret.Error(0) } return r0 } func (_m *MockHaproxy) Upstream(svcName string, address string) error { ret := _m.Called(svcName, address) var r0 error if rf, ok := ret.Get(0).(func(string, string) error); ok { r0 = rf(svcName, address) } else { r0 = ret.Error(0) } return r0 }
package api import ( "common/logger" "fmt" "github.com/ant0ine/go-json-rest/rest" "github.com/bitly/go-simplejson" "io/ioutil" ) const ( KEY_OP = "operation" KEY_CLASS = "class" ) //define customize api request type AlcedoApiRequest struct { *rest.Request //匿名字段 operation string class string //mongodb document name bodyContent []byte js *simplejson.Json } //decode body msg func (request *AlcedoApiRequest) DecodeMsg() { request.ReadBody() // js, err := simplejson.NewJson(request.bodyContent) request.js = js //handle json body operation field _, ok := request.js.CheckGet(KEY_OP) if ok { request.operation, err = request.js.Get(KEY_OP).String() } //handle json body class field _, ok = request.js.CheckGet(KEY_CLASS) if ok { request.class, err = request.js.Get(KEY_CLASS).String() } if err != nil { logger.Log.Error(err.Error()) } // logger.Log.Info(fmt.Sprintf("the rest api url:%s ,the operation:%s, the class:%s, the request body is %s", request.RequestURI, request.operation, request.class, request.bodyContent)) } func (request *AlcedoApiRequest) ReadBody() { content, err := ioutil.ReadAll(request.Body) if err != nil { logger.Log.Error(err.Error()) } else { request.bodyContent = content } }
/* * Copyright (c) 2020 - present Kurtosis Technologies LLC. * All Rights Reserved. */ package testsuite import "github.com/kurtosis-tech/kurtosis-client/golang/networks" // Docs available at https://docs.kurtosistech.com/kurtosis-libs/lib-documentation type Test interface { // Docs available at https://docs.kurtosistech.com/kurtosis-libs/lib-documentation Configure(builder *TestConfigurationBuilder) // Docs available at https://docs.kurtosistech.com/kurtosis-libs/lib-documentation Setup(networkCtx *networks.NetworkContext) (networks.Network, error) // NOTE: if Go had generics, 'network' would be a parameterized type representing the network that this test consumes // as produced by the NetworkLoader // Docs available at https://docs.kurtosistech.com/kurtosis-libs/lib-documentation Run(network networks.Network) error }
package main import ( "context" "github.com/gocolly/colly/v2" "go.mongodb.org/mongo-driver/bson" "log" "shopify_review_scrapper/config" "shopify_review_scrapper/data" "shopify_review_scrapper/phrasecounter" "strconv" "sync" ) func main() { reviewCollector := createConfiguredReviewCollector() scrapeReviewsToDatabase(reviewCollector, config.Config.ReviewsURLFirstPage) } func createConfiguredReviewCollector() *colly.Collector { reviewCollector := colly.NewCollector( colly.Async(true), ) reviewCollector.Limit(&colly.LimitRule{DomainGlob: "*", Parallelism: config.Config.WebsiteVisitorParallelismLimit}) return reviewCollector } func scrapeReviewsToDatabase(reviewCollector *colly.Collector, reviewsURL string) { reviewProcessingWaitGroup := setupReviewCollector(reviewCollector) reviewCollector.Visit(reviewsURL) reviewCollector.Wait() log.Println("Waiting for all review contents to be processed.") reviewProcessingWaitGroup.Wait() log.Println("Finished processing all review contents.") } func setupReviewCollector(reviewCollector *colly.Collector) *sync.WaitGroup { reviewProcessingWaitGroup := setupScrappingAndParsingReviews(reviewCollector) setupVisitingPages(reviewCollector) return reviewProcessingWaitGroup } func setupScrappingAndParsingReviews(reviewCollector *colly.Collector) *sync.WaitGroup { reviewContentChannel := make(chan string) waitGroup := &sync.WaitGroup{} reviewCollector.OnHTML(".review-listing", func(e *colly.HTMLElement) { externalID, _ := strconv.Atoi(e.ChildAttr("div", "data-review-id")) collection := data.GetReviewCollection() count, err := collection.CountDocuments(context.Background(), bson.M{"externalID": externalID}) if err != nil { panic(err) } // TODO: In theory, if a review is deleted and a shift happens, this might cause concurrency issues if the same review appears in 2 pages at once if count == 0 { log.Printf("New review %d ! Parsing.\n", externalID) collection.Create(data.NewReview(externalID)) content := e.ChildText(".truncate-content-copy") go addReviewToReviewContentChannel(externalID, content, waitGroup, reviewContentChannel) go consumeReviewFromReviewContentChannel(externalID, waitGroup, reviewContentChannel) } else { log.Printf("Existing review %d !\n", externalID) } }) return waitGroup } func consumeReviewFromReviewContentChannel(externalID int, waitGroup *sync.WaitGroup, reviewContentChannel <-chan string) { phraseFrequency := phrasecounter.CountThreeWordPhraseFrequency(<-reviewContentChannel) data.UpsertThreeWordPhraseFrequency(phraseFrequency) log.Println("Processed another review content!", externalID) waitGroup.Done() } func addReviewToReviewContentChannel(externalID int, content string, waitGroup *sync.WaitGroup, reviewContentChannel chan<- string) { waitGroup.Add(1) log.Println("Added another review content for processing!", externalID) reviewContentChannel <- content } // We are using a slice to track already visited pages, to ensure each page is only visited once. func setupVisitingPages(reviewCollector *colly.Collector) { visitedPages := make([]string, 0) var visitedPagesMutex = &sync.Mutex{} reviewCollector.OnHTML(".search-pagination__link", func(e *colly.HTMLElement) { pageURL := e.Attr("href") if canConsumePage(pageURL, &visitedPages, visitedPagesMutex) { log.Println("Visiting next page ", pageURL) e.Request.Visit(pageURL) } }) }
// Package errors is a drop-in replacement and extension of the Go standard // library's package [errors]. package errors import ( stderrors "errors" "fmt" "strings" ) // Error is the constant error type. // // See https://dave.cheney.net/2016/04/07/constant-errors. type Error string // Error implements the error interface for Error. func (err Error) Error() (msg string) { return string(err) } // Wrapper is a copy of the hidden wrapper interface from the Go standard // library. It is added here for tests, linting, etc. type Wrapper interface { Unwrap() error } // As finds the first error in err's chain that matches target, and if so, sets // target to that error value and returns true. Otherwise, it returns false. // // It calls [errors.As] from the Go standard library. func As(err error, target any) (ok bool) { return stderrors.As(err, target) } // Aser is a copy of the hidden aser interface from the Go standard library. It // is added here for tests, linting, etc. type Aser interface { As(target any) (ok bool) } // Is reports whether any error in err's chain matches target. // // It calls [errors.Is] from the Go standard library. func Is(err, target error) (ok bool) { return stderrors.Is(err, target) } // Iser is a copy of the hidden iser interface from the Go standard library. It // is added here for tests, linting, etc. type Iser interface { Is(target error) (ok bool) } // New returns an error that formats as the given msg. Each call to New returns // a distinct error value even if the text is identical. // // It calls [errors.New] from the Go standard library. // // Deprecated: Use type [Error] and constant errors instead. func New(msg string) (err error) { return stderrors.New(msg) } // Unwrap returns the result of calling the Unwrap method on err, if err's type // contains an Unwrap method returning error. Otherwise, Unwrap returns nil. // // It calls [errors.Unwrap] from the Go standard library. func Unwrap(err error) (unwrapped error) { return stderrors.Unwrap(err) } // Deferred is the interface for errors that were returned by cleanup functions, // such as Close. This is useful in APIs which desire to handle such errors // differently, for example to log them as warnings. // // Method Deferred returns a bool to mirror the behavior of types like // [net.Error] and allow implementations to decide if the error is a deferred // one dynamically. Users of this API must check it's return value as well as // the result [errors.As]. // // if derr := errors.Deferred(nil); errors.As(err, &derr) && derr.Deferred() { // // … // } // // See https://dave.cheney.net/2014/12/24/inspecting-errors. type Deferred interface { error Deferred() (ok bool) } // deferredError is a helper to implement Deferred. type deferredError struct { error } // type check var _ Deferred = deferredError{} // Deferred implements the [Deferred] interface for deferredError. func (err deferredError) Deferred() (ok bool) { return true } // type check var _ error = deferredError{} // Error implements the error interface for deferredError. func (err deferredError) Error() (msg string) { return fmt.Sprintf("deferred: %s", err.error) } // Unwrap implements the [Wrapper] interface for deferredError. func (err deferredError) Unwrap() (unwrapped error) { return err.error } // Pair is a pair of errors. The Returned error is the main error that has been // returned by a function. The Deferred error is the error returned by the // cleanup function, such as Close. // // In pairs returned from [WithDeferred], the Deferred error always implements // the [Deferred] interface. type Pair struct { Returned error Deferred error } // type check var _ error = (*Pair)(nil) // Error implements the error interface for *Pair. func (err *Pair) Error() string { return fmt.Sprintf("returned: %q, deferred: %q", err.Returned, Unwrap(err.Deferred)) } // type check var _ Wrapper = (*Pair)(nil) // Unwrap implements the [Wrapper] interface for *Pair. It returns the // Returned error. func (err *Pair) Unwrap() (unwrapped error) { return err.Returned } // WithDeferred is a helper function for deferred errors. For example, to // preserve errors from the Close method, replace this: // // defer f.Close() // // With this: // // defer func() { err = errors.WithDeferred(err, f.Close()) } // // If returned is nil and deferred is non-nil, the returned error implements the // [Deferred] interface. If both returned and deferred are non-nil, result has // the underlying type of [*Pair]. // // # Warning // // This function requires that there be only ONE error named "err" in the // function and that it is always the one that is returned. Example (Bad) // provides an example of the incorrect usage of WithDeferred. func WithDeferred(returned, deferred error) (result error) { if deferred == nil { return returned } if returned == nil { return deferredError{error: deferred} } return &Pair{ Returned: returned, Deferred: deferredError{error: deferred}, } } // listError is an error containing several wrapped errors. type listError struct { msg string errs []error } // List wraps several errors into a single error with an additional message. // // TODO(a.garipov): Deprecate once golibs switches to Go 1.20. func List(msg string, errs ...error) (err error) { return &listError{ msg: msg, errs: errs, } } // type check var _ error = (*listError)(nil) // Error implements the error interface for *listError. func (err *listError) Error() (msg string) { switch l := len(err.errs); l { case 0: return err.msg case 1: return fmt.Sprintf("%s: %s", err.msg, err.errs[0]) default: b := &strings.Builder{} // Here and further, ignore the errors since they are known to // be nil. _, _ = fmt.Fprintf(b, "%s: %d errors: ", err.msg, l) for i, e := range err.errs { if i == l-1 { _, _ = fmt.Fprintf(b, "%q", e) } else { _, _ = fmt.Fprintf(b, "%q, ", e) } } return b.String() } } // type check var _ Wrapper = (*listError)(nil) // Unwrap implements the Wrapper interface for *listError. func (err *listError) Unwrap() (unwrapped error) { if len(err.errs) == 0 { return nil } return err.errs[0] } // Annotate annotates the error with the message, unless the error is nil. The // last verb in format must be a verb compatible with errors, for example "%w". // // # In Defers // // The primary use case for this function is to simplify code like this: // // func (f *foo) doStuff(s string) (err error) { // defer func() { // if err != nil { // err = fmt.Errorf("bad foo %q: %w", s, err) // } // }() // // // … // } // // Instead, write: // // func (f *foo) doStuff(s string) (err error) { // defer func() { err = errors.Annotate(err, "bad foo %q: %w", s) }() // // // … // } // // # At The End Of Functions // // Another possible use case is to simplify final checks like this: // // func (f *foo) doStuff(s string) (err error) { // // … // // if err != nil { // return fmt.Errorf("doing stuff with %s: %w", s, err) // } // // return nil // } // // Instead, you could write: // // func (f *foo) doStuff(s string) (err error) { // // … // // return errors.Annotate(err, "doing stuff with %s: %w", s) // } // // # Warning // // This function requires that there be only ONE error named "err" in the // function and that it is always the one that is returned. Example (Bad) // provides an example of the incorrect usage of WithDeferred. func Annotate(err error, format string, args ...any) (annotated error) { if err == nil { return nil } return fmt.Errorf(format, append(args, err)...) }
package processors import ( "context" sdk "github.com/identityOrg/oidcsdk" "github.com/identityOrg/oidcsdk/impl/sdkerror" ) type DefaultAudienceValidationProcessor struct { } func NewDefaultAudienceValidationProcessor() *DefaultAudienceValidationProcessor { return &DefaultAudienceValidationProcessor{} } func (d *DefaultAudienceValidationProcessor) HandleTokenEP(ctx context.Context, requestContext sdk.ITokenRequestContext) sdk.IError { if requestContext.GetGrantType() == sdk.GrantResourceOwnerPassword || requestContext.GetGrantType() == sdk.GrantClientCredentials { requestedAudience := requestContext.GetRequestedAudience() client := requestContext.GetClient() if len(requestedAudience) == 0 { requestContext.GetProfile().SetAudience([]string{requestContext.GetClientID()}) return nil } else { if client.GetApprovedScopes().Has(requestedAudience...) { requestedAudience = append(requestedAudience, requestContext.GetClientID()) requestContext.GetProfile().SetAudience(requestedAudience) } else { return sdkerror.ErrInvalidRequest.WithHint("un-approved audience requested") } } } return nil } func (d *DefaultAudienceValidationProcessor) HandleAuthEP(_ context.Context, requestContext sdk.IAuthenticationRequestContext) sdk.IError { requestedAudience := requestContext.GetRequestedAudience() client := requestContext.GetClient() if len(requestedAudience) == 0 { requestContext.GetProfile().SetAudience([]string{requestContext.GetClientID()}) return nil } else { if client.GetApprovedScopes().Has(requestedAudience...) { requestedAudience = append(requestedAudience, requestContext.GetClientID()) requestContext.GetProfile().SetAudience(requestedAudience) return nil } else { return sdkerror.ErrInvalidRequest.WithHint("un-approved audience requested") } } }
package main import ( "fmt" "github.com/bitmaelum/bitmaelum-suite/cmd/bm-client/pkg/vault" "github.com/bitmaelum/bitmaelum-suite/internal" "github.com/bitmaelum/bitmaelum-suite/internal/config" "github.com/bitmaelum/bitmaelum-suite/pkg/address" "github.com/sirupsen/logrus" ) type options struct { Config string `short:"c" long:"config" description:"Configuration file" default:"./client-config.yml"` Addr string `short:"a" long:"address" description:"account"` Password string `short:"p" long:"password" description:"Password to decrypt your account"` } var opts options func main() { internal.ParseOptions(&opts) config.LoadClientConfig(opts.Config) // Convert strings into addresses fromAddr, err := address.New(opts.Addr) if err != nil { logrus.Fatal(err) } // Load account accountVault, err := vault.New(config.Client.Accounts.Path, []byte(opts.Password)) if err != nil { logrus.Fatal(err) } info, err := accountVault.GetAccountInfo(*fromAddr) if err != nil { logrus.Fatal(err) } fmt.Println("PRIV:") fmt.Printf("%s\n", info.PrivKey) fmt.Println("PUB:") fmt.Printf("%s\n", info.PubKey) fmt.Println("") ts, err := internal.GenerateJWTToken(fromAddr.Hash(), info.PrivKey) if err != nil { logrus.Fatal(err) } fmt.Println(ts) fmt.Println("") token, err := internal.ValidateJWTToken(ts, fromAddr.Hash(), info.PubKey) if err != nil { logrus.Fatal(err) } fmt.Printf("%#v\n", token.Claims) }
package main import ( "fmt" ) func parameterDataType1(x, y int) { fmt.Println("As x & y have same datatype, we need to declare datatype only once.") } func parameterDataType2(x, y int, z string) { fmt.Println("we can declare params like this as well.") } func main() { parameterDataType1(1, 2) parameterDataType2(1, 2, "String") }
package reporter import ( "bytes" "net/http" "net/url" "reflect" "testing" ) func TestNewHTTPReporter(t *testing.T) { type args struct { scheme string host string username string password string } tests := []struct { name string args args want *HTTPReporter }{ // TODO: Add test cases. } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := NewHTTPReporter(tt.args.scheme, tt.args.host, tt.args.username, tt.args.password); !reflect.DeepEqual(got, tt.want) { t.Errorf("NewHTTPReporter() = %v, want %v", got, tt.want) } }) } } func TestHTTPReporter_Report(t *testing.T) { type args struct { reportPath string buffer *bytes.Buffer } tests := []struct { name string reporter *HTTPReporter args args wantErr bool }{ // TODO: Add test cases. } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := tt.reporter.Report(tt.args.reportPath, tt.args.buffer); (err != nil) != tt.wantErr { t.Errorf("HTTPReporter.Report() error = %v, wantErr %v", err, tt.wantErr) } }) } } func TestHTTPReporter_ReportWithQueries(t *testing.T) { type args struct { reportPath string buffer *bytes.Buffer queries map[string]string } tests := []struct { name string reporter *HTTPReporter args args want bool wantErr bool }{ // TODO: Add test cases. } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := tt.reporter.ReportWithQueries(tt.args.reportPath, tt.args.buffer, tt.args.queries) if (err != nil) != tt.wantErr { t.Errorf("HTTPReporter.ReportWithQueries() error = %v, wantErr %v", err, tt.wantErr) return } if got != tt.want { t.Errorf("HTTPReporter.ReportWithQueries() = %v, want %v", got, tt.want) } }) } } func TestHTTPReporter_formReportingUrl(t *testing.T) { type args struct { reportingUrl url.URL buffer *bytes.Buffer } tests := []struct { name string reporter *HTTPReporter args args want *http.Request wantErr bool }{ // TODO: Add test cases. } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := tt.reporter.formReportingUrl(tt.args.reportingUrl, tt.args.buffer) if (err != nil) != tt.wantErr { t.Errorf("HTTPReporter.formReportingUrl() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("HTTPReporter.formReportingUrl() = %v, want %v", got, tt.want) } }) } }
package apis import ( "github.com/kataras/iris/context" ) func Login(ctx context.Context){ ctx.JSON(context.Map{"message": "Hello iris web framework."}) }
package main import ( sp "github.com/kpkhxlgy0/gs_libs/services" ) func startup() { go sig_handler() // init services discovery sp.Init("game", "snowflake") }
func climbStairs(n int) int { if n < 3 { return n } n1 := 1 n2 := 2 result := n1 + n2 for i := 3; i <= n; i++ { result = result + n2 n2 = n1 + n2 n1 = result - n2 } return n2 }
package main import ( "fmt" "io/ioutil" "log" "net/http" "strings" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() // 指定用户使用GET请求访问/hello时,执行sayGenHello函数 r.GET("/hello", sayGinHello) r.GET("/book", func(c *gin.Context) { c.JSON(200, gin.H{ "method": "GET", }) }) r.POST("/book", func(c *gin.Context) { c.JSON(200, gin.H{ "method": "POST", }) }) r.PUT("/book", func(c *gin.Context) { c.JSON(200, gin.H{ "method": "PUT", }) }) r.DELETE("/book", func(c *gin.Context) { c.JSON(200, gin.H{ "method": "DELETE", }) }) r.Run(":9090") // 默认是8080端口 } func sayGinHello(c *gin.Context) { c.JSON(200, gin.H{ "message": "Hello golang!", }) } /// ------------------------- 默认http -------------------------- func main1() { http.HandleFunc("/", sayhelloName) // 设置访问的路由 http.HandleFunc("/wmy", sayYeah) err := http.ListenAndServe(":9090", nil) // 设置监听的端口 if err != nil { log.Fatal("ListenAndServe: ", err) } } func sayhelloName(w http.ResponseWriter, r *http.Request) { fmt.Println("--------------------------------------") r.ParseForm() // 解析参数,默认是不会解析的 fmt.Println(r.Form) // 这些信息是输出到服务器端的打印信息 fmt.Println("path", r.URL.Path) fmt.Println("scheme", r.URL.Scheme) fmt.Println(r.Form["url_long"]) for k, v := range r.Form { fmt.Println("key:", k) fmt.Println("val:", strings.Join(v, "")) } fmt.Fprintf(w, "<h1>Hello world!<h1><h2>how are you</h2>") // 这个写入到 w 的是输出到客户端的 } func sayYeah(w http.ResponseWriter, r *http.Request) { b, _ := ioutil.ReadFile("hello.html") fmt.Fprintln(w, string(b)) }
package apiokex var ( BASE_URI = "https://www.okex.com/api/v1" FTRADE_URI = "/future_trade.do" FTRADE_CANCEL_URI = "/future_cancel.do" FTRADE_DEVOLVE_URI = "/future_devolve.do" ) type FutureResult struct { ErrorCode int64 `json:"error_code"` OrderId int64 `json:"order_id"` Result bool `json:"result"` }
package handler import ( "Golang-API-Game/pkg/dcontext" "Golang-API-Game/pkg/repository/characters" "Golang-API-Game/pkg/server/response" "errors" "log" "net/http" ) type UserCharacters struct { UserID string UserCharacterID string CharacterID string } type CharactersResponse struct { UserCharacterID string `json:"userCharacterID"` CharacterID string `json:"characterID"` Name string `json:"name"` } type userCharacterListResponses struct { Characters []CharactersResponse `json:"characters"` //何個も入れられる } //HandleUserCharacterInfoUpdate ユーザ情報更新処理 func HandleCharacterList() http.HandlerFunc { //すでにuser.goで使われているのでUserUpdateではなく違うものにした方がわかりやすい return func(writer http.ResponseWriter, request *http.Request) { //ヘッダーとボディをrequestは持っている() // Contextから認証済みのユーザIDを取得 ctx := request.Context() userID := dcontext.GetUserIDFromContext(ctx) if userID == "" { log.Println(errors.New("userID is empty")) response.InternalServerError(writer, "Internal Server Error") return } //userIDによってuserCharacter型のスライスを返す userCharacterList, err := gachaUserCharacter.SelectByUserID(userID) if err != nil { log.Println(err) response.InternalServerError(writer, "Internal Server Error") return } var charaResponse []CharactersResponse for _, userCharacter := range userCharacterList { log.Println("failed to get") var character *characters.Character character, err = characters.SelectByCharacterName(userCharacter.CharacterID) if err != nil { response.InternalServerError(writer, "Internal Server Error") //クライアント側 log.Println(character) return } charaRes := CharactersResponse{userCharacter.UserCharacterID, userCharacter.CharacterID, character.Name} charaResponse = append(charaResponse, charaRes) } response.Success(writer, userCharacterListResponses{Characters: charaResponse}) } }
package ibmcloud import ( "net/http" "strings" "github.com/IBM/vpc-go-sdk/vpcv1" "github.com/pkg/errors" ) const vpcTypeName = "vpc" // listVPCs lists VPCs func (o *ClusterUninstaller) listVPCs() (cloudResources, error) { o.Logger.Debugf("Listing VPCs") ctx, cancel := o.contextWithTimeout() defer cancel() options := o.vpcSvc.NewListVpcsOptions() resources, _, err := o.vpcSvc.ListVpcsWithContext(ctx, options) if err != nil { return nil, errors.Wrapf(err, "failed to list vpcs") } result := []cloudResource{} for _, vpc := range resources.Vpcs { if strings.Contains(*vpc.Name, o.InfraID) { result = append(result, cloudResource{ key: *vpc.ID, name: *vpc.Name, status: *vpc.Status, typeName: vpcTypeName, id: *vpc.ID, }) } } return cloudResources{}.insert(result...), nil } func (o *ClusterUninstaller) deleteVPC(item cloudResource) error { if item.status == vpcv1.VPCStatusDeletingConst { o.Logger.Debugf("Waiting for VPC %q to delete", item.name) return nil } o.Logger.Debugf("Deleting VPC %q", item.name) ctx, cancel := o.contextWithTimeout() defer cancel() options := o.vpcSvc.NewDeleteVPCOptions(item.id) details, err := o.vpcSvc.DeleteVPCWithContext(ctx, options) if err != nil && details != nil && details.StatusCode == http.StatusNotFound { // The resource is gone o.deletePendingItems(item.typeName, []cloudResource{item}) o.Logger.Infof("Deleted VPC %q", item.name) return nil } if err != nil && details != nil && details.StatusCode != http.StatusNotFound { return errors.Wrapf(err, "Failed to delete VOC %s", item.name) } return nil } // listVPCs removes all VPC resources that have a name prefixed // with the cluster's infra ID. func (o *ClusterUninstaller) destroyVPCs() error { if o.UserProvidedVPC != "" { o.Logger.Infof("Skipping deletion of user-provided VPC %q", o.UserProvidedVPC) return nil } found, err := o.listVPCs() if err != nil { return err } items := o.insertPendingItems(vpcTypeName, found.list()) for _, item := range items { if _, ok := found[item.key]; !ok { // This item has finished deletion. o.deletePendingItems(item.typeName, []cloudResource{item}) o.Logger.Infof("Deleted VPC %q", item.name) continue } err := o.deleteVPC(item) if err != nil { o.errorTracker.suppressWarning(item.key, err, o.Logger) } } if items = o.getPendingItems(vpcTypeName); len(items) > 0 { return errors.Errorf("%d items pending", len(items)) } return nil }
package weldr import ( "encoding/json" "errors" "time" "github.com/osbuild/osbuild-composer/internal/common" "github.com/osbuild/osbuild-composer/internal/distro" "github.com/google/uuid" "github.com/osbuild/osbuild-composer/internal/target" ) type uploadResponse struct { UUID uuid.UUID `json:"uuid"` Status common.ImageBuildState `json:"status"` ProviderName string `json:"provider_name"` ImageName string `json:"image_name"` CreationTime float64 `json:"creation_time"` Settings uploadSettings `json:"settings"` } type uploadSettings interface { isUploadSettings() } type awsUploadSettings struct { Region string `json:"region"` AccessKeyID string `json:"accessKeyID,omitempty"` SecretAccessKey string `json:"secretAccessKey,omitempty"` Bucket string `json:"bucket"` Key string `json:"key"` } func (awsUploadSettings) isUploadSettings() {} type azureUploadSettings struct { StorageAccount string `json:"storageAccount,omitempty"` StorageAccessKey string `json:"storageAccessKey,omitempty"` Container string `json:"container"` } func (azureUploadSettings) isUploadSettings() {} type vmwareUploadSettings struct { Host string `json:"host"` Username string `json:"username"` Password string `json:"password"` Datacenter string `json:"datacenter"` Cluster string `json:"cluster"` Datastore string `json:"datastore"` } func (vmwareUploadSettings) isUploadSettings() {} type uploadRequest struct { Provider string `json:"provider"` ImageName string `json:"image_name"` Settings uploadSettings `json:"settings"` } type rawUploadRequest struct { Provider string `json:"provider"` ImageName string `json:"image_name"` Settings json.RawMessage `json:"settings"` } func (u *uploadRequest) UnmarshalJSON(data []byte) error { var rawUploadRequest rawUploadRequest err := json.Unmarshal(data, &rawUploadRequest) if err != nil { return err } var settings uploadSettings switch rawUploadRequest.Provider { case "azure": settings = new(azureUploadSettings) case "aws": settings = new(awsUploadSettings) case "vmware": settings = new(vmwareUploadSettings) default: return errors.New("unexpected provider name") } err = json.Unmarshal(rawUploadRequest.Settings, settings) if err != nil { return err } u.Provider = rawUploadRequest.Provider u.ImageName = rawUploadRequest.ImageName u.Settings = settings return err } // Converts a `Target` to a serializable `uploadResponse`. // // This ignore the status in `targets`, because that's never set correctly. // Instead, it sets each target's status to the ImageBuildState equivalent of // `state`. // // This also ignores any sensitive data passed into targets. Access keys may // be passed as input to composer, but should not be possible to be queried. func targetsToUploadResponses(targets []*target.Target, state ComposeState) []uploadResponse { var uploads []uploadResponse for _, t := range targets { upload := uploadResponse{ UUID: t.Uuid, ImageName: t.ImageName, CreationTime: float64(t.Created.UnixNano()) / 1000000000, } switch state { case ComposeWaiting: upload.Status = common.IBWaiting case ComposeRunning: upload.Status = common.IBRunning case ComposeFinished: upload.Status = common.IBFinished case ComposeFailed: upload.Status = common.IBFailed } switch options := t.Options.(type) { case *target.AWSTargetOptions: upload.ProviderName = "aws" upload.Settings = &awsUploadSettings{ Region: options.Region, Bucket: options.Bucket, Key: options.Key, // AccessKeyID and SecretAccessKey are intentionally not included. } uploads = append(uploads, upload) case *target.AzureTargetOptions: upload.ProviderName = "azure" upload.Settings = &azureUploadSettings{ Container: options.Container, // StorageAccount and StorageAccessKey are intentionally not included. } uploads = append(uploads, upload) case *target.VMWareTargetOptions: upload.ProviderName = "vmware" upload.Settings = &vmwareUploadSettings{ Host: options.Host, Cluster: options.Cluster, Datacenter: options.Datacenter, Datastore: options.Datastore, // Username and Password are intentionally not included. } uploads = append(uploads, upload) } } return uploads } func uploadRequestToTarget(u uploadRequest, imageType distro.ImageType) *target.Target { var t target.Target t.Uuid = uuid.New() t.ImageName = u.ImageName t.Status = common.IBWaiting t.Created = time.Now() switch options := u.Settings.(type) { case *awsUploadSettings: t.Name = "org.osbuild.aws" t.Options = &target.AWSTargetOptions{ Filename: imageType.Filename(), Region: options.Region, AccessKeyID: options.AccessKeyID, SecretAccessKey: options.SecretAccessKey, Bucket: options.Bucket, Key: options.Key, } case *azureUploadSettings: t.Name = "org.osbuild.azure" t.Options = &target.AzureTargetOptions{ Filename: imageType.Filename(), StorageAccount: options.StorageAccount, StorageAccessKey: options.StorageAccessKey, Container: options.Container, } case *vmwareUploadSettings: t.Name = "org.osbuild.vmware" t.Options = &target.VMWareTargetOptions{ Filename: imageType.Filename(), Username: options.Username, Password: options.Password, Host: options.Host, Cluster: options.Cluster, Datacenter: options.Datacenter, Datastore: options.Datastore, } } return &t }
package main import ( "fmt" "reflect" ) type Animal struct { Name string } func (a Animal) A() { fmt.Println("A") } func (a Animal) B() { fmt.Println("B") } func main() { a := Animal{ Name: "ganshuoos", } t := reflect.TypeOf(a) fmt.Println(t.Kind(), t.Name(), t.NumMethod()) v := reflect.ValueOf(&a) v = v.Elem() v.Field(0).SetString("new Eggo") fmt.Println(a) }
package conversion // //func ToInterface(slice []interface{}) []interface{} { // data := make([]interface{}, 0) // data = append(data, slice...) // return data //}
package main import ( "github.com/julienschmidt/httprouter" "net/http" "video_server/scheduler/orm" ) func videoDelHandler(writer http.ResponseWriter, request *http.Request, params httprouter.Params) { vid := params.ByName("video_id") if len(vid) == 0 { sendResponse(writer, 400, "video_id is should not be empty") return } err := orm.AddVideoDeletionRecord(vid) if err != nil { sendResponse(writer, 500, "Internal Server Error") return } sendResponse(writer, 200, "Success") return }
package util /* #include "util.h" */ import "C" import "fmt" func GoSum(a,b int) int { s := C.sum(C.int(a),C.int(b)) fmt.Println(s) return int(s) }
package main import ( "github.com/koeng101/armos/devices/ar3" "log" "github.com/jmoiron/sqlx" _ "modernc.org/sqlite" "net/http/httptest" "os" "strings" "testing" ) var app App func TestMain(m *testing.M) { // Initialize the local sqlite database db, err := sqlx.Open("sqlite", ":memory:") if err != nil { log.Fatalf("Failed to open sqlite database on err: %s", err) } _, err = db.Exec(Schema) if err != nil { log.Fatalf("Failed on CreateDatabase with error: %s", err) } // Initialize ar3 mock arm arm := ar3.ConnectMock() app = initializeApp(db, arm) // Run the rest of our code code := m.Run() os.Exit(code) } func TestPing(t *testing.T) { req := httptest.NewRequest("GET", "/api/ping", nil) resp := httptest.NewRecorder() app.Router.ServeHTTP(resp, req) r := `{"message":"Online"}` if strings.TrimSpace(resp.Body.String()) != r { t.Errorf("Unexpected response. Expected: " + r + "\nGot: " + resp.Body.String()) } }
package httpclient import ( "context" "fmt" "net/http" "strings" "github.com/asecurityteam/transport" "github.com/asecurityteam/settings" transportd "github.com/asecurityteam/transportd/pkg" componentsd "github.com/asecurityteam/transportd/pkg/components" ) const ( // TypeDefault is used to select the default Go HTTP client. TypeDefault = "DEFAULT" // TypeSmart is used to select the transportd HTTP client. TypeSmart = "SMART" ) // DefaultConfig contains all settings for the default Go HTTP client. type DefaultConfig struct { ContentType string } // DefaultComponent is a component for creating the default Go HTTP client. type DefaultComponent struct{} // Settings returns the default configuration. func (*DefaultComponent) Settings() *DefaultConfig { return &DefaultConfig{ ContentType: "application/json", } } // New constructs a client from the given configuration func (*DefaultComponent) New(ctx context.Context, conf *DefaultConfig) (http.RoundTripper, error) { return transport.NewHeader( func(*http.Request) (string, string) { return "Content-Type", conf.ContentType }, )(http.DefaultTransport), nil } // SmartConfig contains all settings for the transportd HTTP client. type SmartConfig struct { OpenAPI string `description:"The full OpenAPI specification with transportd extensions."` } // Name of the configuration tree. func (*SmartConfig) Name() string { return "smart" } // SmartComponent is a component for creating a transportd HTTP client. type SmartComponent struct { Plugins []transportd.NewComponent } // Settings returns the default configuration. func (*SmartComponent) Settings() *SmartConfig { return &SmartConfig{} } // New constructs a client from the given configuration. func (c *SmartComponent) New(ctx context.Context, conf *SmartConfig) (http.RoundTripper, error) { return transportd.NewTransport(ctx, []byte(conf.OpenAPI), c.Plugins...) } // Config wraps all HTTP related settings. type Config struct { Type string `description:"The type of HTTP client. Choices are SMART and DEFAULT."` Default *DefaultConfig Smart *SmartConfig } // Name of the config. func (*Config) Name() string { return "httpclient" } // Component is the top level HTTP client component. type Component struct { Default *DefaultComponent Smart *SmartComponent } // NewComponent populates an HTTPComponent with defaults. func NewComponent() *Component { return &Component{ Default: &DefaultComponent{}, Smart: &SmartComponent{ Plugins: componentsd.Defaults, }, } } // Settings returns the default configuration. func (c *Component) Settings() *Config { return &Config{ Type: "DEFAULT", Default: c.Default.Settings(), Smart: c.Smart.Settings(), } } // New constructs a client from the given configuration. func (c *Component) New(ctx context.Context, conf *Config) (http.RoundTripper, error) { switch { case strings.EqualFold(conf.Type, TypeDefault): return c.Default.New(ctx, conf.Default) case strings.EqualFold(conf.Type, TypeSmart): return c.Smart.New(ctx, conf.Smart) default: return nil, fmt.Errorf("unknown HTTP client type %s", conf.Type) } } // Load is a convenience method for binding the source to the component. func Load(ctx context.Context, source settings.Source, c *Component) (http.RoundTripper, error) { dst := new(http.RoundTripper) err := settings.NewComponent(ctx, source, c, dst) if err != nil { return nil, err } return *dst, nil } // New is the top-level entry point for creating a new HTTP client. // The default set of plugins will be installed for the smart client. Use the // LoadHTTP() method if a custom set of plugins are required. func New(ctx context.Context, source settings.Source) (http.RoundTripper, error) { return Load(ctx, source, NewComponent()) }
// Package redis implements a registry in redis. package redis import ( "context" "fmt" "sort" "strings" "sync" "time" "github.com/cenkalti/backoff/v4" "github.com/go-redis/redis/v8" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/durationpb" "github.com/pomerium/pomerium/internal/log" "github.com/pomerium/pomerium/internal/redisutil" "github.com/pomerium/pomerium/internal/registry" "github.com/pomerium/pomerium/internal/registry/redis/lua" "github.com/pomerium/pomerium/internal/signal" registrypb "github.com/pomerium/pomerium/pkg/grpc/registry" ) const ( registryKey = redisutil.KeyPrefix + "registry" registryUpdateKey = redisutil.KeyPrefix + "registry_changed_ch" pollInterval = time.Second * 30 ) type impl struct { cfg *config client redis.UniversalClient onChange *signal.Signal closeOnce sync.Once closed chan struct{} } // New creates a new registry implementation backend by redis. func New(rawURL string, options ...Option) (registry.Interface, error) { cfg := getConfig(options...) client, err := redisutil.NewClientFromURL(rawURL, cfg.tls) if err != nil { return nil, err } i := &impl{ cfg: cfg, client: client, onChange: signal.New(), closed: make(chan struct{}), } go i.listenForChanges(context.Background()) return i, nil } func (i *impl) Report(ctx context.Context, req *registrypb.RegisterRequest) (*registrypb.RegisterResponse, error) { _, err := i.runReport(ctx, req.GetServices()) if err != nil { return nil, err } return &registrypb.RegisterResponse{ CallBackAfter: durationpb.New(i.cfg.ttl / 2), }, nil } func (i *impl) List(ctx context.Context, req *registrypb.ListRequest) (*registrypb.ServiceList, error) { all, err := i.runReport(ctx, nil) if err != nil { return nil, err } include := map[registrypb.ServiceKind]struct{}{} for _, kind := range req.GetKinds() { include[kind] = struct{}{} } filtered := make([]*registrypb.Service, 0, len(all)) for _, svc := range all { if _, ok := include[svc.GetKind()]; !ok { continue } filtered = append(filtered, svc) } sort.Slice(filtered, func(i, j int) bool { { iv, jv := filtered[i].GetKind(), filtered[j].GetKind() switch { case iv < jv: return true case jv < iv: return false } } { iv, jv := filtered[i].GetEndpoint(), filtered[j].GetEndpoint() switch { case iv < jv: return true case jv < iv: return false } } return false }) return &registrypb.ServiceList{ Services: filtered, }, nil } func (i *impl) Watch(req *registrypb.ListRequest, stream registrypb.Registry_WatchServer) error { // listen for changes ch := i.onChange.Bind() defer i.onChange.Unbind(ch) // force a check periodically poll := time.NewTicker(pollInterval) defer poll.Stop() var prev *registrypb.ServiceList for { // retrieve the most recent list of services lst, err := i.List(stream.Context(), req) if err != nil { return err } // only send a new list if something changed if !proto.Equal(prev, lst) { err = stream.Send(lst) if err != nil { return err } } prev = lst // wait for an update select { case <-i.closed: return nil case <-stream.Context().Done(): return stream.Context().Err() case <-ch: case <-poll.C: } } } func (i *impl) Close() error { var err error i.closeOnce.Do(func() { err = i.client.Close() close(i.closed) }) return err } func (i *impl) listenForChanges(ctx context.Context) { ctx, cancel := context.WithCancel(ctx) go func() { <-i.closed cancel() }() bo := backoff.NewExponentialBackOff() bo.MaxElapsedTime = 0 outer: for { pubsub := i.client.Subscribe(ctx, registryUpdateKey) for { msg, err := pubsub.Receive(ctx) if err != nil { _ = pubsub.Close() select { case <-ctx.Done(): return case <-time.After(bo.NextBackOff()): } continue outer } bo.Reset() switch msg.(type) { case *redis.Message: i.onChange.Broadcast(ctx) } } } } func (i *impl) runReport(ctx context.Context, updates []*registrypb.Service) ([]*registrypb.Service, error) { args := []interface{}{ i.cfg.getNow().UnixNano() / int64(time.Millisecond), // current_time i.cfg.ttl.Milliseconds(), // ttl } for _, svc := range updates { args = append(args, i.getRegistryHashKey(svc)) } res, err := i.client.Eval(ctx, lua.Registry, []string{registryKey, registryUpdateKey}, args...).Result() if err != nil { return nil, err } if values, ok := res.([]interface{}); ok { var all []*registrypb.Service for _, value := range values { svc, err := i.getServiceFromRegistryHashKey(fmt.Sprint(value)) if err != nil { log.Warn(ctx).Err(err).Msg("redis: invalid service") continue } all = append(all, svc) } return all, nil } return nil, nil } func (i *impl) getServiceFromRegistryHashKey(key string) (*registrypb.Service, error) { idx := strings.Index(key, "|") if idx == -1 { return nil, fmt.Errorf("redis: invalid service entry in hash: %s", key) } svcKindStr := key[:idx] svcEndpointStr := key[idx+1:] svcKind, ok := registrypb.ServiceKind_value[svcKindStr] if !ok { return nil, fmt.Errorf("redis: unknown service kind: %s", svcKindStr) } svc := &registrypb.Service{ Kind: registrypb.ServiceKind(svcKind), Endpoint: svcEndpointStr, } return svc, nil } func (i *impl) getRegistryHashKey(svc *registrypb.Service) string { return svc.GetKind().String() + "|" + svc.GetEndpoint() }
package pprof import ( "flag" "strings" ) type ( FlagSet struct { *flag.FlagSet input []string usageMsgs []string } ) func NewFlagSet(input []string) *FlagSet { return &FlagSet{ flag.NewFlagSet("", flag.ContinueOnError), input, []string{}, } } func (f *FlagSet) StringList(o, d, c string) *[]*string { return &[]*string{f.String(o, d, c)} } func (f *FlagSet) ExtraUsage() string { return strings.Join(f.usageMsgs, "\n") } func (f *FlagSet) AddExtraUsage(eu string) { f.usageMsgs = append(f.usageMsgs, eu) } func (f *FlagSet) Parse(usage func()) []string { f.Usage = usage f.FlagSet.Parse(f.input) args := f.Args() if len(args) == 0 { usage() } return args }
package utils import "strings" // This function take a string and returns the string // avoiding special letters func RemoveLetters(word string) string { word = strings.Replace(word, "á", "a", -1) word = strings.Replace(word, "é", "e", -1) word = strings.Replace(word, "í", "i", -1) word = strings.Replace(word, "ó", "o", -1) word = strings.Replace(word, "ú", "u", -1) word = strings.Replace(word, "¿", "", -1) word = strings.Replace(word, "?", "", -1) word = strings.Replace(word, "¡", "", -1) word = strings.Replace(word, "!", "", -1) return word } // This function takes a string and returns // the string without special letters and // a lower string. func CleanWord(word string) string { word = RemoveLetters(word) return strings.ToLower(word) }
/* Copyright 2018 Pressinfra SRL. 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 v1alpha1 import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // SecretRef represents a reference to a Secret type SecretRef string // Domain represents a valid domain name type Domain string // WordpressSpec defines the desired state of Wordpress type WordpressSpec struct { // WordpressRuntime to use // +kubebuilder:validation:MinLength=1 Runtime string `json:"runtime"` // Number of desired web pods. This is a pointer to distinguish between // explicit zero and not specified. Defaults to 1. // +optional Replicas *int32 `json:"replicas,omitempty"` // Image overrides WordpressRuntime spec.defaultImage // +optional Image string `json:"image,omitempty"` // ImagePullPolicy overrides WordpressRuntime spec.imagePullPolicy // +kubebuilder:validation:Enum=Always,IfNotPresent,Never // +optional ImagePullPolicy corev1.PullPolicy `json:"imagePullPolicy,omitempty"` // ImagePullSecrets defines additional secrets to use when pulling images ImagePullSecrets []corev1.LocalObjectReference `json:"imagePullSecrets,omitempty"` // ServiceAccountName is the name of the ServiceAccount to use to run this // site's pods // More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/ // +optional ServiceAccountName string `json:"serviceAccountName,omitempty"` // Domains for which this this site answers. // The first item is set as the "main domain" (eg. WP_HOME and WP_SITEURL constants). // +kubebuilder:validation:MinItems=1 Domains []Domain `json:"domains"` // TLSSecretRef a secret containing the TLS certificates for this site. // +optional TLSSecretRef SecretRef `json:"tlsSecretRef,omitempty"` // WebrootVolumeSpec overrides WordpressRuntime spec.webrootVolumeSpec // This field is immutable. // +optional WebrootVolumeSpec *WordpressVolumeSpec `json:"webrootVolumeSpec,omitempty"` // MediaVolumeSpec overrides WordpressRuntime spec.mediaVolumeSpec // This field is immutable. // +optional MediaVolumeSpec *WordpressVolumeSpec `json:"mediaVolumeSpec,omitempty"` // Volumes defines additional volumes to get injected into web and cli pods // +optional Volumes []corev1.Volume `json:"volumes,omitempty"` // VolumeMountsSpec defines additional mounts which get injected into web // and cli pods. // +optional VolumeMountsSpec []corev1.VolumeMount `json:"volumeMountsSpec,omitempty"` // Env defines additional environment variables which get injected into web // and cli pods // +optional // +patchMergeKey=name // +patchStrategy=merge Env []corev1.EnvVar `json:"env,omitempty" patchStrategy:"merge" patchMergeKey:"name"` // EnvFrom defines additional envFrom's which get injected into web // and cli pods // +optional EnvFrom []corev1.EnvFromSource `json:"envFrom,omitempty"` // IngressAnnotations for this Wordpress site // +optional IngressAnnotations map[string]string `json:"ingressAnnotations,omitempty"` // Labels to apply to generated resources Labels map[string]string `json:"labels,omitempty"` } // WordpressVolumeSpec is the desired spec of a wordpress volume type WordpressVolumeSpec struct { // EmptyDir to use if no PersistentVolumeClaim or HostPath is specified // +optional EmptyDir *corev1.EmptyDirVolumeSource `json:"emptyDir,omitempty"` // HostPath to use instead of a PersistentVolumeClaim. // +optional HostPath *corev1.HostPathVolumeSource `json:"hostPath,omitempty"` // PersistentVolumeClaim to use. It has the highest level of precedence, // followed by HostPath and EmptyDir // +optional PersistentVolumeClaim *corev1.PersistentVolumeClaimSpec `json:"persistentVolumeClaim,omitempty"` } // WordpressStatus defines the observed state of Wordpress type WordpressStatus struct { } // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // Wordpress is the Schema for the wordpresses API // +k8s:openapi-gen=true type Wordpress struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec WordpressSpec `json:"spec,omitempty"` Status WordpressStatus `json:"status,omitempty"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // WordpressList contains a list of Wordpress type WordpressList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []Wordpress `json:"items"` } func init() { SchemeBuilder.Register(&Wordpress{}, &WordpressList{}) }
package main import ( "fmt" "math/rand" "time" "hawx.me/code/chords" ) var rnd = rand.New(rand.NewSource(time.Now().UnixNano())) func Random(root chords.Note) chords.Chord { i := rnd.Intn(len(chords.Variants)) return chords.Variants[i](root) } func Shuffle(s []chords.Note) { for i := len(s) - 1; i > 0; i-- { j := rnd.Intn(i + 1) s[i], s[j] = s[j], s[i] } } func main() { copyNotes := make([]chords.Note, 12) copy(copyNotes, chords.Notes[:]) Shuffle(copyNotes) for i := 0; ; i = (i + 1) % 12 { chord := Random(copyNotes[i]) fmt.Print(chord.Name) fmt.Scanf(" ") fmt.Println(chord.Fretboard()) } }
package pkg import ( "bytes" "context" "crypto/rand" "encoding/base64" "errors" "github.com/SungminSo/qr-generator/models" "github.com/SungminSo/qr-generator/models/qrcode" "github.com/gin-gonic/gin" qr "github.com/skip2/go-qrcode" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo/options" "image" "image/jpeg" "log" "net/http" ) // Generate a 6-digit random number. func GenerateRandom() string { randomNum, err := rand.Prime(rand.Reader, 32) if err != nil { log.Fatal(err) } return randomNum.String()[:6] } // Add salt string and encrypt them as base64 to increase the length of the QR code content. // Because the length of the QR code content affects the complexity of the QR code. func B64Encrypt(qrToken string) string { salt := "/qr-g3nerat0r/" data := salt + qrToken return base64.StdEncoding.EncodeToString([]byte(data)) } // If there is a content, generate a QR Code with the content, // If there is no content, generate a QR Code withe a 6-digit authentication number. // Return QR Code, 6-digit authentication number and error. func GenerateQR(content string) (qrCode []byte, qrContent string, qrToken string, err error) { qrContent = content qrToken = GenerateRandom() encryptedQRToken := B64Encrypt(qrToken) if len(encryptedQRToken) == 0 { return nil, "", "", errors.New("fail to create QR Code Token") } qrCode, err = qr.Encode(encryptedQRToken, qr.Medium, 256) if err != nil { return nil, "", "", errors.New("fail to create QR Code") } return qrCode, qrContent, qrToken, nil } func SendQR(c *gin.Context) { type Req struct { Content string `json:"content"` } reqBody := &Req{} err := c.ShouldBindJSON(reqBody) if err != nil { c.String(http.StatusBadRequest, err.Error()) return } qrCode, qrContent, qrToken, err := GenerateQR(reqBody.Content) if err != nil { c.String(http.StatusInternalServerError, err.Error()) return } _, err = models.QRCodes.InsertOne(context.Background(), qrcode.NewQRCode(reqBody.Content, qrToken).QRToBson()) if err != nil { c.String(http.StatusInternalServerError, err.Error()) return } qrCodeImg, _, _ := image.Decode(bytes.NewReader(qrCode)) buffer := new(bytes.Buffer) err = jpeg.Encode(buffer, qrCodeImg, nil) if err != nil { c.String(http.StatusInternalServerError, err.Error()) return } qrCodeStr := base64.StdEncoding.EncodeToString(buffer.Bytes()) c.JSON(http.StatusOK, gin.H{ "qrCode": qrCodeStr, "qrContent": qrContent, "qrToken": qrToken, }) } // Verify by comparing entered QR Token with token,created when QR Code was generated, stored in DB. func VerifyQR(c *gin.Context) { QRToken := c.Param("qrToken") var findResult qrcode.QRCode filter := bson.D{{Key: "qrToken", Value: QRToken}} opts := options.FindOne() opts.SetSort(bson.D{{"createdAt", -1}}) err := models.QRCodes.FindOne(context.Background(), filter, opts).Decode(&findResult) if err != nil { c.String(http.StatusInternalServerError, err.Error()) return } if findResult.QRToken == QRToken { c.String(http.StatusOK, "Success") } else { c.String(http.StatusBadRequest, "Wrong QR Token") } return }
package atomicutil import ( "testing" "github.com/stretchr/testify/assert" ) func TestValue(t *testing.T) { v := NewValue(5) assert.Equal(t, 5, v.Load()) t.Run("nil", func(t *testing.T) { var v *Value[int] assert.Equal(t, 0, v.Load()) }) t.Run("default", func(t *testing.T) { var v Value[int] assert.Equal(t, 0, v.Load()) }) }
package hw04_lru_cache //nolint:golint,stylecheck import ( "testing" "github.com/stretchr/testify/require" ) func TestList(t *testing.T) { t.Run("empty list", func(t *testing.T) { l := NewList() require.Equal(t, l.Len(), 0) require.Nil(t, l.Front()) require.Nil(t, l.Back()) }) t.Run("complex", func(t *testing.T) { l := NewList() l.PushFront(10) // [10] l.PushBack(20) // [10, 20] l.PushBack(30) // [10, 20, 30] require.Equal(t, l.Len(), 3) middle := l.Back().Prev // 20 l.Remove(middle) // [10, 30] require.Equal(t, l.Len(), 2) for i, v := range [...]int{40, 50, 60, 70, 80} { if i%2 == 0 { l.PushFront(v) } else { l.PushBack(v) } } // [80, 60, 40, 10, 30, 50, 70] require.Equal(t, l.Len(), 7) require.Equal(t, 80, l.Front().Value) require.Equal(t, 70, l.Back().Value) l.MoveToFront(l.Front()) // [80, 60, 40, 10, 30, 50, 70] l.MoveToFront(l.Back()) // [70, 80, 60, 40, 10, 30, 50] <- last item elems := make([]int, 0, l.Len()) for i := l.Back(); i != nil; i = i.Prev { elems = append(elems, i.Value.(int)) } require.Equal(t, []int{50, 30, 10, 40, 60, 80, 70}, elems) }) t.Run("MoveToFront Test", func(t *testing.T) { l := NewList() for i := 10; i < 100; i += 10 { l.PushBack(i) } // [10, 20, 30, 40, 50, 60, 70, 80, 90] item := l.Back().Prev.Prev // 70 l.MoveToFront(item) // [70, 10, 20, 30, 40, 50, 60, 80, 90] <- not last item result := make([]int, 0, l.Len()) for i := l.Front(); i != nil; i = i.Next { result = append(result, i.Value.(int)) } require.Equal(t, []int{70, 10, 20, 30, 40, 50, 60, 80, 90}, result) }) }
/* Disclaimer: The story told within this question is entirely fictional, and invented solely for the purpose of providing an intro. My boss has gotten a new toy robot, and he wants me to help program it. He wants to be able to enter simple arrow instructions to get it to move. These instructions are: ^ (for move forward) < (for turn left), and > (for turn right). However, now that I've programmed the robot, he wants additional functionality. He wants me to transform any sequence of arrows he inputs, so that rather than having the robot take the path indicated, it moves to the desired location, indicated by the place it would end up if it had taken the inputted path, as efficiently as possible. I appeal to you, the members of PP&CG, to help me with this task. Your Task: Write a program or function to convert a string made up of arrows into a string that will get to the location indicated by the input as quickly as possible. Turning takes exactly as long as moving backwards or forwards. Input: A string of arrows, as indicated above. If you wish, different characters may be substituted for the arrows, but be sure to include the fact that you do so in your answer. All test cases use the arrows normally. Output: A string of arrows (or your equivalent characters), that take the robot to the desired destination as efficiently as possible. Test Cases: Note that the solutions offered are only possibilities, and that other solutions may be valid. >^<<^^>^^ -> ^^<^ ^^^^>^^^^ -> ^^^^>^^^^ >>>^^^^^^ -> <^^^^^^ >^>^>^>^ -> (empty string) ^<^^<^^<^^^^ -> >^^>^ Scoring: The robot's memory is limited, so your program must have the lowest byte count possible. */ package main import ( "fmt" "strings" ) func main() { test(">^<<^^>^^", "^^<^") test("^^^^>^^^^", "^^^^>^^^^") test(">>>^^^^^^", "<^^^^^^") test(">^>^>^>^", "") test("^<^^<^^<^^^^", ">^^>^") } func assert(x bool) { if !x { panic("assertion failed") } } func test(s, r string) { p := efficient(s) sx, sy := traverse(s) px, py := traverse(p) fmt.Printf("(%+d, %+d) %q\n", px, py, p) assert(sx == px && sy == py) assert(len(p) == len(r)) } func efficient(s string) string { x, y := traverse(s) if x == 0 && y == 0 { return "" } t := "<" if x > 0 { t = ">" } dx := strings.Repeat("^", abs(x)) dy := strings.Repeat("^", abs(y)) r := "" switch { case y > 0: r = fmt.Sprintf("%v", dy) if dx != "" { r += fmt.Sprintf("%v%v", t, dx) } default: r = fmt.Sprintf("%v%v", t, dx) if dy != "" { r += fmt.Sprintf("%v%v", t, dy) } } return r } func traverse(s string) (int, int) { x, y, d := 0, 0, 0 for _, c := range s { switch c { case '^': switch d { case 0: y += 1 case 1: x += 1 case 2: y -= 1 case 3: x -= 1 } case '<': d = mod(d-1, 4) case '>': d = mod(d+1, 4) } } return x, y } func abs(x int) int { if x < 0 { x = -x } return x } func mod(x, m int) int { x %= m if x < 0 { x += m } return x }
package handlers import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "database/sql" "encoding/hex" "encoding/json" "errors" "net/http" "net/http/httptest" "os" "reflect" "sync" "testing" "time" "github.com/SIGBlockchain/project_aurum/internal/accountstable" "github.com/SIGBlockchain/project_aurum/internal/block" "github.com/SIGBlockchain/project_aurum/internal/constants" "github.com/SIGBlockchain/project_aurum/internal/contracts" "github.com/SIGBlockchain/project_aurum/internal/hashing" "github.com/SIGBlockchain/project_aurum/internal/mock" "github.com/SIGBlockchain/project_aurum/internal/pendingpool" "github.com/SIGBlockchain/project_aurum/internal/publickey" "github.com/SIGBlockchain/project_aurum/internal/sqlstatements" "github.com/SIGBlockchain/project_aurum/internal/requests" _ "github.com/mattn/go-sqlite3" ) func TestHandleAccountInfoRequest(t *testing.T) { req, err := requests.NewAccountInfoRequest("", "xyz") if err != nil { t.Errorf("failed to create new account info request : %v", err) } rr := httptest.NewRecorder() dbConn, err := sql.Open("sqlite3", constants.AccountsTable) if err != nil { t.Errorf("failed to open database connection : %v", err) } defer func() { if err := dbConn.Close(); err != nil { t.Errorf("failed to close database connection : %v", err) } if err := os.Remove(constants.AccountsTable); err != nil { t.Errorf("failed to remove database : %v", err) } }() statement, _ := dbConn.Prepare(sqlstatements.CREATE_ACCOUNT_BALANCES_TABLE) statement.Exec() var pLock = new(sync.Mutex) // Check empty table var emptyPMap pendingpool.PendingMap handler := http.HandlerFunc(HandleAccountInfoRequest(dbConn, emptyPMap, pLock)) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned with wrong status code: got %v want %v", status, http.StatusNotFound) } body := rr.Body.String() if body != NOT_FOUND_ERR_MSG { t.Errorf("Wrong body message.\nExpexted %s\nFound %s", NOT_FOUND_ERR_MSG, body) } // Insert key into table privateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) encodedSenderPublicKey, _ := publickey.Encode(&privateKey.PublicKey) var walletAddress = hashing.New(encodedSenderPublicKey) err = accountstable.InsertAccountIntoAccountBalanceTable(dbConn, walletAddress, 1337) if err != nil { t.Errorf("failed to insert sender account") } req, err = requests.NewAccountInfoRequest("", hex.EncodeToString(walletAddress)) if err != nil { t.Errorf("failed to create new account info request : %v", err) } rr = httptest.NewRecorder() handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned with wrong status code: got %v want %v", status, http.StatusOK) } type AccountInfo struct { WalletAddress string Balance uint64 StateNonce uint64 } var accInfo AccountInfo if err := json.Unmarshal(rr.Body.Bytes(), &accInfo); err != nil { t.Errorf("failed to unmarshall response body: %v", err) } if accInfo.WalletAddress != hex.EncodeToString(walletAddress) { t.Errorf("failed to get correct wallet address: got %s want %s", accInfo.WalletAddress, walletAddress) } if accInfo.Balance != 1337 { t.Errorf("failed to get correct balance: got %d want %d", accInfo.Balance, 1337) } if accInfo.StateNonce != 0 { t.Errorf("failed to get correct state nonce: got %d want %d", accInfo.StateNonce, 0) } // Pending case privateKey, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) encodedSenderPublicKey, _ = publickey.Encode(&privateKey.PublicKey) walletAddress = hashing.New(encodedSenderPublicKey) pData := pendingpool.NewPendingData(1234, 5678) pMap := pendingpool.NewPendingMap() pMap.Sender[hex.EncodeToString(walletAddress)] = &pData req, err = requests.NewAccountInfoRequest("", hex.EncodeToString(walletAddress)) rr = httptest.NewRecorder() handler = http.HandlerFunc(HandleAccountInfoRequest(dbConn, pMap, pLock)) handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned with wrong status code: got %v want %v", status, http.StatusOK) } if err := json.Unmarshal(rr.Body.Bytes(), &accInfo); err != nil { t.Errorf("failed to unmarshall response body: %v", err) } if accInfo.WalletAddress != hex.EncodeToString(walletAddress) { t.Errorf("failed to get correct wallet address: got %s want %s", accInfo.WalletAddress, walletAddress) } if accInfo.Balance != 1234 { t.Errorf("failed to get correct balance: got %d want %d", accInfo.Balance, 1234) } if accInfo.StateNonce != 5678 { t.Errorf("failed to get correct state nonce: got %d want %d", accInfo.StateNonce, 5678) } } func createContractNReq(version uint16, sender *ecdsa.PrivateKey, recip []byte, bal uint64, nonce uint64) (c *contracts.Contract, r *http.Request, e error) { returnContract, err := contracts.New(version, sender, recip, bal, nonce) if err != nil { return nil, nil, errors.New("failed to make contract : " + err.Error()) } returnContract.Sign(sender) req, err := requests.NewContractRequest("", *returnContract) if err != nil { return nil, nil, errors.New("failed to create new contract request: " + err.Error()) } return returnContract, req, nil } func TestContractRequestHandler(t *testing.T) { dbConn, err := sql.Open("sqlite3", constants.AccountsTable) if err != nil { t.Errorf("failed to open database connection : %v", err) } defer func() { if err := dbConn.Close(); err != nil { t.Errorf("failed to close database connection : %v", err) } if err := os.Remove(constants.AccountsTable); err != nil { t.Errorf("failed to remove database : %v", err) } }() statement, _ := dbConn.Prepare(sqlstatements.CREATE_ACCOUNT_BALANCES_TABLE) statement.Exec() pMap := pendingpool.NewPendingMap() contractChan := make(chan contracts.Contract, 2) pLock := new(sync.Mutex) handler := http.HandlerFunc(HandleContractRequest(dbConn, contractChan, pMap, pLock)) senderPrivateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) encodedSenderPublicKey, _ := publickey.Encode(&senderPrivateKey.PublicKey) encodedSenderStr := hex.EncodeToString(hashing.New(encodedSenderPublicKey)) recipientPrivateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) encodedRecipientPublicKey, _ := publickey.Encode(&recipientPrivateKey.PublicKey) var recipientWalletAddress = hashing.New(encodedRecipientPublicKey) sender2PrivateKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) encodedSender2PublicKey, _ := publickey.Encode(&sender2PrivateKey.PublicKey) encodedSender2Str := hex.EncodeToString(hashing.New(encodedSender2PublicKey)) var walletAddress2 = hashing.New(encodedSender2PublicKey) if err := accountstable.InsertAccountIntoAccountBalanceTable(dbConn, walletAddress2, 5000); err != nil { t.Errorf("failed to insert sender account") } testContract, req, err := createContractNReq(1, senderPrivateKey, recipientWalletAddress, 25, 1) if err != nil { t.Errorf("failed to make contract : %v", err) } testContract2, req2, err := createContractNReq(1, senderPrivateKey, recipientWalletAddress, 59, 2) if err != nil { t.Errorf("failed to make contract : %v", err) } invalidNonceContract, invalidNonceReq, err := createContractNReq(1, senderPrivateKey, recipientWalletAddress, 10, 4) if err != nil { t.Errorf("failed to make contract : %v", err) } invalidBalanceContract, invalidBalanceReq, err := createContractNReq(1, senderPrivateKey, recipientWalletAddress, 100000, 3) if err != nil { t.Errorf("failed to make contract : %v", err) } testContract3, req3, err := createContractNReq(1, senderPrivateKey, recipientWalletAddress, 100, 3) if err != nil { t.Errorf("failed to make contract : %v", err) } diffSenderContract, diffSenderReq, err := createContractNReq(1, sender2PrivateKey, recipientWalletAddress, 10, 1) if err != nil { t.Errorf("failed to make contract : %v", err) } rr := httptest.NewRecorder() handler.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusBadRequest { t.Errorf("handler returned with wrong status code: got %v want %v", status, http.StatusBadRequest) t.Logf("%s", rr.Body.String()) } var walletAddress = hashing.New(encodedSenderPublicKey) if err := accountstable.InsertAccountIntoAccountBalanceTable(dbConn, walletAddress, 1337); err != nil { t.Errorf("failed to insert sender account") } req, err = requests.NewContractRequest("", *testContract) if err != nil { t.Errorf("failed to create new contract request: %v", err) } tests := []struct { name string c *contracts.Contract req *http.Request wantBal uint64 wantNonce uint64 key string status int }{ { "valid contract", testContract, req, 1312, 1, encodedSenderStr, http.StatusOK, }, { "valid contract2", testContract2, req2, 1337 - 25 - 59, 2, encodedSenderStr, http.StatusOK, }, { "invalid nonce contract", invalidNonceContract, invalidNonceReq, 1337 - 25 - 59, 2, encodedSenderStr, http.StatusBadRequest, }, { "invalid balance contract", invalidBalanceContract, invalidBalanceReq, 1337 - 25 - 59, 2, encodedSenderStr, http.StatusBadRequest, }, { "valid contract3", testContract3, req3, 1337 - 25 - 59 - 100, 3, encodedSenderStr, http.StatusOK, }, { "Diff sender contract", diffSenderContract, diffSenderReq, 5000 - 10, 1, encodedSender2Str, http.StatusOK, }, } var wG sync.WaitGroup for i, tt := range tests { t.Run(tt.name, func(t *testing.T) { rr = httptest.NewRecorder() wG.Add(1) go func() { handler.ServeHTTP(rr, tt.req) wG.Done() }() wG.Wait() status := rr.Code if status != tt.status { t.Errorf("handler returned with wrong status code: got %v want %v", status, tt.status) } if status == http.StatusOK { channelledContract := <-contractChan if !tt.c.Equals(channelledContract) { t.Errorf("contracts do not match: got %+v want %+v", *tt.c, channelledContract) } if pMap.Sender[tt.key].PendingBal != tt.wantBal { t.Errorf("balance do not match") } if pMap.Sender[tt.key].PendingNonce != tt.wantNonce { t.Errorf("state nonce do not match") } } if i < 5 { if l := len(pMap.Sender); l != 1 { t.Errorf("number of key-value pairs in map does not match: got %v want %v", l, 1) } } else { if l := len(pMap.Sender); l != 2 { t.Errorf("number of key-value pairs in map does not match: got %v want %v", l, 2) } } }) } } func TestGetJSONBlockByHeight(t *testing.T) { // Arrange tt := []struct { name string expectedBlock block.Block height uint64 e error expectedStatus int }{ { "Valid Block", block.Block{ Version: 3, Height: 584, PreviousHash: []byte("guavapineapplemango1234567890abc"), MerkleRootHash: []byte("grapewatermeloncoconut1emonsabcd"), Timestamp: time.Now().UnixNano(), Data: [][]byte{{12, 13}, {232, 190, 123}, {123}}, DataLen: 3, }, 584, nil, http.StatusOK, }, { "Block not found", block.Block{}, 1043, errors.New("This block was not found"), http.StatusBadRequest, }, } // Create the mock object m := mock.MockBlockFetcher{} for _, test := range tt { t.Run(test.name, func(t *testing.T) { // Configure the mock object // When the Mock object called "FetchBlockByHeight" given the test case's height, // Return that test case's serialized block and corresponding expected error m.When("FetchBlockByHeight").Given(test.height).Return(test.expectedBlock.Serialize(), test.e) // Set up the handler handler := http.HandlerFunc(HandleGetJSONBlockByHeight(m)) // Form the request req, err := requests.GetBlockByHeightRequest(test.height) if err != nil { t.Error(err) } // Set up the recorder for the response rr := httptest.NewRecorder() // Serve the request handler.ServeHTTP(rr, req) // Actual block that is recorded in the response actualJSONBlock := block.JSONBlock{} json.Unmarshal(rr.Body.Bytes(), &actualJSONBlock) // Expected block from the test case expectedJSONBlock := test.expectedBlock.Marshal() // Assert if rr.Code != test.expectedStatus { t.Errorf("Expected HTTP Status OK, recieved: %v", rr.Code) } if rr.Code == http.StatusOK { if !reflect.DeepEqual(expectedJSONBlock, actualJSONBlock) { t.Errorf("Body of response not what expected.\nExpected: %v\nActual: %v", expectedJSONBlock, actualJSONBlock) } } }) } } func TestGetBlockFromResponse(t *testing.T) { // Arrange tt := []struct { name string expectedBlock block.Block height uint64 e error expectedStatus int }{ { "Valid Block", block.Block{ Version: 3, Height: 584, PreviousHash: hashing.New([]byte("0x34")), MerkleRootHash: hashing.New([]byte("0x34")), Timestamp: time.Now().UnixNano(), Data: [][]byte{{12, 13}, {232, 190, 123}, {123}}, DataLen: 3, }, 584, nil, http.StatusOK, }, { "Block not found", block.Block{}, 1043, errors.New("StatusBadRequest"), http.StatusBadRequest, }, } // Create the mock object m := mock.MockBlockFetcher{} for _, test := range tt { t.Run(test.name, func(t *testing.T) { // Configure the mock object // When the Mock object called "FetchBlockByHeight" given the test case's height, // Return that test case's serialized block and corresponding expected error m.When("FetchBlockByHeight").Given(test.height).Return(test.expectedBlock.Serialize(), test.e) // Set up the handler handler := http.HandlerFunc(HandleGetJSONBlockByHeight(m)) // Form the request req, err := requests.GetBlockByHeightRequest(test.height) if err != nil { t.Error(err) } // Set up the recorder for the response rr := httptest.NewRecorder() // Serve the request handler.ServeHTTP(rr, req) // Actual block that is recorded in the response actualBlock, err := GetBlockFromResponse(rr.Result()) // Assert if !test.expectedBlock.Equals(actualBlock) { t.Errorf("Body of response not what expected.\nExpected: %v\nActual: %v", test.expectedBlock, actualBlock) } }) } }
package main import ( "bytes" "flag" "fmt" "os" . "github.com/donnie4w/tfdoc" ) func main() { dir, _ := os.Getwd() tofile := "newfile.thrift" java := "" _go := "" cpp := "" php := "" py := "" flag.StringVar(&dir, "dir", "", "") flag.StringVar(&tofile, "tofile", "newfile.thrift", "") flag.StringVar(&java, "java", "", "java namespace") flag.StringVar(&_go, "go", "", "go namespace") flag.StringVar(&cpp, "cpp", "", "c++ namespace") flag.StringVar(&php, "php", "", "php namespace") flag.StringVar(&py, "py", "", "python namespace") flag.Parse() if dir == "" { fmt.Println("dir is empty") os.Exit(1) } WalkDir(dir, "thrift") if java != "" { java = fmt.Sprint("namespace java ", java) } if _go != "" { _go = fmt.Sprint("namespace go ", _go) } if cpp != "" { cpp = fmt.Sprint("namespace cpp ", cpp) } if php != "" { php = fmt.Sprint("namespace php ", php) } if py != "" { py = fmt.Sprint("namespace py ", py) } CreateNewThrifFile(tofile, joinEndNL(java, _go, cpp, php, py)) } func joinEndNL(ss ...string) string { var buf bytes.Buffer for _, s := range ss { if s != "" { buf.WriteString(s) buf.WriteString("\n") } } return buf.String() }
package ssh import "time" // SSHWorker 可以通过 gossh.SSHWorker 修改 const SSHWorker = 10 // RemoteExec 执行远程命令,需要提供 hosts 列表 func RemoteExec(command string, runUser string, port int, hosts []string, timeOutSecond int64) ([]ExecResult, error) { sshExecAgent := SSHExecAgent{} sshExecAgent.Worker = SSHWorker sshExecAgent.TimeOut = time.Duration(timeOutSecond) * time.Second s, err := sshExecAgent.SSHHostByKey(hosts, port, runUser, command) return s, err }
package main import ( "fmt" "strconv" "texas_real_foods/pkg/utils" relay "texas_real_foods/pkg/mail-relay" ) var ( // create map to house environment variables cfg = utils.NewConfigMapWithValues( map[string]string{ "listen_port": "10785", "listen_address": "0.0.0.0", "utils_api_port": "10847", "utils_api_host": "0.0.0.0", "mail_chimp_api_url": "https://us7.api.mailchimp.com/3.0/", "mail_chimp_api_key": "", "mail_chimp_api_list_id": "", "postgres_url": "postgres://postgres:postgres-dev@192.168.99.100:5432", }, ) ) func getUtilsAPIConfig() utils.APIDependencyConfig { // get configuration for downstream API dependencies and convert to integer apiPortString := cfg.Get("utils_api_port") apiPort, err := strconv.Atoi(apiPortString) if err != nil { panic(fmt.Sprintf("received invalid api port for trf API '%s'", apiPortString)) } return utils.APIDependencyConfig{ Host: cfg.Get("utils_api_host"), Port: &apiPort, Protocol: "http", } } func getMailChimpConfig() relay.MailChimpConfig { // get configuration for downstream API dependencies and convert to integer return relay.MailChimpConfig{ APIKey: cfg.Get("mail_chimp_api_key"), APIUrl: cfg.Get("mail_chimp_api_url"), ListID: cfg.Get("mail_chimp_api_list_id"), } } func main() { cfg.ConfigureLogging() // get listen port from environment variables and start new server listenPort, err := strconv.Atoi(cfg.Get("listen_port")) if err != nil { panic(fmt.Sprintf("invalid listen port '%s'", cfg.Get("listen_port"))) } // generate new postgres persistence persistence := relay.NewPersistence(cfg.Get("postgres_url")) conn, err := persistence.Connect() if err != nil { panic(fmt.Errorf("unable to connect to postgres server: %+v", err)) } defer conn.Close() // generate new mail server and run mailServer := relay.NewMailRelay(getMailChimpConfig(), getUtilsAPIConfig(), persistence) mailServer.Run(fmt.Sprintf(":%d", listenPort)) }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/12/11 9:00 上午 # @File : lt_12_整数转罗马数字_test.go.go # @Description : # @Attention : */ package hot100 import ( "fmt" "testing" ) func Test_intToRoman(t *testing.T) { fmt.Println(intToRoman(1994)) }
package main import ( "errors" ) type user struct { Email string Friends []string QueryStatus bool Subscribers []string } func (u *user) createFriends() error { if len(u.Friends) != 2 { return errors.New("incorrect number of friends") } for _, user := range u.Friends { if !isEmailValid(user) { return errors.New("invalid email being submitted") } } if u.Friends[0] == u.Friends[1] { return errors.New("cannot be friends with oneself") } exists, relationships, err := ifExistsRelationship(u.Friends) if err != nil { return err } if exists { if isBlocked, err := relationships.isBlocked(); isBlocked { return err } if isFriend, err := relationships.isFriend(); isFriend { return err } if isSubscribed, err := relationships.isSubscribed(); isSubscribed { return err } } return createFriends(u.Friends) } func (u *user) getFriends() error { if !isEmailValid(u.Email) { return errors.New("invalid user") } friends, err := getFriendsList(u.Email) if err != nil { return err } u.Friends = friends return nil } func (u *user) getCommonFriends() error { if len(u.Friends) != 2 { return errors.New("incorrect number of friends") } for _, user := range u.Friends { if !isEmailValid(user) { return errors.New("invalid user") } } exists, relationships, err := ifExistsRelationship(u.Friends) if err != nil { return err } if exists { if isBlocked, err := relationships.isBlocked(); isBlocked { return err } } friends, err := getCommonFriendsList(u.Friends) if err != nil { return err } u.Friends = friends return nil } func (u *user) getSubscribers() { } func (u *user) getQueryStatus() bool { return u.QueryStatus } func (u *user) listFriends() []string { return u.Friends } func (u *user) getCount() int { return len(u.Friends) } func (u *user) listSubscribers() []string { return u.Subscribers }
// Copyright 2021 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "context" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" alphapb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/compute/alpha/compute_alpha_go_proto" emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto" "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute/alpha" ) // Server implements the gRPC interface for Interconnect. type InterconnectServer struct{} // ProtoToInterconnectLinkTypeEnum converts a InterconnectLinkTypeEnum enum from its proto representation. func ProtoToComputeAlphaInterconnectLinkTypeEnum(e alphapb.ComputeAlphaInterconnectLinkTypeEnum) *alpha.InterconnectLinkTypeEnum { if e == 0 { return nil } if n, ok := alphapb.ComputeAlphaInterconnectLinkTypeEnum_name[int32(e)]; ok { e := alpha.InterconnectLinkTypeEnum(n[len("ComputeAlphaInterconnectLinkTypeEnum"):]) return &e } return nil } // ProtoToInterconnectInterconnectTypeEnum converts a InterconnectInterconnectTypeEnum enum from its proto representation. func ProtoToComputeAlphaInterconnectInterconnectTypeEnum(e alphapb.ComputeAlphaInterconnectInterconnectTypeEnum) *alpha.InterconnectInterconnectTypeEnum { if e == 0 { return nil } if n, ok := alphapb.ComputeAlphaInterconnectInterconnectTypeEnum_name[int32(e)]; ok { e := alpha.InterconnectInterconnectTypeEnum(n[len("ComputeAlphaInterconnectInterconnectTypeEnum"):]) return &e } return nil } // ProtoToInterconnectOperationalStatusEnum converts a InterconnectOperationalStatusEnum enum from its proto representation. func ProtoToComputeAlphaInterconnectOperationalStatusEnum(e alphapb.ComputeAlphaInterconnectOperationalStatusEnum) *alpha.InterconnectOperationalStatusEnum { if e == 0 { return nil } if n, ok := alphapb.ComputeAlphaInterconnectOperationalStatusEnum_name[int32(e)]; ok { e := alpha.InterconnectOperationalStatusEnum(n[len("ComputeAlphaInterconnectOperationalStatusEnum"):]) return &e } return nil } // ProtoToInterconnectExpectedOutagesSourceEnum converts a InterconnectExpectedOutagesSourceEnum enum from its proto representation. func ProtoToComputeAlphaInterconnectExpectedOutagesSourceEnum(e alphapb.ComputeAlphaInterconnectExpectedOutagesSourceEnum) *alpha.InterconnectExpectedOutagesSourceEnum { if e == 0 { return nil } if n, ok := alphapb.ComputeAlphaInterconnectExpectedOutagesSourceEnum_name[int32(e)]; ok { e := alpha.InterconnectExpectedOutagesSourceEnum(n[len("ComputeAlphaInterconnectExpectedOutagesSourceEnum"):]) return &e } return nil } // ProtoToInterconnectExpectedOutagesStateEnum converts a InterconnectExpectedOutagesStateEnum enum from its proto representation. func ProtoToComputeAlphaInterconnectExpectedOutagesStateEnum(e alphapb.ComputeAlphaInterconnectExpectedOutagesStateEnum) *alpha.InterconnectExpectedOutagesStateEnum { if e == 0 { return nil } if n, ok := alphapb.ComputeAlphaInterconnectExpectedOutagesStateEnum_name[int32(e)]; ok { e := alpha.InterconnectExpectedOutagesStateEnum(n[len("ComputeAlphaInterconnectExpectedOutagesStateEnum"):]) return &e } return nil } // ProtoToInterconnectExpectedOutagesIssueTypeEnum converts a InterconnectExpectedOutagesIssueTypeEnum enum from its proto representation. func ProtoToComputeAlphaInterconnectExpectedOutagesIssueTypeEnum(e alphapb.ComputeAlphaInterconnectExpectedOutagesIssueTypeEnum) *alpha.InterconnectExpectedOutagesIssueTypeEnum { if e == 0 { return nil } if n, ok := alphapb.ComputeAlphaInterconnectExpectedOutagesIssueTypeEnum_name[int32(e)]; ok { e := alpha.InterconnectExpectedOutagesIssueTypeEnum(n[len("ComputeAlphaInterconnectExpectedOutagesIssueTypeEnum"):]) return &e } return nil } // ProtoToInterconnectStateEnum converts a InterconnectStateEnum enum from its proto representation. func ProtoToComputeAlphaInterconnectStateEnum(e alphapb.ComputeAlphaInterconnectStateEnum) *alpha.InterconnectStateEnum { if e == 0 { return nil } if n, ok := alphapb.ComputeAlphaInterconnectStateEnum_name[int32(e)]; ok { e := alpha.InterconnectStateEnum(n[len("ComputeAlphaInterconnectStateEnum"):]) return &e } return nil } // ProtoToInterconnectExpectedOutages converts a InterconnectExpectedOutages object from its proto representation. func ProtoToComputeAlphaInterconnectExpectedOutages(p *alphapb.ComputeAlphaInterconnectExpectedOutages) *alpha.InterconnectExpectedOutages { if p == nil { return nil } obj := &alpha.InterconnectExpectedOutages{ Name: dcl.StringOrNil(p.GetName()), Description: dcl.StringOrNil(p.GetDescription()), Source: ProtoToComputeAlphaInterconnectExpectedOutagesSourceEnum(p.GetSource()), State: ProtoToComputeAlphaInterconnectExpectedOutagesStateEnum(p.GetState()), IssueType: ProtoToComputeAlphaInterconnectExpectedOutagesIssueTypeEnum(p.GetIssueType()), StartTime: dcl.Int64OrNil(p.GetStartTime()), EndTime: dcl.Int64OrNil(p.GetEndTime()), } for _, r := range p.GetAffectedCircuits() { obj.AffectedCircuits = append(obj.AffectedCircuits, r) } return obj } // ProtoToInterconnectCircuitInfos converts a InterconnectCircuitInfos object from its proto representation. func ProtoToComputeAlphaInterconnectCircuitInfos(p *alphapb.ComputeAlphaInterconnectCircuitInfos) *alpha.InterconnectCircuitInfos { if p == nil { return nil } obj := &alpha.InterconnectCircuitInfos{ GoogleCircuitId: dcl.StringOrNil(p.GetGoogleCircuitId()), GoogleDemarcId: dcl.StringOrNil(p.GetGoogleDemarcId()), CustomerDemarcId: dcl.StringOrNil(p.GetCustomerDemarcId()), } return obj } // ProtoToInterconnect converts a Interconnect resource from its proto representation. func ProtoToInterconnect(p *alphapb.ComputeAlphaInterconnect) *alpha.Interconnect { obj := &alpha.Interconnect{ Description: dcl.StringOrNil(p.GetDescription()), SelfLink: dcl.StringOrNil(p.GetSelfLink()), Id: dcl.Int64OrNil(p.GetId()), Name: dcl.StringOrNil(p.GetName()), Location: dcl.StringOrNil(p.GetLocation()), LinkType: ProtoToComputeAlphaInterconnectLinkTypeEnum(p.GetLinkType()), RequestedLinkCount: dcl.Int64OrNil(p.GetRequestedLinkCount()), InterconnectType: ProtoToComputeAlphaInterconnectInterconnectTypeEnum(p.GetInterconnectType()), AdminEnabled: dcl.Bool(p.GetAdminEnabled()), NocContactEmail: dcl.StringOrNil(p.GetNocContactEmail()), CustomerName: dcl.StringOrNil(p.GetCustomerName()), OperationalStatus: ProtoToComputeAlphaInterconnectOperationalStatusEnum(p.GetOperationalStatus()), ProvisionedLinkCount: dcl.Int64OrNil(p.GetProvisionedLinkCount()), PeerIPAddress: dcl.StringOrNil(p.GetPeerIpAddress()), GoogleIPAddress: dcl.StringOrNil(p.GetGoogleIpAddress()), GoogleReferenceId: dcl.StringOrNil(p.GetGoogleReferenceId()), State: ProtoToComputeAlphaInterconnectStateEnum(p.GetState()), Project: dcl.StringOrNil(p.GetProject()), } for _, r := range p.GetInterconnectAttachments() { obj.InterconnectAttachments = append(obj.InterconnectAttachments, r) } for _, r := range p.GetExpectedOutages() { obj.ExpectedOutages = append(obj.ExpectedOutages, *ProtoToComputeAlphaInterconnectExpectedOutages(r)) } for _, r := range p.GetCircuitInfos() { obj.CircuitInfos = append(obj.CircuitInfos, *ProtoToComputeAlphaInterconnectCircuitInfos(r)) } return obj } // InterconnectLinkTypeEnumToProto converts a InterconnectLinkTypeEnum enum to its proto representation. func ComputeAlphaInterconnectLinkTypeEnumToProto(e *alpha.InterconnectLinkTypeEnum) alphapb.ComputeAlphaInterconnectLinkTypeEnum { if e == nil { return alphapb.ComputeAlphaInterconnectLinkTypeEnum(0) } if v, ok := alphapb.ComputeAlphaInterconnectLinkTypeEnum_value["InterconnectLinkTypeEnum"+string(*e)]; ok { return alphapb.ComputeAlphaInterconnectLinkTypeEnum(v) } return alphapb.ComputeAlphaInterconnectLinkTypeEnum(0) } // InterconnectInterconnectTypeEnumToProto converts a InterconnectInterconnectTypeEnum enum to its proto representation. func ComputeAlphaInterconnectInterconnectTypeEnumToProto(e *alpha.InterconnectInterconnectTypeEnum) alphapb.ComputeAlphaInterconnectInterconnectTypeEnum { if e == nil { return alphapb.ComputeAlphaInterconnectInterconnectTypeEnum(0) } if v, ok := alphapb.ComputeAlphaInterconnectInterconnectTypeEnum_value["InterconnectInterconnectTypeEnum"+string(*e)]; ok { return alphapb.ComputeAlphaInterconnectInterconnectTypeEnum(v) } return alphapb.ComputeAlphaInterconnectInterconnectTypeEnum(0) } // InterconnectOperationalStatusEnumToProto converts a InterconnectOperationalStatusEnum enum to its proto representation. func ComputeAlphaInterconnectOperationalStatusEnumToProto(e *alpha.InterconnectOperationalStatusEnum) alphapb.ComputeAlphaInterconnectOperationalStatusEnum { if e == nil { return alphapb.ComputeAlphaInterconnectOperationalStatusEnum(0) } if v, ok := alphapb.ComputeAlphaInterconnectOperationalStatusEnum_value["InterconnectOperationalStatusEnum"+string(*e)]; ok { return alphapb.ComputeAlphaInterconnectOperationalStatusEnum(v) } return alphapb.ComputeAlphaInterconnectOperationalStatusEnum(0) } // InterconnectExpectedOutagesSourceEnumToProto converts a InterconnectExpectedOutagesSourceEnum enum to its proto representation. func ComputeAlphaInterconnectExpectedOutagesSourceEnumToProto(e *alpha.InterconnectExpectedOutagesSourceEnum) alphapb.ComputeAlphaInterconnectExpectedOutagesSourceEnum { if e == nil { return alphapb.ComputeAlphaInterconnectExpectedOutagesSourceEnum(0) } if v, ok := alphapb.ComputeAlphaInterconnectExpectedOutagesSourceEnum_value["InterconnectExpectedOutagesSourceEnum"+string(*e)]; ok { return alphapb.ComputeAlphaInterconnectExpectedOutagesSourceEnum(v) } return alphapb.ComputeAlphaInterconnectExpectedOutagesSourceEnum(0) } // InterconnectExpectedOutagesStateEnumToProto converts a InterconnectExpectedOutagesStateEnum enum to its proto representation. func ComputeAlphaInterconnectExpectedOutagesStateEnumToProto(e *alpha.InterconnectExpectedOutagesStateEnum) alphapb.ComputeAlphaInterconnectExpectedOutagesStateEnum { if e == nil { return alphapb.ComputeAlphaInterconnectExpectedOutagesStateEnum(0) } if v, ok := alphapb.ComputeAlphaInterconnectExpectedOutagesStateEnum_value["InterconnectExpectedOutagesStateEnum"+string(*e)]; ok { return alphapb.ComputeAlphaInterconnectExpectedOutagesStateEnum(v) } return alphapb.ComputeAlphaInterconnectExpectedOutagesStateEnum(0) } // InterconnectExpectedOutagesIssueTypeEnumToProto converts a InterconnectExpectedOutagesIssueTypeEnum enum to its proto representation. func ComputeAlphaInterconnectExpectedOutagesIssueTypeEnumToProto(e *alpha.InterconnectExpectedOutagesIssueTypeEnum) alphapb.ComputeAlphaInterconnectExpectedOutagesIssueTypeEnum { if e == nil { return alphapb.ComputeAlphaInterconnectExpectedOutagesIssueTypeEnum(0) } if v, ok := alphapb.ComputeAlphaInterconnectExpectedOutagesIssueTypeEnum_value["InterconnectExpectedOutagesIssueTypeEnum"+string(*e)]; ok { return alphapb.ComputeAlphaInterconnectExpectedOutagesIssueTypeEnum(v) } return alphapb.ComputeAlphaInterconnectExpectedOutagesIssueTypeEnum(0) } // InterconnectStateEnumToProto converts a InterconnectStateEnum enum to its proto representation. func ComputeAlphaInterconnectStateEnumToProto(e *alpha.InterconnectStateEnum) alphapb.ComputeAlphaInterconnectStateEnum { if e == nil { return alphapb.ComputeAlphaInterconnectStateEnum(0) } if v, ok := alphapb.ComputeAlphaInterconnectStateEnum_value["InterconnectStateEnum"+string(*e)]; ok { return alphapb.ComputeAlphaInterconnectStateEnum(v) } return alphapb.ComputeAlphaInterconnectStateEnum(0) } // InterconnectExpectedOutagesToProto converts a InterconnectExpectedOutages object to its proto representation. func ComputeAlphaInterconnectExpectedOutagesToProto(o *alpha.InterconnectExpectedOutages) *alphapb.ComputeAlphaInterconnectExpectedOutages { if o == nil { return nil } p := &alphapb.ComputeAlphaInterconnectExpectedOutages{} p.SetName(dcl.ValueOrEmptyString(o.Name)) p.SetDescription(dcl.ValueOrEmptyString(o.Description)) p.SetSource(ComputeAlphaInterconnectExpectedOutagesSourceEnumToProto(o.Source)) p.SetState(ComputeAlphaInterconnectExpectedOutagesStateEnumToProto(o.State)) p.SetIssueType(ComputeAlphaInterconnectExpectedOutagesIssueTypeEnumToProto(o.IssueType)) p.SetStartTime(dcl.ValueOrEmptyInt64(o.StartTime)) p.SetEndTime(dcl.ValueOrEmptyInt64(o.EndTime)) sAffectedCircuits := make([]string, len(o.AffectedCircuits)) for i, r := range o.AffectedCircuits { sAffectedCircuits[i] = r } p.SetAffectedCircuits(sAffectedCircuits) return p } // InterconnectCircuitInfosToProto converts a InterconnectCircuitInfos object to its proto representation. func ComputeAlphaInterconnectCircuitInfosToProto(o *alpha.InterconnectCircuitInfos) *alphapb.ComputeAlphaInterconnectCircuitInfos { if o == nil { return nil } p := &alphapb.ComputeAlphaInterconnectCircuitInfos{} p.SetGoogleCircuitId(dcl.ValueOrEmptyString(o.GoogleCircuitId)) p.SetGoogleDemarcId(dcl.ValueOrEmptyString(o.GoogleDemarcId)) p.SetCustomerDemarcId(dcl.ValueOrEmptyString(o.CustomerDemarcId)) return p } // InterconnectToProto converts a Interconnect resource to its proto representation. func InterconnectToProto(resource *alpha.Interconnect) *alphapb.ComputeAlphaInterconnect { p := &alphapb.ComputeAlphaInterconnect{} p.SetDescription(dcl.ValueOrEmptyString(resource.Description)) p.SetSelfLink(dcl.ValueOrEmptyString(resource.SelfLink)) p.SetId(dcl.ValueOrEmptyInt64(resource.Id)) p.SetName(dcl.ValueOrEmptyString(resource.Name)) p.SetLocation(dcl.ValueOrEmptyString(resource.Location)) p.SetLinkType(ComputeAlphaInterconnectLinkTypeEnumToProto(resource.LinkType)) p.SetRequestedLinkCount(dcl.ValueOrEmptyInt64(resource.RequestedLinkCount)) p.SetInterconnectType(ComputeAlphaInterconnectInterconnectTypeEnumToProto(resource.InterconnectType)) p.SetAdminEnabled(dcl.ValueOrEmptyBool(resource.AdminEnabled)) p.SetNocContactEmail(dcl.ValueOrEmptyString(resource.NocContactEmail)) p.SetCustomerName(dcl.ValueOrEmptyString(resource.CustomerName)) p.SetOperationalStatus(ComputeAlphaInterconnectOperationalStatusEnumToProto(resource.OperationalStatus)) p.SetProvisionedLinkCount(dcl.ValueOrEmptyInt64(resource.ProvisionedLinkCount)) p.SetPeerIpAddress(dcl.ValueOrEmptyString(resource.PeerIPAddress)) p.SetGoogleIpAddress(dcl.ValueOrEmptyString(resource.GoogleIPAddress)) p.SetGoogleReferenceId(dcl.ValueOrEmptyString(resource.GoogleReferenceId)) p.SetState(ComputeAlphaInterconnectStateEnumToProto(resource.State)) p.SetProject(dcl.ValueOrEmptyString(resource.Project)) sInterconnectAttachments := make([]string, len(resource.InterconnectAttachments)) for i, r := range resource.InterconnectAttachments { sInterconnectAttachments[i] = r } p.SetInterconnectAttachments(sInterconnectAttachments) sExpectedOutages := make([]*alphapb.ComputeAlphaInterconnectExpectedOutages, len(resource.ExpectedOutages)) for i, r := range resource.ExpectedOutages { sExpectedOutages[i] = ComputeAlphaInterconnectExpectedOutagesToProto(&r) } p.SetExpectedOutages(sExpectedOutages) sCircuitInfos := make([]*alphapb.ComputeAlphaInterconnectCircuitInfos, len(resource.CircuitInfos)) for i, r := range resource.CircuitInfos { sCircuitInfos[i] = ComputeAlphaInterconnectCircuitInfosToProto(&r) } p.SetCircuitInfos(sCircuitInfos) return p } // applyInterconnect handles the gRPC request by passing it to the underlying Interconnect Apply() method. func (s *InterconnectServer) applyInterconnect(ctx context.Context, c *alpha.Client, request *alphapb.ApplyComputeAlphaInterconnectRequest) (*alphapb.ComputeAlphaInterconnect, error) { p := ProtoToInterconnect(request.GetResource()) res, err := c.ApplyInterconnect(ctx, p) if err != nil { return nil, err } r := InterconnectToProto(res) return r, nil } // applyComputeAlphaInterconnect handles the gRPC request by passing it to the underlying Interconnect Apply() method. func (s *InterconnectServer) ApplyComputeAlphaInterconnect(ctx context.Context, request *alphapb.ApplyComputeAlphaInterconnectRequest) (*alphapb.ComputeAlphaInterconnect, error) { cl, err := createConfigInterconnect(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return s.applyInterconnect(ctx, cl, request) } // DeleteInterconnect handles the gRPC request by passing it to the underlying Interconnect Delete() method. func (s *InterconnectServer) DeleteComputeAlphaInterconnect(ctx context.Context, request *alphapb.DeleteComputeAlphaInterconnectRequest) (*emptypb.Empty, error) { cl, err := createConfigInterconnect(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return &emptypb.Empty{}, cl.DeleteInterconnect(ctx, ProtoToInterconnect(request.GetResource())) } // ListComputeAlphaInterconnect handles the gRPC request by passing it to the underlying InterconnectList() method. func (s *InterconnectServer) ListComputeAlphaInterconnect(ctx context.Context, request *alphapb.ListComputeAlphaInterconnectRequest) (*alphapb.ListComputeAlphaInterconnectResponse, error) { cl, err := createConfigInterconnect(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } resources, err := cl.ListInterconnect(ctx, request.GetProject()) if err != nil { return nil, err } var protos []*alphapb.ComputeAlphaInterconnect for _, r := range resources.Items { rp := InterconnectToProto(r) protos = append(protos, rp) } p := &alphapb.ListComputeAlphaInterconnectResponse{} p.SetItems(protos) return p, nil } func createConfigInterconnect(ctx context.Context, service_account_file string) (*alpha.Client, error) { conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file)) return alpha.NewClient(conf), nil }
package present // Entry is a struct which connects the Present and it's Recipient type Entry struct { Present Recipient } // Present represents a present with it's various attributes type Present struct { Brand string Name string Store string Cost float64 } // Recipient represents a Recipient of a present with it's first and last name type Recipient struct { FirstName string LastName string } func (r *Recipient) ToStringArray() *[]string { return &[]string{r.FirstName, r.LastName} } func (p *Present) ToStringArray() *[]string { // TODO: Float to string var cost string return &[]string{p.Brand, p.Name, p.Store, cost} }
package main import ( "bytes" "encoding/json" "fmt" "github.com/prometheus/common/model" "github.com/neuron-digital/go-prometheus-tgbot/jira" "gopkg.in/alecthomas/kingpin.v2" "gopkg.in/telegram-bot-api.v4" "html/template" "io/ioutil" "log" "net/http" "sort" "strings" "time" "sync" ) var ( host = kingpin.Flag("host", "HTTP server host").Short('h').Default("0.0.0.0").String() port = kingpin.Flag("port", "HTTP server port").Short('p').Default("8080").Int() chat = kingpin.Flag("chat", "Telegram chat ID").Required().Int64() token = kingpin.Flag("token", "Telegram TOKEN").Required().String() pollUpdates = kingpin.Flag("poll", "Poll telegram updates").Default("false").Bool() alertManagerEndpoint = kingpin.Flag("alert-manager", "Alertmanager endpoint").String() templatesPath = kingpin.Flag("templates-path", "Path to GO templates").Default("/opt/tgbot/templates").ExistingDir() zeroDate = time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC) muted = zeroDate appStartTime = time.Now() ) type AlertManagerRequest struct { Alerts model.Alerts `json:"alerts"` } type AlertsResponse struct { Status string `json:"status"` As model.Alerts `json:"data"` } func execTelegramCommands(updates tgbotapi.UpdatesChannel, messages chan<- BotMessage) { for update := range updates { if update.Message == nil || update.Message.Time().Before(appStartTime) { continue } if update.Message.IsCommand() { switch update.Message.Command() { case "mute": args := strings.TrimSpace(update.Message.CommandArguments()) if args == "" { args = "5m" } duration, err := time.ParseDuration(args) if err == nil { messages <- BotMessage{ Chat: update.Message.Chat.ID, Text: mute(duration), ParseMode: tgbotapi.ModeHTML, Mutable: false, } go func(m time.Time) { time.Sleep(duration) if muted == m { messages <- BotMessage{ Chat: update.Message.Chat.ID, Text: unmute(), ParseMode: tgbotapi.ModeHTML, Mutable: false, } } }(muted) } else { messages <- BotMessage{ Chat: update.Message.Chat.ID, Text: fmt.Sprintf("<b>%s</b>", err.Error()), ParseMode: tgbotapi.ModeHTML, Mutable: false, } } case "unmute": messages <- BotMessage{ Chat: update.Message.Chat.ID, Text: unmute(), ParseMode: tgbotapi.ModeHTML, Mutable: false, } case "alerts": if alerts, err := composeAlertsMessages(); err == nil { for _, alert := range alerts { messages <- BotMessage{ Chat: update.Message.Chat.ID, Text: alert, ParseMode: tgbotapi.ModeHTML, Mutable: false, } } } else { messages <- BotMessage{ Chat: update.Message.Chat.ID, Text: err.Error(), ParseMode: tgbotapi.ModeHTML, Mutable: false, } } } } } } func mute(duration time.Duration) string { muted = time.Now().Add(duration) return fmt.Sprintf(`<b>Muted until %s</b>`, muted.Format("02.01.2006 15:04:05 MST")) } func unmute() string { if muted.IsZero() { return "<b>Oh, I am not muted!</b>" } muted = zeroDate return "<b>Unmuted</b>" } type TemplateName string // composeAlertsMessages fetch GET alerts from alertsmanager and render them by template. // Alerts are grouped by alert label "job". func composeAlertsMessages() (messages []string, err error) { defer func() { if r := recover(); r != nil { messages, err = nil, r.(error) } }() endpoint := strings.TrimRight(*alertManagerEndpoint, "/") alertsLocation := fmt.Sprintf("%s/api/v1/alerts", endpoint) resp, err := http.Get(alertsLocation) if err != nil { panic(err) } body, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } var alertsResponse AlertsResponse if err := json.Unmarshal(body, &alertsResponse); err != nil { panic(err) } // Group by job: map[job][]alert alerts := make(map[string][]string) for _, alert := range alertsResponse.As { alert.Status() text, err := renderAlert(alert, TemplateName("alert.html")) if err != nil { text = err.Error() } job := string(alert.Labels[model.LabelName("job")]) if _, ok := alerts[job]; ok { alerts[job] = append(alerts[job], text) } else { alerts[job] = []string{text} } } // Get jobs to sort by them var jobs []string for job, _ := range alerts { jobs = append(jobs, job) } sort.Strings(jobs) // Messages sorted by job for _, job := range jobs { a := alerts[job] messages = append(messages, fmt.Sprintf("\n<b>%s:</b>", strings.Replace(strings.ToUpper(job), "_", " ", len(job)))) for _, text := range a { messages = append(messages, text) } } return []string{strings.Join(messages, "\n")}, nil } // renderAlert renders alert template func renderAlert(a *model.Alert, tpl TemplateName) (string, error) { var text bytes.Buffer t, err := template.New("").Funcs(template.FuncMap{ "label": func(s model.LabelSet, l string) string { return string(s[model.LabelName(l)]) }}).ParseFiles(fmt.Sprintf("%s/%s", *templatesPath, tpl)) if err != nil { return "", err } if execute_err := t.ExecuteTemplate(&text, string(tpl), a); execute_err != nil { return "", execute_err } return text.String(), nil } // sendTelegramMessages send all channel messages to telegram channel func sendTelegramMessages(bot *tgbotapi.BotAPI, messages <-chan BotMessage) { for msg := range messages { if msg.Mutable && time.Now().Before(muted) { continue } m := tgbotapi.NewMessage(*chat, msg.Text) m.ParseMode = msg.ParseMode m.DisableWebPagePreview = true bot.Send(m) } } func initBot() *tgbotapi.BotAPI { bot, err := tgbotapi.NewBotAPI(*token) if err != nil { log.Panic(err) } log.Printf("Telegram bot authorized: %s", bot.Self.UserName) return bot } func initTelegramUpdatesChannel(bot *tgbotapi.BotAPI) tgbotapi.UpdatesChannel { u := tgbotapi.NewUpdate(0) u.Timeout = 60 updates, _ := bot.GetUpdatesChan(u) return updates } type View struct { channel chan BotMessage } func (view *View) handleJira(w http.ResponseWriter, r *http.Request) { event := jira.Event{} body, err := ioutil.ReadAll(r.Body) if err != nil { log.Print(err) } else { json.Unmarshal(body, &event) view.channel <- BotMessage{ Chat: *chat, Text: event.ComposeMessage(), ParseMode: tgbotapi.ModeHTML, Mutable: true, } } } func (view *View) handleAlerts(w http.ResponseWriter, r *http.Request) { templateName := strings.TrimSpace(r.URL.Query().Get("template")) if templateName == "" { templateName = "alert.html" } processAlert := func(alert *model.Alert, wg *sync.WaitGroup) { text, err := renderAlert(alert, TemplateName(templateName)) if err == nil { view.channel <- BotMessage{ Chat: *chat, Text: text, ParseMode: tgbotapi.ModeHTML, Mutable: true, } } else { log.Print(err) } wg.Done() } var amRequest AlertManagerRequest body, err := ioutil.ReadAll(r.Body) log.Println("Alertmanager request body:") log.Print(string(body)) if err != nil { log.Print(err) } else { err := json.Unmarshal(body, &amRequest) if err != nil { log.Print(err) } else { log.Printf("Processing %d alerts...\n", len(amRequest.Alerts)) wg := sync.WaitGroup{} wg.Add(len(amRequest.Alerts)) for _, alert := range amRequest.Alerts { go processAlert(alert, &wg) } wg.Wait() log.Println("Processing alerts done.") } } } func (view *View) sendMessage(w http.ResponseWriter, r *http.Request) { message := r.FormValue("message") if len(message) > 0 { view.channel <- BotMessage{ Chat: *chat, Text: message, ParseMode: tgbotapi.ModeHTML, Mutable: true, } } } type BotMessage struct { Chat int64 Text string ParseMode string Mutable bool } func main() { kingpin.Parse() // Telegram bot bot := initBot() // Messages to send to telegram channel messages := make(chan BotMessage, 10) go sendTelegramMessages(bot, messages) log.Printf("Poll updates: %t", *pollUpdates) if *pollUpdates { go execTelegramCommands(initTelegramUpdatesChannel(bot), messages) } view := View{channel: messages} http.HandleFunc("/api/v1/alert", view.handleAlerts) http.HandleFunc("/api/v1/message", view.sendMessage) http.HandleFunc("/api/v1/jira", view.handleJira) log.Printf(`Listen %s:%d`, *host, *port) http.ListenAndServe(fmt.Sprintf("%s:%d", *host, *port), nil) }
package service import ( "github.com/container-storage-interface/spec/lib/go/csi" "github.com/golang/protobuf/ptypes/wrappers" "github.com/ovirt/csi-driver/internal/ovirt" "golang.org/x/net/context" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "k8s.io/klog" ) //IdentityService of ovirt-csi-driver type IdentityService struct { ovirtClient ovirt.Client } //GetPluginInfo returns the vendor name and version - set in build time func (i *IdentityService) GetPluginInfo(context.Context, *csi.GetPluginInfoRequest) (*csi.GetPluginInfoResponse, error) { return &csi.GetPluginInfoResponse{ Name: VendorName, VendorVersion: VendorVersion, }, nil } //GetPluginCapabilities declares the plugins capabilities func (i *IdentityService) GetPluginCapabilities(context.Context, *csi.GetPluginCapabilitiesRequest) (*csi.GetPluginCapabilitiesResponse, error) { return &csi.GetPluginCapabilitiesResponse{ Capabilities: []*csi.PluginCapability{ { Type: &csi.PluginCapability_Service_{ Service: &csi.PluginCapability_Service{ Type: csi.PluginCapability_Service_CONTROLLER_SERVICE, }, }, }, }, }, nil } // Probe checks the state of the connection to ovirt-engine func (i *IdentityService) Probe(ctx context.Context, request *csi.ProbeRequest) (*csi.ProbeResponse, error) { c, err := i.ovirtClient.GetConnection() if err != nil { klog.Errorf("Could not get connection %v", err) return nil, status.Error(codes.FailedPrecondition, "Could not get connection to ovirt-engine") } if err := c.Test(); err != nil { klog.Errorf("Connection test failed %v", err) return nil, status.Error(codes.FailedPrecondition, "Could not get connection to ovirt-engine") } return &csi.ProbeResponse{Ready: &wrappers.BoolValue{Value: true}}, nil }
package main import ( "github.com/stretchr/testify/assert" "log" "testing" ) // //func Test_ConvertString(t *testing.T) { // tcs := []struct { // Width int // N int // Answer string // }{ // {3, 1, "001"}, // } // // for _, tc := range tcs { // t.Run("PASS", func(t *testing.T) { // res := ConvertString(tc.Width, tc.N) // assert.Equal(t, tc.Answer, res) // }) // } //} //func Test_NextPermutation(t *testing.T) { // tcs := []struct { // S []string // Ret bool // }{ // {[]string{"0", "1", "2"}, true}, // } // // for _, tc := range tcs { // t.Run("PASS", func(t *testing.T) { // log.Println(tc.S) // for NextPermutation(tc.S) { // } // }) // } //} func Test_Permutation(t *testing.T) { tcs := []struct { Data []string Depth int N int R int Res *[][]string }{ //{[]string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}, 0, 10, 3, &[][]string{}}, {[]string{"a", "b", "c", "d"}, 0, 4, 3, &[][]string{}}, } for _, tc := range tcs { t.Run("PASS", func(t *testing.T) { //Permutation(tc.Data, tc.Depth, tc.N, tc.R, tc.Res) Permutation(tc.Data, tc.Depth, tc.N, tc.R) log.Printf("%+v", tc.Res) }) } } func Test_Check(t *testing.T) { tcs := []struct { Signs []string Width int Num []string Answer bool }{ {[]string{"<", ">"}, 2, []string{"8", "9", "7"}, true}, //{[]string{"<", ">"}, 2, []string{"8", "9", "8"}, false}, } for _, tc := range tcs { t.Run("PASS", func(t *testing.T) { res := Check(tc.Signs, tc.Width, tc.Num) assert.Equal(t, tc.Answer, res) }) } } func Test_Solve2529(t *testing.T) { tcs := []struct { Num int Signs string Max string Min string }{ {2, "< >", "897", "021"}, {9, "> < < < > > > < <", "9567843012", "1023765489"}, } for _, tc := range tcs { t.Run("PASS", func(t *testing.T) { vmax, vmin := Solve(tc.Num, tc.Signs) assert.Equal(t, tc.Max, vmax) assert.Equal(t, tc.Min, vmin) }) } } func Test_Min(t *testing.T) { t.Run("PASS", func(t *testing.T) { res := Min([]string{"021"}, []string{"897"}) log.Println("VALUE!!:", res) resMax := Max([]string{"021"}, []string{"897"}) log.Println("VALUE!!:", resMax) }) }
package pgeo import ( "database/sql/driver" "errors" "fmt" "strconv" "strings" ) // Circle is represented by a center point and radius. type Circle struct { Point Radius float64 `json:"radius"` } // Value for the database func (c Circle) Value() (driver.Value, error) { return valueCircle(c) } // Scan from sql query func (c *Circle) Scan(src interface{}) error { return scanCircle(c, src) } func valueCircle(c Circle) (driver.Value, error) { return fmt.Sprintf(`<%s,%v>`, formatPoint(c.Point), c.Radius), nil } func scanCircle(c *Circle, src interface{}) error { if src == nil { *c = NewCircle(Point{}, 0) return nil } val, err := iToS(src) if err != nil { return err } points, err := parsePoints(val) if err != nil { return err } pdzs := strings.Split(val, "),") if len(points) != 1 || len(pdzs) != 2 { return errors.New("wrong circle") } r, err := strconv.ParseFloat(strings.Trim(pdzs[1], ">"), 64) if err != nil { return err } *c = NewCircle(points[0], r) return nil } func randCircle(nextInt func() int64) Circle { return Circle{randPoint(nextInt), newRandNum(nextInt)} } // Randomize for sqlboiler func (c *Circle) Randomize(nextInt func() int64, fieldType string, shouldBeNull bool) { *c = randCircle(nextInt) }
package shared type Source struct { Target string `json:"target"` SonarToken string `json:"sonartoken"` Component string `json:"component"` Metrics string `json:"metrics"` } func (s *Source) Valid() bool { if len(s.Component) == 0 || len(s.Metrics) == 0 || len(s.Target) == 0 || len(s.SonarToken) == 0 { return false } return true } type Version map[string]string func HasError(err error) bool { return err != nil }
package httputil import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/url" ) var print = fmt.Print func PostUrlEncodeForm(postUrl string, val url.Values) (map[string]string, error) { resp, err1 := http.PostForm(postUrl, val) if err1 != nil { return nil, err1 } if resp.StatusCode != http.StatusOK { return nil, errors.New("connect remote server failed") } defer resp.Body.Close() content, err2 := ioutil.ReadAll(resp.Body) if err2 != nil { return nil, err2 } fmt.Println(string(content)) tempMap := make(map[string]string) err3 := json.Unmarshal(content, &tempMap) if err3 != nil { return nil, err3 } return tempMap, nil }
package middleware import ( "context" "fmt" "github.com/qiniu/qmgo/operator" "testing" "github.com/stretchr/testify/require" ) func TestMiddleware(t *testing.T) { ast := require.New(t) ctx := context.Background() // not register ast.NoError(Do(ctx, "success", operator.BeforeInsert)) // valid register Register(callbackTest) ast.NoError(Do(ctx, "success", operator.BeforeInsert)) ast.Error(Do(ctx, "failure", operator.BeforeUpsert)) ast.NoError(Do(ctx, "failure", operator.BeforeUpdate, "success")) } func callbackTest(ctx context.Context, doc interface{}, opType operator.OpType, opts ...interface{}) error { if doc.(string) == "success" && opType == operator.BeforeInsert { return nil } if len(opts) > 0 && opts[0].(string) == "success" { return nil } if doc.(string) == "failure" && opType == operator.BeforeUpsert { return fmt.Errorf("this is error") } return nil }
package schema import ( "regexp" "sync" ) type Column struct { Schema string `db:"TABLE_SCHEMA"` Table string `db:"TABLE_NAME"` Name string `db:"COLUMN_NAME"` DataType string `db:"DATA_TYPE"` ColumnType string `db:"COLUMN_TYPE"` } type ColumnList []*Column type ColumnMap struct { columns map[string]map[string]ColumnList sync.RWMutex } func BuildColumnMap(columns ColumnList) *ColumnMap { cs := make(map[string]map[string]ColumnList, 100) cm := ColumnMap{ columns: cs, } for _, column := range columns { _, ok := cs[column.Schema] if !ok { cs[column.Schema] = make(map[string]ColumnList) } _, ok = cs[column.Schema] if !ok { cs[column.Schema][column.Table] = make([]*Column, 0, 10) } cs[column.Schema][column.Table] = append(cs[column.Schema][column.Table], column) } return &cm } func (this *ColumnMap) GetColumns() map[string]map[string]ColumnList { this.RLock() defer this.RUnlock() return this.columns } func (this *ColumnMap) Schemas() []string { schemas := make([]string, 0, 10) this.RLock() defer this.RUnlock() for schema, _ := range this.columns { schemas = append(schemas, schema) } return schemas } func (this *ColumnMap) Tables(schema string) []string { this.RLock() defer this.RUnlock() tableMap, ok := this.columns[schema] if !ok { return nil } tables := make([]string, 0, 10) for table, _ := range tableMap { tables = append(tables, table) } return tables } func (this *ColumnMap) Columns(schema, table string) ColumnList { this.RLock() defer this.RUnlock() if tableMap, ok := this.columns[schema]; ok { return tableMap[table] } return nil } func (this *ColumnMap) ColumNames(schema, table string) []string { this.RLock() defer this.RUnlock() columns := this.Columns(schema, table) if columns == nil { return nil } names := make([]string, 0, 10) for _, column := range columns { names = append(names, column.Name) } return names } func (this *ColumnMap) GetColumn(schema, table string, index int) *Column { this.RLock() defer this.RUnlock() columns := this.Columns(schema, table) if columns != nil && index >= 0 && index < len(columns) { return columns[index] } return nil } func (this *ColumnMap) GetColumnByName(schema, table, column string) *Column { this.RLock() defer this.RUnlock() columns := this.Columns(schema, table) for _, c := range columns { if column == c.Name { return c } } return nil } func (this *Column) IsUnsigned() bool { return StringContainsIgnoreCase(this.DataType, "unsigned") } func (this *Column) IsEnum() bool { return StringContainsIgnoreCase(this.DataType, "enum") } func (this *Column) IsSet() bool { return StringContainsIgnoreCase(this.DataType, "set") } func (this *Column) IsText() bool { return StringContainsIgnoreCase(this.DataType, "text") } func (this *Column) IsBlob() bool { return StringContainsIgnoreCase(this.DataType, "blob") } func (this *Column) GetEnumValue(index int) string { values := this.getEnumValues() if index >= 0 && index < len(values) { return values[index] } return "" } func (this *Column) getEnumValues() []string { s := `'(\w+)'` re := regexp.MustCompile(s) matches := re.FindAllStringSubmatch(this.ColumnType, -1) values := make([]string, 0, 5) for _, m := range matches { values = append(values, m[1]) } return values }
package aoc2017 import ( "testing" aoc "github.com/janreggie/aoc/internal" "github.com/stretchr/testify/assert" ) func TestDay01(t *testing.T) { assert := assert.New(t) testCases := []aoc.TestCase{ {Input: "1122", Result1: "3", Result2: "0"}, {Input: "1212", Result1: "0", Result2: "6"}, {Input: "1234", Result1: "0", Result2: "0"}, {Input: "91212129", Result1: "9", Result2: "6"}, {Details: "Y2017D01 my input", Input: day01myInput, Result1: "1182", Result2: "1152", }, } for _, tt := range testCases { tt.Test(Day01, assert) } } func BenchmarkDay01(b *testing.B) { aoc.Benchmark(Day01, b, day01myInput) }
package constant const ( EmailFeedbackNotice = "反馈内容:%s <br /> 时间:%s" JWTContextKey = "user" )
package data import ( "database/sql" _ "github.com/lib/pq" ) //個別のタグデータを削除する func DeleteTagData(tagId int) { //データベースと接続 db, err := sql.Open("postgres", "user=trainer password=1111 dbname=imagebbs sslmode=disable") if err != nil { panic(err) } //タグデータを削除するSQL文をセット stmt, err := db.Prepare("delete from tags where tag_id =$1") if err != nil { panic(err) } //対象のタグのIDを渡しsqlを実行 stmt.Exec(tagId) return }
package main import ( "database/sql" "errors" "fmt" ) type Employee struct { ID int `json:"id,omitempty"` Name string `json:"name"` Department string `json:"department"` Title string `json:"title"` Remuneration float64 `json:"remuneration"` Expenses float64 `json:"expenses"` Year int `json:"year"` } func (em *Employee) getEmployee(db *sql.DB) error { getEmpQuery := "SELECT name, department, title, remuneration, expenses, year FROM remuneration WHERE id = $1" return db.QueryRow(getEmpQuery, em.ID).Scan(&em.Name, &em.Department, &em.Title, &em.Remuneration, &em.Expenses, &em.Year) } func (em *Employee) createEmployee(db *sql.DB) error { createEmpQuery := "INSERT INTO employeee(name, department, title, remuneration, expenses, year) VALUES($1, $2, $3, $4, $5, $6) RETURNING id" err := db.QueryRow(createEmpQuery, em.Name, em.Department, em.Title, em.Remuneration, em.Expenses, em.Year).Scan(&em.ID) if err != nil { return err } return nil } func (em *Employee) updateEmployee(db *sql.DB) error { updateEmpQuery := "UPDATE employee SET name=$1, department=$1, title=$3, remuneration=$4, expenses=$5, year=$6 WHERE id=$7" _, err := db.Exec(updateEmpQuery, em.Name, em.Department, em.Title, em.Remuneration, em.Expenses, em.Year, em.ID) return err } func (em *Employee) deleteEmployee(db *sql.DB) error { deleteEmpQuery := "DELETE from employee WHERE id=$1" _, err := db.Exec(deleteEmpQuery, em.ID) return err } func getAllEmployees(db *sql.DB) ([]Employee, error) { getAllEmpQuery := "SELECT name, department, title, remuneration, expenses, year FROM employee" rows, err := db.Query(getAllEmpQuery) if err != nil { return nil, err } defer rows.Close() allEmployees := []Employee{} for rows.Next() { var currEmp Employee if err := rows.Scan(&currEmp.Name, &currEmp.Department, &currEmp.Title, &currEmp.Remuneration, &currEmp.Expenses, &currEmp.Year); err != nil { fmt.Println(err) return nil, err } allEmployees = append(allEmployees, currEmp) } return allEmployees, nil } func isAnEmployeeDepartment(filter string) bool { s := []string{ "Engineering Services", "Dev Svcs, Bldg & Licensing", "Mayor & City Council", "Office of the City Manager", "City Clerk's Office", "Planning, Urban Des & Sustain", "IT, Digital Strategy & 311", "Community Services", "Real Estate & Facilities Mgmt", "Board of Parks & Recreation", "Vancouver Public Library Board", "Finance, Risk&Supply Chain Mgt", "VFRS & OEM", "Human Resources", "Law Department", } for _, dept := range s { if dept == filter { fmt.Println("Matches: " + filter) return true } fmt.Println("the other cases.") } fmt.Println("Called") return false } func getSomeEmployees(db *sql.DB, filter string) ([]Employee, error) { getSomeEmpQuery := "SELECT name, department, title, remuneration, expenses, year FROM employee WHERE department = $1" if !isAnEmployeeDepartment(filter) { fmt.Println("it hits.") return []Employee{}, errors.New("The entered subdomain is not a department") } rows, err := db.Query(getSomeEmpQuery, filter) if err != nil { fmt.Println("query error" + err.Error()) return nil, err } defer rows.Close() allEmployees := []Employee{} for rows.Next() { var currEmp Employee if err := rows.Scan(&currEmp.Name, &currEmp.Department, &currEmp.Title, &currEmp.Remuneration, &currEmp.Expenses, &currEmp.Year); err != nil { fmt.Println(err) return nil, err } allEmployees = append(allEmployees, currEmp) } return allEmployees, nil }
package main import "fmt" //函数可以返回多个值 func test() (a,b,c int) { return 1,2,3 } func main() { //a := 10 //b := 20 //c := 30 //多重赋值 a, b := 10, 20 fmt.Println(a, b) //a = b //b = a //fmt.Println(a, b) var c int c = a a = b b = c fmt.Println(a, b) //i := 10 //j := 20 i, j := 10, 20 //多重赋值 i, j = j, i fmt.Println(i, j) //_匿名变量 丢弃数据不处理 tmp,_:=7,8 fmt.Println(tmp) //var d,e,f int _,e,f := test() fmt.Println(e,f) } /* 总结: 一 多重赋值 一次对多个变量进行赋值 例如 a,b,c = 1,2,3 二 匿名变量 "_"单个下划线命名的变量就是匿名变量 特点:丢弃数据不处理 例如: tmp,_ := 10,20 注意: 1.不能打印_匿名变量 2.匿名变量配合函数返回值才有优势 */
package main import ( "fmt" "github.com/faroukelkholy/myhttp" ) func main() { limit, urls := myhttp.ParseCLI() if err := myhttp.Start(limit,urls); err != nil { fmt.Println(err.Error()) } }
package main import ( "bytes" "compress/gzip" "io" "io/ioutil" "os" "testing" ) var goodOutputGz = `Package: vim-tiny Source: vim Version: 2:7.4.052-1ubuntu3 Architecture: amd64 Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com> Installed-Size: 931 Depends: vim-common (= 2:7.4.052-1ubuntu3), libacl1 (>= 2.2.51-8), libc6 (>= 2.15), libselinux1 (>= 1.32), libtinfo5 Suggests: indent Provides: editor Section: editors Priority: important Homepage: http://www.vim.org/ Description: Vi IMproved - enhanced vi editor - compact version Vim is an almost compatible version of the UNIX editor Vi. . Many new features have been added: multi level undo, syntax highlighting, command line history, on-line help, filename completion, block operations, folding, Unicode support, etc. . This package contains a minimal version of vim compiled with no GUI and a small subset of features in order to keep small the package size. This package does not depend on the vim-runtime package, but installing it you will get its additional benefits (online documentation, plugins, ...). Original-Maintainer: Debian Vim Maintainers <pkg-vim-maintainers@lists.alioth.debian.org> ` var goodOutputLzma = `Package: ifupdown2 Version: 3.0.0-1 Architecture: all Maintainer: Julien Fortin <julien@cumulusnetworks.com> Installed-Size: 1576 Depends: python3:any, iproute2 Suggests: isc-dhcp-client, bridge-utils, ethtool, python3-gvgen, python3-mako Conflicts: ifupdown Replaces: ifupdown Provides: ifupdown Section: admin Priority: optional Homepage: https://github.com/cumulusnetworks/ifupdown2 Description: Network Interface Management tool similar to ifupdown ifupdown2 is ifupdown re-written in Python. It replaces ifupdown and provides the same user interface as ifupdown for network interface configuration. Like ifupdown, ifupdown2 is a high level tool to configure (or, respectively deconfigure) network interfaces based on interface definitions in /etc/network/interfaces. It is capable of detecting network interface dependencies and comes with several new features which are available as new command options to ifup/ifdown/ifquery commands. It also comes with a new command ifreload to reload interface configuration with minimum disruption. Most commands are also capable of input and output in JSON format. It is backward compatible with ifupdown /etc/network/interfaces format and supports newer simplified format. It also supports interface templates with python-mako for large scale interface deployments. See /usr/share/doc/ifupdown2/README.rst for details about ifupdown2. Examples are available under /usr/share/doc/ifupdown2/examples. ` var goodPkgGzOutput = `Package: vim-tiny Source: vim Version: 2:7.4.052-1ubuntu3 Architecture: amd64 Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com> Installed-Size: 931 Depends: vim-common (= 2:7.4.052-1ubuntu3), libacl1 (>= 2.2.51-8), libc6 (>= 2.15), libselinux1 (>= 1.32), libtinfo5 Suggests: indent Provides: editor Section: editors Priority: important Homepage: http://www.vim.org/ Description: Vi IMproved - enhanced vi editor - compact version Vim is an almost compatible version of the UNIX editor Vi. . Many new features have been added: multi level undo, syntax highlighting, command line history, on-line help, filename completion, block operations, folding, Unicode support, etc. . This package contains a minimal version of vim compiled with no GUI and a small subset of features in order to keep small the package size. This package does not depend on the vim-runtime package, but installing it you will get its additional benefits (online documentation, plugins, ...). Original-Maintainer: Debian Vim Maintainers <pkg-vim-maintainers@lists.alioth.debian.org> Filename: dists/stable/main/binary-cats/test.deb Size: 391240 MD5sum: 0ec79417129746ff789fcff0976730c5 SHA1: b2ac976af80f0f50a8336402d5a29c67a2880b9b SHA256: 9938ec82a8c882ebc2d59b64b0bf2ac01e9cbc5a235be4aa268d4f8484e75eab ` var goodPkgGzOutputNonDefault = `Package: vim-tiny Source: vim Version: 2:7.4.052-1ubuntu3 Architecture: amd64 Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com> Installed-Size: 931 Depends: vim-common (= 2:7.4.052-1ubuntu3), libacl1 (>= 2.2.51-8), libc6 (>= 2.15), libselinux1 (>= 1.32), libtinfo5 Suggests: indent Provides: editor Section: editors Priority: important Homepage: http://www.vim.org/ Description: Vi IMproved - enhanced vi editor - compact version Vim is an almost compatible version of the UNIX editor Vi. . Many new features have been added: multi level undo, syntax highlighting, command line history, on-line help, filename completion, block operations, folding, Unicode support, etc. . This package contains a minimal version of vim compiled with no GUI and a small subset of features in order to keep small the package size. This package does not depend on the vim-runtime package, but installing it you will get its additional benefits (online documentation, plugins, ...). Original-Maintainer: Debian Vim Maintainers <pkg-vim-maintainers@lists.alioth.debian.org> Filename: dists/blah/main/binary-cats/test.deb Size: 391240 MD5sum: 0ec79417129746ff789fcff0976730c5 SHA1: b2ac976af80f0f50a8336402d5a29c67a2880b9b SHA256: 9938ec82a8c882ebc2d59b64b0bf2ac01e9cbc5a235be4aa268d4f8484e75eab ` func TestInspectPackage(t *testing.T) { _, err := inspectPackage("samples/vim-tiny_7.4.052-1ubuntu3_amd64.deb") if err != nil { t.Errorf("inspectPackage() error: %s", err) } _, err = inspectPackage("thisfileshouldnotexist") if err == nil { t.Error("inspectPackage() should have failed, it did not") } } func TestInspectPackageControlGz(t *testing.T) { sampleDeb, err := ioutil.ReadFile("samples/control.tar.gz") if err != nil { t.Errorf("error opening sample deb file: %s", err) } var controlBuf bytes.Buffer cfReader := bytes.NewReader(sampleDeb) io.Copy(&controlBuf, cfReader) parsedControl, err := inspectPackageControl(GZIP, controlBuf) if err != nil { t.Errorf("error inspecting GZIP control file: %s", err) } if parsedControl != goodOutputGz { t.Errorf("control file does not match") } var failControlBuf bytes.Buffer _, err = inspectPackageControl(GZIP, failControlBuf) if err == nil { t.Error("inspectPackageControl() should have failed, it did not") } } func TestInspectPackageControlLzma(t *testing.T) { sampleDeb, err := ioutil.ReadFile("samples/control.tar.xz") if err != nil { t.Errorf("error opening sample deb file: %s", err) } var controlBuf bytes.Buffer cfReader := bytes.NewReader(sampleDeb) io.Copy(&controlBuf, cfReader) parsedControl, err := inspectPackageControl(LZMA, controlBuf) if err != nil { t.Errorf("error inspecting LZMA control file: %s", err) } if parsedControl != goodOutputLzma { t.Errorf("control file does not match") } var failControlBuf bytes.Buffer _, err = inspectPackageControl(LZMA, failControlBuf) if err == nil { t.Error("inspectPackageControl() should have failed, it did not") } } func TestCreatePackagesGz(t *testing.T) { pwd, err := os.Getwd() if err != nil { t.Errorf("Unable to get current working directory: %s", err) } config := conf{ListenPort: "9666", RootRepoPath: pwd + "/testing", SupportArch: []string{"cats", "dogs"}, DistroNames: []string{"stable"}, Sections: []string{"main", "blah"}, EnableSSL: false} // sanity check... if config.RootRepoPath != pwd+"/testing" { t.Errorf("RootRepoPath is %s, should be %s\n ", config.RootRepoPath, pwd+"/testing") } // copy sample deb to repo location (assuming it exists) origDeb, err := os.Open("samples/vim-tiny_7.4.052-1ubuntu3_amd64.deb") if err != nil { t.Errorf("error opening up sample deb: %s", err) } defer origDeb.Close() for _, archDir := range config.SupportArch { // do not use the built-in createDirs() in case it is broken if err := os.MkdirAll(config.RootRepoPath+"/dists/stable/main/binary-"+archDir, 0755); err != nil { t.Errorf("error creating directory for %s: %s\n", archDir, err) } copyDeb, err := os.Create(config.RootRepoPath + "/dists/stable/main/binary-" + archDir + "/test.deb") if err != nil { t.Errorf("error creating copy of deb: %s", err) } _, err = io.Copy(copyDeb, origDeb) if err != nil { t.Errorf("error writing copy of deb: %s", err) } if err := copyDeb.Close(); err != nil { t.Errorf("error saving copy of deb: %s", err) } } if err := createPackagesGz(config, "stable", "main", "cats"); err != nil { t.Errorf("error creating packages gzip for cats") } pkgGzip, err := ioutil.ReadFile(config.RootRepoPath + "/dists/stable/main/binary-cats/Packages.gz") if err != nil { t.Errorf("error reading Packages.gz: %s", err) } pkgReader, err := gzip.NewReader(bytes.NewReader(pkgGzip)) if err != nil { t.Errorf("error reading existing Packages.gz: %s", err) } buf := bytes.NewBuffer(nil) io.Copy(buf, pkgReader) if goodPkgGzOutput != buf.String() { t.Errorf("Packages.gz does not match, returned value is:\n %s \n\n should be:\n %s", buf.String(), goodPkgGzOutput) } pkgFile, err := ioutil.ReadFile(config.RootRepoPath + "/dists/stable/main/binary-cats/Packages") if err != nil { t.Errorf("error reading Packages: %s", err) } if goodPkgGzOutput != string(pkgFile) { t.Errorf("Packages does not match, returned value is:\n %s \n\n should be:\n %s", buf.String(), goodPkgGzOutput) } // cleanup if err := os.RemoveAll(config.RootRepoPath); err != nil { t.Errorf("error cleaning up after createPackagesGz(): %s", err) } // create temp file tempFile, err := os.Create(pwd + "/tempFile") if err != nil { t.Fatalf("create %s: %s", pwd+"/tempFile", err) } defer tempFile.Close() config.RootRepoPath = pwd + "/tempFile" // Can't make directory named after file if err := createPackagesGz(config, "stable", "main", "cats"); err == nil { t.Errorf("createPackagesGz() should have failed, it did not") } // cleanup if err := os.RemoveAll(pwd + "/tempFile"); err != nil { t.Errorf("error cleaning up after createDirs(): %s", err) } } func TestCreatePackagesGzNonDefault(t *testing.T) { pwd, err := os.Getwd() if err != nil { t.Errorf("Unable to get current working directory: %s", err) } config := conf{ListenPort: "9666", RootRepoPath: pwd + "/testing", SupportArch: []string{"cats", "dogs"}, DistroNames: []string{"blah"}, EnableSSL: false} // sanity check... if config.RootRepoPath != pwd+"/testing" { t.Errorf("RootRepoPath is %s, should be %s\n ", config.RootRepoPath, pwd+"/testing") } // copy sample deb to repo location (assuming it exists) origDeb, err := os.Open("samples/vim-tiny_7.4.052-1ubuntu3_amd64.deb") if err != nil { t.Errorf("error opening up sample deb: %s", err) } defer origDeb.Close() for _, archDir := range config.SupportArch { // do not use the built-in createDirs() in case it is broken if err := os.MkdirAll(config.RootRepoPath+"/dists/blah/main/binary-"+archDir, 0755); err != nil { t.Errorf("error creating directory for %s: %s\n", archDir, err) } copyDeb, err := os.Create(config.RootRepoPath + "/dists/blah/main/binary-" + archDir + "/test.deb") if err != nil { t.Errorf("error creating copy of deb: %s", err) } _, err = io.Copy(copyDeb, origDeb) if err != nil { t.Errorf("error writing copy of deb: %s", err) } if err := copyDeb.Close(); err != nil { t.Errorf("error saving copy of deb: %s", err) } } if err := createPackagesGz(config, "blah", "main", "cats"); err != nil { t.Errorf("error creating packages gzip for cats") } pkgGzip, err := ioutil.ReadFile(config.RootRepoPath + "/dists/blah/main/binary-cats/Packages.gz") if err != nil { t.Errorf("error reading Packages.gz: %s", err) } pkgReader, err := gzip.NewReader(bytes.NewReader(pkgGzip)) if err != nil { t.Errorf("error reading existing Packages.gz: %s", err) } buf := bytes.NewBuffer(nil) io.Copy(buf, pkgReader) if goodPkgGzOutputNonDefault != buf.String() { t.Errorf("Packages.gz does not match, returned value is: %s", buf.String()) } // cleanup if err := os.RemoveAll(config.RootRepoPath); err != nil { t.Errorf("error cleaning up after createPackagesGz(): %s", err) } }
package provider import ( "github.com/operator-framework/operator-lifecycle-manager/pkg/package-server/apis/operators" "k8s.io/apimachinery/pkg/labels" ) type PackageManifestProvider interface { Get(namespace, name string) (*operators.PackageManifest, error) List(namespace string, selector labels.Selector) (*operators.PackageManifestList, error) }
package go_scout import ( secretsmanager "cloud.google.com/go/secretmanager/apiv1" "cloud.google.com/go/storage" "context" "encoding/json" "errors" "fmt" tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" "log" "net/http" "os" "reflect" "strconv" "strings" ) const zoneAvailURLPrefix = "https://www.roh.org.uk/api/proxy/TXN/Performances/ZoneAvailabilities?performanceIds=%s" const seatRetrievURLPrefix = "https://www.roh.org.uk/api/proxy/TXN/Performances/%s/Seats?constituentId=0&modeOfSaleId=9&performanceId=%s" const visitURL = "https://www.roh.org.uk/seatmap?performanceId=%s" const availableSeatCode = 0 type ZoneAvailability struct { Zone struct { Id int Description string } PerformanceId int AvailableCount int } type Seat struct { Id int ZoneId int SeatRow string SeatNumber string SeatStatusId int } type PubSubMessage struct { Data []byte `json:"data"` } func findZoneId(performanceId string, seats string) (int, error) { log.Println("looking for the zoneID...") zoneAvailURL := fmt.Sprintf(zoneAvailURLPrefix, performanceId) r, err := http.Get(zoneAvailURL) if err != nil { return 0, err } var zAvs []ZoneAvailability err = json.NewDecoder(r.Body).Decode(&zAvs) if err != nil { return 0, err } for _, zAv := range zAvs { if zAv.Zone.Description == seats { return zAv.Zone.Id, nil } } return 0, errors.New(fmt.Sprintf("seats not found: %s", seats)) } func findSeatsInZoneId(performanceId string, zoneId int) ([]Seat, error) { seatRetrievalUrl := fmt.Sprintf(seatRetrievURLPrefix, performanceId, performanceId) r, err := http.Get(seatRetrievalUrl) if err != nil { return []Seat{}, err } var seats []Seat err = json.NewDecoder(r.Body).Decode(&seats) if err != nil { return []Seat{}, err } var availableSeats []Seat for _, seat := range seats { if seat.ZoneId == zoneId && seat.SeatStatusId == availableSeatCode { availableSeats = append(availableSeats, seat) } } return availableSeats, nil } func sendTelegramMessage(ctx context.Context, m string) error { chatID, err := strconv.Atoi(os.Getenv("TELEGRAM_CHAT_ID")) if err != nil { return err } client, err := secretsmanager.NewClient(ctx) if err != nil { return err } defer func() { _ = client.Close() }() req := &secretmanagerpb.AccessSecretVersionRequest{ Name: os.Getenv("TELEGRAM_SECRET_ID") + "/versions/latest", } secret, err := client.AccessSecretVersion(ctx, req) if err != nil { return err } bot, err := tgbotapi.NewBotAPI(string(secret.GetPayload().Data)) if err != nil { return err } msg := tgbotapi.NewMessage(int64(chatID), m) if _, err := bot.Send(msg); err != nil { return err } log.Printf("the message has been sent to chatID: %d. Message: %s", chatID, m) return nil } func putSavedNotifications(ctx context.Context, savedNotifications []Seat, performanceId string) error { log.Println("putting saved notifications...") client, err := storage.NewClient(ctx) if err != nil { return err } defer func() { _ = client.Close() }() obj := client.Bucket(os.Getenv("BUCKET")).Object(performanceId) w := obj.NewWriter(ctx) if err != nil { return err } err = json.NewEncoder(w).Encode(savedNotifications) if err != nil { return err } err = w.Close() if err != nil { return err } log.Printf("file %s written", performanceId) return nil } func getSavedNotifications(ctx context.Context, performanceId string) ([]Seat, error) { log.Println("retrieving saved notifications...") client, err := storage.NewClient(ctx) if err != nil { return []Seat{}, err } defer func() { _ = client.Close() }() obj := client.Bucket(os.Getenv("BUCKET")).Object(performanceId) if _, err = obj.Attrs(ctx); err != nil { return []Seat{}, nil } r, err := obj.NewReader(ctx) if err != nil { return []Seat{}, err } var savedNotifications []Seat err = json.NewDecoder(r).Decode(&savedNotifications) if err != nil { return []Seat{}, err } err = r.Close() if err != nil { return []Seat{}, err } log.Println("saved notification seats retrieved") return savedNotifications, nil } func findTicket(ctx context.Context, performanceId string) error { seats := os.Getenv("SEATS") savedNotifications, err := getSavedNotifications(ctx, performanceId) if err != nil { return err } ticketsWanted, err := strconv.Atoi(os.Getenv("TICKETS_WANTED")) if err != nil { return err } zoneId, err := findZoneId(performanceId, seats) if err != nil { return err } log.Printf("zoneId found: %d", zoneId) availSeats, err := findSeatsInZoneId(performanceId, zoneId) if err != nil { return err } if len(availSeats) >= ticketsWanted { msg := "The following seats are available:\n" for _, seat := range availSeats { msg += fmt.Sprintf("SeatRow: %s, SeatNumber: %s\n", seat.SeatRow, seat.SeatNumber) } msg += "book: " + fmt.Sprintf(visitURL, performanceId) log.Println(msg) if reflect.DeepEqual(savedNotifications, availSeats) { log.Println("already notified for the tickets, skipping sending telegram...") } else { if err := sendTelegramMessage(ctx, msg); err != nil { return err } if err = putSavedNotifications(ctx, availSeats, performanceId); err != nil { return err } } } else { log.Println("no available seats found") } return nil } func Run(ctx context.Context, _ PubSubMessage) error { performanceIds := strings.Split(os.Getenv("PERFORMANCE_IDS"), ",") for _, performanceId := range performanceIds { log.Printf("running performanceId: %s", performanceId) if err := findTicket(ctx, performanceId); err != nil { return err } } log.Println("execution completed") return nil }
package producers import ( "errors" "fmt" "log" "time" c "github.com/pedromss/kafli/config" cst "github.com/pedromss/kafli/config/constants" "github.com/pedromss/kafli/confluent" "github.com/pedromss/kafli/contracts" "github.com/pedromss/kafli/model" "github.com/pedromss/kafli/segmentio" inptils "github.com/pedromss/kafli/utils/input" ) // ResolveProducer producer will create a new Producer of the requested implementation func ResolveProducer(conf *c.AppConf, ssl bool) contracts.Producer { if ssl { return confluent.NewProducer(conf) } var producer contracts.Producer switch conf.Impl { case cst.Confluent: producer = confluent.NewProducer(conf) case cst.SegmentIO: producer = segmentio.NewProducer(conf) } return producer } // InputExtractor is a function that channels input data from the specified // input stream to the channel it returns type InputExtractor = func(*c.AppConf) (chan *model.RecordToSend, error) // BurstProducer is a function that produces records to the given Producer from // the given channel as fast as possible type BurstProducer = func(contracts.Producer, chan *model.RecordToSend) // ThrottledProducer is a function that produces records to the given Producer // in a throttled manner. type ThrottledProducer = func(contracts.Producer, chan *model.RecordToSend, <-chan time.Time, func()) // RunProducer will produce messages to the given producer from the supplied source // in AppConf func RunProducer(p contracts.Producer, conf *c.AppConf) error { ch, err := prepareInputData(conf, inptils.StreamInput) if err != nil { return err } produce(p, conf, ch, produceBurst, produceThrottled) return nil } func prepareInputData(conf *c.AppConf, inputExtractor InputExtractor) (chan *model.RecordToSend, error) { if conf.In == nil { return nil, errors.New("an input source is required when producing things") } ch, err := inputExtractor(conf) if err != nil { return nil, fmt.Errorf("unable to read from %s", conf.In) } return ch, nil } func produce( p contracts.Producer, conf *c.AppConf, ch chan *model.RecordToSend, burstHandler BurstProducer, throttledHandler ThrottledProducer) { if conf.Rate == nil || conf.Rate.Duration == nil { burstHandler(p, ch) } else { log.Printf("Producing messages throttled at %s", conf.Rate.Duration.String()) throttledHandler(p, ch, conf.Ticker.C, func() { conf.Ticker.Stop() }) } } func produceBurst(p contracts.Producer, ch chan *model.RecordToSend) { i := 1 for msg := range ch { reportWrite(msg) if err := p.Send(msg); err != nil { log.Fatalf("Failed to write message %d. Err %s", i, err) } i++ } } func produceThrottled(p contracts.Producer, ch chan *model.RecordToSend, ticker <-chan time.Time, onEnd func()) { i := 1 for range ticker { msg, ok := <-ch if !ok { log.Println("Finished producing messages") onEnd() break } reportWrite(msg) if err := p.Send(msg); err != nil { log.Fatalf("Failed to write message %d. Err %s", i, err) } i++ } } func reportWrite(msg *model.RecordToSend) { var key string if msg.Key != nil { key = string(*msg.Key) } else { key = "unknown" } log.Printf("Writing message %s", key) }
package letter import "sync" type FreqMap map[rune]int var waitGroup sync.WaitGroup var mutex sync.Mutex func Frequency(s string) FreqMap { m := FreqMap{} for _, r := range s { m[r]++ } return m } func ConcurrentFrequency(phrases []string) FreqMap { m := FreqMap{} waitGroup.Add(len(phrases)) for _, word := range phrases { go func(word string) { m.add(word) waitGroup.Done() }(word) } waitGroup.Wait() return m } func (freqMap FreqMap) add(word string) { for _, r := range word { go func(r rune) { mutex.Lock() freqMap.increment(r) mutex.Unlock() }(r) } } func (freqMap FreqMap) increment(r rune) { freqMap[r]++ }
package spi import ( "github.com/BurntSushi/toml" "log" ) type AppConfig struct { Database DatabaseConfig Http HttpConfig } type DatabaseConfig struct { Driver string Url string Host string Port int } type HttpConfig struct { Host string Port int } func Load(file string) (*AppConfig, error) { var config = AppConfig{} if _, err := toml.DecodeFile(file, &config); err != nil { log.Fatal(err) return nil, err } return &config, nil }
package types import ( "github.com/irisnet/irishub/codec" ) // Register concrete types on codec func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(MsgRequestRand{}, "irishub/rand/MsgRequestRand", nil) cdc.RegisterConcrete(&Rand{}, "irishub/rand/Rand", nil) cdc.RegisterConcrete(&Request{}, "irishub/rand/Request", nil) } var msgCdc = codec.New() func init() { RegisterCodec(msgCdc) }
package operatorclient import ( "context" "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/klog" apiregistrationv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" ) // CreateAPIService creates the APIService. func (c *Client) CreateAPIService(ig *apiregistrationv1.APIService) (*apiregistrationv1.APIService, error) { return c.ApiregistrationV1Interface().ApiregistrationV1().APIServices().Create(context.TODO(), ig, metav1.CreateOptions{}) } // GetAPIService returns the existing APIService. func (c *Client) GetAPIService(name string) (*apiregistrationv1.APIService, error) { return c.ApiregistrationV1Interface().ApiregistrationV1().APIServices().Get(context.TODO(), name, metav1.GetOptions{}) } // DeleteAPIService deletes the APIService. func (c *Client) DeleteAPIService(name string, options *metav1.DeleteOptions) error { return c.ApiregistrationV1Interface().ApiregistrationV1().APIServices().Delete(context.TODO(), name, *options) } // UpdateAPIService will update the given APIService resource. func (c *Client) UpdateAPIService(apiService *apiregistrationv1.APIService) (*apiregistrationv1.APIService, error) { klog.V(4).Infof("[UPDATE APIService]: %s", apiService.GetName()) oldAPIService, err := c.GetAPIService(apiService.GetName()) if err != nil { return nil, err } patchBytes, err := createPatch(oldAPIService, apiService) if err != nil { return nil, fmt.Errorf("error creating patch for APIService: %v", err) } return c.ApiregistrationV1Interface().ApiregistrationV1().APIServices().Patch(context.TODO(), apiService.GetName(), types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}) }
// Copyright (c) 2019 Aiven, Helsinki, Finland. https://aiven.io/ package aiven import ( "fmt" "github.com/aiven/aiven-go-client" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) func datasourceVPCPeeringConnection() *schema.Resource { return &schema.Resource{ Read: datasourceVPCPeeringConnectionRead, Schema: resourceSchemaAsDatasourceSchema(aivenVPCPeeringConnectionSchema, "vpc_id", "peer_cloud_account", "peer_vpc"), } } func datasourceVPCPeeringConnectionRead(d *schema.ResourceData, m interface{}) error { client := m.(*aiven.Client) projectName, vpcID := splitResourceID2(d.Get("vpc_id").(string)) peerCloudAccount := d.Get("peer_cloud_account").(string) peerVPC := d.Get("peer_vpc").(string) vpc, err := client.VPCs.Get(projectName, vpcID) if err != nil { return err } for _, peer := range vpc.PeeringConnections { if peer.PeerCloudAccount == peerCloudAccount && peer.PeerVPC == peerVPC { if peer.PeerRegion != nil && *peer.PeerRegion != "" { d.SetId(buildResourceID(projectName, vpcID, peer.PeerCloudAccount, peer.PeerVPC, *peer.PeerRegion)) } else { d.SetId(buildResourceID(projectName, vpcID, peer.PeerCloudAccount, peer.PeerVPC)) } return copyVPCPeeringConnectionPropertiesFromAPIResponseToTerraform(d, peer, projectName, vpcID) } } return fmt.Errorf("Peering connection from %s/%s to %s/%s not found", projectName, vpc.CloudName, peerCloudAccount, peerVPC) }
package goSolution func findRedundantConnection(edges [][]int) []int { n := len(edges) for i, _ := range edges { edges[i][0]-- edges[i][1]-- } dsu := InitializeDSU(n) for i := n - 1; i >= 0; i-- { foundLoop := false for j := 0; j < n; j++ { if j != i { edge := edges[j] if dsu.FindSet(edge[0]) == dsu.FindSet(edge[1]) { foundLoop = true break } dsu.MergeSet(edge[0], edge[1]) } } if !foundLoop { edges[i][0]++ edges[i][1]++ return edges[i] } dsu.Reset() } return nil }
package route import ( "github.com/gin-gonic/gin" "secKill/controller" ) func InitRouter() (router *gin.Engine) { router = gin.Default() router.POST("/secKill", controller.SecKill) router.POST("/secKillInfo", controller.GetProductInfo) return }
/* * @lc app=leetcode.cn id=541 lang=golang * * [541] 反转字符串 II */ // @lc code=start // package leetcode func reverse(b []byte) { left := 0 right := len(b) - 1 for right > left { b[left], b[right] = b[right], b[left] left++ right-- } } func reverseStr(s string, k int) string { n := len(s) b := []byte(s) for i := 0; i < n; { if n-i < k { reverse(b[i:n]) } else { reverse(b[i : i+k]) } i += 2 * k } return string(b) } // @lc code=end
/* A matrix is antisymmetric, or skew-symmetric, if its transpose equals its negative. The transpose of a matrix can be obtained by reflecting its elements across the main diagonal. Examples of transpositions can be seen here: 0 2 -1 -2 0 0 1 0 0 All antisymmetric matrices exhibit certain characteristics: Antisymmetry can only be found on square matrices, because otherwise the matrix and its transpose would be of different dimensions. Elements which lie on the main diagonal must equal zero because they do not move and consequently must be their own negatives, and zero is the only number which satisfies x=−x. The sum of two antisymmetric matrices is also antisymmetric. The Challenge Given a square, non-empty matrix which contains only integers, check whether it is antisymmetric or not. Rules This is code-golf so the shortest program in bytes wins. Input and output can assume whatever forms are most convenient as long as they are self-consistent (including output which is not truthy or falsy, or is truthy for non-antisymmetry and falsy for antisymmetry, etc). Assume only valid input will be given. Test Cases In: 1 1 1 1 1 1 1 1 1 Out: False In: 0 0 1 0 0 0 -1 0 0 Out: True In: 0 -2 2 0 Out: True */ package main func main() { assert(antisymmetric([][]int{ {1, 1, 1}, {1, 1, 1}, {1, 1, 1}, }) == false) assert(antisymmetric([][]int{ {0, 0, 1}, {0, 0, 0}, {-1, 0, 0}, }) == true) assert(antisymmetric([][]int{ {0, -2}, {2, 0}, }) == true) assert(antisymmetric([][]int{ {0, 2, -1}, {-2, 0, 0}, {1, 0, 0}, }) == true) } func assert(x bool) { if !x { panic("assertion failed") } } func antisymmetric(m [][]int) bool { for i := range m { for j := range m[i] { if m[i][j] != -m[j][i] { return false } } } return true }
// Copyright 2017 Jeff Foley. All rights reserved. // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. package amass import ( "bufio" "errors" "io" "io/ioutil" "log" "net" "strings" "time" "github.com/OWASP/Amass/amass/core" "github.com/OWASP/Amass/amass/dnssrv" "github.com/OWASP/Amass/amass/utils" evbus "github.com/asaskevich/EventBus" ) // Banner is the ASCII art logo used within help output. var Banner = ` .+++:. : .+++. +W@@@@@@8 &+W@# o8W8: +W@@@@@@#. oW@@@W#+ &@#+ .o@##. .@@@o@W.o@@o :@@#&W8o .@#: .:oW+ .@#+++&#& +@& &@& #@8 +@W@&8@+ :@W. +@8 +@: .@8 8@ @@ 8@o 8@8 WW .@W W@+ .@W. o@#: WW &@o &@: o@+ o@+ #@. 8@o +W@#+. +W@8: #@ :@W &@+ &@+ @8 :@o o@o oW@@W+ oW@8 o@+ @@& &@+ &@+ #@ &@. .W@W .+#@& o@W. WW +@W@8. &@+ :& o@+ #@ :@W&@& &@: .. :@o :@W: o@# +Wo &@+ :W: +@W&o++o@W. &@& 8@#o+&@W. #@: o@+ :W@@WWWW@@8 + :&W@@@@& &W .o#@@W&. :W@WWW@@& +o&&&&+. +oooo. ` const ( // Version is used to display the current version of Amass. Version = "2.8.2" // Author is used to display the developer of the amass package. Author = "https://github.com/OWASP/Amass" defaultWordlistURL = "https://raw.githubusercontent.com/OWASP/Amass/master/wordlists/namelist.txt" ) // EnumerationTiming represents a speed band for the enumeration to execute within. type EnumerationTiming int // The various timing/speed templates for an Amass enumeration. const ( Paranoid EnumerationTiming = iota Sneaky Polite Normal Aggressive Insane ) // Enumeration is the object type used to execute a DNS enumeration with Amass. type Enumeration struct { // The channel that will receive the results Output chan *core.AmassOutput // Broadcast channel that indicates no further writes to the output channel Done chan struct{} // Logger for error messages Log *log.Logger // The ASNs that the enumeration will target ASNs []int // The CIDRs that the enumeration will target CIDRs []*net.IPNet // The IPs that the enumeration will target IPs []net.IP // The ports that will be checked for certificates Ports []int // Will whois info be used to add additional domains? Whois bool // The list of words to use when generating names Wordlist []string // Will the enumeration including brute forcing techniques BruteForcing bool // Will recursive brute forcing be performed? Recursive bool // Minimum number of subdomain discoveries before performing recursive brute forcing MinForRecursive int // Will discovered subdomain name alterations be generated? Alterations bool // Indicates a speed band for the enumeration to execute within Timing EnumerationTiming // Only access the data sources for names and return results? Passive bool // Determines if active information gathering techniques will be used Active bool // A blacklist of subdomain names that will not be investigated Blacklist []string // The writer used to save the data operations performed DataOptsWriter io.Writer // The root domain names that the enumeration will target domains []string // Pause/Resume channels for halting the enumeration pause chan struct{} resume chan struct{} } // NewEnumeration returns an initialized Enumeration that has not been started yet. func NewEnumeration() *Enumeration { return &Enumeration{ Output: make(chan *core.AmassOutput, 100), Done: make(chan struct{}), Log: log.New(ioutil.Discard, "", 0), Ports: []int{443}, Recursive: true, MinForRecursive: 1, Alterations: true, Timing: Normal, pause: make(chan struct{}), resume: make(chan struct{}), } } // AddDomain appends another DNS domain name to an Enumeration. func (e *Enumeration) AddDomain(domain string) { e.domains = utils.UniqueAppend(e.domains, domain) } // Domains returns the current set of DNS domain names assigned to an Enumeration. func (e *Enumeration) Domains() []string { return e.domains } func (e *Enumeration) generateAmassConfig() (*core.AmassConfig, error) { if e.Output == nil { return nil, errors.New("The configuration did not have an output channel") } if e.Passive && e.BruteForcing { return nil, errors.New("Brute forcing cannot be performed without DNS resolution") } if e.Passive && e.Active { return nil, errors.New("Active enumeration cannot be performed without DNS resolution") } if e.Passive && e.DataOptsWriter != nil { return nil, errors.New("Data operations cannot be saved without DNS resolution") } if len(e.Ports) == 0 { e.Ports = []int{443} } if e.BruteForcing && len(e.Wordlist) == 0 { e.Wordlist, _ = getDefaultWordlist() } config := &core.AmassConfig{ Log: e.Log, ASNs: e.ASNs, CIDRs: e.CIDRs, IPs: e.IPs, Ports: e.Ports, Whois: e.Whois, Wordlist: e.Wordlist, BruteForcing: e.BruteForcing, Recursive: e.Recursive, MinForRecursive: e.MinForRecursive, Alterations: e.Alterations, Passive: e.Passive, Active: e.Active, Blacklist: e.Blacklist, DataOptsWriter: e.DataOptsWriter, } config.SetGraph(core.NewGraph()) config.MaxFlow = utils.NewSemaphore(timingToMaxFlow(e.Timing)) for _, domain := range e.Domains() { config.AddDomain(domain) } return config, nil } // Start begins the DNS enumeration process for the Amass Enumeration object. func (e *Enumeration) Start() error { config, err := e.generateAmassConfig() if err != nil { return err } bus := evbus.New() bus.SubscribeAsync(core.OUTPUT, e.sendOutput, false) // Select the correct services to be used in this enumeration services := []core.AmassService{ NewSubdomainService(config, bus), NewSourcesService(config, bus), } if !config.Passive { services = append(services, NewDataManagerService(config, bus), dnssrv.NewDNSService(config, bus), NewAlterationService(config, bus), NewBruteForceService(config, bus), NewActiveCertService(config, bus), ) } for _, srv := range services { if err := srv.Start(); err != nil { return err } } // When done, we want to know if the enumeration completed var completed bool // Periodically check if all the services have finished t := time.NewTicker(3 * time.Second) loop: for { select { case <-e.Done: break loop case <-e.pause: t.Stop() case <-e.resume: t = time.NewTicker(3 * time.Second) case <-t.C: done := true for _, srv := range services { if srv.IsActive() { done = false break } } if done { completed = true break loop } } } t.Stop() // Stop all the services for _, service := range services { service.Stop() } // Wait for output to finish being handled bus.Unsubscribe(core.OUTPUT, e.sendOutput) bus.WaitAsync() if completed { close(e.Done) } time.Sleep(1 * time.Second) close(e.Output) return nil } // Pause temporarily halts the DNS enumeration. func (e *Enumeration) Pause() { e.pause <- struct{}{} } // Resume causes a previously paused enumeration to resume execution. func (e *Enumeration) Resume() { e.resume <- struct{}{} } func (e *Enumeration) sendOutput(out *core.AmassOutput) { // Check if the output channel has been closed select { case <-e.Done: return default: e.Output <- out } } // ObtainAdditionalDomains discovers and appends DNS domain names related to the current set of names. func (e *Enumeration) ObtainAdditionalDomains() { if e.Whois { for _, domain := range e.domains { more, err := ReverseWhois(domain) if err != nil { e.Log.Printf("ReverseWhois error: %v", err) continue } for _, domain := range more { e.AddDomain(domain) } } } } func timingToMaxFlow(t EnumerationTiming) int { var result int switch t { case Paranoid: result = 1 case Sneaky: result = 10 case Polite: result = 25 case Normal: result = 50 case Aggressive: result = 100 case Insane: result = 250 } return result } func getDefaultWordlist() ([]string, error) { var list []string var wordlist io.Reader page, err := utils.GetWebPage(defaultWordlistURL, nil) if err != nil { return list, err } wordlist = strings.NewReader(page) scanner := bufio.NewScanner(wordlist) // Once we have used all the words, we are finished for scanner.Scan() { // Get the next word in the list word := scanner.Text() if word != "" { // Add the word to the list list = append(list, word) } } return list, nil }
// Copyright (c) 2016 Readium Foundation // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the organization nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. package index import ( "database/sql" "errors" "strings" "github.com/readium/readium-lcp-server/config" ) // ErrNotFound signals content not found var ErrNotFound = errors.New("Content not found") // Index is an interface type Index interface { Get(id string) (Content, error) Add(c Content) error Update(c Content) error List() func() (Content, error) } // Content represents an encrypted resource type Content struct { ID string `json:"id"` EncryptionKey []byte `json:"-"` Location string `json:"location"` Length int64 `json:"length"` //not exported in license spec? Sha256 string `json:"sha256"` //not exported in license spec? Type string `json:"type"` } type dbIndex struct { db *sql.DB get *sql.Stmt add *sql.Stmt list *sql.Stmt } func (i dbIndex) Get(id string) (Content, error) { records, err := i.get.Query(id) defer records.Close() if records.Next() { var c Content err = records.Scan(&c.ID, &c.EncryptionKey, &c.Location, &c.Length, &c.Sha256, &c.Type) return c, err } return Content{}, ErrNotFound } func (i dbIndex) Add(c Content) error { add, err := i.db.Prepare("INSERT INTO content (id,encryption_key,location,length,sha256,type) VALUES (?, ?, ?, ?, ?, ?)") if err != nil { return err } defer add.Close() _, err = add.Exec(c.ID, c.EncryptionKey, c.Location, c.Length, c.Sha256, c.Type) return err } func (i dbIndex) Update(c Content) error { add, err := i.db.Prepare("UPDATE content SET encryption_key=? , location=?, length=?, sha256=?, type=? WHERE id=?") if err != nil { return err } defer add.Close() _, err = add.Exec(c.EncryptionKey, c.Location, c.Length, c.Sha256, c.Type, c.ID) return err } func (i dbIndex) List() func() (Content, error) { rows, err := i.list.Query() if err != nil { return func() (Content, error) { return Content{}, err } } return func() (Content, error) { var c Content var err error if rows.Next() { err = rows.Scan(&c.ID, &c.EncryptionKey, &c.Location, &c.Length, &c.Sha256, &c.Type) } else { rows.Close() err = ErrNotFound } return c, err } } // Open opens an SQL database func Open(db *sql.DB) (i Index, err error) { // if sqlite, create the content table in the lcp db if it does not exist if strings.HasPrefix(config.Config.LcpServer.Database, "sqlite") { _, err = db.Exec(tableDef) if err != nil { return } db.Exec("ALTER TABLE content ADD COLUMN \"type\" varchar(255) NOT NULL DEFAULT 'application/epub+zip'") } get, err := db.Prepare("SELECT id,encryption_key,location,length,sha256,type FROM content WHERE id = ? LIMIT 1") if err != nil { return } list, err := db.Prepare("SELECT id,encryption_key,location,length,sha256,type FROM content") if err != nil { return } i = dbIndex{db, get, nil, list} return } const tableDef = "CREATE TABLE IF NOT EXISTS content (" + "id varchar(255) PRIMARY KEY," + "encryption_key varchar(64) NOT NULL," + "location text NOT NULL," + "length bigint," + "sha256 varchar(64)," + "\"type\" varchar(256) NOT NULL default 'application/epub+zip')"
package model import "time" // Woof db struct type Woof struct { ID string `db:"id"` Body string `db:"body"` CreatedAt time.Time `db:"created_at"` } // WoofRequest json struct type WoofRequest struct { Message string `json:"message"` } // WoofResponse json struct type WoofResponse struct { ID string `json:"id"` }
package response import ( "sort" "sync" "github.com/mayflower/docker-ls/lib" ) type RepositoryL0 string type RepositoryCollectionL0 []RepositoryL0 func (r RepositoryCollectionL0) Len() int { return len(r) } func (r RepositoryCollectionL0) Less(i, j int) bool { return string(r[i]) < string(r[j]) } func (r RepositoryCollectionL0) Swap(i, j int) { tmp := r[i] r[i] = r[j] r[j] = tmp } type RepositoriesL0 struct { Repositories []RepositoryL0 `yaml:"repositories",json:"repositories"` mutex sync.Mutex } func (r *RepositoriesL0) AddRepository(repo lib.Repository) { r.mutex.Lock() r.Repositories = append(r.Repositories, RepositoryL0(repo.Name())) r.mutex.Unlock() } func (r *RepositoriesL0) Sort() { r.mutex.Lock() sort.Sort(RepositoryCollectionL0(r.Repositories)) r.mutex.Unlock() } func NewRepositoriesL0() *RepositoriesL0 { return new(RepositoriesL0) } type RepositoryL1 *TagsL0 type RepositoryCollectionL1 []RepositoryL1 func (r RepositoryCollectionL1) Len() int { return len(r) } func (r RepositoryCollectionL1) Less(i, j int) bool { return string(r[i].RepositoryName) < string(r[j].RepositoryName) } func (r RepositoryCollectionL1) Swap(i, j int) { tmp := r[i] r[i] = r[j] r[j] = tmp } type RepositoriesL1 struct { Repositories []RepositoryL1 `yaml:"repositories",json:"repositories"` mutex sync.Mutex } func (r *RepositoriesL1) AddTags(tags *TagsL0) { r.mutex.Lock() r.Repositories = append(r.Repositories, RepositoryL1(tags)) r.mutex.Unlock() } func (r *RepositoriesL1) Sort() { r.mutex.Lock() sort.Sort(RepositoryCollectionL1(r.Repositories)) r.mutex.Unlock() for _, repository := range r.Repositories { (*TagsL0)(repository).Sort() } } func NewRepositoriesL1() *RepositoriesL1 { return new(RepositoriesL1) }
package train type TypeOfCarriage int const ( COMPARTMENT TypeOfCarriage = iota BUSINESS ECONOM )
// This file was generated by counterfeiter package fake_routing_table import ( "sync" . "github.com/cloudfoundry-incubator/route-emitter/routing_table" ) type FakeRoutingTable struct { SyncStub func(routes RoutesByProcessGuid, containers ContainersByProcessGuid) MessagesToEmit syncMutex sync.RWMutex syncArgsForCall []struct { arg1 RoutesByProcessGuid arg2 ContainersByProcessGuid } syncReturns struct { result1 MessagesToEmit } MessagesToEmitStub func() MessagesToEmit messagesToEmitMutex sync.RWMutex messagesToEmitArgsForCall []struct{} messagesToEmitReturns struct { result1 MessagesToEmit } SetRoutesStub func(processGuid string, routes ...string) MessagesToEmit setRoutesMutex sync.RWMutex setRoutesArgsForCall []struct { arg1 string arg2 []string } setRoutesReturns struct { result1 MessagesToEmit } RemoveRoutesStub func(processGuid string) MessagesToEmit removeRoutesMutex sync.RWMutex removeRoutesArgsForCall []struct { arg1 string } removeRoutesReturns struct { result1 MessagesToEmit } AddOrUpdateContainerStub func(processGuid string, container Container) MessagesToEmit addOrUpdateContainerMutex sync.RWMutex addOrUpdateContainerArgsForCall []struct { arg1 string arg2 Container } addOrUpdateContainerReturns struct { result1 MessagesToEmit } RemoveContainerStub func(processGuid string, container Container) MessagesToEmit removeContainerMutex sync.RWMutex removeContainerArgsForCall []struct { arg1 string arg2 Container } removeContainerReturns struct { result1 MessagesToEmit } } func (fake *FakeRoutingTable) Sync(arg1 RoutesByProcessGuid, arg2 ContainersByProcessGuid) MessagesToEmit { fake.syncMutex.Lock() defer fake.syncMutex.Unlock() fake.syncArgsForCall = append(fake.syncArgsForCall, struct { arg1 RoutesByProcessGuid arg2 ContainersByProcessGuid }{arg1, arg2}) if fake.SyncStub != nil { return fake.SyncStub(arg1, arg2) } else { return fake.syncReturns.result1 } } func (fake *FakeRoutingTable) SyncCallCount() int { fake.syncMutex.RLock() defer fake.syncMutex.RUnlock() return len(fake.syncArgsForCall) } func (fake *FakeRoutingTable) SyncArgsForCall(i int) (RoutesByProcessGuid, ContainersByProcessGuid) { fake.syncMutex.RLock() defer fake.syncMutex.RUnlock() return fake.syncArgsForCall[i].arg1, fake.syncArgsForCall[i].arg2 } func (fake *FakeRoutingTable) SyncReturns(result1 MessagesToEmit) { fake.syncReturns = struct { result1 MessagesToEmit }{result1} } func (fake *FakeRoutingTable) MessagesToEmit() MessagesToEmit { fake.messagesToEmitMutex.Lock() defer fake.messagesToEmitMutex.Unlock() fake.messagesToEmitArgsForCall = append(fake.messagesToEmitArgsForCall, struct{}{}) if fake.MessagesToEmitStub != nil { return fake.MessagesToEmitStub() } else { return fake.messagesToEmitReturns.result1 } } func (fake *FakeRoutingTable) MessagesToEmitCallCount() int { fake.messagesToEmitMutex.RLock() defer fake.messagesToEmitMutex.RUnlock() return len(fake.messagesToEmitArgsForCall) } func (fake *FakeRoutingTable) MessagesToEmitReturns(result1 MessagesToEmit) { fake.messagesToEmitReturns = struct { result1 MessagesToEmit }{result1} } func (fake *FakeRoutingTable) SetRoutes(arg1 string, arg2 ...string) MessagesToEmit { fake.setRoutesMutex.Lock() defer fake.setRoutesMutex.Unlock() fake.setRoutesArgsForCall = append(fake.setRoutesArgsForCall, struct { arg1 string arg2 []string }{arg1, arg2}) if fake.SetRoutesStub != nil { return fake.SetRoutesStub(arg1, arg2...) } else { return fake.setRoutesReturns.result1 } } func (fake *FakeRoutingTable) SetRoutesCallCount() int { fake.setRoutesMutex.RLock() defer fake.setRoutesMutex.RUnlock() return len(fake.setRoutesArgsForCall) } func (fake *FakeRoutingTable) SetRoutesArgsForCall(i int) (string, []string) { fake.setRoutesMutex.RLock() defer fake.setRoutesMutex.RUnlock() return fake.setRoutesArgsForCall[i].arg1, fake.setRoutesArgsForCall[i].arg2 } func (fake *FakeRoutingTable) SetRoutesReturns(result1 MessagesToEmit) { fake.setRoutesReturns = struct { result1 MessagesToEmit }{result1} } func (fake *FakeRoutingTable) RemoveRoutes(arg1 string) MessagesToEmit { fake.removeRoutesMutex.Lock() defer fake.removeRoutesMutex.Unlock() fake.removeRoutesArgsForCall = append(fake.removeRoutesArgsForCall, struct { arg1 string }{arg1}) if fake.RemoveRoutesStub != nil { return fake.RemoveRoutesStub(arg1) } else { return fake.removeRoutesReturns.result1 } } func (fake *FakeRoutingTable) RemoveRoutesCallCount() int { fake.removeRoutesMutex.RLock() defer fake.removeRoutesMutex.RUnlock() return len(fake.removeRoutesArgsForCall) } func (fake *FakeRoutingTable) RemoveRoutesArgsForCall(i int) string { fake.removeRoutesMutex.RLock() defer fake.removeRoutesMutex.RUnlock() return fake.removeRoutesArgsForCall[i].arg1 } func (fake *FakeRoutingTable) RemoveRoutesReturns(result1 MessagesToEmit) { fake.removeRoutesReturns = struct { result1 MessagesToEmit }{result1} } func (fake *FakeRoutingTable) AddOrUpdateContainer(arg1 string, arg2 Container) MessagesToEmit { fake.addOrUpdateContainerMutex.Lock() defer fake.addOrUpdateContainerMutex.Unlock() fake.addOrUpdateContainerArgsForCall = append(fake.addOrUpdateContainerArgsForCall, struct { arg1 string arg2 Container }{arg1, arg2}) if fake.AddOrUpdateContainerStub != nil { return fake.AddOrUpdateContainerStub(arg1, arg2) } else { return fake.addOrUpdateContainerReturns.result1 } } func (fake *FakeRoutingTable) AddOrUpdateContainerCallCount() int { fake.addOrUpdateContainerMutex.RLock() defer fake.addOrUpdateContainerMutex.RUnlock() return len(fake.addOrUpdateContainerArgsForCall) } func (fake *FakeRoutingTable) AddOrUpdateContainerArgsForCall(i int) (string, Container) { fake.addOrUpdateContainerMutex.RLock() defer fake.addOrUpdateContainerMutex.RUnlock() return fake.addOrUpdateContainerArgsForCall[i].arg1, fake.addOrUpdateContainerArgsForCall[i].arg2 } func (fake *FakeRoutingTable) AddOrUpdateContainerReturns(result1 MessagesToEmit) { fake.addOrUpdateContainerReturns = struct { result1 MessagesToEmit }{result1} } func (fake *FakeRoutingTable) RemoveContainer(arg1 string, arg2 Container) MessagesToEmit { fake.removeContainerMutex.Lock() defer fake.removeContainerMutex.Unlock() fake.removeContainerArgsForCall = append(fake.removeContainerArgsForCall, struct { arg1 string arg2 Container }{arg1, arg2}) if fake.RemoveContainerStub != nil { return fake.RemoveContainerStub(arg1, arg2) } else { return fake.removeContainerReturns.result1 } } func (fake *FakeRoutingTable) RemoveContainerCallCount() int { fake.removeContainerMutex.RLock() defer fake.removeContainerMutex.RUnlock() return len(fake.removeContainerArgsForCall) } func (fake *FakeRoutingTable) RemoveContainerArgsForCall(i int) (string, Container) { fake.removeContainerMutex.RLock() defer fake.removeContainerMutex.RUnlock() return fake.removeContainerArgsForCall[i].arg1, fake.removeContainerArgsForCall[i].arg2 } func (fake *FakeRoutingTable) RemoveContainerReturns(result1 MessagesToEmit) { fake.removeContainerReturns = struct { result1 MessagesToEmit }{result1} } var _ RoutingTableInterface = new(FakeRoutingTable)
package service import ( "context" "fmt" "io" "net/http" "time" "github.com/gofrs/uuid" "github.com/patrickmn/go-cache" pbAS "github.com/go-ocf/cloud/authorization/pb" "github.com/go-ocf/cloud/cloud2cloud-connector/events" "github.com/go-ocf/cloud/cloud2cloud-connector/store" projectionRA "github.com/go-ocf/cloud/resource-aggregate/cqrs/projection" pbRA "github.com/go-ocf/cloud/resource-aggregate/pb" "github.com/go-ocf/kit/codec/json" "github.com/go-ocf/kit/log" kitHttp "github.com/go-ocf/kit/net/http" ) const AuthorizationHeader string = "Authorization" const AcceptHeader string = "Accept" const Cloud2cloudConnectorConnectionId string = "cloud2cloud-connector" type SubscribeManager struct { eventsURL string store store.Store raClient pbRA.ResourceAggregateClient asClient pbAS.AuthorizationServiceClient resourceProjection *projectionRA.Projection cache *cache.Cache } func NewSubscriptionManager(EventsURL string, asClient pbAS.AuthorizationServiceClient, raClient pbRA.ResourceAggregateClient, store store.Store, resourceProjection *projectionRA.Projection) *SubscribeManager { return &SubscribeManager{ eventsURL: EventsURL, store: store, raClient: raClient, asClient: asClient, cache: cache.New(time.Minute*10, time.Minute*5), resourceProjection: resourceProjection, } } func subscribe(ctx context.Context, href, correlationID string, reqBody events.SubscriptionRequest, l store.LinkedAccount) (resp events.SubscriptionResponse, err error) { client := http.Client{} r, w := io.Pipe() req, err := http.NewRequest("POST", l.TargetURL+kitHttp.CanonicalHref(href), r) if err != nil { return resp, fmt.Errorf("cannot create post request: %v", err) } req.Header.Set(events.CorrelationIDKey, correlationID) req.Header.Set("Accept", events.ContentType_JSON+","+events.ContentType_CBOR+","+events.ContentType_VNDOCFCBOR) req.Header.Set(events.ContentTypeKey, events.ContentType_JSON) req.Header.Set(AuthorizationHeader, "Bearer "+string(l.TargetCloud.AccessToken)) go func() { defer w.Close() err := json.WriteTo(w, reqBody) if err != nil { log.Errorf("cannot encode to json: %v", err) } }() httpResp, err := client.Do(req) if err != nil { return resp, fmt.Errorf("cannot post: %v", err) } defer httpResp.Body.Close() if httpResp.StatusCode != http.StatusOK { return resp, fmt.Errorf("unexpected statusCode %v", httpResp.StatusCode) } err = json.ReadFrom(httpResp.Body, &resp) if err != nil { return resp, fmt.Errorf("cannot device response: %v", err) } return resp, nil } func cancelSubscription(ctx context.Context, href string, l store.LinkedAccount) error { client := http.Client{} req, err := http.NewRequest("DELETE", l.TargetURL+kitHttp.CanonicalHref(href), nil) if err != nil { return fmt.Errorf("cannot create delete request: %v", err) } req.Header.Set("Token", l.ID) req.Header.Set("Accept", events.ContentType_JSON+","+events.ContentType_CBOR+","+events.ContentType_VNDOCFCBOR) req.Header.Set(AuthorizationHeader, "Bearer "+string(l.TargetCloud.AccessToken)) httpResp, err := client.Do(req) if err != nil { return fmt.Errorf("cannot delete: %v", err) } defer httpResp.Body.Close() if httpResp.StatusCode != http.StatusOK { return fmt.Errorf("unexpected statusCode %v", httpResp.StatusCode) } return nil } type SubscriptionHandler struct { subscription store.Subscription ok bool } func (h *SubscriptionHandler) Handle(ctx context.Context, iter store.SubscriptionIter) (err error) { var s store.Subscription if iter.Next(ctx, &s) { h.ok = true h.subscription = s return iter.Err() } return iter.Err() } func (s *SubscribeManager) HandleEvent(ctx context.Context, header events.EventHeader, body []byte) (int, error) { var subData subscriptionData var err error data, ok := s.cache.Get(header.CorrelationID) if ok { subData = data.(subscriptionData) subData.subscription.SubscriptionID = header.SubscriptionID newSubscription, err := s.store.FindOrCreateSubscription(ctx, subData.subscription) if err != nil { cancelDevicesSubscription(ctx, subData.linkedAccount, subData.subscription.SubscriptionID) return http.StatusGone, fmt.Errorf("cannot store subscription to DB: %v", err) } subData.subscription = newSubscription } else { var h SubscriptionHandler err := s.store.LoadSubscriptions(ctx, []store.SubscriptionQuery{{SubscriptionID: header.SubscriptionID}}, &h) if err != nil { return http.StatusGone, fmt.Errorf("cannot load subscription from DB: %v", err) } if !h.ok { return http.StatusGone, fmt.Errorf("unknown subscription %v, eventType %v", header.SubscriptionID, header.EventType) } subData.subscription = h.subscription var lh LinkedAccountHandler err = s.store.LoadLinkedAccounts(ctx, store.Query{ID: subData.subscription.LinkedAccountID}, &lh) if err != nil { return http.StatusGone, fmt.Errorf("cannot load linked account for subscription %v: %v", header.SubscriptionID, err) } if !h.ok { return http.StatusGone, fmt.Errorf("unknown linked account %v subscription %v", subData.subscription.LinkedAccountID, subData.subscription.SubscriptionID) } subData.linkedAccount = lh.linkedAccount } // verify event signature if header.EventSignature != events.CalculateEventSignature(subData.subscription.SigningSecret, header.ContentType, header.EventType, header.SubscriptionID, header.SequenceNumber, header.EventTimestamp, body) { return http.StatusBadRequest, fmt.Errorf("invalid event signature %v: %v", header.SubscriptionID, err) } s.cache.Set(header.CorrelationID, subData, cache.DefaultExpiration) subData.linkedAccount, err = subData.linkedAccount.RefreshTokens(ctx, s.store) if err != nil { return http.StatusGone, fmt.Errorf("cannot refresh access token for linked account %v: %v", subData.linkedAccount.ID, err) } if header.EventType == events.EventType_SubscriptionCanceled { err := s.HandleCancelEvent(ctx, header, subData.linkedAccount) if err != nil { return http.StatusGone, fmt.Errorf("cannot cancel subscription: %v", err) } return http.StatusOK, nil } switch subData.subscription.Type { case store.Type_Devices: err = s.HandleDevicesEvent(ctx, header, body, subData) case store.Type_Device: err = s.HandleDeviceEvent(ctx, header, body, subData) case store.Type_Resource: err = s.HandleResourceEvent(ctx, header, body, subData) default: return http.StatusGone, fmt.Errorf("cannot handle event %v: handler not found", header.EventType) } if err != nil { return http.StatusGone, err } return http.StatusOK, nil } type LinkedAccountHandler struct { linkedAccount store.LinkedAccount ok bool } func (h *LinkedAccountHandler) Handle(ctx context.Context, iter store.LinkedAccountIter) (err error) { var s store.LinkedAccount if iter.Next(ctx, &s) { h.ok = true h.linkedAccount = s return iter.Err() } return fmt.Errorf("not found") } func (s *SubscribeManager) HandleCancelEvent(ctx context.Context, header events.EventHeader, linkedAccount store.LinkedAccount) error { var h SubscriptionHandler err := s.store.LoadSubscriptions(ctx, []store.SubscriptionQuery{{SubscriptionID: header.SubscriptionID}}, &h) if err != nil { return fmt.Errorf("cannot load subscription from DB: %v", err) } if !h.ok { return fmt.Errorf("unknown subscription %v, eventType %v", header.SubscriptionID, header.EventType) } return s.store.RemoveSubscriptions(ctx, store.SubscriptionQuery{SubscriptionID: header.SubscriptionID}) } type subscriptionData struct { linkedAccount store.LinkedAccount subscription store.Subscription } func (s *SubscribeManager) StartSubscriptions(ctx context.Context, l store.LinkedAccount) error { signingSecret, err := generateRandomString(32) if err != nil { return fmt.Errorf("cannot generate signingSecret for start subscriptions: %v", err) } corID, err := uuid.NewV4() if err != nil { return fmt.Errorf("cannot generate correlationID for start subscriptions: %v", err) } correlationID := corID.String() sub := store.Subscription{ Type: store.Type_Devices, LinkedAccountID: l.ID, SigningSecret: signingSecret, } err = s.cache.Add(correlationID, subscriptionData{ linkedAccount: l, subscription: sub, }, cache.DefaultExpiration) if err != nil { return fmt.Errorf("cannot cache subscription for start subscriptions: %v", err) } sub.SubscriptionID, err = s.subscribeToDevices(ctx, l, correlationID, signingSecret) if err != nil { s.cache.Delete(correlationID) return fmt.Errorf("cannot subscribe to devices for %v: %v", l.ID, err) } _, err = s.store.FindOrCreateSubscription(ctx, sub) if err != nil { cancelDevicesSubscription(ctx, l, sub.SubscriptionID) return fmt.Errorf("cannot store subscription to DB: %v", err) } return nil } type SubscriptionsHandler struct { subscriptions []store.Subscription } func (h *SubscriptionsHandler) Handle(ctx context.Context, iter store.SubscriptionIter) (err error) { var s store.Subscription for iter.Next(ctx, &s) { h.subscriptions = append(h.subscriptions, s) } return iter.Err() } func (s *SubscribeManager) StopSubscriptions(ctx context.Context, l store.LinkedAccount) error { var h SubscriptionsHandler err := s.store.LoadSubscriptions(ctx, []store.SubscriptionQuery{{LinkedAccountID: l.ID}}, &h) if err != nil { return fmt.Errorf("cannot load subscriptions: %v", err) } if len(h.subscriptions) == 0 { return nil } l, err = l.RefreshTokens(ctx, s.store) var errors []error for _, sub := range h.subscriptions { switch sub.Type { case store.Type_Devices: err = cancelDevicesSubscription(ctx, l, sub.SubscriptionID) if err != nil { errors = append(errors, err) } case store.Type_Device: err = cancelDeviceSubscription(ctx, l, sub.DeviceID, sub.SubscriptionID) if err != nil { errors = append(errors, err) } case store.Type_Resource: err = cancelResourceSubscription(ctx, l, sub.DeviceID, sub.Href, sub.SubscriptionID) if err != nil { errors = append(errors, err) } } } err = s.store.RemoveSubscriptions(ctx, store.SubscriptionQuery{LinkedAccountID: l.ID}) if err != nil { errors = append(errors, err) } if len(errors) > 0 { return fmt.Errorf("%v", errors) } return nil }