text
stringlengths
11
4.05M
package db import ( _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" "github.com/spf13/viper" ) var db *gorm.DB func Init() (err error) { db, err = gorm.Open("mysql", viper.GetString("db.server")) if err != nil { return } db.SingularTable(true) if viper.GetString("log.level") == "debug" { db.LogMode(true) } else { db.LogMode(false) } return } func DB() *gorm.DB { return db } func CloseDB() { db.Close() }
package main func main() { consumer() }
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "github.com/syndtr/goleveldb/leveldb" ) // CreateStreamRequest represents a request to create a stream type CreateStreamRequest struct { StreamName string ShardCount int } type EnhancedMonitoringData struct { ShardLevelMetrics []string } type ShardData struct { ShardId string } type StreamData struct { RetentionPeriodHours string EnhancedMonitoring []EnhancedMonitoringData EncryptionType string HasMoreShards bool Shards []ShardData StreamARN string StreamName string StreamStatus string StreamCreationTimestamp int _seqIx []int // Hidden data, remove when returning _tags []string // Hidden data, remove when returning } func handler(w http.ResponseWriter, r *http.Request) { b, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } fmt.Printf("Body: %s\n", b) // fmt.Fprintf(w, "%s", b) fmt.Printf("Method:%s \nURL:%s \nProto:%s \n", r.Method, r.URL, r.Proto) //Iterate over all header fields for k, v := range r.Header { fmt.Printf("Header field %q, Value %q\n", k, v) } fmt.Printf("Host = %q\n", r.Host) fmt.Printf("RemoteAddr= %q\n", r.RemoteAddr) //Get value for a specified token fmt.Printf("\n\nFinding value of \"Accept\" %q\n", r.Header["Accept"]) createStream(b) } func createStream(data []byte) { var req CreateStreamRequest json.Unmarshal(data, &req) fmt.Printf("StreamName: %s\n", req.StreamName) fmt.Printf("ShardCount: %d\n", req.ShardCount) db := initDB() defer db.Close() stream := StreamData{StreamName: req.StreamName} streamBytes, _ := json.Marshal(&stream) err := db.Put([]byte(req.StreamName), streamBytes, nil) if err != nil { log.Fatal(err) } val, err := db.Get([]byte(req.StreamName), nil) if err != nil { log.Fatal(err) } log.Println(string(val)) } func initDB() *leveldb.DB { db, err := leveldb.OpenFile("/tmp/kinesis-lite.db", nil) if err != nil { log.Fatal(err) } return db } func main() { fmt.Println("The server is starting...") http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe(":4567", nil)) }
package pacs import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00200106 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:pacs.002.001.06 Document"` Message *FIToFIPaymentStatusReportV06 `xml:"FIToFIPmtStsRpt"` } func (d *Document00200106) AddMessage() *FIToFIPaymentStatusReportV06 { d.Message = new(FIToFIPaymentStatusReportV06) return d.Message } // Scope // The FinancialInstitutionToFinancialInstitutionPaymentStatusReport message is sent by an instructed agent to the previous party in the payment chain. It is used to inform this party about the positive or negative status of an instruction (either single or file). It is also used to report on a pending instruction. // Usage // The FIToFIPaymentStatusReport message is exchanged between agents to provide status information about instructions previously sent. Its usage will always be governed by a bilateral agreement between the agents. // The FIToFIPaymentStatusReport message can be used to provide information about the status (e.g. rejection, acceptance) of a credit transfer instruction, a direct debit instruction, as well as other intra-agent instructions (for example FIToFIPaymentCancellationRequest). // The FIToFIPaymentStatusReport message refers to the original instruction(s) by means of references only or by means of references and a set of elements from the original instruction. // The FIToFIPaymentStatusReport message can be used in domestic and cross-border scenarios. type FIToFIPaymentStatusReportV06 struct { // Set of characteristics shared by all individual transactions included in the status report message. GroupHeader *iso20022.GroupHeader53 `xml:"GrpHdr"` // Original group information concerning the group of transactions, to which the status report message refers to. OriginalGroupInformationAndStatus []*iso20022.OriginalGroupHeader1 `xml:"OrgnlGrpInfAndSts,omitempty"` // Information concerning the original transactions, to which the status report message refers. TransactionInformationAndStatus []*iso20022.PaymentTransaction52 `xml:"TxInfAndSts,omitempty"` // Additional information that cannot be captured in the structured elements and/or any other specific block. SupplementaryData []*iso20022.SupplementaryData1 `xml:"SplmtryData,omitempty"` } func (f *FIToFIPaymentStatusReportV06) AddGroupHeader() *iso20022.GroupHeader53 { f.GroupHeader = new(iso20022.GroupHeader53) return f.GroupHeader } func (f *FIToFIPaymentStatusReportV06) AddOriginalGroupInformationAndStatus() *iso20022.OriginalGroupHeader1 { newValue := new(iso20022.OriginalGroupHeader1) f.OriginalGroupInformationAndStatus = append(f.OriginalGroupInformationAndStatus, newValue) return newValue } func (f *FIToFIPaymentStatusReportV06) AddTransactionInformationAndStatus() *iso20022.PaymentTransaction52 { newValue := new(iso20022.PaymentTransaction52) f.TransactionInformationAndStatus = append(f.TransactionInformationAndStatus, newValue) return newValue } func (f *FIToFIPaymentStatusReportV06) AddSupplementaryData() *iso20022.SupplementaryData1 { newValue := new(iso20022.SupplementaryData1) f.SupplementaryData = append(f.SupplementaryData, newValue) return newValue }
package core import ( "YNM3000/code/logger" "YNM3000/code/scripts" "YNM3000/code/utils" "github.com/robertkrimen/otto" ) const ( Append = "Append" Cleaning = "Cleaning" ExecCmd = "ExecCmd" CreateFolder = "CreateFolder" DeleteFile = "DeleteFile" ) // InitVM init scripting engine func (r *Runner) InitVM() { r.VM = otto.New() r.LoadEngineScripts() } func (r *Runner) ExecScript(script string) string { logger.Info(script) value, err := r.VM.Run(script) if err == nil { out, nerr := value.ToString() if nerr == nil { return out } } return "" } func (r *Runner) LoadEngineScripts() { r.LoadScripts() // r.LoadDBScripts() // r.LoadImportScripts() // r.LoadExternalScripts() // r.LoadGitScripts() // r.LoadNotiScripts() } func (r *Runner) LoadScripts() string { var output string vm := r.VM vm.Set(Append, func(call otto.FunctionCall) otto.Value { dest := call.Argument(0).String() src := call.Argument(1).String() scripts.Append(dest, src) returnValue, _ := otto.ToValue(true) return returnValue }) vm.Set(Cleaning, func(call otto.FunctionCall) otto.Value { if !r.Clean { return otto.Value{} } scripts.Cleaning(call.Argument(0).String(), r.Reports) return otto.Value{} }) // ExecCmd execute command vm.Set(ExecCmd, func(call otto.FunctionCall) otto.Value { cmd := call.Argument(0).String() _, err := utils.RunCommandWithErr(cmd) var validate bool if err != nil { validate = true } result, err := vm.ToValue(validate) if err != nil { return otto.Value{} } return result }) vm.Set(CreateFolder, func(call otto.FunctionCall) otto.Value { utils.MakeDir(call.Argument(0).String()) return otto.Value{} }) vm.Set(DeleteFile, func(call otto.FunctionCall) otto.Value { scripts.DeleteFile(call.Argument(0).String()) return otto.Value{} }) r.VM = vm return output }
package encode_test import ( "testing" "github.com/openacid/slim/encode" "github.com/stretchr/testify/require" ) func TestI8(t *testing.T) { ta := require.New(t) cases := []struct { input int8 want string wantsize int }{ {0, string([]byte{0}), 1}, {1, string([]byte{1}), 1}, {0x12, string([]byte{0x12}), 1}, {^int8(0), string([]byte{0xff}), 1}, } m := encode.I8{} for _, c := range cases { rst := m.Encode(c.input) ta.Equal(c.want, string(rst)) n := m.GetSize(c.input) ta.Equal(c.wantsize, n) n = m.GetEncodedSize(rst) ta.Equal(c.wantsize, n) n, u64 := m.Decode(rst) ta.Equal(c.input, u64) ta.Equal(c.wantsize, n) } }
package cas import ( "fmt" "net/http" "net/http/httptest" "net/url" "strings" "testing" ) func TestUnauthenticatedRequestShouldRedirectToCasURL(t *testing.T) { url, _ := url.Parse("https://cas.example.com/") client := NewClient(&Options{ URL: url, }) handler := client.HandleFunc(func(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { RedirectToLogin(w, r) return } fmt.Fprintln(w, "You are logged in, but you shouldn't be, oh noes!!") }) req, err := http.NewRequest("GET", "http://example.com/", nil) if err != nil { t.Error(err) } w := httptest.NewRecorder() handler.ServeHTTP(w, req) if w.Code != http.StatusFound { t.Errorf("Expected HTTP response code to be <%v>, got <%v>", http.StatusFound, w.Code) } loc := w.Header().Get("Location") exp := "https://cas.example.com/login?service=http%3A%2F%2Fexample.com%2F" if loc != exp { t.Errorf("Expected HTTP redirect to <%s>, got <%s>", exp, loc) } setCookie := w.Header().Get("Set-Cookie") if !strings.HasPrefix(setCookie, sessionCookieName) { t.Errorf("Expected response to have Set-Cookie header with <%v>, got <%v>", sessionCookieName, setCookie) } req.Header.Set("X-Forwarded-Proto", "https") handler.ServeHTTP(w, req) if w.Code != http.StatusFound { t.Errorf("Expected HTTP response code to be <%v>, got <%v>", http.StatusFound, w.Code) } loc = w.Header().Get("Location") exp = "https://cas.example.com/login?service=https%3A%2F%2Fexample.com%2F" if loc != exp { t.Errorf("Expected HTTP redirect to <%s>, got <%s>", exp, loc) } } func TestInvalidServiceTicket(t *testing.T) { server := &TestServer{} defer server.Close() ts := httptest.NewServer(server) defer ts.Close() url, _ := url.Parse(ts.URL) client := NewClient(&Options{ URL: url, }) handler := client.HandleFunc(func(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { RedirectToLogin(w, r) return } fmt.Fprintln(w, "You are logged in, but you shouldn't be, oh noes!!") }) req, err := http.NewRequest("GET", "http://example.com/?ticket=ST-l8d6b51d8e9c4569345a30e2f904626a1066384db8694784a60b515d62f6c", nil) if err != nil { t.Error(err) } w := httptest.NewRecorder() handler.ServeHTTP(w, req) if w.Code != http.StatusFound { t.Errorf("Expected HTTP response code to be <%v>, got <%v>", http.StatusFound, w.Code) } loc := w.Header().Get("Location") exp, _ := url.Parse("/login?service=http%3A%2F%2Fexample.com%2F") if loc != exp.String() { t.Errorf("Expected HTTP redirect to <%s>, got <%s>", exp, loc) } setCookie := w.Header().Get("Set-Cookie") if !strings.HasPrefix(setCookie, sessionCookieName) { t.Errorf("Expected response to have Set-Cookie header with <%v>, got <%v>", sessionCookieName, setCookie) } } func TestValidServiceTicket(t *testing.T) { server := &TestServer{} ticket := server.NewTicket("ST-l8d6b51d8e9c4569345a30e2f904626a1066384db8694784a60b515d62f6c") ticket.Service = "http://example.com/" ticket.Username = "TestValidServiceTicket" server.AddTicket(ticket) defer server.Close() ts := httptest.NewServer(server) defer ts.Close() url, _ := url.Parse(ts.URL) client := NewClient(&Options{ URL: url, }) message := "You are logged in, welcome client" handler := client.HandleFunc(func(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { RedirectToLogin(w, r) return } fmt.Fprintln(w, message) }) req, err := http.NewRequest("GET", "http://example.com/?ticket=ST-l8d6b51d8e9c4569345a30e2f904626a1066384db8694784a60b515d62f6c", nil) if err != nil { t.Error(err) } w := httptest.NewRecorder() handler.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("Expected HTTP response code to be <%v>, got <%v>", http.StatusOK, w.Code) } if message != strings.Trim(w.Body.String(), "\n") { t.Errorf("Expected body to be <%s>, got <%s>", message, strings.Trim(w.Body.String(), "\n")) } setCookie := w.Header().Get("Set-Cookie") if !strings.HasPrefix(setCookie, sessionCookieName) { t.Errorf("Expected response to have Set-Cookie header with <%v>, got <%v>", sessionCookieName, setCookie) } } func TestGetUsernameFromServiceTicket(t *testing.T) { server := &TestServer{} ticket := server.NewTicket("ST-l8d6b51d8e9c4569345a30e2f904626a1066384db8694784a60b515d62f6c") ticket.Service = "http://example.com/" ticket.Username = "enoch.root" server.AddTicket(ticket) defer server.Close() ts := httptest.NewServer(server) defer ts.Close() url, _ := url.Parse(ts.URL) client := NewClient(&Options{ URL: url, }) message := "You are logged in, welcome" handler := client.HandleFunc(func(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { RedirectToLogin(w, r) return } user := Username(r) fmt.Fprintln(w, message, user) }) req, err := http.NewRequest("GET", "http://example.com/?ticket=ST-l8d6b51d8e9c4569345a30e2f904626a1066384db8694784a60b515d62f6c", nil) if err != nil { t.Error(err) } w := httptest.NewRecorder() handler.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("Expected HTTP response code to be <%v>, got <%v>", http.StatusOK, w.Code) } expected := fmt.Sprintf("%s %s", message, ticket.Username) if expected != strings.Trim(w.Body.String(), "\n") { t.Errorf("Expected body to be <%s>, got <%s>", expected, strings.Trim(w.Body.String(), "\n")) } setCookie := w.Header().Get("Set-Cookie") if !strings.HasPrefix(setCookie, sessionCookieName) { t.Errorf("Expected response to have Set-Cookie header with <%v>, got <%v>", sessionCookieName, setCookie) } } func TestGetAttributesFromServiceTicket(t *testing.T) { server := &TestServer{} ticket := server.NewTicket("ST-l8d6b51d8e9c4569345a30e2f904626a1066384db8694784a60b515d62f6c") ticket.Service = "http://example.com/" ticket.Username = "enoch.root" ticket.Attributes.Add("admin", "true") ticket.Attributes.Add("account", "testing") server.AddTicket(ticket) defer server.Close() ts := httptest.NewServer(server) defer ts.Close() url, _ := url.Parse(ts.URL) client := NewClient(&Options{ URL: url, }) message := "You are logged in, welcome %s%s, your account is %s" handler := client.HandleFunc(func(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { RedirectToLogin(w, r) return } user := Username(r) attr := Attributes(r) admin := "" if attr.Get("admin") == "true" { admin = "Sir " } account := attr.Get("account") fmt.Fprintf(w, message, admin, user, account) fmt.Fprintf(w, "\n") }) req, err := http.NewRequest("GET", "http://example.com/?ticket=ST-l8d6b51d8e9c4569345a30e2f904626a1066384db8694784a60b515d62f6c", nil) if err != nil { t.Error(err) } w := httptest.NewRecorder() handler.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("Expected HTTP response code to be <%v>, got <%v>", http.StatusOK, w.Code) } expected := fmt.Sprintf(message, "Sir ", ticket.Username, "testing") if expected != strings.Trim(w.Body.String(), "\n") { t.Errorf("Expected body to be <%s>, got <%s>", expected, strings.Trim(w.Body.String(), "\n")) } setCookie := w.Header().Get("Set-Cookie") if !strings.HasPrefix(setCookie, sessionCookieName) { t.Errorf("Expected response to have Set-Cookie header with <%v>, got <%v>", sessionCookieName, setCookie) } } func TestSecondRequestShouldBeCookied(t *testing.T) { server := &TestServer{} ticket := server.NewTicket("ST-l8d6b51d8e9c4569345a30e2f904626a1066384db8694784a60b515d62f6c") ticket.Service = "http://example.com/" ticket.Username = "enoch.root" ticket.Attributes.Add("admin", "true") ticket.Attributes.Add("account", "testing") server.AddTicket(ticket) defer server.Close() ts := httptest.NewServer(server) defer ts.Close() url, _ := url.Parse(ts.URL) client := NewClient(&Options{ URL: url, }) message := "You are logged in, welcome %s%s, your account is %s" handler := client.HandleFunc(func(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { RedirectToLogin(w, r) return } user := Username(r) attr := Attributes(r) admin := "" if attr.Get("admin") == "true" { admin = "Sir " } account := attr.Get("account") fmt.Fprintf(w, message, admin, user, account) fmt.Fprintf(w, "\n") }) req, err := http.NewRequest("GET", "http://example.com/?ticket=ST-l8d6b51d8e9c4569345a30e2f904626a1066384db8694784a60b515d62f6c", nil) if err != nil { t.Error(err) } w := httptest.NewRecorder() handler.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("Expected First HTTP response code to be <%v>, got <%v>", http.StatusOK, w.Code) } setCookie := w.Header().Get("Set-Cookie") if !strings.HasPrefix(setCookie, sessionCookieName) { t.Errorf("Expected response to have Set-Cookie header with <%v>, got <%v>", sessionCookieName, setCookie) } req, err = http.NewRequest("GET", "http://example.com/", nil) if err != nil { t.Error(err) } // Parse response headers and add them to the new request resp := http.Response{Header: w.Header()} for _, cookie := range resp.Cookies() { req.AddCookie(cookie) } w = httptest.NewRecorder() handler.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("Expected Second HTTP response code to be <%v>, got <%v>", http.StatusOK, w.Code) } } func TestLogOut(t *testing.T) { server := &TestServer{} ticket := server.NewTicket("ST-l8d6b51d8e9c4569345a30e2f904626a1066384db8694784a60b515d62f6c") ticket.Service = "http://example.com/" ticket.Username = "enoch.root" server.AddTicket(ticket) defer server.Close() ts := httptest.NewServer(server) defer ts.Close() u, _ := url.Parse(ts.URL) client := NewClient(&Options{ URL: u, }) handler := client.HandleFunc(func(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { RedirectToLogin(w, r) return } if r.URL.Query().Get("logout") == "1" { RedirectToLogout(w, r) return } fmt.Fprintln(w, "Welcome, you are logged in") }) // Log them in req, err := http.NewRequest("GET", "http://example.com/?ticket=ST-l8d6b51d8e9c4569345a30e2f904626a1066384db8694784a60b515d62f6c", nil) if err != nil { t.Error(err) } w := httptest.NewRecorder() handler.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("Expected First HTTP response code to be <%v>, got <%v>", http.StatusOK, w.Code) } setCookie := w.Header().Get("Set-Cookie") if !strings.HasPrefix(setCookie, sessionCookieName) { t.Errorf("Expected response to have Set-Cookie header with <%v>, got <%v>", sessionCookieName, setCookie) } if _, err := client.tickets.Read(ticket.Name); err != nil { t.Errorf("Expected tickets.Read error to be nil, got %v", err) } // Request Logout req, err = http.NewRequest("GET", "http://example.com/?logout=1", nil) if err != nil { t.Error(err) } // Parse response headers and add them to the new request resp := http.Response{Header: w.Header()} for _, cookie := range resp.Cookies() { req.AddCookie(cookie) } w = httptest.NewRecorder() handler.ServeHTTP(w, req) if w.Code != http.StatusFound { t.Errorf("Expected Second HTTP response code to be <%v>, got <%v>", http.StatusOK, w.Code) } if _, err := client.tickets.Read(ticket.Name); err != ErrInvalidTicket { t.Errorf("Expected tickets.Read error to be ErrInvalidTicket, got %v", err) } expected := fmt.Sprintf("%s://%s/logout", u.Scheme, u.Host) location := w.Header().Get("Location") if location != expected { t.Errorf("Expected Location to be %q, got %q", expected, location) } exists := false resp = http.Response{Header: w.Header()} for _, cookie := range resp.Cookies() { if cookie.Name != sessionCookieName { continue } exists = true if cookie.MaxAge != -1 { t.Errorf("Expected cookie max age to be -1, got <%v> %v", cookie.MaxAge, cookie) } } if !exists { t.Errorf("Expected session cookie to exist") } } func TestSingleLogOut(t *testing.T) { server := &TestServer{} ticket := server.NewTicket("ST-l8d6b51d8e9c4569345a30e2f904626a1066384db8694784a60b515d62f6c") ticket.Service = "http://example.com/" ticket.Username = "enoch.root" server.AddTicket(ticket) defer server.Close() ts := httptest.NewServer(server) defer ts.Close() u, _ := url.Parse(ts.URL) client := NewClient(&Options{ URL: u, }) handler := client.HandleFunc(func(w http.ResponseWriter, r *http.Request) { if !IsAuthenticated(r) { RedirectToLogin(w, r) return } fmt.Fprintln(w, "Welcome, you are logged in") }) // Log them in req, err := http.NewRequest("GET", "http://example.com/?ticket=ST-l8d6b51d8e9c4569345a30e2f904626a1066384db8694784a60b515d62f6c", nil) if err != nil { t.Error(err) } w := httptest.NewRecorder() handler.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("Expected First HTTP response code to be <%v>, got <%v>", http.StatusOK, w.Code) } if _, err := client.tickets.Read(ticket.Name); err != nil { t.Errorf("Expected tickets.Read error to be nil, got %v", err) } // Single Logout Request logoutRequest, err := xmlLogoutRequest(ticket.Name) if err != nil { t.Errorf("xmlLogoutRequest returned an error: %v", err) } postData := make(url.Values) postData.Set("logoutRequest", string(logoutRequest)) req, err = http.NewRequest("POST", "http://example.com/any/path/in/the/application", strings.NewReader(postData.Encode())) if err != nil { t.Error(err) } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") w = httptest.NewRecorder() handler.ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("Expected Second HTTP response code to be <%v>, got <%v>", http.StatusOK, w.Code) } if _, err := client.tickets.Read(ticket.Name); err != ErrInvalidTicket { t.Errorf("Expected tickets.Read error to be ErrInvalidTicket, got %v", err) } }
package endpoint import ( "context" "github.com/go-kit/kit/endpoint" "github.com/go-kit/kit/log" "github.com/mashenjun/courier/pkg/service" ) type Endpoints struct { PingEndpoint endpoint.Endpoint SubscribeEndpoint endpoint.Endpoint SendEndpoint endpoint.Endpoint CloseEndpoint endpoint.Endpoint } func New(srv service.Service, logger log.Logger) Endpoints { var eps Endpoints eps.PingEndpoint = MakePingEndpoint(srv) eps.SubscribeEndpoint = MakeSubscribeEndpoint(srv) eps.SendEndpoint = MakeSendEndpoint(srv) eps.CloseEndpoint = MakeCloseEndpoint(srv) // add logging middleware eps.PingEndpoint = LoggingMiddleware(log.With(logger, "method", "ping"))(eps.PingEndpoint) eps.SubscribeEndpoint = LoggingMiddleware(log.With(logger, "method", "subscribe"))(eps.SubscribeEndpoint) eps.SendEndpoint = LoggingMiddleware(log.With(logger, "method", "send"))(eps.SendEndpoint) eps.CloseEndpoint = LoggingMiddleware(log.With(logger, "method", "close"))(eps.CloseEndpoint) return eps } func MakePingEndpoint(srv service.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { pong, err := srv.Ping(ctx, struct {}{}) return pong, err } } func MakeSubscribeEndpoint(srv service.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { return srv.Subscribe(ctx, request.(service.SubscribeReq)) } } func MakeSendEndpoint(srv service.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { return srv.Send(ctx, request.(service.SendReq)) } } func MakeCloseEndpoint(srv service.Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { return srv.Close(ctx, request.(service.CloseReq)) } }
package main import ( "encoding/json" "io/ioutil" "os" "path/filepath" "github.com/otiai10/copy" ) const ( root = "./settings-to-copy" ) type config struct { UserPath string `json:"user_path"` BackupPath string `json:"backup_path"` FoldersToSave []string `json:"folders_to_save"` FoldersToIgnore []string `json:"folders_to_ignore"` } func main() { var configFiles []string // look for backup config files err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if filepath.Base(path) == "backup-config.json" { configFiles = append(configFiles, path) } return nil }) if err != nil { panic(err) } for _, configFile := range configFiles { backupFollowingConfigFile(configFile) } } func backupFollowingConfigFile(configFile string) error { file, err := ioutil.ReadFile(configFile) if err != nil { return err } data := config{} _ = json.Unmarshal([]byte(file), &data) toSkip := make(map[string]struct{}) for _, folderToSkip := range data.FoldersToIgnore { folderToSkip = filepath.Join(data.UserPath, folderToSkip) toSkip[folderToSkip] = struct{}{} } for _, folderToSave := range data.FoldersToSave { backupFolder := filepath.Join(data.BackupPath, folderToSave) folderToSave = filepath.Join(data.UserPath, folderToSave) err := copyFolderToBackupFolder(folderToSave, backupFolder, toSkip) if err != nil { return err } } return nil } func copyFolderToBackupFolder(folderToSave string, backupFolder string, toSkip map[string]struct{}) error { opt := copy.Options{Skip: func(src string) bool { if _, isToSkip := toSkip[src]; isToSkip { return true } return false }} err := copy.Copy(folderToSave, backupFolder, opt) if err != nil { return err } return nil }
package migrationutils import ( "crypto/rand" "os" "path/filepath" ) // RandomSlice returns a randomly filled byte array with length of given size func RandomSlice(size int) (out []byte) { r := make([]byte, size) _, err := rand.Read(r) // Note that err == nil only if we read len(b) bytes. if err != nil { panic(err) } return r } // RandomByte32 returns a randomly filled byte array with length of 32 func RandomByte32() (out [32]byte) { r := RandomSlice(32) copy(out[:], r[:32]) return } // CleanupDBFiles deletes all files in the provided path func CleanupDBFiles(prefix string) { files, err := filepath.Glob(prefix + "*") if err != nil { panic(err) } for _, f := range files { if err := os.RemoveAll(f); err != nil { panic(err) } } }
// 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 v20180930 import ( "github.com/tencentyun/tcecloud-sdk-go/tcecloud/common" tchttp "github.com/tencentyun/tcecloud-sdk-go/tcecloud/common/http" "github.com/tencentyun/tcecloud-sdk-go/tcecloud/common/profile" ) const APIVersion = "2018-09-30" type Client struct { common.Client } // Deprecated func NewClientWithSecretId(secretId, secretKey, region string) (client *Client, err error) { cpf := profile.NewClientProfile() client = &Client{} client.Init(region).WithSecretId(secretId, secretKey).WithProfile(cpf) return } func NewClient(credential *common.Credential, region string, clientProfile *profile.ClientProfile) (client *Client, err error) { client = &Client{} client.Init(region). WithCredential(credential). WithProfile(clientProfile) return } func NewAllBizTopoRequest() (request *AllBizTopoRequest) { request = &AllBizTopoRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "AllBizTopo") return } func NewAllBizTopoResponse() (response *AllBizTopoResponse) { response = &AllBizTopoResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 获取所有的业务树 func (c *Client) AllBizTopo(request *AllBizTopoRequest) (response *AllBizTopoResponse, err error) { if request == nil { request = NewAllBizTopoRequest() } response = NewAllBizTopoResponse() err = c.Send(request, response) return } func NewBindPkgRequest() (request *BindPkgRequest) { request = &BindPkgRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "BindPkg") return } func NewBindPkgResponse() (response *BindPkgResponse) { response = &BindPkgResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 解绑包 func (c *Client) BindPkg(request *BindPkgRequest) (response *BindPkgResponse, err error) { if request == nil { request = NewBindPkgRequest() } response = NewBindPkgResponse() err = c.Send(request, response) return } func NewBizTopoRequest() (request *BizTopoRequest) { request = &BizTopoRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "BizTopo") return } func NewBizTopoResponse() (response *BizTopoResponse) { response = &BizTopoResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 业务拓扑 func (c *Client) BizTopo(request *BizTopoRequest) (response *BizTopoResponse, err error) { if request == nil { request = NewBizTopoRequest() } response = NewBizTopoResponse() err = c.Send(request, response) return } func NewCreateStandConfigureRequest() (request *CreateStandConfigureRequest) { request = &CreateStandConfigureRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "CreateStandConfigure") return } func NewCreateStandConfigureResponse() (response *CreateStandConfigureResponse) { response = &CreateStandConfigureResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 新增标准化配置 func (c *Client) CreateStandConfigure(request *CreateStandConfigureRequest) (response *CreateStandConfigureResponse, err error) { if request == nil { request = NewCreateStandConfigureRequest() } response = NewCreateStandConfigureResponse() err = c.Send(request, response) return } func NewCreateTopoConfigRequest() (request *CreateTopoConfigRequest) { request = &CreateTopoConfigRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "CreateTopoConfig") return } func NewCreateTopoConfigResponse() (response *CreateTopoConfigResponse) { response = &CreateTopoConfigResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 创建配置 func (c *Client) CreateTopoConfig(request *CreateTopoConfigRequest) (response *CreateTopoConfigResponse, err error) { if request == nil { request = NewCreateTopoConfigRequest() } response = NewCreateTopoConfigResponse() err = c.Send(request, response) return } func NewDeleteStandConfigureRequest() (request *DeleteStandConfigureRequest) { request = &DeleteStandConfigureRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "DeleteStandConfigure") return } func NewDeleteStandConfigureResponse() (response *DeleteStandConfigureResponse) { response = &DeleteStandConfigureResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 删除标准化配置 func (c *Client) DeleteStandConfigure(request *DeleteStandConfigureRequest) (response *DeleteStandConfigureResponse, err error) { if request == nil { request = NewDeleteStandConfigureRequest() } response = NewDeleteStandConfigureResponse() err = c.Send(request, response) return } func NewDeleteTopoConfigRequest() (request *DeleteTopoConfigRequest) { request = &DeleteTopoConfigRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "DeleteTopoConfig") return } func NewDeleteTopoConfigResponse() (response *DeleteTopoConfigResponse) { response = &DeleteTopoConfigResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 删除配置 func (c *Client) DeleteTopoConfig(request *DeleteTopoConfigRequest) (response *DeleteTopoConfigResponse, err error) { if request == nil { request = NewDeleteTopoConfigRequest() } response = NewDeleteTopoConfigResponse() err = c.Send(request, response) return } func NewDeployOverviewRequest() (request *DeployOverviewRequest) { request = &DeployOverviewRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "DeployOverview") return } func NewDeployOverviewResponse() (response *DeployOverviewResponse) { response = &DeployOverviewResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 部署概览 func (c *Client) DeployOverview(request *DeployOverviewRequest) (response *DeployOverviewResponse, err error) { if request == nil { request = NewDeployOverviewRequest() } response = NewDeployOverviewResponse() err = c.Send(request, response) return } func NewEnumInfoRequest() (request *EnumInfoRequest) { request = &EnumInfoRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "EnumInfo") return } func NewEnumInfoResponse() (response *EnumInfoResponse) { response = &EnumInfoResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 对象枚举信息 func (c *Client) EnumInfo(request *EnumInfoRequest) (response *EnumInfoResponse, err error) { if request == nil { request = NewEnumInfoRequest() } response = NewEnumInfoResponse() err = c.Send(request, response) return } func NewGetModulePkgInfoRequest() (request *GetModulePkgInfoRequest) { request = &GetModulePkgInfoRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "GetModulePkgInfo") return } func NewGetModulePkgInfoResponse() (response *GetModulePkgInfoResponse) { response = &GetModulePkgInfoResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 获取模块绑定的文件包列表 func (c *Client) GetModulePkgInfo(request *GetModulePkgInfoRequest) (response *GetModulePkgInfoResponse, err error) { if request == nil { request = NewGetModulePkgInfoRequest() } response = NewGetModulePkgInfoResponse() err = c.Send(request, response) return } func NewGetModuleSchedulesListRequest() (request *GetModuleSchedulesListRequest) { request = &GetModuleSchedulesListRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "GetModuleSchedulesList") return } func NewGetModuleSchedulesListResponse() (response *GetModuleSchedulesListResponse) { response = &GetModuleSchedulesListResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 业务运维获取模块管理的定时任务列表 func (c *Client) GetModuleSchedulesList(request *GetModuleSchedulesListRequest) (response *GetModuleSchedulesListResponse, err error) { if request == nil { request = NewGetModuleSchedulesListRequest() } response = NewGetModuleSchedulesListResponse() err = c.Send(request, response) return } func NewGetPkgInsInfoRequest() (request *GetPkgInsInfoRequest) { request = &GetPkgInsInfoRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "GetPkgInsInfo") return } func NewGetPkgInsInfoResponse() (response *GetPkgInsInfoResponse) { response = &GetPkgInsInfoResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 获取文件包实例列表 func (c *Client) GetPkgInsInfo(request *GetPkgInsInfoRequest) (response *GetPkgInsInfoResponse, err error) { if request == nil { request = NewGetPkgInsInfoRequest() } response = NewGetPkgInsInfoResponse() err = c.Send(request, response) return } func NewGetSchedulesTaskInfoRequest() (request *GetSchedulesTaskInfoRequest) { request = &GetSchedulesTaskInfoRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "GetSchedulesTaskInfo") return } func NewGetSchedulesTaskInfoResponse() (response *GetSchedulesTaskInfoResponse) { response = &GetSchedulesTaskInfoResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // GetSchedulesTaskInfo func (c *Client) GetSchedulesTaskInfo(request *GetSchedulesTaskInfoRequest) (response *GetSchedulesTaskInfoResponse, err error) { if request == nil { request = NewGetSchedulesTaskInfoRequest() } response = NewGetSchedulesTaskInfoResponse() err = c.Send(request, response) return } func NewGetTaskInfoRequest() (request *GetTaskInfoRequest) { request = &GetTaskInfoRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "GetTaskInfo") return } func NewGetTaskInfoResponse() (response *GetTaskInfoResponse) { response = &GetTaskInfoResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 查询作业编排任务列表 func (c *Client) GetTaskInfo(request *GetTaskInfoRequest) (response *GetTaskInfoResponse, err error) { if request == nil { request = NewGetTaskInfoRequest() } response = NewGetTaskInfoResponse() err = c.Send(request, response) return } func NewGetWorkflowTemplateDetailRequest() (request *GetWorkflowTemplateDetailRequest) { request = &GetWorkflowTemplateDetailRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "GetWorkflowTemplateDetail") return } func NewGetWorkflowTemplateDetailResponse() (response *GetWorkflowTemplateDetailResponse) { response = &GetWorkflowTemplateDetailResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 获取作业编排 func (c *Client) GetWorkflowTemplateDetail(request *GetWorkflowTemplateDetailRequest) (response *GetWorkflowTemplateDetailResponse, err error) { if request == nil { request = NewGetWorkflowTemplateDetailRequest() } response = NewGetWorkflowTemplateDetailResponse() err = c.Send(request, response) return } func NewGetWorkflowTemplatesRequest() (request *GetWorkflowTemplatesRequest) { request = &GetWorkflowTemplatesRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "GetWorkflowTemplates") return } func NewGetWorkflowTemplatesResponse() (response *GetWorkflowTemplatesResponse) { response = &GetWorkflowTemplatesResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 获取作业编排 func (c *Client) GetWorkflowTemplates(request *GetWorkflowTemplatesRequest) (response *GetWorkflowTemplatesResponse, err error) { if request == nil { request = NewGetWorkflowTemplatesRequest() } response = NewGetWorkflowTemplatesResponse() err = c.Send(request, response) return } func NewModifyStandConfigureRequest() (request *ModifyStandConfigureRequest) { request = &ModifyStandConfigureRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "ModifyStandConfigure") return } func NewModifyStandConfigureResponse() (response *ModifyStandConfigureResponse) { response = &ModifyStandConfigureResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 更改标准化配置 func (c *Client) ModifyStandConfigure(request *ModifyStandConfigureRequest) (response *ModifyStandConfigureResponse, err error) { if request == nil { request = NewModifyStandConfigureRequest() } response = NewModifyStandConfigureResponse() err = c.Send(request, response) return } func NewNodeHostRequest() (request *NodeHostRequest) { request = &NodeHostRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "NodeHost") return } func NewNodeHostResponse() (response *NodeHostResponse) { response = &NodeHostResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 节点下所有主机 func (c *Client) NodeHost(request *NodeHostRequest) (response *NodeHostResponse, err error) { if request == nil { request = NewNodeHostRequest() } response = NewNodeHostResponse() err = c.Send(request, response) return } func NewNodeInfoRequest() (request *NodeInfoRequest) { request = &NodeInfoRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "NodeInfo") return } func NewNodeInfoResponse() (response *NodeInfoResponse) { response = &NodeInfoResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 获取节点基本信息 func (c *Client) NodeInfo(request *NodeInfoRequest) (response *NodeInfoResponse, err error) { if request == nil { request = NewNodeInfoRequest() } response = NewNodeInfoResponse() err = c.Send(request, response) return } func NewQueryAuditRequest() (request *QueryAuditRequest) { request = &QueryAuditRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "QueryAudit") return } func NewQueryAuditResponse() (response *QueryAuditResponse) { response = &QueryAuditResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 审计日志 func (c *Client) QueryAudit(request *QueryAuditRequest) (response *QueryAuditResponse, err error) { if request == nil { request = NewQueryAuditRequest() } response = NewQueryAuditResponse() err = c.Send(request, response) return } func NewQueryBizRequest() (request *QueryBizRequest) { request = &QueryBizRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "QueryBiz") return } func NewQueryBizResponse() (response *QueryBizResponse) { response = &QueryBizResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 查询业务 func (c *Client) QueryBiz(request *QueryBizRequest) (response *QueryBizResponse, err error) { if request == nil { request = NewQueryBizRequest() } response = NewQueryBizResponse() err = c.Send(request, response) return } func NewQueryModuleRequest() (request *QueryModuleRequest) { request = &QueryModuleRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "QueryModule") return } func NewQueryModuleResponse() (response *QueryModuleResponse) { response = &QueryModuleResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 查询模块 func (c *Client) QueryModule(request *QueryModuleRequest) (response *QueryModuleResponse, err error) { if request == nil { request = NewQueryModuleRequest() } response = NewQueryModuleResponse() err = c.Send(request, response) return } func NewQueryPkgListRequest() (request *QueryPkgListRequest) { request = &QueryPkgListRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "QueryPkgList") return } func NewQueryPkgListResponse() (response *QueryPkgListResponse) { response = &QueryPkgListResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 拉取织云包列表 func (c *Client) QueryPkgList(request *QueryPkgListRequest) (response *QueryPkgListResponse, err error) { if request == nil { request = NewQueryPkgListRequest() } response = NewQueryPkgListResponse() err = c.Send(request, response) return } func NewQueryPkgVersionListRequest() (request *QueryPkgVersionListRequest) { request = &QueryPkgVersionListRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "QueryPkgVersionList") return } func NewQueryPkgVersionListResponse() (response *QueryPkgVersionListResponse) { response = &QueryPkgVersionListResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 拉取织云包版本列表 func (c *Client) QueryPkgVersionList(request *QueryPkgVersionListRequest) (response *QueryPkgVersionListResponse, err error) { if request == nil { request = NewQueryPkgVersionListRequest() } response = NewQueryPkgVersionListResponse() err = c.Send(request, response) return } func NewQuerySetRequest() (request *QuerySetRequest) { request = &QuerySetRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "QuerySet") return } func NewQuerySetResponse() (response *QuerySetResponse) { response = &QuerySetResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 查询蓝鲸CMDB集群 func (c *Client) QuerySet(request *QuerySetRequest) (response *QuerySetResponse, err error) { if request == nil { request = NewQuerySetRequest() } response = NewQuerySetResponse() err = c.Send(request, response) return } func NewQueryTopoConfigRequest() (request *QueryTopoConfigRequest) { request = &QueryTopoConfigRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "QueryTopoConfig") return } func NewQueryTopoConfigResponse() (response *QueryTopoConfigResponse) { response = &QueryTopoConfigResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 查询配置 func (c *Client) QueryTopoConfig(request *QueryTopoConfigRequest) (response *QueryTopoConfigResponse, err error) { if request == nil { request = NewQueryTopoConfigRequest() } response = NewQueryTopoConfigResponse() err = c.Send(request, response) return } func NewQueryUuidPkgLastVersionRequest() (request *QueryUuidPkgLastVersionRequest) { request = &QueryUuidPkgLastVersionRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "QueryUuidPkgLastVersion") return } func NewQueryUuidPkgLastVersionResponse() (response *QueryUuidPkgLastVersionResponse) { response = &QueryUuidPkgLastVersionResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 查询机器的安装过某个包的上一版本 func (c *Client) QueryUuidPkgLastVersion(request *QueryUuidPkgLastVersionRequest) (response *QueryUuidPkgLastVersionResponse, err error) { if request == nil { request = NewQueryUuidPkgLastVersionRequest() } response = NewQueryUuidPkgLastVersionResponse() err = c.Send(request, response) return } func NewRunModuleWorkflowRequest() (request *RunModuleWorkflowRequest) { request = &RunModuleWorkflowRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "RunModuleWorkflow") return } func NewRunModuleWorkflowResponse() (response *RunModuleWorkflowResponse) { response = &RunModuleWorkflowResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 执行作业编排任务 func (c *Client) RunModuleWorkflow(request *RunModuleWorkflowRequest) (response *RunModuleWorkflowResponse, err error) { if request == nil { request = NewRunModuleWorkflowRequest() } response = NewRunModuleWorkflowResponse() err = c.Send(request, response) return } func NewRunStandardizationTaskRequest() (request *RunStandardizationTaskRequest) { request = &RunStandardizationTaskRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "RunStandardizationTask") return } func NewRunStandardizationTaskResponse() (response *RunStandardizationTaskResponse) { response = &RunStandardizationTaskResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 执行标准化任务 func (c *Client) RunStandardizationTask(request *RunStandardizationTaskRequest) (response *RunStandardizationTaskResponse, err error) { if request == nil { request = NewRunStandardizationTaskRequest() } response = NewRunStandardizationTaskResponse() err = c.Send(request, response) return } func NewSearchStandConfigureRequest() (request *SearchStandConfigureRequest) { request = &SearchStandConfigureRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "SearchStandConfigure") return } func NewSearchStandConfigureResponse() (response *SearchStandConfigureResponse) { response = &SearchStandConfigureResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 查询标准化配置 func (c *Client) SearchStandConfigure(request *SearchStandConfigureRequest) (response *SearchStandConfigureResponse, err error) { if request == nil { request = NewSearchStandConfigureRequest() } response = NewSearchStandConfigureResponse() err = c.Send(request, response) return } func NewSearchStandardizationHistoryRequest() (request *SearchStandardizationHistoryRequest) { request = &SearchStandardizationHistoryRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "SearchStandardizationHistory") return } func NewSearchStandardizationHistoryResponse() (response *SearchStandardizationHistoryResponse) { response = &SearchStandardizationHistoryResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 搜索标准化历史 func (c *Client) SearchStandardizationHistory(request *SearchStandardizationHistoryRequest) (response *SearchStandardizationHistoryResponse, err error) { if request == nil { request = NewSearchStandardizationHistoryRequest() } response = NewSearchStandardizationHistoryResponse() err = c.Send(request, response) return } func NewSearchStandardizationTasksRequest() (request *SearchStandardizationTasksRequest) { request = &SearchStandardizationTasksRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "SearchStandardizationTasks") return } func NewSearchStandardizationTasksResponse() (response *SearchStandardizationTasksResponse) { response = &SearchStandardizationTasksResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 查询标准化任务 func (c *Client) SearchStandardizationTasks(request *SearchStandardizationTasksRequest) (response *SearchStandardizationTasksResponse, err error) { if request == nil { request = NewSearchStandardizationTasksRequest() } response = NewSearchStandardizationTasksResponse() err = c.Send(request, response) return } func NewUnbindPkgRequest() (request *UnbindPkgRequest) { request = &UnbindPkgRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "UnbindPkg") return } func NewUnbindPkgResponse() (response *UnbindPkgResponse) { response = &UnbindPkgResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 解绑包 func (c *Client) UnbindPkg(request *UnbindPkgRequest) (response *UnbindPkgResponse, err error) { if request == nil { request = NewUnbindPkgRequest() } response = NewUnbindPkgResponse() err = c.Send(request, response) return } func NewUpdateHostRequest() (request *UpdateHostRequest) { request = &UpdateHostRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "UpdateHost") return } func NewUpdateHostResponse() (response *UpdateHostResponse) { response = &UpdateHostResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 修改主机 func (c *Client) UpdateHost(request *UpdateHostRequest) (response *UpdateHostResponse, err error) { if request == nil { request = NewUpdateHostRequest() } response = NewUpdateHostResponse() err = c.Send(request, response) return } func NewUpdateNodeRequest() (request *UpdateNodeRequest) { request = &UpdateNodeRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "UpdateNode") return } func NewUpdateNodeResponse() (response *UpdateNodeResponse) { response = &UpdateNodeResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 修改节点基本信息 func (c *Client) UpdateNode(request *UpdateNodeRequest) (response *UpdateNodeResponse, err error) { if request == nil { request = NewUpdateNodeRequest() } response = NewUpdateNodeResponse() err = c.Send(request, response) return } func NewUpdateTopoConfigRequest() (request *UpdateTopoConfigRequest) { request = &UpdateTopoConfigRequest{ BaseRequest: &tchttp.BaseRequest{}, } request.Init().WithApiInfo("opbiz", APIVersion, "UpdateTopoConfig") return } func NewUpdateTopoConfigResponse() (response *UpdateTopoConfigResponse) { response = &UpdateTopoConfigResponse{ BaseResponse: &tchttp.BaseResponse{}, } return } // 修改配置 func (c *Client) UpdateTopoConfig(request *UpdateTopoConfigRequest) (response *UpdateTopoConfigResponse, err error) { if request == nil { request = NewUpdateTopoConfigRequest() } response = NewUpdateTopoConfigResponse() err = c.Send(request, response) return }
// Copyright 2022 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package sessionstates import ( "crypto/x509" "encoding/json" "fmt" "path/filepath" "testing" "time" "github.com/pingcap/failpoint" "github.com/pingcap/tidb/util" "github.com/stretchr/testify/require" ) var ( mockNowOffset = "github.com/pingcap/tidb/sessionctx/sessionstates/mockNowOffset" ) func TestSetCertAndKey(t *testing.T) { tempDir := t.TempDir() certPath := filepath.Join(tempDir, "test1_cert.pem") keyPath := filepath.Join(tempDir, "test1_key.pem") createRSACert(t, certPath, keyPath) // no cert and no key _, err := CreateSessionToken("test_user") require.ErrorContains(t, err, "no certificate or key file") // no cert SetKeyPath(keyPath) _, err = CreateSessionToken("test_user") require.ErrorContains(t, err, "no certificate or key file") // no key SetKeyPath("") SetCertPath(certPath) _, err = CreateSessionToken("test_user") require.ErrorContains(t, err, "no certificate or key file") // both configured SetKeyPath(keyPath) _, err = CreateSessionToken("test_user") require.NoError(t, err) // When the key and cert don't match, it will still use the old pair. certPath2 := filepath.Join(tempDir, "test2_cert.pem") keyPath2 := filepath.Join(tempDir, "test2_key.pem") err = util.CreateCertificates(certPath2, keyPath2, 4096, x509.RSA, x509.UnknownSignatureAlgorithm) require.NoError(t, err) SetKeyPath(keyPath2) _, err = CreateSessionToken("test_user") require.NoError(t, err) } func TestSignAlgo(t *testing.T) { tests := []struct { pubKeyAlgo x509.PublicKeyAlgorithm signAlgos []x509.SignatureAlgorithm keySizes []int }{ { pubKeyAlgo: x509.RSA, signAlgos: []x509.SignatureAlgorithm{ x509.SHA256WithRSA, x509.SHA384WithRSA, x509.SHA512WithRSA, x509.SHA256WithRSAPSS, x509.SHA384WithRSAPSS, x509.SHA512WithRSAPSS, }, keySizes: []int{ 2048, 4096, }, }, { pubKeyAlgo: x509.ECDSA, signAlgos: []x509.SignatureAlgorithm{ x509.ECDSAWithSHA256, x509.ECDSAWithSHA384, x509.ECDSAWithSHA512, }, keySizes: []int{ 4096, }, }, { pubKeyAlgo: x509.Ed25519, signAlgos: []x509.SignatureAlgorithm{ x509.PureEd25519, }, keySizes: []int{ 4096, }, }, } tempDir := t.TempDir() certPath := filepath.Join(tempDir, "test1_cert.pem") keyPath := filepath.Join(tempDir, "test1_key.pem") SetKeyPath(keyPath) SetCertPath(certPath) for _, test := range tests { for _, signAlgo := range test.signAlgos { for _, keySize := range test.keySizes { msg := fmt.Sprintf("pubKeyAlgo: %s, signAlgo: %s, keySize: %d", test.pubKeyAlgo.String(), signAlgo.String(), keySize) err := util.CreateCertificates(certPath, keyPath, keySize, test.pubKeyAlgo, signAlgo) require.NoError(t, err, msg) ReloadSigningCert() _, tokenBytes := createNewToken(t, "test_user") err = ValidateSessionToken(tokenBytes, "test_user") require.NoError(t, err, msg) } } } } func TestVerifyToken(t *testing.T) { tempDir := t.TempDir() certPath := filepath.Join(tempDir, "test1_cert.pem") keyPath := filepath.Join(tempDir, "test1_key.pem") createRSACert(t, certPath, keyPath) SetKeyPath(keyPath) SetCertPath(certPath) // check succeeds token, tokenBytes := createNewToken(t, "test_user") err := ValidateSessionToken(tokenBytes, "test_user") require.NoError(t, err) // the token expires timeOffset := uint64(tokenLifetime + time.Minute) require.NoError(t, failpoint.Enable(mockNowOffset, fmt.Sprintf(`return(%d)`, timeOffset))) err = ValidateSessionToken(tokenBytes, "test_user") require.NoError(t, failpoint.Disable(mockNowOffset)) require.ErrorContains(t, err, "token expired") // the current user is different with the token err = ValidateSessionToken(tokenBytes, "another_user") require.ErrorContains(t, err, "username does not match") // forge the user name token.Username = "another_user" tokenBytes2, err := json.Marshal(token) require.NoError(t, err) err = ValidateSessionToken(tokenBytes2, "another_user") require.ErrorContains(t, err, "verification error") // forge the expire time token.Username = "test_user" token.ExpireTime = time.Now().Add(-time.Minute) tokenBytes2, err = json.Marshal(token) require.NoError(t, err) err = ValidateSessionToken(tokenBytes2, "test_user") require.ErrorContains(t, err, "verification error") } func TestCertExpire(t *testing.T) { tempDir := t.TempDir() certPath := filepath.Join(tempDir, "test1_cert.pem") keyPath := filepath.Join(tempDir, "test1_key.pem") createRSACert(t, certPath, keyPath) SetKeyPath(keyPath) SetCertPath(certPath) _, tokenBytes := createNewToken(t, "test_user") err := ValidateSessionToken(tokenBytes, "test_user") require.NoError(t, err) // replace the cert, but the old cert is still valid for a while certPath2 := filepath.Join(tempDir, "test2_cert.pem") keyPath2 := filepath.Join(tempDir, "test2_key.pem") createRSACert(t, certPath2, keyPath2) SetKeyPath(keyPath2) SetCertPath(certPath2) err = ValidateSessionToken(tokenBytes, "test_user") require.NoError(t, err) // the old cert expires and the original token is invalid timeOffset := uint64(LoadCertInterval) require.NoError(t, failpoint.Enable(mockNowOffset, fmt.Sprintf(`return(%d)`, timeOffset))) ReloadSigningCert() timeOffset += uint64(oldCertValidTime + time.Minute) require.NoError(t, failpoint.Enable(mockNowOffset, fmt.Sprintf(`return(%d)`, timeOffset))) err = ValidateSessionToken(tokenBytes, "test_user") require.ErrorContains(t, err, "verification error") // the new cert is not rotated but is reloaded _, tokenBytes = createNewToken(t, "test_user") ReloadSigningCert() err = ValidateSessionToken(tokenBytes, "test_user") require.NoError(t, err) // the cert is rotated but is still valid createRSACert(t, certPath2, keyPath2) timeOffset += uint64(LoadCertInterval) require.NoError(t, failpoint.Enable(mockNowOffset, fmt.Sprintf(`return(%d)`, timeOffset))) ReloadSigningCert() err = ValidateSessionToken(tokenBytes, "test_user") require.ErrorContains(t, err, "token expired") // after some time, it's not valid timeOffset += uint64(oldCertValidTime + time.Minute) require.NoError(t, failpoint.Enable(mockNowOffset, fmt.Sprintf(`return(%d)`, timeOffset))) err = ValidateSessionToken(tokenBytes, "test_user") require.NoError(t, failpoint.Disable(mockNowOffset)) require.ErrorContains(t, err, "verification error") } func TestLoadAndReadConcurrently(t *testing.T) { tempDir := t.TempDir() certPath := filepath.Join(tempDir, "test1_cert.pem") keyPath := filepath.Join(tempDir, "test1_key.pem") createRSACert(t, certPath, keyPath) SetKeyPath(keyPath) SetCertPath(certPath) deadline := time.Now().Add(5 * time.Second) var wg util.WaitGroupWrapper // the writer wg.Run(func() { for time.Now().Before(deadline) { createRSACert(t, certPath, keyPath) time.Sleep(time.Second) } }) // the loader for i := 0; i < 2; i++ { wg.Run(func() { for time.Now().Before(deadline) { ReloadSigningCert() time.Sleep(500 * time.Millisecond) } }) } // the reader for i := 0; i < 3; i++ { id := i wg.Run(func() { username := fmt.Sprintf("test_user_%d", id) for time.Now().Before(deadline) { _, tokenBytes := createNewToken(t, username) time.Sleep(10 * time.Millisecond) err := ValidateSessionToken(tokenBytes, username) require.NoError(t, err) time.Sleep(10 * time.Millisecond) } }) } wg.Wait() } func createNewToken(t *testing.T, username string) (*SessionToken, []byte) { token, err := CreateSessionToken(username) require.NoError(t, err) tokenBytes, err := json.Marshal(token) require.NoError(t, err) return token, tokenBytes } func createRSACert(t *testing.T, certPath, keyPath string) { err := util.CreateCertificates(certPath, keyPath, 4096, x509.RSA, x509.UnknownSignatureAlgorithm) require.NoError(t, err) }
package caryatid import ( "flag" "fmt" "os" "path" "runtime" "testing" ) const integrationTestDirName = "integration_tests" var ( _, thisfile, _, runtimeCallerOk = runtime.Caller(0) thisdir, _ = path.Split(thisfile) integrationTestDir = path.Join(thisdir, integrationTestDirName) ) func TestMain(m *testing.M) { var ( err error keepFlag = flag.Bool("k", false, fmt.Sprintf("Keep the %v directory after running integration tests", integrationTestDir)) ) // Have to check this here because we can't put logic outside of a function if !runtimeCallerOk { panic("Failed to detect thisdir using runtime.Caller()") } fmt.Println(fmt.Sprintf("Detected running the test directory as '%v'", thisdir)) err = os.MkdirAll(integrationTestDir, 0777) if err != nil { panic(fmt.Sprintf("Error trying to create test directory: %v", err)) } testRv := m.Run() // os.Exit() doesn't respect defer, so we can't have defered the call to os.RemoveAll() at creation time if *keepFlag { fmt.Println(fmt.Sprintf("Will not remove integraion test dir after tests complete\n%v", integrationTestDir)) } else { os.RemoveAll(integrationTestDir) } os.Exit(testRv) } func TestDetermineProvider(t *testing.T) { var ( err error resultProviderName string testProviderName = "TESTPROVIDER" testGzipArtifact = path.Join(integrationTestDir, "testDetProvGz.box") testTarArtifact = path.Join(integrationTestDir, "testDetProvTar.box") ) err = CreateTestBoxFile(testGzipArtifact, testProviderName, true) if err != nil { t.Fatal(fmt.Sprintf("Error trying to write input artifact file: %v", err)) } resultProviderName, err = DetermineProvider(testGzipArtifact) if err != nil { t.Fatal("Error trying to determine provider: ", err) } if resultProviderName != testProviderName { t.Fatal("Expected provider name does not match result provider name: ", testProviderName, resultProviderName) } err = CreateTestBoxFile(testTarArtifact, testProviderName, false) if err != nil { t.Fatal(fmt.Sprintf("Error trying to write input artifact file: %v", err)) } resultProviderName, err = DetermineProvider(testTarArtifact) if err != nil { t.Fatal("Error trying to determine provider: ", err) } if resultProviderName != testProviderName { t.Fatal("Expected provider name does not match result provider name: ", testProviderName, resultProviderName) } }
package model import ( "github.com/mongodb/mongo-go-driver/bson" "github.com/mongodb/mongo-go-driver/bson/primitive" "github.com/mongodb/mongo-go-driver/mongo" log "github.com/sirupsen/logrus" ) // SlugGenesis ... const ( SlugGenesis = "genesis" NameGenesis = "超级管理员" SlugAdmin = "admin" NameAdmin = "节点管理员" SlugOrg = "organization" NameOrg = "组织管理员" SlugMonitor = "monitor" NameMonitor = "监督" SlugUser = "user" NameUser = "普通用户" ) // Role ... type Role struct { Model `bson:",inline"` Name string `bson:"name"` Slug string `bson:"slug"` Description string `bson:"description"` Level int `bson:"level"` } // IsExist ... func (r *Role) IsExist() bool { if r.ID != primitive.NilObjectID { return IDExist(r) } return IsExist(r, bson.M{ "slug": r.Slug, }) } // CreateIfNotExist ... func (r *Role) CreateIfNotExist() error { return CreateIfNotExist(r) } // SetID ... func (r *Role) SetID(id primitive.ObjectID) { r.ID = id } // Create ... func (r *Role) Create() error { return InsertOne(r) } // Update ... func (r *Role) Update() error { return UpdateOne(r) } // Delete ... func (r *Role) Delete() error { return DeleteByID(r) } // Find ... func (r *Role) Find() error { if r.ID != primitive.NilObjectID { return FindByID(r) } return FindOne(r, bson.M{ "slug": r.Slug, }) } // All ... func (r *Role) All() ([]*Role, error) { var roles []*Role m := bson.M{} err := Find(r, m, func(cursor mongo.Cursor) error { log.Println(cursor.DecodeBytes()) var r Role err := cursor.Decode(&r) if err != nil { return err } roles = append(roles, &r) return nil }) return roles, err } func (r *Role) _Name() string { return "role" } // GetID ... func (r *Role) GetID() primitive.ObjectID { return r.ID } // Users ... func (r *Role) Users() ([]*User, error) { var users []*User ru := NewRoleUser() err := Find(ru, bson.M{ "role_id": r.ID, }, func(cursor mongo.Cursor) error { ru := NewRoleUser() err := cursor.Decode(ru) if err != nil { return err } user, err := ru.User() if err != nil { return err } users = append(users, user) return nil }) return users, err } // Permissions ... func (r *Role) Permissions() ([]*Permission, error) { var ps []*Permission pr := NewPermissionRole() err := Find(pr, bson.M{ "role_id": r.ID, }, func(cursor mongo.Cursor) error { ru := NewPermissionRole() err := cursor.Decode(ru) if err != nil { return err } p, err := ru.Permission() if err != nil { return err } ps = append(ps, p) return nil }) return ps, err } // CheckPermission ... func (r *Role) CheckPermission(permission *Permission) error { pr := NewPermissionRole() err := FindOne(pr, bson.M{ "role_id": r.ID, "permission_id": permission.ID, }) if err != nil { return err } return nil } // NewGenesisRole ... func NewGenesisRole() *Role { role := NewRole() role.Slug = SlugGenesis role.Name = NameGenesis role.Description = NameGenesis return role } // NewAdminRole ... func NewAdminRole() *Role { role := NewRole() role.Slug = SlugAdmin role.Name = NameAdmin role.Description = NameAdmin return role } // NewOrgRole ... func NewOrgRole() *Role { role := NewRole() role.Slug = SlugOrg role.Name = NameOrg role.Description = NameOrg return role } // NewMonitorRole ... func NewMonitorRole() *Role { role := NewRole() role.Slug = SlugMonitor role.Name = NameMonitor role.Description = NameMonitor return role } // NewGodRole 用户就是上帝 func NewGodRole() *Role { role := NewRole() role.Slug = SlugUser role.Name = NameUser role.Description = NameUser return role } // NewRole ... func NewRole() *Role { return &Role{ Model: model(), } }
package entities import ( "strconv" // "github.com/ventuary-lab/cache-updater/enums" ) const NEUTRINO_ORDERS_NAME = "f_neutrino_orders" type NeutrinoOrder struct { tableName struct{} `pg:"f_neutrino_orders"` OrderId *string `pg:"order_id,pk"` Currency, Owner, Status, Type *string Height uint64 OrderPrev *string `pg:"order_prev"` OrderNext *string `pg:"order_next"` RestTotal int64 `pg:"resttotal"` Total int64 `pg:"total"` IsFirst bool `pg:"is_first"` IsLast bool `pg:"is_last"` } func (no *NeutrinoOrder) GetKeys(regex *string) []string { id := unwrapDefaultRegex(regex, "([A-Za-z0-9]{40,50})") return []string { "order_height_" + id, "order_owner_" + id, "order_total_" + id, "order_filled_total_" + id, "order_status_" + id, "order_prev_" + id, "order_next_" + id, "orderbook", "order_first", "order_last", } } func (no *NeutrinoOrder) UpdateAll (nodeData *map[string]string) []*NeutrinoOrder { ids, resolveData, _ := UpdateAll(nodeData, no.GetKeys) result := make([]*NeutrinoOrder, len(ids)) for index, id := range ids { mappedModel := no.MapItemToModel(id, resolveData[id]) result[index] = mappedModel } return result } func (no *NeutrinoOrder) MapItemToModel (id string, item map[string]string) *NeutrinoOrder { height, _ := strconv.ParseInt(item["order_height_" + id], 10, 64) owner := item["order_owner_" + id] status := item["order_status_" + id] total, totalErr := strconv.ParseInt(item["order_total_" + id], 10, 64) filledtotal, filledtotalErr := strconv.ParseInt(item["order_filled_total_" + id], 10, 64) currency := "usd-nb" orderType := "liquidate" if totalErr != nil { total = 0 } if filledtotalErr != nil { filledtotal = 0 } rawOrderNext := item["order_next_" + id] rawOrderPrev := item["order_prev_" + id] var orderNext, orderPrev *string if rawOrderNext == "" { orderNext = nil } else { orderNext = &rawOrderNext } if rawOrderPrev == "" { orderPrev = nil } else { orderPrev = &rawOrderPrev } return &NeutrinoOrder{ OrderId: &id, Height: uint64(height), Currency: &currency, Owner: &owner, Total: total, Status: &status, RestTotal: total - filledtotal, Type: &orderType, OrderNext: orderNext, OrderPrev: orderPrev, IsFirst: id == item["order_first"], IsLast: id == item["order_last"], } }
package mill import ( "bytes" "fmt" "image" "image/color/palette" "image/draw" "image/gif" "image/jpeg" "image/png" "io" "strconv" "github.com/disintegration/imaging" "github.com/rwcarlsen/goexif/exif" ) // Format enumerates the type of images currently supported type Format string const ( JPEG Format = "jpeg" PNG Format = "png" GIF Format = "gif" ) type ImageSize struct { Width int Height int } type ImageResizeOpts struct { Width string `json:"width"` Quality string `json:"quality"` } type ImageResize struct { Opts ImageResizeOpts } func (m *ImageResize) ID() string { return "/image/resize" } func (m *ImageResize) Encrypt() bool { return true } func (m *ImageResize) Pin() bool { return false } func (m *ImageResize) AcceptMedia(media string) error { return accepts([]string{ "image/jpeg", "image/png", "image/gif", }, media) } func (m *ImageResize) Options(add map[string]interface{}) (string, error) { return hashOpts(m.Opts, add) } func (m *ImageResize) Mill(input []byte, name string) (*Result, error) { img, formatStr, err := image.Decode(bytes.NewReader(input)) if err != nil { return nil, err } format := Format(formatStr) clean, err := removeExif(bytes.NewReader(input), img, format) if err != nil { return nil, err } width, err := strconv.Atoi(m.Opts.Width) if err != nil { return nil, fmt.Errorf("invalid width: " + m.Opts.Width) } quality, err := strconv.Atoi(m.Opts.Quality) if err != nil { return nil, fmt.Errorf("invalid quality: " + m.Opts.Quality) } buff, rect, err := encodeImage(clean, format, width, quality) if err != nil { return nil, err } return &Result{ File: buff.Bytes(), Meta: map[string]interface{}{ "width": rect.Dx(), "height": rect.Dy(), }, }, nil } // removeExif strips exif data from an image func removeExif(reader io.Reader, img image.Image, format Format) (io.Reader, error) { if format == GIF { return reader, nil } exf, _ := exif.Decode(reader) var err error img, err = correctOrientation(img, exf) if err != nil { return nil, err } // re-encoding will remove any exif return encodeSingleImage(img, format) } // encodeImage creates a jpeg|gif from reader (quality applies to jpeg only) // NOTE: format is the reader image format, destination format is chosen accordingly. func encodeImage(reader io.Reader, format Format, width int, quality int) (*bytes.Buffer, *image.Rectangle, error) { buff := new(bytes.Buffer) var size image.Rectangle if format != GIF { // encode to png or jpeg img, _, err := image.Decode(reader) if err != nil { return nil, nil, err } if img.Bounds().Size().X < width { width = img.Bounds().Size().X } resized := imaging.Resize(img, width, 0, imaging.Lanczos) if format == PNG { if err = png.Encode(buff, resized); err != nil { return nil, nil, err } } else { if err = jpeg.Encode(buff, resized, &jpeg.Options{Quality: quality}); err != nil { return nil, nil, err } } size = resized.Rect } else { // encode to gif img, err := gif.DecodeAll(reader) if err != nil { return nil, nil, err } if len(img.Image) == 0 { return nil, nil, fmt.Errorf("gif does not have any frames") } firstFrame := img.Image[0].Bounds() if firstFrame.Dx() < width { width = firstFrame.Dx() } rect := image.Rect(0, 0, firstFrame.Dx(), firstFrame.Dy()) rgba := image.NewRGBA(rect) for index, frame := range img.Image { bounds := frame.Bounds() draw.Draw(rgba, bounds, frame, bounds.Min, draw.Over) img.Image[index] = imageToPaletted(imaging.Resize(rgba, width, 0, imaging.Lanczos)) } img.Config.Width = img.Image[0].Bounds().Dx() img.Config.Height = img.Image[0].Bounds().Dy() if err = gif.EncodeAll(buff, img); err != nil { return nil, nil, err } size = img.Image[0].Bounds() } return buff, &size, nil } // correctOrientation returns a copy of an image (jpg|png|gif) with exif removed func correctOrientation(img image.Image, exf *exif.Exif) (image.Image, error) { if exf == nil { return img, nil } orient, err := exf.Get(exif.Orientation) if err != nil && err != exif.TagNotPresentError(exif.Orientation) { return nil, err } if orient != nil { img = reverseOrientation(img, orient.String()) } else { img = reverseOrientation(img, "1") } return img, nil } // encodeSingleImage creates a reader from an image func encodeSingleImage(img image.Image, format Format) (*bytes.Reader, error) { writer := &bytes.Buffer{} var err error switch format { case JPEG: err = jpeg.Encode(writer, img, &jpeg.Options{Quality: 100}) case PNG: // NOTE: while PNGs don't technically have exif data, // they can contain meta data with sensitive info err = png.Encode(writer, img) default: err = fmt.Errorf("unrecognized image format") } if err != nil { return nil, err } return bytes.NewReader(writer.Bytes()), nil } // reverseOrientation transforms the given orientation to 1 func reverseOrientation(img image.Image, orientation string) *image.NRGBA { switch orientation { case "1": return imaging.Clone(img) case "2": return imaging.FlipV(img) case "3": return imaging.Rotate180(img) case "4": return imaging.Rotate180(imaging.FlipV(img)) case "5": return imaging.Rotate270(imaging.FlipV(img)) case "6": return imaging.Rotate270(img) case "7": return imaging.Rotate90(imaging.FlipV(img)) case "8": return imaging.Rotate90(img) } log.Warningf("unknown orientation %s, expected 1-8", orientation) return imaging.Clone(img) } // imageToPaletted convert Image to Paletted for GIF handling func imageToPaletted(img image.Image) *image.Paletted { b := img.Bounds() pm := image.NewPaletted(b, palette.Plan9) draw.FloydSteinberg.Draw(pm, b, img, image.ZP) return pm }
/* * @lc app=leetcode.cn id=142 lang=golang * * [142] 环形链表 II */ // @lc code=start /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ package main import "fmt" type ListNode struct { Val int Next *ListNode } func main() { v1 := &ListNode{Val: 1} v2 := &ListNode{Val: 2} v3 := &ListNode{Val: 3} v4 := &ListNode{Val: 4} v5 := &ListNode{Val: 5} v6 := &ListNode{Val: 6} v7 := &ListNode{Val: 7} v8 := &ListNode{Val: 8} v9 := &ListNode{Val: 9} v1.Next = v2 v2.Next = v3 v3.Next = v4 v4.Next = v5 v5.Next = v6 v6.Next = v7 v7.Next = v8 v8.Next = v9 v9.Next = v5 // print(v1) tmp := detectCycle(v1) fmt.Println(tmp.Val) } func print(head *ListNode) { for head != nil { fmt.Printf("%d ", head.Val) head = head.Next } fmt.Println() } func detectCycle(head *ListNode) *ListNode { if head == nil { return nil } p1 := head p2 := head for p2.Next != nil && p2.Next.Next != nil { p1 = p1.Next p2 = p2.Next.Next if p2 == nil { return nil } if p1 == p2 { // fmt.Println("here") p := head for p != p1 { // fmt.Println("there") p = p.Next p1 = p1.Next } return p } } return nil } // @lc code=end
package models type HealthConfig struct { Port int `yaml:"port"` }
package jwt import ( "github.com/gin-gonic/gin" ) const TokenKey = "Authorization" type GinJwtMiddleware struct { Signer JwtSigner Unauthorized interface{} } func (g *GinJwtMiddleware) Jwt(c *gin.Context) { token := c.Request.Header.Get(TokenKey) claims, isUpdate, err := g.Signer.Verification(token) if err != nil { c.JSON(200, g.Unauthorized) c.Abort() return } // 如果需要更新token if isUpdate { newToken, err := g.Signer.Refresh(claims) if err != nil { c.JSON(200, g.Unauthorized) c.Abort() return } c.Writer.Header().Set(TokenKey, newToken) } for k, v := range claims { c.Set(k, v) } }
// Copyright 2019 The go-interpreter Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !appengine package exec import ( "bytes" "runtime" "testing" "github.com/go-interpreter/wagon/disasm" "github.com/go-interpreter/wagon/exec/internal/compile" ops "github.com/go-interpreter/wagon/wasm/operators" ) func fakeNativeCompiler(t *testing.T) *nativeCompiler { t.Helper() return &nativeCompiler{ Builder: &mockInstructionBuilder{}, Scanner: &mockSequenceScanner{}, allocator: &mockPageAllocator{}, } } type mockSequenceScanner struct { emit []compile.CompilationCandidate } func (s *mockSequenceScanner) ScanFunc(bc []byte, meta *compile.BytecodeMetadata) ([]compile.CompilationCandidate, error) { return s.emit, nil } type mockPageAllocator struct{} func (a *mockPageAllocator) AllocateExec(asm []byte) (compile.NativeCodeUnit, error) { return nil, nil } func (a *mockPageAllocator) Close() error { return nil } type mockInstructionBuilder struct{} func (b *mockInstructionBuilder) Build(candidate compile.CompilationCandidate, code []byte, meta *compile.BytecodeMetadata) ([]byte, error) { return []byte{byte(candidate.Start), byte(candidate.End)}, nil } func TestNativeAsmStructureSetup(t *testing.T) { nc := fakeNativeCompiler(t) constInst, _ := ops.New(ops.I32Const) addInst, _ := ops.New(ops.I32Add) subInst, _ := ops.New(ops.I32Sub) setGlobalInst, _ := ops.New(ops.SetGlobal) wasm, err := disasm.Assemble([]disasm.Instr{ {Op: constInst, Immediates: []interface{}{int32(1)}}, {Op: constInst, Immediates: []interface{}{int32(1)}}, {Op: addInst}, {Op: setGlobalInst, Immediates: []interface{}{uint32(0)}}, {Op: constInst, Immediates: []interface{}{int32(8)}}, {Op: constInst, Immediates: []interface{}{int32(16)}}, {Op: constInst, Immediates: []interface{}{int32(4)}}, {Op: addInst}, {Op: subInst}, }) if err != nil { t.Fatal(err) } vm := &VM{ funcs: []function{ compiledFunction{ code: wasm, }, }, nativeBackend: nc, } vm.newFuncTable() // setup mocks. nc.Scanner.(*mockSequenceScanner).emit = []compile.CompilationCandidate{ // Sequence with single integer op - should not compiled. {Start: 0, End: 7, EndInstruction: 4, Metrics: compile.Metrics{IntegerOps: 1}}, // Sequence with two integer ops - should be emitted. {Start: 7, End: 15, StartInstruction: 4, EndInstruction: 10, Metrics: compile.Metrics{IntegerOps: 2}}, } if err := vm.tryNativeCompile(); err != nil { t.Fatalf("tryNativeCompile() failed: %v", err) } // Our scanner emitted two sequences. The first should not have resulted in // compilation, but the second should have. Lets check thats the case. fn := vm.funcs[0].(compiledFunction) if got, want := len(fn.asm), 1; got != want { t.Fatalf("len(fn.asm) = %d, want %d", got, want) } if got, want := int(fn.asm[0].resumePC), 15; got != want { t.Errorf("fn.asm[0].resumePC = %v, want %v", got, want) } // The function bytecode should have been modified to call wagon.nativeExec, // with the index of the block (0) following, and remaining bytes set to the // unreachable opcode. if got, want := fn.code[7], ops.WagonNativeExec; got != want { t.Errorf("fn.code[7] = %v, want %v", got, want) } if got, want := fn.code[8:12], []byte{0, 0, 0, 0}; !bytes.Equal(got, want) { t.Errorf("fn.code[8:12] = %v, want %v", got, want) } for i := 13; i < len(fn.code)-2; i++ { if fn.code[i] != ops.Unreachable { t.Errorf("fn.code[%d] = %v, want ops.Unreachable", i, fn.code[i]) } } } func TestBasicAMD64(t *testing.T) { if runtime.GOARCH != "amd64" || runtime.GOOS != "linux" { t.SkipNow() } constInst, _ := ops.New(ops.I64Const) addInst, _ := ops.New(ops.I64Add) code, meta := compile.Compile([]disasm.Instr{ {Op: constInst, Immediates: []interface{}{int32(100)}}, {Op: constInst, Immediates: []interface{}{int32(16)}}, {Op: constInst, Immediates: []interface{}{int32(4)}}, {Op: addInst}, {Op: addInst}, }) vm := &VM{ funcs: []function{ compiledFunction{ returns: true, maxDepth: 6, code: code, branchTables: meta.BranchTables, codeMeta: meta, }, }, ctx: context{ stack: make([]uint64, 0, 6), }, } vm.newFuncTable() _, be := nativeBackend() vm.nativeBackend = be originalLen := len(code) if err := vm.tryNativeCompile(); err != nil { t.Fatalf("tryNativeCompile() failed: %v", err) } fn := vm.funcs[0].(compiledFunction) if want := 1; len(fn.asm) != want { t.Fatalf("len(fn.asm) = %d, want %d", len(vm.funcs[0].(compiledFunction).asm), want) } if want := originalLen - 1; int(fn.asm[0].resumePC) != want { t.Errorf("fn.asm[0].stride = %v, want %v", fn.asm[0].resumePC, want) } // The function bytecode should have been modified to call wagon.nativeExec, // with the index of the block (0) following, and remaining bytes set to the // unreachable opcode. if want := ops.WagonNativeExec; fn.code[0] != want { t.Errorf("fn.code[0] = %v, want %v", fn.code[0], want) } if want := []byte{0, 0, 0, 0}; !bytes.Equal(fn.code[1:5], want) { t.Errorf("fn.code[1:5] = %v, want %v", fn.code[1:5], want) } for i := 6; i < 15; i++ { if fn.code[i] != ops.Unreachable { t.Errorf("fn.code[%d] = %v, want ops.Unreachable", i, fn.code[i]) } } fn.call(vm, 0) if len(vm.ctx.stack) != 1 || vm.ctx.stack[0] != 120 { t.Errorf("stack = %+v, want [120]", vm.ctx.stack) } }
package model import ( "strings" "time" "walletApi/src/common" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) //签名数据表 type SignData struct { Id int64 `orm:"auto" json:"id" description:"主键ID"` QrCode string `orm:"size(64)" json:"qrCode" description:"二维码标识"` //二维码 Address string `orm:"size(100)" json:"address" description:"钱包地址"` PubKey string `orm:"size(100)" json:"pubKey" description:"公钥"` SignType int `json:"signType" description:"签名类型 1、发布合约 2、实例化合约 3、升级合约 4、发行token 5、设置master、manager 6、manager签名确认 7、添加manager 8、替换manager 9 、删除manager 10、设置manager操作确认的阀值 11、设置发行token所需要的平台币 12、设置发布合约所需要的平台币 13、设置手续费返还规则"` TipMsg string `orm:"-" json:"tipMsg" description:"提示信息"` OriginData string `orm:"size(2000)" json:"originData" description:"签名原始数据"` SignData string `orm:"size(4000)" json:"signData" description:"签名数据"` Status int `json:"status" description:"状态 : 1、待签名 2、已签名 3、已确认 -1、已失效"` CreateTime time.Time `orm:"auto_now_add;type(datetime)" json:"createTime" description:"生成二维码日期"` SignTime time.Time `orm:"type(datetime)" json:"signTime" description:"签名日期"` RespResult string `orm:"size(2000)" json:"respResult" description:"底层链调用结果"` CreateTimeFmt string `orm:"-" json:"createTimeFmt" description:"日期格式化输出"` SignTimeFmt string `orm:"-" json:"signTimeFmt" description:"日期格式化输出"` ValidTime int64 `orm:"size(11)" json:"validTime" description:"有效时间戳"` LangType string `orm:"size(20)" json:"langType" description:"语言类型:zh: 中文 en:英文"` } type ContractRequest struct { Name string `json:"name" description:"合约名称"` ContractSymbol string `json:"contractSymbol" description:"合约英文间写"` Version string `json:"version" description:"合约版本"` Remark string `json:"remark" description:"备注"` CcUrl string `json:"ccUrl" description:"合约源码路径"` } func (q *SignData) TableName() string { return "t_sign_data" } //添加 func AddSignData(sign *SignData) error { o := orm.NewOrm() _, err := o.Insert(sign) return err } //修改 func UpdateSignData(sign *SignData) error { o := orm.NewOrm() var rSign SignData err := o.Raw("SELECT * FROM t_sign_data WHERE qr_code=?", sign.QrCode).QueryRow(&rSign) if rSign.Status == 3 { _, err = o.Raw("UPDATE t_sign_data SET resp_result=? WHERE qr_code=?", sign.RespResult, sign.QrCode).Exec() } else { _, err = o.Raw("UPDATE t_sign_data SET address = ?,pub_key=?,sign_data=?,status=?,sign_time=now(),resp_result=? WHERE status<>3 AND qr_code=?", sign.Address, sign.PubKey, sign.SignData, sign.Status, sign.RespResult, sign.QrCode).Exec() } return err } //查询 func GetSingInfo(qrCode string) (*SignData, error) { o := orm.NewOrm() sign := new(SignData) err := o.Raw("SELECT * FROM t_sign_data WHERE qr_code = ?", qrCode).QueryRow(sign) if err != nil { return nil, err } timeUnix := time.Now().Unix() if timeUnix > sign.ValidTime { //已失效 ret, err := o.Raw("UPDATE t_sign_data SET status=-1 WHERE status<>3 AND qr_code=?", qrCode).Exec() if err == nil { num, _ := ret.RowsAffected() if num > 0 { sign.Status = -1 } } } sign.CreateTimeFmt = common.FormatTime(sign.CreateTime) sign.SignTimeFmt = common.FormatTime(sign.SignTime) return sign, nil } func GetAllSignInfos(address string, pageSize, pageNo int) map[string]interface{} { o := orm.NewOrm() qs := o.QueryTable("t_sign_data") cond := orm.NewCondition() addrs := strings.Split(address, ",") for _, addr := range addrs { cond = cond.Or("Address__exact", addr) } cond = cond.AndNot("Status__exact", -1) qs = qs.SetCond(cond) resultMap := make(map[string]interface{}) cnt, err := qs.Count() if err == nil && cnt > 0 { signs := make([]SignData, 0) _, err := qs.Limit(pageSize, (pageNo-1)*pageSize).OrderBy("-SignTime").All(&signs) if err == nil && len(signs) > 0 { resultMap["total"] = cnt for i := range signs { signs[i].CreateTimeFmt = common.FormatTime(signs[i].CreateTime) signs[i].SignTimeFmt = common.FormatTime(signs[i].SignTime) } resultMap["data"] = signs return resultMap } } resultMap["total"] = 0 resultMap["data"] = nil return resultMap } //初始化模型 func init() { // 需要在init中注册定义的model orm.RegisterModel(new(SignData)) }
package main import ( "encoding/json" "fmt" "github.com/levigross/grequests" ) func main() { netReceiveAmount, confirmations, err := ZecBlocksChainCheck(0.02588889, "t1aZ2DGuiokCxHVfb4cGQqXghxy9hUpE6xQ", "t1J7StFmqay9sWHMtUhXseLRMzvm1vLE7i7") if err != nil { fmt.Println("request failed...") return } fmt.Println(fmt.Sprintf("net_withdraw_amount: %f, confirmations: %d", netReceiveAmount, confirmations)) } // HTTPGet asfdadsf. func HTTPGet(url string, requestOptions *grequests.RequestOptions) (response []byte, err error) { httpResponse, err := grequests.Get(url, requestOptions) if err == nil { if httpResponse.StatusCode == 200 { response = httpResponse.Bytes() } } return } type script struct { Addresses []string `json:"addresses"` } type vout struct { Value float64 `json:"value"` ScriptPubkey script `json:"scriptPubkey"` } type address struct { Vout []vout `json:"vout"` } // ZecBlocksChainCheck . func ZecBlocksChainCheck(withdrawAmount float64, originalAddress string, targetAddress string) (netWithdrawAmount float64, confirmations int64, err error) { url := fmt.Sprintf("https://api.zcha.in/v2/mainnet/accounts/%s/recv?limit=20&offset=0", targetAddress) bData, err := HTTPGet(url, nil) if err != nil { fmt.Println("error:", err) return } // fmt.Println(string(bData[:])) var add []address err = json.Unmarshal(bData, &add) if err != nil { fmt.Println("error:", err) return } // fmt.Printf("%+v\n", add) for i := 0; i < len(add); i++ { out := add[i].Vout // fmt.Printf("%+v\n", out) for j := 0; j < len(out); j++ { // fmt.Printf("%+v\n", out[j]) if out[j].Value == withdrawAmount && out[j].ScriptPubkey.Addresses[0] == targetAddress { netWithdrawAmount = out[j].Value return } } } return }
/* description : ex0101 prints the name of the command that invoked it and its command-line arguments author : Tom Geudens (https://github.com/tomgeudens/) modified : 2017/07/18 */ package main import ( "fmt" "os" "strings" ) func main() { fmt.Println("invoking command = " + os.Args[0]) fmt.Println("command-line arguments = " + strings.Join(os.Args[1:], " ")) }
package main import ( "fmt" "github.com/karantin2020/csvgen/parser" "os" ) var ( pp = parser.Parser{AllStructs: true} ) func main() { fname := "./fixture" fInfo, err := os.Stat(fname) if err != nil { return } // pp := parser.Parser{AllStructs: true} if err := pp.Parse(fname, fInfo.IsDir()); err != nil { return } fmt.Println("Parse Error:", pp.Error) fmt.Println(pp.StructMap) fmt.Printf("%+v\n", pp.Structs) }
// Note the Library is a Portfolio Specific Library, Should Not be used on Schemes // Monte Carlo Simulation Algorithm : // The inputs to the process are: // 1) Start capital // 2) Annual mean return taken from the (10 portfolios) // 3) Annual mean standard deviation // 4) Number of years (observations) // 5) Number of simulations = 500 => This is what is configurable // // Logic: // // 1) Generate monthly mean return = annual return / 12 // 2) Generate monthly standard deviation = annual standard deviation / (square root 12) // 3) Generate N random numbers where N = (number of years * number of simulations) with mean = mean return, std = standard deviation in a matrix // Which has number of years as rows and number of simulations as columns // // Investment.matrix[number of years, number of simulation] // // 4) Define NAV as another matrix with number of years as rows and number of simulations as columns // // Loop: // For i = 1: number of years // NAV (i+1) = NAV (i) * Investment.matrix[i,] package main import ( "fmt" "math" "math/rand" "time" "sync" "runtime" "sort" ) type MonteCarlo struct { GraphType string StartCapital float64 AnnualMeanReturn float64 AnnualReturnStandardDeviation float64 Years int Time time.Time // Config Parameters NumberOfSimulations int AnnualInflation float64 AnnualInflationStandardDeviation float64 MonthlyWithdrawals float64 MonthlyMeanReturn float64 MonthlyRetStdDev float64 MonthlyInflation float64 MonthlyInfStdDev float64 MonthlyInvestmentReturns [][]float64 MonthlyInflationReturns [][]float64 CombinedMatrix [][]float64 StartCapitalMatrix [][]float64 NAVMatrix [][]float64 // Scenario Ranges GoodRange []float64 AverageRange []float64 BadRange []float64 NumberOfObservations int } var MoCa MonteCarlo var Result = make(map[string][][]interface{}) var wg sync.WaitGroup func init() { runtime.GOMAXPROCS(runtime.NumCPU()) // Dummy initialization MoCa = MonteCarlo{ Time: time.Now(), GraphType: "yearly", StartCapital: 10000, AnnualMeanReturn: 0.1, AnnualReturnStandardDeviation: 0.1, Years: 5, NumberOfSimulations: 500, AnnualInflation: 0.025, AnnualInflationStandardDeviation: 0.015, MonthlyWithdrawals: 0.0, GoodRange: []float64{0.8, 1.0}, AverageRange: []float64{0.4, 0.7}, BadRange: []float64{0.0, 0.3}, } } func (MoCa *MonteCarlo) prediction() { MoCa.convert_annual_values_to_monthly_values() MoCa.calculate_number_of_observations() wg.Add(2) go MoCa.simulate_monthly_invest_return() go MoCa.simulate_monthly_inflation_return() wg.Wait() wg.Add(2) go MoCa.generate_combined_random_matrix() go MoCa.generate_matrix_for_start_capital() wg.Wait() MoCa.simulate_nav_values_for_portfolio() MoCa.replace_all_values_less_than_zero_to_mean_of_row_in_nav_matrix() MoCa.generate_scenario_distribution() } func main() { fmt.Println("Monte Carlo Algorithm") fmt.Println("=====================") MoCa.prediction() //time_taken := time.Since(MoCa.Time) //fmt.Println(MoCa, Result, "Time Taken", time_taken) fmt.Println(Result) } func (MoCa *MonteCarlo) convert_annual_values_to_monthly_values() { MoCa.MonthlyMeanReturn = MoCa.AnnualMeanReturn / 12 MoCa.MonthlyRetStdDev = MoCa.AnnualReturnStandardDeviation / math.Sqrt(12) MoCa.MonthlyInflation = MoCa.AnnualInflation / 12 MoCa.MonthlyInfStdDev = MoCa.AnnualInflationStandardDeviation / math.Sqrt(12) } func (MoCa *MonteCarlo) calculate_number_of_observations() { if MoCa.GraphType == "daily" { MoCa.NumberOfObservations = MoCa.Years * 365 } else { MoCa.NumberOfObservations = MoCa.Years * 12 } } func (MoCa *MonteCarlo) simulate_monthly_invest_return() { random_norm_size := MoCa.NumberOfSimulations * MoCa.NumberOfObservations random_norm := generate_random_norm(random_norm_size, MoCa.MonthlyMeanReturn, MoCa.MonthlyRetStdDev) MoCa.MonthlyInvestmentReturns = make([][]float64, MoCa.NumberOfObservations) for i, j, k := 0, MoCa.NumberOfSimulations, 0; k < MoCa.NumberOfObservations; i += MoCa.NumberOfSimulations { MoCa.MonthlyInvestmentReturns[k] = make([]float64, MoCa.NumberOfSimulations) MoCa.MonthlyInvestmentReturns[k] = random_norm[i:j] k++ j += MoCa.NumberOfSimulations } wg.Done() } func (MoCa *MonteCarlo) simulate_monthly_inflation_return() { random_norm_size := MoCa.NumberOfSimulations * MoCa.NumberOfObservations random_norm := generate_random_norm(random_norm_size, MoCa.MonthlyInflation, MoCa.MonthlyInfStdDev) MoCa.MonthlyInflationReturns = make([][]float64, MoCa.NumberOfObservations) for i, j, k := 0, MoCa.NumberOfSimulations, 0; k < MoCa.NumberOfObservations; i += MoCa.NumberOfSimulations { MoCa.MonthlyInflationReturns[k] = make([]float64, MoCa.NumberOfSimulations) MoCa.MonthlyInflationReturns[k] = random_norm[i:j] k++ j += MoCa.NumberOfSimulations } wg.Done() } func generate_random_norm(n int, mean, std_dev float64) []float64 { random_norm := make([]float64, n) for i := 0; i < n; i++ { random_norm[i] = (rand.NormFloat64() * std_dev) + mean } return random_norm } func (MoCa *MonteCarlo) generate_combined_random_matrix() { MoCa.CombinedMatrix = make([][]float64, MoCa.NumberOfObservations) for i := 0 ; i < MoCa.NumberOfObservations ; i++ { MoCa.CombinedMatrix[i] = make([]float64, MoCa.NumberOfSimulations) for j := 0; j < MoCa.NumberOfSimulations ; j++ { MoCa.CombinedMatrix[i][j] = 1 + MoCa.MonthlyInvestmentReturns[i][j] - MoCa.MonthlyInflationReturns[i][j] } } wg.Done() } func (MoCa *MonteCarlo) generate_matrix_for_start_capital() { MoCa.StartCapitalMatrix = make([][]float64, MoCa.NumberOfObservations) for i := 0 ; i < MoCa.NumberOfObservations ; i++ { MoCa.StartCapitalMatrix[i] = make([]float64, MoCa.NumberOfSimulations) for j := 0; j < MoCa.NumberOfSimulations ; j++ { MoCa.StartCapitalMatrix[i][j] = MoCa.StartCapital } } wg.Done() } func (MoCa *MonteCarlo) simulate_nav_values_for_portfolio() { MoCa.NAVMatrix = MoCa.StartCapitalMatrix for i := 1; i < MoCa.NumberOfObservations; i++ { for j := 0; j < MoCa.NumberOfSimulations; j++ { MoCa.NAVMatrix[i][j] = (MoCa.NAVMatrix[i][j] * MoCa.CombinedMatrix[i][j]) - MoCa.MonthlyWithdrawals } sort.Float64s(MoCa.NAVMatrix[i]) } } func average(xs[]float64)float64 { total:=0.0 total_positive := 0 for _,v:=range xs { if v > 0 { total +=v total_positive++ } } return total/float64(total_positive) } func (MoCa *MonteCarlo) replace_all_values_less_than_zero_to_mean_of_row_in_nav_matrix() { for i := 1; i < MoCa.NumberOfObservations; i++ { for j := 0; j < MoCa.NumberOfSimulations; j++ { mean := average(MoCa.NAVMatrix[i]) if MoCa.NAVMatrix[i][j] < 0 { MoCa.NAVMatrix[i][j] = mean } } } // Skip first row //MoCa.NAVMatrix = MoCa.NAVMatrix[1:] } //--------------------------------------------------------------------------- // Scenario Distribution //--------------------------------------------------------------------------- func (MoCa *MonteCarlo) generate_scenario_distribution() { Result["good_scenario"] = make([][]interface{}, MoCa.NumberOfObservations) Result["average_scenario"] = make([][]interface{}, MoCa.NumberOfObservations) Result["bad_scenario"] = make([][]interface{}, MoCa.NumberOfObservations) for i := 0; i < MoCa.NumberOfObservations; i++ { Result["good_scenario"][i] = make([]interface{}, 2) Result["average_scenario"][i] = make([]interface{}, 2) Result["bad_scenario"][i] = make([]interface{}, 2) Result["good_scenario"][i][0] = int32(last_day_of_month(i).Unix()) Result["average_scenario"][i][0] = int32(last_day_of_month(i).Unix()) Result["bad_scenario"][i][0] = int32(last_day_of_month(i).Unix()) Result["good_scenario"][i][1] = average(MoCa.NAVMatrix[i][int(float64(MoCa.NumberOfSimulations) * MoCa.GoodRange[0]):int(float64(MoCa.NumberOfSimulations) * MoCa.GoodRange[1])]) Result["average_scenario"][i][1] = average(MoCa.NAVMatrix[i][int(float64(MoCa.NumberOfSimulations) * MoCa.AverageRange[0]):int(float64(MoCa.NumberOfSimulations) * MoCa.AverageRange[1])]) Result["bad_scenario"][i][1] = average(MoCa.NAVMatrix[i][int(float64(MoCa.NumberOfSimulations) * MoCa.BadRange[0]):int(float64(MoCa.NumberOfSimulations) * MoCa.BadRange[1])]) } } func last_day_of_month(inc_month int) time.Time { ist, _ := time.LoadLocation("Asia/Kolkata") now := time.Now().In(ist) currentYear, currentMonth, _ := now.Date() currentLocation := now.Location() newMonth := int(currentMonth) + inc_month // Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time firstOfMonth := time.Date(currentYear, time.Month(newMonth), 1, 0, 0, 0, 0, currentLocation) return firstOfMonth.AddDate(0, 1, -1) }
package gettime import ( "log" "time" ) const ( TimeFormart = "2006-01-02 15:04:05" TimeFarmart1 = "20060102" ) func GetNowTime() (starttime string, stoptime string) { now := time.Now() yesterday, err := time.ParseDuration("-48h") if err != nil { log.Println(err) } start := now.Add(yesterday).Format(TimeFormart) current := now.Format(TimeFormart) return start, current } func YESTERDAY() (yesday string) { NowTime := time.Now() //fmt.Println(NowTime) diff, err := time.ParseDuration("-24h") if err != nil { log.Println(err) } yesday = NowTime.Add(diff).Format(TimeFarmart1) //fmt.Println(yesterday) return yesday } func TWODAYS() (one, two string) { NowTime := time.Now() //fmt.Println(NowTime) diff_one, err := time.ParseDuration("-48h") if err != nil { log.Println(err) } diff_two, err := time.ParseDuration("-72h") if err != nil { log.Println(err) } one = NowTime.Add(diff_one).Format(TimeFarmart1) two = NowTime.Add(diff_two).Format(TimeFarmart1) //fmt.Println(yesterday) return one, two }
package account // NotFoundError represents account not found error type NotFoundError struct{} func (anf NotFoundError) Error() string { return "Account Not Found" } // AlreadyExistError represents account already exist error type AlreadyExistError struct{} func (aee AlreadyExistError) Error() string { return "Account already exist" }
package iface import "github.com/PuerkitoBio/goquery" type IParse interface { //传入待爬地址,返回文档对象 GetDocument(url string) (*goquery.Document, error) //传入需要解析的文档对象 ParseHtml(doc *goquery.Document) }
package receiver import ( l "github.com/b2wdigital/goignite/pkg/log" natsce "github.com/cloudevents/sdk-go/v2/protocol/nats" "github.com/nats-io/nats.go" ) func NewSender(conn *nats.Conn, subject string) (*natsce.Sender, error) { sender, err := natsce.NewSenderFromConn(conn, subject) if err != nil { l.Fatalf("failed to create transport: %s", err.Error()) } return sender, nil }
package main import "testing" func TestDaoOfficer(t *testing.T) { u := &Officer{} u.Officerid = 0 u.Name = "niko" u.Gender = 1 u.IdentityCard = "441599" u.Phone = "17396157096" u.Address = "升升公寓" u.Position = "学生" d := NewDaoOfficer() defer d.Close() d.Insert(u) }
/* The MIT License (MIT) Copyright (c) 2019 Microsoft Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package controllers import ( "math/rand" "os" "path/filepath" "testing" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" db "github.com/xinsnake/databricks-sdk-golang" dbazure "github.com/xinsnake/databricks-sdk-golang/azure" databricksv1alpha1 "github.com/microsoft/azure-databricks-operator/api/v1alpha1" "k8s.io/client-go/kubernetes/scheme" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/envtest" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/log/zap" // +kubebuilder:scaffold:imports ) // These tests use Ginkgo (BDD-style Go testing framework). Refer to // http://onsi.github.io/ginkgo/ to learn more about Ginkgo. var k8sClient client.Client var k8sManager ctrl.Manager var testEnv *envtest.Environment var apiClient dbazure.DBClient func TestAPIs(t *testing.T) { RegisterFailHandler(Fail) RunSpecsWithDefaultAndCustomReporters(t, "Controller Suite", []Reporter{envtest.NewlineReporter{}}) } var _ = BeforeSuite(func(done Done) { logf.SetLogger(zap.LoggerTo(GinkgoWriter, true)) By("bootstrapping test environment") t := true if os.Getenv("TEST_USE_EXISTING_CLUSTER") == "true" { testEnv = &envtest.Environment{ UseExistingCluster: &t, } } else { testEnv = &envtest.Environment{ CRDDirectoryPaths: []string{filepath.Join("..", "config", "crd", "bases")}, } } cfg, err := testEnv.Start() Expect(err).ToNot(HaveOccurred()) Expect(cfg).ToNot(BeNil()) err = scheme.AddToScheme(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) err = databricksv1alpha1.AddToScheme(scheme.Scheme) Expect(err).NotTo(HaveOccurred()) // +kubebuilder:scaffold:scheme k8sManager, err = ctrl.NewManager(cfg, ctrl.Options{ Scheme: scheme.Scheme, }) Expect(err).ToNot(HaveOccurred()) host, token := os.Getenv("DATABRICKS_HOST"), os.Getenv("DATABRICKS_TOKEN") if host == "" || token == "" { Fail("Missing environment variable required for tests. DATABRICKS_HOST and DATABRICKS_TOKEN must both be set.") } var apiClient dbazure.DBClient apiClient.Init(db.DBClientOption{ Host: host, Token: token, }) err = (&SecretScopeReconciler{ Client: k8sManager.GetClient(), Log: ctrl.Log.WithName("controllers").WithName("SecretScope"), Recorder: k8sManager.GetEventRecorderFor("secretscope-controller"), APIClient: apiClient, }).SetupWithManager(k8sManager) Expect(err).ToNot(HaveOccurred()) err = (&DjobReconciler{ Client: k8sManager.GetClient(), Log: ctrl.Log.WithName("controllers").WithName("Djob"), Recorder: k8sManager.GetEventRecorderFor("djob-controller"), APIClient: apiClient, }).SetupWithManager(k8sManager) Expect(err).ToNot(HaveOccurred()) err = (&RunReconciler{ Client: k8sManager.GetClient(), Log: ctrl.Log.WithName("controllers").WithName("Run"), Recorder: k8sManager.GetEventRecorderFor("run-controller"), APIClient: apiClient, }).SetupWithManager(k8sManager) Expect(err).ToNot(HaveOccurred()) err = (&DclusterReconciler{ Client: k8sManager.GetClient(), Log: ctrl.Log.WithName("controllers").WithName("Run"), Recorder: k8sManager.GetEventRecorderFor("dcluster-controller"), APIClient: apiClient, }).SetupWithManager(k8sManager) Expect(err).ToNot(HaveOccurred()) err = (&DbfsBlockReconciler{ Client: k8sManager.GetClient(), Log: ctrl.Log.WithName("controllers").WithName("Run"), Recorder: k8sManager.GetEventRecorderFor("dbfsblock-controller"), APIClient: apiClient, }).SetupWithManager(k8sManager) Expect(err).ToNot(HaveOccurred()) err = (&WorkspaceItemReconciler{ Client: k8sManager.GetClient(), Log: ctrl.Log.WithName("controllers").WithName("Run"), Recorder: k8sManager.GetEventRecorderFor("workspaceitem-controller"), APIClient: apiClient, }).SetupWithManager(k8sManager) Expect(err).ToNot(HaveOccurred()) go func() { err = k8sManager.Start(ctrl.SetupSignalHandler()) Expect(err).ToNot(HaveOccurred()) }() k8sClient = k8sManager.GetClient() Expect(k8sClient).ToNot(BeNil()) close(done) }, 60) var _ = AfterSuite(func() { By("tearing down the test environment") gexec.KillAndWait(5 * time.Second) err := testEnv.Stop() Expect(err).ToNot(HaveOccurred()) }) const charset = "abcdefghijklmnopqrstuvwxyz" func randomStringWithCharset(length int, charset string) string { var seededRand = rand.New(rand.NewSource(time.Now().UnixNano())) b := make([]byte, length) for i := range b { b[i] = charset[seededRand.Intn(len(charset))] } return string(b) }
package model import ( "github.com/alec-z/interests-back/util" ) type ItemsInput struct { Amount float64 `json:"amount" form:"amount" query:"amount"` AnnualInterest float64 `json:"annualInterest" form:"annualInterest" query:"annualInterest"` Period int `json:"period" form:"period" query:"period"` } func (i *ItemsInput) GetItems() float64{ return util.CalItemFromInterest(i.Amount, i.AnnualInterest / 100.0, i.Period) }
package context import ( "sync" ) const defaultScope = "" var currentContext Context var lock sync.RWMutex type dependencyRequest struct { Type interface{} Waiter chan interface{} Scope string } type Context interface { Ask(interfaceNil interface{}) chan interface{} Reg(interfaceNil interface{}, constructor func() interface{}, request ...*dependencyRequest) RegScoped(scope string, interfaceNil interface{}, constructor func() interface{}, request ...*dependencyRequest) AskScoped(scope string, interfaceNil interface{}) chan interface{} GetUnresolvedRequests() []*dependencyRequest } func Dep[T any]() *dependencyRequest { return &dependencyRequest{(*T)(nil), make(chan interface{}, 1), defaultScope} } func DepScoped[T any](scope string) *dependencyRequest { return &dependencyRequest{(*T)(nil), make(chan interface{}, 1), scope} } func SetContext(context Context) { lock.Lock() defer lock.Unlock() currentContext = context } func GetContext() Context { lock.RLock() defer lock.RUnlock() return currentContext } func Ask[T any](ctx Context) T { return (<-ctx.Ask((*T)(nil))).(T) } func Reg[T any](ctx Context, constructor func() interface{}, request ...*dependencyRequest) { ctx.Reg((*T)(nil), constructor, request...) } func RegScoped[T any](ctx Context, scope string, interfaceNil interface{}, constructor func() interface{}, request ...*dependencyRequest) { ctx.RegScoped(scope, (*T)(nil), constructor, request...) } func AskScoped[T any](ctx Context, scope string) T { return (<-ctx.AskScoped(scope, (*T)(nil))).(T) }
package goproxmoxapi_test import ( "strings" "testing" "github.com/lnxbil/goproxmoxapi" ) func TestVersionAPI(t *testing.T) { t.Parallel() c, err := goproxmoxapi.New(GetProxmoxAccess()) if err != nil { t.Log(c) t.Error(err) } // test version number of the PVE pvever, err := goproxmoxapi.GetVersion(c) if err != nil { t.Error(err) } if !strings.HasPrefix(pvever.Version, "5.1") { t.Error("Should run this test against pve version 5.x, yet you have '" + pvever.Version + "'") } }
package business import ( "fmt" "github.com/police-police-mashed-potatoes/console" "github.com/police-police-mashed-potatoes/data" ) type FetchCycle struct { hours int location string crimeType string } func (f FetchCycle) Start(config EventsConfig) { fmt.Println("Thank you for using Police Police Mashed Potatoes!") fmt.Println("Initiating scan...") fmt.Println("") entries := data.LoadFromAPI( config.Hours, config.Location, config.CrimeType, ) entries = SanitizeEntries(entries) console.OutputResult(entries) }
package com import ( "database/sql" "reflect" ) /** `*@数据库查询映射为对象 */ func CreateObjectResultSet(rows *sql.Rows,objects ...interface{}) { columns, err := rows.Columns(); if (nil != err) { panic("get data Columns err ,on method:CreateObjectResultSet"); } var clen int = len(columns); values := make([]interface{}, clen); dataResult := make([]interface{}, clen); for i, _ := range values { dataResult[i] = &values[i] } //只支持一个结构的映射 if (len(objects) > 1) { panic("support one struct only now"); } var etyp reflect.Type; var v reflect.Value; v =reflect.ValueOf(objects[0]); i :=reflect.Indirect(v); etyp =i.Type().Elem() typ :=etyp if typ.Kind() == reflect.Ptr { typ = typ.Elem() } var newIndValue reflect.Value = i; var num int = 0; for rows.Next() { ind := reflect.New(etyp) scanErr := rows.Scan(dataResult...); if scanErr != nil { panic("scan data Columns err;"); } for t, col := range columns { v := values[t]; var field reflect.Value = ind.Elem().FieldByName(CamelString(col)); if(field.CanSet()){ vd :=reflect.ValueOf(v).Type().Kind(); switch vd{ case reflect.Slice: b, ok := v.([]byte) if ok { field.SetString( string(b)) } else { field.SetString(""); } case reflect.Int64: field.SetInt(reflect.ValueOf(v).Int()) } } } newIndValue = reflect.Append(newIndValue, reflect.Indirect(ind)) num++; } if (num > 0) { i.Set(newIndValue); } }
package goney // Currency represents an ISO4217 currency type Currency struct { Code string Precision int32 } func (c Currency) String() string { return c.Code } // Find returns the currency having provided code, if found, // or XXX (= no currency) if not found func Find(code string) Currency { for _, curr := range currencies { if curr.Code == code { return curr } } return XXX } var currencies = []Currency{ AED, AFN, ALL, AMD, ANG, AOA, ARS, AUD, AWG, AZN, BAM, BBD, BDT, BGN, BHD, BIF, BMD, BND, BOB, BOV, BRL, BSD, BTN, BWP, BYN, BZD, CAD, CDF, CHE, CHF, CHW, CLF, CLP, CNY, COP, COU, CRC, CUC, CUP, CVE, CZK, DJF, DKK, DOP, DZD, EGP, ERN, ETB, EUR, FJD, FKP, GBP, GEL, GHS, GIP, GMD, GNF, GTQ, GYD, HKD, HNL, HRK, HTG, HUF, IDR, ILS, INR, IQD, IRR, ISK, JMD, JOD, JPY, KES, KGS, KHR, KMF, KPW, KRW, KWD, KYD, KZT, LAK, LBP, LKR, LRD, LSL, LYD, MAD, MDL, MGA, MKD, MMK, MNT, MOP, MRU, MUR, MVR, MWK, MXN, MXV, MYR, MZN, NAD, NGN, NIO, NOK, NPR, NZD, OMR, PAB, PEN, PGK, PHP, PKR, PLN, PYG, QAR, RON, RSD, RUB, RWF, SAR, SBD, SCR, SDG, SEK, SGD, SHP, SLL, SOS, SRD, SSP, STN, SVC, SYP, SZL, THB, TJS, TMT, TND, TOP, TRY, TTD, TWD, TZS, UAH, UGX, USD, USN, UYI, UYU, UYW, UZS, VES, VND, VUV, WST, XAF, XAG, XAU, XBA, XBB, XBC, XBD, XCD, XDR, XOF, XPD, XPF, XPT, XSU, XTS, XUA, XXX, YER, ZAR, ZMW, ZWL, } // AED United Arab Emirates dirham var AED = Currency{"AED", 2} // AFN Afghan afghani var AFN = Currency{"AFN", 2} // ALL Albanian lek var ALL = Currency{"ALL", 2} // AMD Armenian dram var AMD = Currency{"AMD", 2} // ANG Netherlands Antillean guilder var ANG = Currency{"ANG", 2} // AOA Angolan kwanza var AOA = Currency{"AOA", 2} // ARS Argentine peso var ARS = Currency{"ARS", 2} // AUD Australian dollar var AUD = Currency{"AUD", 2} // AWG Aruban florin var AWG = Currency{"AWG", 2} // AZN Azerbaijani manat var AZN = Currency{"AZN", 2} // BAM Bosnia and Herzegovina convertible mark var BAM = Currency{"BAM", 2} // BBD Barbados dollar var BBD = Currency{"BBD", 2} // BDT Bangladeshi taka var BDT = Currency{"BDT", 2} // BGN Bulgarian lev var BGN = Currency{"BGN", 2} // BHD Bahraini dinar var BHD = Currency{"BHD", 3} // BIF Burundian franc var BIF = Currency{"BIF", 0} // BMD Bermudian dollar var BMD = Currency{"BMD", 2} // BND Brunei dollar var BND = Currency{"BND", 2} // BOB Boliviano var BOB = Currency{"BOB", 2} // BOV Bolivian Mvdol (funds code) var BOV = Currency{"BOV", 2} // BRL Brazilian real var BRL = Currency{"BRL", 2} // BSD Bahamian dollar var BSD = Currency{"BSD", 2} // BTN Bhutanese ngultrum var BTN = Currency{"BTN", 2} // BWP Botswana pula var BWP = Currency{"BWP", 2} // BYN Belarusian ruble var BYN = Currency{"BYN", 2} // BZD Belize dollar var BZD = Currency{"BZD", 2} // CAD Canadian dollar var CAD = Currency{"CAD", 2} // CDF Congolese franc var CDF = Currency{"CDF", 2} // CHE WIR Euro (complementary currency) var CHE = Currency{"CHE", 2} // CHF Swiss franc var CHF = Currency{"CHF", 2} // CHW WIR Franc (complementary currency) var CHW = Currency{"CHW", 2} // CLF Unidad de Fomento (funds code) var CLF = Currency{"CLF", 4} // CLP Chilean peso var CLP = Currency{"CLP", 0} // CNY Renminbi (Chinese) yuan var CNY = Currency{"CNY", 2} // COP Colombian peso var COP = Currency{"COP", 2} // COU Unidad de Valor Real (UVR) (funds code) var COU = Currency{"COU", 2} // CRC Costa Rican colon var CRC = Currency{"CRC", 2} // CUC Cuban convertible peso var CUC = Currency{"CUC", 2} // CUP Cuban peso var CUP = Currency{"CUP", 2} // CVE Cape Verdean escudo var CVE = Currency{"CVE", 2} // CZK Czech koruna var CZK = Currency{"CZK", 2} // DJF Djiboutian franc var DJF = Currency{"DJF", 0} // DKK Danish krone var DKK = Currency{"DKK", 2} // DOP Dominican peso var DOP = Currency{"DOP", 2} // DZD Algerian dinar var DZD = Currency{"DZD", 2} // EGP Egyptian pound var EGP = Currency{"EGP", 2} // ERN Eritrean nakfa var ERN = Currency{"ERN", 2} // ETB Ethiopian birr var ETB = Currency{"ETB", 2} // EUR Euro var EUR = Currency{"EUR", 2} // FJD Fiji dollar var FJD = Currency{"FJD", 2} // FKP Falkland Islands pound var FKP = Currency{"FKP", 2} // GBP Pound sterling var GBP = Currency{"GBP", 2} // GEL Georgian lari var GEL = Currency{"GEL", 2} // GHS Ghanaian cedi var GHS = Currency{"GHS", 2} // GIP Gibraltar pound var GIP = Currency{"GIP", 2} // GMD Gambian dalasi var GMD = Currency{"GMD", 2} // GNF Guinean franc var GNF = Currency{"GNF", 0} // GTQ Guatemalan quetzal var GTQ = Currency{"GTQ", 2} // GYD Guyanese dollar var GYD = Currency{"GYD", 2} // HKD Hong Kong dollar var HKD = Currency{"HKD", 2} // HNL Honduran lempira var HNL = Currency{"HNL", 2} // HRK Croatian kuna var HRK = Currency{"HRK", 2} // HTG Haitian gourde var HTG = Currency{"HTG", 2} // HUF Hungarian forint var HUF = Currency{"HUF", 2} // IDR Indonesian rupiah var IDR = Currency{"IDR", 2} // ILS Israeli new shekel var ILS = Currency{"ILS", 2} // INR Indian rupee var INR = Currency{"INR", 2} // IQD Iraqi dinar var IQD = Currency{"IQD", 3} // IRR Iranian rial var IRR = Currency{"IRR", 2} // ISK Icelandic króna var ISK = Currency{"ISK", 0} // JMD Jamaican dollar var JMD = Currency{"JMD", 2} // JOD Jordanian dinar var JOD = Currency{"JOD", 3} // JPY Japanese yen var JPY = Currency{"JPY", 0} // KES Kenyan shilling var KES = Currency{"KES", 2} // KGS Kyrgyzstani som var KGS = Currency{"KGS", 2} // KHR Cambodian riel var KHR = Currency{"KHR", 2} // KMF Comoro franc var KMF = Currency{"KMF", 0} // KPW North Korean won var KPW = Currency{"KPW", 2} // KRW South Korean won var KRW = Currency{"KRW", 0} // KWD Kuwaiti dinar var KWD = Currency{"KWD", 3} // KYD Cayman Islands dollar var KYD = Currency{"KYD", 2} // KZT Kazakhstani tenge var KZT = Currency{"KZT", 2} // LAK Lao kip var LAK = Currency{"LAK", 2} // LBP Lebanese pound var LBP = Currency{"LBP", 2} // LKR Sri Lankan rupee var LKR = Currency{"LKR", 2} // LRD Liberian dollar var LRD = Currency{"LRD", 2} // LSL Lesotho loti var LSL = Currency{"LSL", 2} // LYD Libyan dinar var LYD = Currency{"LYD", 3} // MAD Moroccan dirham var MAD = Currency{"MAD", 2} // MDL Moldovan leu var MDL = Currency{"MDL", 2} // MGA 11] Malagasy ariary var MGA = Currency{"MGA", 2} // MKD Macedonian denar var MKD = Currency{"MKD", 2} // MMK Myanmar kyat var MMK = Currency{"MMK", 2} // MNT Mongolian tögrög var MNT = Currency{"MNT", 2} // MOP Macanese pataca var MOP = Currency{"MOP", 2} // MRU Mauritanian ouguiya var MRU = Currency{"MRU", 2} // MUR Mauritian rupee var MUR = Currency{"MUR", 2} // MVR Maldivian rufiyaa var MVR = Currency{"MVR", 2} // MWK Malawian kwacha var MWK = Currency{"MWK", 2} // MXN Mexican peso var MXN = Currency{"MXN", 2} // MXV Mexican Unidad de Inversion (UDI) (funds code) var MXV = Currency{"MXV", 2} // MYR Malaysian ringgit var MYR = Currency{"MYR", 2} // MZN Mozambican metical var MZN = Currency{"MZN", 2} // NAD Namibian dollar var NAD = Currency{"NAD", 2} // NGN Nigerian naira var NGN = Currency{"NGN", 2} // NIO Nicaraguan córdoba var NIO = Currency{"NIO", 2} // NOK Norwegian krone var NOK = Currency{"NOK", 2} // NPR Nepalese rupee var NPR = Currency{"NPR", 2} // NZD New Zealand dollar var NZD = Currency{"NZD", 2} // OMR Omani rial var OMR = Currency{"OMR", 3} // PAB Panamanian balboa var PAB = Currency{"PAB", 2} // PEN Peruvian sol var PEN = Currency{"PEN", 2} // PGK Papua New Guinean kina var PGK = Currency{"PGK", 2} // PHP Philippine peso var PHP = Currency{"PHP", 2} // PKR Pakistani rupee var PKR = Currency{"PKR", 2} // PLN Polish złoty var PLN = Currency{"PLN", 2} // PYG Paraguayan guaraní var PYG = Currency{"PYG", 0} // QAR Qatari riyal var QAR = Currency{"QAR", 2} // RON Romanian leu var RON = Currency{"RON", 2} // RSD Serbian dinar var RSD = Currency{"RSD", 2} // RUB Russian ruble var RUB = Currency{"RUB", 2} // RWF Rwandan franc var RWF = Currency{"RWF", 0} // SAR Saudi riyal var SAR = Currency{"SAR", 2} // SBD Solomon Islands dollar var SBD = Currency{"SBD", 2} // SCR Seychelles rupee var SCR = Currency{"SCR", 2} // SDG Sudanese pound var SDG = Currency{"SDG", 2} // SEK Swedish krona/kronor var SEK = Currency{"SEK", 2} // SGD Singapore dollar var SGD = Currency{"SGD", 2} // SHP Saint Helena pound var SHP = Currency{"SHP", 2} // SLL Sierra Leonean leone var SLL = Currency{"SLL", 2} // SOS Somali shilling var SOS = Currency{"SOS", 2} // SRD Surinamese dollar var SRD = Currency{"SRD", 2} // SSP South Sudanese pound var SSP = Currency{"SSP", 2} // STN São Tomé and Príncipe dobra var STN = Currency{"STN", 2} // SVC Salvadoran colón var SVC = Currency{"SVC", 2} // SYP Syrian pound var SYP = Currency{"SYP", 2} // SZL Swazi lilangeni var SZL = Currency{"SZL", 2} // THB Thai baht var THB = Currency{"THB", 2} // TJS Tajikistani somoni var TJS = Currency{"TJS", 2} // TMT Turkmenistan manat var TMT = Currency{"TMT", 2} // TND Tunisian dinar var TND = Currency{"TND", 3} // TOP Tongan paʻanga var TOP = Currency{"TOP", 2} // TRY Turkish lira var TRY = Currency{"TRY", 2} // TTD Trinidad and Tobago dollar var TTD = Currency{"TTD", 2} // TWD New Taiwan dollar var TWD = Currency{"TWD", 2} // TZS Tanzanian shilling var TZS = Currency{"TZS", 2} // UAH Ukrainian hryvnia var UAH = Currency{"UAH", 2} // UGX Ugandan shilling var UGX = Currency{"UGX", 0} // USD United States dollar var USD = Currency{"USD", 2} // USN United States dollar (next day) (funds code) var USN = Currency{"USN", 2} // UYI Uruguay Peso en Unidades Indexadas (URUIURUI) (funds code) var UYI = Currency{"UYI", 0} // UYU Uruguayan peso var UYU = Currency{"UYU", 2} // UYW Unidad previsional[15] var UYW = Currency{"UYW", 4} // UZS Uzbekistan som var UZS = Currency{"UZS", 2} // VES Venezuelan bolívar soberano var VES = Currency{"VES", 2} // VND Vietnamese đồng var VND = Currency{"VND", 0} // VUV Vanuatu vatu var VUV = Currency{"VUV", 0} // WST Samoan tala var WST = Currency{"WST", 2} // XAF CFA franc BEAC var XAF = Currency{"XAF", 0} // XAG Silver (one troy var XAG = Currency{"XAG", 0} // XAU Gold (one troy var XAU = Currency{"XAU", 0} // XBA European Composite Unit (EURCO) (bond market) var XBA = Currency{"XBA", 0} // XBB European Monetary Unit (E.M.U.-6) (bond market) var XBB = Currency{"XBB", 0} // XBC European Unit of Account 9 (E.U.A.-9) (bond market) var XBC = Currency{"XBC", 0} // XBD European Unit of Account 17 (E.U.A.-17) (bond market) var XBD = Currency{"XBD", 0} // XCD East Caribbean dollar var XCD = Currency{"XCD", 2} // XDR Special drawing rights var XDR = Currency{"XDR", 0} // XOF CFA franc BCEAO var XOF = Currency{"XOF", 0} // XPD Palladium var XPD = Currency{"XPD", 0} // XPF CFP franc var XPF = Currency{"XPF", 0} // XPT Platinum var XPT = Currency{"XPT", 0} // XSU SUCRE var XSU = Currency{"XSU", 0} // XTS Code reserved for testing var XTS = Currency{"XTS", 0} // XUA ADB Unit of Account var XUA = Currency{"XUA", 0} // XXX No currency var XXX = Currency{"XXX", 0} // YER Yemeni rial var YER = Currency{"YER", 2} // ZAR South African rand var ZAR = Currency{"ZAR", 2} // ZMW Zambian kwacha var ZMW = Currency{"ZMW", 2} // ZWL Zimbabwean dollar var ZWL = Currency{"ZWL", 2}
package controllers type TestController struct { BaseController } func (c *TestController)Fire() { c.Layout = "index.html" c.TplName = "demo.html" c.Data["frameName"] = c.URLFor("TestController.FireFrame") } func (c *TestController)FireFrame() { c.TplName = "demo/fire.html" } func (c *TestController)Jellyfish() { c.Layout = "index.html" c.TplName = "demo.html" c.Data["frameName"] = c.URLFor("TestController.JellyfishFrame") } func (c *TestController)JellyfishFrame() { c.TplName = "demo/jellyfish.html" }
// Package xaction provides core functionality for the AIStore extended actions. /* * Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. */ package xaction import ( "errors" "fmt" "strconv" "time" "github.com/NVIDIA/aistore/3rdparty/atomic" "github.com/NVIDIA/aistore/3rdparty/glog" "github.com/NVIDIA/aistore/cluster" "github.com/NVIDIA/aistore/cmn" "github.com/NVIDIA/aistore/cmn/cos" "github.com/NVIDIA/aistore/cmn/debug" "github.com/NVIDIA/aistore/fs" "github.com/NVIDIA/aistore/nl" ) type ( XactBase struct { id string kind string bck cmn.Bck sutime atomic.Int64 eutime atomic.Int64 objects atomic.Int64 bytes atomic.Int64 abrt chan struct{} aborted atomic.Bool notif *NotifXact } XactMarked struct { Xact cluster.Xact Interrupted bool } ErrXactExpired struct { // return it if called (right) after self-termination msg string } ) var IncInactive func() ////////////// // XactBase - partially implements Xact interface ////////////// func (xact *XactBase) InitBase(id, kind string, bck *cmn.Bck) { debug.AssertMsg(cos.IsValidUUID(id) || isValidRebID(id), id) debug.AssertMsg(IsValidKind(kind), kind) xact.id, xact.kind = id, kind xact.abrt = make(chan struct{}) if bck != nil { xact.bck = *bck } xact.setStartTime(time.Now()) } func (xact *XactBase) ID() string { return xact.id } func (xact *XactBase) Kind() string { return xact.kind } func (xact *XactBase) Bck() cmn.Bck { return xact.bck } func (xact *XactBase) Finished() bool { return xact.eutime.Load() != 0 } func (xact *XactBase) ChanAbort() <-chan struct{} { return xact.abrt } func (xact *XactBase) Aborted() bool { return xact.aborted.Load() } func (xact *XactBase) AbortedAfter(d time.Duration) (aborted bool) { sleep := cos.CalcProbeFreq(d) aborted = xact.Aborted() for elapsed := time.Duration(0); elapsed < d && !aborted; elapsed += sleep { time.Sleep(sleep) aborted = xact.Aborted() } return } // count all the way to duration; reset and adjust every time activity is detected func (xact *XactBase) Quiesce(d time.Duration, cb cluster.QuiCB) cluster.QuiRes { var ( idle, total time.Duration sleep = cos.CalcProbeFreq(d) dur = d ) if xact.Aborted() { return cluster.QuiAborted } wait: for idle < dur { time.Sleep(sleep) if xact.Aborted() { return cluster.QuiAborted } total += sleep switch res := cb(total); res { case cluster.QuiInactive: idle += sleep case cluster.QuiActive: idle = 0 // reset dur = cos.MinDuration(dur+sleep, 2*d) // bump up to 2x initial case cluster.QuiDone: return cluster.QuiDone case cluster.QuiTimeout: break wait } } return cluster.QuiTimeout } func (xact *XactBase) String() string { prefix := xact.Kind() if xact.bck.Name != "" { prefix += "@" + xact.bck.Name } if !xact.Finished() { return fmt.Sprintf("%s(%q)", prefix, xact.ID()) } var ( stime = xact.StartTime() stimestr = cos.FormatTimestamp(stime) etime = xact.EndTime() d = etime.Sub(stime) ) return fmt.Sprintf("%s(%q) started %s ended %s (%v)", prefix, xact.ID(), stimestr, cos.FormatTimestamp(etime), d) } func (xact *XactBase) StartTime() time.Time { u := xact.sutime.Load() if u != 0 { return time.Unix(0, u) } return time.Time{} } func (xact *XactBase) setStartTime(s time.Time) { xact.sutime.Store(s.UnixNano()) } func (xact *XactBase) EndTime() time.Time { u := xact.eutime.Load() if u != 0 { return time.Unix(0, u) } return time.Time{} } // upon completion, all xactions: // - atomically set end-time // - optionally, notify listener(s) // - optionally, refresh local capacity stats, etc. func (xact *XactBase) _setEndTime(err error) { xact.eutime.Store(time.Now().UnixNano()) // notifications if n := xact.Notif(); n != nil { nl.OnFinished(n, err) } xactDtor := XactsDtor[xact.kind] if xactDtor.RefreshCap { if cs, _ := fs.RefreshCapStatus(nil, nil); cs.Err != nil { glog.Error(cs.Err) // log warning } } IncInactive() } func (xact *XactBase) Notif() (n cluster.Notif) { if xact.notif == nil { return } return xact.notif } func (xact *XactBase) AddNotif(n cluster.Notif) { debug.Assert(xact.notif == nil) // currently, "add" means "set" xact.notif = n.(*NotifXact) debug.Assert(xact.notif.Xact != nil && xact.notif.F != nil) debug.Assert(!n.Upon(cluster.UponProgress) || xact.notif.P != nil) } func (*XactBase) Renew() {} func (xact *XactBase) Abort() { if !xact.aborted.CAS(false, true) { glog.Infof("already aborted: " + xact.String()) return } close(xact.abrt) glog.Infof("ABORT: " + xact.String()) } func (xact *XactBase) Finish(err error) { if xact.eutime.Load() == 0 { xact._setEndTime(err) } } func (*XactBase) Result() (interface{}, error) { return nil, errors.New("getting result is not implemented") } func (xact *XactBase) ObjCount() int64 { return xact.objects.Load() } func (xact *XactBase) ObjectsInc() int64 { return xact.objects.Inc() } func (xact *XactBase) ObjectsAdd(cnt int64) int64 { return xact.objects.Add(cnt) } func (xact *XactBase) BytesCount() int64 { return xact.bytes.Load() } func (xact *XactBase) BytesAdd(size int64) int64 { return xact.bytes.Add(size) } func (xact *XactBase) Stats() cluster.XactStats { return &BaseXactStats{ IDX: xact.ID(), KindX: xact.Kind(), StartTimeX: xact.StartTime(), EndTimeX: xact.EndTime(), BckX: xact.Bck(), ObjCountX: xact.ObjCount(), BytesCountX: xact.BytesCount(), AbortedX: xact.Aborted(), } } // errors func NewErrXactExpired(msg string) *ErrXactExpired { return &ErrXactExpired{msg: msg} } func (e *ErrXactExpired) Error() string { return e.msg } func IsErrXactExpired(err error) bool { _, ok := err.(*ErrXactExpired); return ok } // RebID helpers func RebID2S(id int64) string { return fmt.Sprintf("g%d", id) } func S2RebID(id string) (int64, error) { return strconv.ParseInt(id[1:], 10, 64) } func isValidRebID(id string) bool { _, err := S2RebID(id); return err == nil } func CompareRebIDs(a, b string) int { if ai, err := S2RebID(a); err != nil { debug.AssertMsg(false, a) } else if bi, err := S2RebID(b); err != nil { debug.AssertMsg(false, b) } else { if ai < bi { return -1 } if ai > bi { return 1 } } return 0 }
package main import ( "archive/zip" "bufio" "fmt" "github.com/cavaliercoder/grab" "github.com/garyburd/redigo/redis" "io" "log" "net/http" "os" "path/filepath" "regexp" "sync" "time" ) // Get html page that has list of files and return the // actual URL for the webpage (after the redirect) func writeHTMLAndReturnRequestURL() (URL string) { output, err := os.Create("./files.txt") if err != nil { fmt.Println(err) } defer output.Close() resp, err := http.Get("http://bitly.com/nuvi-plz") if err != nil { fmt.Println(err) } defer resp.Body.Close() _, err = io.Copy(output, resp.Body) if err != nil { fmt.Println(err) return } baseURL := resp.Request.URL fmt.Println(baseURL) return baseURL.String() } // Read/step through the zip files and iterate // over the xml files within, call insertContentRedis() func readZipFiles(dirName string, fileName string, wgReadZip *sync.WaitGroup) { defer wgReadZip.Done() zipFile := "./" + dirName + "/" + fileName zipReader, err := zip.OpenReader(zipFile) if err != nil { fmt.Println(zipFile) fmt.Println(err) } defer zipReader.Close() fmt.Printf("Processing zip file: %s\n", zipFile) for _, fileContents := range zipReader.File { insertContentRedis(fileContents) } fmt.Printf("Processing zip file: %s\n", zipFile) } // Creates a Redisgo pool which allows the program // to use and reuse concurrent redigo connections func newPool() *redis.Pool { return &redis.Pool{ MaxIdle: 80, MaxActive: 12000, // max number of connections Dial: func() (redis.Conn, error) { c, err := redis.Dial("tcp", ":6379") if err != nil { panic(err.Error()) } return c, err }, } } // Open xml file, copy content to string // remove string from Redis list if exists // insert xml file as string into redis list func insertContentRedis(fileContents *zip.File) { openFile, err := fileContents.Open() if err != nil { log.Fatal(err) } fmt.Printf("Processing xml file: %s\n", fileContents.Name) parsedString := "" scanner := bufio.NewScanner(openFile) for scanner.Scan() { parsedString += scanner.Text() } redisConn := pool.Get() defer redisConn.Close() _, err = redisConn.Do("LREM", "NEWS_XML", -1, parsedString) if err != nil { fmt.Println(err) } _, err = redisConn.Do("LPUSH", "NEWS_XML", parsedString) if err != nil { log.Fatal(err) } fmt.Printf("Processed xml file: %s\n", fileContents.Name) } // Creating Redigo pool var pool = newPool() func main() { //getting base url and writing page contents to file baseURL := writeHTMLAndReturnRequestURL() output, err := os.Open("files.txt") if err != nil { log.Fatal(err) } defer output.Close() // Using a regex to match strings with 13 numbers followed by .zip (only once) re := regexp.MustCompile(`\d{13}\.zip`) scanner := bufio.NewScanner(output) // slices to hold remote file paths and // regexed file names var urlSlice []string var fileNameSlice []string // Iterating over files.txt to regex file names // appending urls and filenames to appropriate slices fmt.Println("Getting file list") for scanner.Scan() { fileName := re.FindAllString(scanner.Text(), 1) // Making sure we have a filename to append if len(fileName) > 0 { fileNameSlice = append(fileNameSlice, fileName[0]) urlSlice = append(urlSlice, baseURL+fileName[0]) } } fmt.Println("Done getting file list") zipDir := "ZipDir" // Creating directory for zip files os.Mkdir("."+string(filepath.Separator)+zipDir, 0755) // start file downloads, 3 at a time fmt.Printf("Downloading %d files...\n", len(urlSlice)) respch, err := grab.GetBatch(100, zipDir, urlSlice...) if err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) os.Exit(1) } // start a ticker to update progress every 200ms t := time.NewTicker(200 * time.Millisecond) // monitor downloads completed := 0 inProgress := 0 responses := make([]*grab.Response, 0) for completed < len(urlSlice) { select { case resp := <-respch: // a new response has been received and has started downloading // (nil is received once, when the channel is closed by grab) if resp != nil { responses = append(responses, resp) } case <-t.C: // clear lines if inProgress > 0 { fmt.Printf("\033[%dA\033[K", inProgress) } // update completed downloads for i, resp := range responses { if resp != nil && resp.IsComplete() { // print final result if resp.Error != nil { fmt.Fprintf(os.Stderr, "Error downloading %s: %v\n", resp.Request.URL(), resp.Error) } else { fmt.Printf("Finished %s %d / %d bytes (%d%%)\n", resp.Filename, resp.BytesTransferred(), resp.Size, int(100*resp.Progress())) } // mark completed responses[i] = nil completed++ } } // update downloads in progress inProgress = 0 for _, resp := range responses { if resp != nil { inProgress++ fmt.Printf("Downloading %s %d / %d bytes (%d%%)\033[K\n", resp.Filename, resp.BytesTransferred(), resp.Size, int(100*resp.Progress())) } } } } t.Stop() fmt.Printf("%d files successfully downloaded.\n", len(urlSlice)) // Creating WaitGroup in order to read and // process files concurrently var wgReadZip sync.WaitGroup fmt.Println("Reading files") for _, value := range fileNameSlice { wgReadZip.Add(1) go readZipFiles(zipDir, value, &wgReadZip) } wgReadZip.Wait() fmt.Println("Done reading files") }
package cmd import ( "github.com/Files-com/files-cli/lib" "github.com/spf13/cobra" files_sdk "github.com/Files-com/files-sdk-go" "fmt" "os" remote_server "github.com/Files-com/files-sdk-go/remoteserver" ) var ( RemoteServers = &cobra.Command{ Use: "remote-servers [command]", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) {}, } ) func RemoteServersInit() { var fieldsList string paramsRemoteServerList := files_sdk.RemoteServerListParams{} var MaxPagesList int cmdList := &cobra.Command{ Use: "list", Short: "list", Long: `list`, Args: cobra.MinimumNArgs(0), Run: func(cmd *cobra.Command, args []string) { params := paramsRemoteServerList params.MaxPages = MaxPagesList it, err := remote_server.List(params) if err != nil { fmt.Println(err) os.Exit(1) } lib.JsonMarshalIter(it, fieldsList) }, } cmdList.Flags().StringVarP(&paramsRemoteServerList.Cursor, "cursor", "c", "", "Used for pagination. Send a cursor value to resume an existing list from the point at which you left off. Get a cursor from an existing list via the X-Files-Cursor-Next header.") cmdList.Flags().IntVarP(&paramsRemoteServerList.PerPage, "per-page", "p", 0, "Number of records to show per page. (Max: 10,000, 1,000 or less is recommended).") cmdList.Flags().IntVarP(&MaxPagesList, "max-pages", "m", 1, "When per-page is set max-pages limits the total number of pages requested") cmdList.Flags().StringVarP(&fieldsList, "fields", "", "", "comma separated list of field names to include in response") RemoteServers.AddCommand(cmdList) var fieldsFind string paramsRemoteServerFind := files_sdk.RemoteServerFindParams{} cmdFind := &cobra.Command{ Use: "find", Run: func(cmd *cobra.Command, args []string) { result, err := remote_server.Find(paramsRemoteServerFind) if err != nil { fmt.Println(err) os.Exit(1) } lib.JsonMarshal(result, fieldsFind) }, } cmdFind.Flags().Int64VarP(&paramsRemoteServerFind.Id, "id", "i", 0, "Remote Server ID.") cmdFind.Flags().StringVarP(&fieldsFind, "fields", "", "", "comma separated list of field names") RemoteServers.AddCommand(cmdFind) var fieldsListForTesting string paramsRemoteServerListForTesting := files_sdk.RemoteServerListForTestingParams{} cmdListForTesting := &cobra.Command{ Use: "list-for-testing", Run: func(cmd *cobra.Command, args []string) { result, err := remote_server.ListForTesting(paramsRemoteServerListForTesting) if err != nil { fmt.Println(err) os.Exit(1) } lib.JsonMarshal(result, fieldsListForTesting) }, } cmdListForTesting.Flags().Int64VarP(&paramsRemoteServerListForTesting.RemoteServerId, "remote-server-id", "", 0, "RemoteServer ID") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.Root, "root", "", "", "Remote path to list") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.AwsAccessKey, "aws-access-key", "k", "", "AWS Access Key.") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.AwsSecretKey, "aws-secret-key", "e", "", "AWS secret key.") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.Password, "password", "p", "", "Password if needed.") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.PrivateKey, "private-key", "v", "", "Private key if needed.") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.SslCertificate, "ssl-certificate", "", "", "SSL client certificate.") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.GoogleCloudStorageCredentialsJson, "google-cloud-storage-credentials-json", "j", "", "A JSON file that contains the private key. To generate see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.WasabiAccessKey, "wasabi-access-key", "", "", "Wasabi access key.") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.WasabiSecretKey, "wasabi-secret-key", "", "", "Wasabi secret key.") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.BackblazeB2KeyId, "backblaze-b2-key-id", "i", "", "Backblaze B2 Cloud Storage keyID.") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.BackblazeB2ApplicationKey, "backblaze-b2-application-key", "", "", "Backblaze B2 Cloud Storage applicationKey.") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.RackspaceApiKey, "rackspace-api-key", "", "", "Rackspace API key from the Rackspace Cloud Control Panel.") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.AzureBlobStorageAccessKey, "azure-blob-storage-access-key", "y", "", "Azure Blob Storage secret key.") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.Hostname, "hostname", "o", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.Name, "name", "", "", "") cmdListForTesting.Flags().IntVarP(&paramsRemoteServerListForTesting.MaxConnections, "max-connections", "x", 0, "") cmdListForTesting.Flags().IntVarP(&paramsRemoteServerListForTesting.Port, "port", "t", 0, "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.S3Bucket, "s3-bucket", "", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.S3Region, "s3-region", "", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.ServerCertificate, "server-certificate", "f", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.ServerHostKey, "server-host-key", "", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.ServerType, "server-type", "", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.Ssl, "ssl", "l", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.Username, "username", "", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.GoogleCloudStorageBucket, "google-cloud-storage-bucket", "u", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.GoogleCloudStorageProjectId, "google-cloud-storage-project-id", "d", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.BackblazeB2Bucket, "backblaze-b2-bucket", "b", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.BackblazeB2S3Endpoint, "backblaze-b2-s3-endpoint", "n", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.WasabiBucket, "wasabi-bucket", "", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.WasabiRegion, "wasabi-region", "", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.RackspaceUsername, "rackspace-username", "s", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.RackspaceRegion, "rackspace-region", "g", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.RackspaceContainer, "rackspace-container", "", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.OneDriveAccountType, "one-drive-account-type", "r", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.AzureBlobStorageAccount, "azure-blob-storage-account", "a", "", "") cmdListForTesting.Flags().StringVarP(&paramsRemoteServerListForTesting.AzureBlobStorageContainer, "azure-blob-storage-container", "c", "", "") cmdListForTesting.Flags().StringVarP(&fieldsListForTesting, "fields", "", "", "comma separated list of field names") RemoteServers.AddCommand(cmdListForTesting) var fieldsCreate string paramsRemoteServerCreate := files_sdk.RemoteServerCreateParams{} cmdCreate := &cobra.Command{ Use: "create", Run: func(cmd *cobra.Command, args []string) { result, err := remote_server.Create(paramsRemoteServerCreate) if err != nil { fmt.Println(err) os.Exit(1) } lib.JsonMarshal(result, fieldsCreate) }, } cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.AwsAccessKey, "aws-access-key", "k", "", "AWS Access Key.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.AwsSecretKey, "aws-secret-key", "e", "", "AWS secret key.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.Password, "password", "p", "", "Password if needed.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.PrivateKey, "private-key", "v", "", "Private key if needed.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.SslCertificate, "ssl-certificate", "", "", "SSL client certificate.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.GoogleCloudStorageCredentialsJson, "google-cloud-storage-credentials-json", "j", "", "A JSON file that contains the private key. To generate see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.WasabiAccessKey, "wasabi-access-key", "", "", "Wasabi access key.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.WasabiSecretKey, "wasabi-secret-key", "", "", "Wasabi secret key.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.BackblazeB2KeyId, "backblaze-b2-key-id", "i", "", "Backblaze B2 Cloud Storage keyID.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.BackblazeB2ApplicationKey, "backblaze-b2-application-key", "", "", "Backblaze B2 Cloud Storage applicationKey.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.RackspaceApiKey, "rackspace-api-key", "", "", "Rackspace API key from the Rackspace Cloud Control Panel.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.AzureBlobStorageAccessKey, "azure-blob-storage-access-key", "y", "", "Azure Blob Storage secret key.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.Hostname, "hostname", "o", "", "Hostname or IP address") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.Name, "name", "", "", "Internal name for your reference") cmdCreate.Flags().IntVarP(&paramsRemoteServerCreate.MaxConnections, "max-connections", "x", 0, "Max number of parallel connections. Ignored for S3 connections (we will parallelize these as much as possible).") cmdCreate.Flags().IntVarP(&paramsRemoteServerCreate.Port, "port", "t", 0, "Port for remote server. Not needed for S3.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.S3Bucket, "s3-bucket", "", "", "S3 bucket name") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.S3Region, "s3-region", "", "", "S3 region") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.ServerCertificate, "server-certificate", "f", "", "Remote server certificate") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.ServerHostKey, "server-host-key", "", "", "Remote server SSH Host Key. If provided, we will require that the server host key matches the provided key. Uses OpenSSH format similar to what would go into ~/.ssh/known_hosts") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.ServerType, "server-type", "", "", "Remote server type.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.Ssl, "ssl", "l", "", "Should we require SSL?") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.Username, "username", "", "", "Remote server username. Not needed for S3 buckets.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.GoogleCloudStorageBucket, "google-cloud-storage-bucket", "u", "", "Google Cloud Storage bucket name") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.GoogleCloudStorageProjectId, "google-cloud-storage-project-id", "d", "", "Google Cloud Project ID") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.BackblazeB2Bucket, "backblaze-b2-bucket", "b", "", "Backblaze B2 Cloud Storage Bucket name") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.BackblazeB2S3Endpoint, "backblaze-b2-s3-endpoint", "n", "", "Backblaze B2 Cloud Storage S3 Endpoint") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.WasabiBucket, "wasabi-bucket", "", "", "Wasabi region") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.WasabiRegion, "wasabi-region", "", "", "Wasabi Bucket name") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.RackspaceUsername, "rackspace-username", "s", "", "Rackspace username used to login to the Rackspace Cloud Control Panel.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.RackspaceRegion, "rackspace-region", "g", "", "Three letter airport code for Rackspace region. See https://support.rackspace.com/how-to/about-regions/") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.RackspaceContainer, "rackspace-container", "", "", "The name of the container (top level directory) where files will sync.") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.OneDriveAccountType, "one-drive-account-type", "r", "", "Either personal or business_other account types") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.AzureBlobStorageAccount, "azure-blob-storage-account", "a", "", "Azure Blob Storage Account name") cmdCreate.Flags().StringVarP(&paramsRemoteServerCreate.AzureBlobStorageContainer, "azure-blob-storage-container", "c", "", "Azure Blob Storage Container name") cmdCreate.Flags().StringVarP(&fieldsCreate, "fields", "", "", "comma separated list of field names") RemoteServers.AddCommand(cmdCreate) var fieldsUpdate string paramsRemoteServerUpdate := files_sdk.RemoteServerUpdateParams{} cmdUpdate := &cobra.Command{ Use: "update", Run: func(cmd *cobra.Command, args []string) { result, err := remote_server.Update(paramsRemoteServerUpdate) if err != nil { fmt.Println(err) os.Exit(1) } lib.JsonMarshal(result, fieldsUpdate) }, } cmdUpdate.Flags().Int64VarP(&paramsRemoteServerUpdate.Id, "id", "", 0, "Remote Server ID.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.AwsAccessKey, "aws-access-key", "k", "", "AWS Access Key.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.AwsSecretKey, "aws-secret-key", "e", "", "AWS secret key.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.Password, "password", "p", "", "Password if needed.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.PrivateKey, "private-key", "v", "", "Private key if needed.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.SslCertificate, "ssl-certificate", "", "", "SSL client certificate.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.GoogleCloudStorageCredentialsJson, "google-cloud-storage-credentials-json", "j", "", "A JSON file that contains the private key. To generate see https://cloud.google.com/storage/docs/json_api/v1/how-tos/authorizing#APIKey") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.WasabiAccessKey, "wasabi-access-key", "", "", "Wasabi access key.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.WasabiSecretKey, "wasabi-secret-key", "", "", "Wasabi secret key.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.BackblazeB2KeyId, "backblaze-b2-key-id", "i", "", "Backblaze B2 Cloud Storage keyID.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.BackblazeB2ApplicationKey, "backblaze-b2-application-key", "", "", "Backblaze B2 Cloud Storage applicationKey.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.RackspaceApiKey, "rackspace-api-key", "", "", "Rackspace API key from the Rackspace Cloud Control Panel.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.AzureBlobStorageAccessKey, "azure-blob-storage-access-key", "y", "", "Azure Blob Storage secret key.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.Hostname, "hostname", "o", "", "Hostname or IP address") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.Name, "name", "", "", "Internal name for your reference") cmdUpdate.Flags().IntVarP(&paramsRemoteServerUpdate.MaxConnections, "max-connections", "x", 0, "Max number of parallel connections. Ignored for S3 connections (we will parallelize these as much as possible).") cmdUpdate.Flags().IntVarP(&paramsRemoteServerUpdate.Port, "port", "t", 0, "Port for remote server. Not needed for S3.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.S3Bucket, "s3-bucket", "", "", "S3 bucket name") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.S3Region, "s3-region", "", "", "S3 region") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.ServerCertificate, "server-certificate", "f", "", "Remote server certificate") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.ServerHostKey, "server-host-key", "", "", "Remote server SSH Host Key. If provided, we will require that the server host key matches the provided key. Uses OpenSSH format similar to what would go into ~/.ssh/known_hosts") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.ServerType, "server-type", "", "", "Remote server type.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.Ssl, "ssl", "l", "", "Should we require SSL?") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.Username, "username", "", "", "Remote server username. Not needed for S3 buckets.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.GoogleCloudStorageBucket, "google-cloud-storage-bucket", "u", "", "Google Cloud Storage bucket name") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.GoogleCloudStorageProjectId, "google-cloud-storage-project-id", "d", "", "Google Cloud Project ID") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.BackblazeB2Bucket, "backblaze-b2-bucket", "b", "", "Backblaze B2 Cloud Storage Bucket name") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.BackblazeB2S3Endpoint, "backblaze-b2-s3-endpoint", "n", "", "Backblaze B2 Cloud Storage S3 Endpoint") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.WasabiBucket, "wasabi-bucket", "", "", "Wasabi region") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.WasabiRegion, "wasabi-region", "", "", "Wasabi Bucket name") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.RackspaceUsername, "rackspace-username", "s", "", "Rackspace username used to login to the Rackspace Cloud Control Panel.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.RackspaceRegion, "rackspace-region", "g", "", "Three letter airport code for Rackspace region. See https://support.rackspace.com/how-to/about-regions/") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.RackspaceContainer, "rackspace-container", "", "", "The name of the container (top level directory) where files will sync.") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.OneDriveAccountType, "one-drive-account-type", "r", "", "Either personal or business_other account types") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.AzureBlobStorageAccount, "azure-blob-storage-account", "a", "", "Azure Blob Storage Account name") cmdUpdate.Flags().StringVarP(&paramsRemoteServerUpdate.AzureBlobStorageContainer, "azure-blob-storage-container", "c", "", "Azure Blob Storage Container name") cmdUpdate.Flags().StringVarP(&fieldsUpdate, "fields", "", "", "comma separated list of field names") RemoteServers.AddCommand(cmdUpdate) var fieldsDelete string paramsRemoteServerDelete := files_sdk.RemoteServerDeleteParams{} cmdDelete := &cobra.Command{ Use: "delete", Run: func(cmd *cobra.Command, args []string) { result, err := remote_server.Delete(paramsRemoteServerDelete) if err != nil { fmt.Println(err) os.Exit(1) } lib.JsonMarshal(result, fieldsDelete) }, } cmdDelete.Flags().Int64VarP(&paramsRemoteServerDelete.Id, "id", "i", 0, "Remote Server ID.") cmdDelete.Flags().StringVarP(&fieldsDelete, "fields", "", "", "comma separated list of field names") RemoteServers.AddCommand(cmdDelete) }
package command import ( "fmt" "github.com/DmiAS/cube_cli/internal/app/cli" "github.com/DmiAS/cube_cli/internal/app/connection/tcp" "github.com/DmiAS/cube_cli/internal/app/delivery/iproto" ) const ( argsError = iota connectionError internalError argsLen = 4 ) func Run(args []string) int { if len(args) < argsLen { fmt.Println("not enough arguments for cli call") return argsError } host, port := args[0], args[1] token, scope := args[2], args[3] connector, err := tcp.NewConnector(host, port) if err != nil { fmt.Println("can't resolve service addr due to", err) return connectionError } proto := iproto.NewClient(connector) cube := cli.NewCubeClient(proto) resp, err := cube.Send(token, scope) if err != nil { fmt.Println("internal error = ", err) return internalError } cube.PrintResponse(resp) return 0 }
package frenyard import ( "github.com/veandco/go-sdl2/sdl" "runtime" ) var fySDL2CRTCRegistry *crtcRegistry = newCRTCRegistryPtr() // sdl2RendererCore is the crtcContext. type sdl2RendererCore struct { base *sdl.Renderer } func (r *sdl2RendererCore) osDelete() { if r.base == nil { panic("Renderer was already destroyed!") } fySDL2CRTCRegistry.osRemoveRenderer(crtcContext(r)) r.base.Destroy() r.base = nil } // sdl2Renderer is the Renderer; meaning is dependent on render target. type sdl2Renderer struct { base *sdl2RendererCore clip Area2i translate Vec2i } func newSDL2Renderer(base *sdl2RendererCore) sdl2Renderer { return sdl2Renderer{ base, Area2i{}, Vec2i{}, } } func fySDL2AreaToRect(a Area2i) sdl.Rect { return sdl.Rect{ X: a.X.Pos, Y: a.Y.Pos, W: a.X.Size, H: a.Y.Size, } } func (r *sdl2Renderer) osFySDL2DrawColour(colour uint32) { red := (uint8)((colour >> 16) & 0xFF) green := (uint8)((colour >> 8) & 0xFF) blue := (uint8)((colour >> 0) & 0xFF) alpha := (uint8)((colour >> 24) & 0xFF) r.base.base.SetDrawColor(red, green, blue, alpha) } func (r *sdl2Renderer) osFyExtractSDL2Texture(tex Texture) *sdl.Texture { switch sheetActual := tex.(type) { case *crtcTextureExternal: // Explicit cast so you can see what's going on with the contexts sheetLocal := sheetActual.osGetLocalTexture(crtcContext(r.base)).(*fySDL2LocalTexture) return sheetLocal.base } panic("Unknown texture type forwarded into engine core.") } func (r *sdl2Renderer) DrawRect(drc DrawRectCommand) { { z := sdl2Os() defer z.End() } sRect := fySDL2AreaToRect(drc.TexSprite) tRect := fySDL2AreaToRect(drc.Target.Translate(r.translate)) blendMode := sdl.BlendMode(sdl.BLENDMODE_BLEND) if drc.Mode == DrawModeNoBlending { blendMode = sdl.BlendMode(sdl.BLENDMODE_NONE) } else if drc.Mode == DrawModeAdd { blendMode = sdl.BlendMode(sdl.BLENDMODE_ADD) } else if drc.Mode == DrawModeModulate { blendMode = sdl.BlendMode(sdl.BLENDMODE_MOD) } if drc.Tex != nil { // If the image has zero size, it doesn't exist. Anyway, osGetLocalTexture will crash size := drc.Tex.Size() if size.X == 0 || size.Y == 0 { return } sheetLocal := r.osFyExtractSDL2Texture(drc.Tex) red := (uint8)((drc.Colour >> 16) & 0xFF) green := (uint8)((drc.Colour >> 8) & 0xFF) blue := (uint8)((drc.Colour >> 0) & 0xFF) alpha := (uint8)((drc.Colour >> 24) & 0xFF) sheetLocal.SetColorMod(red, green, blue) sheetLocal.SetAlphaMod(alpha) sheetLocal.SetBlendMode(blendMode) r.base.base.Copy(sheetLocal, &sRect, &tRect) } else { r.osFySDL2DrawColour(drc.Colour) r.base.base.SetDrawBlendMode(blendMode) r.base.base.FillRect(&tRect) } } func (r *sdl2Renderer) Clip() Area2i { { z := sdl2Os() defer z.End() } return r.clip.Translate(r.translate.Negate()) } func (r *sdl2Renderer) SetClip(val Area2i) { { z := sdl2Os() defer z.End() } r.clip = val.Translate(r.translate) rect := fySDL2AreaToRect(r.clip) r.base.base.SetClipRect(&rect) } func (r *sdl2Renderer) Translate(val Vec2i) { { z := sdl2Os() defer z.End() } r.translate = r.translate.Add(val) } func (r *sdl2Renderer) Translation() Vec2i { { z := sdl2Os() defer z.End() } return r.translate } func (r *sdl2Renderer) Size() Vec2i { { z := sdl2Os() defer z.End() } wsX, wsY, err := r.base.base.GetOutputSize() if err != nil { // SDL2 will actually assertion-fail before ever erroring this way. // Why it even has the capability of erroring I do not know. panic(err) } return Vec2i{wsX, wsY} } func (r *sdl2Renderer) Reset(colour uint32) { { z := sdl2Os() defer z.End() } r.translate = Vec2i{} r.SetClip(Area2iOfSize(r.Size())) r.osFySDL2DrawColour(colour) r.base.base.SetDrawBlendMode(sdl.BLENDMODE_NONE) r.base.base.Clear() } func (r *sdl2Renderer) RenderToTexture(size Vec2i, drawer func (), reserved bool) Texture { { z := sdl2Os() defer z.End() } if reserved { panic("reserved must be kept false for future expansion") } if size.X <= 0 || size.Y <= 0 { // Empty texture return GlobalBackend.CreateTexture(Vec2i{}, []uint32{}) } tex, err := r.base.base.CreateTexture(sdl.PIXELFORMAT_RGBA8888, sdl.TEXTUREACCESS_TARGET, size.X, size.Y) if err != nil { // No RTT, so ignore the whole thing and return an empty texture return GlobalBackend.CreateTexture(Vec2i{}, []uint32{}) } oldClip := r.Clip() oldTranslate := r.translate oldRT := r.base.base.GetRenderTarget() r.translate = Vec2i{} r.SetClip(Area2iOfSize(size)) r.base.base.SetRenderTarget(tex) drawer() r.base.base.SetRenderTarget(oldRT) r.translate = oldTranslate r.SetClip(oldClip) localTexture := &fySDL2LocalTexture{ base: tex, } return fySDL2CRTCRegistry.osCreateLocalTexture(crtcContext(r.base), localTexture, size) } func (r *sdl2Renderer) Present() { { z := sdl2Os() defer z.End() } r.base.base.Present() } type fySDL2LocalTexture struct { base *sdl.Texture } func (r *fySDL2LocalTexture) osDelete() { r.base.Destroy() } type fySDL2TextureData struct { base *sdl.Surface } func (r *fySDL2TextureData) osMakeLocal(render crtcContext) crtcLocalTexture { renderActual := render.(*sdl2RendererCore) result, err := renderActual.base.CreateTextureFromSurface(r.base) if err != nil { panic(err) } return &fySDL2LocalTexture{ result, } } func (r *fySDL2TextureData) Size() Vec2i { return Vec2i{X: r.base.W, Y: r.base.H} } func (r *fySDL2TextureData) osDelete() { r.base.Free() } // This API is package-local so that sdl_ttf & sdl can get at it func osSdl2SurfaceToFyTexture(surface *sdl.Surface) Texture { return fySDL2CRTCRegistry.osCreateTexture(&fySDL2TextureData{ base: surface, }) } // { z := sdl2Os(); defer z.End() } type sdl2BlockOS struct{} func sdl2Os() sdl2BlockOS { runtime.LockOSThread(); return sdl2BlockOS{} } func (*sdl2BlockOS) End() { runtime.UnlockOSThread() }
package herd import ( "bytes" "os/exec" "runtime" "time" ) var ( carriageReturnLiteral = []byte{'\r'} newlineLiteral = []byte{'\n'} newlineReplacement = []byte{'\\', 'n'} ) type completionType struct { failed bool hostname string } type installerQueueType struct { entries map[string]*queueEntry // Key: subHostname (nil: processing). first *queueEntry last *queueEntry } type queueEntry struct { startTime time.Time hostname string prev *queueEntry next *queueEntry } func (herd *Herd) subdInstallerLoop() { if *subdInstaller == "" { return } availableSlots := runtime.NumCPU() completion := make(chan completionType, 1) queueAdd := make(chan string, 1) herd.subdInstallerQueueAdd = queueAdd queueDelete := make(chan string, 1) herd.subdInstallerQueueDelete = queueDelete queueErase := make(chan string, 1) herd.subdInstallerQueueErase = queueErase queue := installerQueueType{entries: make(map[string]*queueEntry)} for { sleepInterval := time.Hour if queue.first != nil && availableSlots > 0 { sleepInterval = time.Until(queue.first.startTime) } timer := time.NewTimer(sleepInterval) select { case <-timer.C: case hostname := <-queueAdd: if _, ok := queue.entries[hostname]; !ok { entry := &queueEntry{ startTime: time.Now().Add(*subdInstallDelay), hostname: hostname, prev: queue.last, } queue.add(entry) } case hostname := <-queueDelete: if entry := queue.entries[hostname]; entry != nil { queue.delete(entry) delete(queue.entries, hostname) } case hostname := <-queueErase: if entry := queue.entries[hostname]; entry != nil { queue.delete(entry) } delete(queue.entries, hostname) case result := <-completion: availableSlots++ if _, ok := queue.entries[result.hostname]; ok { // Not erased. delete(queue.entries, result.hostname) if result.failed && *subdInstallRetryDelay > *subdInstallDelay { // Come back later rather than sooner, must re-inject now. entry := &queueEntry{ startTime: time.Now().Add(*subdInstallRetryDelay), hostname: result.hostname, prev: queue.last, } queue.add(entry) } } } timer.Stop() entry := queue.first if entry != nil && availableSlots > 0 && time.Since(entry.startTime) >= 0 { availableSlots-- go herd.subInstall(entry.hostname, completion) queue.delete(entry) queue.entries[entry.hostname] = nil // Mark as processing. } } } func (herd *Herd) addSubToInstallerQueue(subHostname string) { if herd.subdInstallerQueueAdd != nil { herd.subdInstallerQueueAdd <- subHostname } } func (herd *Herd) eraseSubFromInstallerQueue(subHostname string) { if herd.subdInstallerQueueErase != nil { herd.subdInstallerQueueErase <- subHostname } } func (herd *Herd) removeSubFromInstallerQueue(subHostname string) { if herd.subdInstallerQueueDelete != nil { herd.subdInstallerQueueDelete <- subHostname } } func (herd *Herd) subInstall(subHostname string, completion chan<- completionType) { failed := false defer func() { completion <- completionType{failed, subHostname} }() herd.logger.Printf("Installing subd on: %s\n", subHostname) cmd := exec.Command(*subdInstaller, subHostname) output, err := cmd.CombinedOutput() if err != nil { failed = true if len(output) > 0 && output[len(output)-1] == '\n' { output = output[:len(output)-1] } output = bytes.ReplaceAll(output, carriageReturnLiteral, nil) output = bytes.ReplaceAll(output, newlineLiteral, newlineReplacement) herd.logger.Printf("Error installing subd on: %s: %s: %s\n", subHostname, err, string(output)) } } func (queue *installerQueueType) add(entry *queueEntry) { entry.prev = queue.last if queue.first == nil { queue.first = entry } else { queue.last.next = entry } queue.last = entry queue.entries[entry.hostname] = entry } func (queue *installerQueueType) delete(entry *queueEntry) { if entry.prev == nil { queue.first = entry.next } else { entry.prev.next = entry.next } if entry.next == nil { queue.last = entry.prev } else { entry.next.prev = entry.prev } }
// Shows example use of the keyring package // // May need to be built with a platform-specific build flag to specify a // provider. See keyring documentation for details. // package main import ( "os" "fmt" "github.com/tmc/keyring" ) func main() { args := os.Args[1:] if len(args) < 1 { fmt.Fprintf(os.Stderr, "No variable was provided.") os.Exit(1) } variable := os.Args[1] if pw, err := keyring.Get("summon", variable); err == nil { os.Stdout.WriteString( pw) } else if err == keyring.ErrNotFound { fmt.Fprintf(os.Stderr, "%s could not be retrieved", variable) } else { fmt.Fprintf(os.Stderr, "error:", err) os.Exit(1) } }
package main //func test() { // defer func() { // err := recover() // if err != nil{ // fmt.Println(err) // } // }() // num1 := 10 // num2 := 0 // res := num1/num2 // fmt.Println(res) //} //func main() { // test() // fmt.Println("ok") //} //array //func main() { ////var shuzu [6]float64 ////shuzu[0] = 3.0 ////shuzu[1] = 3.0 ////shuzu[2] = 3.0 ////shuzu[3] = 3.0 ////shuzu[4] = 3.0 ////shuzu[5] = 3.0 ////var totalw float64 = 0.0 ////for i := 0 ;i < len(shuzu);i++{ //// totalw += shuzu[i] ////} ////fmt.Println(totalw,len(shuzu)) ////} //func main() { // var shuzu [5]int // shuzu[0] = 10 // fmt.Println(shuzu) // fmt.Printf("%p,%p,%p,%p",&shuzu,&shuzu[0],&shuzu[1],&shuzu[2]) //} //func main() { // var shuzu [5]float64 // for i:=0;i < len(shuzu);i++ { // fmt.Println("input\n") // fmt.Scanln(&shuzu[i]) // } // for i:=0;i < len(shuzu);i++ { // fmt.Println(shuzu[i]) // } //} //初始化数组的四种方式 /* func main() { var shuzu1 [3]int = [3]int{1, 2, 3} var shuzu2 = [3]int{4,5,6} var shuzu3 = [...]int{7,8,9,10} var shuzu4 = [...]int{1:12,0:11,2:13} fmt.Println(shuzu1,shuzu2,shuzu3,shuzu4) } */ //for-range结构遍历 //func main() { // var shuzu [10]int = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} // for index, value := range shuzu { // fmt.Println(index, value) // } //} //冒泡排序 //func main() { // slice := []int{69,24,80,57,55,45} // for i := (len(slice) - 1); i > 0; i-- { // for i := 0; i < (len(slice) - 1); i++ { //长度为n的数组,两数直接比较n-1次,此层循环一次最大数会被排到最后,再次循环时最大数(排最后的数) // // 无需再参与比较,因此此层循环一次,上层循环减少一次,上层则使用i-- // if slice[i] > slice[i+1] { //如果第一个数大于第二个数则交换它们的位置,否则不做交换,各自等于原来的值(以下6行) // t := slice[i+1] // slice[i+1] = slice[i] // slice[i] = t // } else { // slice[i] = slice[i] // slice[i+1] = slice[i+1] // } // } // } // fmt.Println(slice) //} //func mp(arr *[10]int) { // for j := (len(*arr) - 1); j > 0; j-- { // for i := 0; i < (len(*arr) - 1); i++ { //长度为n的数组,两数直接比较n-1次,此层循环一次最大数会被排到最后,再次循环时最大数(排最后的数) // // 无需再参与比较,因此此层循环一次,上层循环减少一次,上层则使用i-- // if (*arr)[i] > (*arr)[i+1] { //如果第一个数大于第二个数则交换它们的位置,否则不做交换,各自等于原来的值(以下6行) // t := (*arr)[i+1] // (*arr)[i+1] = (*arr)[i] // (*arr)[i] = t // } // } // } // } // //func main() { // arr := [10]int{69,24,80,57,55,45,65,24,58,12} // mp(&arr) // fmt.Println(arr) //} //二分 //func binary(arr *[11]int,Leftindex int,Rightindex int,num int){ // middle := (Leftindex+Rightindex)/2 //} //func main() { // arr := [11]int{12,14,16,19,20,25,29,30,33,39,40} // binary(&arr,leftindex) //} //二位数组 //func main() { // var arr [4][6]int // arr [1][2] = 1 // for i:=0;i < 4;i++{ // for j:=0;j < 6;j++{ // fmt.Print(arr[i][j]," ") // } // fmt.Println() // } //} //func main() { //var arr [4][6]int = [4][6]int{{1,2,3,4,5,6},{1,2,3,4,5,6},{1,2,3,4,5,6},{1,2,3,4,5,6}} //fmt.Println(arr) //for i := 0 ;i < 4;i++ { // for j := 0; j < 6; j++ { // fmt.Print(arr[i][j]," ") // } // fmt.Println() //} //for index,value := range arr{ // for j,v2 := range value{ // fmt.Printf("arr[%v][%v]=[%v]\n",index,j,v2) // } //} //} //func main() { // var arr [3][5]int // for i,v1 := range arr{ // for j,_ := range v1{ // fmt.Printf("请输入第%d个班第%d位:",i+1,j+1) // fmt.Scanln(&arr[i][j]) // } // } // fmt.Println(arr) //} //map声明 //func main() { // var a map[string]string //使用前必须给map分配数据空间 // a = make(map[string]string,10) //10表示分配给map的空间,能存10个key-value // a["name"] = "dw" //value可重复,key不可重复(覆盖先前的) // a["age"] = "18" // a["hoby"] = "none" // a["home"] = "hn" // fmt.Println(a) //} //map使用 //func main() { //var a map[string]string //a = make(map[string]string,10) //不写空间默认为1 //a["name"] = "dw" //fmt.Println(a) //cities := make(map[string]string) //容量自增涨,无需定义 //cities["city1"] = "hz" //cities["city2"] = "hz" //cities["city3"] = "hz" //cities["city4"] = "hz" //fmt.Println(cities) //name := map[string]string{ // "name1" : "aa", // "name2" : "bb", //} //fmt.Println(name) /* studentMap := make(map[string]map[string]string) studentMap["stu1"] = make(map[string]string,3) studentMap["stu1"]["name"] = "tom" studentMap["stu1"]["sex"] = "man" studentMap["stu2"] = make(map[string]string,3) studentMap["stu2"]["name"] = "alice" studentMap["stu2"]["sex"] = "woman" fmt.Println(studentMap) //统计key,value //fmt.Println(len(studentMap)) fmt.Println(studentMap["stu1"]) fmt.Println(studentMap["stu1"]["name"]) fmt.Println(studentMap["stu1"]["sex"]) */ //map增删改查 /* studentMap["stu2"]["name"] = "alice~" //若key已存在则是修改 fmt.Println(studentMap) studentMap["stu2"]["address"] = "hz" //若key不存在则是增加 fmt.Println(studentMap) delete(studentMap["stu2"],"address") //删除key,如删除的key也不会报错=不操作 fmt.Println(studentMap) val,ok := studentMap["stu1"] if ok { fmt.Println("y",val) }else { fmt.Println("n") } */ //删除map //①遍历,逐个删除 //②make一个新的空间,原来的内存会被gc回收 /* studentMap = make(map[string]map[string]string) fmt.Println(studentMap) */ //遍历map /* for _,value := range studentMap{ for key1,value1 := range value{ fmt.Println(key1,value1) } } */ //map切片 /* var monster []map[string]string monster = make([]map[string]string, 2) //容量为2 if monster[0] == nil { monster[0] = make(map[string]string, 2) monster[0]["name"] = "m1" monster[0]["age"] = "18" } if monster[1] == nil { monster[1] = make(map[string]string, 2) monster[1]["name"] = "m2" monster[1]["age"] = "19" } */ //if monster[2] == nil { //越界了,不合法,报错 // monster[2] = make(map[string]string,2) // monster[2]["name"] = "m3" // monster[2]["age"] = "20" //} //使用切片的append函数,动态增加。 /* newmonster := map[string]string{ "name" : "m3", "age" : "21", } monster = append(monster,newmonster) fmt.Println(monster) */ //} //func main() { // file,err := os.Open("C:\\Users\\x1c\\GolandProjects\\golang\\gofirst\\function入门\\函数\\error\\a.txt") // fmt.Println(*file,err) // file.Close() //} //读文件1 /* func main() { file,err :=os.Open("C:\\Users\\x1c\\GolandProjects\\golang\\gofirst\\function入门\\函数\\error\\a.txt") if err != nil{ fmt.Println(err) } defer file.Close() reader := bufio.NewReader(file) for { str, err := reader.ReadString('\n') if err == io.EOF{ break } fmt.Print(str) } } */ /* func main() { filePath := "d:/golang.txt" file,err := os.OpenFile(filePath, os.O_WRONLY | os.O_CREATE|os.O_APPEND,0777) if err != nil{ fmt.Println(err) return } defer file.Close() str := "hello world!\n" writer := bufio.NewWriter(file) for i:=0;i<5;i++{ writer.WriteString(str) } writer.Flush() } */ /* func main() { oldfilePath := "d:/send.txt" newfilePath := "d:/accept.txt" file, err := os.OpenFile(oldfilePath,os.O_RDONLY,0777) if err != nil{ fmt.Println(err) } defer file.Close() reader := bufio.NewReader(file) for { str, err := reader.ReadString('\n') if err == io.EOF{ break } fmt.Print(str) file,err := os.OpenFile(newfilePath,os.O_RDWR|os.O_APPEND,0777) if err != nil { fmt.Println(err) } writer := bufio.NewWriter(file) writer.WriteString(str) writer.Flush() } } */ /* var count struct{ zimucount int shuzicount int spacecount int othercount int } func main() { filePath := "d:\\send.txt" file, err := os.Open(filePath) if err != nil{ fmt.Println(err) } defer file.Close() reader := bufio.NewReader(file) for { str,err := reader.ReadString('\n') if err == io.EOF{ break } for _,v := range str{ switch { case v >= 'a' && v <='z' : count.zimucount++ case v >= 'A' && v <= 'Z': count.zimucount++ case v == ' ' || v == '\t': count.spacecount++ case v >='0' && v <= '9': count.shuzicount++ default: count.othercount++ } } } fmt.Printf("zimu:%v\n",count.zimucount) fmt.Printf("shuzi:%v\n",count.shuzicount) fmt.Printf("space:%v\n",count.spacecount) fmt.Printf("other:%v\n",count.othercount) } */ /* func main() { fmt.Println(len(os.Args)) for i,v := range os.Args{ fmt.Printf("args[%v]=%v\n",i,v) } } */ //命令行参数 /* func main() { var user string var pwd string var host string var port int flag.StringVar(&user,"u","","用户名") flag.StringVar(&pwd,"pwd","","密码") flag.StringVar(&host,"h","","主机") flag.IntVar(&port,"p",3306,"用户名") flag.Parse() fmt.Printf("user:%v,pwd:%v,host:%v,port:%v",user,pwd,host,port) } */ //序列化 import ( "encoding/json" "fmt" ) type Monster struct { Name string Age int Sal float64 Address string Skill string } func test() { mon := Monster{ Name: "duwei", Age: 23, Sal: 1000, Address: "hunan", Skill: "wu", } data, err := json.Marshal(&mon) if err != nil { fmt.Println(err) } fmt.Println(string(data)) } func main() { test() }
package colr import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01400104 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:colr.014.001.04 Document"` Message *InterestPaymentResponseV04 `xml:"IntrstPmtRspn"` } func (d *Document01400104) AddMessage() *InterestPaymentResponseV04 { d.Message = new(InterestPaymentResponseV04) return d.Message } // Scope // The InterestPaymentResponse message is sent by either; // - the collateral taker or its collateral manager to the collateral giver or its collateral manager, or // - the collateral giver or its collateral manager to the collateral taker or its collateral manager // This is a response to the InterestPaymentRequest message and the amount of interest requested or advised can be accepted or rejected. // // The message definition is intended for use with the ISO20022 Business Application Header. // // Usage // The InterestPaymentResponse message is sent in response to the InterestPaymentRequest in order to accept or reject the amount of interest requested or advised. A rejection reason and information can be provide if the InterestPaymentRequest is being rejected. type InterestPaymentResponseV04 struct { // Unambiguous identification of the transaction as know by the instructing party. TransactionIdentification *iso20022.Max35Text `xml:"TxId"` // Provides information like the identification of the party or parties associated with the collateral agreement, the exposure type and the valuation date. Obligation *iso20022.Obligation4 `xml:"Oblgtn"` // Agreement details for the over the counter market. Agreement *iso20022.Agreement4 `xml:"Agrmt"` // Provides details on the interest amount due to party A. InterestDueToA *iso20022.InterestAmount2 `xml:"IntrstDueToA,omitempty"` // Provides details on the interest amount due to party B. InterestDueToB *iso20022.InterestAmount2 `xml:"IntrstDueToB,omitempty"` // Provides details on the response to the interest payment request. InterestResponse *iso20022.InterestResponse1 `xml:"IntrstRspn"` // Additional information that can not be captured in the structured fields and/or any other specific block. SupplementaryData []*iso20022.SupplementaryData1 `xml:"SplmtryData,omitempty"` } func (i *InterestPaymentResponseV04) SetTransactionIdentification(value string) { i.TransactionIdentification = (*iso20022.Max35Text)(&value) } func (i *InterestPaymentResponseV04) AddObligation() *iso20022.Obligation4 { i.Obligation = new(iso20022.Obligation4) return i.Obligation } func (i *InterestPaymentResponseV04) AddAgreement() *iso20022.Agreement4 { i.Agreement = new(iso20022.Agreement4) return i.Agreement } func (i *InterestPaymentResponseV04) AddInterestDueToA() *iso20022.InterestAmount2 { i.InterestDueToA = new(iso20022.InterestAmount2) return i.InterestDueToA } func (i *InterestPaymentResponseV04) AddInterestDueToB() *iso20022.InterestAmount2 { i.InterestDueToB = new(iso20022.InterestAmount2) return i.InterestDueToB } func (i *InterestPaymentResponseV04) AddInterestResponse() *iso20022.InterestResponse1 { i.InterestResponse = new(iso20022.InterestResponse1) return i.InterestResponse } func (i *InterestPaymentResponseV04) AddSupplementaryData() *iso20022.SupplementaryData1 { newValue := new(iso20022.SupplementaryData1) i.SupplementaryData = append(i.SupplementaryData, newValue) return newValue }
package main import "fmt" type ListNode struct { Val int Next *ListNode } /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { if l1 == nil && l2 == nil { return nil } lm := new(ListNode) l3 := new(ListNode) l3 = lm for l1 != nil || l2 != nil { if l1 == nil { lm.Val = l2.Val l2 = l2.Next } else if l2 == nil { lm.Val = l1.Val l1 = l1.Next } else if l1.Val <= l2.Val { lm.Val = l1.Val l1 = l1.Next } else { lm.Val = l2.Val l2 = l2.Next } if l1 == nil && l2 == nil { break; } lm.Next = new(ListNode) lm = lm.Next } return l3 } func main() { l1a := ListNode{Val: 1} l1b := ListNode{Val: 2} l1c := ListNode{Val: 4} l1a.Next = &l1b l1b.Next = &l1c l2a := ListNode{Val: 1} l2b := ListNode{Val: 3} l2c := ListNode{Val: 4} l2a.Next = &l2b l2b.Next = &l2c lm := mergeTwoLists(&l1a, &l2a) for lm != nil { fmt.Printf("%d ", lm.Val) lm = lm.Next } }
package main import ( "fmt" "html/template" "os" rt "runtime" "strings" "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/containers/libpod/libpod/define" "github.com/containers/libpod/pkg/adapter" "github.com/containers/libpod/version" "github.com/pkg/errors" "github.com/spf13/cobra" ) var ( infoCommand cliconfig.InfoValues infoDescription = `Display information pertaining to the host, current storage stats, and build of podman. Useful for the user and when reporting issues. ` _infoCommand = &cobra.Command{ Use: "info", Args: noSubArgs, Long: infoDescription, Short: "Display podman system information", RunE: func(cmd *cobra.Command, args []string) error { infoCommand.InputArgs = args infoCommand.GlobalFlags = MainGlobalOpts infoCommand.Remote = remoteclient return infoCmd(&infoCommand) }, Example: `podman info`, } ) func init() { infoCommand.Command = _infoCommand infoCommand.SetHelpTemplate(HelpTemplate()) infoCommand.SetUsageTemplate(UsageTemplate()) flags := infoCommand.Flags() flags.BoolVarP(&infoCommand.Debug, "debug", "D", false, "Display additional debug information") flags.StringVarP(&infoCommand.Format, "format", "f", "", "Change the output format to JSON or a Go template") } func infoCmd(c *cliconfig.InfoValues) error { runtime, err := adapter.GetRuntime(getContext(), &c.PodmanCommand) if err != nil { return errors.Wrapf(err, "could not get runtime") } defer runtime.DeferredShutdown(false) i, err := runtime.Info() if err != nil { return errors.Wrapf(err, "error getting info") } info := infoWithExtra{Info: i} if runtime.Remote { endpoint, err := runtime.RemoteEndpoint() if err != nil { return err } info.Remote = getRemote(endpoint) } if !runtime.Remote && c.Debug { d, err := getDebug() if err != nil { return err } info.Debug = d } var out formats.Writer infoOutputFormat := c.Format if strings.Join(strings.Fields(infoOutputFormat), "") == "{{json.}}" { infoOutputFormat = formats.JSONString } switch infoOutputFormat { case formats.JSONString: out = formats.JSONStruct{Output: info} case "": out = formats.YAMLStruct{Output: info} default: tmpl, err := template.New("info").Parse(c.Format) if err != nil { return err } err = tmpl.Execute(os.Stdout, info) return err } return out.Out() } // top-level "debug" info func getDebug() (*debugInfo, error) { v, err := define.GetVersion() if err != nil { return nil, err } return &debugInfo{ Compiler: rt.Compiler, GoVersion: rt.Version(), PodmanVersion: v.Version, GitCommit: v.GitCommit, }, nil } func getRemote(endpoint *adapter.Endpoint) *remoteInfo { return &remoteInfo{ Connection: endpoint.Connection, ConnectionType: endpoint.Type.String(), RemoteAPIVersion: string(version.RemoteAPIVersion), PodmanVersion: version.Version, OSArch: fmt.Sprintf("%s/%s", rt.GOOS, rt.GOARCH), } } type infoWithExtra struct { *define.Info Remote *remoteInfo `json:"remote,omitempty"` Debug *debugInfo `json:"debug,omitempty"` } type remoteInfo struct { Connection string `json:"connection"` ConnectionType string `json:"connectionType"` RemoteAPIVersion string `json:"remoteAPIVersion"` PodmanVersion string `json:"podmanVersion"` OSArch string `json:"OSArch"` } type debugInfo struct { Compiler string `json:"compiler"` GoVersion string `json:"goVersion"` PodmanVersion string `json:"podmanVersion"` GitCommit string `json:"gitCommit"` }
package main import "fmt" func main() { var countryCapitalMap map[string]string countryCapitalMap = make(map[string]string) countryCapitalMap["1"] = "yi" countryCapitalMap["2"] = "er" countryCapitalMap["3"] = "san" countryCapitalMap["4"] = "si" for k, v := range countryCapitalMap { fmt.Println(k, "==", v) } //判断某个key是否存在 s := "3" capital, ok := countryCapitalMap[s] if ok { fmt.Println(s, "==", capital) } else { fmt.Println(s, "==不存在") } }
package 位运算 // ----------- 位运算解法 ----------- func singleNumber(nums []int) int { twos, ones := 0, 0 for _, num := range nums { ones = (ones ^ num) & ^twos twos = (twos ^ num) & ^ones } return ones } // ----------- bitMap解法 ----------- func singleNumber(nums []int) int { countOfBit := make([]int, 64) for _, num := range nums { for i := 0; i < len(countOfBit); i++ { if getBit(num, i) == 1 { countOfBit[i]++ } } } result := 0 for i := 0; i < len(countOfBit); i++ { result |= (countOfBit[i] % 3) << i } return result } func getBit(num, k int) int { if num&(1<<k) == 0 { return 0 } return 1 } /* 题目链接: https://leetcode-cn.com/problems/single-number-ii/ 总结: 1. 这题就是用 2个bit,表示数组元素bit出现的次数。 (需要%3) 2. 方法2就是统计所有bit出现的次数。 (由于go语言int是64位的,所以bitmap要64位) */
package Problem0164 func maximumGap(nums []int) int { if len(nums) < 2 { return 0 } // 自己实现了一个简易的快排 var quickSort func(i, j int) quickSort = func(i, j int) { ci, cj := i, j c := i for i < j { for nums[j] >= nums[c] && i < j { j-- } for nums[i] <= nums[c] && i < j { i++ } nums[i], nums[j] = nums[j], nums[i] } nums[i], nums[c] = nums[c], nums[i] c = i if ci < c { quickSort(ci, c) } if c+1 < cj { quickSort(c+1, cj) } } quickSort(0, len(nums)-1) ret := 0 for i := 1; i < len(nums); i++ { tmp := nums[i] - nums[i-1] if ret < tmp { ret = tmp } } return ret }
package datasource import ( "context" "fmt" "os" "sort" "strings" "time" "github.com/vmware/kube-fluentd-operator/config-reloader/fluentd" "github.com/vmware/kube-fluentd-operator/config-reloader/util" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "github.com/sirupsen/logrus" "github.com/vmware/kube-fluentd-operator/config-reloader/config" "github.com/vmware/kube-fluentd-operator/config-reloader/datasource/kubedatasource" kfoListersV1beta1 "github.com/vmware/kube-fluentd-operator/config-reloader/datasource/kubedatasource/fluentdconfig/client/listers/logs.vdp.vmware.com/v1beta1" core "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" listerv1 "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/clientcmd" ) type kubeInformerConnection struct { client kubernetes.Interface confHashes map[string]string mountedLabels map[string][]map[string]string cfg *config.Config kubeds kubedatasource.KubeDS nslist listerv1.NamespaceLister podlist listerv1.PodLister cmlist listerv1.ConfigMapLister fdlist kfoListersV1beta1.FluentdConfigLister updateChan chan time.Time } // NewKubernetesInformerDatasource builds a new Datasource from the provided config. // The returned Datasource uses Informers to efficiently track objects in the kubernetes // API by watching for updates to a known state. func NewKubernetesInformerDatasource(ctx context.Context, cfg *config.Config, updateChan chan time.Time) (Datasource, error) { kubeConfig := cfg.KubeConfig if cfg.KubeConfig == "" { if _, err := os.Stat(clientcmd.RecommendedHomeFile); err == nil { kubeConfig = clientcmd.RecommendedHomeFile } } kubeCfg, err := clientcmd.BuildConfigFromFlags(cfg.Master, kubeConfig) if err != nil { return nil, err } client, err := kubernetes.NewForConfig(kubeCfg) if err != nil { return nil, err } logrus.Infof("Connected to cluster at %s", kubeCfg.Host) factory := informers.NewSharedInformerFactory(client, 0) namespaceLister := factory.Core().V1().Namespaces().Lister() podLister := factory.Core().V1().Pods().Lister() cmLister := factory.Core().V1().ConfigMaps().Lister() var kubeds kubedatasource.KubeDS fluentdconfigDSLister := &kubedatasource.FluentdConfigDS{ Fdlist: nil, } if cfg.Datasource == "crd" { kubeds, err = kubedatasource.NewFluentdConfigDS(ctx, cfg, kubeCfg, updateChan) if err != nil { return nil, err } fluentdconfigDSLister = &kubedatasource.FluentdConfigDS{ Fdlist: kubeds.GetFdlist(), } } else { if cfg.CRDMigrationMode { kubeds, err = kubedatasource.NewMigrationModeDS(ctx, cfg, kubeCfg, factory, updateChan) if err != nil { return nil, err } fluentdconfigDSLister = &kubedatasource.FluentdConfigDS{ Fdlist: kubeds.GetFdlist(), } } else { kubeds, err = kubedatasource.NewConfigMapDS(ctx, cfg, factory, updateChan) if err != nil { return nil, err } } } factory.Start(nil) if !cache.WaitForCacheSync(nil, factory.Core().V1().Namespaces().Informer().HasSynced, factory.Core().V1().Pods().Informer().HasSynced, factory.Core().V1().ConfigMaps().Informer().HasSynced, kubeds.IsReady) { return nil, fmt.Errorf("Failed to sync local informer with upstream Kubernetes API") } logrus.Infof("Synced local informer with upstream Kubernetes API") kubeInfoCx := &kubeInformerConnection{ client: client, confHashes: make(map[string]string), mountedLabels: make(map[string][]map[string]string), cfg: cfg, kubeds: kubeds, nslist: namespaceLister, podlist: podLister, cmlist: cmLister, fdlist: fluentdconfigDSLister.Fdlist, updateChan: updateChan, } factory.Core().V1().Pods().Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { kubeInfoCx.handlePodChange(ctx, obj) }, UpdateFunc: func(old, obj interface{}) { }, DeleteFunc: func(obj interface{}) { kubeInfoCx.handlePodChange(ctx, obj) }, }) return kubeInfoCx, nil } // GetNamespaces queries the configured Kubernetes API to generate a list of NamespaceConfig objects. // It uses options from the configuration to determine which namespaces to inspect and which resources // within those namespaces contain fluentd configuration. func (d *kubeInformerConnection) GetNamespaces(ctx context.Context) ([]*NamespaceConfig, error) { // Get a list of the namespaces which may contain fluentd configuration: nses, err := d.discoverNamespaces(ctx) if err != nil { return nil, err } nsconfigs := make([]*NamespaceConfig, 0) for _, ns := range nses { // Get the Namespace object associated with a particular name nsobj, err := d.nslist.Get(ns) if err != nil { return nil, err } configdata, err := d.kubeds.GetFluentdConfig(ctx, ns) if err != nil { return nil, err } if configdata == "" { logrus.Infof("Skipping namespace: %v because is empty", ns) continue } fragment, err := fluentd.ParseString(configdata) if err != nil { logrus.Errorf("Error parsing config for ns %s: %v", ns, err) continue } var mountedLabels []map[string]string for _, frag := range fragment { if frag.Name == "source" && frag.Type() == "mounted-file" { paramLabels := frag.Param("labels") paramLabels = util.TrimTrailingComment(paramLabels) currLabels, err := util.ParseTagToLabels(fmt.Sprintf("$labels(%s)", paramLabels)) if err != nil { return nil, err } mountedLabels = append(mountedLabels, currLabels) } } d.updateMountedLabels(ns, mountedLabels) // Create a compact representation of the pods running in the namespace // under consideration pods, err := d.podlist.Pods(ns).List(labels.NewSelector()) if err != nil { logrus.Errorf("Error listing pod in ns %s: %v", ns, err) continue } podsCopy := make([]core.Pod, len(pods)) for i, pod := range pods { podsCopy[i] = *pod.DeepCopy() } podList := &core.PodList{ Items: podsCopy, } minis := convertPodToMinis(podList) // Create a new NamespaceConfig from the data we've processed up to now nsconfigs = append(nsconfigs, &NamespaceConfig{ Name: ns, FluentdConfig: configdata, PreviousConfigHash: d.confHashes[ns], Labels: nsobj.Labels, MiniContainers: minis, }) } return nsconfigs, nil } // WriteCurrentConfigHash is a setter for the hashtable maintained by this Datasource func (d *kubeInformerConnection) WriteCurrentConfigHash(namespace string, hash string) { d.confHashes[namespace] = hash } func (d *kubeInformerConnection) updateMountedLabels(namespace string, labels []map[string]string) { d.mountedLabels[namespace] = labels } // UpdateStatus updates a namespace's status annotation with the latest result // from the config generator. func (d *kubeInformerConnection) UpdateStatus(ctx context.Context, namespace string, status string) { ns, err := d.client.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{}) if err != nil { logrus.Infof("Cannot find namespace to update status for: %v", namespace) } // update annotations annotations := ns.GetAnnotations() if annotations == nil { annotations = make(map[string]string) } statusAnnotationExists := false if _, ok := annotations[d.cfg.AnnotStatus]; ok { statusAnnotationExists = true } // check the annotation status key and add if status not blank if !statusAnnotationExists && status != "" { // not found add it. // only add status if the status key is not "" annotations[d.cfg.AnnotStatus] = status } // check if annotation status key exists and remove if status blank if statusAnnotationExists && status == "" { delete(annotations, d.cfg.AnnotStatus) } ns.SetAnnotations(annotations) _, err = d.client.CoreV1().Namespaces().Update(ctx, ns, metav1.UpdateOptions{}) logrus.Debugf("Saving status annotation to namespace %s: %+v", namespace, err) // errors.IsConflict is safe to ignore since multiple log-routers try update at same time // (only 1 router can update this unique ResourceVersion, no need to retry, each router is a retry process): if err != nil && !errors.IsConflict(err) { logrus.Infof("Cannot set error status on namespace %s: %+v", namespace, err) } } // discoverNamespaces constructs a list of namespaces to inspect for fluentd // configuration, using the configured list if provided, otherwise find only // namespaces that have fluentd configmaps based on default name, and if that fails // find all namespace and iterrate through them. func (d *kubeInformerConnection) discoverNamespaces(ctx context.Context) ([]string, error) { var namespaces []string if len(d.cfg.Namespaces) != 0 { namespaces = d.cfg.Namespaces } else { if d.cfg.Datasource == "crd" { logrus.Infof("Discovering only namespaces that have fluentdconfig crd defined.") nsList, err := d.discoverFluentdConfigNamespaces() if err != nil { return nil, err } namespaces = nsList } else { // Find the configmaps that exist on this cluster to find namespaces: confMapsList, err := d.cmlist.List(labels.NewSelector()) if err != nil { return nil, fmt.Errorf("Failed to list all configmaps in cluster: %v", err) } // If default configmap name is defined get all namespaces for those configmaps: if d.cfg.DefaultConfigmapName != "" { for _, cfmap := range confMapsList { if cfmap.ObjectMeta.Name == d.cfg.DefaultConfigmapName { namespaces = append(namespaces, cfmap.ObjectMeta.Namespace) } else { // We need to find configmaps that honor the global annotation for configmaps: configMapNamespace, _ := d.nslist.Get(cfmap.ObjectMeta.Namespace) configMapName := configMapNamespace.Annotations[d.cfg.AnnotConfigmapName] if configMapName != "" { namespaces = append(namespaces, cfmap.ObjectMeta.Namespace) } } } if d.cfg.CRDMigrationMode { nsList, err := d.discoverFluentdConfigNamespaces() if err != nil { return nil, err } namespaces = append(namespaces, nsList...) } } else { // get all namespaces and iterrate through them like before: nses, err := d.nslist.List(labels.NewSelector()) if err != nil { return nil, fmt.Errorf("Failed to list all namespaces in cluster: %v", err) } namespaces = make([]string, 0) for _, ns := range nses { namespaces = append(namespaces, ns.ObjectMeta.Name) } } } } // Remove duplicates (crds can be many in single namespace): nsKeys := make(map[string]bool) nsList := []string{} for _, ns := range namespaces { if _, value := nsKeys[ns]; !value { nsKeys[ns] = true nsList = append(nsList, ns) } } // Sort the namespaces: sort.Strings(nsList) return nsList, nil } func (d *kubeInformerConnection) handlePodChange(ctx context.Context, obj interface{}) { mObj := obj.(*core.Pod) logrus.Tracef("Detected pod change %s in namespace: %s", mObj.GetName(), mObj.GetNamespace()) configdata, err := d.kubeds.GetFluentdConfig(ctx, mObj.GetNamespace()) nsConfigStr := fmt.Sprintf("%#v", configdata) if err == nil { if strings.Contains(nsConfigStr, "mounted-file") { podLabels := mObj.GetLabels() mountedLabel := d.mountedLabels[mObj.GetNamespace()] for _, container := range mObj.Spec.Containers { if matchAny(podLabels, mountedLabel, container.Name) { logrus.Infof("Detected mounted-file pod change %s in namespace: %s", mObj.GetName(), mObj.GetNamespace()) select { case d.updateChan <- time.Now(): default: } } } } } } func matchAny(contLabels map[string]string, mountedLabelsInNs []map[string]string, name string) bool { for _, mountedLabels := range mountedLabelsInNs { if util.Match(mountedLabels, contLabels, name) { return true } } return false } func (d *kubeInformerConnection) discoverFluentdConfigNamespaces() ([]string, error) { if d.fdlist == nil { return nil, fmt.Errorf("Failed to initialize the fluentdconfig crd client, d.fclient = nil") } fcList, err := d.fdlist.List(labels.NewSelector()) if err != nil { return nil, fmt.Errorf("Failed to list all fluentdconfig crds in cluster: %v", err) } nsList := make([]string, 0) for _, crd := range fcList { nsList = append(nsList, crd.ObjectMeta.Namespace) } logrus.Debugf("Returned these namespaces for fluentdconfig crds: %v", nsList) return nsList, nil }
package factorial import "testing" func TestFactorial(t *testing.T) { check := func(in uint, expected uint) { if out := Factorial(in); out != expected { t.Errorf("factorial of %d is %d and not %d", in, expected, out) } } check(0, 1) check(1, 1) check(2, 2) check(3, 6) check(4, 24) }
package paizaio_test import ( "net/url" "testing" "github.com/pocke/paizaio" ) var api = paizaio.NewAPI() var idCh = make(chan string, 1) var getID = func() func() string { var id string return func() string { if id != "" { return id } id = <-idCh return id } }() const code = ` package main import "fmt" func main() { fmt.Println("Hello World!") } ` func TestRunnerCreate(t *testing.T) { v := url.Values{} v.Add("language", "go") v.Add("source_code", code) r, err := api.RunnerCreate(v) t.Logf("%+v", r) if err != nil { t.Error(err) } idCh <- r.ID v.Set("language", "Golang") _, err = api.RunnerCreate(v) if err == nil { t.Error("Should raise error when dont allowed language. But not raise.") } } func TestRunnerStatus(t *testing.T) { id := getID() r, err := api.RunnerStatus(id) if err != nil { t.Error(err) } t.Log(r) invalidID := "ほげふがぴよぴよ" r, err = api.RunnerStatus(invalidID) if err == nil { t.Logf("%+v", r) t.Error("Should return error when ID doesn't exists. But not return error.") } } func TestRunnerDetails(t *testing.T) { id := getID() d, err := api.RunnerDetails(id) if err != nil { t.Error(err) } t.Log(d) invalidID := "ほげふがぴよぴよ" d, err = api.RunnerDetails(invalidID) if err == nil { t.Logf("%+v", d) t.Error("Should return error when ID doesn't exists. But not return error.") } }
package main import ( "fmt" "sort" ) func sumSubseqWidths(A []int) int { sort.Ints(A) const mod = 1e9 + 7 var c = 1 var res = 0 var n = len(A) for i, v := range A { res = (res+v*c - A[n-1-i]*c)%mod c = (c << 1) % mod } return res } func main() { fmt.Println(sumSubseqWidths([]int{2, 1, 3})) }
package main import ( "html" "regexp" "strings" ) var ( ReIgnoreBlock = map[string]*regexp.Regexp{ "doctype": regexp.MustCompile(`(?ims)<!DOCTYPE.*?>`), // raw doctype "comment": regexp.MustCompile(`(?ims)<!--.*?-->`), // raw comment "script": regexp.MustCompile(`(?ims)<script.*?>.*?</script>`), // javascript "noscript": regexp.MustCompile(`(?ims)<noscript.*?>.*?</noscript>`), // javascript "style": regexp.MustCompile(`(?ims)<style.*?>.*?</style>`), // css "link": regexp.MustCompile(`(?ims)<link.*?>`), // css } ReNewLineBlock = map[string]*regexp.Regexp{ "<div>": regexp.MustCompile(`(?is)<div.*?>`), "<p>": regexp.MustCompile(`(?is)<p.*?>`), "<br>": regexp.MustCompile(`(?is)<br.*?>`), "<hr>": regexp.MustCompile(`(?is)<hr.*?>`), "<li>": regexp.MustCompile(`(?is)<li.*?>`), } ReMultiNewLine = regexp.MustCompile(`(?m)\n+`) ReTag = regexp.MustCompile(`(?ims)<.*?>`) ) func TextFromHTML(rawhtml string) string { lines := strings.Split(rawhtml, "\n") for i, _ := range lines { lines[i] = strings.TrimSpace(lines[i]) } rawhtml = strings.Join(lines, "\n") for _, v := range ReIgnoreBlock { rawhtml = v.ReplaceAllString(rawhtml, "") } for k, v := range ReNewLineBlock { rawhtml = v.ReplaceAllString(rawhtml, "\n"+k) } rawhtml = ReMultiNewLine.ReplaceAllString(rawhtml, "\n") text := strings.TrimSpace(ReTag.ReplaceAllString(rawhtml, "")) lines = strings.Split(text, "\n") for i, _ := range lines { lines[i] = strings.TrimSpace(lines[i]) } return html.UnescapeString(strings.Join(lines, "\n")) }
package response type Maven struct { ArtifactId string `json:"artifactId"` LatestVersion string `json:"latestVersion"` GroupId string `json:"groupId"` } func (m *Maven) SetProperties(ArtifactId,GroupId ,LatestVersion string) { m.ArtifactId = ArtifactId m.LatestVersion = LatestVersion m.GroupId=GroupId }
package caryatid import ( "encoding/json" "fmt" "testing" ) func TestJsonDecodingProvider(t *testing.T) { jstring := `{"name":"testname","url":"http://example.com/whatever","checksum_type":"dummy","checksum":"dummy"}` var prov Provider err := json.Unmarshal([]byte(jstring), &prov) if err != nil { t.Fatal(fmt.Sprintf("Error unmarshalling JSON: %s", err)) } if prov.Name != "testname" { t.Fatal(fmt.Sprintf("Decoded JSON object had bad Name property; should be 'testname' but was '%s'", prov.Name)) } } func TestJsonDecodingCatalog(t *testing.T) { jstring := `{"name":"examplebox","description":"this is an example box","versions":[{"version":"12.34.56","providers":[{"name":"testname","url":"http://example.com/whatever","checksum_type":"dummy","checksum":"dummy"}]}]}` var cata Catalog err := json.Unmarshal([]byte(jstring), &cata) if err != nil { t.Fatal(fmt.Sprintf("Error unmarshalling JSON: %s", err)) } if cata.Name != "examplebox" { t.Fatal(fmt.Sprintf("Decoded JSON had bad Name property; should be 'examplebox' but was '%s'", cata.Name)) } if len(cata.Versions) != 1 { t.Fatal(fmt.Sprintf("Expected decoded JSON to have %v elements in its Versions property, but actually had %v", 1, len(cata.Versions))) } vers := cata.Versions[0] if vers.Version != "12.34.56" { t.Fatal(fmt.Sprintf("Expected decoded JSON to have a Version with a version of '%s', but actually had a version of '%s'", "12.34.56", vers.Version)) } if len(vers.Providers) != 1 { t.Fatal(fmt.Sprintf("Expected first Version to have %v elements in its Providers property, but actually had %v", 1, len(vers.Providers))) } prov := vers.Providers[0] if prov.Name != "testname" { t.Fatal(fmt.Sprintf("Expected first Provider to have a Name of '%s', but actually had '%s'", "testname", prov.Name)) } } func TestJsonDecodingEmptyCatalog(t *testing.T) { var cata Catalog err := json.Unmarshal([]byte("{}"), &cata) if err != nil { t.Fatal("Failed to unmarshal empty catalog with error:", err) } } func TestProviderEquals(t *testing.T) { matchingp1 := Provider{"TestProviderX", "http://example.com/pX", "TestChecksum", "0xB00B135"} matchingp2 := Provider{"TestProviderX", "http://example.com/pX", "TestChecksum", "0xB00B135"} unmatchingp := []Provider{ Provider{"TestProviderYaaaas", "http://example.com/pX", "TestChecksum", "0xB00B135"}, Provider{"TestProviderX", "http://example.com/pother", "TestChecksum", "0xB00B135"}, Provider{"TestProviderX", "http://example.com/pX", "DifferentChecksum", "0xB00B135"}, Provider{"TestProviderX", "http://example.com/pX", "TestChecksum", "0xDECAFBADxxxxx"}, } if !matchingp1.Equals(&matchingp2) { t.Fatal("Providers that should have matched do not match") } for idx := 0; idx < len(unmatchingp); idx += 1 { if matchingp1.Equals(&unmatchingp[idx]) { t.Fatal(fmt.Sprintf("Providers that should not have matched did match. Failing non-matching provider: %v", unmatchingp[idx])) } } } func TestVersionEquals(t *testing.T) { p1 := Provider{"TestProviderOne", "http://example.com/One", "TestChecksum", "0xB00B135"} p2 := Provider{"TestProviderTwo", "http://example.com/Two", "TestChecksum", "0xB00B135"} matchingv1 := Version{"1.2.3", []Provider{p1, p2}} matchingv2 := Version{"1.2.3", []Provider{p1, p2}} unmatchingv := []Version{ Version{"1.2.3", []Provider{p2}}, Version{"1.2.4", []Provider{p1}}, Version{"1.2.3", []Provider{p1, p2, p2}}, } if !matchingv1.Equals(&matchingv2) { t.Fatal("Versions that should have matched did not match") } for idx := 0; idx < len(unmatchingv); idx += 1 { if matchingv1.Equals(&unmatchingv[idx]) { t.Fatal(fmt.Sprintf("Versions that should not have matched did match. Failing non-matching version: %v", unmatchingv[idx])) } } } func TestCatalogEquals(t *testing.T) { p1 := Provider{"TestProvider", "http://example.com/Provider", "TestChecksum", "0xB00B135"} v1 := Version{"1.2.3", []Provider{p1}} v2 := Version{"1.2.4", []Provider{p1}} matchingc1 := Catalog{"SomeName", "This is a desc", []Version{v1, v2}} matchingc2 := Catalog{"SomeName", "This is a desc", []Version{v1, v2}} unmatchingc := []Catalog{ Catalog{"SomeOtherName", "This is a desc", []Version{v1, v2}}, Catalog{"SomeName", "This is a completely different desc", []Version{v1, v2}}, Catalog{"SomeName", "This is a desc", []Version{v1}}, Catalog{"SomeName", "This is a desc", []Version{v1, v2, v2}}, Catalog{"SomeName", "This is a desc", []Version{v2, v1}}, } if !matchingc1.Equals(&matchingc2) { t.Fatal("Catalogs that should have matched did not match") } for idx := 0; idx < len(unmatchingc); idx += 1 { if matchingc1.Equals(&unmatchingc[idx]) { t.Fatal(fmt.Sprintf("Catalogs that should not have matched did match. Failing non-matching version: %v", unmatchingc[idx])) } } } func TestCatalogAddBox(t *testing.T) { addBoxName := "TESTBOX" addBoxDesc := "This is a description of TESTBOX" addBoxVers := "2.4.9" addBoxProv := "PROVIDER" addBoxCataRoot := "file:///catalog/root" addBoxCataUri := fmt.Sprintf("%v/%v.json", addBoxCataRoot, addBoxName) addBoxExpectedUrl := fmt.Sprintf("%v/%v/%v_%v_%v.box", addBoxCataRoot, addBoxName, addBoxName, addBoxVers, addBoxProv) addBoxCheckType := "CHECKSUMTYPE" addBoxChecksum := "0xDECAFBAD" addAndCompareCata := func(description string, initial *Catalog, expected *Catalog, boxName string, boxDesc string, boxVers string, boxProv string, boxCheckType string, boxCheck string) { if err := initial.AddBox(addBoxCataUri, boxName, boxDesc, boxVers, boxProv, boxCheckType, boxCheck); err != nil { t.Fatal(fmt.Sprintf("Error calling AddBox in test '%v': %v", description, err)) } if !initial.Equals(expected) { t.Fatal(fmt.Sprintf("Test '%v' failed\nInitial catalog:\n%v\nExpected catalog:\n%v\n", description, initial, expected)) } } addAndCompareCata( "Add box to empty catalog", &Catalog{}, &Catalog{addBoxName, addBoxDesc, []Version{ Version{addBoxVers, []Provider{ Provider{addBoxProv, addBoxExpectedUrl, addBoxCheckType, addBoxChecksum}, }}, }}, addBoxName, addBoxDesc, addBoxVers, addBoxProv, addBoxCheckType, addBoxChecksum, ) addAndCompareCata( "Add box to catalog where it's already present", &Catalog{addBoxName, addBoxDesc, []Version{ Version{addBoxVers, []Provider{ Provider{addBoxProv, addBoxExpectedUrl, addBoxCheckType, addBoxChecksum}, }}, }}, &Catalog{addBoxName, addBoxDesc, []Version{ Version{addBoxVers, []Provider{ Provider{addBoxProv, addBoxExpectedUrl, addBoxCheckType, addBoxChecksum}, }}, }}, addBoxName, addBoxDesc, addBoxVers, addBoxProv, addBoxCheckType, addBoxChecksum, ) addAndCompareCata( "Add box to catalog with empty version", &Catalog{addBoxName, addBoxDesc, []Version{}}, &Catalog{addBoxName, addBoxDesc, []Version{ Version{addBoxVers, []Provider{ Provider{addBoxProv, addBoxExpectedUrl, addBoxCheckType, addBoxChecksum}, }}, }}, addBoxName, addBoxDesc, addBoxVers, addBoxProv, addBoxCheckType, addBoxChecksum, ) addAndCompareCata( "Add box to catalog with different version", &Catalog{addBoxName, addBoxDesc, []Version{ Version{"2.3.0", []Provider{ Provider{addBoxProv, addBoxExpectedUrl, addBoxCheckType, addBoxChecksum}, }}, }}, &Catalog{addBoxName, addBoxDesc, []Version{ Version{"2.3.0", []Provider{ Provider{addBoxProv, addBoxExpectedUrl, addBoxCheckType, addBoxChecksum}, }}, Version{addBoxVers, []Provider{ Provider{addBoxProv, addBoxExpectedUrl, addBoxCheckType, addBoxChecksum}, }}, }}, addBoxName, addBoxDesc, addBoxVers, addBoxProv, addBoxCheckType, addBoxChecksum, ) addAndCompareCata( "Add box to catalog with empty provider", &Catalog{addBoxName, addBoxDesc, []Version{ Version{addBoxVers, []Provider{ Provider{}, }}, }}, &Catalog{addBoxName, addBoxDesc, []Version{ Version{addBoxVers, []Provider{ Provider{}, Provider{addBoxProv, addBoxExpectedUrl, addBoxCheckType, addBoxChecksum}, }}, }}, addBoxName, addBoxDesc, addBoxVers, addBoxProv, addBoxCheckType, addBoxChecksum, ) addAndCompareCata( "Add box to catalog with different provider", &Catalog{addBoxName, addBoxDesc, []Version{ Version{addBoxVers, []Provider{ Provider{"differentProvider", addBoxExpectedUrl, addBoxCheckType, addBoxChecksum}, }}, }}, &Catalog{addBoxName, addBoxDesc, []Version{ Version{addBoxVers, []Provider{ Provider{"differentProvider", addBoxExpectedUrl, addBoxCheckType, addBoxChecksum}, Provider{addBoxProv, addBoxExpectedUrl, addBoxCheckType, addBoxChecksum}, }}, }}, addBoxName, addBoxDesc, addBoxVers, addBoxProv, addBoxCheckType, addBoxChecksum, ) } type TestParameters struct { ProviderNames []string BoxUri string BoxName string BoxDesc string DigestType string Digest string } var tParams = TestParameters{ []string{"StrongSapling", "FeebleFungus"}, "http://example.com/this/is/my/box", "vagrant_catalog_test_box", "Vagrant Catalog Test Box is a test box", "CRC32", "0xB00B1E5", } var testCatalog = Catalog{tParams.BoxName, tParams.BoxDesc, []Version{ Version{"0.3.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"0.3.4", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"0.3.5-BETA", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.0.0", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.0.1", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.4.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.2.3", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.2.4", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"2.11.1", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, }} func TestQueryCatalogVersions(t *testing.T) { testQueryVers := func(initial *Catalog, query string, expectedResult *Catalog) { result, err := initial.QueryCatalogVersions(query) if err != nil { t.Fatalf("QueryCatalogVersions(%v) returned an error: %v\n", query, err) } else if !expectedResult.Equals(&result) { t.Fatalf("QueryCatalogVersions(%v) returned unexpected value(s). Actual:\n%v\nExpected:\n%v\n", query, result, expectedResult) } } testQueryVers(&testCatalog, ">2", &Catalog{tParams.BoxName, tParams.BoxDesc, []Version{ Version{"2.11.1", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, }}) testQueryVers(&testCatalog, "<=0.3.5", &Catalog{tParams.BoxName, tParams.BoxDesc, []Version{ Version{"0.3.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"0.3.4", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"0.3.5-BETA", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, }}) testQueryVers(&testCatalog, "0.3.5", &Catalog{tParams.BoxName, tParams.BoxDesc, []Version{ Version{"0.3.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"0.3.5-BETA", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, }}) testQueryVers(&testCatalog, "=0.3.5", &Catalog{tParams.BoxName, tParams.BoxDesc, []Version{ Version{"0.3.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, }}) testQueryVers(&testCatalog, "=0.3.6", &Catalog{tParams.BoxName, tParams.BoxDesc, []Version{}}) } func TestQueryCatalogProviders(t *testing.T) { testQueryProv := func(initial Catalog, query string, expectedResult Catalog) { result, err := initial.QueryCatalogProviders(query) if err != nil { t.Fatalf("QueryCatalogProviders() returned an error: %v\n", err) } else if !expectedResult.Equals(&result) { t.Fatalf("QueryCatalogProviders() returned unexpected value(s). Actual:\n%v\nExpected:\n%v\n", result, expectedResult) } } testQueryProv(testCatalog, "^Strong", Catalog{tParams.BoxName, tParams.BoxDesc, []Version{ Version{"0.3.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"0.3.5-BETA", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.0.0", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.4.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.2.3", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.2.4", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, }}) testQueryProv(testCatalog, "Sapling$", Catalog{tParams.BoxName, tParams.BoxDesc, []Version{ Version{"0.3.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"0.3.5-BETA", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.0.0", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.4.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.2.3", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.2.4", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, }}) testQueryProv(testCatalog, "F", Catalog{tParams.BoxName, tParams.BoxDesc, []Version{ Version{"0.3.4", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"0.3.5-BETA", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.0.1", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.2.3", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"2.11.1", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, }}) } func TestDeleteReferences(t *testing.T) { tDelRef := func(initial Catalog, refs []BoxReference, expectedResult Catalog) { result := initial.DeleteReferences(refs) if !expectedResult.Equals(&result) { t.Fatalf("DeleteReferences(%v) returned unexpected value(s). Actual:\n%v\nExpected:\n%v\n", refs, result.DisplayString(), expectedResult.DisplayString()) } } tDelRef(testCatalog, []BoxReference{}, testCatalog) tDelRef( testCatalog, []BoxReference{ BoxReference{Version: "0.3.5", ProviderName: tParams.ProviderNames[0]}, BoxReference{Version: "0.3.5-BETA", ProviderName: tParams.ProviderNames[0]}, BoxReference{Version: "0.3.4", ProviderName: tParams.ProviderNames[1]}, }, Catalog{tParams.BoxName, tParams.BoxDesc, []Version{ Version{"0.3.5-BETA", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.0.0", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.0.1", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.4.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.2.3", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.2.4", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"2.11.1", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, }}, ) } func TestDelete(t *testing.T) { testDelete := func(initial Catalog, query CatalogQueryParams, expectedResult Catalog) { result, err := initial.DeleteQuery(query) if err != nil { t.Fatalf("Delete(%v) returned an error: %v\n", query, err) } else if !expectedResult.Equals(&result) { t.Fatalf("Delete(%v) returned unexpected value(s). Actual:\n%v\nExpected:\n%v\n", query, result.DisplayString(), expectedResult.DisplayString()) } } testDelete(testCatalog, CatalogQueryParams{Version: "", Provider: ""}, Catalog{ tParams.BoxName, tParams.BoxDesc, []Version{}, }) testDelete(testCatalog, CatalogQueryParams{Version: "<=1", Provider: "Feeb"}, Catalog{ tParams.BoxName, tParams.BoxDesc, []Version{ Version{"0.3.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"0.3.5-BETA", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.0.0", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.0.1", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.4.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.2.3", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.2.4", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"2.11.1", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, }, }) testDelete(testCatalog, CatalogQueryParams{Version: "<=1.0.0", Provider: "Feeb"}, Catalog{ tParams.BoxName, tParams.BoxDesc, []Version{ Version{"0.3.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"0.3.5-BETA", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.0.0", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.0.1", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.4.5", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.2.3", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"1.2.4", []Provider{ Provider{tParams.ProviderNames[0], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, Version{"2.11.1", []Provider{ Provider{tParams.ProviderNames[1], tParams.BoxUri, tParams.DigestType, tParams.Digest}, }}, }, }) }
package main import ( "net/http" "log" "io/ioutil" "github.com/json-iterator/go" cmc "github.com/coincircle/go-coinmarketcap" "net/url" "fmt" "telegram-bot-api" "strings" ) var ( json = jsoniter.ConfigCompatibleWithStandardLibrary ) func getTransactions(address string, timestamp string) (txsSuccess []Transaction) { url := config.RippleUrlBase + address + config.RippleUrlParams + timestamp log.Print(url) resp, err := http.Get(url) if err != nil { log.Print(err) return } defer resp.Body.Close() bodyBytes, err := ioutil.ReadAll(resp.Body) if err != nil { log.Print(err) return } //log.Print(string(bodyBytes)) var txs []Transaction str := json.Get(bodyBytes, "transactions").ToString() log.Print(str) err = json.UnmarshalFromString(str, &txs) if err != nil { log.Print(err) return } for _, tx := range txs{ if tx.Meta.TransactionResult == "tesSUCCESS"{ txsSuccess = append(txsSuccess, tx) } } return } func sendNotifications(txs []Transaction, wallet Wallet) { var users []User db.Model(&wallet).Related(&users, "Users") for _, user := range users { var text string for _, tx := range txs { amount := stringToInt64(tx.Tx.Amount) decAmount := float64(amount) / 1000000 decAmountStr := float64ToString(decAmount) var uw UserWallet db.First(&uw, "user_id = ? AND wallet_id = ?", user.ID, wallet.ID) name := "your" if uw.Name != "" { name = "*" + uw.Name + "*" } var balance string for _, node := range tx.Meta.AffectedNodes { if node.Modified.Data.Account == wallet.Address { balance = node.Modified.Data.Balance } } balanceInt := stringToInt64(balance) decBalance := float64(balanceInt) / 1000000 decBalanceStr := float64ToString(decBalance) if tx.Tx.Destination == wallet.Address { text = "💰 You received *" + decAmountStr + " XRP* on " } else { text = "💸 You sent *" + decAmountStr + " XRP* from " } text += name + " wallet\n\n" + "New balance:\n*" + decBalanceStr + " XRP* ≈ " price, err := cmc.Price(&cmc.PriceOptions{ Symbol: "XRP", Convert: user.Currency, }) if err != nil { log.Print(err) } text += float64ToString(price*decBalance) + " "+user.Currency+"\n" *txKeyboard.InlineKeyboard[0][0].URL = "https://xrpcharts.ripple.com/#/transactions/" + tx.Hash sendMessage(user.ID, text, txKeyboard) } } } func shiftArray(arr *[]float64) { for i := range *arr { if i+1 <= len(*arr)-1 { (*arr)[i] = (*arr)[i+1] } else { (*arr)[i] = 0 } } } func tweet(text string) { _, err := twitter.PostTweet(text+phrases[20], url.Values{}) if err != nil { log.Print(err) log.Print(text) } } //func sendAllUsers(text string, keyboard interface{}){ // rows, _ := db.Table("users").Rows() // for rows.Next() { // var user User // db.ScanRows(rows, &user) // sendMessage(user.ID, text, keyboard) // } //} func sendAllUsersMessageConfig(msg tgbotapi.MessageConfig){ rows, _ := db.Table("users").Rows() for rows.Next() { var user User db.ScanRows(rows, &user) msg.ChatID = user.ID msg.ParseMode = tgbotapi.ModeMarkdown _, err := bot.Send(msg) if err != nil{ log.Print(err) } } } func convertAndSendAllUsers(template string,price float64, keyboard interface{}){ rows, _ := db.Table("users").Rows() for rows.Next() { var user User db.ScanRows(rows, &user) currPrice := price * rates[user.Currency] text := fmt.Sprintf(template, float64ToStringPrec3(currPrice)) text = strings.Replace(text, "USD", user.Currency, -1) sendMessage(user.ID, text, keyboard) } } func sendAllGroupsMessageConfig(msg tgbotapi.MessageConfig){ rows, _ := db.Table("groups").Rows() for rows.Next() { var g Group db.ScanRows(rows, &g) msg.ChatID = g.ID msg.ParseMode = tgbotapi.ModeMarkdown _, err := bot.Send(msg) if err != nil{ log.Print(err) } } } func sendAllGroups(text string){ rows, _ := db.Table("groups").Rows() for rows.Next() { var g Group db.ScanRows(rows, &g) sendMessage(g.ID, text, nil) } }
package main import "fmt" //------------------------------------------------------------------------------ // https://leetcode-cn.com/problems/total-hamming-distance/ func totalHammingDistance(nums []int) int { return totalHammingDistance2(nums) } func totalHammingDistance2(nums []int) int { const bitNum = 30 N := len(nums) ans, cnt := 0, 0 for i := 0; i < bitNum; i++ { u := 1 << uint(i) for j := 0; j < N; j++ { if nums[j]&u != 0 { cnt++ } } ans += (N - cnt) * cnt cnt = 0 } return ans } func totalHammingDistance0(nums []int) int { const bitNum = 32 N := len(nums) bitCnt := make([]int, bitNum) ans := 0 for i := 0; i < N; i++ { for v := uint(nums[i]); v != 0; { //j := bits.TrailingZeros(v) //bitCnt[j]++ //v ^= 1<<j } } for j := 0; j < bitNum; j++ { ans += bitCnt[j] * (N - bitCnt[j]) } return ans } func totalHammingDistance1(nums []int) int { ans := 0 for i := 0; i < len(nums); i++ { for j := i + 1; j < len(nums); j++ { // 使用 bits.OnesCount 直接统计, 不会超时 // ans += bits.OnesCount(uint(nums[i]^nums[j])) // 下面方法会超时 for v := nums[i] ^ nums[j]; v > 0; v &= v - 1 { ans++ } } } return ans } func main() { cases := [][]int{ {4, 14, 2}, } realCase := cases[0:] for i, c := range realCase { fmt.Println("## case", i) // solve fmt.Println(totalHammingDistance(c)) } }
package main import ( "path/filepath" "os" ) type Repo struct { mainPath string objPath string } func (r *Repo) createObjectDatabase() { dirName, err := filepath.Abs(r.mainPath + "objects") check(err) os.Mkdir(dirName, 0755) r.objPath = dirName }
package alicloud import ( "net/http" "testing" ) func TestHttpCall_Get(t *testing.T) { req, _ := http.NewRequest("GET", "http://www.baidu.com", nil) bytes, err := http_call(req) if err != nil { t.Log("output:" + string(bytes)) t.Error(err) } } func TestHttpCall_with_error(t *testing.T) { req, _ := http.NewRequest("GET", "http://api.yunpan.alibaba.com/api/upload/commit", nil) _, err := http_call(req) if err == nil { t.Error("Error is expected") } else { t.Log("Got expected error:", err.(ApiError).ErrorDescription) } }
package Problem0137 import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // tcs is testcase slice var tcs = []struct { nums []int ans int }{ { []int{43, 16, 45, 89, 45, -2147483648, 45, 2147483646, -2147483647, -2147483648, 43, 2147483647, -2147483646, -2147483648, 89, -2147483646, 89, -2147483646, -2147483647, 2147483646, -2147483647, 16, 16, 2147483646, 43}, 2147483647, }, { []int{-2, -2, 1, 1, -3, 1, -3, -3, -4, -2}, -4, }, { []int{1, 1, 1, 2, 2, 2, 3}, 3, }, // 可以有多个 testcase } func Test_singleNumber(t *testing.T) { ast := assert.New(t) for _, tc := range tcs { fmt.Printf("~~%v~~\n", tc) ast.Equal(tc.ans, singleNumber(tc.nums), "输入:%v", tc) } } func Benchmark_singleNumber(b *testing.B) { for i := 0; i < b.N; i++ { for _, tc := range tcs { singleNumber(tc.nums) } } }
type TileQueueNode struct { next *TileQueueNode tile *Tile } type TileQueue struct { current *TileQueueNode end *TileQueueNode } func (q TileQueue) push(tile *Tile) { node := &TileQueueNode{ next: nil, tile: tile, } if q.current == nil { q.current = node q.end = node } else { q.end.next = node q.end = node } } func (q TileQueue) pop(tile *Tile) *Tile { out := q.current q.current = out.next return out } func createTiles() [][]*Tile { out := [][]*Tile{} for y := uint16(0); y < map_width; y++ { row := []*Tile{} for x := uint16(0); x < map_height; x++ { row = append(row, &Tile{ geo: Geography { altitude: uint8((x + y)*10 % 256), temperature: uint8(y), humidity: uint8(x), }, }) } out = append(out, row) } return out }
package phone_dao import ( _db "database/sql" "log" ) //查询所有部门列表 func GetAllDepartment(db * _db.DB) ([] Department,error ){ rows,err:=db.Query(`select d_id,d_name from department order by 1`) if nil!=err{ log.Fatal(err) } var ret [] Department for rows.Next() { var d * Department d=new(Department) rows.Scan(&d.DeptId, &d.DeptName) ret=append(ret,*d) } rows.Close() return ret,err } //根据部门查询人员ID/姓名 func GetPersonListByDeptId(db * _db.DB,id int32,)([] Person,error){ var ret [] Person rows, err := db.Query(`select p.p_id,p.p_name,p.p_phone,p.p_tel, p.p_mail ,p.p_position,p.t_id,t.t_name, p.d_id,d.d_name from person p,department d,team t where p.t_id=t.t_id and p.d_id=d.d_id and p.d_id=?`,id) if err != nil { log.Fatal(err) } for rows.Next() { var p * Person p=new(Person) rows.Scan(&p.PId,&p.Name,&p.Phone,&p.Tel,&p.Mail,&p.Position,&p.TeamId,&p.TeamName,&p.DeptId,&p.DeptName) ret=append(ret,*p) } rows.Close() return ret,err } func GetAllPerson(db * _db.DB) ([] Person,error){ var ret [] Person rows,err:=db.Query(`select p.p_id,p.p_name,p.p_phone,p.p_tel, p.p_mail ,p.p_position,p.t_id,t.t_name, p.d_id,d.d_name from person p,department d,team t where p.t_id=t.t_id and p.d_id=d.d_id`) if nil!=err{ log.Fatal(err) } for rows.Next() { var p * Person p=new(Person) rows.Scan(&p.PId,&p.Name,&p.Phone,&p.Tel,&p.Mail,&p.Position,&p.TeamId,&p.TeamName,&p.DeptId,&p.DeptName) ret=append(ret,*p) } rows.Close() return ret,err } //查询某一人 func GetPersonById(db * _db.DB,id int64) (Person,error){ var p Person rows,err:=db.Query(`select p.p_id,p.p_name,p.p_phone,p.p_tel, p.p_mail ,p.p_position,p.t_id,t.t_name, p.d_id,d.d_name from person p,department d,team t where p.t_id=t.t_id and p.d_id=d.d_id and p.p_id=?`,id) if nil!=err{ log.Fatal(err) } for rows.Next() { rows.Scan(&p.PId,&p.Name,&p.Phone,&p.Tel,&p.Mail,&p.Position,&p.TeamId,&p.TeamName,&p.DeptId,&p.DeptName) } rows.Close() return p,err } func GetPersonByQuery(db * _db.DB,query string)([] Person,error){ var ret [] Person tmp:="%"+query+"%" rows,err:=db.Query(`select p.p_id,p.p_name,p.p_phone,p.p_tel, p.p_mail ,p.p_position,p.t_id,t.t_name, p.d_id,d.d_name from person p,department d,team t where p.t_id=t.t_id and p.d_id=d.d_id and (p.p_name like ? or p.p_mail like ? or p.p_phone like ?)`,tmp,tmp,tmp) if nil!=err{ log.Fatal(err) } for rows.Next() { var p * Person p=new(Person) rows.Scan(&p.PId,&p.Name,&p.Phone,&p.Tel,&p.Mail,&p.Position,&p.TeamId,&p.TeamName,&p.DeptId,&p.DeptName) ret=append(ret,*p) } rows.Close() return ret,err }
package main import ("fmt" "math") func main(){ var a,vo,so,t float64 fmt.Println("Enter value for acceleration:") fmt.Scan(&a) fmt.Println("Enter value for initial velocity:") fmt.Scan(&vo) fmt.Println("Enter value for initial displacement:") fmt.Scan(&so) fmt.Println("Enter value for time:") fmt.Scan(&t) fn:=GenDisplaceFn(a,vo,so) fmt.Println("Linear Displacement = ",fn(t)) } func GenDisplaceFn(a,vo,so float64) func (t float64) float64{ f:=func (t float64) float64{ T:=math.Pow(t,2) s:=(0.5*a*T)+(vo*t)+so return(s) } return(f) }
package main import ( "bufio" "log" "net" ) func main() { ln, err := net.Listen("tcp", ":2020") if err != nil { log.Fatalf("listen error: %v", err) } accepted := 0 for { conn, err := ln.Accept() if err != nil { log.Fatalf("accept error: %v", err) } accepted++ go serve(conn) log.Printf("Accepted %d", accepted) } } func serve(conn net.Conn) { bufr := bufio.NewReader(conn) for { line, err := bufr.ReadString('\n') if err != nil { return } conn.Write([]byte(line)) } }
package gamesapi import ( "backend/internal/domain" "backend/internal/usecase/startgameusecase" "github.com/gorilla/mux" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "net/http" "net/http/httptest" "net/url" "strings" "testing" ) func Test_Start_a_new_game(t *testing.T) { basePath, err := url.Parse("https://mydomain") require.NoError(t, err) gameId, err := domain.ParseGameId("b06d89ce-4be5-4f19-9e69-04e79a83c6c1") require.NoError(t, err) startGameUseCaseMock := startgameusecase.Mock() startGameUseCaseMock.ReturnGameId(gameId) sut := NewGamesApi(basePath, startGameUseCaseMock) reqBody := `{ "title": "Sprint 23 planning" }` req, err := http.NewRequest("POST", "/games", strings.NewReader(reqBody)) require.NoError(t, err) rr := httptest.NewRecorder() handleWithGamesApi(sut, rr, req) assert.Equal(t, http.StatusCreated, rr.Code) location := rr.Header().Get("Location") assert.Equal(t, "https://mydomain/games/b06d89ce-4be5-4f19-9e69-04e79a83c6c1", location) } func Test_Start_a_new_game_when_use_case_fails(t *testing.T) { basePath, err := url.Parse("https://mydomain") require.NoError(t, err) startGameUseCaseMock := startgameusecase.Mock() startGameUseCaseMock.ReturnError() sut := NewGamesApi(basePath, startGameUseCaseMock) reqBody := `{ "title": "Sprint 23 planning" }` req, err := http.NewRequest("POST", "/games", strings.NewReader(reqBody)) require.NoError(t, err) rr := httptest.NewRecorder() handleWithGamesApi(sut, rr, req) assert.Equal(t, http.StatusInternalServerError, rr.Code) assert.Equal(t, "Internal Server Error\n", rr.Body.String()) } func handleWithGamesApi(api *GamesApi, w http.ResponseWriter, req *http.Request) { router := mux.NewRouter() api.AddRoutes(router) handler := http.HandlerFunc(router.ServeHTTP) handler.ServeHTTP(w, req) }
package main import ( "context" "log" "github.com/micro/go-micro/v2" microclient "github.com/micro/go-micro/v2/client" pb "github.com/vlasove/Lec14/usercli/proto/user" ) func main() { srv := micro.NewService( micro.Name("usercli"), micro.Version("latest"), ) srv.Init() //создаем функционал клиента client := pb.NewUserService("userserver", microclient.DefaultClient) ////Кого будем скармливать БД name := "Evgen Petrov" email := "evgeny_vlasov@gmail.com" password := "123456789q" company := "Evgen.IO" user := &pb.User{ Name: name, Email: email, Password: password, Company: company, } //Доабвляем юзера в БД resp, err := client.Create(context.TODO(), user) if err != nil { log.Fatalf("could not create user: %v", err) } log.Printf("User created: %s", resp.User.Name) allUsers, err := client.GetAll(context.TODO(), &pb.Request{}) if err != nil { log.Fatalf("DB empty/could not listing all users") } log.Printf("Find %v users in DB", allUsers) //RPC вызов аутентификации (пытается найти юзера по емейл в БД) securityUser := &pb.User{ Email: email, Password: password, } authResponse, err := client.Auth(context.TODO(), securityUser) if err != nil { log.Fatalf("can not auth for user: %v", err) } //В случае если все ок - выбитый токен кидаем в log log.Printf("Access token: %s \n", authResponse.Token) return }
package middleware import ( "github.com/gin-gonic/gin" "github.com/satori/go.uuid" ) const ( RequestIDHeaderKey = "X-Request-Id" ServerHeaderValue = "MessageDB" ) func RequestIdMiddleware() gin.HandlerFunc { return func(ctx *gin.Context) { ctx.Writer.Header().Set("X-Request-Id", uuid.NewV4().String()) ctx.Writer.Header().Set("Server", ServerHeaderValue) ctx.Next() } }
// // hgps -- a resource class for caching Horizon GPS data // // Cache your Horizon GPS data in a "smart" GpsCache instance. Cache features: // - (optional) obfuscate location within specified distance from actual loc // (note that this works correctly for any location anywhere on the globe) // - (optional) can discover elevation when not specified (i.e., ground level) // - caches GPS fixes -- once a fix is found, coordinates are never again zero // Note that GpsCache instances are also thread safe. // // Usage example: // var p *GpsCache = hgps.New() // err := p.SetLocationSourceAndAccuracyInKm(source, gps, accuracy_km) // t := p.SetLocation(lat, lon, -1.0) // Requests elevation discovery // lat, lon, elev := p.GetLocation() // json_str := p.GetAsJSON() // // Written by Glen Darling (glendarling@us.ibm.com), Oct. 2016 // package hgps import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "math/rand" "net/http" // "strconv" // "strings" "sync" "time" // Local modules "gpsdc" "logutil" // For location obfuscation "github.com/kellydunn/golang-geo" ) // DEBUG: // 0 : No debug output from this module // 1 : Trace all state changes // 2 : Also dump full state at each state change // 3 : Also show location obfuscation and altitude discovery const DEBUG = 0 // How long to delay between retries when seeking the public IP address const GET_PUBLIC_IP_RETRY_SEC = 10 // How long to delay between retries for location estimate from IP address const LOC_ESTIMATE_RETRY_SEC = 10 type SourceType string const ( MANUAL SourceType = "Manual" ESTIMATED SourceType = "Estimated" SEARCHING SourceType = "Searching" GPS SourceType = "GPS" ) // JSON struct for location data type LocationData struct { Latitude float64 `json:"latitude" description:"Location latitude"` Longitude float64 `json:"longitude" description:"Location longitude"` ElevationM float64 `json:"elevation" description:"Location elevation in meters"` AccuracyKM float64 `json:"accuracy_km" description:"Location accuracy in kilometers"` LocSource SourceType `json:"loc_source" description:"Location source (one of: Manual, Estimated, GPS, or Searching)"` LastUpdate int64 `json:"loc_last_update" description:"Time of most recent location update (UTC)."` } // JSON struct for satellite data type SatellitesData struct { Satellites []SatelliteData `json:"satellites" description:"Array of data for each of the attached satellites."` } // JSON struct for data about a single satellite type SatelliteData struct { PRN float64 `json:"PRN" description:"PRN ID of the satellite. 1-63 are GNSS satellites, 64-96 are GLONASS satellites, 100-164 are SBAS satellites"` Az float64 `json:"az" description:"Azimuth, degrees from true north."` El float64 `json:"el" description:"Elevation in degrees."` Ss float64 `json:"ss" description:"Signal strength in dB."` Used bool `json:"used" description:"Used in current solution? (SBAS/WAAS/EGNOS satellites may be flagged used if the solution has corrections from them, but not all drivers make this information available.) "` } // JSON struct for Horizon GPS data type GpsData struct { Location LocationData `json:"location" description:"Location"` Satellites []SatelliteData `json:"satellites" description:"Data about discovered satellites."` } // The GpsCache "class" type GpsCache struct { data GpsData mutex sync.RWMutex } // GpsCache "constructor" func New() *GpsCache { n := &GpsCache{} print(n) return n } // Set the source of the location data (Manual, Estimated, GPS, or Searching) func (h *GpsCache) SetLocationSource(loc_source SourceType) { h.mutex.Lock() logutil.LogDebug("SetLocationSource(loc_source=%v)\n", loc_source) // The policy of not obfuscating if source is gps is enforced when env vars are read, so we do not need to do it here // if GPS == loc_source || SEARCHING == loc_source { // if 0.0 != h.data.Location.AccuracyKM { // logutil.Logf("Forcing accuracy_km to 0.0 for location source %q.\n", loc_source) // } // h.data.Location.AccuracyKM = 0.0 // } h.data.Location.LocSource = loc_source print(h) h.mutex.Unlock() return } // Get the source of the location data (Manual, Estimated, GPS, or Searching) func (h *GpsCache) GetLocationSource() (loc_source SourceType) { h.mutex.Lock() loc_source = h.data.Location.LocSource h.mutex.Unlock() return } // Set location source data, accuracy distance, and enforce policy constraints func (h *GpsCache) SetLocationAccuracyInKm(accuracy_km float64) { h.mutex.Lock() logutil.LogDebug("SetLocationAccuracyInKm(accuracy_km=%f)\n", accuracy_km) // The policy of not obfuscating if source is gps is enforced when env vars are read, so we do not need to do it here // loc_source := h.data.Location.LocSource // if 0.0 != accuracy_km && (GPS == loc_source || SEARCHING == loc_source) { // err = errors.New(fmt.Sprintf("ERROR: Nonzero location accuracy (%f) is not permitted when location data source is %q.", accuracy_km, loc_source)) // } else { h.data.Location.AccuracyKM = accuracy_km print(h) // err = nil // } h.mutex.Unlock() return } // Set satellite data func (h *GpsCache) SetSatellites(report *gpsdc.SKYReport) { sats := report.Satellites h.mutex.Lock() if DEBUG > 0 { logutil.LogDebug("SetSatellites(%d satellites found):", len(sats)) for _, sat := range sats { logutil.LogDebug(" PRN:%.1f, Az=%.1f, El=%.1f, Ss=%.1f, Used=%v", sat.PRN, sat.Az, sat.El, sat.Ss, sat.Used) } } // Clear the existing slice, then fill it from the gosdc data h.data.Satellites = nil for _, sat := range sats { var one SatelliteData one.PRN = sat.PRN one.Az = sat.Az one.El = sat.El one.Ss = sat.Ss one.Used = sat.Used h.data.Satellites = append(h.data.Satellites, one) } h.mutex.Unlock() print(h) } // Set location (latitude, longitude, elevation) // NOTE: if location lat, lon, or elev are pure zero, the cache is not updated // NOTE: if location provided matches the cached location, the LastUpdate // value is not changed. // NOTE: Location randomization is done only when set, to prevent clients from // receiving many randomizations of a single actual location (enabling // them to estimate the actual location ever more accurately as more // randomizations are received. // NOTE: See also the note above function obfuscate_lat_lon(), below. func (h *GpsCache) SetLocation(lat float64, lon float64, elev float64) (update_time int64) { h.mutex.Lock() logutil.LogDebug("SetLocation(lat=%f, lon=%f, elev=%f)\n", lat, lon, elev) // Is the passed location nonzero? (zeros mean the GPS has no fix) if 0.0 != lat && 0.0 != lon && elev != 0.0 { // Is the passed location different from the cache? if lat != h.data.Location.Latitude || lon != h.data.Location.Longitude || elev != h.data.Location.ElevationM { // Location has changed. Update the cache, and timestamp h.data.Location.Latitude, h.data.Location.Longitude = obfuscate_lat_lon(lat, lon, h.data.Location.AccuracyKM) if elev < 0.0 { elev = get_elevation_in_meters(lat, lon) } h.data.Location.ElevationM = elev // This is appropriate when loc_source==GPS, but when loc_source==Manual or Estimated we will update the timestamp when location is retrieved as json h.data.Location.LastUpdate = time.Now().UTC().Unix() } } h.mutex.Unlock() print(h) return h.data.Location.LastUpdate } // Return whether or not GPS hardware is available func (h *GpsCache) HasGPS() (has_gps bool) { h.mutex.RLock() has_gps = GPS == h.data.Location.LocSource || SEARCHING == h.data.Location.LocSource h.mutex.RUnlock() return } // Return the current configuration details func (h *GpsCache) GetConfiguration() (config string) { h.mutex.RLock() loc_source := h.data.Location.LocSource source := fmt.Sprintf("Source: %q", loc_source) accuracy_km := h.data.Location.AccuracyKM accuracy := fmt.Sprintf("obfuscation up to %f km", accuracy_km) if 0.0 == accuracy_km { accuracy = "no obfuscation" } config = fmt.Sprintf("%s -- %s", source, accuracy) h.mutex.RUnlock() return } // Return true if lat and lon have been set yet func (h *GpsCache) IsLocationSet() (isSet bool) { h.mutex.RLock() isSet = (h.data.Location.Latitude != 0 && h.data.Location.Longitude != 0) h.mutex.RUnlock() return } // Return cached, and possibly already obfuscated, location (lat, lon, elev) func (h *GpsCache) GetLocation() (lat float64, lon float64, elev float64, accuracy_km float64) { h.mutex.RLock() lat = h.data.Location.Latitude lon = h.data.Location.Longitude elev = h.data.Location.ElevationM accuracy_km = h.data.Location.AccuracyKM h.mutex.RUnlock() return } // Return cached location data as JSON-formatted bytes func (h *GpsCache) GetLocationAsJSON() (json_bytes []byte) { h.mutex.RLock() if h.data.Location.LocSource == MANUAL || h.data.Location.LocSource == ESTIMATED { // copy the location struct and update the timestamp, otherwise this location could look really old loc := h.data.Location loc.LastUpdate = time.Now().UTC().Unix() json_bytes, _ = json.Marshal(loc) } else { json_bytes, _ = json.Marshal(h.data.Location) } h.mutex.RUnlock() return } // Return cached satellite data as JSON-formatted bytes func (h *GpsCache) GetSatellitesAsJSON() (json_bytes []byte) { h.mutex.RLock() var sat_only SatellitesData sat_only.Satellites = h.data.Satellites json_bytes, _ = json.Marshal(sat_only) h.mutex.RUnlock() return } // Return the entire Horizon GPS data as a JSON-formatted bytes func (h *GpsCache) GetAsJSON() (json_bytes []byte) { h.mutex.RLock() json_bytes, _ = json.Marshal(h.data) h.mutex.RUnlock() return } // Estimate node location using its public IP address for geo-location func (h *GpsCache) EstimateLocation() (lat float64, lon float64, err error) { err, ip_address := get_public_address() for nil != err { logutil.Logf("%v\n", err) logutil.Logf("INFO: Pausing for %d seconds before retrying public address...\n", GET_PUBLIC_IP_RETRY_SEC) time.Sleep(time.Duration(GET_PUBLIC_IP_RETRY_SEC) * time.Second) err, ip_address = get_public_address() } logutil.Logf("INFO: Discovered IP address: %v\n", ip_address) lat, lon, err = get_location_from_ip_address(ip_address) for nil != err { logutil.Logf("%v\n", err) logutil.Logf("INFO: Pausing for %d seconds before retrying location estimate...\n", LOC_ESTIMATE_RETRY_SEC) time.Sleep(time.Duration(LOC_ESTIMATE_RETRY_SEC) * time.Second) lat, lon, err = get_location_from_ip_address(ip_address) } logutil.Logf("INFO: Estimated location: lat=%f, lon=%f\n", lat, lon) return } // Internal routine to dump the passed instance as json // Please note that this routine expects that a lock is already held on the // passed GpsCache object! func print(h *GpsCache) { if DEBUG < 2 { return } j, _ := json.Marshal(h.data) var formatted bytes.Buffer _ = json.Indent(&formatted, j, "DEBUG: ", " ") logutil.LogDebug("%s\n", string(formatted.Bytes())) } // Utility routine to obfuscate a location (latitude and longitude only) // to some other location on the surface of the earth placed at some random // bearing, and at some random distance along that bearing within the // specified accuracy_km distance (in kilometers) from the actual location. // Note that this obfuscation should only be done once for any location // otherwise an adversary could receuve many obfuscated locations derived from // a single original location and use a Monte Carlo technique to derive the // original location: https://en.wikipedia.org/wiki/Monte_Carlo_integration func obfuscate_lat_lon(lat float64, lon float64, accuracy_km float64) (obfuscated_lat float64, obfuscated_lon float64) { actual_location := geo.NewPoint(lat, lon) obfuscated_location := actual_location // Obfuscate within the specified accuracy (if nonzero) if 0.0 != accuracy_km { // Inefficiently create a new random number generator each time r := rand.New(rand.NewSource(time.Now().UnixNano())) random_distance_kilometers := accuracy_km * r.Float64() random_bearing_degrees := 360.0 * r.Float64() obfuscated_location = actual_location.PointAtDistanceAndBearing(random_distance_kilometers, random_bearing_degrees) if DEBUG > 2 { logutil.LogDebug("Obfuscating: From: (lat=%f,lon=%f), To: (lat=%f,lon=%f)\n", lat, lon, obfuscated_location.Lat(), obfuscated_location.Lng()) } } return obfuscated_location.Lat(), obfuscated_location.Lng() } // Get the elevation in meters of a (lat, lon) surface location, using the // free USGS Elevation Query Web Service (at http://ned.usgs.gov) which when // invoked with a uri like this (x=lon, y=lat): // http://ned.usgs.gov/epqs/pqs.php?x=-121&y=37&units=Meters&output=json // returns data in this form: // {"USGS_Elevation_Point_Query_Service":{"Elevation_Query":{"x":-121,"y":37,"Data_Source":"3DEP 1\/3 arc-second","Elevation":183.69,"Units":"Meters"}}} func get_elevation_in_meters(lat float64, lon float64) (elevation_m float64) { // USGS returns -1000000 on error, so I'm co-opting that for all errors elevation_m = -1000000 resp, get_err := http.Get(fmt.Sprintf("http://ned.usgs.gov/epqs/pqs.php?x=%f&y=%f&units=Meters&output=json", lon, lat)) if get_err != nil { logutil.Logf("get_elevation_in_meters: error getting elevation from ned.usgs.gov: %v\n", get_err) return } defer resp.Body.Close() body, read_err := ioutil.ReadAll(resp.Body) if read_err != nil { logutil.Logf("get_elevation_in_meters: error reading response body from ned.usgs.gov: %v\n", read_err) return } // The output from ned.usgs.gov is like: {"USGS_Elevation_Point_Query_Service":{"Elevation_Query":{"x":-73.959494,"y":42.214607,"Data_Source":"3DEP 1\/3 arc-second","Elevation":139.13,"Units":"Meters"}}} var parsed map[string]map[string]map[string]interface{} unm_err := json.Unmarshal(body, &parsed) if unm_err != nil { logutil.Logf("get_elevation_in_meters: error parsing response from ned.usgs.gov: %v\n", unm_err) return } data := parsed["USGS_Elevation_Point_Query_Service"]["Elevation_Query"]["Elevation"] e, ok := data.(float64) if !ok { logutil.Logf("get_elevation_in_meters: error converting elevation to float64, elevation=%v\n", data) return } elevation_m = e if DEBUG > 2 { logutil.LogDebug("Discovered altitude for (lat=%f,lon=%f): %f meters\n", lat, lon, elevation_m) } return } // Get the public Internet IP address of this node (outside any firewalled // and NATted LAN). Typically the node wil not be reachable at this IP // address due to the firewall, but it is convenient to use the public IP // address to estimate location when no other source of location data is // available. This function is hard-coded to use "http://ifconfig.co". // It will need to be rewritten if we change to using a different provider. func get_public_address() (err error, ip_address string) { err = nil // NOTE: Using 'https' sometimes fails with a 509 due to // certificate errors. So using 'http' is more reliable. provider_url := "http://ifconfig.co" resp, rest_err := http.Get(provider_url) if rest_err != nil { ip_address = "" err = errors.New(fmt.Sprintf("ERROR: REST call to %s failed: %v", provider_url, rest_err)) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) // Parse out the IP address from the body ip_address = string(body[:len(body)-1]) return } type IPGPSCoordinates struct { Latitude float64 `json:"latitude"` Longitude float64 `json:"longitude"` // there are many more fields, but we don't care about them } // Estimate the location of the node by using its IP address. This function // uses the FreeGeoIP service, which enables up to 10,000 queries per hour // (after which it returns HTTP 403 responses). See "http://freegeoip.net/". func get_location_from_ip_address(ip_address string) (lat float64, lon float64, err error) { apikey := "166f0d44636d9ed71c6a01530f687fdb" url := "http://api.ipstack.com/" + ip_address + "?access_key=" + apikey + "&format=1" resp, rest_err := http.Get(url) if rest_err != nil { err = errors.New(fmt.Sprintf("ERROR: Request to %s failed: %v", url, rest_err)) return } defer resp.Body.Close() httpCode := resp.StatusCode if httpCode != 200 { err = errors.New(fmt.Sprintf("ERROR: Bad http code %d from %s\n", httpCode, url)) return } body, err := ioutil.ReadAll(resp.Body) if DEBUG > 2 { logutil.LogDebug("Response from %s:\n%s\n", url, string(body)) } coordinates := IPGPSCoordinates{} err = json.Unmarshal(body, &coordinates) if err != nil { err = errors.New(fmt.Sprintf("ERROR: failed to unmarshal body response from %s: %v", url, err)) return } lat = coordinates.Latitude lon = coordinates.Longitude return }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2021/6/26 4:07 下午 # @File : lt_offer_链表反转.go # @Description : # @Attention : */ package v2 // 链表反转 func reversePrint(head *ListNode) []int { if nil == head { return nil } stack := make([]int, 0) for nil != head { stack = append(stack, head.Val) head = head.Next } r := make([]int, 0) for len(stack) > 0 { r = append(r, stack[len(stack)-1]) stack = stack[:len(stack)-1] } return r }
package instance_test import ( . "github.com/onsi/ginkgo" "github.com/pivotal-cf/spring-cloud-services-cli-plugin/instance" ) var _ = Describe("Restage", operationTest("restage", instance.NewRestageOperation))
package cbs import ( "bytes" "code.google.com/p/lzma" ) func lzmaCompress(size int64, data []byte) ([]byte, error) { var buf bytes.Buffer wr := lzma.NewWriterSizeLevel(&buf, size, 9) if _, err := wr.Write(data); err != nil { return nil, err } if err := wr.Close(); err != nil { return nil, err } return buf.Bytes(), nil }
package makeusers import ( "Neo/codes/jsonstruct" "Neo/codes/platform" "strings" "time" "os" "github.com/tebeka/selenium" ) var err error //Sevenmaster make sd user func Sevenmaster(d selenium.WebDriver) error { err = platform.Buttonclick(d, ".btn.btn-default.m-nav__link") if err != nil { return err } time.Sleep(time.Millisecond * 2000) err = platform.Insertval(d, "#user_firstName", os.Getenv("SEVENMASTER_FNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_lastName", os.Getenv("SEVENMASTER_LNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_username", os.Getenv("SEVENMASTER_NICKNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_email", os.Getenv("SEVENMASTER_EMAIL")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_password", os.Getenv("SEVENMASTER_FINPUT")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_confirm", os.Getenv("SEVENMASTER_LINPUT")) if err != nil { return err } err = platform.Buttonclick(d, "button[class*='btn-save']") if err != nil { return err } time.Sleep(time.Millisecond * 2000) url, err := d.CurrentURL() if err != nil { return err } if strings.Contains(url, "users/new") { url = strings.Replace(url, "users/new", "users", 1) err = d.Get(url) if err != nil { return err } } time.Sleep(time.Millisecond * 2000) return nil } //SevenCohen make user Daniel cohen func SevenCohen(d selenium.WebDriver) error { err = platform.Buttonclick(d, ".btn.btn-default.m-nav__link") if err != nil { return err } time.Sleep(time.Millisecond * 2000) err = platform.Insertval(d, "#user_firstName", os.Getenv("SEVENCOHEN_FNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_lastName", os.Getenv("SEVENCOHEN_LNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_username", os.Getenv("SEVENCOHEN_NICKNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_email", os.Getenv("SEVENCOHEN_EMAIL")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_password", os.Getenv("SEVENCOHEN_FINPUT")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_confirm", os.Getenv("SEVENCOHEN_LINPUT")) if err != nil { return err } err = platform.Buttonclick(d, "button[class*='btn-save']") if err != nil { return err } time.Sleep(time.Millisecond * 2000) url, err := d.CurrentURL() if err != nil { return err } if strings.Contains(url, "users/new") { url = strings.Replace(url, "users/new", "users", 1) err = d.Get(url) if err != nil { return err } } time.Sleep(time.Millisecond * 2000) return nil } //SevenCs make cs user func SevenCs(d selenium.WebDriver) error { err = platform.Buttonclick(d, ".btn.btn-default.m-nav__link") if err != nil { return err } time.Sleep(time.Millisecond * 2000) err = platform.Insertval(d, "#user_firstName", os.Getenv("SEVENCS_FNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_lastName", os.Getenv("SEVENCS_LNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_username", os.Getenv("SEVENCS_NICKNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_email", os.Getenv("SEVENCS_EMAIL")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_password", os.Getenv("SEVENCS_FINPUT")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_confirm", os.Getenv("SEVENCS_LINPUT")) if err != nil { return err } err = platform.Buttonclick(d, "button[class*='btn-save']") if err != nil { return err } time.Sleep(time.Millisecond * 2000) url, err := d.CurrentURL() if err != nil { return err } if strings.Contains(url, "users/new") { url = strings.Replace(url, "users/new", "users", 1) err = d.Get(url) if err != nil { return err } } time.Sleep(time.Millisecond * 2000) return nil } //SevenEng make eng user func SevenEng(d selenium.WebDriver) error { err = platform.Buttonclick(d, ".btn.btn-default.m-nav__link") if err != nil { return err } time.Sleep(time.Millisecond * 2000) err = platform.Insertval(d, "#user_firstName", os.Getenv("SEVENENG_FNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_lastName", os.Getenv("SEVENENG_LNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_username", os.Getenv("SEVENENG_NICKNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_email", os.Getenv("SEVENENG_EMAIL")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_password", os.Getenv("SEVENENG_FINPUT")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_confirm", os.Getenv("SEVENENG_LINPUT")) if err != nil { return err } err = platform.Buttonclick(d, "button[class*='btn-save']") if err != nil { return err } time.Sleep(time.Millisecond * 2000) url, err := d.CurrentURL() if err != nil { return err } if strings.Contains(url, "users/new") { url = strings.Replace(url, "users/new", "users", 1) err = d.Get(url) if err != nil { return err } } time.Sleep(time.Millisecond * 2000) return nil } //SevenSup make sup user func SevenSup(d selenium.WebDriver) error { err = platform.Buttonclick(d, ".btn.btn-default.m-nav__link") if err != nil { return err } time.Sleep(time.Millisecond * 2000) err = platform.Insertval(d, "#user_firstName", os.Getenv("SEVENSUP_FNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_lastName", os.Getenv("SEVENSUP_LNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_username", os.Getenv("SEVENSUP_NICKNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_email", os.Getenv("SEVENSUP_EMAIL")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_password", os.Getenv("SEVENSUP_FINPUT")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_confirm", os.Getenv("SEVENSUP_LINPUT")) if err != nil { return err } err = platform.Buttonclick(d, "button[class*='btn-save']") if err != nil { return err } time.Sleep(time.Millisecond * 2000) url, err := d.CurrentURL() if err != nil { return err } if strings.Contains(url, "users/new") { url = strings.Replace(url, "users/new", "users", 1) err = d.Get(url) if err != nil { return err } } time.Sleep(time.Millisecond * 2000) return nil } //SevenInfra make infra user func SevenInfra(d selenium.WebDriver) error { err = platform.Buttonclick(d, ".btn.btn-default.m-nav__link") if err != nil { return err } time.Sleep(time.Millisecond * 2000) err = platform.Insertval(d, "#user_firstName", os.Getenv("SEVENINFRA_FNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_lastName", os.Getenv("SEVENINFRA_LNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_username", os.Getenv("SEVENINFRA_NICKNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_email", os.Getenv("SEVENINFRA_EMAIL")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_password", os.Getenv("SEVENINFRA_FINPUT")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_confirm", os.Getenv("SEVENINFRA_LINPUT")) if err != nil { return err } err = platform.Buttonclick(d, "button[class*='btn-save']") if err != nil { return err } time.Sleep(time.Millisecond * 2000) url, err := d.CurrentURL() if err != nil { return err } if strings.Contains(url, "users/new") { url = strings.Replace(url, "users/new", "users", 1) err = d.Get(url) if err != nil { return err } } time.Sleep(time.Millisecond * 2000) return nil } func sevenAMW(d selenium.WebDriver) error { err = platform.Buttonclick(d, ".btn.btn-default.m-nav__link") if err != nil { return err } time.Sleep(time.Millisecond * 2000) err = platform.Insertval(d, ".btn.btn-default.m-nav__link", os.Getenv("SEVENAMW_FNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_lastName", os.Getenv("SEVENAMW_LNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_username", os.Getenv("SEVENAMW_NICKNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_email", os.Getenv("SEVENAMW_EMAIL")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_password", os.Getenv("SEVENAMW_FINPUT")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_confirm", os.Getenv("SEVENAMW_LINPUT")) if err != nil { return err } err = platform.Buttonclick(d, "button[class*='btn-save']") if err != nil { return err } time.Sleep(time.Millisecond * 2000) url, err := d.CurrentURL() if err != nil { return err } if strings.Contains(url, "users/new") { url = strings.Replace(url, "users/new", "users", 1) err = d.Get(url) if err != nil { return err } } time.Sleep(time.Millisecond * 2000) return nil } //SevenSDneo make user sd func SevenSDneo(d selenium.WebDriver) error { err = platform.Buttonclick(d, ".btn.btn-default.m-nav__link") if err != nil { return err } time.Sleep(time.Millisecond * 2000) err = platform.Insertval(d, "#user_firstName", os.Getenv("SEVENSD_FNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_lastName", os.Getenv("SEVENSD_LNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_username", os.Getenv("SEVENSD_NICKNAME")) if err != nil { return err } err = platform.Insertval(d, "#user_email", os.Getenv("SEVENSD_EMAIL")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_password", os.Getenv("SEVENSD_FINPUT")) if err != nil { return err } err = platform.Insertval(d, "#user_plainPassword_confirm", os.Getenv("SEVENSD_LINPUT")) if err != nil { return err } err = platform.Buttonclick(d, "button[class*='btn-save']") if err != nil { return err } time.Sleep(time.Millisecond * 2000) url, err := d.CurrentURL() if err != nil { return err } if strings.Contains(url, "users/new") { url = strings.Replace(url, "users/new", "users", 1) err = d.Get(url) if err != nil { return err } } time.Sleep(time.Millisecond * 2000) return nil } //AutoMakeusers run all func AutoMakeusers(d selenium.WebDriver, p jsonstruct.Configs) error { url := "https://panel."+p.Platform + "/ai/" + os.Getenv("USER_PAGE") err = d.Get(url) if err != nil { return err } time.Sleep(time.Millisecond * 2000) err = SevenSDneo(d) if err != nil { return err } err = Sevenmaster(d) if err != nil { return err } err = SevenCs(d) if err != nil { return err } err = SevenSup(d) if err != nil { return err } err = SevenEng(d) if err != nil { return err } err = SevenCohen(d) if err != nil { return err } err = SevenInfra(d) if err != nil { return err } // err = sevenAMW(d) // if err != nil { // return err // } time.Sleep(time.Millisecond * 2000) return nil }
/* 转移所有图片到一个统一文件夹的工具 */ package main import ( "fmt" "io" "log" "os" "path" "sync" ) var ( // 控制程序结束栅栏 waitGroup = sync.WaitGroup{} // 文件转移线程池 fileChan = make(chan struct{}, 20) ) func main() { handTask("H:/wallpaper/P站壁纸/电脑壁纸,质量保证", "images/横屏") handTask("H:/wallpaper/P站壁纸/电脑壁纸,质量保证", "images/竖屏") handTask("H:/wallpaper/P站壁纸/电脑壁纸,质量保证", "images/长图-方图") handTask("H:/wallpaper/P站壁纸/精品小图,手机可用", "images/小图") // 等待转移结束 waitGroup.Wait() } //dstDir 目标地址 //srcDir 源地址 func handTask(dstDir, srcDir string) { file, _ := os.Open(srcDir) infos, _ := file.Readdir(0) for _, info := range infos { waitGroup.Add(1) go transferFile(path.Join(dstDir, info.Name()), path.Join(srcDir, info.Name())) } } // 转移图片逻辑 func transferFile(dst, src string) { fileChan <- struct{}{} dstFile, _ := os.OpenFile(dst, os.O_RDWR|os.O_CREATE, 0644) srcFile, _ := os.Open(src) _, err := io.Copy(dstFile, srcFile) if err != nil { log.Println(err) } srcFile.Close() dstFile.Close() // 删除原图片 os.Remove(src) waitGroup.Done() <-fileChan fmt.Println(src, " 转移完成!") }
package controller import ( "fmt" "make_invoice/model" "make_invoice/service" "net/http" "strconv" "github.com/gin-gonic/gin" ) func AddInvoice(c *gin.Context) { invoice := &model.Invoice{} binderr := c.Bind(invoice) if binderr != nil { c.String(http.StatusBadRequest, "Bad request") return } err := service.InsertInvoice(invoice) if err != nil { c.String(http.StatusInternalServerError, "Server Error") return } c.Redirect(http.StatusFound, fmt.Sprintf("/invoice/%d", invoice.ID)) } func DeleteInvoice(c *gin.Context) { paramid := c.Param("id") err := service.DeleteInvoice(paramid) if err != nil { if err.Error() == "record not found" { c.String(http.StatusNotFound, "Not Found") } else { c.String(http.StatusInternalServerError, "Server Error") } println(err) return } c.Redirect(http.StatusFound, "/invoice") } func UpadateInvoice(c *gin.Context) { paramid := c.Param("id") invoice := &model.Invoice{} binderr := c.Bind(invoice) if binderr != nil { fmt.Println(binderr.Error()) c.String(http.StatusBadRequest, "Bad request") return } if paramid != strconv.FormatUint(uint64(invoice.ID), 10) { c.String(http.StatusBadRequest, "Bad request") return } err := service.UpdateInvoice(invoice) if err != nil { if err.Error() == "record not found" { c.String(http.StatusNotFound, "Not Found") } else { c.String(http.StatusInternalServerError, "Server Error") } return } c.Redirect(http.StatusFound, fmt.Sprintf("/invoice/%d", invoice.ID)) } func AddItem(c *gin.Context) { item := &model.Item{} binderr := c.Bind(item) if binderr != nil { c.String(http.StatusBadRequest, "Bad request") return } err := service.InsertItem(item) if err != nil { c.String(http.StatusInternalServerError, "Server Error") return } c.JSON(http.StatusCreated, gin.H{ "status": "ok", "data": item, }) } func InvoiceListAll(c *gin.Context) { invoices, err := service.ListInvoice() if err != nil { c.String(http.StatusInternalServerError, "Server Error") return } c.JSONP(http.StatusOK, gin.H{ "message": "ok", "data": invoices, }) } func OneInvoiceById(c *gin.Context) { id := c.Param("id") invoice, err := service.SelectInvoiceById(id) if err != nil { if err.Error() == "record not found" { c.String(http.StatusNotFound, "Not Found") } else { c.String(http.StatusInternalServerError, "Server Error") } return } c.JSONP(http.StatusOK, gin.H{ "message": "ok", "data": invoice, }) }
package ui import ( "fmt" "github.com/askovpen/gocui" "log" ) func setCurrentViewOnTop(g *gocui.Gui, name string) (*gocui.View, error) { if _, err := g.SetCurrentView(name); err != nil { return nil, err } return g.SetViewOnTop(name) } // Layout default func Layout(g *gocui.Gui) error { maxX, maxY := g.Size() status, err := g.SetView("status", -1, maxY-2, maxX-11, maxY) if err != nil && err != gocui.ErrUnknownView { return err } statusTime, err := g.SetView("statusTime", maxX-12, maxY-2, maxX, maxY) if err != nil && err != gocui.ErrUnknownView { return err } status.Frame = false status.Wrap = false status.BgColor = gocui.ColorBlue status.FgColor = gocui.ColorWhite | gocui.AttrBold status.Clear() statusTime.Frame = false statusTime.Wrap = false statusTime.BgColor = gocui.ColorBlue statusTime.FgColor = gocui.ColorWhite | gocui.AttrBold statusTime.Clear() fmt.Fprintf(status, StatusLine) fmt.Fprintf(statusTime, StatusTime) err = CreateAreaList(g) if err != nil { log.Print(err) } setCurrentViewOnTop(g, ActiveWindow) return nil }
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -o ../../fakes/fake_strategy.go resolver.go Strategy //go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -o ../../fakes/fake_strategy_installer.go resolver.go StrategyInstaller //go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -o ../../fakes/fake_strategy_resolver.go resolver.go StrategyResolverInterface package install import ( "fmt" "time" "github.com/operator-framework/api/pkg/operators/v1alpha1" "github.com/operator-framework/operator-lifecycle-manager/pkg/api/wrappers" "github.com/operator-framework/operator-lifecycle-manager/pkg/lib/operatorclient" "github.com/operator-framework/operator-lifecycle-manager/pkg/lib/operatorlister" "github.com/operator-framework/operator-lifecycle-manager/pkg/lib/ownerutil" ) type Strategy interface { GetStrategyName() string } type StrategyInstaller interface { Install(strategy Strategy) error CheckInstalled(strategy Strategy) (bool, error) CertsRotateAt() time.Time CertsRotated() bool } type StrategyResolverInterface interface { UnmarshalStrategy(s v1alpha1.NamedInstallStrategy) (strategy Strategy, err error) InstallerForStrategy(strategyName string, opClient operatorclient.ClientInterface, opLister operatorlister.OperatorLister, owner ownerutil.Owner, annotations map[string]string, apiServiceDescriptions []v1alpha1.APIServiceDescription, webhookDescriptions []v1alpha1.WebhookDescription, previousStrategy Strategy) StrategyInstaller } type StrategyResolver struct { OverridesBuilderFunc DeploymentInitializerBuilderFunc } func (r *StrategyResolver) UnmarshalStrategy(s v1alpha1.NamedInstallStrategy) (strategy Strategy, err error) { switch s.StrategyName { case v1alpha1.InstallStrategyNameDeployment: return &s.StrategySpec, nil } err = fmt.Errorf("unrecognized install strategy") return } func (r *StrategyResolver) InstallerForStrategy(strategyName string, opClient operatorclient.ClientInterface, opLister operatorlister.OperatorLister, owner ownerutil.Owner, annotations map[string]string, apiServiceDescriptions []v1alpha1.APIServiceDescription, webhookDescriptions []v1alpha1.WebhookDescription, previousStrategy Strategy) StrategyInstaller { switch strategyName { case v1alpha1.InstallStrategyNameDeployment: strategyClient := wrappers.NewInstallStrategyDeploymentClient(opClient, opLister, owner.GetNamespace()) initializers := []DeploymentInitializerFunc{} if r.OverridesBuilderFunc != nil { initializers = append(initializers, r.OverridesBuilderFunc(owner)) } return NewStrategyDeploymentInstaller(strategyClient, annotations, owner, previousStrategy, initializers, apiServiceDescriptions, webhookDescriptions) } // Insurance against these functions being called incorrectly (unmarshal strategy will return a valid strategy name) return &NullStrategyInstaller{} } type NullStrategyInstaller struct{} var _ StrategyInstaller = &NullStrategyInstaller{} func (i *NullStrategyInstaller) Install(s Strategy) error { return fmt.Errorf("null InstallStrategy used") } func (i *NullStrategyInstaller) CheckInstalled(s Strategy) (bool, error) { return true, nil } func (i *NullStrategyInstaller) CertsRotateAt() time.Time { return time.Time{} } func (i *NullStrategyInstaller) CertsRotated() bool { return false }
package datastore import ( "context" "testing" ) func TestSaveStruct_Basic(t *testing.T) { ctx := context.Background() type Data struct { Str string } ps, err := SaveStruct(ctx, &Data{"Test"}) if err != nil { t.Fatal(err) } if v := len(ps); v != 1 { t.Fatalf("unexpected: %v", v) } p := ps[0] if v := p.Name; v != "Str" { t.Fatalf("unexpected: %v", v) } if v, ok := p.Value.(string); !ok { t.Fatalf("unexpected: %v", ok) } else if v != "Test" { t.Fatalf("unexpected: %v", v) } } func TestSaveStruct_Object(t *testing.T) { ctx := context.Background() type Data struct { Str string } ps, err := SaveStruct(ctx, &Data{Str: "Str"}) if err != nil { t.Fatal(err) } if v := len(ps); v != 1 { t.Fatalf("unexpected: %v", v) } p := ps[0] if v := p.Name; v != "Str" { t.Fatalf("unexpected: %v", v) } if v := p.Value.(string); v != "Str" { t.Fatalf("unexpected: %v", v) } } func TestSaveStruct_ObjectPropertyRename(t *testing.T) { ctx := context.Background() type Data struct { Str string `datastore:"modified"` } ps, err := SaveStruct(ctx, &Data{Str: "Str"}) if err != nil { t.Fatal(err) } if v := len(ps); v != 1 { t.Fatalf("unexpected: %v", v) } p := ps[0] if v := p.Name; v != "modified" { t.Fatalf("unexpected: %v", v) } if v := p.Value.(string); v != "Str" { t.Fatalf("unexpected: %v", v) } } func TestSaveStruct_EmbedStruct(t *testing.T) { ctx := context.Background() type Embed struct { Inner string } type Data struct { Embed Str string } ps, err := SaveStruct(ctx, &Data{ Embed: Embed{ Inner: "Inner", }, Str: "Str", }) if err != nil { t.Fatal(err) } if v := len(ps); v != 2 { t.Fatalf("unexpected: %v", v) } { p := ps[0] if v := p.Name; v != "Inner" { t.Fatalf("unexpected: %v", v) } if v := p.Value.(string); v != "Inner" { t.Fatalf("unexpected: %v", v) } } { p := ps[1] if v := p.Name; v != "Str" { t.Fatalf("unexpected: %v", v) } if v := p.Value.(string); v != "Str" { t.Fatalf("unexpected: %v", v) } } } func TestSaveStruct_WithEmbedPtrStruct(t *testing.T) { ctx := context.Background() type Inner struct { A string B string } type Data struct { *Inner } { ps, err := SaveStruct(ctx, &Data{Inner: &Inner{A: "A", B: "B"}}) if err != nil { t.Fatal(err) } if v := len(ps); v != 2 { t.Errorf("unexpected: %v", v) } obj := &Data{} err = LoadStruct(ctx, obj, ps) if err != nil { t.Fatal(err) } if v := obj.Inner; v == nil { t.Errorf("unexpected: %v", v) } } { ps, err := SaveStruct(ctx, &Data{}) if err != nil { t.Fatal(err) } if v := len(ps); v != 0 { t.Errorf("unexpected: %v", v) } obj := &Data{} err = LoadStruct(ctx, obj, ps) if err != nil { t.Fatal(err) } if v := obj.Inner; v != nil { t.Errorf("unexpected: %v", v) } } } func TestSaveStruct_WithPtrStruct(t *testing.T) { // TODO Why this test is failed? t.SkipNow() ctx := context.Background() type Inner struct { A string B string } type Data struct { Inner *Inner `datastore:",flatten"` } { ps, err := SaveStruct(ctx, &Data{Inner: &Inner{A: "A", B: "B"}}) if err != nil { t.Fatal(err) } if v := len(ps); v != 2 { t.Errorf("unexpected: %v", v) } obj := &Data{} err = LoadStruct(ctx, obj, ps) if err != nil { t.Fatal(err) } if v := obj.Inner; v == nil { t.Errorf("unexpected: %v", v) } } { ps, err := SaveStruct(ctx, &Data{}) if err != nil { t.Fatal(err) } if v := len(ps); v != 0 { t.Errorf("unexpected: %v", v) } obj := &Data{} err = LoadStruct(ctx, obj, ps) if err != nil { t.Fatal(err) } if v := obj.Inner; v != nil { t.Errorf("unexpected: %v", v) } } } func TestSaveStruct_ObjectHasObjectSlice(t *testing.T) { ctx := context.Background() type Inner struct { A string B string } type Data struct { Slice []Inner } ps, err := SaveStruct(ctx, &Data{ Slice: []Inner{ {A: "A1", B: "B1"}, {A: "A2", B: "B2"}, {A: "A3", B: "B3"}, }, }) if err != nil { t.Fatal(err) } if v := len(ps); v != 1 { t.Fatalf("unexpected: %v", v) } p := ps[0] if v := p.Name; v != "Slice" { t.Fatalf("unexpected: %v", v) } es := p.Value.([]interface{}) if v := len(es); v != 3 { t.Fatalf("unexpected: %v", v) } expects := []struct { Name string Value string }{ {"A", "A1"}, {"B", "B1"}, {"A", "A2"}, {"B", "B2"}, {"A", "A3"}, {"B", "B3"}, } for idx, entity := range es { e := entity.(*Entity) if v := len(e.Properties); v != 2 { t.Fatalf("unexpected: %v", v) } for pIdx, p := range e.Properties { expect := expects[idx*len(e.Properties)+pIdx] if v := p.Name; v != expect.Name { t.Errorf("unexpected: %v", v) } if v := p.Value.(string); v != expect.Value { t.Errorf("unexpected: %v", v) } } } } func TestLoadStruct_Basic(t *testing.T) { ctx := context.Background() type Data struct { Str string } var ps PropertyList ps = append(ps, Property{ Name: "Str", Value: "Test", }) obj := &Data{} err := LoadStruct(ctx, obj, ps) if err != nil { t.Fatal(err) } if v := obj.Str; v != "Test" { t.Fatalf("unexpected: %v", v) } } func TestLoadStruct_IgnoreMismatchProperty(t *testing.T) { ctx := context.Background() type Data1 struct { A string B string } type Data2 struct { A string } ps, err := SaveStruct(ctx, &Data1{}) if err != nil { t.Fatal(err) } err = LoadStruct(ctx, &Data2{}, ps) if err != nil { t.Fatal(err) } } func TestLoadStruct_CheckMismatchProperty(t *testing.T) { ctx := context.Background() SuppressErrFieldMismatch = false defer func() { SuppressErrFieldMismatch = true }() type Data1 struct { A string B string } type Data2 struct { A string } ps, err := SaveStruct(ctx, &Data1{}) if err != nil { t.Fatal(err) } err = LoadStruct(ctx, &Data2{}, ps) if err == nil { t.Fatal(err) } else if _, ok := err.(*ErrFieldMismatch); ok { // ok! } else { t.Fatal(err) } }
package server import ( "strconv" "github.com/Tanibox/tania-core/src/assets/domain" "github.com/Tanibox/tania-core/src/assets/storage" "github.com/gofrs/uuid" ) func (rv *RequestValidation) ValidateReservoir(s FarmServer, reservoirUID uuid.UUID) (storage.ReservoirRead, error) { result := <-s.ReservoirReadQuery.FindByID(reservoirUID) reservoir, _ := result.Result.(storage.ReservoirRead) if reservoir.UID == (uuid.UUID{}) { return reservoir, NewRequestValidationError(NOT_FOUND, "reservoir_id") } return reservoir, nil } func (rv *RequestValidation) ValidateFarm(s FarmServer, farmUID uuid.UUID) (storage.FarmRead, error) { result := <-s.FarmReadQuery.FindByID(farmUID) farm, _ := result.Result.(storage.FarmRead) if farm.UID == (uuid.UUID{}) { return farm, NewRequestValidationError(NOT_FOUND, "farm_id") } return farm, nil } func (rv *RequestValidation) ValidateAreaSize(size string, sizeUnit string) (domain.AreaSize, error) { if size == "" { return domain.AreaSize{}, NewRequestValidationError(REQUIRED, "size") } if sizeUnit == "" { return domain.AreaSize{}, NewRequestValidationError(REQUIRED, "size_unit") } sizeFloat, err := strconv.ParseFloat(size, 32) if err != nil { return domain.AreaSize{}, err } unit := domain.GetAreaUnit(sizeUnit) if unit == (domain.AreaUnit{}) { return domain.AreaSize{}, NewRequestValidationError(INVALID_OPTION, "size_unit") } return domain.AreaSize{ Value: float32(sizeFloat), Unit: unit, }, nil } func (rv *RequestValidation) ValidateAreaLocation(location string) (string, error) { if location == "" { return "", NewRequestValidationError(REQUIRED, "location") } areaLocation := domain.GetAreaLocation(location) if areaLocation == (domain.AreaLocation{}) { return "", NewRequestValidationError(INVALID_OPTION, "location") } return areaLocation.Code, nil }
package NoQ_RoomQ_Exception type InvalidApiKeyException struct{} func (ex *InvalidApiKeyException) Error() string { return "Invalid api key" }
// Copyright © 2018 NAME HERE <EMAIL ADDRESS> // // 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 cmd import ( "bytes" "encoding/json" "fmt" "io/ioutil" "os" // "path" "strings" "github.com/spf13/cobra" "gopkg.in/rana/ora.v4" ) var configFileName string // uploadManyCmd represents the uploadMany command var uploadManyCmd = &cobra.Command{ Use: "upload_many", Short: "Upload files to Oracle DB", Long: `Upload files to Oracle DB via configuration file`, Run: func(cmd *cobra.Command, args []string) { // TODO: Work your own magic here if (dsn == "") || (configFileName == "") { fmt.Println("Error:", "The UploadMany command demands presence of parameters") os.Exit(-1) } if err := uploadMany(); err != nil { fmt.Println("Error:", err) os.Exit(-1) } fmt.Println("Upload completed") }, } func init() { RootCmd.AddCommand(uploadManyCmd) uploadManyCmd.PersistentFlags().StringVar(&dsn, "dsn", "", "Username/Password@ConnStr") uploadManyCmd.PersistentFlags().StringVar(&configFileName, "config", "", "Name of config file") } func uploadMany() error { type info struct { FileName string Name string Desc string Schema string Dl_id *int64 } fmt.Println("Open configuration file ", configFileName) buf, err := ioutil.ReadFile(configFileName) if err != nil { return err } bom := []byte{0xef, 0xbb, 0xbf} // UTF-8 if bytes.Equal(buf[:3], bom) { buf = buf[len(bom):] } fmt.Println("Parse configuration file - config length ", len(buf)) infos := make([]info, 0) if err = json.Unmarshal(buf, &infos); err != nil { return err } //fmt.Println("infos = ", infos) if len(infos) == 0 { fmt.Println("Empty configuration") return nil } env, srv, ses, err := ora.NewEnvSrvSes(dsn) defer func() { if ses != nil { ses.Close() } if srv != nil { srv.Close() } if env != nil { env.Close() } }() if err != nil { return err } for _, v := range infos { // filename, filedesc := func() (string, string) { // _, name := path.Split(strings.Replace(v.Name, "\\", "/", -1)) // ext := path.Ext(name) // name = name[:len(name)-len(ext)] // parts := strings.Split(name, "~") // if len(parts) < 2 { // filedesc = parts[0] // } else { // filedesc = parts[1] // } // name = parts[0] + ext // return name, filedesc // }() //fmt.Println("filepath =", v.Name, " filename =", filename, " filedesc =", filedesc) dl_id_Var := ora.Int64{true, 0} if v.Dl_id != nil { dl_id_Var.Value = *v.Dl_id dl_id_Var.IsNull = false } schemaVar := ora.String{true, ""} if v.Schema != "" { schemaVar.IsNull = false schemaVar.Value = v.Schema } //fmt.Println("Read file ", v.Name) b, err := ioutil.ReadFile(strings.ToLower(v.FileName)) if err != nil { return err } body := ora.Lob{Reader: bytes.NewReader(b)} if _, err = ses.PrepAndExe(stm, body, schemaVar, v.Name, v.Desc, dl_id_Var); err != nil { return err } fmt.Printf("File \"%s\" for scheme \"%s\" and DL_ID=%v successfully uploaded\n", v.FileName, v.Schema, v.Dl_id) } return nil }
package sequence import ( "context" "fmt" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" ) type Sequence_Student struct { Key string `json:"student_id_seq"` Number int `json:"number"` } func GetNextID(col *mongo.Collection, seq string) int { var sequence Sequence_Student filter := bson.M{"key": seq} update := bson.M{"$inc": bson.M{"number": 1}} err := col.FindOneAndUpdate(context.TODO(), filter, update).Decode(&sequence) if err != nil { col.InsertOne(context.TODO(), Sequence_Student{seq, 0}) fmt.Println(err) } return sequence.Number + 1 }
// Licensed to SolID under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. SolID 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 jwt import "errors" //go:generate mockgen -destination mock/signer.gen.go -package mock zntr.io/solid/pkg/sdk/jwt Signer // Signer describe JWT signer contract. type Signer interface { Sign(claims interface{}) (string, error) } //go:generate mockgen -destination mock/verifier.gen.go -package mock zntr.io/solid/pkg/sdk/jwt Verifier // Verifier describes JWT verifier contract. type Verifier interface { Parse(token string) (Token, error) Verify(token string) error Claims(token string, claims interface{}) error } //go:generate mockgen -destination mock/token.gen.go -package mock zntr.io/solid/pkg/sdk/jwt Token // Token represents a jwt token contract. type Token interface { Type() (string, error) KeyID() (string, error) PublicKey() (interface{}, error) PublicKeyThumbPrint() (string, error) Algorithm() (string, error) Claims(publicKey interface{}, claims interface{}) error } // ErrInvalidTokenSignature is raised when token is signed with a private key // where the public key is not known by the keyset. var ErrInvalidTokenSignature = errors.New("invalid token signature")
package run import ( "sync" floc "gopkg.in/workanator/go-floc.v1" ) /* RaceLimit runs jobs in their own goroutines and waits until first N jobs finish. During the race only first N calls to update are allowed while further calls are discarded. Before starting the race the function synchronizes start of the each job putting them in equal conditions. If limit is less than 1 or greater than the number of jobs the function will panic. Summary: - Run jobs in goroutines : YES - Wait all jobs finish : YES - Run order : PARALLEL with synchronization of start Diagram: +-->[JOB_1]--+ | | --+--> .. --+--> | | +-->[JOB_N]--+ */ func RaceLimit(limit int, jobs ...floc.Job) floc.Job { // Validate the winner limit if limit < 1 || limit > len(jobs) { panic("invalid amount of possible race winners") } return func(flow floc.Flow, state floc.State, update floc.Update) { // Do not start the race if the execution is finished if flow.IsFinished() { return } // Create the channel which will have the value when the race is won done := make(chan struct{}, len(jobs)) defer close(done) // Wrap the flow into disablable flow so the calls to Cancel and Complete // can be disabled when the race is won disFlow, disable := floc.NewFlowWithDisable(flow) // Wrap the trigger to a function which allows to hit the update only // `limit` time(s) mutex := sync.Mutex{} winnerJobs := 0 limitedUpdate := func(flow floc.Flow, state floc.State, key string, value interface{}) { mutex.Lock() defer mutex.Unlock() if winnerJobs < limit { winnerJobs++ update(flow, state, key, value) if winnerJobs == limit { disable() } } } // Condition is used to synchronize start of jobs canStart := false startMutex := &sync.RWMutex{} startCond := sync.NewCond(startMutex.RLocker()) // Run jobs in parallel and wait until all of them ready to start runningJobs := 0 for _, job := range jobs { runningJobs++ go func(job floc.Job) { defer func() { done <- struct{}{} }() // Wait for the start of the race startCond.L.Lock() for !canStart && !flow.IsFinished() { startCond.Wait() } startCond.L.Unlock() // Perform the job if the flow is not finished if !flow.IsFinished() { job(disFlow, state, limitedUpdate) } }(job) } // Notify all jobs they can start the race startMutex.Lock() canStart = true startCond.Broadcast() startMutex.Unlock() // Wait until `limit` job(s) done finishedJobs := 0 for finishedJobs < runningJobs { select { case <-disFlow.Done(): // The execution has been finished or canceled so the trigger // should not be triggered anymore, therefore we disable it. But we // do not return and wait until all jobs finish the race. disable() case <-done: // One of the jobs finished. finishedJobs++ if finishedJobs == limit { disable() } } } } }
package spec import ( "testing" "github.com/stretchr/testify/assert" ) var ( defaultSpec = &Spec{ Config{ HTTPPort: 8080, HTTPSPort: 8443, }, []HTTPMock{ HTTPMock{ HTTPExpect: HTTPExpect{ Methods: []string{"GET"}, Path: "/", Prefix: false, Queries: nil, Headers: nil, }, HTTPResponse: &HTTPResponse{ Delay: "", StatusCode: 200, Headers: nil, Body: nil, }, }, }, []RESTMock{}, } specSimple = &Spec{ Config: Config{ HTTPPort: 8080, HTTPSPort: 8443, }, HTTPMocks: []HTTPMock{ HTTPMock{ HTTPExpect: HTTPExpect{ Methods: []string{"GET"}, Path: "/health", Prefix: false, Queries: nil, Headers: nil, }, HTTPResponse: &HTTPResponse{ Delay: "", StatusCode: 200, Headers: nil, Body: nil, }, }, HTTPMock{ HTTPExpect: HTTPExpect{ Methods: []string{"POST", "PUT"}, Path: "/api/v1/sendMessage", Prefix: false, Queries: nil, Headers: nil, }, HTTPResponse: &HTTPResponse{ Delay: "", StatusCode: 201, Headers: nil, Body: map[string]interface{}{ "id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", }, }, }, }, RESTMocks: []RESTMock{ RESTMock{ RESTExpect{ BasePath: "/api/v1/teams", Headers: nil, }, RESTResponse{ Delay: "", GetStatusCode: 200, PostStatusCode: 201, PutStatusCode: 200, PatchStatusCode: 200, DeleteStatusCode: 204, Headers: map[string]string{ "Content-Type": "application/json", }, ListKey: "", }, RESTStore{ Objects: []JSON{ {"_id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "name": "Back-end"}, {"_id": "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "name": "Front-end"}, }, Directory: map[interface{}]JSON{ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa": {"_id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "name": "Back-end"}, "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb": {"_id": "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "name": "Front-end"}, }, }, }, }, } specFull = &Spec{ Config: Config{ HTTPPort: 9080, HTTPSPort: 9443, }, HTTPMocks: []HTTPMock{ HTTPMock{ HTTPExpect: HTTPExpect{ Methods: []string{"GET"}, Path: "/health", Prefix: false, Queries: nil, Headers: nil, }, HTTPResponse: &HTTPResponse{ Delay: "", StatusCode: 200, Headers: nil, Body: nil, }, }, HTTPMock{ HTTPExpect: HTTPExpect{ Methods: []string{"GET"}, Path: "/app", Prefix: false, Queries: nil, Headers: nil, }, HTTPForward: &HTTPForward{ Delay: "", To: "http://example.com", Headers: map[string]string{ "Is-Test": "true", }, }, }, HTTPMock{ HTTPExpect: HTTPExpect{ Methods: []string{"POST", "PUT"}, Path: "/api/v1/sendMessage", Prefix: false, Queries: map[string]string{ "tenantId": "[0-9A-Fa-f-]+", "groupId": "[0-9A-Fa-f-]+", }, Headers: map[string]string{ "Accept": "application/json", "Content-Type": "application/json", "Authorization": "Bearer .*", }, }, HTTPResponse: &HTTPResponse{ Delay: "10ms", StatusCode: 201, Headers: map[string]string{ "Content-Type": "application/json", }, Body: map[string]interface{}{ "id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", }, }, }, }, RESTMocks: []RESTMock{ RESTMock{ RESTExpect{ BasePath: "/api/v1/teams", Headers: map[string]string{ "Accept": "application/json", "Content-Type": "application/json", "Authorization": "Bearer .*", }, }, RESTResponse{ Delay: "10ms", GetStatusCode: 200, PostStatusCode: 201, PutStatusCode: 200, PatchStatusCode: 200, DeleteStatusCode: 204, Headers: map[string]string{ "Content-Type": "application/json", }, ListKey: "data", }, RESTStore{ Identifier: "_id", Objects: []JSON{ {"_id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "name": "Back-end"}, {"_id": "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "name": "Front-end"}, }, Directory: map[interface{}]JSON{ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa": {"_id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "name": "Back-end"}, "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb": {"_id": "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "name": "Front-end"}, }, }, }, }, } ) func TestDefaultSpec(t *testing.T) { tests := []struct { name string expectedSpec *Spec }{ { "OK", defaultSpec, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { spec := DefaultSpec() assert.Equal(t, tc.expectedSpec, spec) }) } } func TestReadSpec(t *testing.T) { tests := []struct { name string path string expectedError string expectedSpec *Spec }{ { name: "NoFile", path: "./test/spec", expectedError: "", expectedSpec: defaultSpec, }, { name: "UnknownFormat", path: "./test/unknown", expectedError: "unknown spec file", expectedSpec: nil, }, { name: "EmptyJSON", path: "./test/empty.json", expectedError: "unknown spec file", expectedSpec: nil, }, { name: "EmptyYAML", path: "./test/empty.yaml", expectedError: "unknown spec file", expectedSpec: nil, }, { name: "InvalidJSON", path: "./test/invalid.json", expectedError: "unknown spec file", expectedSpec: nil, }, { name: "InvalidYAML", path: "./test/invalid.yaml", expectedError: "unknown spec file", expectedSpec: nil, }, { name: "SimpleJSON", path: "./test/simple.json", expectedError: "", expectedSpec: specSimple, }, { name: "SimpleYAML", path: "./test/simple.yaml", expectedError: "", expectedSpec: specSimple, }, { name: "FullJSON", path: "./test/full.json", expectedError: "", expectedSpec: specFull, }, { name: "FullYAML", path: "./test/full.yaml", expectedError: "", expectedSpec: specFull, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { spec, err := ReadSpec(tc.path) if tc.expectedError == "" { assert.NoError(t, err) assert.Equal(t, tc.expectedSpec, spec) } else { assert.Contains(t, err.Error(), tc.expectedError) assert.Nil(t, spec) } }) } }
package models import ( "fmt" "github.com/hxangel/dogo" db "github.com/hxangel/bot/libs/db" utils "github.com/hxangel/bot/libs/utils" "strings" ) type Model struct { TableName string PrimaryKey string Data map[string]string where string args []interface{} limit string orderby string groupby string } func NewModel(tableName, primaryKey string) *Model { return &Model{TableName: tableName, PrimaryKey: primaryKey} } //params func (model *Model) Wherep(id interface{}) *Model { model.where = fmt.Sprintf(" WHERE %s = %v ", model.PrimaryKey, id) return model } func (model *Model) Where(where string, args ...interface{}) *Model { model.where, model.args = fmt.Sprintf(" WHERE %s ", where), args return model } func (model *Model) Limit(start, offset int) *Model { model.limit = fmt.Sprintf(" LIMIT %d,%d ", start, offset) return model } func (model *Model) OrderBy(orderby ...string) *Model { model.orderby = " ORDER BY " + strings.Join(orderby, ",") + " " return model } func (model *Model) GroupBy(groupby string) { model.groupby = groupby } //select query func (model *Model) Gets() (results []map[string]interface{}, err error) { query := fmt.Sprintf("SELECT * FROM %s%s%s%s", model.GetTable(), model.where, model.orderby, model.limit) results, err = model.Db().FetchAll(query, model.args...) return results, err } func (model *Model) Get() (result map[string]interface{}, err error) { query := fmt.Sprintf("SELECT * FROM %s%s%s", model.GetTable(), model.where, model.orderby) result, err = model.Db().Fetch(query, model.args...) return result, err } //count func (model *Model) Count() (int64, error) { var total int64 query := fmt.Sprintf("SELECT COUNT(*) AS total FROM %s %s", model.GetTable(), model.where) row, err := model.Db().FetchRow(query, model.args...) if err != nil { return total, err } err = row.Scan(&total) if err != nil { return total, err } return total, nil } func (model *Model) CleanData() *Model { for key := range model.Data { delete(model.Data, key) } return model } //insert data func (model *Model) Insert(mData map[string]string) (int64, error) { data, args := model.CookMap(mData, " =?, ", ", ") query := fmt.Sprintf("INSERT INTO %s SET %s", model.GetTable(), data) result, err := model.Db().Execute(query, args...) if err != nil { return 0, err } return result, err } //update func (model *Model) Update(mData map[string]string) (int64, error) { data, dargs := model.CookMap(mData, " =?, ", ", ") args := utils.MapMerge(dargs, model.args) query := fmt.Sprintf("UPDATE %s SET %s%s", model.GetTable(), data, model.where) result, err := model.Db().Execute(query, args...) if err != nil { return 0, err } return result, err } //delete func (model *Model) Delete() (int64, error) { query := fmt.Sprintf("DELETE FROM %s %s", model.GetTable(), model.where) result, err := model.Db().Execute(query, model.args...) if err != nil { return 0, err } return result, nil } func (model *Model) CookMap(data map[string]string, sep string, cutset string) (string, []interface{}) { var fields []string var values []interface{} for field, value := range data { fields = append(fields, field) values = append(values, value) } return strings.Trim(strings.Join(fields, sep)+sep, cutset), values } func (model *Model) GetTable() string { return model.TableName } func (model *Model) Db() *db.Mysql { cfgpath := dogo.NewRegister().Get("cfg_path") file := fmt.Sprintf("%s/mysql.ini", cfgpath) return db.NewMysql(file) }
package levels import ( "fmt" "os" "os/exec" "os/signal" "regexp" "strings" "syscall" "time" ) func CmdOK(cmd string) (bool, string) { if cmd == "" { return true, "" } output, err := exec.Command("sh", "-c", cmd).Output() return err == nil, string(output) } var key_pressed = false func print_line(text string, keypress chan []byte, echo_state bool) { var counter = 0 var b []byte = make([]byte, 1) for _, char := range text { print(string(char)) if echo_state == false { counter++ go func() { os.Stdin.Read(b); keypress <- b }() select { case key := <-keypress: // only skip if enter or space was pressed if key[0] == 10 || key[0] == 32 { key_pressed = true fmt.Println(text[counter:len(text)]) return } default: fmt.Print("") } } time.Sleep(50 * time.Millisecond) if char == '.' || char == '!' || char == '?' { time.Sleep(500 * time.Millisecond) } } print("\n") } func PrintText(text string, pretty_print bool) { var echo_state bool = true sigs := make(chan os.Signal, 1) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigs if echo_state == false { exec.Command("stty", "-F", "/dev/tty", "echo").Run() } os.Exit(0) }() if pretty_print == false { // disable input buffering err := exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run() if err == nil { // do not display entered characters on the screen exec.Command("stty", "-F", "/dev/tty", "-echo").Run() echo_state = false // restore the echoing state when exiting defer exec.Command("stty", "-F", "/dev/tty", "echo").Run() } } keypress := make(chan []byte, 1) lines := strings.Split(text, "\n") var counter = 0 for _, line := range lines { counter += len(line) + 1 if counter > len(text) { counter = len(text) } print_line(line, keypress, echo_state) if key_pressed { fmt.Println(text[counter:len(text)]) break } } } func MarkdownToTerminal(text string) string { bold_regex, _ := regexp.Compile(`\*\*([^\*]+)\*\*`) italic_regex, _ := regexp.Compile(`\*([^\*]+)\*`) header_regex, _ := regexp.Compile(`^\s*\#+\s*(.+)`) bold := "\033[1m" inverse := "\033[7m" underline_bold := "\033[1;4m" reset := "\033[0m" text = regexReplaceFunc(bold_regex, text, bold, reset) text = regexReplaceFunc(italic_regex, text, inverse, reset) text = regexReplaceFunc(header_regex, text, underline_bold, reset) return text } func regexReplaceFunc(r *regexp.Regexp, text string, start string, end string) string { return r.ReplaceAllStringFunc(text, func(s string) string { return start + r.FindStringSubmatch(s)[1] + end }) }
package identity import ( "encoding/json" "testing" "github.com/stretchr/testify/assert" ) func TestClaims_Flatten(t *testing.T) { var claims Claims _ = json.Unmarshal([]byte(` { "a": { "aa": { "aaa": 12345 }, "ab": [1, 2, 3, 4, 5] } } `), &claims) flattened := claims.Flatten() assert.Equal(t, FlattenedClaims{ "a.aa.aaa": {12345.0}, "a.ab": {1.0, 2.0, 3.0, 4.0, 5.0}, }, flattened) }
package v1 import ( "github.com/coreos/prometheus-operator/pkg/client/versioned" "k8s.io/client-go/rest" ) type PrometheusMonitoringInterface interface { PrometheusGetter PrometheusRulesGetter //ServiceMonitorsGetter } type PrometheusMonitoring struct { client *versioned.Clientset } func NewForConfig(c *rest.Config) (*PrometheusMonitoring, error) { config := c client, err := versioned.NewForConfig(config) if err != nil { return nil, err } return &PrometheusMonitoring{ client: client, }, nil } func (c *PrometheusMonitoring) Prometheuses(namespace string) PrometheusInterface { return newPrometheuses(c.client, namespace) } func (c *PrometheusMonitoring) PrometheusRules(namespace string) PrometheusRuleInterface { return newPrometheusRules(c.client, namespace) }
package httputil import ( "bytes" "io/ioutil" "net/http" ) // FakeTransport represents a fake http.Transport that returns prerecorded responses. type FakeTransport struct { responses map[string]*responseCollection } // NewFakeTransport creates a new FakeTransport instance without any responses. func NewFakeTransport() *FakeTransport { return &FakeTransport{ responses: make(map[string]*responseCollection), } } // AddResponse stores a fake HTTP response for the given URL. func (ft *FakeTransport) AddResponse(url string, status int, body string, headers map[string]string) { if _, ok := ft.responses[url]; !ok { ft.responses[url] = &responseCollection{} } ft.responses[url].Add(createResponse(status, body, headers)) } // RoundTrip returns a prerecorded response to the given request, if one exists. Otherwise its response indicates 404 - not found. func (ft *FakeTransport) RoundTrip(req *http.Request) (*http.Response, error) { if responses, ok := ft.responses[req.URL.String()]; ok { return responses.Next(), nil } return notFound(), nil } type responseCollection struct { all []*http.Response next int } func (rc *responseCollection) Add(resp *http.Response) { rc.all = append(rc.all, resp) } func (rc *responseCollection) Next() *http.Response { if rc.next >= len(rc.all) { return notFound() } rc.next++ return rc.all[rc.next-1] } func createResponse(status int, body string, headers map[string]string) *http.Response { return &http.Response{ StatusCode: status, Body: ioutil.NopCloser(bytes.NewBufferString(body)), Header: transformHeaders(headers), } } func transformHeaders(original map[string]string) http.Header { result := make(map[string][]string) for k, v := range original { result[k] = []string{v} } return result } func notFound() *http.Response { return createResponse(http.StatusNotFound, "", nil) }
package main import ( "math/rand" "time" "golang.org/x/mobile/app" "golang.org/x/mobile/event/key" "golang.org/x/mobile/event/lifecycle" "golang.org/x/mobile/event/paint" "golang.org/x/mobile/event/size" "golang.org/x/mobile/event/touch" "golang.org/x/mobile/exp/gl/glutil" //"golang.org/x/mobile/exp/sprite/clock" "golang.org/x/mobile/gl" ) type _lineDefT struct { lineNO int lineSTR string } type _textDefT struct { lineAmountMax int "the max amount of line" lineAmountNow int "the rotation amount should change" lineARR []_lineDefT } type _textAPP func( *_textDefT ) var ( _startTime = time.Now() _glImageS *glutil.Images _GamE *Game ) func _textScreenMain( ___appReset1 , ___appPaint _textAPP ) { rand.Seed(time.Now().UnixNano()) app.Main( _textScreenEventLoop ) } // _textScreenMain() func _textScreenEventLoop( ___a7 app.App) { var __glCtx7 gl.Context var __sz7 size.Event for __e7 := range ___a7.Events() { switch __e8 := ___a7.Filter(__e7).(type) { case lifecycle.Event: switch __e8.Crosses(lifecycle.StageVisible) { case lifecycle.CrossOn: __glCtx7, _ = __e8.DrawContext.(gl.Context) onStart(__glCtx7) ___a7.Send(paint.Event{}) case lifecycle.CrossOff: onStop() __glCtx7 = nil } // switch __e8.Crosses(lifecycle.StageFocused) { // case lifecycle.CrossOn: // __glCtx7, _ = __e8.DrawContext.(gl.Context) // onStart(__glCtx7) // ___a7.Send(paint.Event{}) // case lifecycle.CrossOff: // __glCtx7.ClearColor(1, 1, 1, 1) // __glCtx7.Clear(gl.COLOR_BUFFER_BIT) // ___a7.Publish() // onStop() // __glCtx7 = nil // } case size.Event: __sz7 = __e8 case paint.Event: if __glCtx7 == nil || __e8.External { continue } _screenOnPaint(__glCtx7, __sz7) ___a7.Publish() ___a7.Send(paint.Event{}) // keep animating case touch.Event: if __down7 := __e8.Type == touch.TypeBegin; __down7 || __e8.Type == touch.TypeEnd { _GamE.Touch(__down7) } case key.Event: if __e8.Code != key.CodeSpacebar { break } if __down7 := __e8.Direction == key.DirPress; __down7 || __e8.Direction == key.DirRelease { _GamE.Touch(__down7) } } } } // _textScreenEventLoop
package main // 한글 '가' 부터 '갛' 까지 unicode 값을 사용하여 출력하는 예제 import "fmt" func main() { start := 44032 end := 44059 for i := start; i<=end; i++{ fmt.Print(string(i)) } }
package sort import ( "github.com/google/go-cmp/cmp" "math/rand" "sort" "testing" "time" ) func generateRandomSlice(maxSize, maxValue int) ([]int, []int) { rand.Seed(time.Now().UnixNano()) nums1 := make([]int, rand.Intn(maxSize+1)) nums2 := make([]int, len(nums1)) for i := 0; i < len(nums1); i++ { // 表达式后面的注释是因为计数排序只能对非负整数排序 nums1[i] = rand.Intn(maxValue + 1) // - rand.Intn(maxValue) } copy(nums2, nums1) return nums1, nums2 } func TestGenerateRandomSlice(t *testing.T) { for i := 0; i < 10; i++ { nums1, nums2 := generateRandomSlice(10, 99) t.Log(nums1, "\n", nums2) time.Sleep(time.Nanosecond) } } func TestBubbleSort(t *testing.T) { for i := 0; i < 1000; i++ { nums1, nums2 := generateRandomSlice(15, 99) BubbleSort(nums1, len(nums1)) sort.Ints(nums2) diff := cmp.Diff(nums1, nums2) if diff != "" { t.Fatalf(diff) } time.Sleep(time.Nanosecond) } } func TestInsertionSort(t *testing.T) { for i := 0; i < 10000; i++ { nums1, nums2 := generateRandomSlice(200, 99) InsertionSort(nums1, len(nums1)) sort.Ints(nums2) diff := cmp.Diff(nums1, nums2) if diff != "" { t.Fatalf(diff) } time.Sleep(time.Nanosecond) } } func TestSelectionSort(t *testing.T) { for i := 0; i < 10000; i++ { nums1, nums2 := generateRandomSlice(15, 99) SelectionSort(nums1, len(nums1)) sort.Ints(nums2) diff := cmp.Diff(nums1, nums2) if diff != "" { t.Fatalf(diff) } time.Sleep(time.Nanosecond) } } func TestMergeSort(t *testing.T) { for i := 0; i < 10000; i++ { nums1, nums2 := generateRandomSlice(15, 99) MergeSort(nums1, len(nums1)) sort.Ints(nums2) diff := cmp.Diff(nums1, nums2) if diff != "" { t.Fatalf(diff) } time.Sleep(time.Nanosecond) } } func TestQuickSort(t *testing.T) { for i := 0; i < 10000; i++ { nums1, nums2 := generateRandomSlice(15, 99) QuickSort(nums1, len(nums1)) sort.Ints(nums2) diff := cmp.Diff(nums1, nums2) if diff != "" { t.Fatalf(diff) } time.Sleep(time.Nanosecond) } } // 计数排序只能对非负整数进行排序 func TestCountingSort(t *testing.T) { for i := 0; i < 10000; i++ { nums1, nums2 := generateRandomSlice(15, 99) CountingSort(nums1, len(nums1)) sort.Ints(nums2) diff := cmp.Diff(nums1, nums2) if diff != "" { t.Fatalf(diff) } time.Sleep(time.Nanosecond) } }
package main import ( "fmt" "log" "os" ) func main() { archivo := "prueba.txt" f, err := os.Open(archivo) // defer no se ejecuta secuencialmente, solo lo hace al final defer f.Close() if err != nil { fmt.Println("error abriendo el archivo") // os.Exit(1) } ejemploPanic() } func ejemploPanic() { // defer ejecuta una sola cosa por eso, si quiero mas instrucciones debo crear una funcion anonima defer func() { // con recover capturo el panic reco := recover() if reco != nil { log.Fatalf("Ocurrio un error generado por panic %v", reco) } }() a := 1 if a == 1 { // forzar error panic("Se encontro valor 1") } }
package common import ( "github.com/google/logger" . "myproj.com/clmgr-coordinator/config" "os" ) func InitLogger() error { lf, err := os.OpenFile(Config.LogCoordPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660) if err != nil { logger.Fatalf("Failed to open log file: %v", err) } logger.Init("Logger", false, true, lf) return nil }
package main import ( "fmt" "os" ) func main() { fp, err := openFile(os.Args[1]) if err != nil { os.Exit(1) } fmt.Println(string(readFile(fp))) os.Exit(0) } func openFile(filename string) (*os.File, error) { fp, err := os.Open(filename) if err != nil { fmt.Println("Error while opening the file with name", filename, err) return nil, err } return fp, nil } func readFile(fp *os.File) []byte { stats, _ := fp.Stat() data := make([]byte, stats.Size()) bytes, err := fp.Read(data) if err != nil { fmt.Println("some thing went wrong while reading the file", err) } else { fmt.Println("successfully read", bytes, "from the file") } fp.Close() return data }
package diff import ( "bytes" "database/sql" "fmt" "github.com/ngaut/log" "github.com/onsi/gomega" "github.com/pingcap/errors" ) func init() { log.SetLevelByString("error") } // Diff contains two sql DB, used for comparing. type Diff struct { cfg *Config db1 *sql.DB db2 *sql.DB } // New returns a Diff instance. func New(cfg *Config, db1, db2 *sql.DB) *Diff { if cfg == nil { cfg = defaultConfig } return &Diff{ cfg: cfg, db1: db1, db2: db2, } } // Equal tests whether two database have same data and schema. func (df *Diff) Equal() (eq bool, err error) { tbls1, err := getTables(df.db1) if err != nil { err = errors.Trace(err) return } tbls2, err := getTables(df.db2) if err != nil { err = errors.Trace(err) return } eq = equalStrings(tbls1, tbls2) if !eq { log.Infof("show tables get different table. [source db tables] %v [target db tables] %v", tbls1, tbls2) return false, nil } for _, tblName := range tbls1 { if df.cfg.EqualIndex { eq, err = df.EqualIndex(tblName) if err != nil { err = errors.Trace(err) return } if !eq { log.Infof("table have different index: %s\n", tblName) return } } eq, err = df.EqualTable(tblName) if err != nil || !eq { err = errors.Trace(err) return } } return } // EqualTable tests whether two database table have same data and schema. func (df *Diff) EqualTable(tblName string) (eq bool, err error) { if df.cfg.EqualCreateTable { eq, err = df.equalCreateTable(tblName) if err != nil { return eq, errors.Trace(err) } if !eq { log.Infof("table have different schema: %s\n", tblName) return eq, err } } if df.cfg.EqualRowCount { eq, err = df.equalTableRowCount(tblName) if err != nil { return eq, errors.Trace(err) } if !eq { log.Infof("table row count different: %s\n", tblName) } } if df.cfg.EqualData { eq, err = df.equalTableData(tblName) if err != nil { return eq, errors.Trace(err) } if !eq { log.Infof("table data different: %s\n", tblName) } } return } // EqualIndex tests whether two database index are same. func (df *Diff) EqualIndex(tblName string) (bool, error) { index1, err := getTableIndex(df.db1, tblName) if err != nil { return false, errors.Trace(err) } defer index1.Close() index2, err := getTableIndex(df.db2, tblName) if err != nil { return false, errors.Trace(err) } defer index2.Close() eq, err := equalRows(index1, index2, &showIndex{}, &showIndex{}) if err != nil || !eq { return eq, errors.Trace(err) } return eq, nil } func (df *Diff) equalCreateTable(tblName string) (bool, error) { _, err1 := getCreateTable(df.db1, tblName) _, err2 := getCreateTable(df.db2, tblName) if err1 != nil && errors.IsNotFound(err1) && err2 != nil && errors.IsNotFound(err2) { return true, nil } if err1 != nil { return false, errors.Trace(err1) } if err2 != nil { return false, errors.Trace(err2) } // TODO ignore table schema currently // return table1 == table2, nil return true, nil } func (df *Diff) equalTableRowCount(tblName string) (bool, error) { rows1, err := getTableRowCount(df.db1, tblName) if err != nil { return false, errors.Trace(err) } defer rows1.Close() rows2, err := getTableRowCount(df.db2, tblName) if err != nil { return false, errors.Trace(err) } defer rows2.Close() cols1, err := rows1.ColumnTypes() if err != nil { return false, errors.Trace(err) } cols2, err := rows2.ColumnTypes() if err != nil { return false, errors.Trace(err) } if len(cols1) != len(cols2) { return false, nil } row1 := newRawBytesRow(cols1) row2 := newRawBytesRow(cols2) return equalRows(rows1, rows2, row1, row2) } func (df *Diff) equalTableData(tblName string) (bool, error) { rows1, err := getTableRows(df.db1, tblName) if err != nil { return false, errors.Trace(err) } defer rows1.Close() rows2, err := getTableRows(df.db2, tblName) if err != nil { return false, errors.Trace(err) } defer rows2.Close() cols1, err := rows1.ColumnTypes() if err != nil { return false, errors.Trace(err) } cols2, err := rows2.ColumnTypes() if err != nil { return false, errors.Trace(err) } if len(cols1) != len(cols2) { return false, nil } row1 := newRawBytesRow(cols1) row2 := newRawBytesRow(cols2) return equalRows(rows1, rows2, row1, row2) } func equalRows(rows1, rows2 *sql.Rows, row1, row2 comparableSQLRow) (bool, error) { for rows1.Next() { if !rows2.Next() { // rows2 count less than rows1 log.Info("rows count different") return false, nil } eq, err := equalOneRow(rows1, rows2, row1, row2) if err != nil || !eq { return eq, errors.Trace(err) } } if rows2.Next() { // rows1 count less than rows2 log.Info("rows count different") return false, nil } return true, nil } func equalOneRow(rows1, rows2 *sql.Rows, row1, row2 comparableSQLRow) (bool, error) { err := row1.Scan(rows1) if err != nil { return false, errors.Trace(err) } row2.Scan(rows2) if err != nil { return false, errors.Trace(err) } return row1.Equal(row2), nil } func getTableRows(db *sql.DB, tblName string) (*sql.Rows, error) { descs, err := getTableSchema(db, tblName) if err != nil { return nil, errors.Trace(err) } pk1 := orderbyKey(descs) // TODO select all data out may OOM if table is huge rows, err := querySQL(db, fmt.Sprintf("select * from `%s` order by %s", tblName, pk1)) if err != nil { return nil, errors.Trace(err) } return rows, nil } func getTableRowCount(db *sql.DB, tblName string) (*sql.Rows, error) { rows, err := querySQL(db, fmt.Sprintf("select count(*) from `%s`", tblName)) if err != nil { return nil, errors.Trace(err) } return rows, nil } func getTableIndex(db *sql.DB, tblName string) (*sql.Rows, error) { rows, err := querySQL(db, fmt.Sprintf("show index from `%s`;", tblName)) if err != nil { return nil, errors.Trace(err) } return rows, nil } func getTables(db *sql.DB) ([]string, error) { rs, err := querySQL(db, "show tables;") if err != nil { return nil, errors.Trace(err) } defer rs.Close() var tbls []string for rs.Next() { var name string err := rs.Scan(&name) if err != nil { return nil, errors.Trace(err) } tbls = append(tbls, name) } return tbls, nil } func getCreateTable(db *sql.DB, tn string) (string, error) { stmt := fmt.Sprintf("show create table `%s`;", tn) rs, err := querySQL(db, stmt) if err != nil { return "", errors.Trace(err) } defer rs.Close() if rs.Next() { var ( name string cs string ) err := rs.Scan(&name, &cs) return cs, errors.Trace(err) } return "", errors.NotFoundf("table not exist") } type comparableSQLRow interface { sqlRow comparable } type sqlRow interface { Scan(*sql.Rows) error } type comparable interface { Equal(comparable) bool } type rawBytesRow struct { rawBytes []sql.RawBytes colTypes []*sql.ColumnType } func newRawBytesRow(colTypes []*sql.ColumnType) rawBytesRow { return rawBytesRow{ colTypes: colTypes, rawBytes: make([]sql.RawBytes, len(colTypes)), } } func (r rawBytesRow) Len() int { return len(r.rawBytes) } func (r rawBytesRow) Scan(rows *sql.Rows) error { args := make([]interface{}, len(r.rawBytes)) for i := 0; i < len(args); i++ { args[i] = &r.rawBytes[i] } err := rows.Scan(args...) if err != nil { return errors.Trace(err) } return nil } func equalJSON(data1 []byte, data2 []byte) bool { if len(data1) == 0 && len(data2) != 0 { return false } if len(data2) == 0 && len(data1) != 0 { return false } if len(data1) == 0 && len(data2) == 0 { return true } matcher := gomega.MatchJSON(string(data1)) // key-ordering and whitespace shouldn't matter matched, err := matcher.Match(string(data2)) if err != nil { log.Error(err, "data1: ", string(data1), " data2: ", string(data2)) return false } return matched } func (r rawBytesRow) Equal(data comparable) bool { r2, ok := data.(rawBytesRow) if !ok { return false } if r.Len() != r2.Len() { return false } for i := 0; i < r.Len(); i++ { tname := r.colTypes[i].DatabaseTypeName() if len(tname) == 0 { log.Warn("empty type name: ", tname) } if r.colTypes[i].DatabaseTypeName() == "JSON" { if !equalJSON(r.rawBytes[i], r2.rawBytes[i]) { return false } } else { if bytes.Compare(r.rawBytes[i], r2.rawBytes[i]) != 0 { return false } } } return true } type showIndex struct { Table sql.RawBytes NonUnique sql.RawBytes KeyName sql.RawBytes SeqInIndex sql.RawBytes ColumnName sql.RawBytes Collation sql.RawBytes Cardinality sql.RawBytes SubPart sql.RawBytes Packed sql.RawBytes Null sql.RawBytes IndexType sql.RawBytes Comment sql.RawBytes IndexComment sql.RawBytes } func (si *showIndex) Scan(rows *sql.Rows) error { err := rows.Scan(&si.Table, &si.NonUnique, &si.KeyName, &si.SeqInIndex, &si.ColumnName, &si.Collation, &si.Cardinality, &si.SubPart, &si.Packed, &si.Null, &si.IndexType, &si.Comment, &si.IndexComment) return errors.Trace(err) } func (si *showIndex) Equal(data comparable) bool { si1, ok := data.(*showIndex) if !ok { return false } return bytes.Compare(si.Table, si1.Table) == 0 && bytes.Compare(si.NonUnique, si1.NonUnique) == 0 && bytes.Compare(si.KeyName, si1.KeyName) == 0 && bytes.Compare(si.SeqInIndex, si1.SeqInIndex) == 0 && bytes.Compare(si.ColumnName, si1.ColumnName) == 0 && bytes.Compare(si.SubPart, si1.SubPart) == 0 && bytes.Compare(si.Packed, si1.Packed) == 0 } type describeTable struct { Field string Type string Null string Key string Default interface{} Extra interface{} } func (desc *describeTable) Scan(rows *sql.Rows) error { err := rows.Scan(&desc.Field, &desc.Type, &desc.Null, &desc.Key, &desc.Default, &desc.Extra) return errors.Trace(err) } func getTableSchema(db *sql.DB, tblName string) ([]describeTable, error) { stmt := fmt.Sprintf("describe `%s`;", tblName) rows, err := querySQL(db, stmt) if err != nil { return nil, errors.Trace(err) } defer rows.Close() var descs []describeTable for rows.Next() { var desc describeTable err = desc.Scan(rows) if err != nil { return nil, errors.Trace(err) } descs = append(descs, desc) } return descs, err } func orderbyKey(descs []describeTable) string { // TODO can't get the real primary key var buf bytes.Buffer firstTime := true for _, desc := range descs { if desc.Key == "PRI" { if firstTime { fmt.Fprintf(&buf, "`%s`", desc.Field) firstTime = false } else { fmt.Fprintf(&buf, ",`%s`", desc.Field) } } } if buf.Len() == 0 { // if no primary key found, use all fields as order by key for _, desc := range descs { if firstTime { fmt.Fprintf(&buf, "`%s`", desc.Field) firstTime = false } else { fmt.Fprintf(&buf, ",`%s`", desc.Field) } } } return buf.String() } func querySQL(db *sql.DB, query string) (*sql.Rows, error) { var ( err error rows *sql.Rows ) log.Debugf("[query][sql]%s", query) rows, err = db.Query(query) if err != nil { log.Errorf("query sql[%s] failed %v", query, errors.ErrorStack(err)) return nil, errors.Trace(err) } return rows, nil } func equalStrings(str1, str2 []string) bool { if len(str1) != len(str2) { return false } for i := 0; i < len(str1); i++ { if str1[i] != str2[i] { return false } } return true } // ShowDatabases returns a database lists. func ShowDatabases(db *sql.DB) ([]string, error) { var ret []string rows, err := querySQL(db, "show databases;") if err != nil { return nil, err } defer rows.Close() for rows.Next() { var dbName string err := rows.Scan(&dbName) if err != nil { return nil, errors.Trace(err) } ret = append(ret, dbName) } return ret, nil }