text
stringlengths
11
4.05M
package log import ( "sync" ) var _ Labels = (*labels)(nil) type labels sync.Map // NewLabels returns a Labels instance. func NewLabels() Labels { l := labels(sync.Map{}) return &l } func (l *labels) Get(key string) (string, bool) { value, ok := (*sync.Map)(l).Load(key) return value.(string), ok } func (l *labels) Set(key string, value string) { (*sync.Map)(l).Store(key, value) } func (l *labels) Delete(key string) { (*sync.Map)(l).Delete(key) } func (l *labels) Clone() Labels { cloned := NewLabels() m := (*sync.Map)(l) m.Range(func(k, v interface{}) bool { cloned.Set(k.(string), v.(string)) return true }) return cloned } func (l *labels) CloneAsMap() map[string]string { m := make(map[string]string) syncM := (*sync.Map)(l) syncM.Range(func(k, v interface{}) bool { m[k.(string)] = v.(string) return true }) return m } func (l *labels) Map() map[string]string { return l.CloneAsMap() }
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) var ( a AddressBook message string ) func initialize() { a = AddressBook{} fmt.Println(" \n------------------------------------ ") fmt.Println(" 📕 Welcome To Your Address Book 📗 ") fmt.Println("------------------------------------ ") fmt.Println("😌 Here Are Your Options Today 😌 ") fmt.Println("------------------------------------ ") fmt.Println(" 1 ⇢ Display data in address book") fmt.Println(" 2 ⇢ Save to file") fmt.Println(" 3 ⇢ Add an entry") fmt.Println(" 4 ⇢ Remove an entry") // fmt.Println(" 5 ⇢ Edit an existing entry") // fmt.Println(" 6 ⇢ Search for a specific entry") // fmt.Println(" 7 ⇢ Sort the address book") fmt.Println(" 5 ⇢ Quit") fmt.Println(" ----------------------------------- ") } func main() { initialize() fmt.Println(" Choose From The Numbers Above ") fmt.Println(" ----------------------------------- ") for { scanner := bufio.NewReader(os.Stdin) fmt.Print(" Please choose what you'd like to do with the database (1 - 9): ") operation, _ := scanner.ReadString('\n') operation = strings.TrimSuffix(operation, "\n") convOperation, err := strconv.Atoi(operation) if err != nil { log.Fatal(err) } switch convOperation { case 1: displayAllData() fmt.Println() break case 2: newEntry := createNewEntry() a.AddEntry(newEntry) case 3: newEntry := createNewEntry() a.AddEntry(newEntry) case 4: remove := getUserInput(" Remove Existing query using FirstName, LastName, Address or PhoneNumber: ") dataRemoved := a.RemoveEntry(remove) fmt.Println(" ⛑ The Data Below was successfully deleted ⛑ ") prettyPrint(dataRemoved) break case 5: break case 6: break case 7: break case 8: break case 9: fmt.Println(" Quitting Address Book.. ") return default: break } } } func prettyPrint(a []Entry) { fmt.Println("------------------------------------ ") for _, entry := range a { fmt.Printf("Id: %v\n", entry.ID) fmt.Println("FirstName: " + entry.FirstName) fmt.Println("LastName: " + entry.LastName) fmt.Println("PhoneNumber: " + entry.PhoneNumber) fmt.Println("------------------------------------ ") } } func displayAllData() { data := a.GetAllEntries() prettyPrint(data) } func createNewEntry() Entry { index := len(a.GetAllEntries()) fmt.Println(" 🗒 Create a new addressBook entry 🗒 ") fname := getUserInput(" Enter First Name: ") lname := getUserInput(" Enter Last Name: ") address := getUserInput(" Enter Address: ") phone := getUserInput(" Enter Phone Number: ") fmt.Println() return Entry{index + 1, fname, lname, address, phone} } func getUserInput(message string) string { scanner := bufio.NewReader(os.Stdin) fmt.Print(message) input, _ := scanner.ReadString('\n') input = strings.TrimSuffix(input, "\n") return input }
package main import ( "OneeSan/controllers" _ "OneeSan/models" "OneeSan/pixiv" _ "OneeSan/routers" "github.com/astaxie/beego" "strings" "time" ) func main() { getdelay, err := beego.AppConfig.Int("get_illust_delay") if controllers.CheckError(err) { return } pixiv.BooksLimit, err = beego.AppConfig.Int("add_books_limit") if controllers.CheckError(err) { return } controllers.SafeMode, err = beego.AppConfig.Bool("safe_mode") if controllers.CheckError(err) { return } pixiv.AllowAdd, err = beego.AppConfig.Bool("allow_add_illust") if controllers.CheckError(err) { return } controllers.FreqLimit, err = beego.AppConfig.Int("add_freq_limit") if controllers.CheckError(err) { return } pixiv.DiscoEveryDelay, err = beego.AppConfig.Int("illust_every_delay") if controllers.CheckError(err) { return } discodelay, err := beego.AppConfig.Int("illust_disco_delay") if controllers.CheckError(err) { return } banedtags := beego.AppConfig.String("baned_tags") if len(banedtags) != 0 { pixiv.BanedTags = strings.Split(banedtags, ",") } allowtags := beego.AppConfig.String("allow_tags") if len(allowtags) != 0 { pixiv.AllowTags = strings.Split(allowtags, ",") } pixiv.PixivCookie = beego.AppConfig.String("pixiv_cookie") go WhileGet(getdelay) go WhileCount() go WhileResetFreq() go WhileDiscoIllust(discodelay) beego.Run() } func WhileGet(delay int) { for delay > 0 { pixiv.AddRandomIllust() time.Sleep(time.Duration(delay) * time.Millisecond) } } func WhileCount() { for { count := pixiv.DBCount() if count != -1 { controllers.DB_counts = pixiv.DBCount() } time.Sleep(time.Duration(1000) * time.Millisecond) } } func WhileResetFreq() { for { controllers.AddCounts = 0 time.Sleep(time.Duration(1000) * time.Millisecond) } } func WhileDiscoIllust(delay int) { for delay > 0 { pixiv.IllustDiscovery() time.Sleep(time.Duration(delay) * time.Minute) } }
package models import ( "gorm.io/gorm" "time" ) type BaseModel struct { CreatedAt *time.Time `gorm:"created_at" json:"createdAt"` UpdatedAt *time.Time `gorm:"updated_at" json:"updatedAt"` CreateBy string `gorm:"create_by" json:"createBy"` UpdateBy string `gorm:"update_by" json:"updateBy"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deleteAt"` DeleteBy string `gorm:"delete_by" json:"deleteBy"` ID uint `gorm:"primaryKey;autoIncrement" json:"id"` }
package ws_local_server import ( "encoding/json" "open_im_sdk/open_im_sdk" ) type GroupCallback struct { uid string } func (g *GroupCallback) OnMemberEnter(groupId string, memberList string) { m := make(map[string]interface{}, 2) m["groupId"] = groupId m["memberList"] = memberList j, _ := json.Marshal(m) SendOneUserMessage(EventData{cleanUpfuncName(runFuncName()), 0, "", string(j), "0"}, g.uid) } func (g *GroupCallback) OnMemberLeave(groupId string, memberList string) { m := make(map[string]interface{}, 2) m["groupId"] = groupId m["memberList"] = memberList j, _ := json.Marshal(m) SendOneUserMessage(EventData{cleanUpfuncName(runFuncName()), 0, "", string(j), "0"}, g.uid) } func (g *GroupCallback) OnMemberInvited(groupId string, opUser string, memberList string) { m := make(map[string]interface{}, 3) m["groupId"] = groupId m["opUser"] = opUser m["memberList"] = memberList j, _ := json.Marshal(m) SendOneUserMessage(EventData{cleanUpfuncName(runFuncName()), 0, "", string(j), "0"}, g.uid) } func (g *GroupCallback) OnMemberKicked(groupId string, opUser string, memberList string) { m := make(map[string]interface{}, 3) m["groupId"] = groupId m["opUser"] = opUser m["memberList"] = memberList j, _ := json.Marshal(m) SendOneUserMessage(EventData{cleanUpfuncName(runFuncName()), 0, "", string(j), "0"}, g.uid) } func (g *GroupCallback) OnGroupCreated(groupId string) { m := make(map[string]interface{}, 1) m["groupId"] = groupId j, _ := json.Marshal(m) SendOneUserMessage(EventData{cleanUpfuncName(runFuncName()), 0, "", string(j), "0"}, g.uid) } func (g *GroupCallback) OnGroupInfoChanged(groupId string, groupInfo string) { m := make(map[string]interface{}, 2) m["groupId"] = groupId m["groupInfo"] = groupInfo j, _ := json.Marshal(m) SendOneUserMessage(EventData{cleanUpfuncName(runFuncName()), 0, "", string(j), "0"}, g.uid) } func (g *GroupCallback) OnReceiveJoinApplication(groupId string, member string, opReason string) { m := make(map[string]interface{}, 3) m["groupId"] = groupId m["member"] = member m["opReason"] = opReason j, _ := json.Marshal(m) SendOneUserMessage(EventData{cleanUpfuncName(runFuncName()), 0, "", string(j), "0"}, g.uid) } func (g *GroupCallback) OnApplicationProcessed(groupId string, opUser string, AgreeOrReject int32, opReason string) { m := make(map[string]interface{}, 4) m["groupId"] = groupId m["opUser"] = opUser m["AgreeOrReject"] = AgreeOrReject m["opReason"] = opReason j, _ := json.Marshal(m) SendOneUserMessage(EventData{cleanUpfuncName(runFuncName()), 0, "", string(j), "0"}, g.uid) } func (wsRouter *WsFuncRouter) SetGroupListener() { var g GroupCallback g.uid = wsRouter.uId userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.SetGroupListener(&g) } func (wsRouter *WsFuncRouter) CreateGroup(input, operationID string) { m := make(map[string]interface{}) if err := json.Unmarshal([]byte(input), &m); err != nil { wrapSdkLog("unmarshal failed") wsRouter.GlobalSendMessage(EventData{cleanUpfuncName(runFuncName()), 1001, "unmarshal failed", "", operationID}) return } if !wsRouter.checkKeysIn(input, operationID, runFuncName(), m, "gInfo", "memberList") { return } userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.CreateGroup(m["gInfo"].(string), m["memberList"].(string), &BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) } func (wsRouter *WsFuncRouter) JoinGroup(input, operationID string) { m := make(map[string]interface{}) if err := json.Unmarshal([]byte(input), &m); err != nil { wrapSdkLog("unmarshal failed") wsRouter.GlobalSendMessage(EventData{cleanUpfuncName(runFuncName()), 1001, "unmarshal failed", "", operationID}) return } if !wsRouter.checkKeysIn(input, operationID, runFuncName(), m, "groupId", "message") { return } userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.JoinGroup(m["groupId"].(string), m["message"].(string), &BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) } func (wsRouter *WsFuncRouter) QuitGroup(groupId, operationID string) { userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.QuitGroup(groupId, &BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) } func (wsRouter *WsFuncRouter) GetJoinedGroupList(input, operationID string) { userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.GetJoinedGroupList(&BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) } func (wsRouter *WsFuncRouter) GetGroupsInfo(input, operationID string) { //(groupIdList string, callback Base) { m := make(map[string]interface{}) if err := json.Unmarshal([]byte(input), &m); err != nil { wrapSdkLog("unmarshal failed") wsRouter.GlobalSendMessage(EventData{cleanUpfuncName(runFuncName()), 1001, "unmarshal failed", "", operationID}) return } if !wsRouter.checkKeysIn(input, operationID, runFuncName(), m, "groupIdList") { return } userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.GetGroupsInfo(m["groupIdList"].(string), &BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) } func (wsRouter *WsFuncRouter) SetGroupInfo(input, operationID string) { m := make(map[string]interface{}) if err := json.Unmarshal([]byte(input), &m); err != nil { wrapSdkLog("unmarshal failed") wsRouter.GlobalSendMessage(EventData{cleanUpfuncName(runFuncName()), 1001, "unmarshal failed", "", operationID}) return } if !wsRouter.checkKeysIn(input, operationID, runFuncName(), m, "groupInfo") { return } userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.SetGroupInfo(m["groupInfo"].(string), &BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) } func (wsRouter *WsFuncRouter) GetGroupMemberList(input, operationID string) { //(groupId string, filter int32, next int32, callback Base) { m := make(map[string]interface{}) if err := json.Unmarshal([]byte(input), &m); err != nil { wrapSdkLog("unmarshal failed") wsRouter.GlobalSendMessage(EventData{cleanUpfuncName(runFuncName()), 1001, "unmarshal failed", "", operationID}) return } if !wsRouter.checkKeysIn(input, operationID, runFuncName(), m, "groupId", "filter", "next") { return } userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.GetGroupMemberList(m["groupId"].(string), int32(m["filter"].(float64)), int32(m["next"].(float64)), &BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) } func (wsRouter *WsFuncRouter) GetGroupMembersInfo(input, operationID string) { //(groupId string, userList string, callback Base) { m := make(map[string]interface{}) if err := json.Unmarshal([]byte(input), &m); err != nil { wrapSdkLog("unmarshal failed") wsRouter.GlobalSendMessage(EventData{cleanUpfuncName(runFuncName()), 1001, "unmarshal failed", "", operationID}) return } if !wsRouter.checkKeysIn(input, operationID, runFuncName(), m, "groupId", "userList") { return } userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.GetGroupMembersInfo(m["groupId"].(string), m["userList"].(string), &BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) } func (wsRouter *WsFuncRouter) KickGroupMember(input, operationID string) { //(groupId string, reason string, userList string, callback Base) { m := make(map[string]interface{}) if err := json.Unmarshal([]byte(input), &m); err != nil { wrapSdkLog("unmarshal failed") wsRouter.GlobalSendMessage(EventData{cleanUpfuncName(runFuncName()), 1001, "unmarshal failed", "", operationID}) return } if !wsRouter.checkKeysIn(input, operationID, runFuncName(), m, "groupId", "reason", "userList") { return } userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.KickGroupMember(m["groupId"].(string), m["reason"].(string), m["userList"].(string), &BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) } func (wsRouter *WsFuncRouter) TransferGroupOwner(input, operationID string) { //(groupId, userId string, callback Base) { m := make(map[string]interface{}) if err := json.Unmarshal([]byte(input), &m); err != nil { wrapSdkLog("unmarshal failed") wsRouter.GlobalSendMessage(EventData{cleanUpfuncName(runFuncName()), 1001, "unmarshal failed", "", operationID}) return } if !wsRouter.checkKeysIn(input, operationID, runFuncName(), m, "groupId", "userId") { return } userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.TransferGroupOwner(m["groupId"].(string), m["userId"].(string), &BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) } func (wsRouter *WsFuncRouter) InviteUserToGroup(input, operationID string) { //(groupId, reason string, userList string, callback Base) { m := make(map[string]interface{}) if err := json.Unmarshal([]byte(input), &m); err != nil { wrapSdkLog("unmarshal failed") wsRouter.GlobalSendMessage(EventData{cleanUpfuncName(runFuncName()), 1001, "unmarshal failed", "", operationID}) return } if !wsRouter.checkKeysIn(input, operationID, runFuncName(), m, "groupId", "reason", "userList") { return } userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.InviteUserToGroup(m["groupId"].(string), m["reason"].(string), m["userList"].(string), &BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) } func (wsRouter *WsFuncRouter) GetGroupApplicationList(input, operationID string) { //(callback Base) { userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.GetGroupApplicationList(&BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) } func (wsRouter *WsFuncRouter) AcceptGroupApplication(input, operationID string) { //(application, reason string, callback Base) { m := make(map[string]interface{}) if err := json.Unmarshal([]byte(input), &m); err != nil { wrapSdkLog("unmarshal failed") wsRouter.GlobalSendMessage(EventData{cleanUpfuncName(runFuncName()), 1001, "unmarshal failed", "", operationID}) return } if !wsRouter.checkKeysIn(input, operationID, runFuncName(), m, "application", "reason") { return } userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.AcceptGroupApplication(m["application"].(string), m["reason"].(string), &BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) } func (wsRouter *WsFuncRouter) RefuseGroupApplication(input, operationID string) { //(application, reason string, callback Base) { m := make(map[string]interface{}) if err := json.Unmarshal([]byte(input), &m); err != nil { wrapSdkLog("unmarshal failed") wsRouter.GlobalSendMessage(EventData{cleanUpfuncName(runFuncName()), 1001, "unmarshal failed", "", operationID}) return } if !wsRouter.checkKeysIn(input, operationID, runFuncName(), m, "application", "reason") { return } userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.RefuseGroupApplication(m["application"].(string), m["reason"].(string), &BaseSuccFailed{runFuncName(), operationID, wsRouter.uId}) }
package main import ( "./dao" "./http" "./socket" "./types" "encoding/gob" "encoding/json" "flag" "fmt" "log" "net" "os" "strconv" "strings" "time" ) /* Note - I am still learning a lot about Go. I'm not sure how much of this is idiomatic. Its just a hobby / learning experiment and a bit of fun. */ //TODO Set the domain based upon the path the executable was run from var domain string = "dev.myclublink.com.au" var service = flag.String("service", ":6969", "tcp port to bind to") var lat = flag.String("lat", "", "latitude to test") var lon = flag.String("long", "", "longitude to test") func init() { gob.Register(types.User{}) gob.Register(types.Company{}) gob.Register(types.Settings{}) } func main() { var addr = flag.String("addr", ":8080", "http(s) service address") flag.Parse() if _, err := os.Stat("backend.db"); err != nil { log.Fatal("\nError: ", err) } if _, err := os.Stat("license.key"); err != nil { log.Fatal("\nError: ", err) } dao.Open() //TODO remove this shit.. its just testing street name stuff if *lat != "" && *lon != "" { street := dao.GetStreetName(*lat, *lon) fmt.Printf("\nStreet is %s\n", street) os.Exit(0) } defer dao.Close() //Socket related channels WSDataChannel := make(chan types.Record, 100) //buffered WSCommandChannel := make(chan int32) NetworkChannel := make(chan int32, 1) //buffered go socket.Monitor(WSDataChannel, WSCommandChannel) //Start a websocket dude to arbitrate websockets go connectionManager(NetworkChannel, WSCommandChannel, WSDataChannel) //Connection manager to handle (re)connects go http.HttpRouter(addr) /Kick off initial connection - send COMMAND_RECONNECT on the Network Channel NetworkChannel <- types.COMMAND_RECONNECT //Wait forever nicely select {} } func connectionManager(NetworkChannel chan int32, WSCommandChannel chan<- int32, WSDataChannel chan<- types.Record) { //Select from first available channel ipc - note this blocks until there is data in one of the channels select { //Keep slurping records from the bufered channel and farm them out to UpdateClient as a goroutine case msg := <-NetworkChannel: switch msg { case types.COMMAND_RECONNECT: lnk, err := net.Listen("tcp", *service) if err != nil { fmt.Printf("\nFailed to get tcp listener - %s", err.Error()) os.Exit(1) } fmt.Printf("\nListening on TCP Port %s", *service) for { //this blocks until there is a connection tcpcon, err := lnk.Accept() fmt.Printf("\nLink Accepted - Receiving packets from Vehicle") if err != nil { fmt.Printf("\nFailed to create tcp connection - %s", err) os.Exit(1) } go handleClient(tcpcon.(*net.TCPConn), WSDataChannel, NetworkChannel) } } } } fmt.Printf("\nFailed to insert row %s", err) func handleClient(conn *net.TCPConn, WSDataChannel chan<- types.Record, NetworkChannel chan<- int32) { //defer anonymous func to handle panics - most likely panicking from garbage that was to be parsed. defer func() { if r := recover(); r != nil { fmt.Println("Recovered from a panic \n", r) } }() var buff = make([]byte, 512) var incomingpacket types.Packet var R types.Record R.GPS = new(types.GPSRecord) R.Diagnostic = new(types.DiagnosticRecord) var n int var err error for { n, err = conn.Read(buff) if err != nil { fmt.Printf("\nError occured - %s, will recreate the connection.", err.Error()) NetworkChannel <- types.COMMAND_RECONNECT return } //lets unmarshal those JSON bytes into the map https://groups.google.com/forum/#!topic/golang-nuts/77HJlZhWXpk note to slice properly otherwise it chokes on trying to decode the full buffer err := json.Unmarshal(buff[:n], &incomingpacket) if err != nil { fmt.Printf("Failed to decode the JSON bytes -%s\n", err.Error()) } diagnosticfields := strings.Split(string(incomingpacket["diagnostics"]), ",") if len(diagnosticfields) != 4 { fmt.Printf("Error. Diagnostic fields length is incorrect. Is %d should be %d", len(diagnosticfields), 4) fmt.Printf("The source string was %s\n", string(incomingpacket["diagnostics"])) } gpsfields := strings.Split(string(incomingpacket["sentence"]), ",") if len(gpsfields) != 7 { fmt.Printf("Error. GPS fields length is incorrect. Is %d should be %d\n", len(gpsfields), 7) fmt.Printf("The source string was %s\n", string(incomingpacket["sentence"])) continue } R.Diagnostic.CPUTemp, _ = strconv.ParseFloat(diagnosticfields[0][2:], 32) R.Diagnostic.CPUVolt, _ = strconv.ParseFloat(diagnosticfields[1][2:], 32) R.Diagnostic.CPUFreq, _ = strconv.ParseFloat(diagnosticfields[2][2:], 32) R.Diagnostic.MemFree, _ = strconv.ParseUint(diagnosticfields[3][2:], 10, 64) R.GPS.Message = gpsfields[0][1:] R.GPS.Latitude = gpsfields[0][2:] R.GPS.Longitude = gpsfields[1] R.GPS.Speed, _ = strconv.ParseFloat(gpsfields[2][1:], 32) R.GPS.Heading, _ = strconv.ParseFloat(gpsfields[3][1:], 32) R.GPS.Date, _ = time.Parse(time.RFC3339, gpsfields[4][1:]) R.GPS.Fix = gpsfields[5][1:] == "true" R.GPS.ID = gpsfields[6][1:] Uncomment to see decoded packets if string(incomingpacket["sentence"][0:1]) != "T" { go func() { dao.SavePacket(R.GPS, R.Diagnostic) }() } WSDataChannel <- R conn.Write([]byte("OK\n")) } return }
// +groupName=vacuum.swine.de package vacuum const GroupName = "vacuum.swine.de"
package main import ( "fmt" ) type embedded struct { i int } func (x embedded) do() { fmt.Println("do()") } type test struct { embedded } func main() { var x test x.do() fmt.Println(x.i) }
package main import ( "net/http" "github.com/a-h/gosign" "github.com/gorilla/mux" ) func main() { // Initialise the Gorilla Router. r := mux.NewRouter() // Create a test Hello World handler. helloHandler := &helloHandler{} // Load the private key, and create an instance of the signing // middleware which wraps the helloHandler. priv, _ := gosign.LoadPrivateKeyFromFile("private.pem") helloSigner := gosign.NewHandler(priv, helloHandler) // Handle incoming HTTP requests. r.Handle("/", helloSigner) // Start the server with the routes. http.ListenAndServe(":8080", r) } type helloHandler struct { } func (th *helloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write([]byte("<h1>Hello!</h1>")) w.Write([]byte("<p>Check the HTTP headers to see the base64 encoded hash and signature.</p>")) w.Write([]byte("<p>Validate the signature with the public.pem key.</p>")) }
package auth import ( "net/http" // "fmt" // "log" "html/template" // "database/sql" "github.com/kataras/go-sessions" // "github.com/kataras/go-sessions" "golang.org/x/crypto/bcrypt" // q "project_reservasi/src/controller/query" conn "project_reservasi/src/config" mo "project_reservasi/src/model" ) func LoginHandler(w http.ResponseWriter,r *http.Request){ http.FileServer(http.Dir("assets/login")) var data = map[string]interface{}{ "title": "Learning Golang Web", "name": "Kelompok 2", } var tmpl = template.Must(template.ParseFiles( "views/auth/login.html", )) var err = tmpl.ExecuteTemplate(w, "login", data) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func Login(w http.ResponseWriter,r *http.Request){ db := conn.Connect() session := sessions.Start(w, r) if len(session.GetString("username")) != 0 { http.Redirect(w, r, "/", 302) } defer db.Close() username := r.FormValue("username") password := r.FormValue("password") // fmt.Println(username) // fmt.Println(password) var users = mo.User{} err = db.QueryRow(` SELECT id, username, password FROM user WHERE username=? `, username). Scan( &users.Id, &users.Username, &users.Password, ) var password_tes = bcrypt.CompareHashAndPassword([]byte(users.Password), []byte(password)) if password_tes == nil { //login success session := sessions.Start(w, r) session.Set("username", users.Username) http.Redirect(w, r, "/loginadmin", 302) } else { //login failed http.Redirect(w, r, "/admin", 302) } }
package catalog import ( "k8s.io/client-go/dynamic" "github.com/operator-framework/operator-lifecycle-manager/pkg/api/client/clientset/versioned" "github.com/operator-framework/operator-lifecycle-manager/pkg/lib/clients" "github.com/operator-framework/operator-lifecycle-manager/pkg/lib/operatorclient" ) type stubClientFactory struct { operatorClient operatorclient.ClientInterface kubernetesClient versioned.Interface dynamicClient dynamic.Interface } var _ clients.Factory = &stubClientFactory{} func (f *stubClientFactory) WithConfigTransformer(clients.ConfigTransformer) clients.Factory { return f } func (f *stubClientFactory) NewOperatorClient() (operatorclient.ClientInterface, error) { return f.operatorClient, nil } func (f *stubClientFactory) NewKubernetesClient() (versioned.Interface, error) { return f.kubernetesClient, nil } func (f *stubClientFactory) NewDynamicClient() (dynamic.Interface, error) { return f.dynamicClient, nil }
// Copyright 2018 the Service Broker Project Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package models import ( "encoding/json" ) const ( // The following operation types are used as part of the OSB process. // The types correspond to asynchronous provision/deprovision/update calls // and will exist on a ServiceInstanceDetails with an operation ID that can be // used to look up the state of an operation. ProvisionOperationType = "provision" DeprovisionOperationType = "deprovision" UpdateOperationType = "update" ClearOperationType = "" ) var encryptorInstance Encryptor = nil func SetEncryptor(encryptor Encryptor) { encryptorInstance = encryptor } //go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -o fakes/fake_encryption.go . Encryptor type Encryptor interface { Encrypt(plaintext []byte) (string, error) Decrypt(ciphertext string) ([]byte, error) } // ServiceBindingCredentials holds credentials returned to the users after // binding to a service. type ServiceBindingCredentials ServiceBindingCredentialsV1 // SetOtherDetails marshals the value passed in into a JSON string and sets // OtherDetails to it if marshalling was successful. func (sbc *ServiceBindingCredentials) SetOtherDetails(toSet interface{}) error { out, err := json.Marshal(toSet) if err != nil { return err } encryptedDetails, err := encryptorInstance.Encrypt(out) if err != nil { return err } sbc.OtherDetails = string(encryptedDetails) return nil } // GetOtherDetails returns and unmarshalls the OtherDetails field into the given // struct. An empty OtherDetails field does not get unmarshalled and does not error. func (sbc ServiceBindingCredentials) GetOtherDetails(v interface{}) error { if sbc.OtherDetails == "" { return nil } decryptedDetails, err := encryptorInstance.Decrypt(sbc.OtherDetails) if err != nil { return err } return json.Unmarshal(decryptedDetails, v) } // ServiceInstanceDetails holds information about provisioned services. type ServiceInstanceDetails ServiceInstanceDetailsV2 // SetOtherDetails marshals the value passed in into a JSON string and sets // OtherDetails to it if marshalling was successful. func (si *ServiceInstanceDetails) SetOtherDetails(toSet interface{}) error { out, err := json.Marshal(toSet) if err != nil { return err } encryptedDetails, err := encryptorInstance.Encrypt(out) if err != nil { return err } si.OtherDetails = string(encryptedDetails) return nil } // GetOtherDetails returns and unmarshalls the OtherDetails field into the given // struct. An empty OtherDetails field does not get unmarshalled and does not error. func (si ServiceInstanceDetails) GetOtherDetails(v interface{}) error { if si.OtherDetails == "" { return nil } decryptedDetails, err := encryptorInstance.Decrypt(si.OtherDetails) if err != nil { return err } return json.Unmarshal(decryptedDetails, v) } // ProvisionRequestDetails holds user-defined properties passed to a call // to provision a service. type ProvisionRequestDetails ProvisionRequestDetailsV1 func (pr *ProvisionRequestDetails) SetRequestDetails(rawMessage json.RawMessage) error { encryptedDetails, err := encryptorInstance.Encrypt(rawMessage) if err != nil { return err } pr.RequestDetails = string(encryptedDetails) return nil } func (pr ProvisionRequestDetails) GetRequestDetails() (json.RawMessage, error) { decryptedDetails, err := encryptorInstance.Decrypt(pr.RequestDetails) if err != nil { return nil, err } return decryptedDetails, nil } // Migration represents the mgirations table. It holds a monotonically // increasing number that gets incremented with every database schema revision. type Migration MigrationV1 // CloudOperation holds information about the status of Google Cloud // long-running operations. type CloudOperation CloudOperationV1 // TerraformDeployment holds Terraform state and plan information for resources // that use that execution system. type TerraformDeployment TerraformDeploymentV2 func (t *TerraformDeployment) SetWorkspace(value string) error { encrypted, err := encryptorInstance.Encrypt([]byte(value)) if err != nil { return err } t.Workspace = encrypted return nil } func (t *TerraformDeployment) GetWorkspace() (string, error) { decrypted, err := encryptorInstance.Decrypt(t.Workspace) if err != nil { return "", err } return string(decrypted), nil } // PasswordMetadata contains information about the passwords, but never the // passwords themselves type PasswordMetadata PasswordMetadataV1
package pokemon import ( "encoding/json" "github.com/pkg/errors" "io/ioutil" "net/http" ) const pokemonAPI = "https://pokeapi.co/api/v2/pokemon/" type Location struct { Name string } type Encounter struct { Location Location `json:"location_area"` } type Pokemon struct { Name string `json:"name"` } type Output struct { Name string Locations []string } func GetData(url string) ([]byte, error) { httpResponse, err := http.Get(url) if err != nil { return nil, errors.New("HTTP get towards pokeapi") } bodyContent, err := ioutil.ReadAll(httpResponse.Body) if err != nil { return nil, errors.New("error while reading pokeapi") } return bodyContent, nil } func FindLocations(nameOrNumber string) ([]byte, error) { data, err := GetData(pokemonAPI + nameOrNumber) if err != nil { return nil, err } var decoded Pokemon err = json.Unmarshal(data, &decoded) if err != nil { return nil, errors.New("unmarshalling the JSON body content") } data, err = GetData(pokemonAPI + nameOrNumber + "/encounters") if err != nil { return nil, err } var areas []Encounter err = json.Unmarshal(data, &areas) if err != nil { return nil, errors.New("unmarshalling the JSON body content") } var output Output output.Name = decoded.Name for _, value := range areas { output.Locations = append(output.Locations, value.Location.Name) } result, err := json.MarshalIndent(output, "", "\t") return result, err }
package main import ( "bytes" "encoding/json" "fmt" "io" "my9awsgo/my9client" "my9awsgo/my9ec2" "my9awsgo/my9ecs" "my9awsgo/my9s3" "my9awsgo/my9sfn" "my9awsgo/my9sns" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" ) type StepWorkerCleanupConfig struct { Project string `json:"project"` Env string `json:"env"` Region string `json:"region"` ConfigPrefix string `json:"configprefix"` Ec2InstConfig string `json:"ec2instanceconfig"` EcsContConfig string `json:"containerconfig"` WorkerConfig string `json:"workerconfig"` AwsAccountId string `json:"accountid"` StateMachineArn string `json:"stateMachineArn"` StateMachineName string `json:"stateMachineName"` ExecutionArn string `json:"executionarn"` EcsTaskConfig string `json:"ecstaskconfig"` EcsTaskCluster string `json:"ecstaskcluster"` EcsSfnClusterList []string `json:"ecssfnclusterlist"` SnsTopicArn string `json:"snstopicarn"` } type StateMachineInput struct { Project string `json:"project"` Env string `json:"env"` Region string `json:"region"` Mode string `json:"mode"` ExecutionArn string `json:"executionarn"` ConfigBucket string `json:"configbucket"` ConfigBucketKey string `json:"configbucketkey"` } type SwlRun struct { S3Session my9s3.S3Session EC2Session my9ec2.EC2Session SFNSession my9sfn.SFNSession EcsSession my9ecs.ECSSession SnsSession my9sns.SNSSession Mode string ConfigBucket string ConfigBucketKey string SwlConf StepWorkerCleanupConfig SmInput StateMachineInput Ec2InstanceConfigFilePath string EcsTaskConfigFilePath string Result string //SwlDateTime SwlRunDateTime } const CONF_PREFIX = "projects" func (swlRun *SwlRun) StepWorkerCleanupRun() (err error) { switch swlRun.Mode { case "cleanup_state_machine": swlRun.CleanupStateMachine() case "periodic_cleanup": // periodic cleanup every hour for _, cluster := range swlRun.SwlConf.EcsSfnClusterList { fmt.Println("StepWorkerCleanupRun: Cleaning up cluster :", cluster) swlRun.SwlConf.EcsTaskCluster = cluster swlRun.CleanupStateMachine() } case "cleanup_used_and_new": // once every 6 hours cleanup both used and new for _, cluster := range swlRun.SwlConf.EcsSfnClusterList { fmt.Println("StepWorkerCleanupRun: Cleaning up cluster :", cluster) swlRun.SwlConf.EcsTaskCluster = cluster swlRun.CleanupStateMachine() } default: fmt.Println("No mode supplied for Step Worker Cleanup run ... Will still run cleanup ... ") swlRun.CleanupStateMachine() } return err } var def_project, def_env, def_region, def_mode, def_confbucket, def_confbucketkey, def_result string func main() { var project, env, region, mode, configbucket, configbucketkey, executionarn, result string region = os.Args[3] fmt.Println("Main : Len OS args => ", len(os.Args)) fmt.Println("Main : region => ", region) if (len(os.Args) == 9) && (region != "undefined") { project = os.Args[1] env = os.Args[2] region = os.Args[3] mode = os.Args[4] configbucket = os.Args[5] configbucketkey = os.Args[6] executionarn = os.Args[7] result = os.Args[8] fmt.Println("Main : Obtained normal params ... ") } else { project = def_project env = def_env region = def_region mode = def_mode configbucket = def_confbucket configbucketkey = def_confbucketkey executionarn = "UNKNOWN" result = def_result fmt.Println("Main : Using default params ... ") } var swlRun SwlRun swlRun.Mode = mode swlRun.Result = result swlRun.SwlConf.ConfigPrefix = configbucketkey swlRun.ConfigBucket = configbucket swlRun.ConfigBucketKey = CONF_PREFIX + "/" + project + "/" + env + "/master.json" /*keyname Create AWS Service Sessions */ sess, err := my9client.My9AWSNewClient() if err != nil { fmt.Println("Error creating AWS Session") } ecs_session, err := my9ecs.NewEcsSession(sess, region) if err != nil { fmt.Println("Error creating ECS Session") } s3_session, err := my9s3.NewS3Session(sess, region) if err != nil { fmt.Println("Error creating S3 Session") } ec2_session, err := my9ec2.NewEc2Session(sess, region) if err != nil { fmt.Println("Error creating EC2 Session") } sfn_session, err := my9sfn.NewSfnSession(sess, region) if err != nil { fmt.Println("Error creating SFN Session") } sns_session, err := my9sns.NewSnsSession(sess, region) if err != nil { fmt.Println("Error creating SNS Session") } swlRun.S3Session = s3_session swlRun.EC2Session = ec2_session swlRun.SFNSession = sfn_session swlRun.EcsSession = ecs_session swlRun.SnsSession = sns_session err = readConfig(&swlRun) fmt.Println("Reading SWL config from S3 ") //ecsTaskConfigFile := swlRun.SwlConf.EcsTaskConfig + "/" + project + "/" + env + ".json" fmt.Println("Main: Ecs cluster :", swlRun.SwlConf.EcsTaskCluster) swlRun.SwlConf.Project = project swlRun.SwlConf.Env = env swlRun.SwlConf.Region = region swlRun.SwlConf.ExecutionArn = executionarn err = swlRun.StepWorkerCleanupRun() if err != nil { fmt.Println("Error during StepWorkerCleanupRun") } fmt.Println("End of StepWorkerCleanupRun ... ! ") } func readConfig(swlRun *SwlRun) (err error) { confData, err := readConfFile(swlRun.S3Session, swlRun.ConfigBucket, swlRun.ConfigBucketKey) err = json.Unmarshal(confData, &swlRun.SwlConf) if err != nil { fmt.Println("Error in reading APN conf file :: Error=%s", err) return err } return err } func readConfFile(s3_session my9s3.S3Session, bucketname string, bucketkey string) (content []byte, err error) { confFile, err := s3_session.Svc.GetObject(&s3.GetObjectInput{ Bucket: aws.String(bucketname), Key: aws.String(bucketkey), }) if err != nil { fmt.Println("Error in obtaining S3 config file object :: Error=%s", err) return content, err } defer confFile.Body.Close() buf := bytes.NewBuffer(nil) _, err = io.Copy(buf, confFile.Body) if err != nil { fmt.Println("Error in reading S3 config file :: Error=%s", err) return content, err } content = buf.Bytes() return content, err }
package resources import ( "github.com/anshap1719/authentication/design/types" . "goa.design/goa/v3/dsl" ) var _ = Service("password-auth", func() { HTTP(func() { Path("/") }) Method("register", func() { Security(APIKeyAuth) Description("Register a new user with an email and password") HTTP(func() { POST("/register") Response(StatusOK, func() { Headers(func() { Header("Authorization") Header("X-Session") Required("Authorization", "X-Session") }) }) Headers(func() { Header("Authorization") Header("X-Session") Header("API-Key") }) }) Payload(types.RegisterParams) Result(types.UserMedia) Error("BadRequest") Error("Forbidden") Error("InternalServerError") }) Method("login", func() { Security(APIKeyAuth) Description("Login a user using an email and password") HTTP(func() { POST("/login") Params(func() { Param("token", String, "A merge token for merging into an account", func() { Format(FormatUUID) }) }) Response(StatusOK, func() { Headers(func() { Header("Authorization") Header("X-Session") Required("Authorization", "X-Session") }) }) Headers(func() { Header("API-Key") }) }) Payload(types.LoginParams) Result(types.UserMedia) Error("Unauthorized") Error("BadRequest") Error("InternalServerError") }) Method("remove", func() { Description("Removes using a password as a login method") HTTP(func() { POST("/remove-password") Headers(func() { Header("Authorization") Header("X-Session") Header("API-Key") }) }) Security(JWTSec, APIKeyAuth) Payload(func() { Token("Authorization") Token("X-Session") APIKey("api_key", "API-Key", String) }) Result(Empty) Error("NotFound") Error("Forbidden") Error("InternalServerError") }) Method("change-password", func() { Description("Changes the user's current password to a new one, also adds a password to the account if there is none") HTTP(func() { POST("/change-password") Headers(func() { Header("Authorization") Header("X-Session") Header("API-Key") }) }) Security(JWTSec, APIKeyAuth) Payload(types.ChangePasswordParams) Result(Empty) Error("BadRequest") Error("InternalServerError") }) Method("reset", func() { Security(APIKeyAuth) Description("Send an email to user to get a password reset, responds with no content even if the email is not on any user account") HTTP(func() { POST("/reset-password") Params(func() { Param("email", String, "Email of the account to send a password reset", func() { Format("email") }) Required("email", "redirect-url") }) Headers(func() { Header("API-Key") }) }) Payload(func() { Attribute("email") APIKey("api_key", "API-Key", String) }) Result(Empty) Error("InternalServerError") }) Method("confirm-reset", func() { Security(APIKeyAuth) Description("Confirms that a reset has been completed and changes the password to the new one passed in") HTTP(func() { POST("/finalize-reset") Headers(func() { Header("API-Key") }) }) Payload(types.ResetPasswordParams) Result(Empty) Error("Forbidden") Error("InternalServerError") }) Method("check-email-available", func() { Security(APIKeyAuth) Description("Checks if an email is available for signup") HTTP(func() { POST("/check-email-available") Params(func() { Param("email", String) }) Headers(func() { Header("API-Key") }) }) Payload(func() { Attribute("email", String) APIKey("api_key", "API-Key", String) }) Result(Boolean) Error("InternalServerError") }) Method("check-phone-available", func() { Security(APIKeyAuth) Description("Checks if an phone is available for signup") HTTP(func() { POST("/check-phone-available") Params(func() { Param("phone", String) }) Headers(func() { Header("API-Key") }) }) Payload(func() { Attribute("phone", String) APIKey("api_key", "API-Key", String) }) Result(Boolean) Error("InternalServerError") }) })
package main import ( "fmt" "math" ) func main() { n := 361 for i := 1; i <= 100; i++ { for j := 2; j <= 100; j++ { temp := math.Pow(float64(i), float64(j)) if n == int(temp) { fmt.Println("true") return } } } fmt.Println("false") }
/* * KSQL * * This is a swagger spec for ksqldb * * API version: 1.0.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package swagger type DescribeResultItemSourceDescriptionSchema struct { Type_ string `json:"type,omitempty"` MemberSchema *interface{} `json:"memberSchema,omitempty"` Fields []interface{} `json:"fields,omitempty"` }
package concurrency import ( "runtime" "testing" ) func TestNoSched(t *testing.T) { NoSched() // only prints "Bye" } func TestSched(t *testing.T) { Sched() //show some, since according documentation //runtime.Gosched allows other goroutines to run //which mean that maybe not all are allowed } func TestSchedNoParallel(t *testing.T) { runtime.GOMAXPROCS(1) Sched() }
// Copyright 2018 Andrew Bates // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "fmt" "sort" "strings" "github.com/abates/insteon" ) func printLinkDatabase(linkable insteon.LinkableDevice) error { dbLinks, err := linkable.Links() fmt.Printf("Link Database:\n") if len(dbLinks) > 0 { fmt.Printf(" Flags Group Address Data\n") links := make(map[string][]*insteon.LinkRecord) for _, link := range dbLinks { links[link.Address.String()] = append(links[link.Address.String()], link) } linkAddresses := []string{} for linkAddress := range links { linkAddresses = append(linkAddresses, linkAddress) } sort.Strings(linkAddresses) for _, linkAddress := range linkAddresses { for _, link := range links[linkAddress] { fmt.Printf(" %-5s %5s %8s %02x %02x %02x\n", link.Flags, link.Group, link.Address, link.Data[0], link.Data[1], link.Data[2]) } } } else { fmt.Printf(" No links defined\n") } return err } func dumpLinkDatabase(linkable insteon.LinkableDevice) error { links, err := linkable.Links() if err == nil { fmt.Printf("links:\n") for _, link := range links { buf, _ := link.MarshalBinary() s := make([]string, len(buf)) for i, b := range buf { s[i] = fmt.Sprintf("0x%02x", b) } fmt.Printf("- [ %s ]\n", strings.Join(s, ", ")) } } return err }
package backends import ( "context" "github.com/pkg/errors" "github.com/batchcorp/plumber/backends/activemq" "github.com/batchcorp/plumber/backends/awskinesis" "github.com/batchcorp/plumber/backends/awssns" "github.com/batchcorp/plumber/backends/awssqs" azureEventhub "github.com/batchcorp/plumber/backends/azure-eventhub" azureServicebus "github.com/batchcorp/plumber/backends/azure-servicebus" "github.com/batchcorp/plumber/backends/cdcmongo" "github.com/batchcorp/plumber/backends/cdcpostgres" "github.com/batchcorp/plumber/backends/gcppubsub" "github.com/batchcorp/plumber/backends/kafka" kubemqQueue "github.com/batchcorp/plumber/backends/kubemq-queue" "github.com/batchcorp/plumber/backends/memphis" "github.com/batchcorp/plumber/backends/mqtt" "github.com/batchcorp/plumber/backends/nats" natsJetstream "github.com/batchcorp/plumber/backends/nats-jetstream" natsStreaming "github.com/batchcorp/plumber/backends/nats-streaming" "github.com/batchcorp/plumber/backends/nsq" "github.com/batchcorp/plumber/backends/pulsar" rabbitStreams "github.com/batchcorp/plumber/backends/rabbit-streams" "github.com/batchcorp/plumber/backends/rabbitmq" "github.com/batchcorp/plumber/backends/rpubsub" "github.com/batchcorp/plumber/backends/rstreams" "github.com/batchcorp/plumber/tunnel" "github.com/batchcorp/plumber-schemas/build/go/protos/opts" "github.com/batchcorp/plumber-schemas/build/go/protos/records" ) // Backend is the interface that all backends implement; the interface is used // for facilitating all CLI and server functionality in plumber. // NOTE: Most backends do not support _some_ part of the interface - in those // cases the methods will either return types.NotImplementedErr or // types.UnsupportedFeatureErr. type Backend interface { // Read will read data from the bus and dump each message to the results // channel. This method should _not_ decode the message - that is left up // to the upstream user. The error channel _should_ be optional. // // Decoding should happen _outside_ the backend. Read(ctx context.Context, readOpts *opts.ReadOptions, resultsChan chan *records.ReadRecord, errorChan chan *records.ErrorRecord) error // Write will attempt to write the input messages as a batch (if the backend // supports batch writing). This call will block until success/error. // // Encoding should happen _outside_ the backend. // // NOTE: Key, headers and any other metadata is fetched from CLIOptions // (that are passed when instantiating the backend). Write(ctx context.Context, writeOpts *opts.WriteOptions, errorCh chan<- *records.ErrorRecord, messages ...*records.WriteRecord) error // Test performs a "test" to see if the connection to the backend is alive. // The test varies between backends (ie. in kafka, it might be just attempting // to connect to a broker, while with another backend, plumber might try to // put/get sample data). Test(ctx context.Context) error // Tunnel creates a tunnel to Batch and exposes the connected backend as a // destination. This is a blocking call. Tunnel(ctx context.Context, tunnelOpts *opts.TunnelOptions, tunnelSvc tunnel.ITunnel, errorCh chan<- *records.ErrorRecord) error // Relay will hook into a message bus as a consumer and relay all messages // to the relayCh; if an error channel is provided, any errors will be piped // to the channel as well. This method _usually_ blocks. Relay(ctx context.Context, relayOpts *opts.RelayOptions, relayCh chan interface{}, errorCh chan<- *records.ErrorRecord) error // DisplayMessage will parse a Read record and print (pretty) output to STDOUT DisplayMessage(cliOpts *opts.CLIOptions, msg *records.ReadRecord) error // DisplayError will parse an Error record and print (pretty) output to STDOUT DisplayError(msg *records.ErrorRecord) error // Close closes any connections the backend has open. Once this is ran, you // should create a new backend instance. Close(ctx context.Context) error // Name returns the name of the backend Name() string } // New is a convenience function to instantiate the appropriate backend based on // package name of the backend. func New(connOpts *opts.ConnectionOptions) (Backend, error) { var be Backend var err error switch connOpts.Conn.(type) { case *opts.ConnectionOptions_Kafka: be, err = kafka.New(connOpts) case *opts.ConnectionOptions_ActiveMq: be, err = activemq.New(connOpts) case *opts.ConnectionOptions_AwsSqs: be, err = awssqs.New(connOpts) case *opts.ConnectionOptions_AwsSns: be, err = awssns.New(connOpts) case *opts.ConnectionOptions_AzureServiceBus: be, err = azureServicebus.New(connOpts) case *opts.ConnectionOptions_AzureEventHub: be, err = azureEventhub.New(connOpts) case *opts.ConnectionOptions_Mqtt: be, err = mqtt.New(connOpts) case *opts.ConnectionOptions_GcpPubsub: be, err = gcppubsub.New(connOpts) case *opts.ConnectionOptions_Nats: be, err = nats.New(connOpts) case *opts.ConnectionOptions_NatsStreaming: be, err = natsStreaming.New(connOpts) case *opts.ConnectionOptions_Nsq: be, err = nsq.New(connOpts) case *opts.ConnectionOptions_Pulsar: be, err = pulsar.New(connOpts) case *opts.ConnectionOptions_Rabbit: be, err = rabbitmq.New(connOpts) case *opts.ConnectionOptions_RabbitStreams: be, err = rabbitStreams.New(connOpts) case *opts.ConnectionOptions_RedisPubsub: be, err = rpubsub.New(connOpts) case *opts.ConnectionOptions_RedisStreams: be, err = rstreams.New(connOpts) case *opts.ConnectionOptions_Mongo: be, err = cdcmongo.New(connOpts) case *opts.ConnectionOptions_KubemqQueue: be, err = kubemqQueue.New(connOpts) case *opts.ConnectionOptions_Postgres: be, err = cdcpostgres.New(connOpts) case *opts.ConnectionOptions_NatsJetstream: be, err = natsJetstream.New(connOpts) case *opts.ConnectionOptions_AwsKinesis: be, err = awskinesis.New(connOpts) case *opts.ConnectionOptions_Memphis: be, err = memphis.New(connOpts) default: return nil, errors.New("unknown backend") } if err != nil { return nil, errors.Wrap(err, "unable to instantiate backend") } return be, nil }
package cmd import ( "net/http" "strconv" ) func Logs(subsystem string, level string, texOnly bool) error { if subsystem != "" { subsystem = "/" + subsystem } var method method method = http.MethodGet if level != "" { method = http.MethodPost } opts := map[string]string{ "subsystem": subsystem, "level": level, "tex-only": strconv.FormatBool(texOnly), } res, err := executeJsonCmd(method, "logs"+subsystem, params{opts: opts}, nil) if err != nil { return err } output(res) return nil }
/** * Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. * If the last word does not exist, return 0. * Note: A word is defined as a character sequence consists of non-space characters only. * For example, Given s = "Hello World", return 5. */ func lengthOfLastWord(s string) int { n := len(s) - 1; if n == -1 { return 0; } c_space := " "[0] for n >= 0 && s[n] == c_space { n -= 1 } size := n + 1 for ; n >= 0; n-- { if s[n] == c_space { return size - n - 1 } } return size }
package main import ( "context" "errors" "net" "strings" "sync" "sync/atomic" "time" "github.com/Sirupsen/logrus" "github.com/miekg/dns" ) const ( dnsDefaultPort = ":53" ) var ( allowedDomainChars [255]bool dnsServers []string ) func init() { for _, b := range []byte("1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM.-") { allowedDomainChars[b] = true } } func domainValidName(domain string) error { if len(domain) == 0 { return errors.New("Zero length domain name") } if domain[0] == '.' || domain[0] == '-' { return errors.New("Bad start symbol") } if domain[len(domain)-1] == '-' { return errors.New("Bad end symbol") } for _, latinChar := range []byte(domain) { if !allowedDomainChars[latinChar] { return errors.New("Bad symbol") } } return nil } func domainHasLocalIP(ctx context.Context, domain string) (res bool) { defer func() { logrus.Debugf("domainHasLocalIP for '%v': %v", domain, res) }() var ipsChan = make(chan []net.IP, 1) defer func() { // clean channel for no leak blocked goroutines for range ipsChan { // pass } }() var dnsRequests = &sync.WaitGroup{} dnsRequests.Add(1) go func() { ips, err := net.LookupIP(domain) if err == nil { ipsChan <- ips } else { logrus.Infof("Can't local lookup ip for domain %v: %v", DomainPresent(domain), err) } logrus.Debugf("Receive answer from local lookup for domain %v ips: '%v'", DomainPresent(domain), ips) dnsRequests.Done() }() domainForRequest := domain if !strings.HasSuffix(domainForRequest, ".") { domainForRequest += "." } dnsq := func(server string) { const recordTypeForRequest = 2 // two request for every server: for A and AAAA record var serverWg sync.WaitGroup serverWg.Add(recordTypeForRequest) var dnsServerIpsChan = make(chan []net.IP, recordTypeForRequest) var dnsRequestErrorCount int32 go func() { defer serverWg.Done() ips, err := getIPsFromDNS(ctx, domainForRequest, server, dns.TypeA) if err == nil { dnsServerIpsChan <- ips } else { logrus.Debugf("Error with request to dns server '%v' (type A) for domain '%v': %v", server, domain, err) atomic.AddInt32(&dnsRequestErrorCount, 1) } }() go func() { defer serverWg.Done() ips, err := getIPsFromDNS(ctx, domainForRequest, server, dns.TypeAAAA) if err == nil { dnsServerIpsChan <- ips } else { logrus.Debugf("Error with request to dns server '%v' (type AAAA) for domain '%v': %v", server, domain, err) atomic.AddInt32(&dnsRequestErrorCount, 1) } }() go func() { serverWg.Wait() close(dnsServerIpsChan) }() var serverResult []net.IP for serverIps := range dnsServerIpsChan { serverResult = append(serverResult, serverIps...) } if dnsRequestErrorCount > 0 { logrus.Infof("Dns server '%v' has errors while request process for domain '%v'. It is not send IP result for main IP comparer.", server, domain) return } ipsChan <- serverResult } dnsRequests.Add(len(dnsServers)) for _, dnsServer := range dnsServers { go func(server string) { dnsq(server) dnsRequests.Done() }(dnsServer) } go func() { // close channel after all requests complete dnsRequests.Wait() close(ipsChan) }() hasIP := false allowIPs := getAllowIPs() for ips := range ipsChan { if len(ips) > 0 { hasIP = true logrus.Debugf("Has IP for domain '%v' set: %v", domain, hasIP) } else { logrus.Infof("Some dns server doesn't know domain and no return IP addresses (see debug log for details) for domain: %v", domain) return false } for _, ip := range ips { // If domain has ip doesn't that doesn't bind to the server if !ipContains(allowIPs, ip) { logrus.Debugf("Domain have ip of other server. domain %v, Domain ips: '%v', Server ips: '%v'", DomainPresent(domain), ips, allowIPs) return false } } } logrus.Debugf("HasIP after receive all dns answer for domain '%v': %v", domain, hasIP) if !hasIP { logrus.Infof("Doesn't found ip addresses for domain %v", DomainPresent(domain)) return false } return true } func getIPsFromDNS(ctx context.Context, domain, dnsServer string, recordType uint16) (ips []net.IP, err error) { dnsClient := dns.Client{} if deadline, hasDeadline := ctx.Deadline(); hasDeadline { ctxTimeout := time.Until(deadline) if *dnsTimeout < ctxTimeout { ctxTimeout = *dnsTimeout } dnsClient.DialTimeout = ctxTimeout dnsClient.ReadTimeout = ctxTimeout dnsClient.WriteTimeout = ctxTimeout } msg := dns.Msg{} msg.Id = dns.Id() msg.SetQuestion(domain, recordType) answer, _, err := dnsClient.Exchange(&msg, dnsServer) if err != nil { logrus.Infof("Error from dns server '%v' for domain %v, record type '%v': %v", dnsServer, DomainPresent(domain), dns.TypeToString[recordType], err) return nil, err } if answer.Id != msg.Id { logrus.Infof("Error answer ID from dns server '%v' for domain %v, record type '%v', %v != %v", dnsServer, DomainPresent(domain), dns.TypeToString[recordType], msg.Id, answer.Id) return nil, errors.New("error answer ID from dns server") } var res []net.IP for _, r := range answer.Answer { if r.Header().Rrtype != recordType { continue } switch r.Header().Rrtype { case dns.TypeA: res = append(res, r.(*dns.A).A) case dns.TypeAAAA: res = append(res, r.(*dns.AAAA).AAAA) default: continue } } logrus.Debugf("Receive answer from dns server '%v' for domain %v record type '%v' ips: '%v'", dnsServer, DomainPresent(domain), dns.TypeToString[recordType], res) return res, nil } func parseDnsServers(arg string) (res []string) { parts := strings.Split(arg, ",") for _, part := range parts { part := strings.TrimSpace(part) if part == "" { continue } ip := net.ParseIP(part) tcpAddr, _ := net.ResolveTCPAddr("tcp", part) var ipPort string switch { case ip.To4() != nil: ipPort = ip.To4().String() + dnsDefaultPort case ip.To16() != nil: ipPort = "[" + ip.String() + "]" + dnsDefaultPort case tcpAddr != nil: ipPort = tcpAddr.String() default: logrus.Errorf("Error parse dns address '%v'", part) continue } logrus.Debugf("Parse dns '%v' to '%v'", part, ipPort) res = append(res, ipPort) } logrus.Infof("Parse dns servers: %v", res) return res }
package categories import ( "sync" "github.com/Nv7-Github/Nv7Haven/eod/base" "github.com/Nv7-Github/Nv7Haven/eod/polls" "github.com/Nv7-Github/Nv7Haven/eod/types" "github.com/bwmarrin/discordgo" ) type Categories struct { dat map[string]types.ServerData lock *sync.RWMutex base *base.Base dg *discordgo.Session polls *polls.Polls } func NewCategories(dat map[string]types.ServerData, base *base.Base, dg *discordgo.Session, polls *polls.Polls, lock *sync.RWMutex) *Categories { return &Categories{ dat: dat, lock: lock, base: base, dg: dg, polls: polls, } }
package messages import "fmt" type SimpleMessage struct { OriginalName string RelayPeerAddr string Contents string } type GossipPacket struct { Simple *SimpleMessage Rumor *RumorMessage Status *StatusPacket Private *PrivateMessage DataRequest *DataRequest DataReply *DataReply ShareFile *ShareFile } type RumorMessage struct { Origin string ID uint32 Text string } type PrivateMessage struct { Origin string ID uint32 Text string Destination string HopLimit uint32 } type DataRequest struct { Origin string Destination string HopLimit uint32 HashValue []byte // hash of the requested chunk or the MetaHash (if the metafile is requested) } type DataReply struct { Origin string Destination string HopLimit uint32 HashValue []byte // hash of the data that is sent with this message Data []byte // the actual data that is sent (chunk or the metafile) } type ShareFile struct { Filename string } type PeerStatus struct { Identifier string NextID uint32 } type StatusPacket struct { Want []PeerStatus } func (packet *GossipPacket) String() string { return packet.Simple.String() } func (message *SimpleMessage) String() string { return fmt.Sprintf("OriginalName: %s\nRelayPeerAddr: %s\nContents: %s", message.OriginalName, message.RelayPeerAddr, message.Contents) }
// +build unit package coreapi import ( "testing" "github.com/go-chi/chi" "github.com/stretchr/testify/assert" ) func TestRegister(t *testing.T) { r := chi.NewRouter() Register(r, nil, nil, nil) assert.Len(t, r.Routes(), 6) assert.Equal(t, r.Routes()[0].Pattern, "/documents") assert.Len(t, r.Routes()[0].Handlers, 2) assert.NotNil(t, r.Routes()[0].Handlers["POST"]) assert.NotNil(t, r.Routes()[0].Handlers["PUT"]) assert.Equal(t, r.Routes()[1].Pattern, "/documents/{document_id}") assert.NotNil(t, r.Routes()[1].Handlers["GET"]) assert.Equal(t, r.Routes()[2].Pattern, "/documents/{document_id}/proofs") assert.NotNil(t, r.Routes()[2].Handlers["POST"]) assert.Equal(t, r.Routes()[3].Pattern, "/documents/{document_id}/versions/{version_id}") assert.NotNil(t, r.Routes()[3].Handlers["GET"]) assert.Equal(t, r.Routes()[4].Pattern, "/documents/{document_id}/versions/{version_id}/proofs") assert.NotNil(t, r.Routes()[4].Handlers["POST"]) assert.Equal(t, r.Routes()[5].Pattern, "/jobs/{job_id}") assert.NotNil(t, r.Routes()[5].Handlers["GET"]) }
package codec import ( "github.com/iotaledger/wasp/packages/coretypes" ) func DecodeHname(b []byte) (coretypes.Hname, bool, error) { if b == nil { return 0, false, nil } r, err := coretypes.NewHnameFromBytes(b) return r, err == nil, err } func EncodeHname(value coretypes.Hname) []byte { return value.Bytes() }
package main import ( "crypto/md5" "fmt" "github.com/zenazn/goji" "html/template" "io/ioutil" "net/http" "path/filepath" "strings" ) const ( ASSET_ROOT = "./assets" ) type fileInfo struct { directory string name string extension string nameWithoutExtension string } func parse(path string) fileInfo { li := strings.LastIndex(path, "/") if li < 0 { nameWithoutExtension, extension := parseFileName(path) return fileInfo{directory: "", name: path, extension: extension, nameWithoutExtension: nameWithoutExtension, } } dir := path[:li] file := path[li+1:] nameWithoutExtension, extension := parseFileName(file) return fileInfo{directory: dir, name: file, extension: extension, nameWithoutExtension: nameWithoutExtension, } } func parseFileName(fileName string) (nameWithoutExtension, extension string) { li := strings.LastIndex(fileName, ".") if li < 0 { return fileName, "" } return fileName[:li], fileName[li+1:] } type tagOutput struct { root string } func checkDir(target string, root string) bool { rootAbs, err1 := filepath.Abs(root) if err1 != nil { panic(err1) } targetAbs, err2 := filepath.Abs(target) if err2 != nil { panic(err2) } return strings.Index(targetAbs, rootAbs) == 0 } func (t *tagOutput) getTag(path string, fn func(fileInfo, string) string) (template.HTML, error) { fileInfo := parse(path) dir := t.root + fileInfo.directory if !checkDir(dir, t.root) { panic("invalid path -> " + path) } data, readErr := ioutil.ReadFile(dir + "/" + fileInfo.name) if readErr != nil { return "", readErr } hash := md5.Sum(data) hashStr := fmt.Sprintf("%x", hash) tag := fn(fileInfo, hashStr) return template.HTML(tag), nil } func (t *tagOutput) getCssTag(path string) template.HTML { tag, err := t.getTag(path, func(fileInfo fileInfo, hash string) string { return fmt.Sprintf("<link href=\"%s/%s___%s\" type=\"text/css\" rel=\"stylesheet\"></link>", fileInfo.directory, fileInfo.name, hash) }) if err != nil { panic(err) } return tag } func (t *tagOutput) getJsTag(path string) template.HTML { tag, err := t.getTag(path, func(fileInfo fileInfo, hash string) string { return fmt.Sprintf("<script src=\"%s/%s___%s\" type=\"text/javascript\"></script>", fileInfo.directory, fileInfo.name, hash) }) if err != nil { panic(err) } return tag } func rootHandler(w http.ResponseWriter, r *http.Request) { to := tagOutput{"./assets"} funcMap := template.FuncMap{ "jsTag": to.getJsTag, "cssTag": to.getCssTag, } data, readErr := ioutil.ReadFile("./assets/index.html") if readErr != nil { panic(readErr) } tmpl := template.Must(template.New("base").Funcs(funcMap).Parse(string(data))) tmplErr := tmpl.ExecuteTemplate(w, "base", nil) if tmplErr != nil { panic(tmplErr) } } type contentHandler struct { contentType string } func (e *contentHandler) staticHandler(w http.ResponseWriter, r *http.Request) { w.Header().Add("content-type", e.contentType) fileInfo := parse(r.URL.Path) li := strings.LastIndex(fileInfo.name, "___") if li < 0 { writeFile(fileInfo.directory+"/"+fileInfo.name, w, r) return } plainFileName := fileInfo.name[:li] writeFile(fileInfo.directory+"/"+plainFileName, w, r) } func writeFile(file string, w http.ResponseWriter, r *http.Request) { data, err := ioutil.ReadFile(ASSET_ROOT + file) if err != nil { http.NotFound(w, r) return } w.Write(data) } func main() { goji.Get("/", rootHandler) cssHandler := contentHandler{"text/css"} goji.Get("/css/*", cssHandler.staticHandler) jsHandler := contentHandler{"text/javascript"} goji.Get("/js/*", jsHandler.staticHandler) goji.Get("/*", http.FileServer(http.Dir(ASSET_ROOT))) goji.Serve() }
// Copyright 2021 Akamai Technologies, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( log "github.com/apex/log" "github.com/akamai/edgedns-registrar-coordinator/registrar" "fmt" dns "github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v2" edgegrid "github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid" "gopkg.in/yaml.v2" "io/ioutil" "os" "strconv" "strings" ) const () var ( akamaiLibRegistrar AkamaiLibRegistrar LibPluginArgs registrar.PluginFuncArgs LibPluginResult registrar.PluginFuncResult libLog *log.Entry ) // edgeDNSClient is a proxy interface of the Akamai edgegrid configdns-v2 package that can be stubbed for testing. type AkamaiDNSService interface { GetDomains() GetDomain(domain string) GetTsigKey(domain string) GetServeAlgorithm(domain string) GetMasterIPs() } // AkamaiProvider implements the DNS provider for Akamai. type AkamaiLibRegistrar struct { //registrar.BaseRegistrarProvider akaConfig *AkamaiConfig config *edgegrid.Config // Defines client. Allows for mocking. client AkamaiDNSService } type AkamaiConfig struct { AkamaiContracts string `yaml:"akamai_contracts"` AkamaiNameFilter string `yaml:"akamai_name_filter"` AkamaiEdgercPath string `yaml:"akamai_edgerc_path"` AkamaiEdgercSection string `yaml:"akamai_edgerc_section"` AkamaiHost string `yaml:"akamai_host"` AkamaiAccessToken string `yaml:"akamai_access_token"` AkamaiClientToken string `yaml:"akamai_client_token"` AkamaiClientSecret string `yaml:"akamai_client_secret"` MaxBody int `yaml:"akamai_client_maxbody"` AccountKey string `yaml:"akamai_client_account_key"` } // NewAkamaiProvider initializes a new Akamai DNS based Provider. func NewPluginLibRegistrar() { var akaConfig *AkamaiConfig var err error pluginConfig := LibPluginArgs.PluginArg.(registrar.PluginConfig) libLog = pluginConfig.LogEntry // Get file config and parse if pluginConfig.PluginConfigPath == "" { LibPluginResult.PluginError = fmt.Errorf("Akamai Plugin Library requires a configurtion file") return } akaConfig, err = loadConfig(pluginConfig.PluginConfigPath) if err != nil { LibPluginResult.PluginError = fmt.Errorf("Akamai Plugin Library configuration file load failed. Error: %s", err.Error()) return } // validate config if len(akaConfig.AkamaiContracts) == 0 { LibPluginResult.PluginError = fmt.Errorf("Akamai Plugin Library configuration requires one or more contracts.") return } if akaConfig.AkamaiEdgercPath == "" && (akaConfig.AkamaiHost == "" || akaConfig.AkamaiAccessToken == "" || akaConfig.AkamaiClientToken == "" || akaConfig.AkamaiClientSecret == "") { LibPluginResult.PluginError = fmt.Errorf("Akamai Plugin Library configuration requires valid set of auth keys.") return } // Process creds. Could be on cmd line, config file var edgeGridConfig edgegrid.Config libLog.Debugf("Host: %s", akaConfig.AkamaiHost) libLog.Debugf("ClientToken: %s", akaConfig.AkamaiClientToken) libLog.Debugf("ClientSecret: %s", akaConfig.AkamaiClientSecret) libLog.Debugf("AccessToken: %s", akaConfig.AkamaiAccessToken) libLog.Debugf("EdgePath: %s", akaConfig.AkamaiEdgercPath) libLog.Debugf("EdgeSection: %s", akaConfig.AkamaiEdgercSection) libLog.Debugf("AkamaiContracts: %v", akaConfig.AkamaiContracts) // environment overrides edgerc file but config needs to be complete if akaConfig.AkamaiHost == "" || akaConfig.AkamaiClientToken == "" || akaConfig.AkamaiClientSecret == "" || akaConfig.AkamaiAccessToken == "" { // Look for Akamai environment or .edgerd creds var err error edgeGridConfig, err = edgegrid.Init(akaConfig.AkamaiEdgercPath, akaConfig.AkamaiEdgercSection) // use default .edgerc location and section if err != nil { libLog.Errorf("Edgegrid Init Failed") LibPluginResult.PluginError = err return // return empty provider for backward compatibility } } else { // Use external-dns config edgeGridConfig = edgegrid.Config{ Host: akaConfig.AkamaiHost, ClientToken: akaConfig.AkamaiClientToken, ClientSecret: akaConfig.AkamaiClientSecret, AccessToken: akaConfig.AkamaiAccessToken, MaxBody: 131072, // same default val as used by Edgegrid Debug: false, } // Check for edgegrid overrides if envval, ok := os.LookupEnv("AKAMAI_MAX_BODY"); ok { if i, err := strconv.Atoi(envval); err == nil { edgeGridConfig.MaxBody = i libLog.Debugf("Edgegrid maxbody set to %s", envval) } } if envval, ok := os.LookupEnv("AKAMAI_ACCOUNT_KEY"); ok { edgeGridConfig.AccountKey = envval libLog.Debugf("Edgegrid applying account key %s", envval) } if envval, ok := os.LookupEnv("AKAMAI_DEBUG"); ok { if dbgval, err := strconv.ParseBool(envval); err == nil { edgeGridConfig.Debug = dbgval libLog.Debugf("Edgegrid debug set to %s", envval) } } } akamaiLibRegistrar = AkamaiLibRegistrar{ config: &edgeGridConfig, akaConfig: akaConfig, } /* if akaService != nil { log.Debugf("Using STUB") provider.client = akaService } else { provider.client = provider } */ // Init library for direct endpoint calls dns.Init(edgeGridConfig) return } func resetDNSConfig(orig edgegrid.Config) { dns.Config = orig } func GetDomains() { libLog.Debug("Entering Plugin Lib Akamai registrar GetDomains") // both edgedns and this plugin using dns. need to temp swap config... existConfig := dns.Config defer resetDNSConfig(existConfig) dns.Config = *akamaiLibRegistrar.config LibPluginResult.PluginResult = []string{} queryArgs := dns.ZoneListQueryArgs{ Types: "PRIMARY", SortBy: "zone", ContractIds: akamaiLibRegistrar.akaConfig.AkamaiContracts, Search: akamaiLibRegistrar.akaConfig.AkamaiNameFilter, } libLog.Debugf("ListZones Query Args: %v", queryArgs) zlResp, err := dns.ListZones(queryArgs) if err != nil { libLog.Debugf("Plugin Lib Registrar GetDomains failed. Error: %s", err.Error()) LibPluginResult.PluginError = err return } filter := "LOCKED" domains := make([]string, 0, len(zlResp.Zones)) for _, zone := range zlResp.Zones { if strings.Contains(filter, zone.ActivationState) { continue } domains = append(domains, zone.Zone) } libLog.Debugf("Plugin Akamai Registrar GetDomains result: %v", domains) LibPluginResult.PluginResult = domains return } func GetDomain() { libLog.Debug("Entering Akamai Plugin Lib registrar GetDomain") // both edgedns and this plugin using dns. need to temp swap config... existConfig := dns.Config defer resetDNSConfig(existConfig) dns.Config = *akamaiLibRegistrar.config domain := LibPluginArgs.PluginArg.(string) zone, err := dns.GetZone(domain) if err != nil { LibPluginResult.PluginResult = registrar.Domain{} LibPluginResult.PluginError = err return } libLog.Debugf("Akamai Plugin Lib Registrar GetDomain result: %v", zone) LibPluginResult.PluginResult = registrar.Domain{ Name: zone.Zone, Type: zone.Type, SignAndServe: zone.SignAndServe, SignAndServeAlgorithm: zone.SignAndServeAlgorithm, Masters: zone.Masters, TsigKey: zone.TsigKey, } return } func GetTsigKey() { //(tsigKey *dns.TSIGKey, err error) { libLog.Debug("Entering Akamai Plugin Lib registrar GetTsigKey") // both edgedns and this plugin using dns. need to temp swap config... existConfig := dns.Config defer resetDNSConfig(existConfig) dns.Config = *akamaiLibRegistrar.config domain := LibPluginArgs.PluginArg.(string) resp, err := dns.GetZoneKey(domain) if err != nil { LibPluginResult.PluginResult = dns.TSIGKey{} LibPluginResult.PluginError = err return } libLog.Debugf("Returning Registrar GetTsigKey result") LibPluginResult.PluginResult = resp.TSIGKey return } func GetServeAlgorithm() { libLog.Debug("Entering Akamai Plugin Lib registrar GetServeAlgorithm") // both edgedns and this plugin using dns. need to temp swap config... existConfig := dns.Config defer resetDNSConfig(existConfig) dns.Config = *akamaiLibRegistrar.config domain := LibPluginArgs.PluginArg.(string) zone, err := dns.GetZone(domain) if err != nil { LibPluginResult.PluginResult = "" LibPluginResult.PluginError = err return } libLog.Debugf("Returning Registrar GetServeAlgorithm result") LibPluginResult.PluginResult = zone.SignAndServeAlgorithm return } func GetMasterIPs() { libLog.Debug("Entering Akamai Plugin Lib registrar GetMasterIPs") // both edgedns and this plugin using dns. need to temp swap config... existConfig := dns.Config defer resetDNSConfig(existConfig) dns.Config = *akamaiLibRegistrar.config LibPluginResult.PluginResult = []string{} if len(akamaiLibRegistrar.akaConfig.AkamaiContracts) < 1 { libLog.Debug("Registrar GetMasterIPs failed. No contracts") LibPluginResult.PluginError = fmt.Errorf("No contracts provided") return } contractId := strings.Split(akamaiLibRegistrar.akaConfig.AkamaiContracts, ",")[0] masters, err := dns.GetNameServerRecordList(contractId) if err != nil { libLog.Debugf("Registrar GetMasterIPs failed. Error: %s", err.Error()) LibPluginResult.PluginError = err return } libLog.Debugf("Akamai Plugin Registrar GetMasterIPs result: %v", masters) LibPluginResult.PluginResult = masters return } func loadConfig(configFile string) (*AkamaiConfig, error) { libLog.Debug("Entering Plugin Lib Akamai registrar loadConfig") if fileExists(configFile) { // Load config from file configData, err := ioutil.ReadFile(configFile) if err != nil { return nil, err } return loadConfigContent(configData) } libLog.Infof("Config file %v does not exist, using default values", configFile) return nil, nil } func loadConfigContent(configData []byte) (*AkamaiConfig, error) { config := AkamaiConfig{} err := yaml.Unmarshal(configData, &config) if err != nil { return nil, err } libLog.Info("Akamai plugin registrar config loaded") libLog.Debugf("Loaded config: %v", config) return &config, nil } func fileExists(filename string) bool { info, err := os.Stat(filename) if os.IsNotExist(err) { return false } return !info.IsDir() } func main() { fmt.Println("Akamai Plugin Library Registrar") }
package gfuns import ( "github.com/joho/godotenv" "log" "os" ) func Run_init() { err := godotenv.Load("env") if err != nil { log.Fatal("Error loading env file", err) } load() } func load() { if !Exists(os.TempDir() + "/ffmpeg") { ffmpeg, _ := os.Create(os.TempDir() + "/ffmpeg") ffprobe, _ := os.Create(os.TempDir() + "/ffprobe") _ = Download(GCSEvent{File: File{Url: "https://storage.googleapis.com/asrevo/ffmpeg"}}, *ffmpeg) _ = Download(GCSEvent{File: File{Url: "https://storage.googleapis.com/asrevo/ffprobe"}}, *ffprobe) _ = chmod(ffmpeg.Name()) _ = chmod(ffprobe.Name()) } }
package iban //IBAN is the international bank number representation type IBAN struct { Number string Length int } //NewIBAN creates a new IBAN from the given IBAN string func NewIBAN(number string) *IBAN { iban := IBAN{Number: number, Length: len(number)} return &iban }
package sensu import ( "encoding/json" "fmt" "github.com/streadway/amqp" "log" "os" "plugins" "strings" "time" ) const RESULTS_QUEUE = "results" type check struct { Name string `json:"name"` // the check name in sensu Command string `json:"command"` // the "command" that was run Executed uint `json:"executed"` // timestamp for when this check was started Issued uint `json:"issued"` // timestamp for when this check was sent Status int `json:"status"` // the status for the check. 0 = success. > 0 = fail Output string `json:"output"` // the output of the check script Duration float64 `json:"duration"` // how long it took to run the check. this needs to be transformed to "seconds.milliseconds CheckType string `json:"type"` // "metric|???" Handlers []string `json:"handlers"` // how this data is processed Interval int `json:"interval"` // how long between checks, in seconds Standalone bool `json:"standalone"` // was this check unsolicited? Address string `json:"-"` // usage unknown // not used timeout int started time.Time time_taken time.Duration } type ResultInterface interface { HasOutput() bool GetPayload() amqp.Publishing toJson() []byte } type Result struct { Client string `json:"client"` // DNS Name for this host client_short_name string Check check `json:"check"` checkStatus string // for checks we want to know if they are critical/warning/unknown/ok wrapOutput bool } type SavedResult struct { result []byte } // sets up the common result data func NewResult(clientConfig ClientConfig, check_name string) *Result { result := new(Result) result.wrapOutput = true result.Client = clientConfig.Name // host name schema is stb.<location-name>.loc.swiftnetworks.com.au bits := strings.Split(result.Client, ".") if "stb" == bits[0] { result.client_short_name = fmt.Sprintf("%s.%s", bits[0], bits[1]) } else { result.client_short_name = bits[0] } result.Check.Name = check_name result.Check.Address = clientConfig.Address result.Check.Executed = uint(time.Now().Unix()) result.Check.Handlers = make([]string, 1) result.Check.Handlers[0] = "metrics" result.Check.CheckType = "metric" result.Check.Standalone = true result.Check.Status = 0 result.Check.started = time.Now() return result } // takes each of our lines of output and prefixes the system we are checking // and suffixes the timestamp when we checked func (r *Result) SetOutput(rows []plugins.ResultStat) { switch r.Check.CheckType { case "metric": if !r.wrapOutput { // mainly for external metrics that provide their own fully qualified lines of output for _, row := range rows { r.Check.Output += row.Output + "\n" } } else { var t uint for _, row := range rows { if row.TimeIsSet { t = uint(row.Time.Unix()) } else { t = r.StartTime() } r.Check.Output += fmt.Sprintf("%s.%s %d\n", r.ShortName(), row.Output, t) } } case "check": for _, row := range rows { r.Check.Output += row.Output } } } func (r *Result) SetCheckStatus(s string) { r.checkStatus = s } func (r *Result) Output() string { var output string switch r.Check.CheckType { case "metric": output = r.Check.Output case "check": output = r.checkStatus + ": " + r.Check.Output } return output } func (r *Result) HasOutput() bool { return "" != r.Check.Output } func (r *Result) SetInterval(interval time.Duration) { r.Check.Interval = int(interval / time.Second) } func (r *Result) ShortName() string { return r.client_short_name } func (r *Result) StartTime() uint { return r.Check.Executed } func (r *Result) SetStatus(status int) { r.Check.Status = status } func (r *Result) SetCommand(command string) { r.Check.Command = command } func (r *Result) SetType(checktype string) { r.Check.CheckType = checktype } func (r *Result) SetWrapOutput(wrapOutput bool) { r.wrapOutput = wrapOutput } func (r *Result) calculate_duration() { var duration = time.Now().Sub(r.Check.started) r.Check.Duration = duration.Seconds() } func (result *Result) toJson() []byte { result.calculate_duration() result.Check.Output += "\n" result.Check.Issued = uint(time.Now().Unix()) json, err := json.Marshal(result) if nil != err { log.Panic(err) } if "" != os.Getenv("DEBUG") { log.Printf(string(json)) // handy json debug printing } return json } func (result *Result) GetPayload() amqp.Publishing { return getRabbitPayload(result.toJson()) } func getRabbitPayload(json []byte) amqp.Publishing { return amqp.Publishing{ ContentType: "application/octet-stream", Body: json, DeliveryMode: amqp.Transient, } } // Saved Results are just wrappers around JSON blobs func (sr *SavedResult) SetResult(json string) { sr.result = []byte(json) } func (sr *SavedResult) HasOutput() bool { return len(sr.result) > 0 } func (sr *SavedResult) GetPayload() amqp.Publishing { return getRabbitPayload(sr.result) } func (sr *SavedResult) toJson() []byte { return []byte(sr.result) }
package db import ( "log" "os" "testing" "time" "github.com/breathingdust/house.api/models" "github.com/stretchr/testify/assert" "gopkg.in/mgo.v2" ) func clearDatabase(conn string) { s, _ := mgo.Dial(conn) //defer s.Close() s.DB("house_test").C("transactions").RemoveAll(nil) } func getConnectionString() string { var mgoConn = os.Getenv("MGOCONN") if mgoConn == "" { log.Fatal("No connection string found.") } return mgoConn } func TestGetTransaction(t *testing.T) { mgoConn := getConnectionString() clearDatabase(mgoConn) database := NewDatabase(mgoConn, "house_test") tr := models.Transaction{} tr.Name = "Transaction Name" tr.Timestamp = time.Now() tr.Amount = 1.50 tr.Buyer = "simon" tr.Type = "shared" createdTransaction := database.CreateTransaction(&tr) gotTransaction := database.GetTransaction(createdTransaction.Id.Hex()) assert.Equal(t, tr.Name, gotTransaction.Name) } func TestGetTransactions(t *testing.T) { mgoConn := getConnectionString() clearDatabase(mgoConn) database := NewDatabase(mgoConn, "house_test") tr := models.Transaction{} tr.Name = "Transaction Name" tr.Timestamp = time.Now() tr.Amount = 1.50 tr.Buyer = "simon" tr.Type = "shared" database.CreateTransaction(&tr) transactions := database.GetTransactions() assert.Equal(t, tr.Name, (*transactions)[0].Name) }
package tree import ( "testing" ) // 1 // 2 3 // 4 5 6 func generateBinaryTree() *Node { root := NewTreeNode(1) root.left = NewTreeNode(2) root.right = NewTreeNode(3) root.left.left = NewTreeNode(4) root.left.right = NewTreeNode(5) root.right.left = NewTreeNode(6) return root } // 前序遍历,输出应为 1 2 4 5 3 6 func TestPreOrderRecursion(t *testing.T) { PreOrderRecursion(generateBinaryTree()) } func TestPreOrderNotRecursion(t *testing.T) { PreOrderNotRecursion(generateBinaryTree()) println() PreOrderNonRecursion(generateBinaryTree()) } // 中序遍历,输出应为 4 2 5 1 6 3 func TestInOrderRecursion(t *testing.T) { InOrderRecursion(generateBinaryTree()) } // 后序遍历,输出应为 4 5 2 6 3 1 func TestPostOrderRecursion(t *testing.T) { PostOrderRecursion(generateBinaryTree()) } // 层序遍历,输出应为 1 2 3 4 5 6 func TestLevelOrder(t *testing.T) { LevelOrder(generateBinaryTree()) }
package main import ( "math/big" "fmt" "bytes" ) //定义切片存储base58字母 var b58Alphaet = []byte("123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") func Base58Encode(input []byte) []byte { var result []byte //定义一个切片。返回值 x := big.NewInt(0).SetBytes(input) //把字节数组input转化为大整数bigint base := big.NewInt(int64(len(b58Alphaet))) //长度58的大整数 zero := big.NewInt(0) //0的大整数 mod := &big.Int{} //大整数的指针 //循环。不停地对58取余数,大小为58 for x.Cmp(zero) != 0 { x.DivMod(x,base,mod) //对x取余数 result = append(result,b58Alphaet[mod.Int64()]) //将余数添加到数组当中 } ReverseBytes(result) //反转字节数组 //如果字节数组的前位为字节0,替换为1。比特币中特殊做法 for b := range input{ if b ==0x00{ result = append([]byte{b58Alphaet[0]},result...) }else { break } } return result } func Base58Decode(input []byte) []byte { result := big.NewInt(0) zeroBytes := 0 for _, b := range input { if b != b58Alphaet[0] { break } zeroBytes++ } payload := input[zeroBytes:] for _, b := range payload { charIndex := bytes.IndexByte(b58Alphaet, b) result.Mul(result, big.NewInt(int64(len(b58Alphaet)))) result.Add(result, big.NewInt(int64(charIndex))) } decoded := result.Bytes() decoded = append(bytes.Repeat([]byte{byte(0x00)}, zeroBytes), decoded...) return decoded } //反转字节数组 func ReverseBytes(data []byte) { for i,j := 0,len(data) -1;i < j; i,j = i+1,j - 1 { data[i],data[j] = data[j],data[i] } } func main() { /* 测试反转 org := []byte("qwerty") fmt.Println(string(org)) ReverseBytes(org) fmt.Println(string(org))*/ fmt.Printf("%s\n",string(Base58Encode([]byte("hello audiRStony")))) fmt.Printf("%s\n",string(Base58Decode([]byte("15Thn1blcfwNDHKggdKybtR")))) }
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "context" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" betapb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/binaryauthorization/beta/binaryauthorization_beta_go_proto" emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto" "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/binaryauthorization/beta" ) // AttestorServer implements the gRPC interface for Attestor. type AttestorServer struct{} // ProtoToAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum converts a AttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum enum from its proto representation. func ProtoToBinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum(e betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum) *beta.AttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum { if e == 0 { return nil } if n, ok := betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum_name[int32(e)]; ok { e := beta.AttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum(n[len("BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum"):]) return &e } return nil } // ProtoToAttestorUserOwnedDrydockNote converts a AttestorUserOwnedDrydockNote object from its proto representation. func ProtoToBinaryauthorizationBetaAttestorUserOwnedDrydockNote(p *betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNote) *beta.AttestorUserOwnedDrydockNote { if p == nil { return nil } obj := &beta.AttestorUserOwnedDrydockNote{ NoteReference: dcl.StringOrNil(p.GetNoteReference()), DelegationServiceAccountEmail: dcl.StringOrNil(p.GetDelegationServiceAccountEmail()), } for _, r := range p.GetPublicKeys() { obj.PublicKeys = append(obj.PublicKeys, *ProtoToBinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeys(r)) } return obj } // ProtoToAttestorUserOwnedDrydockNotePublicKeys converts a AttestorUserOwnedDrydockNotePublicKeys object from its proto representation. func ProtoToBinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeys(p *betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeys) *beta.AttestorUserOwnedDrydockNotePublicKeys { if p == nil { return nil } obj := &beta.AttestorUserOwnedDrydockNotePublicKeys{ Comment: dcl.StringOrNil(p.GetComment()), Id: dcl.StringOrNil(p.GetId()), AsciiArmoredPgpPublicKey: dcl.StringOrNil(p.GetAsciiArmoredPgpPublicKey()), PkixPublicKey: ProtoToBinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKey(p.GetPkixPublicKey()), } return obj } // ProtoToAttestorUserOwnedDrydockNotePublicKeysPkixPublicKey converts a AttestorUserOwnedDrydockNotePublicKeysPkixPublicKey object from its proto representation. func ProtoToBinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKey(p *betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKey) *beta.AttestorUserOwnedDrydockNotePublicKeysPkixPublicKey { if p == nil { return nil } obj := &beta.AttestorUserOwnedDrydockNotePublicKeysPkixPublicKey{ PublicKeyPem: dcl.StringOrNil(p.GetPublicKeyPem()), SignatureAlgorithm: ProtoToBinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum(p.GetSignatureAlgorithm()), } return obj } // ProtoToAttestor converts a Attestor resource from its proto representation. func ProtoToAttestor(p *betapb.BinaryauthorizationBetaAttestor) *beta.Attestor { obj := &beta.Attestor{ Name: dcl.StringOrNil(p.GetName()), Description: dcl.StringOrNil(p.GetDescription()), UserOwnedDrydockNote: ProtoToBinaryauthorizationBetaAttestorUserOwnedDrydockNote(p.GetUserOwnedDrydockNote()), UpdateTime: dcl.StringOrNil(p.GetUpdateTime()), Project: dcl.StringOrNil(p.GetProject()), } return obj } // AttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnumToProto converts a AttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum enum to its proto representation. func BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnumToProto(e *beta.AttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum) betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum { if e == nil { return betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum(0) } if v, ok := betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum_value["AttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum"+string(*e)]; ok { return betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum(v) } return betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnum(0) } // AttestorUserOwnedDrydockNoteToProto converts a AttestorUserOwnedDrydockNote object to its proto representation. func BinaryauthorizationBetaAttestorUserOwnedDrydockNoteToProto(o *beta.AttestorUserOwnedDrydockNote) *betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNote { if o == nil { return nil } p := &betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNote{} p.SetNoteReference(dcl.ValueOrEmptyString(o.NoteReference)) p.SetDelegationServiceAccountEmail(dcl.ValueOrEmptyString(o.DelegationServiceAccountEmail)) sPublicKeys := make([]*betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeys, len(o.PublicKeys)) for i, r := range o.PublicKeys { sPublicKeys[i] = BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysToProto(&r) } p.SetPublicKeys(sPublicKeys) return p } // AttestorUserOwnedDrydockNotePublicKeysToProto converts a AttestorUserOwnedDrydockNotePublicKeys object to its proto representation. func BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysToProto(o *beta.AttestorUserOwnedDrydockNotePublicKeys) *betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeys { if o == nil { return nil } p := &betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeys{} p.SetComment(dcl.ValueOrEmptyString(o.Comment)) p.SetId(dcl.ValueOrEmptyString(o.Id)) p.SetAsciiArmoredPgpPublicKey(dcl.ValueOrEmptyString(o.AsciiArmoredPgpPublicKey)) p.SetPkixPublicKey(BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeyToProto(o.PkixPublicKey)) return p } // AttestorUserOwnedDrydockNotePublicKeysPkixPublicKeyToProto converts a AttestorUserOwnedDrydockNotePublicKeysPkixPublicKey object to its proto representation. func BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeyToProto(o *beta.AttestorUserOwnedDrydockNotePublicKeysPkixPublicKey) *betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKey { if o == nil { return nil } p := &betapb.BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKey{} p.SetPublicKeyPem(dcl.ValueOrEmptyString(o.PublicKeyPem)) p.SetSignatureAlgorithm(BinaryauthorizationBetaAttestorUserOwnedDrydockNotePublicKeysPkixPublicKeySignatureAlgorithmEnumToProto(o.SignatureAlgorithm)) return p } // AttestorToProto converts a Attestor resource to its proto representation. func AttestorToProto(resource *beta.Attestor) *betapb.BinaryauthorizationBetaAttestor { p := &betapb.BinaryauthorizationBetaAttestor{} p.SetName(dcl.ValueOrEmptyString(resource.Name)) p.SetDescription(dcl.ValueOrEmptyString(resource.Description)) p.SetUserOwnedDrydockNote(BinaryauthorizationBetaAttestorUserOwnedDrydockNoteToProto(resource.UserOwnedDrydockNote)) p.SetUpdateTime(dcl.ValueOrEmptyString(resource.UpdateTime)) p.SetProject(dcl.ValueOrEmptyString(resource.Project)) return p } // applyAttestor handles the gRPC request by passing it to the underlying Attestor Apply() method. func (s *AttestorServer) applyAttestor(ctx context.Context, c *beta.Client, request *betapb.ApplyBinaryauthorizationBetaAttestorRequest) (*betapb.BinaryauthorizationBetaAttestor, error) { p := ProtoToAttestor(request.GetResource()) res, err := c.ApplyAttestor(ctx, p) if err != nil { return nil, err } r := AttestorToProto(res) return r, nil } // applyBinaryauthorizationBetaAttestor handles the gRPC request by passing it to the underlying Attestor Apply() method. func (s *AttestorServer) ApplyBinaryauthorizationBetaAttestor(ctx context.Context, request *betapb.ApplyBinaryauthorizationBetaAttestorRequest) (*betapb.BinaryauthorizationBetaAttestor, error) { cl, err := createConfigAttestor(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return s.applyAttestor(ctx, cl, request) } // DeleteAttestor handles the gRPC request by passing it to the underlying Attestor Delete() method. func (s *AttestorServer) DeleteBinaryauthorizationBetaAttestor(ctx context.Context, request *betapb.DeleteBinaryauthorizationBetaAttestorRequest) (*emptypb.Empty, error) { cl, err := createConfigAttestor(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return &emptypb.Empty{}, cl.DeleteAttestor(ctx, ProtoToAttestor(request.GetResource())) } // ListBinaryauthorizationBetaAttestor handles the gRPC request by passing it to the underlying AttestorList() method. func (s *AttestorServer) ListBinaryauthorizationBetaAttestor(ctx context.Context, request *betapb.ListBinaryauthorizationBetaAttestorRequest) (*betapb.ListBinaryauthorizationBetaAttestorResponse, error) { cl, err := createConfigAttestor(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } resources, err := cl.ListAttestor(ctx, request.GetProject()) if err != nil { return nil, err } var protos []*betapb.BinaryauthorizationBetaAttestor for _, r := range resources.Items { rp := AttestorToProto(r) protos = append(protos, rp) } p := &betapb.ListBinaryauthorizationBetaAttestorResponse{} p.SetItems(protos) return p, nil } func createConfigAttestor(ctx context.Context, service_account_file string) (*beta.Client, error) { conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file)) return beta.NewClient(conf), nil }
package main import ( "encoding/binary" "fmt" "math/big" "time" clt "github.com/QuarkChain/goqkcclient/client" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/rlp" ) var ( client = clt.NewClient("http://jrpc.devnet.quarkchain.io:38391") fullShardKey = uint32(0) ) func main() { address, _ := hexutil.Decode("0x33f99d65322731353c948808b2e9208d2b22f5520000888d") prvkey, _ := crypto.ToECDSA(common.FromHex("0x8d298c57e269a379c4956583f095b2557c8f07226410e02ae852bc4563864790")) context := make(map[string]string) addr := clt.QkcAddress{Recipient: common.BytesToAddress(address[:20]), FullShardKey: binary.BigEndian.Uint32(address[20:])} context["address"] = addr.Recipient.Hex() context["fromFullShardKey"] = addr.FullShardKeyToHex() getBalance(&addr) _, qkcToAddr, err := clt.NewAddress(0) if err != nil { fmt.Println("NewAddress error: ", err.Error()) } context["from"] = addr.Recipient.Hex() context["to"] = qkcToAddr.Recipient.Hex() context["amount"] = "0" context["price"] = "100000000000" context["toFullShardKey"] = qkcToAddr.FullShardKeyToHex() context["privateKey"] = common.Bytes2Hex(prvkey.D.Bytes()) tx, txid, err := sent(context) if err != nil { fmt.Printf("sent transaction err: %s\r\n", err.Error()) } encode, _ := rlp.EncodeToBytes(tx) fmt.Printf("tx encode: %s\n", common.Bytes2Hex(encode)) decodeTx := new(clt.EvmTransaction) rlp.DecodeBytes(encode, decodeTx) fmt.Printf("tx decode: %v\n", decodeTx) context["txid"] = txid getTransaction(context) time.Sleep(15 * time.Second) getReceipt(context) } // 获取余额 func getBalance(addr *clt.QkcAddress) { // address := common.HexToAddress(ctx.FormValue("address")) balance, err := client.GetBalance(addr, "QKC") if err != nil { fmt.Println(err.Error()) } fmt.Println(balance) } // 获取区块和交易内容 func getBlock(ctx map[string]string) map[string]interface{} { heightStr := ctx["height"] height := new(big.Int).SetBytes(common.FromHex(heightStr)) result, err := client.GetRootBlockByHeight(height) if err != nil { fmt.Println(err.Error()) } headers := result.Result.(map[string]interface{})["minorBlockHeaders"] headerIdList := make([]string, 0) txList := make([]interface{}, 0) for _, h := range headers.([]interface{}) { info := h.(map[string]interface{}) id := (info["id"]).(string) headerIdList = append(headerIdList, id) } fmt.Println("headerIdList len", len(headerIdList)) for _, headerId := range headerIdList { mresult, err := client.GetMinorBlockById(headerId) if err != nil { fmt.Println(err.Error()) } txs := mresult.Result.(map[string]interface{})["transactions"] for _, tx := range txs.([]interface{}) { txList = append(txList, tx) } } result.Result.(map[string]interface{})["transactions"] = txList fmt.Println("txList len", len(txList)) fmt.Println(result.Result) return result.Result.(map[string]interface{}) } // 获取交易回执 func getReceipt(ctx map[string]string) { txid, err := clt.ByteToTransactionId(common.FromHex(ctx["txid"])) if err != nil { fmt.Println(err.Error()) } result, err := client.GetTransactionReceipt(txid) if err != nil { fmt.Println("getTransactionReceipt error: ", err.Error()) } fmt.Println(result.Result) } func getHeight(ctx map[string]string) uint64 { height, err := client.GetRootBlockHeight() if err != nil { fmt.Println(err.Error()) } fmt.Println(height) return height } func getTransaction(ctx map[string]string) { txid, err := clt.ByteToTransactionId(common.FromHex(ctx["txid"])) if err != nil { fmt.Println(err.Error()) } result, err := client.GetTransactionById(txid) if err != nil { fmt.Println(err.Error()) } fmt.Println("txid", result.Result.(map[string]interface{})["id"]) fmt.Println(result.Result) } func sent(ctx map[string]string) (*clt.EvmTransaction, string, error) { from := common.HexToAddress(ctx["from"]) to := common.HexToAddress(ctx["to"]) amount, _ := new(big.Int).SetString(ctx["amount"], 10) gasPrice, _ := new(big.Int).SetString(ctx["price"], 10) privateKey := ctx["privateKey"] prvkey, _ := crypto.ToECDSA(common.FromHex(privateKey)) fromFullShardKey := fullShardKey if _, ok := ctx["fromFullShardKey"]; ok { fromFullShardKey = uint32(new(big.Int).SetBytes(common.FromHex(ctx["fromFullShardKey"])).Uint64()) } toFullShardKey := fullShardKey if _, ok := ctx["toFullShardKey"]; ok { toFullShardKey = uint32(new(big.Int).SetBytes(common.FromHex(ctx["toFullShardKey"])).Uint64()) } nonce, err := client.GetNonce(&clt.QkcAddress{Recipient: from, FullShardKey: fromFullShardKey}) if err != nil { return nil, "", err } networkid, err := client.NetworkID() if err != nil { return nil, "", err } tx := client.CreateTransaction(networkid, nonce, fromFullShardKey, &clt.QkcAddress{Recipient: to, FullShardKey: toFullShardKey}, amount, uint64(30000), gasPrice, clt.TokenIDEncode("QKC"), []byte{}) // tx, err := client.CreateTransaction(&clt.QkcAddress{Recipient: from, FullShardKey: fromFullShardKey}, &clt.QkcAddress{Recipient: to, FullShardKey: toFullShardKey}, amount, uint64(30000), gasPrice) if err != nil { return nil, "", err } tx, err = clt.SignTx(tx, prvkey) if err != nil { return nil, "", err } txid, err := client.SendTransaction(tx) if err != nil { return nil, "", err } fmt.Println(common.Bytes2Hex(txid)) return tx, common.Bytes2Hex(txid), nil }
/* The Chinese Remainder Theorem tells us that we can always find a number that produces any required remainders under different prime moduli. Your goal is to write code to output such a number in polynomial time. Shortest code wins. For example, say we're given these constraints: n ≡ 2 mod 7 n ≡ 4 mod 5 n ≡ 0 mod 11 One solution is n=44. The first constraint is satisfied because 44=6×7+2, and so 44 has remainder 2 when divided by 7, and thus 44≡2mod7. The other two constraints are met as well. There exist other solutions, such as n=814 and n=−341. Input A non-empty list of pairs (pi,ai), where each modulus pi is a distinct prime and each target ai is a natural number in the range 0≤ai<pi. You can take input in whatever form is convenient; it doesn't have to actually be a list of pairs. You may not assume the input is sorted. Output An integer n such that n ≡ a_i mod p_i for each index i. It doesn't have to be the smallest such value, and may be negative. Polynomial time restriction To prevent cheap solutions that just try n=0,1,2,…, and so on, your code must run in polynomial time in the length of the input. Note that a number m in the input has length Θ(logm), so m itself is not polynomial in its length. This means that you can't count up to m or do an operation m times, but you can compute arithmetic operations on the values. You may not use an inefficient input format like unary to get around this. Other bans Built-ins to do the following are not allowed: Implement the Chinese Remainder theorem, solve equations, or factor numbers. You may use built-ins to find mods and do modular addition, subtraction, multiplication, and exponentiation (with natural-number exponent). You may not use other built-in modular operations, including modular inverse, division, and order-finding. Test cases These give the smallest non-negative solution. Your answer may be different. It's probably better if you check directly that your output satisfies each constraint. [(5, 3)] 3 [(7, 2), (5, 4), (11, 0)] 44 [(5, 1), (73, 4), (59, 30), (701, 53), (139, 112)] 1770977011 [(982451653, 778102454), (452930477, 133039003)] 68121500720666070 */ package main import ( "fmt" "math/big" ) func main() { test([][2]uint64{ {5, 3}, }, 3) test([][2]uint64{ {7, 2}, {5, 4}, {11, 0}, }, 44) test([][2]uint64{ {5, 1}, {73, 4}, {59, 30}, {701, 53}, {139, 112}, }, 1770977011) test([][2]uint64{ {982451653, 778102454}, {452930477, 133039003}, }, 68121500720666070) } func test(a [][2]uint64, r uint64) { p := crt(a) fmt.Println(p) assert(p == r) } func assert(x bool) { if !x { panic("assertion failed") } } // https://crypto.stanford.edu/pbc/notes/numbertheory/crt.html func crt(p [][2]uint64) uint64 { m := new(big.Int) a := new(big.Int) b := new(big.Int) bi := new(big.Int) M := big.NewInt(1) for _, v := range p { m.SetUint64(v[0]) M.Mul(M, m) } t := new(big.Int) r := new(big.Int) for _, v := range p { m.SetUint64(v[0]) a.SetUint64(v[1]) b.Quo(M, m) bi.ModInverse(b, m) t.Set(a) t.Mul(t, b) t.Mul(t, bi) r.Add(r, t) } r.Mod(r, M) return r.Uint64() }
package ecs import "testing" var commandOverrideTests = []struct { commandString string expectedOverride []string }{ {"node src/bin/cli.js generate-snapshots", []string{"node", "src/bin/cli.js", "generate-snapshots"}}, { "sh -c \"/var/www/qc2-crons; php /var/www/app/Console/cake.php cron generateScorecardsData\"", []string{"sh", "-c", "/var/www/qc2-crons; php /var/www/app/Console/cake.php cron generateScorecardsData"}, }, } func TestCommandParsing(t *testing.T) { for _, args := range commandOverrideTests { t.Run(args.commandString, func(t *testing.T) { override, err := parseCommandOverride(args.commandString) if err != nil && args.expectedOverride != nil { t.Errorf("expected error") } for i := range override { if override[i] != args.expectedOverride[i] { t.Errorf("expected override %v , got %v", args.expectedOverride, override) } } }) } }
package cloudflare import ( "context" "encoding/json" "errors" "fmt" "net/http" ) var ErrMissingWorkerRouteID = errors.New("missing required route ID") type ListWorkerRoutes struct{} type CreateWorkerRouteParams struct { Pattern string `json:"pattern"` Script string `json:"script,omitempty"` } type ListWorkerRoutesParams struct{} type UpdateWorkerRouteParams struct { ID string `json:"id,omitempty"` Pattern string `json:"pattern"` Script string `json:"script,omitempty"` } // CreateWorkerRoute creates worker route for a script. // // API reference: https://api.cloudflare.com/#worker-routes-create-route func (api *API) CreateWorkerRoute(ctx context.Context, rc *ResourceContainer, params CreateWorkerRouteParams) (WorkerRouteResponse, error) { if rc.Level != ZoneRouteLevel { return WorkerRouteResponse{}, fmt.Errorf(errInvalidResourceContainerAccess, ZoneRouteLevel) } if rc.Identifier == "" { return WorkerRouteResponse{}, ErrMissingIdentifier } uri := fmt.Sprintf("/zones/%s/workers/routes", rc.Identifier) res, err := api.makeRequestContext(ctx, http.MethodPost, uri, params) if err != nil { return WorkerRouteResponse{}, err } var r WorkerRouteResponse err = json.Unmarshal(res, &r) if err != nil { return WorkerRouteResponse{}, fmt.Errorf("%s: %w", errUnmarshalError, err) } return r, nil } // DeleteWorkerRoute deletes worker route for a script. // // API reference: https://api.cloudflare.com/#worker-routes-delete-route func (api *API) DeleteWorkerRoute(ctx context.Context, rc *ResourceContainer, routeID string) (WorkerRouteResponse, error) { if rc.Level != ZoneRouteLevel { return WorkerRouteResponse{}, fmt.Errorf(errInvalidResourceContainerAccess, ZoneRouteLevel) } if rc.Identifier == "" { return WorkerRouteResponse{}, ErrMissingIdentifier } if routeID == "" { return WorkerRouteResponse{}, errors.New("missing required route ID") } uri := fmt.Sprintf("/zones/%s/workers/routes/%s", rc.Identifier, routeID) res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return WorkerRouteResponse{}, err } var r WorkerRouteResponse err = json.Unmarshal(res, &r) if err != nil { return WorkerRouteResponse{}, fmt.Errorf("%s: %w", errUnmarshalError, err) } return r, nil } // ListWorkerRoutes returns list of Worker routes. // // API reference: https://api.cloudflare.com/#worker-routes-list-routes func (api *API) ListWorkerRoutes(ctx context.Context, rc *ResourceContainer, params ListWorkerRoutesParams) (WorkerRoutesResponse, error) { if rc.Level != ZoneRouteLevel { return WorkerRoutesResponse{}, fmt.Errorf(errInvalidResourceContainerAccess, ZoneRouteLevel) } if rc.Identifier == "" { return WorkerRoutesResponse{}, ErrMissingIdentifier } uri := fmt.Sprintf("/zones/%s/workers/routes", rc.Identifier) res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return WorkerRoutesResponse{}, err } var r WorkerRoutesResponse err = json.Unmarshal(res, &r) if err != nil { return WorkerRoutesResponse{}, fmt.Errorf("%s: %w", errUnmarshalError, err) } return r, nil } // GetWorkerRoute returns a Workers route. // // API reference: https://api.cloudflare.com/#worker-routes-get-route func (api *API) GetWorkerRoute(ctx context.Context, rc *ResourceContainer, routeID string) (WorkerRouteResponse, error) { if rc.Level != ZoneRouteLevel { return WorkerRouteResponse{}, fmt.Errorf(errInvalidResourceContainerAccess, ZoneRouteLevel) } if rc.Identifier == "" { return WorkerRouteResponse{}, ErrMissingIdentifier } uri := fmt.Sprintf("/zones/%s/workers/routes/%s", rc.Identifier, routeID) res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return WorkerRouteResponse{}, err } var r WorkerRouteResponse err = json.Unmarshal(res, &r) if err != nil { return WorkerRouteResponse{}, fmt.Errorf("%s: %w", errUnmarshalError, err) } return r, nil } // UpdateWorkerRoute updates worker route for a script. // // API reference: https://api.cloudflare.com/#worker-routes-update-route func (api *API) UpdateWorkerRoute(ctx context.Context, rc *ResourceContainer, params UpdateWorkerRouteParams) (WorkerRouteResponse, error) { if rc.Level != ZoneRouteLevel { return WorkerRouteResponse{}, fmt.Errorf(errInvalidResourceContainerAccess, ZoneRouteLevel) } if rc.Identifier == "" { return WorkerRouteResponse{}, ErrMissingIdentifier } if params.ID == "" { return WorkerRouteResponse{}, ErrMissingWorkerRouteID } uri := fmt.Sprintf("/zones/%s/workers/routes/%s", rc.Identifier, params.ID) res, err := api.makeRequestContext(ctx, http.MethodPut, uri, params) if err != nil { return WorkerRouteResponse{}, err } var r WorkerRouteResponse err = json.Unmarshal(res, &r) if err != nil { return WorkerRouteResponse{}, fmt.Errorf("%s: %w", errUnmarshalError, err) } return r, nil }
package queue type ( // Queue FIFO Queue struct { start, end *node length int } node struct { value interface{} next *node } ) // New Create a new queue func New() *Queue { return &Queue{nil, nil, 0} } // Len Return the number of items in the queue func (q *Queue) Len() int { return q.length } // Enqueue Put an item on the end of a queue func (q *Queue) Enqueue(value interface{}) { n := &node{value, nil} if q.length != 0 { q.end.next = n q.end = n } else { q.start, q.end = n, n } q.length++ } // Dequeue Take the next item off the front of the queue func (q *Queue) Dequeue() interface{} { if q.length == 0 { return nil } n := q.start if q.length != 1 { q.start = q.start.next } else { q.start = nil q.end = nil } q.length-- return n.value } // Peek Return the first item in the queue without removing it func (q *Queue) Peek() interface{} { if q.length == 0 { return nil } return q.start.value }
package main import ( "flag" "fmt" //"log" "os" //"os/exec" "strconv" "strings" ) const ( ErrorRevision = -1 RevisionSep = "," ) type Revision int32 type RevisionPair struct { defined bool a Revision b Revision } func (r *Revision) String() string { return strconv.Itoa(int(*r)) } func (r *Revision) Set(s string) error { *r = ErrorRevision v, err := strconv.ParseInt(s, 0, 32) if nil != err { return fmt.Errorf("revision number \"%s\" not an integer", s) } if v < 0 { return fmt.Errorf("revision number \"%d\" less than zero", v) } *r = Revision(v) return nil } func (p *RevisionPair) String() string { if (p.a != ErrorRevision) && (p.b != ErrorRevision) { return fmt.Sprintf("%ld%s%ld", p.a, RevisionSep, p.b) } if p.a != ErrorRevision { return fmt.Sprintf("%ld", p.a) } if p.b != ErrorRevision { return fmt.Sprintf("%ld", p.b) } return "" } func (p *RevisionPair) Set(s string) error { set := func(r *Revision, t []string, i uint8) error { if int(i) < len(t) { return r.Set(t[i]) } else { *r = ErrorRevision return nil // not an error } } t := strings.Split(s, RevisionSep) if e := set(&p.a, t, 0); nil != e { return e } if e := set(&p.b, t, 1); nil != e { return e } p.defined = true return nil } type SVNPath struct { path string rev Revision wc bool head bool } func (p *SVNPath) String() string { a := []string{fmt.Sprintf("%d", p.rev)} if p.head { a = append(a, "HEAD") } if p.wc { a = append(a, "WC") } return fmt.Sprintf("%s@(%s)", p.path, strings.Join(a, ",")) } var revision RevisionPair func usage() { fmt.Println("") fmt.Println("-- USAGE -----------------------------------------------------------------------") fmt.Println("") fmt.Printf(" %s [-r REVS] PATH\n", os.Args[0]) fmt.Println("") fmt.Println("") fmt.Println("-- OPTIONS ---------------------------------------------------------------------") fmt.Println("") flag.PrintDefaults() fmt.Println("") fmt.Println("\tif no options are provided:") fmt.Println("\t 1. the WC at PATH is compared to the HEAD revision") fmt.Println("\t * PATH must be a valid SVN WC") fmt.Println("") fmt.Println("\tif a single revision REV is provided to option -r:") fmt.Println("\t if PATH exists on local filesystem:") fmt.Println("\t 2. the revision at REV is compared to the WC at PATH") fmt.Println("\t * PATH must be a valid SVN WC") fmt.Println("\t if PATH does NOT exist on local filesystem:") fmt.Println("\t 3. the revision at REV is compared to the revision at HEAD") fmt.Println("\t * PATH must be a fully-qualified SVN URL") fmt.Println("") fmt.Println("\tif two comma-separated revisions REV1,REV2 are provided to option -r:") fmt.Println("\t 4. the revision at REV1 is compared to the revision at REV2") fmt.Println("\t * PATH must be a fully-qualified SVN URL") fmt.Println("") } func main() { flag.Usage = usage flag.Var(&revision, "r", "compare path at the specified SVN revision(s) `rev1[,rev2]`.") flag.Parse() if revision.defined { fmt.Printf("yes") } else { fmt.Printf("no") } }
package main import ( "bytes" "io/ioutil" "log" "regexp" "time" "github.com/fatih/color" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.Use(reqLogger()) router.GET("/", func(context *gin.Context) { context.JSON(200, gin.H{ "app": "budgetbro API", "timeNow": time.Now(), }) }) router.POST("/fulfillment") router.Run() } func reqLogger() gin.HandlerFunc { return func(context *gin.Context) { // skip log if req is a file upload header := context.GetHeader("Content-Type") // check if incoming header is multipart form upload, _ := regexp.MatchString("multipart/form-data", header) if upload { log.Printf("File upload recognized. Header: %s\n", header) context.Next() return } bodyBytes, err := ioutil.ReadAll(context.Request.Body) if err != nil { log.Println("Unable to read request body: ", err.Error()) context.Next() return } // restore the io.ReadCloser to its original state context.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) // set bytes into readable string bodyString := string(bodyBytes) // log request body color.Cyan("Request header: %s \n", header) color.Cyan("Request body: ") color.Cyan(bodyString) context.Next() } }
package mocking import "reflect" //Restorer 함수 타입은 이전 상태를 복원하기 위해 //사용할 수 있는 함수를 보유하고 있다. type Restorer func() //Restore 함수를 호출하면 이전 상태로 복원된다. func (r Restorer) Restore() { r() } //Patch 함수는 지정된 대상(destination)이 가리키는 값을 주어진 값으로 //설정하고, 이를 원래 상태로 되돌릴 수 있는 함수를 리턴한다. //이 값은 반드시 대상 타입의 객체에 //할당 가능 (assignable)해야 한다. func Patch(dest, value interface{}) Restorer { destv := reflect.ValueOf(dest).Elem() oldv := reflect.New(destv.Type()).Elem() oldv.Set(destv) valuev := reflect.ValueOf(value) if !valuev.IsValid() { //대상 타입이 nil 값을 가질 수 없는 타입인 경우, //이렇게 처리하는 것은 좋은 방법이라고 할 수 없지만 //다른 복잡한 방법을 사용하는 것보단 낫다. valuev = reflect.Zero(destv.Type()) } destv.Set(valuev) return func() { destv.Set(oldv) } }
package fuctional_options import ( "crypto/tls" "time" ) type Server struct { Addr string Port int Protocol string Timeout time.Duration MaxConns int TLS *tls.Config } func NewDefaultServer(addr string, port int) (*Server, error) { return &Server{addr, port, "tcp", 30 * time.Second, 100, nil}, nil } func NewTLSServer(addr string, port int, tls *tls.Config) (*Server, error) { return &Server{addr, port, "tcp", 30 * time.Second, 100, tls}, nil } func NewServerWithTimeout(addr string, port int, timeout time.Duration) (*Server, error) { return &Server{addr, port, "tcp", timeout, 100, nil}, nil } func NewTLSServerWithMaxConnAndTimeout(addr string, port int, maxconns int, timeout time.Duration, tls *tls.Config) (*Server, error) { return &Server{addr, port, "tcp", 30 * time.Second, maxconns, tls}, nil }
/* nighthawk.nhstruct.persistence.go * author: roshan maskey <roshanmaskey@gmail.com> * * Datastructure for persistence */ package nhstruct type PersistenceItem struct { JobCreated string `xml:"created,attr"` TlnTime string `json:"TlnTime"` PersistenceType string RegPath string RegOwner string RegModified string Path string `xml:"FilePath"` FileOwner string FileCreated string FileModified string FileAccessed string FileChanged string Md5sum string `xml:"md5sum"` File FileItem `xml:"FileItem"` Registry RegistryItem `xml:"RegistryItem"` StackPath string IsGoodPersistence string IsWhitelisted bool IsBlacklisted bool NHScore int Tag string NhComment NHComment `json:"Comment"` }
package heapsort func heapify(arr []int, n, current int) { right := 2*current + 2 left := 2*current + 1 root := current if left < n && arr[left] > arr[root] { root = left } if right < n && arr[right] > arr[root] { root = right } if root != current { swap(arr, current, root) heapify(arr, n, root) } } func swap(arr []int, a, b int) { arr[a], arr[b] = arr[b], arr[a] } //HeapSort sorts the given array func HeapSort(arr []int) { n := len(arr) for i := n/2 - 1; i >= 0; i-- { heapify(arr, n, i) } for i := n - 1; i >= 0; i-- { swap(arr, 0, i) heapify(arr, i, 0) } }
package api import ( "bytes" "encoding/json" "fmt" "io" "net/http" "time" "strconv" "github.com/go-errors/errors" "tezos-contests.izibi.com/backend/signing" ) func (s *Server) NewGame(firstBlock string) (*GameState, error) { type Request struct { Author string `json:"author"` FirstBlock string `json:"first_block"` Timestamp string `json:"timestamp"` } res := GameState{} err := s.SignedRequest("/Games", Request{ Author: s.Author(), FirstBlock: firstBlock, Timestamp: time.Now().Format(time.RFC3339), }, &res) if err != nil { return nil, err } return &res, nil } func (s *Server) ShowGame(gameKey string) (*GameState, error) { type Response struct { Game GameState `json:"game"` } var res = &Response{} err := s.GetRequest("/Games/"+gameKey, res) if err != nil { return nil, err } return &res.Game, nil } /* Register a number of bots for our team and retrieve their ranks in the game. */ func (s *Server) Register(gameKey string, botIds []uint32) ([]uint32, error) { type Request struct { Author string `json:"author"` GameKey string `json:"gameKey"` Action string `json:"action"` BotIds []uint32 `json:"botIds"` } type Response struct { Ranks []uint32 `json:"ranks"` } reqPath := fmt.Sprintf("/Games/%s", gameKey) var res Response err := s.SignedRequest(reqPath, Request{ Author: s.Author(), Action: "register bots", GameKey: gameKey, BotIds: botIds, }, &res) if err != nil { return nil, err } return res.Ranks, nil } func (s *Server) InputCommands(gameKey string, currentBlock string, teamPlayer uint32, commands string) error { type Request struct { Author string `json:"author"` GameKey string `json:"gameKey"` Action string `json:"action"` Player uint32 `json:"player"` CurrentBlock string `json:"current_block"` Commands string `json:"commands"` } reqPath := fmt.Sprintf("/Games/%s", gameKey) return s.SignedRequest(reqPath, Request{ Author: s.Author(), Action: "enter commands", GameKey: gameKey, Player: teamPlayer, CurrentBlock: currentBlock, Commands: commands, }, nil) } func (s *Server) CloseRound(gameKey string, currentBlock string) ([]byte, error) { type Request struct { Author string `json:"author"` GameKey string `json:"gameKey"` Action string `json:"action"` CurrentBlock string `json:"current_block"` } type Response struct { Commands json.RawMessage `json:"commands"` } var err error var res Response reqPath := fmt.Sprintf("/Games/%s", gameKey) err = s.SignedRequest(reqPath, Request{ Author: s.Author(), Action: "close round", GameKey: gameKey, CurrentBlock: currentBlock, }, &res) if err != nil { return nil, err } return res.Commands, nil } func (s *Server) Ping(gameKey string) (io.ReadCloser, error) { var err error type Request struct { Author string `json:"author"` GameKey string `json:"gameKey"` Action string `json:"action"` Timestamp string `json:"timestamp"` } b := new(bytes.Buffer) err = json.NewEncoder(b).Encode(&Request{ Author: s.Author(), Action: "ping", GameKey: gameKey, Timestamp: unixMillisTimestamp(), }) if err != nil { return nil, errors.Errorf("malformed message: %s", err) } bsReq, err := signing.Sign(s.teamKeyPair.Private, s.ApiKey, b.Bytes()) var resp *http.Response url := fmt.Sprintf("%s/Games/%s", s.Base, gameKey) resp, err = http.Post(url, "text/plain", bytes.NewReader(bsReq)) if err != nil { return nil, err } if resp.StatusCode < 200 || resp.StatusCode >= 299 { buf := new(bytes.Buffer) buf.ReadFrom(resp.Body) return nil, errors.Errorf("%s: %s", resp.Status, buf.String()) } return resp.Body, nil } func (s *Server) Pong(gameKey string, payload string, botIds []uint32) error { type Request struct { Author string `json:"author"` GameKey string `json:"gameKey"` Action string `json:"action"` Payload string `json:"payload"` BotIds []uint32 `json:"botIds"` Timestamp string `json:"timestamp"` } var err error reqPath := fmt.Sprintf("/Games/%s", gameKey) err = s.SignedRequest(reqPath, Request{ Author: s.Author(), GameKey: gameKey, Action: "pong", BotIds: botIds, Payload: payload, Timestamp: unixMillisTimestamp(), }, nil) if err != nil { return err } return nil } func unixMillisTimestamp() string { return strconv.FormatInt(time.Now().UnixNano() / 1000000, 10) }
package main import "fmt" /** 133. 克隆图 给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。 图中的每个节点都包含它的值 `val(int)` 和其邻居的列表`(list[Node])`。 ``` class Node { public int val; public List<Node> neighbors; } ``` 测试用例格式: 简单起见,每个节点的值都和它的索引相同。例如,第一个节点值为 1(val = 1),第二个节点值为 2(val = 2),以此类推。该图在测试用例中使用邻接列表表示。 邻接列表 是用于表示有限图的无序列表的集合。每个列表都描述了图中节点的邻居集。 给定节点将始终是图中的第一个节点(值为 1)。你必须将 给定节点的拷贝 作为对克隆图的引用返回。 示例1: ``` 输入:adjList = [[2,4],[1,3],[2,4],[1,3]] 输出:[[2,4],[1,3],[2,4],[1,3]] 解释: 图中有 4 个节点。 节点 1 的值是 1,它有两个邻居:节点 2 和 4 。 节点 2 的值是 2,它有两个邻居:节点 1 和 3 。 节点 3 的值是 3,它有两个邻居:节点 2 和 4 。 节点 4 的值是 4,它有两个邻居:节点 1 和 3 。 ``` 示例2: ``` 输入:adjList = [[]] 输出:[[]] 解释:输入包含一个空列表。该图仅仅只有一个值为 1 的节点,它没有任何邻居。 ``` 示例3: ``` 输入:adjList = [] 输出:[] 解释:这个图是空的,它不含任何节点。 ``` 示例4: ``` 输入:adjList = [[2],[1]] 输出:[[2],[1]] ``` 提示: - `节点数不超过 100 。` - `每个节点值 Node.val 都是唯一的,1 <= Node.val <= 100。` - `无向图是一个简单图,这意味着图中没有重复的边,也没有自环。` - `由于图是无向的,如果节点 p 是节点 q 的邻居,那么节点 q 也必须是节点 p 的邻居。` - `图是连通图,你可以从给定节点访问到所有节点。` */ /** 今天的题实在是不想做 ~~~ ERROR */ /** * Definition for a Node. * type Node struct { * Val int * Neighbors []*Node * } */ func CloneGraph(node *Node) *Node { if node == nil { return nil } fmt.Println(node.Val) newNode := Node{Val: node.Val, Neighbors: []*Node{}} return &newNode } type Node struct { Val int Neighbors []*Node }
package main import ( "fmt" "io" "log" "net/http" "net/url" "os" "strings" "time" "github.com/PuerkitoBio/goquery" "github.com/gorilla/feeds" ) func main() { for _, rawUri := range os.Args[1:] { b, err := readerFromURI(rawUri) if err != nil { log.Fatal(err) } defer b.Close() f, err := extractFeed(rawUri, b) if err != nil { log.Fatal(err) } payload, err := f.ToAtom() if err != nil { log.Fatal(err) } fmt.Print(payload) } } func readerFromURI(rawUri string) (io.ReadCloser, error) { uri, err := url.ParseRequestURI(rawUri) if err != nil { return nil, err } switch uri.Scheme { case "http": fallthrough case "https": req, err := http.NewRequest("GET", rawUri, nil) if err != nil { return nil, err } req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7") req.Header.Set("Accept-Language", "de-DE,de;q=0.9,en-DE;q=0.8,en;q=0.7,en-US;q=0.6") req.Header.Set("Cache-Control", "no-cache") req.Header.Set("Connection", "keep-alive") req.Header.Set("Dnt", "1") req.Header.Set("Pragma", "no-cache") req.Header.Set("Sec-Fetch-Dest", "document") req.Header.Set("Sec-Fetch-Mode", "navigate") req.Header.Set("Sec-Fetch-Site", "none") req.Header.Set("Sec-Fetch-User", "?1") req.Header.Set("Upgrade-Insecure-Requests", "1") req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36") req.Header.Set("Sec-Ch-Ua", "\"Google Chrome\";v=\"111\", \"Not(A:Brand\";v=\"8\", \"Chromium\";v=\"111\"") req.Header.Set("Sec-Ch-Ua-Mobile", "?0") req.Header.Set("Sec-Ch-Ua-Platform", "\"macOS\"") r, err := http.DefaultClient.Do(req) if err != nil { return nil, err } if r.StatusCode >= 299 { return nil, fmt.Errorf("can't handle status %q (%q) for %s", r.StatusCode, r.Status, uri) } return r.Body, err case "file": var fname string if uri.Host != "" && uri.Host != "localhost" { fname = uri.Host } else { fname = uri.Path } return os.Open(fname) } return nil, fmt.Errorf("can not handle scheme: %q", uri.Scheme) } func extractFeed(rawUri string, body io.Reader) (*feeds.Feed, error) { now := time.Now() feed := &feeds.Feed{ Title: "Laufende Fusionskontrollverfahren", Link: &feeds.Link{Href: rawUri}, Description: `Hier finden Sie eine Liste der laufenden Fusionskontrollverfahren. Das Prüfverfahren beginnt nach dem Eingang der vollständigen Anmeldeunterlagen beim Bundeskartellamt. Die Behörde hat zunächst einen Monat Zeit, um den Zusammenschluss zu prüfen (sog. "erste Phase"). Erweist sich das Fusionsvorhaben als unproblematisch, gibt die Beschlussabteilung den Zusammenschluss vor Ablauf der Monatsfrist formlos frei. Hält die Beschlussabteilung dagegen eine weitere Prüfung für erforderlich, wird ein förmliches Hauptprüfverfahren eingeleitet (sog. "zweite Phase") und die Frist für die Prüfung des Vorhabens verlängert. Das Bundeskartellamt muss bei Durchführung eines Hauptprüfverfahrens innerhalb von vier Monaten ab Eingang der vollständigen Anmeldung entscheiden. Die Liste der Hauptprüfverfahren finden Sie hier. Bei den mit * gekennzeichneten Verfahren wurde der Zusammenschluss bereits vollzogen. Hier handelt es sich um eine nachträgliche Prüfung im fristungebundenen Verfahren nach § 41 Abs. 3 GWB. Die Liste erhebt keinen Anspruch auf Vollständigkeit. `, Author: &feeds.Author{Name: "Martin Treusch von Buttlar", Email: "fusion2feed@m.t17r.de"}, Created: now, } feed.Items = make([]*feeds.Item, 0, 20) doc, err := goquery.NewDocumentFromReader(body) if err != nil { return nil, err } doc.Find("table.csvTable tr").Each(func(i int, row *goquery.Selection) { if err != nil { return } /* if i < 50 || len(feed.Items) > 3 { return } */ data := make([]string, 0, 6) row.Find("td").Each(func(_ int, cell *goquery.Selection) { raw := cell.Text() raw = strings.ReplaceAll(raw, "\u00ad", "") data = append(data, raw) }) if len(data) == 0 { return } var created time.Time created, err = time.ParseInLocation("02.01.2006", data[0], time.Local) if err != nil { return } //fmt.Printf("%#v\n", data) item := &feeds.Item{ Title: data[2], Link: &feeds.Link{Href: fmt.Sprintf("%s#%s", rawUri, data[1])}, Id: data[1], Description: fmt.Sprintf("%s<br>%s<br>%s", data[2], data[3], data[4]), Created: created, } feed.Items = append(feed.Items, item) }) return feed, err }
package core import ( "fmt" "github.com/textileio/go-textile/pb" ) func (t *Textile) Likes(target string) (*pb.LikeList, error) { likes := make([]*pb.Like, 0) query := fmt.Sprintf("type=%d and target='%s'", pb.Block_LIKE, target) for _, block := range t.Blocks("", -1, query).Items { info, err := t.like(block, feedItemOpts{annotations: true}) if err != nil { continue } likes = append(likes, info) } return &pb.LikeList{Items: likes}, nil } func (t *Textile) Like(blockId string) (*pb.Like, error) { block, err := t.Block(blockId) if err != nil { return nil, err } return t.like(block, feedItemOpts{annotations: true}) } func (t *Textile) like(block *pb.Block, opts feedItemOpts) (*pb.Like, error) { if block.Type != pb.Block_LIKE { return nil, ErrBlockWrongType } item := &pb.Like{ Id: block.Id, Date: block.Date, User: t.PeerUser(block.Author), } if opts.target != nil { item.Target = opts.target } else if !opts.annotations { target, err := t.feedItem(t.datastore.Blocks().Get(block.Target), feedItemOpts{}) if err != nil { return nil, err } item.Target = target } return item, nil }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/6/16 10:04 上午 # @File : lt_二进制_位1的个数.go # @Description : # @Attention : */ package v2 func hammingWeight(num uint32) int { count := 0 for num > 0 { count++ num = num & (num - 1) } return count }
//这是一个账号密码加密解密的例子 //程序员开发程序的基本礼貌,如果数据被泄露了,密码也不应该能被还原 //date:2018-06-12 //此时的感想:不想加班,我喜欢写文档,但是不想做需要用office的工作 //需要安装bcyrpt库 //go get golang.org/x/crypto/bcrypt package main import ( "fmt" "golang.org/x/crypto/bcrypt" ) func main() { passwddok := "admin" //正确的密码 passwdERR := "adminerr" //错误的密码 hash, err := bcrypt.GenerateFromPassword([]byte(passwddok), bcrypt.DefaultCost) //编码 checkErr(err) encodePW := string(hash) //编码后的密码,每次生成都是不同的,但是保存任意一份即可 err = bcrypt.CompareHashAndPassword([]byte(encodePW), []byte(passwddok)) checkErr(err) fmt.Println("密码正确") err = bcrypt.CompareHashAndPassword([]byte(encodePW), []byte(passwdERR)) checkErr(err) } func checkErr(err error) { if err != nil { fmt.Println(err) } }
package main import ( "fmt" "net/http" "io/ioutil" ) func headers(w http.ResponseWriter, req *http.Request) { fmt.Printf("got headers:\n") w.WriteHeader(500) fmt.Fprintf(w, "got headers:\n") for name, headers := range req.Header { for _, h := range headers { fmt.Printf("%v: %v\n", name, h) fmt.Fprintf(w, "%v: %v\n", name, h) } } body, _ := ioutil.ReadAll(req.Body) fmt.Printf("got body: %s\n", body) fmt.Fprintf(w, "body: %s\n", body) } func main() { http.HandleFunc("/", headers) http.ListenAndServe(":8090", nil) }
package main import ( "net/http" "net/http/httptest" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Raindrops", func() { Describe("Print Pling Plang Plong based on whether the number passed in the URL is divisible by 3, 5 or 7", func() { Context("Print Pling if number is divisible by 3", func() { It("Should return Pling", func() { req, _ := http.NewRequest("GET", "/3", nil) rr := httptest.NewRecorder() handler := http.HandlerFunc(RainDrops) handler.ServeHTTP(rr, req) Expect(rr.Body.String()).To(Equal("Pling")) }) }) Context("Print Plang if number is divisible by 5", func() { It("Should return Plang", func() { req, _ := http.NewRequest("GET", "/5", nil) rr := httptest.NewRecorder() handler := http.HandlerFunc(RainDrops) handler.ServeHTTP(rr, req) Expect(rr.Body.String()).To(Equal("Plang")) }) }) Context("Print Plong if number is divisible by 7", func() { It("Should return Plong", func() { req, _ := http.NewRequest("GET", "/7", nil) rr := httptest.NewRecorder() handler := http.HandlerFunc(RainDrops) handler.ServeHTTP(rr, req) Expect(rr.Body.String()).To(Equal("Plong")) }) }) Context("Print PlingPlangPlong if number is divisible by 3, 5 and 7", func() { It("Should return PlingPlangPlong", func() { req, _ := http.NewRequest("GET", "/105", nil) rr := httptest.NewRecorder() handler := http.HandlerFunc(RainDrops) handler.ServeHTTP(rr, req) Expect(rr.Body.String()).To(Equal("PlingPlangPlong")) }) }) Context("Print PlingPlang if number is divisible by 3 and 5", func() { It("Should return PlingPlang", func() { req, _ := http.NewRequest("GET", "/15", nil) rr := httptest.NewRecorder() handler := http.HandlerFunc(RainDrops) handler.ServeHTTP(rr, req) Expect(rr.Body.String()).To(Equal("PlingPlang")) }) }) Context("Print PlingPlong if number is divisible by 3 and 7", func() { It("Should return PlingPlong", func() { req, _ := http.NewRequest("GET", "/21", nil) rr := httptest.NewRecorder() handler := http.HandlerFunc(RainDrops) handler.ServeHTTP(rr, req) Expect(rr.Body.String()).To(Equal("PlingPlong")) }) }) Context("Print PlangPlong if number is divisible by 5 and 7", func() { It("Should return PlangPlong", func() { req, _ := http.NewRequest("GET", "/35", nil) rr := httptest.NewRecorder() handler := http.HandlerFunc(RainDrops) handler.ServeHTTP(rr, req) Expect(rr.Body.String()).To(Equal("PlangPlong")) }) }) }) })
package email import ( "bytes" "errors" "fmt" "net/smtp" "github.com/ch3lo/overlord/logger" "github.com/ch3lo/overlord/notification" "github.com/ch3lo/overlord/notification/factory" ) const notificationID = "email" func init() { factory.Register(notificationID, &emailCreator{}) } // emailCreator implementa la interfaz factory.NotificationFactory type emailCreator struct{} func (factory *emailCreator) Create(id string, params map[string]interface{}) (notification.Notification, error) { return NewFromParameters(id, params) } // EmailParameters encapsula los parametros de configuracion de Email type parameters struct { id string from string to string subject string smtp string user string password string } // NewFromParameters construye un EmailNotification a partir de un mapeo de parámetros func NewFromParameters(id string, params map[string]interface{}) (*Notification, error) { smtp, ok := params["smtp"] if !ok || fmt.Sprint(smtp) == "" { return nil, errors.New("Parametro smtp no existe") } from, ok := params["from"] if !ok || fmt.Sprint(from) == "" { return nil, errors.New("Parametro de origen (from) no existe") } to, ok := params["to"] if !ok || fmt.Sprint(to) == "" { return nil, errors.New("Parametro de destinatario (to) no existe") } // TODO implementacion con autenticacion y subject /* subject := "" if subjectTmp, ok := parameters["subject"]; ok { subject = fmt.Sprint(subjectTmp) }*/ p := parameters{ id: id, smtp: fmt.Sprint(smtp), from: fmt.Sprint(from), to: fmt.Sprint(to), } return New(p) } // New construye un nuevo EmailNotification func New(params parameters) (*Notification, error) { email := &Notification{ id: params.id, address: params.smtp, from: params.from, to: params.to, } return email, nil } // Notification es una implementacion de notification.Notification // Permite la comunicacion via email type Notification struct { id string address string from string to string } // ID retorna el identificador de este notificador func (n *Notification) ID() string { return n.id } // Notify notifica via email al destinatario func (n *Notification) Notify(data []byte) error { logger.Instance().Infoln("Notificando via email") logger.Instance().Debugf("Data: %s", string(data)) // Connect to the remote SMTP server. c, err := smtp.Dial(n.address) if err != nil { return err } defer c.Close() // Set the sender and recipient. c.Mail(n.from) c.Rcpt(n.to) // Send the email body. wc, err := c.Data() if err != nil { return err } defer wc.Close() buf := bytes.NewBuffer(data) //buf := bytes.NewBufferString("This is the email body.") if _, err = buf.WriteTo(wc); err != nil { return err } return nil }
package main import ( "bufio" "fmt" "net" "net/http" ) type client struct { connection net.Conn reader *bufio.Reader writer *bufio.Writer clientNum int port int playerInfo connectionPlayerInfo } const debug = false const NUMPLAYERS = 2 func main() { fmt.Println("starting game service!") initPortService() portHttpController := makePortHttpController() matchMakingFunction := startMatchmakingController() go listenForConnections(portHttpController.connPasser,matchMakingFunction) //start listening for http startHttpServer(portHttpController) } func listenForConnections(connPasser <-chan clientConnection, matchMakingFunction func(connection *playerConnection)) { fmt.Println("listening for connections") currentClientNumber := 0 for conn := range connPasser { fmt.Println("starting handling for a connection") client := client{} client.connection = conn.connection client.reader = bufio.NewReader(conn.connection) client.writer = bufio.NewWriter(conn.connection) client.clientNum = currentClientNumber client.port = conn.port client.playerInfo = conn.playerInfo currentClientNumber++ playerConnection := MakePlayerConnection(client,nil) matchMakingFunction(playerConnection) } } func startHttpServer(portHttpController portHttpController) { http.HandleFunc("/", portHttpController.handlePortRequested) err := http.ListenAndServe(":6000", nil) if err != nil { fmt.Println(err.Error()) } }
package routes import ( "context" "encoding/json" "log" "net/http" "push_article/pkg/token" "firebase.google.com/go/v4/messaging" "github.com/go-chi/chi" ) type NotificationService struct { *messaging.Client token.Storage } func (ns *NotificationService) sendNotification(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() var request struct { UserID uint64 `json:"user_id"` Data map[string]string `json:"data"` Notification *messaging.Notification `json:"notification"` Android *messaging.AndroidConfig `json:"android"` Webpush *messaging.WebpushConfig `json:"webpush"` APNS *messaging.APNSConfig `json:"apns"` } err := json.NewDecoder(r.Body).Decode(&request) if err != nil { http.Error(w, "bad json: "+err.Error(), http.StatusBadRequest) return } tokens, err := ns.UserTokens(r.Context(), request.UserID) if err != nil { http.Error(w, "user tokens get failed: "+err.Error(), http.StatusInternalServerError) return } tokenStrings := make([]string, len(tokens)) for i, t := range tokens { tokenStrings[i] = t.Token } resp, err := ns.SendMulticast(r.Context(), &messaging.MulticastMessage{ Tokens: tokenStrings, Data: request.Data, Notification: request.Notification, Android: request.Android, Webpush: request.Webpush, APNS: request.APNS, }) if err != nil { http.Error(w, "send notifications failed: "+err.Error(), http.StatusInternalServerError) return } go func() { // we should clean up unregistered tokens var unregisteredTokens []string for i, item := range resp.Responses { if messaging.IsRegistrationTokenNotRegistered(item.Error) { unregisteredTokens = append(unregisteredTokens, tokenStrings[i]) } } log.Printf("Delete unregistered tokens: %+v", unregisteredTokens) err := ns.DeleteTokens(context.Background(), unregisteredTokens) if err != nil { log.Printf("Delete unregistered tokens failed: %v", err) } }() } func (ns *NotificationService) confirm(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() log.Printf("Push %s confirmed", chi.URLParam(r, "id")) } func (ns *NotificationService) AddToRouter(r chi.Router) { r.Post("/", ns.sendNotification) r.Post("/{id}/confirm", ns.confirm) }
package 模拟 // ------------------- 方法1: 使用栈 ------------------- func minAddToMakeValid(S string) int { stackStoringLeftParentheses := NewMyStack() minCountOfAdding := 0 for i := 0; i < len(S); i++ { if S[i] == '(' { stackStoringLeftParentheses.Push(S[i]) continue } if stackStoringLeftParentheses.IsEmpty() { minCountOfAdding++ continue } stackStoringLeftParentheses.Pop() } minCountOfAdding += stackStoringLeftParentheses.GetSize() return minCountOfAdding } // ------------------------- MyStack ------------------------- type MyStack struct { data []byte } func NewMyStack() *MyStack { return &MyStack{} } func (ms *MyStack) Push(val byte) { ms.data = append(ms.data, val) } func (ms *MyStack) Pop() byte { top := ms.data[ms.GetSize()-1] ms.data = ms.data[:ms.GetSize()-1] return top } func (ms *MyStack) GetTop() byte { return ms.data[ms.GetSize()-1] } func (ms *MyStack) IsEmpty() bool { return ms.GetSize() == 0 } func (ms *MyStack) GetSize() int { return len(ms.data) } // ------------------- 方法2: 计次 ------------------- func minAddToMakeValid(S string) int { countOfLeftParentheses := 0 minCountOfAdding := 0 for i := 0; i < len(S); i++ { if S[i] == '(' { countOfLeftParentheses++ continue } if countOfLeftParentheses == 0 { minCountOfAdding++ continue } countOfLeftParentheses-- } minCountOfAdding += countOfLeftParentheses return minCountOfAdding } /* 题目链接: https://leetcode-cn.com/problems/minimum-add-to-make-parentheses-valid/comments/ 总结: 1. 其实栈是可以不要的,只需要记录当前拥有多少左括号就可以了。 */
package e2e import ( "path/filepath" "testing" "time" "github.com/sensu/sensu-go/testing/testutil" "github.com/sensu/sensu-go/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestRoundRobinScheduling(t *testing.T) { t.Parallel() // Create two backends backendA, cleanup := newBackend(t) defer cleanup() sensuctlA, cleanup := newSensuCtl(backendA.HTTPURL, "default", "default", "admin", "P@ssw0rd!") defer cleanup() // TODO(echlebek): make this test work with multiple backends //backendB, cleanup := newBackend(t) //defer cleanup() sensuctlB, cleanup := newSensuCtl(backendA.HTTPURL, "default", "default", "admin", "P@ssw0rd!") defer cleanup() // Two agents belong to backend A, one belongs to backend B agentCfgA := agentConfig{ ID: "agentA", BackendURLs: []string{backendA.WSURL}, } agentCfgB := agentConfig{ ID: "agentB", BackendURLs: []string{backendA.WSURL}, } agentCfgC := agentConfig{ ID: "agentC", BackendURLs: []string{backendA.WSURL}, } agentA, cleanup := newAgent(agentCfgA, sensuctlA, t) defer cleanup() agentB, cleanup := newAgent(agentCfgB, sensuctlA, t) defer cleanup() agentC, cleanup := newAgent(agentCfgC, sensuctlB, t) defer cleanup() // Create an authenticated HTTP Sensu client. newSensuClient is deprecated but // sensuctl does not currently support objects updates with flag parameters clientA := newSensuClient(backendA.HTTPURL) clientB := newSensuClient(backendA.HTTPURL) clientC := newSensuClient(backendA.HTTPURL) // Create a check that publish check requests check := types.FixtureCheckConfig("TestCheckScheduling") check.Publish = true check.Interval = 1 check.Subscriptions = []string{"test"} check.RoundRobin = true check.Command = testutil.CommandPath(filepath.Join(toolsDir, "true")) err := clientA.CreateCheck(check) require.NoError(t, err) check, err = clientA.FetchCheck(check.Name) require.NoError(t, err) // Allow checks to be published time.Sleep(20 * time.Second) eventA, err := clientA.FetchEvent(agentA.ID, check.Name) require.NoError(t, err) require.NotNil(t, eventA) eventB, err := clientB.FetchEvent(agentB.ID, check.Name) require.NoError(t, err) require.NotNil(t, eventB) eventC, err := clientC.FetchEvent(agentC.ID, check.Name) require.NoError(t, err) require.NotNil(t, eventC) histories := append(eventA.Check.History, eventB.Check.History...) histories = append(histories, eventC.Check.History...) executed := make(map[int64]struct{}) for _, h := range histories { assert.Equal(t, uint32(0), h.Status) e := h.Executed executed[e] = struct{}{} } // Ensure that all executed checks have been executed at a separate time. // TODO(echlebek): do this with unique identifiers per check request msg. assert.Equal(t, len(histories), len(executed)) }
// package main // // import "fmt" // // func main() { // var vector struct { // X int // Y int // } // // vector.X = 2 // vector.Y = 5 // fmt.Println(vector) // {2 5} // } // package main // // import "fmt" // // type Vector struct { // X int // Y int // } // // func main() { // var v Vector // // v.X = 2 // v.Y = 5 // fmt.Println(v) // } // package main // // import "fmt" // // type Vector struct { // X int // Y int // } // // func main() { // v := Vector{X: 2, Y: 5} // fmt.Println(v) // {2 5} // } // package main // // import "fmt" // // func main() { // DisplayHello() // } // // func DisplayHello() { // fmt.Println("Hello!") // } // package main // // import "fmt" // // func main() { // DisplaySum(2, 5) // 7が表示される // } // // func DisplaySum(left int, right int) { // fmt.Println(left + right) // } // package main // // import "fmt" // // func main() { // DisplaySumAll(2, 5, 8, 11) // 26が表示される // } // // func DisplaySumAll(values ...int) { // sum := 0 // for _, value := range values { // sum += value // } // fmt.Println(sum) // } // package main // // import "fmt" // // func main() { // fmt.Println(Sum(2, 5)) // 7が表示される // } // // func Sum(left int, right int) int { // return left + right // } // package main // // import "fmt" // // func main() { // result, remainder := Div(19, 4) // fmt.Printf("19を4で割ると%dあまり%dです。\n", result, remainder) // } // // func Div(left int, right int) (int, int) { // 複数指定の場合は戻り値を丸括弧で囲む // return left / right, left % right // } // package main // // import "fmt" // // type LoopNum int // // func main() { // var three LoopNum = 3 // three.TimesDisplay("Hello") // 「Hello」と3回表示される // } // // func (n LoopNum) TimesDisplay(s string) { // for i := 0; i < int(n); i++ { // fmt.Println(s) // } // } // package main // // import "fmt" // // type SavingBox struct { // money int // } // // func NewBox() *SavingBox { // return new(SavingBox) // } // // func (s *SavingBox) Income(amount int) { // s.money += amount // } // // func (s *SavingBox) Break() int { // lastMoney := s.money // s.money = 0 // return lastMoney // } // // func main() { // box := NewBox() // box.Income(100) // box.Income(200) // box.Income(500) // // fmt.Printf("貯金箱を壊したら%d円出てきました。\n", box.Break()) // } // package main // // import "fmt" // // func main() { // defer fmt.Println("A") // fmt.Println("B") // } // package main // // import "fmt" // // func main() { // defer fmt.Println("A") // defer fmt.Println("B") // defer fmt.Println("C") // fmt.Println("D") // } // package main // // import ( // "fmt" // "os" // ) // // func main() { // defer fmt.Println("A") // fmt.Println("B") // os.Exit(0) // } // package main // // import "fmt" // // type Animal interface { // Cry() // } // // type Dog struct {} // func (d *Dog) Cry() { // fmt.Println("わんわん") // } // // type Cat struct {} // func (c *Cat) Cry() { // fmt.Println("にゃーにゃー"); // } // // func MakeAnimalCry(a Animal) { // fmt.Println("鳴け!"); // a.Cry(); // } // // func main() { // dog := new(Dog) // cat := new(Cat) // MakeAnimalCry(dog) // MakeAnimalCry(cat) // } // package main // // import "fmt" // // type Animal interface { // Cry() // } // // type Dog struct {} // func (d *Dog) Cry() { // fmt.Println("わんわん") // } // // type Cat struct {} // func (c *Cat) Cry() { // fmt.Println("にゃーにゃー"); // } // // func MakeSomeoneCry(someone interface{}) { // fmt.Println("鳴け!"); // a, ok := someone.(Animal) // fmt.Println(a); // if !ok { // fmt.Println("動物では無いので鳴けません。") // return // } // a.Cry() // } // // func main() { // dog := new(Dog) // cat := new(Cat) // MakeSomeoneCry(dog) // MakeSomeoneCry(cat) // } // package main // // import ( // "fmt" // ) // // func main() { // // 配列の宣言 // var month [12]string // month[0] = "January" // month[1] = "February" // month[2] = "March" // month[3] = "April" // month[4] = "May" // month[5] = "June" // month[6] = "July" // month[7] = "Autust" // month[8] = "September" // month[9] = "October" // month[10] = "Nobember" // month[11] = "December" // // // 配列の長さの回数、ループして値を表示します。 // for i := 0; i < len(month); i++ { // fmt.Printf("%d月 = %s\n", i+1, month[i]) // } // } // package main // // import ( // "fmt" // ) // // func main() { // // スライスの元となる配列を作成 // num := [5]int{1, 2, 3, 4, 5} // // スライス型変数の宣言 // var slice1 []int // // // 配列全体 // slice1 = num[:] // fmt.Println(slice1) // // // インデックス1〜4まで // slice2 := num[1:4] // fmt.Println(slice2) // // // インデックス4以降 // slice3 := num[4:] // fmt.Println(slice3) // // // インデックス4以前 // slice4 := num[:4] // fmt.Println(slice4) // } // package main // // import ( // "fmt" // ) // // func main() { // // スライスの元となる配列を作成 // num := [...]int{1, 2, 3, 4, 5} // // 配列をスライスとしてを関数に渡す // plusOne(num[:]) // // fmt.Println(num) // } // // // 要素内の数字すべてを+1 // func plusOne(vals []int) { // for i := 0; i < len(vals); i++ { // vals[i] += 1 // } // } package main import ( "fmt" ) func main() { // スライスの元となる配列を作成 num := [5]int{1, 2, 3, 4, 5} // 配列の一部をスライス slice1 := num[1:4] fmt.Println("slice1=", slice1) fmt.Println("len=", len(slice1)) fmt.Println("cap=", cap(slice1)) // スライスの一部をスライス slice2 := slice1[1:4] // 長さを超過した、キャパシティ最大値まで可能 fmt.Println("slice2=", slice2) fmt.Println("len=", len(slice2)) fmt.Println("cap=", cap(slice2)) }
package version import ( "fmt" "strings" ) type Info struct { Name string Tag string Commit string Branch string } // Version show version info func (i *Info) Version() string { parts := []string{i.Name, i.Tag, i.Branch, i.Commit} for k, v := range parts { if len(v) == 0 { parts[k] = "unknown" } } gitInfo := fmt.Sprintf("(git: %s %s)", parts[2], parts[3]) parts = append(parts[:2], gitInfo) return strings.Join(parts, " ") }
/* * Copyright @ 2020 - present Blackvisor Ltd. * * 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 cryptoutils import ( "github.com/netclave/common/storage" ) var PUBLIC_KEYS = "publickeys" var PUBLIC_KEYS_TEMP = "publickeysTemp" var PRIVATE_KEYS = "privatekeys" var LABEL_TO_IDENTIFICATOR_ID = "labeltoidentificatorid" var IDENTIFICATOR_TO_PUBLIC_KEY_LABELS = "identificatortopublickeylabels" var IDENTIFICATORS = "identificators" var IDENTIFICATOR_TO_IDENTIFICATOR = "identificatortoidentificator" var IDENTIFICATOR_CONFIRMATION_CODE = "identificatorscode" var IDENTIFICATOR_TO_IDENTITY_ID = "identificatortoidentity" var IDENTIFICATOR_TO_IDENTITY_ID_TEMP = "identificatortoidentitytemp" var IDENTITY_ID_TO_IDENTIFICATORS = "identityidtoidentificators" var IDENTIFICATOR_TYPE_IDENTITY_PROVIDER = "identityProvider" var IDENTIFICATOR_TYPE_GENERATOR = "generator" var IDENTIFICATOR_TYPE_WALLET = "wallet" var IDENTIFICATOR_TYPE_OPENER = "opener" var IDENTIFICATOR_TYPE_PROXY = "proxy" type CryptoStorage struct { Credentials map[string]string StorageType string } func (cs *CryptoStorage) createStorage() (*storage.GenericStorage, error) { return &storage.GenericStorage{ Credentials: cs.Credentials, StorageType: cs.StorageType, }, nil } func (cs *CryptoStorage) StorePublicKey(label string, pubKey string) error { storage, err := cs.createStorage() if err != nil { return err } return storage.SetKey(PUBLIC_KEYS, label, pubKey, 0) } func (cs *CryptoStorage) RetrievePublicKey(label string) (string, error) { storage, err := cs.createStorage() if err != nil { return "", err } return storage.GetKey(PUBLIC_KEYS, label) } func (cs *CryptoStorage) DeletePublicKey(label string) (int64, error) { storage, err := cs.createStorage() if err != nil { return -1, err } return storage.DelKey(PUBLIC_KEYS, label) } func (cs *CryptoStorage) StoreTempPublicKey(label string, pubKey string) error { storage, err := cs.createStorage() if err != nil { return err } return storage.SetKey(PUBLIC_KEYS_TEMP, label, pubKey, 0) } func (cs *CryptoStorage) RetrieveTempPublicKey(label string) (string, error) { storage, err := cs.createStorage() if err != nil { return "", err } return storage.GetKey(PUBLIC_KEYS_TEMP, label) } func (cs *CryptoStorage) DeleteTempPublicKey(label string) (int64, error) { storage, err := cs.createStorage() if err != nil { return 0, err } return storage.DelKey(PUBLIC_KEYS_TEMP, label) } func (cs *CryptoStorage) StorePrivateKey(label string, priKey string) error { storage, err := cs.createStorage() if err != nil { return err } return storage.SetKey(PRIVATE_KEYS, label, priKey, 0) } func (cs *CryptoStorage) RetrievePrivateKey(label string) (string, error) { storage, err := cs.createStorage() if err != nil { return "", err } return storage.GetKey(PRIVATE_KEYS, label) } func (cs *CryptoStorage) DeletePrivateKey(label string) (int64, error) { storage, err := cs.createStorage() if err != nil { return 0, err } return storage.DelKey(PRIVATE_KEYS, label) } func (cs *CryptoStorage) SetIdentificatorByLabel(label string, identificatorID string) error { storage, err := cs.createStorage() if err != nil { return err } return storage.SetKey(LABEL_TO_IDENTIFICATOR_ID, label, identificatorID, 0) } func (cs *CryptoStorage) GetIdentificatorByLabel(label string) (string, error) { storage, err := cs.createStorage() if err != nil { return "", err } return storage.GetKey(LABEL_TO_IDENTIFICATOR_ID, label) } func (cs *CryptoStorage) DeleteIdentificatorByLabel(label string) (int64, error) { storage, err := cs.createStorage() if err != nil { return 0, err } return storage.DelKey(LABEL_TO_IDENTIFICATOR_ID, label) } type Identificator struct { IdentificatorID string IdentificatorType string IdentificatorURL string IdentificatorName string } func (cs *CryptoStorage) AddIdentificator(identificator *Identificator) error { storage, err := cs.createStorage() if err != nil { return err } return storage.AddToMap(IDENTIFICATORS, "", identificator.IdentificatorID, *identificator) } func (cs *CryptoStorage) DeleteIdentificator(identificatorID string) error { storage, err := cs.createStorage() if err != nil { return err } return storage.DelFromMap(IDENTIFICATORS, "", identificatorID) } func (cs *CryptoStorage) GetIdentificators() (map[string]*Identificator, error) { storage, err := cs.createStorage() if err != nil { return nil, err } var result map[string]*Identificator err = storage.GetMap(IDENTIFICATORS, "", &result) if err != nil { return nil, err } return result, nil } func (cs *CryptoStorage) AddPublicKeyLabelToIdentificator(identificatorID string, label string) error { storage, err := cs.createStorage() if err != nil { return err } return storage.AddToMap(IDENTIFICATOR_TO_PUBLIC_KEY_LABELS, identificatorID, label, label) } func (cs *CryptoStorage) DelPublicKeyLabelToIdentificator(identificatorID string, label string) error { storage, err := cs.createStorage() if err != nil { return err } return storage.DelFromMap(IDENTIFICATOR_TO_PUBLIC_KEY_LABELS, identificatorID, label) } func (cs *CryptoStorage) GetPublicKeyLabelsForIdentificator(identificatorID string) (map[string]string, error) { storage, err := cs.createStorage() if err != nil { return nil, err } var labels map[string]*string err = storage.GetMap(IDENTIFICATOR_TO_PUBLIC_KEY_LABELS, identificatorID, &labels) if err != nil { return nil, err } result := make(map[string]string) for key, value := range labels { result[key] = *value } return result, nil } func (cs *CryptoStorage) AddIdentificatorToIdentificator(identificator1 *Identificator, identificator2 *Identificator) error { storage, err := cs.createStorage() if err != nil { return err } return storage.AddToMap(IDENTIFICATOR_TO_IDENTIFICATOR, identificator1.IdentificatorID, identificator2.IdentificatorID, *identificator2) } func (cs *CryptoStorage) DelIdentificatorToIdentificator(identificator1 *Identificator, identificator2 *Identificator) error { storage, err := cs.createStorage() if err != nil { return err } return storage.DelFromMap(IDENTIFICATOR_TO_IDENTIFICATOR, identificator1.IdentificatorID, identificator2.IdentificatorID) } func (cs *CryptoStorage) GetIdentificatorToIdentificatorMap(identificator1 *Identificator, identificatorType string) (map[string]*Identificator, error) { storage, err := cs.createStorage() if err != nil { return nil, err } var result map[string]*Identificator err = storage.GetMap(IDENTIFICATOR_TO_IDENTIFICATOR, identificator1.IdentificatorID, &result) if err != nil { return nil, err } filteredMap := map[string]*Identificator{} for key, value := range result { if value.IdentificatorType == identificatorType { filteredMap[key] = value } } return filteredMap, nil } func (cs *CryptoStorage) SetIdentityIDForIdentificator(identificatorID string, identityID string) error { storage, err := cs.createStorage() if err != nil { return err } return storage.SetKey(IDENTIFICATOR_TO_IDENTITY_ID, identificatorID, identityID, 0) } func (cs *CryptoStorage) GetIdentityIDForIdentificator(identificatorID string) (string, error) { storage, err := cs.createStorage() if err != nil { return "", err } return storage.GetKey(IDENTIFICATOR_TO_IDENTITY_ID, identificatorID) } func (cs *CryptoStorage) DelIdentityIDForIdentificator(identificatorID string) (int64, error) { storage, err := cs.createStorage() if err != nil { return 0, err } return storage.DelKey(IDENTIFICATOR_TO_IDENTITY_ID, identificatorID) } func (cs *CryptoStorage) SetTempIdentityIDForIdentificator(identificatorID string, identityID string) error { storage, err := cs.createStorage() if err != nil { return err } return storage.SetKey(IDENTIFICATOR_TO_IDENTITY_ID_TEMP, identificatorID, identityID, 0) } func (cs *CryptoStorage) GetTempIdentityIDForIdentificator(identificatorID string) (string, error) { storage, err := cs.createStorage() if err != nil { return "", err } return storage.GetKey(IDENTIFICATOR_TO_IDENTITY_ID_TEMP, identificatorID) } func (cs *CryptoStorage) DelTempIdentityIDForIdentificator(identificatorID string) (int64, error) { storage, err := cs.createStorage() if err != nil { return 0, err } return storage.DelKey(IDENTIFICATOR_TO_IDENTITY_ID_TEMP, identificatorID) } func (cs *CryptoStorage) AddIdentificatorToIdentityID(identificatorID string, identityID string) error { storage, err := cs.createStorage() if err != nil { return err } return storage.AddToMap(IDENTITY_ID_TO_IDENTIFICATORS, identityID, identificatorID, identificatorID) } func (cs *CryptoStorage) DelIdentificatorFromIdentityID(identificatorID string, identityID string) error { storage, err := cs.createStorage() if err != nil { return err } return storage.DelFromMap(IDENTITY_ID_TO_IDENTIFICATORS, identityID, identificatorID) } func (cs *CryptoStorage) GetIdentificatorsByIdentityID(identityID string) (map[string]string, error) { storage, err := cs.createStorage() if err != nil { return nil, err } var tmp map[string]*string err = storage.GetMap(IDENTITY_ID_TO_IDENTIFICATORS, identityID, &tmp) if err != nil { return nil, err } result := make(map[string]string) for key, value := range tmp { result[key] = *value } return result, nil }
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package glide import ( "bytes" "io/ioutil" "log" "os" "path" "path/filepath" "github.com/golang/dep" "github.com/golang/dep/gps" "github.com/golang/dep/internal/fs" "github.com/golang/dep/internal/importers/base" "github.com/pkg/errors" "gopkg.in/yaml.v2" ) const glideYamlName = "glide.yaml" const glideLockName = "glide.lock" // Importer imports glide configuration into the dep configuration format. type Importer struct { *base.Importer glideConfig glideYaml glideLock glideLock lockFound bool } // NewImporter for glide. func NewImporter(logger *log.Logger, verbose bool, sm gps.SourceManager) *Importer { return &Importer{Importer: base.NewImporter(logger, verbose, sm)} } type glideYaml struct { Name string `yaml:"package"` Ignores []string `yaml:"ignore"` ExcludeDirs []string `yaml:"excludeDirs"` Imports []glidePackage `yaml:"import"` TestImports []glidePackage `yaml:"testImport"` } type glideLock struct { Imports []glideLockedPackage `yaml:"imports"` TestImports []glideLockedPackage `yaml:"testImports"` } type glidePackage struct { Name string `yaml:"package"` Reference string `yaml:"version"` // could contain a semver, tag or branch Repository string `yaml:"repo"` // Unsupported fields that we will warn if used Subpackages []string `yaml:"subpackages"` OS string `yaml:"os"` Arch string `yaml:"arch"` } type glideLockedPackage struct { Name string `yaml:"name"` Revision string `yaml:"version"` Repository string `yaml:"repo"` } // Name of the importer. func (g *Importer) Name() string { return "glide" } // HasDepMetadata checks if a directory contains config that the importer can handle. func (g *Importer) HasDepMetadata(dir string) bool { // Only require glide.yaml, the lock is optional y := filepath.Join(dir, glideYamlName) if _, err := os.Stat(y); err != nil { return false } return true } // Import the config found in the directory. func (g *Importer) Import(dir string, pr gps.ProjectRoot) (*dep.Manifest, *dep.Lock, error) { err := g.load(dir) if err != nil { return nil, nil, err } m, l := g.convert(pr) return m, l, nil } // load the glide configuration files. Failure to load `glide.yaml` is considered // unrecoverable and an error is returned for it. But if there is any error while trying // to load the lock file, only a warning is logged. func (g *Importer) load(projectDir string) error { g.Logger.Println("Detected glide configuration files...") y := filepath.Join(projectDir, glideYamlName) if g.Verbose { g.Logger.Printf(" Loading %s", y) } yb, err := ioutil.ReadFile(y) if err != nil { return errors.Wrapf(err, "unable to read %s", y) } err = yaml.Unmarshal(yb, &g.glideConfig) if err != nil { return errors.Wrapf(err, "unable to parse %s", y) } l := filepath.Join(projectDir, glideLockName) if exists, _ := fs.IsRegular(l); exists { if g.Verbose { g.Logger.Printf(" Loading %s", l) } lb, err := ioutil.ReadFile(l) if err != nil { g.Logger.Printf(" Warning: Ignoring lock file. Unable to read %s: %s\n", l, err) return nil } lock := glideLock{} err = yaml.Unmarshal(lb, &lock) if err != nil { g.Logger.Printf(" Warning: Ignoring lock file. Unable to parse %s: %s\n", l, err) return nil } g.lockFound = true g.glideLock = lock } return nil } // convert the glide configuration files into dep configuration files. func (g *Importer) convert(pr gps.ProjectRoot) (*dep.Manifest, *dep.Lock) { projectName := string(pr) task := bytes.NewBufferString("Converting from glide.yaml") if g.lockFound { task.WriteString(" and glide.lock") } task.WriteString("...") g.Logger.Println(task) numPkgs := len(g.glideConfig.Imports) + len(g.glideConfig.TestImports) + len(g.glideLock.Imports) + len(g.glideLock.TestImports) packages := make([]base.ImportedPackage, 0, numPkgs) // Constraints for _, pkg := range append(g.glideConfig.Imports, g.glideConfig.TestImports...) { // Validate if pkg.Name == "" { g.Logger.Println( " Warning: Skipping project. Invalid glide configuration, Name is required", ) continue } // Warn if g.Verbose { if pkg.OS != "" { g.Logger.Printf(" The %s package specified an os, but that isn't supported by dep yet, and will be ignored. See https://github.com/golang/dep/issues/291.\n", pkg.Name) } if pkg.Arch != "" { g.Logger.Printf(" The %s package specified an arch, but that isn't supported by dep yet, and will be ignored. See https://github.com/golang/dep/issues/291.\n", pkg.Name) } } ip := base.ImportedPackage{ Name: pkg.Name, Source: pkg.Repository, ConstraintHint: pkg.Reference, } packages = append(packages, ip) } // Locks for _, pkg := range append(g.glideLock.Imports, g.glideLock.TestImports...) { // Validate if pkg.Name == "" { g.Logger.Println(" Warning: Skipping project. Invalid glide lock, Name is required") continue } ip := base.ImportedPackage{ Name: pkg.Name, Source: pkg.Repository, LockHint: pkg.Revision, } packages = append(packages, ip) } g.ImportPackages(packages, false) // Ignores g.Manifest.Ignored = append(g.Manifest.Ignored, g.glideConfig.Ignores...) if len(g.glideConfig.ExcludeDirs) > 0 { if g.glideConfig.Name != "" && g.glideConfig.Name != projectName { g.Logger.Printf(" Glide thinks the package is '%s' but dep thinks it is '%s', using dep's value.\n", g.glideConfig.Name, projectName) } for _, dir := range g.glideConfig.ExcludeDirs { pkg := path.Join(projectName, dir) g.Manifest.Ignored = append(g.Manifest.Ignored, pkg) } } return g.Manifest, g.Lock }
package main import ( "fmt" _ "github.com/denisenkom/go-mssqldb" ) var ( /* BuildVersion, BuildDate, BuildCommitSha are filled in by the build script */ BuildVersion = "<<< filled in by build >>>" BuildDate = "<<< filled in by build >>>" BuildComment = "<<< filled in by build >>>" ) func main() { fmt.Printf("BuildVersion: %s BuildDate %s ButeComment: %s", BuildVersion, BuildDate, BuildComment) }
package schema import ( "time" "gopkg.in/mgo.v2/bson" ) type Device struct { Id bson.ObjectId `json:"id" bson:"_id,omitempty"` UserId bson.ObjectId `json:"user_id" bson:"user_id,omitempty"` CreatedAt time.Time `json:"created_at" bson:"created_at"` UpdatedAt time.Time `json:"updated_at" bson:"updated_at"` Errors Errors `json:"-" bson:"-"` }
package core import ( "context" "errors" "fmt" "time" "github.com/drand/drand/beacon" "github.com/drand/drand/ecies" "github.com/drand/drand/entropy" "github.com/drand/drand/key" "github.com/drand/drand/protobuf/drand" "google.golang.org/grpc/peer" ) // Setup is the public method to call during a DKG protocol. func (d *Drand) Setup(c context.Context, in *drand.SetupPacket) (*drand.Empty, error) { d.state.Lock() defer d.state.Unlock() if d.dkgDone { return nil, errors.New("drand: dkg finished already") } if d.dkg == nil { return nil, errors.New("drand: no dkg running") } d.dkg.Process(c, in.Dkg) return new(drand.Empty), nil } // Reshare is called when a resharing protocol is in progress func (d *Drand) Reshare(c context.Context, in *drand.ResharePacket) (*drand.Empty, error) { d.state.Lock() defer d.state.Unlock() if d.nextGroupHash == "" { return nil, fmt.Errorf("drand %s: can't reshare because InitReshare has not been called", d.priv.Public.Addr) } // check that we are resharing to the new group that we expect if in.GroupHash != d.nextGroupHash { return nil, errors.New("drand: can't reshare to new group: incompatible hashes") } if !d.nextFirstReceived && d.nextOldPresent { d.nextFirstReceived = true // go routine since StartDKG requires the global lock go d.StartDKG() } if d.dkg == nil { return nil, errors.New("drand: no dkg setup yet") } d.nextFirstReceived = true if in.Dkg != nil { // first packet from the "leader" contains a nil packet for // nodes that are in the old list that must broadcast their // deals. d.dkg.Process(c, in.Dkg) } return new(drand.Empty), nil } // NewBeacon methods receives a beacon generation requests and answers // with the partial signature from this drand node. func (d *Drand) NewBeacon(c context.Context, in *drand.BeaconRequest) (*drand.BeaconResponse, error) { d.state.Lock() defer d.state.Unlock() if d.beacon == nil { return nil, errors.New("drand: beacon not setup yet") } return d.beacon.ProcessBeacon(c, in) } // PublicRand returns a public random beacon according to the request. If the Round // field is 0, then it returns the last one generated. func (d *Drand) PublicRand(c context.Context, in *drand.PublicRandRequest) (*drand.PublicRandResponse, error) { d.state.Lock() defer d.state.Unlock() if d.beacon == nil { return nil, errors.New("drand: beacon generation not started yet") } var beacon *beacon.Beacon var err error if in.GetRound() == 0 { beacon, err = d.beaconStore.Last() } else { beacon, err = d.beaconStore.Get(in.GetRound()) } if err != nil { return nil, fmt.Errorf("can't retrieve beacon: %s", err) } peer, ok := peer.FromContext(c) if ok { d.log.With("module", "public").Info("public_rand", peer.Addr.String(), "round", beacon.Round) d.log.Info("public rand", peer.Addr.String(), "round", beacon.Round) } h := RandomnessHash() h.Write(beacon.GetSignature()) randomness := h.Sum(nil) return &drand.PublicRandResponse{ Previous: beacon.GetPreviousSig(), Round: beacon.Round, Signature: beacon.GetSignature(), Randomness: randomness, }, nil } // PrivateRand returns an ECIES encrypted random blob of 32 bytes from /dev/urandom func (d *Drand) PrivateRand(c context.Context, priv *drand.PrivateRandRequest) (*drand.PrivateRandResponse, error) { protoPoint := priv.GetRequest().GetEphemeral() point := key.KeyGroup.Point() if err := point.UnmarshalBinary(protoPoint); err != nil { return nil, err } msg, err := ecies.Decrypt(key.KeyGroup, ecies.DefaultHash, d.priv.Key, priv.GetRequest()) if err != nil { d.log.With("module", "public").Error("private", "invalid ECIES", "err", err.Error()) return nil, errors.New("invalid ECIES request") } clientKey := key.KeyGroup.Point() if err := clientKey.UnmarshalBinary(msg); err != nil { return nil, errors.New("invalid client key") } randomness, err := entropy.GetRandom(nil, 32) if err != nil { return nil, fmt.Errorf("error gathering randomness: %s", err) } else if len(randomness) != 32 { return nil, fmt.Errorf("error gathering randomness: expected 32 bytes, got %d", len(randomness)) } obj, err := ecies.Encrypt(key.KeyGroup, ecies.DefaultHash, clientKey, randomness[:]) return &drand.PrivateRandResponse{Response: obj}, err } // Home ... func (d *Drand) Home(c context.Context, in *drand.HomeRequest) (*drand.HomeResponse, error) { peer, ok := peer.FromContext(c) if ok { d.log.With("module", "public").Info("home", peer.Addr.String()) } return &drand.HomeResponse{ Status: fmt.Sprintf("drand up and running on %s", d.priv.Public.Address()), }, nil } // Group replies with the current group of this drand node in a TOML encoded // format func (d *Drand) Group(ctx context.Context, in *drand.GroupRequest) (*drand.GroupResponse, error) { d.state.Lock() defer d.state.Unlock() if d.group == nil { return nil, errors.New("drand: no dkg group setup yet") } gtoml := d.group.TOML().(*key.GroupTOML) var resp = new(drand.GroupResponse) resp.Nodes = make([]*drand.Node, len(gtoml.Nodes)) for i, n := range gtoml.Nodes { resp.Nodes[i] = &drand.Node{ Address: n.Address, Key: n.Key, TLS: n.TLS, } } resp.Threshold = uint32(gtoml.Threshold) // take the period in second -> ms. grouptoml already transforms it to toml ms := uint32(d.group.Period / time.Millisecond) resp.Period = ms if gtoml.PublicKey != nil { resp.Distkey = make([]string, len(gtoml.PublicKey.Coefficients)) copy(resp.Distkey, gtoml.PublicKey.Coefficients) } return resp, nil }
package main import ( "context" "fmt" "log" "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter13/firebase" ) func main() { ctx := context.Background() c, err := firebase.Authenticate(ctx, "collection") if err != nil { log.Fatalf("error initializing client: %v", err) } defer c.Close() if err := c.Set(ctx, "key", []string{"val1", "val2"}); err != nil { log.Fatalf(err.Error()) } res, err := c.Get(ctx, "key") if err != nil { log.Fatalf(err.Error()) } fmt.Println(res) if err := c.Set(ctx, "key2", []string{"val3", "val4"}); err != nil { log.Fatalf(err.Error()) } res, err = c.Get(ctx, "key2") if err != nil { log.Fatalf(err.Error()) } fmt.Println(res) }
package main import ( "github.com/gorilla/securecookie" "github.com/gorilla/sessions" "github.com/labstack/echo/v4" uuid "github.com/iris-contrib/go.uuid" ) // Session middleware facilitates HTTP session management backed by gorilla/sessions. // https://echo.labstack.com/middleware/session func main() { app := echo.New() storeKey := securecookie.GenerateRandomKey(32) store := sessions.NewCookieStore(storeKey) app.GET("/sessions", func(ctx echo.Context) error { session, _ := store.Get(ctx.Request(), "session") id, _ := uuid.NewV4() session.Values["ID"] = id.String() session.Values["name"] = "John Doe" if err := session.Save(ctx.Request(), ctx.Response()); err != nil { return ctx.String(500, err.Error()) } v := session.Values["name"] name, ok := v.(string) if !ok { return ctx.String(500, "server error") } return ctx.String(200, name) }) app.Start(":5000") }
/* This challenge is to take an alphabetical string as input and to apply the following conversion: The first of each type of character of the string must stay, and must be immediately followed by an integer representing how many of these characters were in the original string. Any repeating characters must be omitted. All inputs will be entirely lower-case letters (no spaces). Outputs must be ordered in the same way as the inputs (input hi must give output of h1i1, not i1h1) Examples Input: potato Output: p1o2t2a1 Input: pqwertyuiop Output: p2q1w1e1r1t1y1u1i1o1 Input: thisisanexample Output: t1h1i2s2a2n1e2x1m1p1l1 Input: oreganoesque Output: o2r1e3g1a1n1s1q1u1 Input: aaaaaaabaaaaaa Output: a13b1 Scoring This is code-golf. Shortest answer wins! */ package main import ( "bytes" "fmt" ) func main() { assert(compress("potato") == "p1o2t2a1") assert(compress("pqwertyuiop") == "p2q1w1e1r1t1y1u1i1o1") assert(compress("thisisanexample") == "t1h1i2s2a2n1e2x1m1p1l1") assert(compress("oreganoesque") == "o2r1e3g1a1n1s1q1u1") assert(compress("aaaaaaabaaaaaa") == "a13b1") } func assert(x bool) { if !x { panic("assertion failed") } } func compress(s string) string { m := make(map[rune]int) p := []rune{} for _, r := range s { if m[r]++; m[r] == 1 { p = append(p, r) } } w := new(bytes.Buffer) for _, r := range p { fmt.Fprintf(w, "%c%d", r, m[r]) } return w.String() }
package astiamqp import ( "encoding/json" "github.com/molotovtv/go-astilog" "github.com/pkg/errors" "github.com/streadway/amqp" ) // Producer represents a producer type Producer struct { channel func() *amqp.Channel configuration ConfigurationProducer } // AddProducer adds a producer func (a *AMQP) AddProducer(c ConfigurationProducer) (p *Producer, err error) { // Lock a.mp.Lock() defer a.mp.Unlock() // Create producer p = &Producer{ channel: func() *amqp.Channel { return a.channel }, configuration: c, } // Setup producer if err = a.setupProducer(p); err != nil { err = errors.Wrapf(err, "astiamqp: setting up producer %+v failed", c) return } // Append producer a.producers = append(a.producers, p) return } func (a *AMQP) setupProducer(p *Producer) (err error) { // Declare exchange if err = a.declareExchange(p.configuration.Exchange); err != nil { err = errors.Wrapf(err, "astiamqp: declaring exchange %+v failed", p.configuration.Exchange) return } return } // Produce produces a message on a routing key after json.Marshaling it func (p *Producer) Produce(msg interface{}, routingKey string) (err error) { // Marshal msg var b []byte if b, err = json.Marshal(msg); err != nil { err = errors.Wrapf(err, "astiamqp: marshaling msg %+v failed", msg) return } // Publish message if err = p.publishMessage(b, routingKey); err != nil { err = errors.Wrapf(err, "astiamqp: publishing msg %+v for routing key %s failed", msg, routingKey) return } return } func (p *Producer) publishMessage(msg []byte, routingKey string) (err error) { astilog.Debugf("astiamqp: publishing msg %s to exchange %s for routing key %s", msg, p.configuration.Exchange.Name, routingKey) if err = p.channel().Publish( p.configuration.Exchange.Name, // exchange routingKey, // routing key false, // mandatory false, // immediate amqp.Publishing{ ContentType: "application/json", Body: msg, }, ); err != nil { err = errors.Wrapf(err, "astiamqp: publishing msg %s to exchange %+v for routing key %s failed", msg, p.configuration.Exchange, routingKey) return } return }
package chatlog import ( "fmt" "os" "testing" ) func TestHandleChatItem(t *testing.T) { c := New(os.Getenv("VIDEO_ID")) err := c.HandleChat(func(renderer ChatRenderer) error { switch renderer.(type) { case *LiveChatViewerEngagementMessageRenderer: fmt.Println(renderer.ChatMessage()) return nil case *LiveChatTextMessageRenderer: fmt.Println(renderer.ChatMessage()) return nil case *LiveChatMembershipItemRenderer: fmt.Println(renderer.ChatMessage()) return nil case *LiveChatPaidMessageRenderer: fmt.Println(renderer.ChatMessage()) return nil case *LiveChatPlaceholderItemRenderer: fmt.Println(renderer.ChatMessage()) return nil default: return fmt.Errorf("unknown renderer type: %v", renderer) } }) if err != nil { t.Fatal(err) } }
// Copyright Amazon.com Inc. or its affiliates. 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. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file 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 runtime_test import ( "context" "testing" "github.com/stretchr/testify/require" "go.uber.org/zap/zapcore" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" k8sobj "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" k8srtschema "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/client" ctrlrtzap "sigs.k8s.io/controller-runtime/pkg/log/zap" ackv1alpha1 "github.com/aws-controllers-k8s/runtime/apis/core/v1alpha1" ackcompare "github.com/aws-controllers-k8s/runtime/pkg/compare" ackcfg "github.com/aws-controllers-k8s/runtime/pkg/config" ackmetrics "github.com/aws-controllers-k8s/runtime/pkg/metrics" ackrt "github.com/aws-controllers-k8s/runtime/pkg/runtime" ackrtcache "github.com/aws-controllers-k8s/runtime/pkg/runtime/cache" k8srtmocks "github.com/aws-controllers-k8s/runtime/mocks/apimachinery/pkg/runtime" k8srtschemamocks "github.com/aws-controllers-k8s/runtime/mocks/apimachinery/pkg/runtime/schema" ctrlrtclientmock "github.com/aws-controllers-k8s/runtime/mocks/controller-runtime/pkg/client" ackmocks "github.com/aws-controllers-k8s/runtime/mocks/pkg/types" ) func TestReconcilerUpdate(t *testing.T) { require := require.New(t) ctx := context.TODO() arn := ackv1alpha1.AWSResourceName("mybook-arn") delta := ackcompare.NewDelta() delta.Add("Spec.A", "val1", "val2") objKind := &k8srtschemamocks.ObjectKind{} objKind.On("GroupVersionKind").Return( k8srtschema.GroupVersionKind{ Group: "bookstore.services.k8s.aws", Kind: "Book", Version: "v1alpha1", }, ) desiredRTObj := &k8srtmocks.Object{} desiredRTObj.On("GetObjectKind").Return(objKind) desiredRTObj.On("DeepCopyObject").Return(desiredRTObj) desiredMetaObj := &k8sobj.Unstructured{} desiredMetaObj.SetAnnotations(map[string]string{}) desiredMetaObj.SetNamespace("default") desiredMetaObj.SetName("mybook") desiredMetaObj.SetGeneration(int64(1)) desired := &ackmocks.AWSResource{} desired.On("MetaObject").Return(desiredMetaObj) desired.On("RuntimeObject").Return(desiredRTObj) ids := &ackmocks.AWSResourceIdentifiers{} ids.On("ARN").Return(&arn) latestRTObj := &k8srtmocks.Object{} latestRTObj.On("GetObjectKind").Return(objKind) latestRTObj.On("DeepCopyObject").Return(latestRTObj) latestMetaObj := &k8sobj.Unstructured{} latestMetaObj.SetAnnotations(map[string]string{}) latestMetaObj.SetNamespace("default") latestMetaObj.SetName("mybook") latestMetaObj.SetGeneration(int64(1)) latest := &ackmocks.AWSResource{} latest.On("Identifiers").Return(ids) latest.On("Conditions").Return([]*ackv1alpha1.Condition{}) latest.On("MetaObject").Return(latestMetaObj) latest.On("RuntimeObject").Return(latestRTObj) rd := &ackmocks.AWSResourceDescriptor{} rd.On("GroupKind").Return( &metav1.GroupKind{ Group: "bookstore.services.k8s.aws", Kind: "fakeBook", }, ) rd.On("EmptyRuntimeObject").Return( &fakeBook{}, ) rd.On("Delta", desired, latest).Return( delta, ).Once() rd.On("Delta", desired, latest).Return(ackcompare.NewDelta()) rd.On("UpdateCRStatus", latest).Return(true, nil) rd.On("IsManaged", desired).Return(true) rm := &ackmocks.AWSResourceManager{} rm.On("ReadOne", ctx, desired).Return( latest, nil, ) rm.On("Update", ctx, desired, latest, delta).Return( latest, nil, ) rmf := &ackmocks.AWSResourceManagerFactory{} rmf.On("ResourceDescriptor").Return(rd) reg := ackrt.NewRegistry() reg.RegisterResourceManagerFactory(rmf) zapOptions := ctrlrtzap.Options{ Development: true, Level: zapcore.InfoLevel, } fakeLogger := ctrlrtzap.New(ctrlrtzap.UseFlagOptions(&zapOptions)) cfg := ackcfg.Config{} metrics := ackmetrics.NewMetrics("bookstore") sc := &ackmocks.ServiceController{} kc := &ctrlrtclientmock.Client{} statusWriter := &ctrlrtclientmock.StatusWriter{} kc.On("Status").Return(statusWriter) statusWriter.On("Patch", ctx, latestRTObj, client.MergeFrom(desiredRTObj)).Return(nil) kc.On("Patch", ctx, latestRTObj, client.MergeFrom(desiredRTObj)).Return(nil) // TODO(jaypipes): Place the above setup into helper functions that can be // re-used by future unit tests of the reconciler code paths. // With the above mocks and below assertions, we check that if we got a // non-error return from `AWSResourceManager.ReadOne()` and the // `AWSResourceDescriptor.Delta()` returned a non-empty Delta, that we end // up calling the AWSResourceManager.Update() call in the Reconciler.Sync() // method, r := ackrt.NewReconcilerWithClient(sc, kc, rmf, fakeLogger, cfg, metrics, ackrtcache.Caches{}) err := r.Sync(ctx, rm, desired) require.Nil(err) rm.AssertCalled(t, "ReadOne", ctx, desired) rd.AssertCalled(t, "Delta", desired, latest) rm.AssertCalled(t, "Update", ctx, desired, latest, delta) kc.AssertNotCalled(t, "Patch", ctx, latestRTObj, client.MergeFrom(desiredRTObj)) statusWriter.AssertCalled(t, "Patch", ctx, latestRTObj, client.MergeFrom(desiredRTObj)) } func TestReconcilerUpdate_PatchMetadataAndSpec_DiffInMetadata(t *testing.T) { require := require.New(t) ctx := context.TODO() arn := ackv1alpha1.AWSResourceName("mybook-arn") delta := ackcompare.NewDelta() delta.Add("Spec.A", "val1", "val2") objKind := &k8srtschemamocks.ObjectKind{} objKind.On("GroupVersionKind").Return( k8srtschema.GroupVersionKind{ Group: "bookstore.services.k8s.aws", Kind: "Book", Version: "v1alpha1", }, ) desiredRTObj := &k8srtmocks.Object{} desiredRTObj.On("GetObjectKind").Return(objKind) desiredRTObj.On("DeepCopyObject").Return(desiredRTObj) desiredMetaObj := &k8sobj.Unstructured{} desiredMetaObj.SetAnnotations(map[string]string{}) desiredMetaObj.SetNamespace("default") desiredMetaObj.SetName("mybook") desiredMetaObj.SetGeneration(int64(1)) desired := &ackmocks.AWSResource{} desired.On("MetaObject").Return(desiredMetaObj) desired.On("RuntimeObject").Return(desiredRTObj) ids := &ackmocks.AWSResourceIdentifiers{} ids.On("ARN").Return(&arn) latestRTObj := &k8srtmocks.Object{} latestRTObj.On("GetObjectKind").Return(objKind) latestRTObj.On("DeepCopyObject").Return(latestRTObj) latestMetaObj := &k8sobj.Unstructured{} // Note the change in annotaions latestMetaObj.SetAnnotations(map[string]string{"a": "b"}) latestMetaObj.SetNamespace("default") latestMetaObj.SetName("mybook") latestMetaObj.SetGeneration(int64(1)) latest := &ackmocks.AWSResource{} latest.On("Identifiers").Return(ids) latest.On("Conditions").Return([]*ackv1alpha1.Condition{}) latest.On("MetaObject").Return(latestMetaObj) latest.On("RuntimeObject").Return(latestRTObj) rd := &ackmocks.AWSResourceDescriptor{} rd.On("GroupKind").Return( &metav1.GroupKind{ Group: "bookstore.services.k8s.aws", Kind: "fakeBook", }, ) rd.On("EmptyRuntimeObject").Return( &fakeBook{}, ) rd.On("Delta", desired, latest).Return( delta, ).Once() rd.On("Delta", desired, latest).Return(ackcompare.NewDelta()) rd.On("UpdateCRStatus", latest).Return(true, nil) rd.On("IsManaged", desired).Return(true) rm := &ackmocks.AWSResourceManager{} rm.On("ReadOne", ctx, desired).Return( latest, nil, ) rm.On("Update", ctx, desired, latest, delta).Return( latest, nil, ) rmf := &ackmocks.AWSResourceManagerFactory{} rmf.On("ResourceDescriptor").Return(rd) reg := ackrt.NewRegistry() reg.RegisterResourceManagerFactory(rmf) zapOptions := ctrlrtzap.Options{ Development: true, Level: zapcore.InfoLevel, } fakeLogger := ctrlrtzap.New(ctrlrtzap.UseFlagOptions(&zapOptions)) cfg := ackcfg.Config{} metrics := ackmetrics.NewMetrics("bookstore") sc := &ackmocks.ServiceController{} kc := &ctrlrtclientmock.Client{} statusWriter := &ctrlrtclientmock.StatusWriter{} kc.On("Status").Return(statusWriter) statusWriter.On("Patch", ctx, latestRTObj, client.MergeFrom(desiredRTObj)).Return(nil) kc.On("Patch", ctx, latestRTObj, client.MergeFrom(desiredRTObj)).Return(nil) // TODO(jaypipes): Place the above setup into helper functions that can be // re-used by future unit tests of the reconciler code paths. // With the above mocks and below assertions, we check that if we got a // non-error return from `AWSResourceManager.ReadOne()` and the // `AWSResourceDescriptor.Delta()` returned a non-empty Delta, that we end // up calling the AWSResourceManager.Update() call in the Reconciler.Sync() // method, r := ackrt.NewReconcilerWithClient(sc, kc, rmf, fakeLogger, cfg, metrics, ackrtcache.Caches{}) err := r.Sync(ctx, rm, desired) require.Nil(err) rm.AssertCalled(t, "ReadOne", ctx, desired) rd.AssertCalled(t, "Delta", desired, latest) rm.AssertCalled(t, "Update", ctx, desired, latest, delta) kc.AssertCalled(t, "Patch", ctx, latestRTObj, client.MergeFrom(desiredRTObj)) statusWriter.AssertCalled(t, "Patch", ctx, latestRTObj, client.MergeFrom(desiredRTObj)) } func TestReconcilerUpdate_PatchMetadataAndSpec_DiffInSpec(t *testing.T) { require := require.New(t) ctx := context.TODO() arn := ackv1alpha1.AWSResourceName("mybook-arn") delta := ackcompare.NewDelta() delta.Add("Spec.A", "val1", "val2") objKind := &k8srtschemamocks.ObjectKind{} objKind.On("GroupVersionKind").Return( k8srtschema.GroupVersionKind{ Group: "bookstore.services.k8s.aws", Kind: "Book", Version: "v1alpha1", }, ) desiredRTObj := &k8srtmocks.Object{} desiredRTObj.On("GetObjectKind").Return(objKind) desiredRTObj.On("DeepCopyObject").Return(desiredRTObj) desiredMetaObj := &k8sobj.Unstructured{} desiredMetaObj.SetAnnotations(map[string]string{}) desiredMetaObj.SetNamespace("default") desiredMetaObj.SetName("mybook") desiredMetaObj.SetGeneration(int64(1)) desired := &ackmocks.AWSResource{} desired.On("MetaObject").Return(desiredMetaObj) desired.On("RuntimeObject").Return(desiredRTObj) ids := &ackmocks.AWSResourceIdentifiers{} ids.On("ARN").Return(&arn) latestRTObj := &k8srtmocks.Object{} latestRTObj.On("GetObjectKind").Return(objKind) latestRTObj.On("DeepCopyObject").Return(latestRTObj) latestMetaObj := &k8sobj.Unstructured{} // Note Similar metadata latestMetaObj.SetAnnotations(map[string]string{}) latestMetaObj.SetNamespace("default") latestMetaObj.SetName("mybook") latestMetaObj.SetGeneration(int64(1)) latest := &ackmocks.AWSResource{} latest.On("Identifiers").Return(ids) latest.On("Conditions").Return([]*ackv1alpha1.Condition{}) latest.On("MetaObject").Return(latestMetaObj) latest.On("RuntimeObject").Return(latestRTObj) rd := &ackmocks.AWSResourceDescriptor{} rd.On("GroupKind").Return( &metav1.GroupKind{ Group: "bookstore.services.k8s.aws", Kind: "fakeBook", }, ) rd.On("EmptyRuntimeObject").Return( &fakeBook{}, ) rd.On("Delta", desired, latest).Return( delta, ) rd.On("UpdateCRStatus", latest).Return(true, nil) rd.On("IsManaged", desired).Return(true) rm := &ackmocks.AWSResourceManager{} rm.On("ReadOne", ctx, desired).Return( latest, nil, ) rm.On("Update", ctx, desired, latest, delta).Return( latest, nil, ) rmf := &ackmocks.AWSResourceManagerFactory{} rmf.On("ResourceDescriptor").Return(rd) reg := ackrt.NewRegistry() reg.RegisterResourceManagerFactory(rmf) zapOptions := ctrlrtzap.Options{ Development: true, Level: zapcore.InfoLevel, } fakeLogger := ctrlrtzap.New(ctrlrtzap.UseFlagOptions(&zapOptions)) cfg := ackcfg.Config{} metrics := ackmetrics.NewMetrics("bookstore") sc := &ackmocks.ServiceController{} kc := &ctrlrtclientmock.Client{} statusWriter := &ctrlrtclientmock.StatusWriter{} kc.On("Status").Return(statusWriter) statusWriter.On("Patch", ctx, latestRTObj, client.MergeFrom(desiredRTObj)).Return(nil) kc.On("Patch", ctx, latestRTObj, client.MergeFrom(desiredRTObj)).Return(nil) // TODO(jaypipes): Place the above setup into helper functions that can be // re-used by future unit tests of the reconciler code paths. // With the above mocks and below assertions, we check that if we got a // non-error return from `AWSResourceManager.ReadOne()` and the // `AWSResourceDescriptor.Delta()` returned a non-empty Delta, that we end // up calling the AWSResourceManager.Update() call in the Reconciler.Sync() // method, r := ackrt.NewReconcilerWithClient(sc, kc, rmf, fakeLogger, cfg, metrics, ackrtcache.Caches{}) err := r.Sync(ctx, rm, desired) require.Nil(err) rm.AssertCalled(t, "ReadOne", ctx, desired) rd.AssertCalled(t, "Delta", desired, latest) rm.AssertCalled(t, "Update", ctx, desired, latest, delta) kc.AssertCalled(t, "Patch", ctx, latestRTObj, client.MergeFrom(desiredRTObj)) statusWriter.AssertCalled(t, "Patch", ctx, latestRTObj, client.MergeFrom(desiredRTObj)) }
package tfc import ( "fmt" "regexp" "github.com/hyperledger/fabric/core/chaincode/shim" tfcPb "github.com/stefanprisca/strategy-protobufs/tfc" ) func handleTrade(APIstub shim.ChaincodeStubInterface, creatorSign []byte, gameData tfcPb.GameData, payload tfcPb.TradeTrxPayload) (tfcPb.GameData, error) { err := assertTradePrecond(APIstub, gameData, creatorSign, payload) if err != nil { return gameData, fmt.Errorf( "trade preconditions not met: %s", err) } srcID := GetPlayerId(payload.Source) destID := GetPlayerId(payload.Dest) resID := GetResourceId(payload.Resource) srcProfile := gameData.Profiles[srcID] destProfile := gameData.Profiles[destID] srcProfile.Resources[resID] -= payload.Amount destProfile.Resources[resID] += payload.Amount return gameData, assertTradePostcond(gameData, payload) } func stateValidationString(src tfcPb.Player, state tfcPb.GameState) string { return fmt.Sprintf("%v%v", src, state) } var tradeStateValidationRegexp = regexp.MustCompile( fmt.Sprintf("%vRTRADE", tfcPb.Player_RED) + fmt.Sprintf("|%vBTRADE", tfcPb.Player_BLUE) + fmt.Sprintf("|%vGTRADE", tfcPb.Player_GREEN)) // TODO: implement this func assertTradePrecond(APIstub shim.ChaincodeStubInterface, gameData tfcPb.GameData, creatorSign []byte, payload tfcPb.TradeTrxPayload) error { state := gameData.State creator, err := getCreator(APIstub, creatorSign) if err != nil || creator != payload.Source { return fmt.Errorf("invalid trx creator, or creator not identified (<0): expected %v, got %v", creator, payload.Source) } stateValidationStr := stateValidationString(creator, state) if !tradeStateValidationRegexp.MatchString(stateValidationStr) { return fmt.Errorf("expected state to match one of %v, got %v", tradeStateValidationRegexp, stateValidationStr) } return nil } func assertTradePostcond(gameData tfcPb.GameData, payload tfcPb.TradeTrxPayload) error { res := payload.Resource if err := hasValidPostTradeAmount(payload.Source, gameData, res); err != nil { return err } if err := hasValidPostTradeAmount(payload.Dest, gameData, res); err != nil { return err } return nil } func hasValidPostTradeAmount(p tfcPb.Player, gameData tfcPb.GameData, r tfcPb.Resource) error { rID := GetResourceId(r) pP := *gameData.Profiles[GetPlayerId(p)] available := pP.Resources[rID] if available < 0 { return fmt.Errorf("player %v does not have required %v resources: %s", p, r, fmt.Sprintf("available: %v", available)) } return nil }
package nats import ( "context" "sync" "github.com/nats-io/nats.go" pubsub "github.com/zhangce1999/pubsub/interface" ) var _ pubsub.Broker = &Broker{} // Broker - type Broker struct { URL string Opts *BrokerOptions Handlers pubsub.HandlersChain // if the topic has a prefix of some group, it must be added to this group // so if you don't want this topic in a group, make sure that it is not a // group topic conns map[string]*conn rw *sync.Mutex sch chan *nats.Msg } // if isGroup != true, len(relaPath) == 0 type conn struct { relaPaths []string isGroup bool nc *nats.Conn } // NewBroker - func NewBroker(opts ...nats.Option) *Broker { b := &Broker{ rw: new(sync.Mutex), Opts: &BrokerOptions{ Ctx: context.Background(), DefOpts: new(nats.Options), }, sch: make(chan *nats.Msg), tree: NewTrie('/'), group: group{ root: true, basePath: "/", Handlers: nil, }, } b.group.broker = b if NATSURL == "" { b.URL = nats.DefaultURL } else { b.URL = NATSURL } b.Opts.RegisterOptions(opts...) return b } // CreatePublisher - func (b *Broker) CreatePublisher(opts ...pubsub.PublisherOptionFunc) pubsub.Publisher { p := &Publisher{ rw: new(sync.Mutex), Opts: &pubsub.PublisherOptions{ Ctx: context.Background(), }, } for _, opt := range opts { panic(opt(p.Opts)) } if topic, ok := p.Opts.Ctx.Value(pubsub.Key("Topic")).(string); ok { p.Topic = topic } return p } // CreateSubscription - func (b *Broker) CreateSubscription(opts ...pubsub.SubscriptionOptionFunc) pubsub.Subscription { s := &Subscription{ rw: new(sync.Mutex), Opts: &pubsub.SubscriberOptions{ Ctx: context.Background(), }, Subs: make(map[string]*nats.Subscription), } for _, opt := range opts { panic(opt(s.Opts)) } if topic, ok := s.Opts.Ctx.Value(pubsub.Key("Topic")).(string); ok { s.topic = topic } if isGroup, ok := s.Opts.Ctx.Value(pubsub.Key("IsGroup")).(bool); ok { s.isGroup = isGroup } if subType, ok := s.Opts.Ctx.Value(pubsub.Key("SubscriptionType")).(pubsub.SubscriptionType); ok { s.subtype = subType } return s } // Topics - func (b *Broker) Topics() []string { b.rw.Lock() defer b.rw.Unlock() return b.topics } // NumTopics - func (b *Broker) NumTopics() int { b.rw.Lock() defer b.rw.Unlock() return len(b.topics) } // NumSubcribers - func (b *Broker) NumSubcribers(topic string) int { return 0 } // Close - func (b *Broker) Close() error // AsyncSubscribe - func (b *Broker) AsyncSubscribe(ctx context.Context, topic string, handler pubsub.HandlerFunc) (pubsub.Subscription, error) // SubscribeSync - func (b *Broker) SubscribeSync(ctx context.Context, topic string, handler pubsub.HandlerFunc) (pubsub.Subscription, error) // QueueSubscribeSync - func (b *Broker) QueueSubscribeSync(ctx context.Context, topic string, queue string) (pubsub.Subscription, error)
package main import ( "math/rand" "ms/sun/servises/model_service" "ms/sun/scripts/facts/fact_utils" ) func main() { for i := 0; i < 10000; i++ { if rand.Intn(10) < 2 { factUnLike() }else { factLike() } } } func factLike() { model_service.Like_LikePost(fact_utils.GetRandUserId(),fact_utils.GetRandPostId()) } func factUnLike() { model_service.Like_UnlikePost(fact_utils.GetRandUserId(),fact_utils.GetRandPostId()) }
package hateoas import ( "fmt" "reflect" "strings" ) type hateoasResource map[string]interface{} func toHateoasResources(r []Resource, baseUrl string, resourceName string) []hateoasResource { hateoasResources := make([]hateoasResource, len(r)) for index, value := range r { hateoasResources[index] = toHateoasResource(value, baseUrl, resourceName) } return hateoasResources } func toHateoasResource(r Resource, baseUrl string, resourceName string) hateoasResource { resourceId := r.GetId() resourceUrl := Url(fmt.Sprint(baseUrl + resourceName + "/" + resourceId)) hateoasResource := hateoasResource{} hateoasResource["Href"] = resourceUrl v := reflect.ValueOf(r) vi := reflect.Indirect(v) for i := 0; i < v.NumField(); i++ { fName := vi.Type().Field(i).Name fValue := v.Field(i).Interface() resource, isResource := fValue.(Resource) if isResource { if resource.GetId() != "" { hateoasResource[fName] = toHateoasResource(resource, baseUrl, strings.ToLower(fName)) } else { hateoasResource[fName] = nil } } else { hateoasResource[fName] = fValue } } return hateoasResource }
package tests import ( "../lib" "testing" ) func TestSum(t *testing.T) { var a float64 = 5 var b float64 = 5 total := lib.Sum(a, b) if total != 10 { t.Error("Sum is wrong") } }
package manager import ( sdk "github.com/identityOrg/oidcsdk" "gopkg.in/square/go-jose.v2/json" "log" "net/http" "net/url" "path" ) func (d *DefaultManager) ProcessDiscoveryEP(writer http.ResponseWriter, _ *http.Request) { issuerUrl, err := url.Parse(d.Config.Issuer) if err != nil { http.Error(writer, err.Error(), http.StatusInternalServerError) return } metadata := DiscoveryMetadata{ Issuer: issuerUrl.String(), AuthorizationEndpoint: combinePath(*issuerUrl, "oauth2/authorize"), TokenEndpoint: combinePath(*issuerUrl, "oauth2/token"), IntrospectionEndpoint: combinePath(*issuerUrl, "oauth2/introspect"), RevocationEndpoint: combinePath(*issuerUrl, "oauth2/revoke"), UserInfoEndpoint: combinePath(*issuerUrl, "oauth2/me"), JwksUri: combinePath(*issuerUrl, "oauth2/keys"), LogoutUri: combinePath(*issuerUrl, "oauth2/logout"), SubjectTypesSupported: []string{"public"}, GrantTypesSupported: []string{"authorization_code", "password", "refresh_token", "client_credentials", "implicit"}, ResponseModesSupported: []string{"query", "fragment"}, ResponseTypesSupported: []string{"code", "token", "id_token", "code id_token", "code token", "token id_token", "code token id_token"}, TokenEndpointAuthMethodsSupported: []string{"client_secret_basic", "client_secret_post"}, IdTokenSigningAlgValuesSupported: []string{"RS256"}, } writer.Header().Add(sdk.HeaderContentType, sdk.ContentTypeJson) writer.WriteHeader(http.StatusOK) err = json.NewEncoder(writer).Encode(metadata) if err != nil { log.Println(err) } } func combinePath(issuerUrl url.URL, appendPath string) string { issuerUrl.Path = path.Join(issuerUrl.Path, appendPath) return issuerUrl.String() } type DiscoveryMetadata struct { Issuer string `json:"issuer,omitempty"` AuthorizationEndpoint string `json:"authorization_endpoint,omitempty"` TokenEndpoint string `json:"token_endpoint,omitempty"` IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"` RevocationEndpoint string `json:"revocation_endpoint,omitempty"` UserInfoEndpoint string `json:"user_info_endpoint,omitempty"` JwksUri string `json:"jwks_uri,omitempty"` LogoutUri string `json:"end_session_endpoint,omitempty"` ScopesSupported []string `json:"scopes_supported,omitempty"` ResponseTypesSupported []string `json:"response_types_supported,omitempty"` ResponseModesSupported []string `json:"response_modes_supported,omitempty"` GrantTypesSupported []string `json:"grant_types_supported,omitempty"` SubjectTypesSupported []string `json:"subject_types_supported,omitempty"` IdTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported,omitempty"` TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"` ClaimsSupported []string `json:"claims_supported,omitempty"` }
package main import ( "fmt" "strings" ) type person struct { name string age int } func main() { var one person fmt.Println("one: ", one) one = person{name:"alice", age:30} fmt.Println("one: ", one) one = person{name:"fred"} fmt.Println("one: ", one) one = person{"jack", 20} fmt.Println("one: ", one) one = person{"pool", 35} fmt.Println("one.name: ", one.name) one.name = "dead pool" fmt.Println("one.name: ", one.name) fmt.Println(strings.Repeat("-", 10)) two := &person{name:"ant", age:30} fmt.Println("two: ", two) fmt.Println("two.name: ", two.name) two.name = "ant man" fmt.Println("two.name: ", two.name) }
package main import ( "testing" ) type nodeExpceted struct { path string nType nodeType methods HTTPMethod wildChild bool indicesIsEmpty bool childrenNum int isLeaf bool statusIsNil bool } func checkNodeValid(t *testing.T, n *node, e nodeExpceted) { if n == nil { t.Fatalf("checkNodeValid: both node and expect should not be nil") } if string(n.path) != e.path { t.Errorf("n.path should be %s, but n is: %+v", e.path, n) } if n.nType != e.nType { t.Errorf("n.nType should be %d, but n is: %+v", e.nType, n) } if n.methods != e.methods { t.Errorf("n.methods should be %x, but n is: %+v", e.methods, n) } if n.wildChild != e.wildChild { t.Errorf("n.wildChild should be %t, but n is: %+v", e.wildChild, n) } if !(len(n.indices) > 0 && !e.indicesIsEmpty || len(n.indices) == 0 && e.indicesIsEmpty) { t.Errorf("n.indices should be empty? %t, but n is: %+v", e.indicesIsEmpty, n) } if len(n.children) != e.childrenNum { t.Errorf("n should have %d childrens, but n is: %+v", e.childrenNum, n) } if n.isLeaf != e.isLeaf { t.Errorf("n.leaf should be %t, but n is: %+v", e.isLeaf, n) } if !(n.status == nil && e.statusIsNil || n.status != nil && !e.statusIsNil) { t.Errorf("n.status should be nil? %t, but n is: %+v", e.statusIsNil, n) } } func TestMin(t *testing.T) { if 1 != min(1, 2) { t.Error("min(1, 2) should return 1") } if 1 != min(2, 1) { t.Error("min(2, 1) should return 1") } } func TestSetMethods(t *testing.T) { n := &node{} if n.methods != NONE { t.Errorf("n.methods should be NONE, but got: %x", n.methods) } methods := []HTTPMethod{GET, POST, PUT, DELETE, HEAD, OPTIONS, CONNECT, TRACE, PATCH} for _, m := range methods { n.setMethods(m) if !n.hasMethod(m) { t.Errorf("n should have HTTP method %x, but got: %x", m, n.methods) } } } func TestInsertLeaf(t *testing.T) { n := &node{} n.insertChild([]byte("this"), []byte("/use/this")) checkNodeValid( t, n, nodeExpceted{"this", static, NONE, false, true, 0, true, false}, ) n.insertChild([]byte("this"), []byte("/use/this"), GET) if !n.hasMethod(GET) { t.Error("n should have HTTP method `GET` been set, but not") } } func TestInsertChild(t *testing.T) { n := &node{} n.insertChild([]byte("/:name"), []byte("/user/:name"), GET) checkNodeValid( t, n, nodeExpceted{"/", static, NONE, true, true, 1, false, true}, ) // check it's child, then n = n.children[0] checkNodeValid( t, n, nodeExpceted{":name", param, GET, false, true, 0, true, false}, ) } func shouldPanic() { if err := recover(); err == nil { panic("should panic but not") } } func TestInsertBadParamDualWildchard(t *testing.T) { defer shouldPanic() n := &node{} n.insertChild([]byte("/:name:this"), []byte("/user/:name:this/there")) } func TestInsertBadParamNoParamName(t *testing.T) { defer shouldPanic() n := &node{} n.insertChild([]byte("/:"), []byte("/user/:/there")) } func TestInsertBadParamConflict(t *testing.T) { defer shouldPanic() n := &node{} n.insertChild([]byte("/:name"), []byte("/user/:name/there")) n.insertChild([]byte("/:name"), []byte("/user/:name/there")) } func TestInsertDualParam(t *testing.T) { n := &node{} n.insertChild([]byte("/:name/:card"), []byte("/user/:name/:card"), POST) slash1 := n name := n.children[0] slash2 := name.children[0] card := slash2.children[0] checkNodeValid( t, slash1, nodeExpceted{"/", static, NONE, true, true, 1, false, true}, ) checkNodeValid( t, name, nodeExpceted{":name", param, NONE, false, true, 1, false, true}, ) checkNodeValid( t, slash2, nodeExpceted{"/", static, NONE, true, true, 1, false, true}, ) checkNodeValid( t, card, nodeExpceted{":card", param, POST, false, true, 0, true, false}, ) } func TestInsertChildCatchAll(t *testing.T) { n := &node{} n.insertChild([]byte("/user/*name"), []byte("/user/*name"), POST) // first, check n itself checkNodeValid( t, n, nodeExpceted{"/user/", static, NONE, true, true, 1, false, true}, ) // last, the child n = n.children[0] checkNodeValid( t, n, nodeExpceted{"*name", catchAll, POST, false, true, 0, true, false}, ) } func TestInsertCatchAllMultiTimes(t *testing.T) { defer shouldPanic() n := &node{} n.insertChild([]byte("/*name/:haha"), []byte("/*name/:haha")) } func TestInsertCatchAllNoSlash(t *testing.T) { defer shouldPanic() n := &node{} n.insertChild([]byte("/user*name"), []byte("/user*name")) } func TestAddRoute(t *testing.T) { n := &node{} n.addRoute([]byte("/user/hello"), GET, POST) checkNodeValid( t, n, nodeExpceted{"/user/hello", root, GET | POST, false, true, 0, true, false}, ) n.addRoute([]byte("/user/world"), DELETE) checkNodeValid( t, n, nodeExpceted{"/user/", root, NONE, false, false, 2, false, true}, ) hello := n.children[0] world := n.children[1] if string(hello.path) == "world" { hello, world = world, hello } checkNodeValid( t, hello, nodeExpceted{"hello", static, GET | POST, false, true, 0, true, false}, ) checkNodeValid( t, world, nodeExpceted{"world", static, DELETE, false, true, 0, true, false}, ) } func TestAddRouteWildChild(t *testing.T) { n := &node{} n.addRoute([]byte("/user/:name/hello"), GET) checkNodeValid( t, n, nodeExpceted{"/user/", root, NONE, true, true, 1, false, true}, ) name := n.children[0] checkNodeValid( t, name, nodeExpceted{":name", param, NONE, false, true, 1, false, true}, ) hello := name.children[0] checkNodeValid( t, hello, nodeExpceted{"/hello", static, GET, false, true, 0, true, false}, ) } func TestAddRouteDualWildChild(t *testing.T) { n := &node{} n.addRoute([]byte("/user/:name/hello"), GET) checkNodeValid( t, n, nodeExpceted{"/user/", root, NONE, true, true, 1, false, true}, ) n.addRoute([]byte("/user/:name/hello/:card"), GET) checkNodeValid( t, n, nodeExpceted{"/user/", root, NONE, true, true, 1, false, true}, ) name := n.children[0] checkNodeValid( t, name, nodeExpceted{":name", param, NONE, false, true, 1, false, true}, ) slashHello := name.children[0] checkNodeValid( t, slashHello, nodeExpceted{"/hello", static, GET, false, false, 1, true, false}, ) slash := slashHello.children[0] checkNodeValid( t, slash, nodeExpceted{"/", static, NONE, true, true, 1, false, true}, ) card := slash.children[0] checkNodeValid( t, card, nodeExpceted{":card", param, GET, false, true, 0, true, false}, ) } func TestAddRouteWildParamConflict(t *testing.T) { defer shouldPanic() n := &node{} n.addRoute([]byte("/user/:name/hello/world")) n.addRoute([]byte("/user/*whoever")) } func TestAddRouteMultiIndices(t *testing.T) { n := &node{} n.addRoute([]byte("/user/:name/hello/world")) n.addRoute([]byte("/use/this")) n.addRoute([]byte("/usea/this")) n.addRoute([]byte("/useb/that")) n.addRoute([]byte("/usea/that")) } func TestAddRouteSamePath(t *testing.T) { n := &node{} n.addRoute([]byte("/user/hello"), GET, POST) checkNodeValid( t, n, nodeExpceted{"/user/hello", root, GET | POST, false, true, 0, true, false}, ) n.addRoute([]byte("/user/hello"), DELETE) checkNodeValid( t, n, nodeExpceted{"/user/hello", root, GET | POST | DELETE, false, true, 0, true, false}, ) } type byPathExpected struct { node *node tsr bool found bool } func checkByPath(t *testing.T, n *node, tsr bool, found bool, e byPathExpected) { if n != e.node { t.Errorf("node should be %+v, but got: %+v", e.node, n) } if tsr != e.tsr { t.Errorf("tsr should be %t, but got: %t", e.tsr, tsr) } if found != e.found { t.Errorf("found should be %t, but got: %t", e.found, found) } } func TestByPath(t *testing.T) { n := &node{} n.addRoute([]byte("/user"), GET, DELETE) checkNodeValid( t, n, nodeExpceted{"/user", root, GET | DELETE, false, true, 0, true, false}, ) nd, tsr, found := n.byPath([]byte([]byte("/user"))) checkByPath(t, nd, tsr, found, byPathExpected{n, false, true}) nd, tsr, found = n.byPath([]byte([]byte("/user/"))) checkByPath(t, nd, tsr, found, byPathExpected{nil, true, false}) nd, tsr, found = n.byPath([]byte("/what???")) checkByPath(t, nd, tsr, found, byPathExpected{nil, false, false}) n = &node{} n.addRoute([]byte("/user/"), GET, DELETE) n.addRoute([]byte("/usera"), GET, DELETE) checkNodeValid( t, n, nodeExpceted{"/user", root, NONE, false, false, 2, false, true}, ) nd, tsr, found = n.byPath([]byte("/user")) checkByPath(t, nd, tsr, found, byPathExpected{nil, true, false}) } func TestByPathWithWildchild(t *testing.T) { n := &node{} n.addRoute([]byte("/user/:name/hello"), GET, DELETE) n.addRoute([]byte("/use/:this/that"), GET, DELETE) checkNodeValid( t, n, nodeExpceted{"/use", root, NONE, false, false, 2, false, true}, ) nd, tsr, found := n.byPath([]byte("/user/jhon")) checkByPath(t, nd, tsr, found, byPathExpected{nil, false, false}) nd, tsr, found = n.byPath([]byte("/user/jhon/hello/")) checkByPath(t, nd, tsr, found, byPathExpected{nil, true, false}) } func TestByPathParamAndCatchAll(t *testing.T) { n := &node{} n.addRoute([]byte("/user/:name"), GET, DELETE) nd, tsr, found := n.byPath([]byte("/user/jhon")) checkByPath(t, nd, tsr, found, byPathExpected{n.children[0], false, true}) nd, tsr, found = n.byPath([]byte("/user/jhon/")) checkByPath(t, nd, tsr, found, byPathExpected{nil, true, false}) n = &node{} n.addRoute([]byte("/user/*name"), GET, DELETE) nd, tsr, found = n.byPath([]byte("/user/jhon")) checkByPath(t, nd, tsr, found, byPathExpected{n.children[0], false, true}) } func TestByPathBadNode(t *testing.T) { defer shouldPanic() n := &node{} n.addRoute([]byte("/user/:name"), GET, DELETE) child := n.children[0] child.nType = static n.byPath([]byte("/user/jhon")) } // benchmark func BenchmarkByPath(b *testing.B) { n := &node{} n.addRoute([]byte("/user/hello/world/this/is/so/long")) for i := 0; i < b.N; i++ { n.byPath([]byte("/user/hello/world/this/is/so/long")) } } func BenchmarkByPathNotFound(b *testing.B) { n := &node{} n.addRoute([]byte("/user/hello/world/this/is/so/long")) for i := 0; i < b.N; i++ { n.byPath([]byte("/user/")) } } func BenchmarkByPathParam(b *testing.B) { n := &node{} n.addRoute([]byte("/user/hello/:world/this/is/so/long")) for i := 0; i < b.N; i++ { n.byPath([]byte("/user/hello/world/this/is/so/long")) } } func BenchmarkByPathCatchall(b *testing.B) { n := &node{} n.addRoute([]byte("/user/hello/*world")) for i := 0; i < b.N; i++ { n.byPath([]byte("/user/hello/world/this/is/so/long")) } }
package genKey import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "fmt" "os" ) func GenKey()([]byte, *ecdsa.PrivateKey){ //ECDSA KEYPAIR 생성 curve := elliptic.P256() privateKey, err := ecdsa.GenerateKey(curve, rand.Reader) if err != nil { fmt.Println(err) os.Exit(1) } pubKey := append(privateKey.PublicKey.X.Bytes(), privateKey.PublicKey.Y.Bytes()...) return pubKey, privateKey }
package test_persistence import ( "reflect" cdata "github.com/pip-services3-go/pip-services3-commons-go/data" persist "github.com/pip-services3-go/pip-services3-mongodb-go/persistence" "go.mongodb.org/mongo-driver/bson" ) // extends IdentifiableMongoDbPersistence<Dummy, string> // implements IDummyPersistence { type DummyRefMongoDbPersistence struct { persist.IdentifiableMongoDbPersistence } func NewDummyRefMongoDbPersistence() *DummyRefMongoDbPersistence { proto := reflect.TypeOf(&Dummy{}) c := &DummyRefMongoDbPersistence{} c.IdentifiableMongoDbPersistence = *persist.InheritIdentifiableMongoDbPersistence(c, proto, "dummies") return c } func (c *DummyRefMongoDbPersistence) Create(correlationId string, item *Dummy) (result *Dummy, err error) { value, err := c.IdentifiableMongoDbPersistence.Create(correlationId, item) if value != nil { val, _ := value.(*Dummy) result = val } return result, err } func (c *DummyRefMongoDbPersistence) GetListByIds(correlationId string, ids []string) (items []*Dummy, err error) { convIds := make([]interface{}, len(ids)) for i, v := range ids { convIds[i] = v } result, err := c.IdentifiableMongoDbPersistence.GetListByIds(correlationId, convIds) items = make([]*Dummy, len(result)) for i, v := range result { val, _ := v.(*Dummy) items[i] = val } return items, err } func (c *DummyRefMongoDbPersistence) GetOneById(correlationId string, id string) (item *Dummy, err error) { result, err := c.IdentifiableMongoDbPersistence.GetOneById(correlationId, id) if result != nil { val, _ := result.(*Dummy) item = val } return item, err } func (c *DummyRefMongoDbPersistence) Update(correlationId string, item *Dummy) (result *Dummy, err error) { value, err := c.IdentifiableMongoDbPersistence.Update(correlationId, item) if value != nil { val, _ := value.(*Dummy) result = val } return result, err } func (c *DummyRefMongoDbPersistence) UpdatePartially(correlationId string, id string, data *cdata.AnyValueMap) (item *Dummy, err error) { result, err := c.IdentifiableMongoDbPersistence.UpdatePartially(correlationId, id, data) if result != nil { val, _ := result.(*Dummy) item = val } return item, err } func (c *DummyRefMongoDbPersistence) DeleteById(correlationId string, id string) (item *Dummy, err error) { result, err := c.IdentifiableMongoDbPersistence.DeleteById(correlationId, id) if result != nil { val, _ := result.(*Dummy) item = val } return item, err } func (c *DummyRefMongoDbPersistence) DeleteByIds(correlationId string, ids []string) (err error) { convIds := make([]interface{}, len(ids)) for i, v := range ids { convIds[i] = v } return c.IdentifiableMongoDbPersistence.DeleteByIds(correlationId, convIds) } func (c *DummyRefMongoDbPersistence) GetPageByFilter(correlationId string, filter *cdata.FilterParams, paging *cdata.PagingParams) (page *DummyRefPage, err error) { if filter == nil { filter = cdata.NewEmptyFilterParams() } key := filter.GetAsNullableString("Key") var filterObj bson.M if key != nil && *key != "" { filterObj = bson.M{"key": *key} } else { filterObj = bson.M{} } sorting := bson.M{"key": -1} tempPage, err := c.IdentifiableMongoDbPersistence.GetPageByFilter(correlationId, filterObj, paging, sorting, nil) // Convert to DummyRefPage dataLen := int64(len(tempPage.Data)) // For full release tempPage and delete this by GC data := make([]*Dummy, dataLen) for i := range tempPage.Data { temp := tempPage.Data[i].(*Dummy) data[i] = temp } page = NewDummyRefPage(&dataLen, data) return page, err } func (c *DummyRefMongoDbPersistence) GetCountByFilter(correlationId string, filter *cdata.FilterParams) (count int64, err error) { if filter == nil { filter = cdata.NewEmptyFilterParams() } key := filter.GetAsNullableString("Key") var filterObj bson.M if key != nil && *key != "" { filterObj = bson.M{"key": *key} } else { filterObj = bson.M{} } return c.IdentifiableMongoDbPersistence.GetCountByFilter(correlationId, filterObj) }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package parser import ( "github.com/npat-efault/godef/exp-go/token" "os" "testing" ) var fset = token.NewFileSet() var illegalInputs = []interface{}{ nil, 3.14, []byte(nil), "foo!", `package p; func f() { if /* should have condition */ {} };`, `package p; func f() { if ; /* should have condition */ {} };`, `package p; func f() { if f(); /* should have condition */ {} };`, } func TestParseIllegalInputs(t *testing.T) { for _, src := range illegalInputs { _, err := ParseFile(fset, "", src, 0, nil) if err == nil { t.Errorf("ParseFile(%v) should have failed", src) } } } var validPrograms = []interface{}{ "package p\n", `package p;`, `package p; import "fmt"; func f() { fmt.Println("Hello, World!") };`, `package p; func f() { if f(T{}) {} };`, `package p; func f() { _ = (<-chan int)(x) };`, `package p; func f() { _ = (<-chan <-chan int)(x) };`, `package p; func f(func() func() func());`, `package p; func f(...T);`, `package p; func f(float, ...int);`, `package p; func f(x int, a ...int) { f(0, a...); f(1, a...,) };`, `package p; type T []int; var a []bool; func f() { if a[T{42}[0]] {} };`, `package p; type T []int; func g(int) bool { return true }; func f() { if g(T{42}[0]) {} };`, `package p; type T []int; func f() { for _ = range []int{T{42}[0]} {} };`, `package p; var a = T{{1, 2}, {3, 4}}`, `package p; func f() { select { case <- c: case c <- d: case c <- <- d: case <-c <- d: } };`, `package p; func f() { if ; true {} };`, `package p; func f() { switch ; {} };`, `package p; func f() (int,) {}`, `package p; func _(x []int) { for range x {} }`, } func TestParseValidPrograms(t *testing.T) { for _, src := range validPrograms { _, err := ParseFile(fset, "", src, Trace, nil) if err != nil { t.Errorf("ParseFile(%q): %v", src, err) } } } var validFiles = []string{ "parser.go", "parser_test.go", } func TestParse3(t *testing.T) { for _, filename := range validFiles { _, err := ParseFile(fset, filename, nil, DeclarationErrors, nil) if err != nil { t.Errorf("ParseFile(%s): %v", filename, err) } } } func nameFilter(filename string) bool { switch filename { case "parser.go": case "interface.go": case "parser_test.go": default: return false } return true } func dirFilter(f os.FileInfo) bool { return nameFilter(f.Name()) } func TestParse4(t *testing.T) { path := "." pkgs, err := ParseDir(fset, path, dirFilter, 0) if err != nil { t.Fatalf("ParseDir(%s): %v", path, err) } if len(pkgs) != 1 { t.Errorf("incorrect number of packages: %d", len(pkgs)) } pkg := pkgs["parser"] if pkg == nil { t.Errorf(`package "parser" not found`) return } for filename := range pkg.Files { if !nameFilter(filename) { t.Errorf("unexpected package file: %s", filename) } } }
package redis import "gitee.com/johng/gf/g" const prefix = "bbd_" const cache = "cache" func Set(key string, value []byte) error { _, e := g.Redis(cache).Do("Set", prefix+key, value) return e } func Clear() error { _, e := g.Redis(cache).Do("FLUSHDB") return e } func Get(key string) (interface{}, error) { res, err := g.Redis(cache).Do("GET", prefix+key) return res, err }
package oauth import ( "encoding/json" "errors" "oauth-server-lite/g" "oauth-server-lite/models/utils" ) func CreateClient(client OauthClient) error { db := g.ConnectDB() err := db.Create(&client).Error return err } func UpdateClient(client OauthClient) error { db := g.ConnectDB() err := db.Save(&client).Error return err } func DeleteClient(client OauthClient) error { db := g.ConnectDB() err := db.Delete(&client).Error return err } func GetClientByClientID(clientID string) (client OauthClient) { db := g.ConnectDB() db.Where("client_id = ?", clientID).First(&client) return } func GetClients() (clients []OauthClient) { db := g.ConnectDB() db.Find(&clients) return } func GenerateClient() (ClientID, ClientSecret string, err error) { //随机字符串,client_id 16位 ClientID, err = utils.RandHashString(g.SALT, 16) if err != nil { return } //随机字符串,client_secret 32位 ClientSecret, err = utils.RandHashString(g.SALT, 32) if err != nil { return } return } func GenerateClientCredentialsClient(description string, whiteIPArray []string) (client OauthClient, err error) { ClientID, ClientSecret, err := GenerateClient() if err != nil { return } if len(whiteIPArray) == 0 { err = errors.New("must have at least one white ip") return } bs, err := json.Marshal(whiteIPArray) if err != nil { return } client = OauthClient{ ClientID: ClientID, ClientSecret: ClientSecret, GrantType: "client_credentials", Description: description, WhiteIP: string(bs), Scope: "Advance", } err = CreateClient(client) return } func GenerateAuthorizationCodeClient(description, domain string) (client OauthClient, err error) { ClientID, ClientSecret, err := GenerateClient() if err != nil { return } client = OauthClient{ ClientID: ClientID, ClientSecret: ClientSecret, GrantType: "authorization_code", Domain: domain, Description: description, Scope: "Basic", } err = CreateClient(client) return } func CheckClientPass(clientID, clientSecret string) (oauthClient OauthClient, err error) { oauthClient = GetClientByClientID(clientID) if oauthClient.ID == 0 { err = errors.New("cannot found such client id") return } if oauthClient.ClientSecret != clientSecret { err = errors.New("app secret is not correct") return } return } func CheckClientIP(clientIP string, clientID string) (oauthClient OauthClient, err error) { oauthClient = GetClientByClientID(clientID) if oauthClient.ID == 0 { err = errors.New("cannot found such client id") return } if oauthClient.WhiteIP == "" { err = errors.New("client ip is not in white ip list") return } var whiteIPArray []string err = json.Unmarshal([]byte(oauthClient.WhiteIP), &whiteIPArray) if err != nil { return } if !utils.IPCheck(clientIP, whiteIPArray) { err = errors.New("client ip is not in white ip list") return } return }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 remote import ( "context" "net" "sync" "time" "go.uber.org/atomic" ) // TODO: Adding TCP Connections Pool, https://github.com/apache/rocketmq-client-go/v2/issues/298 type tcpConnWrapper struct { net.Conn sync.Mutex closed atomic.Bool } func initConn(ctx context.Context, addr string, config *RemotingClientConfig) (*tcpConnWrapper, error) { var d net.Dialer d.KeepAlive = config.KeepAliveDuration d.Deadline = time.Now().Add(config.ConnectionTimeout) conn, err := d.DialContext(ctx, "tcp", addr) if err != nil { return nil, err } return &tcpConnWrapper{ Conn: conn, }, nil } func (wrapper *tcpConnWrapper) destroy() error { wrapper.closed.Swap(true) return wrapper.Conn.Close() } func (wrapper *tcpConnWrapper) isClosed(err error) bool { if !wrapper.closed.Load() { return false } opErr, ok := err.(*net.OpError) if !ok { return false } return opErr.Err.Error() == "use of closed network connection" }
package permutations import ( "testing" "lib" "fmt" ) func TestPermutation(t *testing.T) { testData := []struct { input []int output [][]int }{ {[]int{1, 2, 3}, [][]int{{3, 2, 1}, {2, 3, 1}, {3, 1, 2}, {1, 3, 2}, {2, 1, 3}, {1, 2, 3}}}, {[]int{0, 1}, [][]int{{1, 0}, {0, 1}}}, {[]int{1}, [][]int{{1}}}, } fmt.Println(len(testData)) for _, data := range testData { t.Run("", func(t *testing.T) { lib.AssertEqual2DSlices(t, permute(data.input), data.output) }) } }
package main import ( "fmt" ) const x int = 10 const y = 10 func main() { fmt.Println(x, y) }
package health import ( "testing" "time" "context" "encoding/json" ) type mockComponent struct { timeout time.Duration countFail int status HealthComponentStatus desc string } func (m *mockComponent) Check(ctx context.Context) HealthComponentState { time.Sleep(m.timeout) if m.countFail > 0 { m.countFail-- return HealthComponentState{ Status:HealthComponentStatusFail, Description:"server not found", } } return HealthComponentState{ Status:m.status, Description:m.desc, } } func TestSuccessHealth(t *testing.T) { healtherObj := New() healtherObj.Register(`componentA`,&mockComponent{ timeout: time.Millisecond * 500, status: HealthComponentStatusOn, desc: `start work on port 934534`, }) healtherObj.Register(`componentB`,&mockComponent{ timeout: time.Microsecond * 500, status: HealthComponentStatusOff, desc: `dns not set - skip`, },SetOptional()) healtherObj.Register(`componentC`,&mockComponent{ timeout: time.Microsecond * 500, countFail: 5, status: HealthComponentStatusOn, desc: `success connect Yo!`, }) ctx,cancel := context.WithTimeout(context.Background(),time.Second) defer cancel() state := healtherObj.Check(ctx) if state.Status != HealthServing { t.Errorf("%s != %s",HealthServing,state.Status) } if ons := state.Stats[HealthComponentStatusOn.String()];ons != 2 { t.Errorf("%d != %d",2,ons) } if offs := state.Stats[HealthComponentStatusOff.String()];offs != 1 { t.Errorf("%d != %d",1,offs) } } func TestFailWithRequiredHealth(t *testing.T) { healtherObj := New() healtherObj.Register(`componentA`,&mockComponent{ timeout: time.Millisecond * 500, status: HealthComponentStatusOn, desc: `start work on port 934534`, }) healtherObj.Register(`componentB`,&mockComponent{ timeout: time.Microsecond * 500, status: HealthComponentStatusOff, desc: `dns not set - skip`, }) healtherObj.Register(`componentC`,&mockComponent{ timeout: time.Microsecond * 500, countFail: 5, status: HealthComponentStatusOn, desc: `success connect Yo!`, }) ctx,cancel := context.WithTimeout(context.Background(),time.Second) defer cancel() state := healtherObj.Check(ctx) if state.Status != HealthNotServing { t.Errorf("%s != %s",HealthNotServing,state.Status) } if ons := state.Stats[HealthComponentStatusOn.String()];ons != 2 { t.Errorf("%d != %d",2,ons) } if offs := state.Stats[HealthComponentStatusOff.String()];offs != 1 { t.Errorf("%d != %d",1,offs) } } func TestFailWithCtxHealth(t *testing.T) { healtherObj := New() healtherObj.Register(`componentA`,&mockComponent{ timeout: time.Millisecond * 500, countFail:5, status: HealthComponentStatusOn, desc: `start work on port 934534`, }) healtherObj.Register(`componentB`,&mockComponent{ timeout: time.Microsecond * 500, status: HealthComponentStatusOff, desc: `dns not set - skip`, }) healtherObj.Register(`componentC`,&mockComponent{ timeout: time.Microsecond * 500, status: HealthComponentStatusOn, desc: `success connect Yo!`, }) ctx,cancel := context.WithTimeout(context.Background(),time.Millisecond * 800) defer cancel() state := healtherObj.Check(ctx) data, _ := json.MarshalIndent(state,"","\t") t.Log(string(data)) if state.Status != HealthNotServing { t.Errorf("%s != %s",HealthNotServing,state.Status) } if ons := state.Stats[HealthComponentStatusOn.String()];ons != 1 { t.Errorf("stats.%s %d != %d",HealthComponentStatusOn.String(),1,ons) } if offs := state.Stats[HealthComponentStatusOff.String()];offs != 1 { t.Errorf("stats.%s %d != %d",HealthComponentStatusOff.String(),1,offs) } if v := state.Stats[HealthComponentStatusFail.String()];v != 0 { t.Errorf("stats.%s %d != %d",HealthComponentStatusFail.String(),0,v) } if v := state.Stats[HealthComponentStatusTimeout.String()];v != 1 { t.Errorf("stats.%s %d != %d",HealthComponentStatusTimeout.String(),1,v) } }
package standard import "github.com/labstack/echo/v4" func Register(group *echo.Group) { group.POST("/standard/encrypt", Encrypt) group.POST("/standard/decrypt", Decrypt) }
package util import ( "time" mesh_proto "github.com/kumahq/kuma/api/mesh/v1alpha1" "github.com/kumahq/kuma/pkg/core/resources/model" "github.com/kumahq/kuma/pkg/util/proto" ) type resourceMeta struct { name string version string mesh string creationTime *time.Time modificationTime *time.Time } func NewResourceMeta(name, mesh, version string, creationTime, modificationTime time.Time) model.ResourceMeta { return &resourceMeta{ name: name, mesh: mesh, version: version, creationTime: &creationTime, modificationTime: &modificationTime, } } func kumaResourceMetaToResourceMeta(meta *mesh_proto.KumaResource_Meta) model.ResourceMeta { return &resourceMeta{ name: meta.Name, mesh: meta.Mesh, version: meta.Version, creationTime: proto.MustTimestampFromProto(meta.CreationTime), modificationTime: proto.MustTimestampFromProto(meta.ModificationTime), } } func (r *resourceMeta) GetName() string { return r.name } func (r *resourceMeta) GetNameExtensions() model.ResourceNameExtensions { return model.ResourceNameExtensionsUnsupported } func (r *resourceMeta) GetVersion() string { return r.version } func (r *resourceMeta) GetMesh() string { return r.mesh } func (r *resourceMeta) GetCreationTime() time.Time { return *r.creationTime } func (r *resourceMeta) GetModificationTime() time.Time { return *r.modificationTime }
package hello import ( "fmt" "html/template" "net/http" ) func init() { http.HandleFunc("/sign", sign) } func sign(w http.ResponseWriter, r *http.Request) { err := signTemplate.Execute(w, r.FormValue("content")) // HL } var signTemplate = template.Must(template.New("sign").Parse(signTemplateHTML)) // HL const signTemplateHTML = ` <html><body><p>You wrote: {{.}}</p></body></html> `
package main import ( "fmt" "strings" "time" "golang.org/x/text/language" ) type tmplIssueTemplateData struct { Labels []string Versions []string Proxies []string } type tmplConfigurationKeysData struct { Timestamp time.Time Keys []string Package string } type tmplScriptsGEnData struct { Package string VersionSwaggerUI string } // GitHubTagsJSON represents the JSON struct for the GitHub Tags API. type GitHubTagsJSON struct { Name string `json:"name"` } type GitHubReleasesJSON struct { ID int `json:"id"` Name string `json:"name"` TagName string `json:"tag_name"` TargetCommitISH string `json:"target_commitish"` NodeID string `json:"node_id"` Draft bool `json:"draft"` Prerelease bool `json:"prerelease"` URL string `json:"url"` AssetsURL string `json:"assets_url"` UploadURL string `json:"upload_url"` HTMLURL string `json:"html_url"` TarballURL string `json:"tarball_url"` ZipballURL string `json:"zipball_url"` Assets []any `json:"assets"` CreatedAt time.Time `json:"created_at"` PublishedAt time.Time `json:"published_at"` Author GitHubAuthorJSON `json:"author"` Body string `json:"body"` } type GitHubAuthorJSON struct { ID int `json:"id"` Login string `json:"login"` NodeID string `json:"node_id"` AvatarURL string `json:"avatar_url"` GravatarID string `json:"gravatar_id"` URL string `json:"url"` HTMLURL string `json:"html_url"` FollowersURL string `json:"followers_url"` FollowingURL string `json:"following_url"` GistsURL string `json:"gists_url"` StarredURL string `json:"starred_url"` SubscriptionsURL string `json:"subscriptions_url"` OrganizationsURL string `json:"organizations_url"` ReposURL string `json:"repos_url"` EventsURL string `json:"events_url"` ReceivedEventsURL string `json:"received_events_url"` Type string `json:"type"` SiteAdmin bool `json:"site_admin"` } // DocsDataMisc represents the docs misc data schema. type DocsDataMisc struct { CSP TemplateCSP `json:"csp"` Latest string `json:"latest"` } // TemplateCSP represents the CSP template vars. type TemplateCSP struct { TemplateDefault string `json:"default"` TemplateDevelopment string `json:"development"` PlaceholderNONCE string `json:"nonce"` } // ConfigurationKey is the docs json model for the Authelia configuration keys. type ConfigurationKey struct { Path string `json:"path"` Secret bool `json:"secret"` Env string `json:"env"` } // Languages is the docs json model for the Authelia languages configuration. type Languages struct { Defaults DefaultsLanguages `json:"defaults"` Namespaces []string `json:"namespaces"` Languages []Language `json:"languages"` } type DefaultsLanguages struct { Language Language `json:"language"` Namespace string `json:"namespace"` } // Language is the docs json model for a language. type Language struct { Display string `json:"display"` Locale string `json:"locale"` Namespaces []string `json:"namespaces,omitempty"` Fallbacks []string `json:"fallbacks,omitempty"` Tag language.Tag `json:"-"` } const ( labelAreaPrefixPriority = "priority" labelAreaPrefixType = "type" labelAreaPrefixStatus = "status" ) type label interface { String() string LabelDescription() string } type labelPriority int //nolint:deadcode,varcheck // Kept for future use. const ( labelPriorityCritical labelPriority = iota labelPriorityHigh labelPriorityMedium labelPriorityNormal labelPriorityLow labelPriorityVeryLow ) var labelPriorityDescriptions = [...]string{ "Critical", "High", "Medium", "Normal", "Low", "Very Low", } func (l labelPriority) String() string { return fmt.Sprintf("%s/%d/%s", labelAreaPrefixPriority, l+1, labelFormatString(labelPriorityDescriptions[l])) } func (l labelPriority) LabelDescription() string { return labelPriorityDescriptions[l] } type labelStatus int const ( labelStatusNeedsDesign labelStatus = iota labelStatusNeedsTriage ) var labelStatusDescriptions = [...]string{ "Needs Design", "Needs Triage", } func (l labelStatus) String() string { return fmt.Sprintf("%s/%s", labelAreaPrefixStatus, labelFormatString(labelStatusDescriptions[l])) } func (l labelStatus) LabelDescription() string { return labelStatusDescriptions[l] } type labelType int //nolint:deadcode,varcheck // Kept for future use. const ( labelTypeFeature labelType = iota labelTypeBugUnconfirmed labelTypeBug ) var labelTypeDescriptions = [...]string{ "Feature", "Bug: Unconfirmed", "Bug", } func (l labelType) String() string { return fmt.Sprintf("%s/%s", labelAreaPrefixType, labelFormatString(labelTypeDescriptions[l])) } func (l labelType) LabelDescription() string { return labelTypeDescriptions[l] } func labelFormatString(in string) string { in = strings.ReplaceAll(in, ": ", "/") in = strings.ReplaceAll(in, " ", "-") return strings.ToLower(in) } // CSPValue represents individual CSP values. type CSPValue struct { Name string Value string } // PackageJSON represents a NPM package.json file. type PackageJSON struct { Version string `json:"version"` }
package schema // ErrorContainer represents a container where we can add errors and retrieve them. type ErrorContainer interface { Push(err error) PushWarning(err error) HasErrors() bool HasWarnings() bool Errors() []error Warnings() []error } // StructValidator is a validator for structs. type StructValidator struct { errors []error warnings []error } // NewStructValidator is a constructor of struct validator. func NewStructValidator() *StructValidator { val := new(StructValidator) val.errors = make([]error, 0) val.warnings = make([]error, 0) return val } // Push an error to the validator. func (v *StructValidator) Push(err error) { v.errors = append(v.errors, err) } // PushWarning error to the validator. func (v *StructValidator) PushWarning(err error) { v.warnings = append(v.warnings, err) } // HasErrors checks whether the validator contains errors. func (v *StructValidator) HasErrors() bool { return len(v.errors) > 0 } // HasWarnings checks whether the validator contains warning errors. func (v *StructValidator) HasWarnings() bool { return len(v.warnings) > 0 } // Errors returns the errors. func (v *StructValidator) Errors() []error { return v.errors } // Warnings returns the warnings. func (v *StructValidator) Warnings() []error { return v.warnings } // Clear errors and warnings. func (v *StructValidator) Clear() { v.errors = []error{} v.warnings = []error{} }
// +build qml package dialog import ( "github.com/therecipe/qt/quick" "github.com/therecipe/qt/internal/examples/sql/masterdetail_qml/controller" ) func init() { deleteDialogController_QmlRegisterType2("Dialog", 1, 0, "DeleteDialogController") } type deleteDialogController struct { quick.QQuickItem _ func() `constructor:"init"` //qml<-controller _ func(title, artist string) `signal:"deleteAlbumShowRequest"` //qml->controller _ func() `signal:"deleteAlbumCommand"` } func (d *deleteDialogController) init() { //qml<-controller controller.Instance.ConnectDeleteAlbumShowRequest(d.DeleteAlbumShowRequest) //qml->controller d.ConnectDeleteAlbumCommand(controller.Instance.DeleteAlbumCommand) }
package display import ( "html/template" "github.com/GoAdminGroup/go-admin/template/types" ) type Dot struct { types.BaseDisplayFnGenerator } func init() { types.RegisterDisplayFnGenerator("dot", new(Dot)) } func (d *Dot) Get(args ...interface{}) types.FieldFilterFn { return func(value types.FieldModel) interface{} { icons := args[0].(map[string]types.FieldDotColor) defaultDot := types.FieldDotColor("") if len(args) > 1 { defaultDot = args[1].(types.FieldDotColor) } for k, style := range icons { if k == value.Value { return template.HTML(`<span class="label-`+style+`" style="width: 8px;height: 8px;padding: 0;border-radius: 50%;display: inline-block;"> </span>&nbsp;&nbsp;`) + template.HTML(value.Value) } } if defaultDot != "" { return template.HTML(`<span class="label-`+defaultDot+`" style="width: 8px;height: 8px;padding: 0;border-radius: 50%;display: inline-block;"> </span>&nbsp;&nbsp;`) + template.HTML(value.Value) } return value.Value } }
package dashSlicer import ( "errors" "sync" ) type sliceData struct { duration int bitrate int data []byte } type sliceDataContainer struct { maxSliceCounter int avSeparated bool videoHeader []byte audioHeader []byte startNumber_av int idx_av int startNumber_a int idx_a int dataAV map[int]*sliceData muxAV sync.RWMutex dataA map[int]*sliceData muxA sync.RWMutex } func (this *sliceDataContainer) init(avSeparate bool, maxSliceDataCounter int) { this.maxSliceCounter = maxSliceDataCounter this.avSeparated = avSeparate this.dataAV = make(map[int]*sliceData) if avSeparate { this.dataA = make(map[int]*sliceData) } } func (this *sliceDataContainer) SetVideoHeader(header []byte) { this.videoHeader = make([]byte, len(header)) copy(this.videoHeader, header) } func (this *sliceDataContainer) SetAudioHeader(header []byte) { this.audioHeader = make([]byte, len(header)) copy(this.audioHeader, header) } func (this *sliceDataContainer) GetVideoHeader() (header []byte) { return this.videoHeader } func (this *sliceDataContainer) GetAudioHeader() (header []byte) { return this.audioHeader } func (this *sliceDataContainer) AddAudioSlice(data []byte, duration, bitrate int) { this.muxA.Lock() defer this.muxA.Unlock() if this.avSeparated { slice_data := &sliceData{ duration, bitrate, data, } this.dataA[this.idx_a] = slice_data this.idx_a++ if len(this.dataA) > this.maxSliceCounter { delete(this.dataA, this.startNumber_a) this.startNumber_a++ } } } func (this *sliceDataContainer) AddVideoSlice(data []byte, duration, bitrate int) { if nil == data || len(data) == 0 { return } this.muxAV.Lock() defer this.muxAV.Unlock() slice_data := &sliceData{ duration, bitrate, data, } this.dataAV[this.idx_av] = slice_data this.idx_av++ if len(this.dataAV) > this.maxSliceCounter { delete(this.dataAV, this.startNumber_av) this.startNumber_av++ } } func (this *sliceDataContainer) MediaDataByIndex(idx int, audio bool) (slice_data *sliceData, err error) { if audio { if false == this.avSeparated { return nil, errors.New("audio and video are in the same track") } else { this.muxA.Lock() defer this.muxA.Unlock() ok := false slice_data, ok = this.dataA[idx] if false == ok { err = errors.New("audio data index out of range") return } return } } else { this.muxAV.Lock() defer this.muxAV.RUnlock() ok := false slice_data, ok = this.dataAV[idx] if false == ok { err = errors.New("av data index out of range") return } return } return }
package persistence import ( "context" "fmt" "github.com/philippgille/gokv" "github.com/tinkerbell/pbnj/pkg/repository" ) // GoKV store, methods implement repository.Actions interface. type GoKV struct { Ctx context.Context Store gokv.Store } // Create a record. func (g *GoKV) Create(id string, val repository.Record) error { return g.Store.Set(id, val) } // Get a record. func (g *GoKV) Get(id string) (repository.Record, error) { rec := new(repository.Record) found, err := g.Store.Get(id, rec) if err != nil { return *rec, err } if !found { err = fmt.Errorf("record id not found: %v", id) } return *rec, err } // Update a record. func (g *GoKV) Update(id string, val repository.Record) error { rec := new(repository.Record) found, err := g.Store.Get(id, rec) if err != nil { return err } if !found { return fmt.Errorf("record id not found: %v", id) } return g.Store.Set(id, val) } // Delete a record. func (g *GoKV) Delete(id string) error { return g.Store.Delete(id) }
// Copyright 2016-2021, Pulumi Corporation. package provider import ( "context" "fmt" "net" gocidr "github.com/apparentlymart/go-cidr/cidr" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/cloudformation" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/pulumi/pulumi/sdk/v3/go/common/resource" ) func (p *cfnProvider) getAZs(ctx context.Context, inputs resource.PropertyMap) (resource.PropertyMap, error) { region, ok := inputs["region"] if !ok { region = resource.NewStringProperty(p.region) } else if !region.IsString() { return nil, fmt.Errorf("'region' must be a string") } resp, err := p.ec2.DescribeAvailabilityZones(ctx, &ec2.DescribeAvailabilityZonesInput{ Filters: []types.Filter{{ Name: aws.String("region-name"), Values: []string{region.StringValue()}, }}, }) if err != nil { return nil, err } azs := make([]string, len(resp.AvailabilityZones)) for i, az := range resp.AvailabilityZones { azs[i] = *az.ZoneName } return resource.NewPropertyMapFromMap(map[string]interface{}{ "azs": azs, }), nil } func (p *cfnProvider) cidr(ctx context.Context, inputs resource.PropertyMap) (resource.PropertyMap, error) { ipBlock, ok := inputs["ipBlock"] if !ok { return nil, fmt.Errorf("missing required property 'ipBlock'") } if !ipBlock.IsString() { return nil, fmt.Errorf("'ipBlock' must be a string") } count, ok := inputs["count"] if !ok { return nil, fmt.Errorf("mising required property 'count'") } if !count.IsNumber() || count.NumberValue() < 1 || count.NumberValue() > 256 { return nil, fmt.Errorf("'count' must be a number between 1 and 256") } cidrBits, ok := inputs["cidrBits"] if !ok { return nil, fmt.Errorf("mising required property 'cidrBits'") } if !cidrBits.IsNumber() || cidrBits.NumberValue() < 0 { return nil, fmt.Errorf("'cidrBits' must be a positive number") } _, network, err := net.ParseCIDR(ipBlock.StringValue()) if err != nil { return nil, fmt.Errorf("invalid IP block: %s", err) } subnets := make([]resource.PropertyValue, int(count.NumberValue())) subnets[0] = resource.NewStringProperty(network.String()) prefixLen := int(cidrBits.NumberValue()) for i := 1; i < len(subnets)-1; i++ { subnet, ok := gocidr.NextSubnet(network, prefixLen) if !ok { return nil, fmt.Errorf("could not create %d subnets", len(subnets)) } subnets[i], network = resource.NewStringProperty(subnet.String()), subnet } return resource.PropertyMap{ "subnets": resource.NewArrayProperty(subnets), }, nil } func (p *cfnProvider) importValue(ctx context.Context, inputs resource.PropertyMap) (resource.PropertyMap, error) { name, ok := inputs["name"] if !ok { return nil, fmt.Errorf("missing required property 'name'") } if !name.IsString() { return nil, fmt.Errorf("'name' must be a string") } value, ok := "", false paginator := cloudformation.NewListExportsPaginator(p.cfn, &cloudformation.ListExportsInput{}) for paginator.HasMorePages() && !ok { output, err := paginator.NextPage(ctx) if err != nil { return nil, err } for _, export := range output.Exports { if *export.Name == name.StringValue() { value, ok = *export.Value, true break } } } if !ok { return nil, fmt.Errorf("unknown export '%s'", name.StringValue()) } return resource.PropertyMap{ "value": resource.NewStringProperty(value), }, nil }