text
stringlengths
11
4.05M
package messenger // ContentType is a specific string type type ContentType string // Content types const ( ContentTypeText ContentType = "text" ContentTypeLocation ContentType = "location" // NotificationTypeRegular will emit a sound/vibration and a phone notification NotificationTypeRegular NotificationType = "REGULAR" // NotificationTypeSilentPush will just emit a phone notification NotificationTypeSilentPush NotificationType = "SILENT_PUSH" // NotificationTypeNoPush will not emit sound/vibration nor a phone notification NotificationTypeNoPush NotificationType = "NO_PUSH" // MessagingTypeResponse described here: https://developers.facebook.com/docs/messenger-platform/send-messages#message_types MessagingTypeResponse MessagingType = "RESPONSE" // MessagingTypeUpdate described here: https://developers.facebook.com/docs/messenger-platform/send-messages#message_types MessagingTypeUpdate MessagingType = "UPDATE" // MessagingTypeMessageTag described here: https://developers.facebook.com/docs/messenger-platform/send-messages#message_types MessagingTypeMessageTag MessagingType = "MESSAGE_TAG" // MessagingTypeNonPromotionalSubscription described here: https://developers.facebook.com/docs/messenger-platform/send-messages#message_types MessagingTypeNonPromotionalSubscription MessagingType = "NON_PROMOTIONAL_SUBSCRIPTION" ) // SendMessage ... type SendMessage struct { Text string `json:"text,omitempty"` Attachment *Attachment `json:"attachment,omitempty"` QuickReplies []QuickReply `json:"quick_replies,omitempty"` Metadata string `json:"metadata,omitempty"` } // QuickReply ... type QuickReply struct { ContentType ContentType `json:"content_type"` Title string `json:"title,omitempty"` Payload string `json:"payload,omitempty"` ImageURL string `json:"image_url,omitempty"` } // Recipient describes the person who will receive the message // Either ID or PhoneNumber has to be set type Recipient struct { ID string `json:"id,omitempty"` PhoneNumber string `json:"phone_number,omitempty"` } // NotificationType describes the behavior phone will execute after receiving the message type NotificationType string // MessagingType ... type MessagingType string // MessageQuery ... type MessageQuery struct { Recipient Recipient `json:"recipient" form:"recipient"` Message *SendMessage `json:"message,omitempty" form:"message,omitempty"` NotificationType NotificationType `json:"notification_type,omitempty" form:"notification_type,omitempty"` Action SenderAction `json:"sender_action,omitempty" form:"sender_action,omitempty"` MessagingType MessagingType `json:"messaging_type,omitempty" form:"messaging_type,omitempty"` PersonaID string `json:"persona_id,omitempty" form:"persona_id,omitempty"` }
package fcm import ( "bufio" "fmt" "net" "strings" "github.com/valyala/fasthttp" ) func FasthttpHTTPDialer(proxyAddr string) fasthttp.DialFunc { return func(addr string) (net.Conn, error) { conn, err := fasthttp.Dial(strings.Replace(strings.Replace(proxyAddr, "https://", "", 1), "http://", "", 1)) if err != nil { return nil, err } req := "CONNECT " + addr + " HTTP/1.1\r\n" // req += "Proxy-Authorization: xxx\r\n" req += "\r\n" if _, err := conn.Write([]byte(req)); err != nil { return nil, err } res := fasthttp.AcquireResponse() defer fasthttp.ReleaseResponse(res) res.SkipBody = true if err := res.Read(bufio.NewReader(conn)); err != nil { conn.Close() return nil, err } if res.Header.StatusCode() != 200 { conn.Close() return nil, fmt.Errorf("could not connect to proxy") } return conn, nil } }
package main import "fmt" func main() { fmt.Println("hogwarts legacy") }
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package parser import ( gio "io" "os" "sort" "strings" "testing" requires "github.com/stretchr/testify/require" ) func TestKeywordConsistent(t *testing.T) { parserFilename := "parser.y" parserFile, err := os.Open(parserFilename) requires.NoError(t, err) data, err := gio.ReadAll(parserFile) requires.NoError(t, err) content := string(data) reservedKeywordStartMarker := "\t/* The following tokens belong to ReservedKeyword. Notice: make sure these tokens are contained in ReservedKeyword. */" unreservedKeywordStartMarker := "\t/* The following tokens belong to UnReservedKeyword. Notice: make sure these tokens are contained in UnReservedKeyword. */" notKeywordTokenStartMarker := "\t/* The following tokens belong to NotKeywordToken. Notice: make sure these tokens are contained in NotKeywordToken. */" tidbKeywordStartMarker := "\t/* The following tokens belong to TiDBKeyword. Notice: make sure these tokens are contained in TiDBKeyword. */" identTokenEndMarker := "%token\t<item>" reservedKeywords := extractKeywords(content, reservedKeywordStartMarker, unreservedKeywordStartMarker) unreservedKeywords := extractKeywords(content, unreservedKeywordStartMarker, notKeywordTokenStartMarker) notKeywordTokens := extractKeywords(content, notKeywordTokenStartMarker, tidbKeywordStartMarker) tidbKeywords := extractKeywords(content, tidbKeywordStartMarker, identTokenEndMarker) for k, v := range aliases { requires.NotEqual(t, k, v) requires.Equal(t, tokenMap[v], tokenMap[k]) } keywordCount := len(reservedKeywords) + len(unreservedKeywords) + len(notKeywordTokens) + len(tidbKeywords) requires.Equal(t, keywordCount-len(windowFuncTokenMap), len(tokenMap)-len(aliases)) unreservedCollectionDef := extractKeywordsFromCollectionDef(content, "\nUnReservedKeyword:") requires.Equal(t, unreservedCollectionDef, unreservedKeywords) notKeywordTokensCollectionDef := extractKeywordsFromCollectionDef(content, "\nNotKeywordToken:") requires.Equal(t, notKeywordTokensCollectionDef, notKeywordTokens) tidbKeywordsCollectionDef := extractKeywordsFromCollectionDef(content, "\nTiDBKeyword:") requires.Equal(t, tidbKeywordsCollectionDef, tidbKeywords) } func extractMiddle(str, startMarker, endMarker string) string { startIdx := strings.Index(str, startMarker) if startIdx == -1 { return "" } str = str[startIdx+len(startMarker):] endIdx := strings.Index(str, endMarker) if endIdx == -1 { return "" } return str[:endIdx] } func extractQuotedWords(strs []string) []string { //nolint: prealloc var words []string for _, str := range strs { word := extractMiddle(str, "\"", "\"") if word == "" { continue } words = append(words, word) } sort.Strings(words) return words } func extractKeywords(content, startMarker, endMarker string) []string { keywordSection := extractMiddle(content, startMarker, endMarker) lines := strings.Split(keywordSection, "\n") return extractQuotedWords(lines) } func extractKeywordsFromCollectionDef(content, startMarker string) []string { keywordSection := extractMiddle(content, startMarker, "\n\n") words := strings.Split(keywordSection, "|") return extractQuotedWords(words) }
package dumper import ( "testing" ) func TestGetDumper(t *testing.T) { GetDumper("fs", map[interface{}]interface{}{}) }
package OgameUtil import "bitbucket.org/jc01rho/ogame" func SendRess(bot *ogame.OGame) { //bot.SendFleet() }
// standalone tool to fetch a stream from Twitch and post it to Discord // run in folder with .env file package main import ( "fmt" "os" "strings" "time" . "github.com/Pyorot/streams/src/utils" "github.com/nicklaw5/helix" "github.com/bwmarrin/discordgo" ) var err error var channelID, iconURL string var discord *discordgo.Session var twitch *helix.Client var getStreamsParams helix.StreamsParams var full bool // full message or stub func init() { // argument validation if len(os.Args) != 3 { exit() } if os.Args[1] == "d" { full = true } else if os.Args[1] != "a" { exit() } // env vars Env.Load() channelID = strings.Split(Env.GetOrExit("MSG_CHANNELS"), ",")[0][1:] iconURL = Env.GetOrExit("MSG_ICON") // discord discord, err = discordgo.New("Bot " + Env.GetOrExit("DISCORD")) ExitIfError(err) // twitch twitch, err = helix.NewClient(&helix.Options{ ClientID: Env.GetOrExit("TWITCH_ID"), ClientSecret: Env.GetOrExit("TWITCH_SEC"), }) ExitIfError(err) res, err := twitch.GetAppAccessToken(nil) ExitIfError(err) twitch.SetAppAccessToken(res.Data.AccessToken) getStreamsParams = helix.StreamsParams{ GameIDs: []string{os.Args[2]}, First: 100, } } func main() { res, err := twitch.GetStreams(&getStreamsParams) if len(res.Data.Streams) == 0 { err = fmt.Errorf("no active streams of this game") } ExitIfError(err) fmt.Println(". | fetched") var msg *discordgo.MessageSend if full { msg = &discordgo.MessageSend{Embed: newMsgFromStream(&res.Data.Streams[0])} } else { msg = newMsgStubFromStream(&res.Data.Streams[0]) } _, err = discord.ChannelMessageSendComplex(channelID, msg) ExitIfError(err) fmt.Println(". | posted") } // what a notification would look like func newMsgStubFromStream(r *helix.Stream) *discordgo.MessageSend { return &discordgo.MessageSend{Content: fmt.Sprintf("%s: %s", r.UserName, r.Title)} } // what a message would look like func newMsgFromStream(r *helix.Stream) *discordgo.MessageEmbed { indexUserStart := strings.LastIndexByte(r.ThumbnailURL, '/') + 11 indexUserEnd := strings.LastIndexByte(r.ThumbnailURL, '-') urlUser := r.ThumbnailURL[indexUserStart:indexUserEnd] thumbnail := r.ThumbnailURL[:indexUserEnd+1] + "440x248.jpg" length := time.Since(r.StartedAt) return &discordgo.MessageEmbed{ Author: &discordgo.MessageEmbedAuthor{ Name: r.UserName + " is live", URL: "https://twitch.tv/" + urlUser, IconURL: iconURL, }, Description: r.Title, Color: 0x00ff00, Thumbnail: &discordgo.MessageEmbedThumbnail{ URL: thumbnail, }, Footer: &discordgo.MessageEmbedFooter{ Text: strings.TrimSuffix(length.Truncate(time.Minute).String(), "0s"), }, Timestamp: time.Now().Format("2006-01-02T15:04:05Z"), } } func exit() { fmt.Print( "Usage: Posts a message with the currently most-popular stream of the specified game (by gameID).\n", "./postmsg a 69 -- stub message for alerts\n", "./postmsg d 69 -- full message for display\n", ) os.Exit(0) }
package detectOldOfficeExtension import ( "bytes" "github.com/richardlehane/mscfb" "io" "os" ) func isOle(in []byte) bool { return bytes.HasPrefix(in, []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}) } /* Работает гораздо лучше чем от vasilie mimetype, но все равно не идеально 2021/08/05 16:20:10 /home/us/Загрузки/7z/test.doc[ext:.ole] */ func DetectOldOffice(filename string) string { file, err := os.Open(filename) if err != nil { return "" } sign := make([]byte,8) //file.Read зависает и не дает идти дальше _,err = file.ReadAt(sign,0) if err != nil { return "" } if !isOle(sign) { return "" } _,err = file.Seek(0,io.SeekStart) if err != nil { return "" } doc, err := mscfb.New(file) if err!= nil { return "" } entry := getLastSummaryInformation(doc) if entry == nil { return "" } if entry.Name == "SummaryInformation"{ buf := make([]byte,entry.Size) _,err = entry.Read(buf) if err!= nil { return "" } if bytes.Contains(buf,[]byte("Microsoft Office PowerPoint")) || bytes.Contains(buf,[]byte("Microsoft PowerPoint")){ return ".ppt" } if bytes.Contains(buf,[]byte("Microsoft Excel")) || bytes.Contains(buf,[]byte("Microsoft Office Excel")) { return ".xls" } if bytes.Contains(buf,[]byte("Microsoft Office Word")) || bytes.Contains(buf,[]byte("Microsoft Word")) { return ".doc" } if bytes.Contains(buf,[]byte("Microsoft Visio")) || bytes.Contains(buf,[]byte("Microsoft Office Visio")) { return ".vsd" } } return ".ole" } //особенность в том, что в документ могут быть встроены //другие документы и из-за этого расширение мб неправильно //распознано, поэтому берется последний файл //SummaryInformation, который относится к основному документу (но это не точно) //в целом пока не было документов которые бы ошибочно определялись этим способом func getLastSummaryInformation(doc *mscfb.Reader)*mscfb.File{ var lastEntry *mscfb.File for entry, err := doc.Next(); err == nil; entry, err = doc.Next() { name := entry.Name if name == "SummaryInformation" { lastEntry = entry } } return lastEntry }
package main import "fmt" func main() { name := "Nabila" if len(name) > 9 { fmt.Println("masuk") } else { fmt.Println("gak masuk") } }
package main import ( "bufio" "encoding/json" "fmt" "io/ioutil" "math/rand" "os" "time" ) //Creating an array struct to store planets type Planets struct { Planets []PlanetDesc `json:"planets"` } //Creating a struct for planets names and descriptions type PlanetDesc struct { Name string `json:"name"` Description string `json:"description"` } func main() { //Initial stdout to user with name request personName := bufio.NewReader(os.Stdin) fmt.Printf("Welcome to the Solar System!\n") fmt.Printf("There are 9 planets to explore.\n") fmt.Printf("What is your name?\n") text, _ := personName.ReadString('\n') //Stdout with name and start of planet selection fmt.Printf("What's up " + text) fmt.Printf("My name is Eliza, I'm Alexas cooler older sister.\n") fmt.Printf("Shall I randomly choose a planet for you to visit? (Y or N)\n") travel() } func travel() { //Creating the response variable var response string var planets Planets fmt.Scanln(&response) //If Y, boolean set to true if response == "Y" { planetChoice(planets, response, true) //If N, boolean remains false } else if response == "N" { fmt.Println("What planet would you like to learn about?") planetChoice(planets, response, false) //Else repeat question } else { fmt.Printf("Could you repeat that?\n") travel() } } func planetChoice(planets Planets, userResponse string, randomizePlanet bool) { //Creating some variables, and random number for randomized planet seed := rand.NewSource(time.Now().UnixNano()) newrand := rand.New(seed) var x = newrand.Intn(9) var specificPlanet string var index int var planetFound bool //Opening the planets json file jsonFile, err := os.Open("planets.json") //Checking if no errors occur, if any do print error if err != nil { fmt.Println(err) } //Defer closing of the json file so it can be parsed defer jsonFile.Close() byteValue, _ := ioutil.ReadAll(jsonFile) json.Unmarshal(byteValue, &planets) //If the user wants a random planet, give it to them if randomizePlanet { fmt.Println(planets.Planets[x].Name + ": " + planets.Planets[x].Description) //Else if they want a specific planet, have them type in the name } else { fmt.Scanln(&specificPlanet) //Iterate through planets to find specific planet chosen for i := 0; i < len(planets.Planets); i++ { //If the users entry exists in the array, print name and description if specificPlanet == planets.Planets[i].Name { index = i planetFound = true } } //Check if planet exists in the array, if so, print out name and description if planetFound { fmt.Println(planets.Planets[index].Name + ": " + planets.Planets[index].Description) //Else repeat question } else { fmt.Println("That's not a planet...try again...") planetChoice(planets, specificPlanet, false) } } }
package main import ( "context" "log" "time" "github.com/brigadecore/brigade-foundations/retries" "github.com/brigadecore/brigade-foundations/signals" "github.com/brigadecore/brigade-foundations/version" "github.com/brigadecore/brigade/sdk/v3" "github.com/brigadecore/brigade/v2/internal/kubernetes" ) func main() { log.Printf( "Starting Brigade Observer -- version %s -- commit %s", version.Version(), version.Commit(), ) ctx := signals.Context() // Brigade Healthcheck and Workers API clients var systemClient sdk.SystemClient var workersClient sdk.WorkersClient { address, token, opts, err := apiClientConfig() if err != nil { log.Fatal(err) } client := sdk.NewAPIClient(address, token, &opts) // No network I/O occurs when creating the API client, so we'll test it // here. This will block until the underlying connection is verified or max // retries are exhausted. What we're trying to prevent is both 1. moving on // in the startup process without the API server available AND 2. crashing // too prematurely while waiting for the API server to become available. if err := testClient(ctx, client); err != nil { log.Fatal(err) } systemClient = client.System() workersClient = client.Core().Events().Workers() } kubeClient, err := kubernetes.Client() if err != nil { log.Fatal(err) } // Observer var observer *observer { config, err := getObserverConfig() if err != nil { log.Fatal(err) } observer = newObserver( systemClient, workersClient, kubeClient, config, ) } // Run it! log.Println(observer.run(ctx)) } func testClient(ctx context.Context, client sdk.APIClient) error { ctx, cancel := context.WithTimeout(ctx, 10*time.Minute) defer cancel() return retries.ManageRetries( ctx, // The retry loop will exit when this context expires "api server ping", 0, // "Infinite" retries 10*time.Second, // Max backoff func() (bool, error) { if _, err := client.System().Ping(ctx, nil); err != nil { return true, err // Retry } return false, nil // Success }, ) }
package main type tokenType int type char uint8 const eof char = 255 const ( tokenEOF tokenType = iota tokenComment // Simple single or multi-line comment tokenIdentifier // Any identifier that is not a keyword tokenOn // The keyword 'on', indicating a trigger tokenFunc // The 'func' keyword indicating a new method tokenIf tokenElse tokenLParen // Left parenthesis '(' tokenRParen // Right parenthesis ')' tokenInteger // An integer literal tokenSemicolon // A semicolon ';' tokenLBrack tokenRBrack tokenAssign tokenString // A string literal tokenBool tokenComma tokenMinus tokenEqual // == tokenNotEqual // != tokenLessThan // < tokenGreaterThan // > tokenLessOrEqual // <= tokenGreaterOrEqual // >= tokenNot // ! tokenPlus tokenDivide tokenMultiply tokenModulo ) type scanAction func(*scanner) scanAction type token struct { tokenType tokenType value string from int to int } type scanner struct { data string pos int prevpos int mark int tokens chan token state scanAction } func (s *scanner) markPosition(offset int) { s.mark = s.pos s.mark += offset } func (s *scanner) current() char { if s.pos >= len(s.data) { return eof } return char(s.data[s.pos]) } func (s *scanner) rewind(num int) { s.pos -= num } func (s *scanner) peek(num int) char { return char(s.data[s.pos+num]) } func (s *scanner) next() char { if s.pos >= len(s.data) { return eof } r := s.data[s.pos] s.pos++ return char(r) } func (s *scanner) value() string { return s.data[s.mark:s.pos] } func (s *scanner) makeToken(t tokenType) { newToken := token{ tokenType: t, value: s.value(), from: s.mark, to: s.pos, } if newToken.tokenType != tokenComment { s.tokens <- newToken } } func scanAny(s *scanner) scanAction { c := s.current() if c == eof { s.makeToken(tokenEOF) return nil } for { if c == 0 || c == eof { s.makeToken(tokenEOF) return nil } else if c == ' ' || c == '\t' || c == '\n' || c == '\r' { s.next() c = s.current() continue } break } s.markPosition(0) if c == '/' { s.next() c = s.peek(0) if c == '/' { s.next() // consume '/' return scanSingleComment } else if c == '*' { s.next() return scanMultilineComment } else { s.makeToken(tokenDivide) return scanAny } } else if c == '"' { return scanString } else if c == '(' { s.next() s.makeToken(tokenLParen) return scanAny } else if c == ')' { s.next() s.makeToken(tokenRParen) return scanAny } else if c == '{' { s.next() s.makeToken(tokenLBrack) return scanAny } else if c == '}' { s.next() s.makeToken(tokenRBrack) return scanAny } else if c == ';' { s.next() s.makeToken(tokenSemicolon) return scanAny } else if c == '=' { s.next() c = s.peek(0) if c == '=' { s.next() s.makeToken(tokenEqual) } else { s.makeToken(tokenAssign) } return scanAny } else if c == '!' { c = s.next() if c == '=' { s.next() s.makeToken(tokenNotEqual) } else { s.makeToken(tokenNot) } return scanAny } else if c == '<' { c = s.next() if c == '=' { s.next() s.makeToken(tokenLessOrEqual) } else { s.makeToken(tokenLessThan) } return scanAny } else if c == '>' { c = s.next() if c == '=' { s.next() s.makeToken(tokenGreaterOrEqual) } else { s.makeToken(tokenGreaterThan) } return scanAny } else if c == ',' { s.next() s.makeToken(tokenComma) return scanAny } else if c == '-' { s.next() if isIntegerChar(s.current()) { return scanIntegerLiteral } else { s.makeToken(tokenMinus) return scanAny } } else if c == '+' { s.next() s.makeToken(tokenPlus) return scanAny } else if c == '*' { s.next() s.makeToken(tokenMultiply) return scanAny } else if c == '%' { s.next() s.makeToken(tokenModulo) return scanAny } if isStartOfIdentifier(c) { return scanIdentifier } else if isIntegerChar(c) { return scanIntegerLiteral } s.rewind(1) fragmentEnd := s.pos + 10 if fragmentEnd > len(s.data) { fragmentEnd = len(s.data) } panic("unknown char: " + string(c) + "; data: " + s.data[s.pos:fragmentEnd]) return nil } func scanSingleComment(s *scanner) scanAction { for { c := s.next() if c == '\n' || c == eof { s.rewind(1) break } } s.makeToken(tokenComment) return scanAny } func scanMultilineComment(s *scanner) scanAction { for { c := s.next() if c == '*' && s.peek(0) == '/' { s.next(); s.next() // consume both * and / break } else if c == eof { s.rewind(1) break } } s.makeToken(tokenComment) return scanAny } func scanString(s *scanner) scanAction { c := s.next() for { c = s.next() if c == '"' { // TODO EOL/EOF break } } s.makeToken(tokenString) return scanAny } func isStartOfIdentifier(c char) bool { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '$' } func isIdentifierChar(c char) bool { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '$' } func isIntegerChar(c char) bool { return c >= '0' && c <= '9' } func scanIdentifier(s *scanner) scanAction { for { c := s.next() if !isIdentifierChar(c) { s.rewind(1) break } } value := s.value() if value == "on" { s.makeToken(tokenOn) } else if value == "func" { s.makeToken(tokenFunc) } else if value == "if" { s.makeToken(tokenIf) } else if value == "else" { s.makeToken(tokenElse) } else if value == "true" || value == "false" { s.makeToken(tokenBool) } else { s.makeToken(tokenIdentifier) } return scanAny } func scanIntegerLiteral(s *scanner) scanAction { if s.current() == '-' { s.next() } for { c := s.next() if !isIntegerChar(c) { s.rewind(1) break } } s.makeToken(tokenInteger) return scanAny } func (s *scanner) run() { for s.state = scanAny; s.state != nil; { s.state = s.state(s) } close(s.tokens) } func ScanText(text string) []token { s := scanner{ data: text, tokens: make(chan token), } go s.run() tokens := make([]token, 512)[:0] for v := range s.tokens { tokens = append(tokens, v) } return tokens }
package queries import ( "database/sql" "encoding/json" "net/url" "github.com/pwang347/cs304/server/common" ) // QueryAllBaseImages returns all baseImage rows func QueryAllBaseImages(db *sql.DB, params url.Values) (data []byte, err error) { var ( response = SQLResponse{} tx *sql.Tx ) if tx, err = db.Begin(); err != nil { return nil, err } if response.Data, response.AffectedRows, err = common.QueryJSON(tx, "SELECT * FROM BaseImage;"); err != nil { tx.Rollback() return } if err = tx.Commit(); err != nil { return } data, err = json.Marshal(response) return }
package avardstock import ( "errors" "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" h "github.com/qasemt/helper" "os" "path" "strings" "sync" ) var pathdb string //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::STRUCT INIT type Nemad struct { ID uint64 `gorm:"primary_key; not null"` NemadID string GroupCode string GroupName string NemadCode string NameEn string NameFa string NameFull string AvardCode int } type NemadAvard struct { ID uint64 `gorm:"primary_key; not null"` TypeId string `json:"type_id"` Type string `json:"type"` EntityId int64 `json:"entity_id"` EntityType string `json:"entity_type"` TradeSymbol string `json:"trade_symbol"` Title string `json:"title"` } type StockFromWebService struct { ID uint64 `gorm:"primary_key; not null"` AssetId string `gorm:"unique_index:indexok;not null"` IsIndex int `gorm:"not null;default:0"` TimeFrame int `gorm:"unique_index:indexok; not null"` TypeChart int `gorm:"unique_index:indexok; not null;default:0"` Time int64 `gorm:"unique_index:indexok;not null" json:"time"` O float64 `json:"open"` H float64 `json:"high"` L float64 `json:"low"` C float64 `json:"close"` V float64 `json:"volume"` } func (e StockFromWebService) TOString() string { return fmt.Sprintf("ID :%v Time:%f ,frame: %v type :%v", e.ID, e.Time, e.TimeFrame, e.TypeChart) } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: func DatabaseInit(dbName1 string, timefrm string) (*gorm.DB, string, error) { var err error var db *gorm.DB var dirdbstr string var fullPath string dirdbstr = path.Join(h.GetRootCache(), "cache") if _, err := os.Stat(dirdbstr); os.IsNotExist(err) { os.MkdirAll(dirdbstr, os.ModePerm) } if timefrm == "" { fullPath = path.Join(dirdbstr, fmt.Sprintf("%v.bin", dbName1)) } else { //fullPath = path.Join(dirdbstr, fmt.Sprintf("%v_%v.bin", dbName1, timefrm)) fullPath = path.Join(dirdbstr, fmt.Sprintf("%v.bin", dbName1)) } db, err = gorm.Open("sqlite3", fullPath) if err != nil { db = nil panic("failed to connect database") } return db, fullPath, nil } func Migrate(dbName1 string, isp *StockProvider) error { var fullPath string db, fullPath, er := DatabaseInit(dbName1, "") if er != nil { return errors.New(fmt.Sprintf("err:%v %v", er, fullPath)) } defer isp.closeMyDb(db) if strings.Contains(fullPath, "main.bin") { db.AutoMigrate(&Nemad{}) } else { db.AutoMigrate(&StockFromWebService{}) } return nil } func InsertStocks(d *gorm.DB, k *sync.Mutex, last_record StockFromWebService, isIndex bool, stockList []StockFromWebService, assetid string, timeframe h.ETimeFrame, tc h.ETypeChart) error { defer k.Unlock() k.Lock() if d == nil { return errors.New("db not init") } /*for i := 0; i < len(stockList); i++ { t := stockList[i] t.AssetId = assetid t.TimeFrame = int(timeframe) t.TypeChart = int(tc) if e1 := d.Where("asset_id = ? and time_frame = ? and type_chart=? and time = ?", assetid, timeframe, int(tc), t.Time).Order("time desc").Limit(1).First(&t).Error; gorm.IsRecordNotFoundError(e1) { d.Create(&t) } }*/ //________________ valueStrings := []string{} for _, t := range stockList { t.AssetId = assetid t.TimeFrame = int(timeframe) t.TypeChart = int(tc) if isIndex == true { t.IsIndex = 1 } valueStrings = append(valueStrings, fmt.Sprintf("(\"%s\", %v,%v, %v, %v, %v, %v, %v, %v, %v)", t.AssetId, t.IsIndex, t.TimeFrame, t.TypeChart, t.Time, t.O, t.H, t.L, t.C, t.V)) } smt := `INSERT OR REPLACE INTO stock_from_web_services (asset_id,is_index,time_frame,type_chart,TIME,o,h,l,c,v) VALUES %s ;` smt = fmt.Sprintf(smt, strings.Join(valueStrings, ",")) tx := d.Begin() if err := tx.Exec(smt).Error; err != nil { tx.Rollback() return err } tx.Commit() //:::::::::::::::::::::::: if last_record.ID != 0 { smt1 := fmt.Sprintf(" delete from stock_from_web_services where id = %v", last_record.ID) tx1 := d.Begin() if err1 := tx1.Exec(smt1).Error; err1 != nil { tx1.Rollback() return err1 } tx1.Commit() } return nil } func getLastRecord(d *gorm.DB, k *sync.Mutex, assetid string, timeframe int, tc h.ETypeChart, out *StockFromWebService) error { defer k.Unlock() k.Lock() if d == nil { return errors.New("db not init") } if e1 := d.Where("asset_id = ? and time_frame = ? and type_chart=?", assetid, timeframe, int(tc)).Order("time desc").Limit(1).First(out).Error; gorm.IsRecordNotFoundError(e1) { //fmt.Println("getLastRecord () -> record not found") } if d.Error != nil { return d.Error } return nil } func getRecordesStock(d *gorm.DB, k *sync.Mutex, assetid string, timeframe h.ETimeFrame, tc h.ETypeChart) ([]StockFromWebService, error) { defer k.Unlock() k.Lock() if d == nil { return nil, errors.New("db not init") } var items []StockFromWebService if e1 := d.Where("asset_id = ? and time_frame = ? and type_chart=?", assetid, int(timeframe), int(tc)).Order("time").Find(&items).Error; gorm.IsRecordNotFoundError(e1) { //fmt.Println("getLastRecord () -> record not found") } if d.Error != nil { return nil, d.Error } return items, nil } func GetNemadList(d *gorm.DB, k *sync.Mutex) ([]NemadAvard, error) { defer k.Unlock() k.Lock() if d == nil { return nil, errors.New("db not init") } var items []NemadAvard if e1 := d.Find(&items).Error; gorm.IsRecordNotFoundError(e1) { fmt.Println("getNemadList () -> record not found") } if d.Error != nil { return nil, d.Error } return items, nil } func InsertAssetInfoFromAvard(d *gorm.DB, k *sync.Mutex, avardsAsset []NemadAvard) error { defer k.Unlock() k.Lock() if d == nil { return errors.New("db not init") } d.DropTableIfExists(&NemadAvard{}) d.AutoMigrate(&NemadAvard{}) //----------------------------------------------------- valueStrings := []string{} for _, f := range avardsAsset { valueStrings = append(valueStrings, fmt.Sprintf("(\"%s\", \"%s\", %v,\"%s\",\"%s\",\"%s\")", f.TypeId, f.Type, f.EntityId, f.EntityType, f.TradeSymbol, f.Title)) } smt := `INSERT INTO nemad_avards (type_id,type,entity_id,entity_type,trade_symbol,title) VALUES %s ;` smt = fmt.Sprintf(smt, strings.Join(valueStrings, ",")) tx := d.Begin() if err := tx.Exec(smt).Error; err != nil { tx.Rollback() return err } tx.Commit() return nil }
package post import ( "encoding/json" "html/template" "net/http" "github.com/VolticFroogo/Animal-Pictures/captcha" "github.com/VolticFroogo/Animal-Pictures/db" "github.com/VolticFroogo/Animal-Pictures/helpers" "github.com/VolticFroogo/Animal-Pictures/models" "github.com/gorilla/context" "github.com/gorilla/mux" ) type voteRequest struct { Upvote bool Captcha, CaptchaV2 string } type voteResponse struct { Score int } // Page is for the for posts. func Page(w http.ResponseWriter, r *http.Request) { uuid, loggedIn := context.GetOk(r, "uuid") variables := models.TemplateVariables{ LoggedIn: loggedIn, } if loggedIn { self, err := db.GetUserFromUUID(uuid.(string)) if err != nil { helpers.ThrowErr(w, r, "Getting user from DB error", err) return } csrfSecret, err := r.Cookie("csrfSecret") if err != nil { helpers.ThrowErr(w, r, "Getting CSRF Secret cookie error", err) return } variables.Self = self variables.CsrfSecret = csrfSecret.Value } vars := mux.Vars(r) post, err := db.GetPost(vars["uuid"]) if err != nil { helpers.ThrowErr(w, r, "Getting post from DB error", err) return } variables.Post = post var t *template.Template if post.Creation == 0 { t, err = template.ParseFiles("templates/post/not-found.html", "templates/nested.html") // Parse the HTML pages. if err != nil { helpers.ThrowErr(w, r, "Template parsing error", err) return } } else { t, err = template.ParseFiles("templates/post/page.html", "templates/nested.html") // Parse the HTML pages. if err != nil { helpers.ThrowErr(w, r, "Template parsing error", err) return } } if vote, ok := variables.Post.Votes[variables.Self.UUID]; ok { if vote { variables.Post.Vote = 1 } else { variables.Post.Vote = 2 } } err = t.Execute(w, variables) if err != nil { helpers.ThrowErr(w, r, "Template execution error", err) } } // Vote is for the for vote requests. func Vote(w http.ResponseWriter, r *http.Request) { var data voteRequest // Create struct to store data. err := json.NewDecoder(r.Body).Decode(&data) // Decode response to struct. if err != nil { w.WriteHeader(http.StatusInternalServerError) helpers.ThrowErr(w, r, "JSON decoding error", err) return } // Secure our request with reCAPTCHA v2 and v3. if !captcha.V3(data.CaptchaV2, data.Captcha, r.Header.Get("CF-Connecting-IP"), "vote") { w.WriteHeader(http.StatusBadRequest) return } vars := mux.Vars(r) post, err := db.GetPost(vars["uuid"]) if err != nil { w.WriteHeader(http.StatusInternalServerError) helpers.ThrowErr(w, r, "Getting post from DB error", err) return } if post.Creation == 0 { // Post has been deleted. w.WriteHeader(http.StatusGone) return } score, err := db.SetVote(post, context.Get(r, "uuid").(string), data.Upvote) if err != nil { w.WriteHeader(http.StatusInternalServerError) helpers.ThrowErr(w, r, "Setting vote error", err) return } helpers.JSONResponse(voteResponse{ Score: score, }, w) return }
/** in addition to the main goroutine, launch two additional goroutines - each additional goroutine should print something out use waitgroups to make sure each goroutine finishes before your program exists */ package main import ( "fmt" "sync" ) var wg sync.WaitGroup func main() { fmt.Println("Main Routine Start") wg.Add(1) go routine1() wg.Add(1) go routine2() fmt.Println("Main Routine End") wg.Wait() } func routine1() { fmt.Println("Routine 1") wg.Done() } func routine2() { fmt.Println("Routine 2") wg.Done() }
package metric import ( "errors" "os" ) // type Query struct { obj string fp *os.File } // 打开查询器 func (p *Query) Open() error { //打开文件指针 // 与windows相比,Linux在open时需要知道具体打开哪个文件 // windows的query是通用指针,不需要提前搜集信息 var err error p.fp, err = os.OpenFile(p.obj, os.O_RDONLY, 0) return err } // 关闭查询器 func (p *Query) Close() error { // 关闭文件指针 return p.fp.Close() } // 查询器采样 // 大多数计数器需要2次采样才能计算出数据 func (p *Query) Collect() error { // 与windows相比,winquery collect后系统给缓存了数据 // 而linux需要自己缓存数据 return nil } // 添加指标对象到查询器 func (p *Query) AddMetric(m interface{}) error { _, ok := m.(Metric) if !ok { return errors.New("can not convert interface to Metric type") } return nil }
package db import ( "time" "github.com/google/uuid" "crud/chrono" ) type ProductMapping struct { Sku *string `bson:"topvalue_sku"` Barcode *string `bson:"cj_barcode"` } type APILog struct { ID *string `bson:"_id"` TransactionID *string `bson:"transaction_id"` OrderID *string `bson:"order_id,omitempty"` CreatedAt *time.Time `bson:"created_at"` Request *APIRequest `bson:"request"` Response *APIResponse `bson:"response"` } type APIRequest struct { URL string `bson:"url"` Method string `bson:"method"` Headers map[string][]string `bson:"headers"` Body interface{} `bson:"body"` } type APIResponse struct { HTTPStatus int `bson:"http_status"` Headers map[string][]string `bson:"header"` Body interface{} `bson:"body"` Latency int64 `bson:"latency"` } func NewAPILog() *APILog { uuid := uuid.NewString() now := chrono.Now().Time return &APILog{ ID: &uuid, TransactionID: &uuid, CreatedAt: &now, } } type Order struct { ID *string `bson:"_id"` OrderID *string `bson:"order_id"` CJCode *string `bson:"cj_code"` CJBillNo *string `bson:"cj_bill_no"` GrandTotal *float64 `bson:"grand_total"` Items []*Item `bson:"items"` CreatedAt *time.Time `bson:"created_at"` IsPaymentConfirmed bool `bson:"is_payment_confirmed"` PaymentConfirmedAt *time.Time `bson:"payment_confirmed_at"` ShouldRetry bool `bson:"should_retry"` IsPendingRetry bool `bson:"is_pending_retry"` LastAttemptAt *time.Time `bson:"last_attempt_at"` RetryAttempt int64 `bson:"retry_attempt"` DeletedAt *time.Time `bson:"deleted_at"` } type Item struct { ItemID *int64 `bson:"item_id"` Barcode string `bson:"barcode"` ItemName *string `bson:"item_name"` Price *float64 `bson:"price"` QtyOrdered *int64 `bson:"qty_ordered"` }
// Package server implements a server for artifactory monitoring. package server import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/url" "os" "os/signal" "sync" "time" "github.com/composer22/hello-world/logger" ) // Server is the main structure that represents a server instance. type Server struct { mu sync.RWMutex // For locking access to server attributes. running bool // Is the server running? srvr *http.Server // HTTP server. log *logger.Logger // Log instance for recording error and other messages. } // New is a factory function that returns a new server instance. func New() *Server { s := &Server{ running: false, log: logger.New(logger.UseDefault, false), } // Setup the routes and server. mux := http.NewServeMux() mux.HandleFunc(httpRouteV1Health, s.healthHandler) mux.HandleFunc(httpRouteV1Hello, s.helloHandler) s.srvr = &http.Server{ Addr: fmt.Sprintf("%s:%d", DefaultHostName, DefaultPort), Handler: &Middleware{serv: s, handler: mux}, ReadTimeout: TCPReadTimeout, WriteTimeout: TCPWriteTimeout, } return s } // Start spins up the server to accept incoming requests. func (s *Server) Start() error { if s.isRunning() { return errors.New("Server already started.") } s.log.Infof("Starting hello world\n") s.handleSignals() s.mu.Lock() s.running = true s.mu.Unlock() err := s.srvr.ListenAndServe() if err != nil { s.log.Emergencyf("Listen and Server Error: %s", err.Error()) } // Done. s.mu.Lock() s.running = false s.mu.Unlock() return nil } // Shutdown takes down the server gracefully back to an initialize state. func (s *Server) Shutdown() { if !s.isRunning() { return } s.log.Infof("BEGIN server service stop.") s.mu.Lock() s.srvr.SetKeepAlivesEnabled(false) s.running = false s.mu.Unlock() s.log.Infof("END server service stop.") } // handleSignals responds to operating system interrupts such as application kills. func (s *Server) handleSignals() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) go func() { for sig := range c { s.log.Infof("Server received signal: %v\n", sig) s.Shutdown() s.log.Infof("Server exiting.") os.Exit(0) } }() } // The following methods handle server routes. // healthHandler handles a client "is the server alive?" request. func (s *Server) healthHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("OK")) } // helloHandler returns "Hello World!". func (s *Server) helloHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello World!")) } // initResponseHeader sets up the common http response headers for the return of all json calls. func (s *Server) initResponseHeader(w http.ResponseWriter) { h := w.Header() h.Add("Content-Type", "application/json;charset=utf-8") h.Add("Date", time.Now().UTC().Format(time.RFC1123Z)) h.Add("X-Request-ID", createV4UUID()) } // isRunning returns a boolean representing whether the server is running or not. func (s *Server) isRunning() bool { s.mu.RLock() defer s.mu.RUnlock() return s.running } // requestLogEntry is a datastructure of a log entry for recording server access requests. type requestLogEntry struct { Method string `json:"method"` URL *url.URL `json:"url"` Proto string `json:"proto"` Header http.Header `json:"header"` Body string `json:"body"` ContentLength int64 `json:"contentLength"` Host string `json:"host"` RemoteAddr string `json:"remoteAddr"` RequestURI string `json:"requestURI"` Trailer http.Header `json:"trailer"` } // LogRequest logs the http request information into the logger. func (s *Server) LogRequest(r *http.Request) { var cl int64 if r.ContentLength > 0 { cl = r.ContentLength } bd, err := ioutil.ReadAll(r.Body) if err != nil { bd = []byte("Could not parse body") } r.Body = ioutil.NopCloser(bytes.NewBuffer(bd)) // We need to set the body back after we read it. b, _ := json.Marshal(&requestLogEntry{ Method: r.Method, URL: r.URL, Proto: r.Proto, Header: r.Header, Body: string(bd), ContentLength: cl, Host: r.Host, RemoteAddr: r.RemoteAddr, RequestURI: r.RequestURI, Trailer: r.Trailer, }) s.log.Infof(`{"request":%s}`, string(b)) }
package datastructures import ( "testing" ) func TestSet_UnionBasic(t *testing.T) { a := NewSet([]string{"A", "B", "C"}) b := NewSet([]string{"D", "E", "F"}) result := a.Union(b) expected := NewSet([]string{"A", "B", "C", "D", "E", "F"}) if !result.Equals(expected) { t.Errorf("result should containa all elements") } } func TestSet_UnionOverlapping(t *testing.T) { a := NewSet([]string{"A", "B", "D", "P"}) b := NewSet([]string{"A", "B", "Q"}) result := a.Union(b) expected := NewSet([]string{"A", "B", "D", "P", "Q"}) if !result.Equals(expected) { t.Errorf("result should containa all elements") } } func TestSet_UnionCopies(t *testing.T) { a := NewSet([]string{"A", "B", "D", "P"}) b := NewSet([]string{"A", "B", "Q"}) result := a.Union(b) if result.Equals(a) || result.Equals(b) { t.Errorf("Union did not create a new struct") } } func TestSet_IntersectionWithValues(t *testing.T) { a := NewSet([]string{"A", "B", "C"}) b := NewSet([]string{"A", "C"}) result := a.Intersection(b) if len(result) != 2 { t.Errorf("should have 2 elements has %v", len(result)) } result2 := b.Intersection(a) if len(result2) != 2 { t.Errorf("should have 2 elements has %v", len(result2)) } } func TestSet_IntersectionWithoutValues(t *testing.T) { a := NewSet([]string{}) b := NewSet([]string{"A", "B", "C"}) result := a.Intersection(b) if len(result) != 0 { t.Errorf("result should have 0 elements, has %v", len(result)) } }
package mysql import ( . "cms/structs" ) func FindUserByName(username string) (user User, err error) { _, err = engine.Where("userName = ?", username).Get(&user) return }
/* * @lc app=leetcode.cn id=54 lang=golang * * [54] 螺旋矩阵 */ // @lc code=start package main import "fmt" func spiralOrder(matrix [][]int) []int { if len(matrix) == 0 { return []int{} } rows := len(matrix) columns := len(matrix[0]) target := rows * columns a := make([]int, target) index := 0 l, t := 0, 0 r, b := columns-1, rows-1 for index < target { for i := l; i <= r && index < target ; i++ { a[index] = matrix[l][i] index++ } t++ for i := t; i <= b && index < target; i++ { a[index] = matrix[i][r] index++ } r-- for i := r; i >= l && index < target ; i-- { a[index] = matrix[b][i] index++ } b-- for i := b; i >= t && index < target; i-- { a[index] = matrix[i][l] index++ } l++ } return a } // @lc code=end func main() { // n := 4 // a := make([][]int, n) // for i := 0 ; i < 4 ; i++{ // a[i] = make([]int, 4) // } a := [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}} // c := make([][]int, 4) // a = make([]int, 4) // a[0] b := spiralOrder(a) fmt.Println(b) c := [][]int{{1,2,3},{4,5,6},{7,8,9}} d := spiralOrder(c) fmt.Println(d) }
package ginplugin import ( "sync" "time" ) type SessionData map[string][]byte type SessionStore interface { Load(id string) (SessionData, error) Save(id string, sessionData SessionData, ttlInMillis int) error TouchIfExists(id string, ttlInMillis int) error } type memSessionStore struct { sync.RWMutex data map[string]entry } type entry struct { val SessionData ttl int64 } func (m *memSessionStore) Load(id string) (SessionData, error) { m.RLock() val, ok := m.data[id] m.RUnlock() now := time.Now().UnixMilli() if !ok { return nil, nil } else if val.ttl <= now { return nil, nil } else { return val.val, nil } } func (m *memSessionStore) Save(id string, sessionData SessionData, ttlInMillis int) error { ttl := time.Now().UnixMilli() + int64(ttlInMillis) m.Lock() val, ok := m.data[id] if !ok { val = entry{} } val.ttl = ttl val.val = sessionData m.data[id] = val m.Unlock() return nil } func (m *memSessionStore) TouchIfExists(id string, ttlInMillis int) error { ttl := time.Now().UnixMilli() + int64(ttlInMillis) m.Lock() val, ok := m.data[id] if ok { val.ttl = ttl m.data[id] = val } m.Unlock() return nil } func (m *memSessionStore) cleanupLoop() { ticker := time.NewTicker(5 * time.Minute) for { <-ticker.C now := time.Now().UnixMilli() func() { m.Lock() defer m.Unlock() for k, v := range m.data { if v.ttl <= now { delete(m.data, k) } } }() } } func NewMemSessionStore() SessionStore { store := &memSessionStore{ data: map[string]entry{}, } go store.cleanupLoop() return store }
package comment import ( "github.com/kataras/iris" "github.com/kataras/iris/mvc" ) type CommentsController struct { topicId int64 } func (m *CommentsController) BeforeActivation(b mvc.BeforeActivation) { b.Handle("GET", "/topics/{topicId:long}/comments", "Get") b.Handle("POST", "/topics/{topicId:long}/comments", "Post") } func (c *CommentsController) BeginRequest(ctx iris.Context) { } func (c *CommentsController) Post(topicId int64) { } func (c *CommentsController) Get(topicId int64) { } type OneCommentController struct { TopicId int64 CommentId int64 } func (m *OneCommentController) BeforeActivation(b mvc.BeforeActivation) { b.Handle("GET", "/topics/{topicId:long}/comments/{commentId:long}", "Get") b.Handle("DELETE", "/topics/{topicId:long}/comments/{commentId:long}", "Delete") } func (c *OneCommentController) BeginRequest(ctx iris.Context) { } func (c *OneCommentController) Get(topicId int64, commentId int64) { } func (c *OneCommentController) Delete(topicId int64, commentId int64) { }
package pkg var Fab func()
package tfc import ( tfcPb "github.com/stefanprisca/strategy-protobufs/tfc" ) func GetPlayerId(player tfcPb.Player) int32 { return int32(player) } func GetResourceId(r tfcPb.Resource) int32 { return int32(r) } func InitPlayerProfile() *tfcPb.PlayerProfile { startingResources := make(map[int32]int32) for _, r := range []tfcPb.Resource{tfcPb.Resource_CAMP, tfcPb.Resource_FIELD, tfcPb.Resource_FOREST, tfcPb.Resource_MOUNTAIN, tfcPb.Resource_PASTURE, tfcPb.Resource_HILL} { id := GetResourceId(r) startingResources[id] = 5 } return &tfcPb.PlayerProfile{ Resources: startingResources, WinningPoints: 0, Settlements: 2, Roads: 2, } }
package main import ( "fmt" "log" "time" "github.com/sanksons/tavern/common/entity" "github.com/BoutiqaatREPO/nitrous/nitrous" ) func main() { Cache, err := nitrous.GetElastiCacheAdapter(nitrous.ElastiCacheConf{ Addrs: []string{"172.17.0.2:30001"}, PoolSize: 20, }) if err != nil { log.Fatal(err) } adapter := Cache.Adapter // // Set a Single key in cache // adapter.Set(entity.CacheItem{ Key: entity.CacheKey{Name: "Key1"}, Value: []byte("I am key 1"), Expiration: 10 * time.Second, //in seconds }) // // Get a Single Key from Cache // data, _ := adapter.Get(entity.CacheKey{Name: "Key1"}) fmt.Printf("%s", string(data)) // // Set Multiple Keys // adapter.MSet([]entity.CacheItem{ entity.CacheItem{ Key: entity.CacheKey{Name: "MKey1"}, Value: []byte("I am MKey1"), Expiration: 10 * time.Hour, }, entity.CacheItem{ Key: entity.CacheKey{Name: "MKey2"}, Value: []byte("I am MKey2"), Expiration: 5 * time.Hour, }, entity.CacheItem{ Key: entity.CacheKey{Name: "MKey3"}, Value: []byte("I am MKey3"), Expiration: 7 * time.Hour, }, }...) // // get Multiple Keys // datamap, _ := adapter.MGet([]entity.CacheKey{ entity.CacheKey{Name: "MKey1"}, entity.CacheKey{Name: "MKey2"}, entity.CacheKey{Name: "MKey3"}, }...) for k, v := range datamap { fmt.Printf("\nKey: %s, Data: %s", k, v) } // // BUCKETING Feature // adapter.MSet([]entity.CacheItem{ entity.CacheItem{ Key: entity.CacheKey{Name: "MKey1b", Bucket: "B1"}, Value: []byte("I am MKey1"), Expiration: 10 * time.Hour, }, entity.CacheItem{ Key: entity.CacheKey{Name: "MKey2b", Bucket: "B2"}, Value: []byte("I am MKey2"), Expiration: 5 * time.Hour, }, entity.CacheItem{ Key: entity.CacheKey{Name: "MKey3b", Bucket: "B3"}, Value: []byte("I am MKey3"), Expiration: 7 * time.Hour, }, }...) datamap1, _ := adapter.MGet([]entity.CacheKey{ entity.CacheKey{Name: "MKey1b", Bucket: "B1"}, entity.CacheKey{Name: "MKey2b", Bucket: "B2"}, entity.CacheKey{Name: "MKey3b", Bucket: "B3"}, }...) for k, v := range datamap1 { fmt.Printf("\nKey: %s, Data: %s", k, v) } }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //220. Contains Duplicate III //Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k. //func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { //} // Time Is Money
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" file_action "github.com/Files-com/files-sdk-go/fileaction" ) var ( FileActions = &cobra.Command{ Use: "file-actions [command]", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) {}, } ) func FileActionsInit() { var fieldsCopy string paramsFileActionCopy := files_sdk.FileActionCopyParams{} cmdCopy := &cobra.Command{ Use: "copy", Run: func(cmd *cobra.Command, args []string) { result, err := file_action.Copy(paramsFileActionCopy) if err != nil { fmt.Println(err) os.Exit(1) } lib.JsonMarshal(result, fieldsCopy) }, } cmdCopy.Flags().StringVarP(&paramsFileActionCopy.Path, "path", "p", "", "Path to operate on.") cmdCopy.Flags().StringVarP(&paramsFileActionCopy.Destination, "destination", "d", "", "Copy destination path.") cmdCopy.Flags().StringVarP(&fieldsCopy, "fields", "", "", "comma separated list of field names") FileActions.AddCommand(cmdCopy) var fieldsMove string paramsFileActionMove := files_sdk.FileActionMoveParams{} cmdMove := &cobra.Command{ Use: "move", Run: func(cmd *cobra.Command, args []string) { result, err := file_action.Move(paramsFileActionMove) if err != nil { fmt.Println(err) os.Exit(1) } lib.JsonMarshal(result, fieldsMove) }, } cmdMove.Flags().StringVarP(&paramsFileActionMove.Path, "path", "p", "", "Path to operate on.") cmdMove.Flags().StringVarP(&paramsFileActionMove.Destination, "destination", "d", "", "Move destination path.") cmdMove.Flags().StringVarP(&fieldsMove, "fields", "", "", "comma separated list of field names") FileActions.AddCommand(cmdMove) var fieldsBeginUpload string paramsFileActionBeginUpload := files_sdk.FileActionBeginUploadParams{} cmdBeginUpload := &cobra.Command{ Use: "begin-upload", Run: func(cmd *cobra.Command, args []string) { result, err := file_action.BeginUpload(paramsFileActionBeginUpload) if err != nil { fmt.Println(err) os.Exit(1) } lib.JsonMarshal(result, fieldsBeginUpload) }, } cmdBeginUpload.Flags().StringVarP(&paramsFileActionBeginUpload.Path, "path", "t", "", "Path to operate on.") cmdBeginUpload.Flags().IntVarP(&paramsFileActionBeginUpload.Part, "part", "p", 0, "Part if uploading a part.") cmdBeginUpload.Flags().IntVarP(&paramsFileActionBeginUpload.Parts, "parts", "a", 0, "How many parts to fetch?") cmdBeginUpload.Flags().StringVarP(&paramsFileActionBeginUpload.Ref, "ref", "r", "", "") cmdBeginUpload.Flags().IntVarP(&paramsFileActionBeginUpload.Restart, "restart", "e", 0, "File byte offset to restart from.") cmdBeginUpload.Flags().StringVarP(&fieldsBeginUpload, "fields", "", "", "comma separated list of field names") FileActions.AddCommand(cmdBeginUpload) }
// Copyright 2020 The Operator-SDK Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package ansible import ( "fmt" "os" "path/filepath" "strings" "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/util/validation" "sigs.k8s.io/kubebuilder/pkg/model/config" "sigs.k8s.io/kubebuilder/pkg/plugin" "sigs.k8s.io/kubebuilder/pkg/plugin/scaffold" "github.com/operator-framework/operator-sdk/internal/kubebuilder/cmdutil" "github.com/operator-framework/operator-sdk/internal/plugins/ansible/v1/scaffolds" "github.com/operator-framework/operator-sdk/internal/plugins/manifests" "github.com/operator-framework/operator-sdk/internal/plugins/scorecard" ) type initPlugin struct { config *config.Config apiPlugin createAPIPlugin // If true, run the `create api` plugin. doCreateAPI bool // For help text. commandName string } var ( _ plugin.Init = &initPlugin{} _ cmdutil.RunOptions = &initPlugin{} ) // UpdateContext injects documentation for the command func (p *initPlugin) UpdateContext(ctx *plugin.Context) { ctx.Description = ` Initialize a new Ansible-based operator project. Writes the following files - a kubebuilder PROJECT file with the domain and project layout configuration - a Makefile that provides an interface for building and managing the operator - Kubernetes manifests and kustomize configuration - a watches.yaml file that defines the mapping between APIs and Roles/Playbooks Optionally creates a new API, using the same flags as "create api" ` ctx.Examples = fmt.Sprintf(` # Scaffold a project with no API $ %s init --plugins=%s --domain=my.domain \ # Invokes "create api" $ %s init --plugins=%s \ --domain=my.domain \ --group=apps --version=v1alpha1 --kind=AppService $ %s init --plugins=%s \ --domain=my.domain \ --group=apps --version=v1alpha1 --kind=AppService \ --generate-role $ %s init --plugins=%s \ --domain=my.domain \ --group=apps --version=v1alpha1 --kind=AppService \ --generate-playbook $ %s init --plugins=%s \ --domain=my.domain \ --group=apps --version=v1alpha1 --kind=AppService \ --generate-playbook \ --generate-role `, ctx.CommandName, pluginKey, ctx.CommandName, pluginKey, ctx.CommandName, pluginKey, ctx.CommandName, pluginKey, ctx.CommandName, pluginKey, ) p.commandName = ctx.CommandName } func (p *initPlugin) BindFlags(fs *pflag.FlagSet) { fs.SortFlags = false fs.StringVar(&p.config.Domain, "domain", "my.domain", "domain for groups") fs.StringVar(&p.config.ProjectName, "project-name", "", "name of this project, the default being directory name") p.apiPlugin.BindFlags(fs) } func (p *initPlugin) InjectConfig(c *config.Config) { c.Layout = pluginKey p.config = c p.apiPlugin.config = p.config } func (p *initPlugin) Run() error { if err := cmdutil.Run(p); err != nil { return err } // Run SDK phase 2 plugins. if err := p.runPhase2(); err != nil { return err } return nil } // SDK phase 2 plugins. func (p *initPlugin) runPhase2() error { if err := manifests.RunInit(p.config); err != nil { return err } if err := scorecard.RunInit(p.config); err != nil { return err } if p.doCreateAPI { if err := p.apiPlugin.runPhase2(); err != nil { return err } } return nil } func (p *initPlugin) Validate() error { // Check if the project name is a valid k8s namespace (DNS 1123 label). if p.config.ProjectName == "" { dir, err := os.Getwd() if err != nil { return fmt.Errorf("error getting current directory: %v", err) } p.config.ProjectName = strings.ToLower(filepath.Base(dir)) } if err := validation.IsDNS1123Label(p.config.ProjectName); err != nil { return fmt.Errorf("project name (%s) is invalid: %v", p.config.ProjectName, err) } defaultOpts := scaffolds.CreateOptions{CRDVersion: "v1"} if !p.apiPlugin.createOptions.GVK.Empty() || p.apiPlugin.createOptions != defaultOpts { p.doCreateAPI = true return p.apiPlugin.Validate() } return nil } func (p *initPlugin) GetScaffolder() (scaffold.Scaffolder, error) { var ( apiScaffolder scaffold.Scaffolder err error ) if p.doCreateAPI { apiScaffolder, err = p.apiPlugin.GetScaffolder() if err != nil { return nil, err } } return scaffolds.NewInitScaffolder(p.config, apiScaffolder), nil } func (p *initPlugin) PostScaffold() error { if !p.doCreateAPI { fmt.Printf("Next: define a resource with:\n$ %s create api\n", p.commandName) } return nil }
package form type Pather interface { Path() string }
package message import ( common "football-squares/server/common" db "football-squares/server/db" "log" "time" ) const insertOneSQL = `INSERT INTO messages (message_text, created_at, user_id, game_id) VALUES ($1, $2, $3, $4) RETURNING id;` const selectFromGameSQL = `SELECT * FROM messages where game_id=$1;` const selectAllSQL = `SELECT * FROM messages;` // Message data object type Message struct { ID string `json:"id"` MessageText string `json:"message_text"` CreatedAt *time.Time `json:"created_at"` UpdatedAt *time.Time `json:"updated_at"` Archived bool `json:"archived"` UserID string `json:"user_id"` GameID *string `json:"game_id"` } // Input for incoming inserted messages type Input struct { MessageText string `json:"message_text"` Archived bool `json:"archived"` UserID string `json:"user_id"` GameID string `json:"game_id"` } // Messages is a slice of message. type Messages struct { Messages []Message } // PostMessageQuery posts a single message func PostMessageQuery(messageInput *Input) (common.ID, error) { var err error out := common.ID{} err = db.DB.QueryRow(insertOneSQL, &messageInput.MessageText, time.Now(), &messageInput.UserID, &messageInput.GameID).Scan(&out.ID) if err != nil { log.Print(err) return out, err } log.Println("New record ID is:", out.ID) return out, nil } // QueryMessages returns all messages func QueryMessages(messages *Messages) error { rows, err := db.DB.Query(selectAllSQL) if err != nil { return err } defer rows.Close() for rows.Next() { message := Message{} err = rows.Scan( &message.ID, &message.MessageText, &message.CreatedAt, &message.UpdatedAt, &message.Archived, &message.UserID, &message.GameID, ) if err != nil { return err } messages.Messages = append(messages.Messages, message) } err = rows.Err() if err != nil { return err } return nil } // QueryMessagesByGame returns a games' worth of messages func QueryMessagesByGame(i *common.ID) (*Messages, error) { val := Messages{} rows, err := db.DB.Query(selectFromGameSQL, &i.ID) if err != nil { return nil, err } defer rows.Close() for rows.Next() { message := Message{} err = rows.Scan( &message.ID, &message.MessageText, &message.CreatedAt, &message.UpdatedAt, &message.Archived, &message.UserID, &message.GameID, ) if err != nil { return nil, err } val.Messages = append(val.Messages, message) } err = rows.Err() if err != nil { return nil, err } return &val, nil } // QueryMessage returns a single message func QueryMessage(i *common.ID) (Message, error) { val := Message{} row := db.DB.QueryRow(`SELECT * FROM messages where id=$1;`, &i.ID) err := row.Scan( &val.ID, &val.MessageText, &val.CreatedAt, &val.UpdatedAt, &val.Archived, &val.UserID, &val.GameID, ) if err != nil { log.Print(err) return val, err } return val, nil }
package ginja import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func TestGetType(t *testing.T) { Convey("GetType returns the reflected type of the underlying Object", t, func() { Convey("on values", func() { ro := ResourceObject{Object: testItem} So(ro.getType(), ShouldEqual, "testitem") }) Convey("as well as on pointers", func() { ro := ResourceObject{Object: &testItem} So(ro.getType(), ShouldEqual, "testitem") }) }) }
package im_mysql_model import ( "Open_IM/pkg/common/db" "time" ) func InsertIntoGroupRequest(groupId, fromUserId, toUserId, reqMsg, fromUserNickName, fromUserFaceUrl string) error { dbConn, err := db.DB.MysqlDB.DefaultGormDB() if err != nil { return err } toInsertInfo := GroupRequest{GroupID: groupId, FromUserID: fromUserId, ToUserID: toUserId, ReqMsg: reqMsg, FromUserNickname: fromUserNickName, FromUserFaceUrl: fromUserFaceUrl, CreateTime: time.Now()} err = dbConn.Table("group_request").Create(&toInsertInfo).Error if err != nil { return err } return nil } func FindGroupRequestUserInfoByGroupIDAndUid(groupId, uid string) (*GroupRequest, error) { dbConn, err := db.DB.MysqlDB.DefaultGormDB() if err != nil { return nil, err } var requestUserInfo GroupRequest err = dbConn.Table("group_request").Where("from_user_id=? and group_id=?", uid, groupId).Find(&requestUserInfo).Error if err != nil { return nil, err } return &requestUserInfo, nil } func DelGroupRequest(groupId, fromUserId, toUserId string) error { dbConn, err := db.DB.MysqlDB.DefaultGormDB() if err != nil { return err } err = dbConn.Exec("delete from group_request where group_id=? and from_user_id=? and to_user_id=?", groupId, fromUserId, toUserId).Error if err != nil { return err } return nil } func FindGroupBeInvitedRequestInfoByUidAndGroupID(groupId, uid string) (*GroupRequest, error) { dbConn, err := db.DB.MysqlDB.DefaultGormDB() if err != nil { return nil, err } var beInvitedRequestUserInfo GroupRequest err = dbConn.Table("group_request").Where("to_user_id=? and group_id=?", uid, groupId).Find(&beInvitedRequestUserInfo).Error if err != nil { return nil, err } return &beInvitedRequestUserInfo, nil } func InsertGroupRequest(groupId, fromUser, fromUserNickName, fromUserFaceUrl, toUser, requestMsg, handledMsg string, handleStatus int) error { return nil }
package api import ( "encoding/json" "log" "net/http" "github.com/tlmiller/garage-door-controller/api" "github.com/tlmiller/garage-door-controller/door" ) type StatusResponse struct { Id door.Id `json:"id"` Current door.State `json:"current"` IsTriggered bool `json:"isTriggered"` Next door.State `json:"next"` } func doorStatusHandler(res http.ResponseWriter, req *http.Request) { statDoor, ok := req.Context().Value(doorIdKey).(door.Door) if ok == false { log.Printf("failed converting context \"%s\" to door.Door", doorIdKey) api.Error(res, http.StatusInternalServerError) return } res.Header().Set("content-type", "application/json") nextState, triggered := statDoor.IsTriggered() status := StatusResponse{ Id: statDoor.Id(), Current: statDoor.State(), IsTriggered: triggered, Next: nextState, } json.NewEncoder(res).Encode(status) }
package main import ( "crypto/tls" "crypto/x509" "errors" "io/ioutil" "log" "code.cloudfoundry.org/go-envstruct" "google.golang.org/grpc/credentials" ) // Config is the configuration for a LogCache. type Config struct { Addr string `env:"ADDR, required, report"` AppSelector string `env:"APP_SELECTOR, required, report"` Namespace string `env:"NAMESPACE"` // QueryTimeout sets the maximum allowed runtime for a single PromQL query. // Smaller timeouts are recommended. QueryTimeout int64 `env:"QUERY_TIMEOUT, report"` TLS } // LoadConfig creates Config object from environment variables func LoadConfig() (*Config, error) { c := Config{ //Addr: ":8080", QueryTimeout: 10, } if err := envstruct.Load(&c); err != nil { return nil, err } return &c, nil } type TLS struct { CAPath string `env:"CA_PATH, required, report"` CertPath string `env:"CERT_PATH, required, report"` KeyPath string `env:"KEY_PATH, required, report"` } func (t TLS) Credentials(cn string) credentials.TransportCredentials { creds, err := NewTLSCredentials(t.CAPath, t.CertPath, t.KeyPath, cn) if err != nil { log.Fatalf("failed to load TLS config: %s", err) } return creds } func NewTLSCredentials( caPath string, certPath string, keyPath string, cn string, ) (credentials.TransportCredentials, error) { cfg, err := NewMutualTLSConfig(caPath, certPath, keyPath, cn) if err != nil { return nil, err } return credentials.NewTLS(cfg), nil } func NewMutualTLSConfig(caPath, certPath, keyPath, cn string) (*tls.Config, error) { cert, err := tls.LoadX509KeyPair(certPath, keyPath) if err != nil { return nil, err } tlsConfig := NewBaseTLSConfig() tlsConfig.ServerName = cn tlsConfig.Certificates = []tls.Certificate{cert} caCertBytes, err := ioutil.ReadFile(caPath) if err != nil { return nil, err } caCertPool := x509.NewCertPool() if ok := caCertPool.AppendCertsFromPEM(caCertBytes); !ok { return nil, errors.New("cannot parse ca cert") } tlsConfig.RootCAs = caCertPool return tlsConfig, nil } func NewBaseTLSConfig() *tls.Config { return &tls.Config{ InsecureSkipVerify: false, MinVersion: tls.VersionTLS12, CipherSuites: supportedCipherSuites, } } var supportedCipherSuites = []uint16{ tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, }
package other import ( "sync/atomic" "testing" ) func TestAtomicAdd(t *testing.T) { var c int32 = 0 atomic.AddInt32(&c, 1) if c != 1 { t.Error("atomic not modify the origin value") } t.Logf("c is %d", c) } func TestChannel(t *testing.T) { }
package service import ( "context" "fmt" "github.com/colinrs/ffly-plus/internal/code" "github.com/colinrs/ffly-plus/internal/config" "github.com/colinrs/ffly-plus/models" "github.com/colinrs/ffly-plus/pkg/token" "github.com/gin-gonic/gin" "gorm.io/gorm" ) // UserRegisterService 管理用户注册服务 type UserRegisterService struct { Nickname string `form:"nickname" json:"nickname" binding:"required,min=2,max=30"` UserName string `form:"user_name" json:"user_name" binding:"required,min=5,max=30"` Password string `form:"password" json:"password" binding:"required,min=8,max=40"` PasswordConfirm string `form:"password_confirm" json:"password_confirm" binding:"required,min=8,max=40"` } // valid 验证表单 func (service *UserRegisterService) valid() error { if service.PasswordConfirm != service.Password { return code.ErrPasswordIncorrect } query := map[string]interface{}{ "user_name": service.UserName, "nickname": service.Nickname, } _, err := models.SelectUser(query) if err != nil { if err == gorm.ErrRecordNotFound { return nil } return err } return code.ErrUserExistBefor } // Register 用户注册 func (service *UserRegisterService) Register() error { user := models.User{ Nickname: service.Nickname, UserName: service.UserName, Status: fmt.Sprintf("%s--status", service.Nickname), Avatar: models.Active, } // 表单验证 if err := service.valid(); err != nil { return err } // 加密密码 if err := user.SetPassword(service.Password); err != nil { return code.ErrEncrypt } // 创建用户 if err := models.CreateUser(&user); err != nil { return code.ErrUserCreate } return nil } // UserLoginService 管理用户登录的服务 type UserLoginService struct { UserName string `form:"user_name" json:"user_name" binding:"required,min=5,max=30"` Password string `form:"password" json:"password" binding:"required,min=8,max=40"` } // Login 用户登录函数 func (service *UserLoginService) Login(c *gin.Context) (string, error) { var user *models.User query := map[string]interface{}{ "user_name": service.UserName, } user, err := models.SelectUser(query) if err != nil { return "", err } if !user.CheckPassword(service.Password) { return "", code.ErrEmailOrPassword } tokenContext := token.Context{ UserID: uint64(user.ID), Username: user.UserName, ExpirationTime: int64(config.Conf.App.JwtExpirationTime), } tokenString, err := token.Sign(context.Background(), tokenContext, config.Conf.App.JwtSecret) return tokenString, err } // SelectUser .... func SelectUser(query map[string]interface{}) (*models.User, error) { return models.SelectUser(query) } // DeletetUser .... func DeletetUser(query map[string]interface{}) (*models.User, error) { return models.DeleteUser(query) } // UserUpdateService 管理用户更新务 type UserUpdateService struct { Nickname string `form:"nickname" json:"nickname"` Password string `form:"password" json:"password"` } // UserUpdate ... func (service *UserUpdateService) UserUpdate(query map[string]interface{}) (*models.User, error) { update := map[string]interface{}{} if service.Password != "" { update["password"] = service.Password } if service.Nickname != "" { update["nickname"] = service.Nickname } if len(update) == 0 { return nil, nil } return models.UpdataUser(query, update) }
// Package customer contains the business logic for customers. package customer
package stringtree_test import ( . "github.com/tomcully/stringtree-go" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("StringTreeNode", func() { Describe("Factory New", func() { It("should construct a node properly", func() { x := NewStringTreeNode('t', 2) Expect(x.Char).To(Equal('t')) Expect(x.Value).To(Equal(2)) Expect(x.Left).To(BeNil()) Expect(x.Right).To(BeNil()) }) }) Describe("Add", func() { var root *StringTreeNode BeforeEach(func() { root = NewStringTreeNode('t', 2) }) It("should return the new node", func() { a := root.Add('a', 10) Expect(a).NotTo(BeNil()) Expect(a.Char).To(Equal('a')) Expect(a.Value).To(Equal(10)) }) It("should add a node left if rune is less", func() { root.Add('a', 10) Expect(root.Left).NotTo(BeNil()) Expect(root.Right).To(BeNil()) Expect(root.Left.Char).To(Equal('a')) Expect(root.Left.Value).To(Equal(10)) }) It("should replace value if rune is equal", func() { root.Add('t', 20) Expect(root.Left).To(BeNil()) Expect(root.Right).To(BeNil()) Expect(root.Char).To(Equal('t')) Expect(root.Value).To(Equal(20)) }) It("should add a node right if rune is greater", func() { root.Add('z', 40) Expect(root.Left).To(BeNil()) Expect(root.Right).NotTo(BeNil()) Expect(root.Right.Char).To(Equal('z')) Expect(root.Right.Value).To(Equal(40)) }) }) Describe("AddNode", func() { var root *StringTreeNode BeforeEach(func() { root = NewStringTreeNode('t', 2) }) It("should add a node left if rune is less", func() { root.AddNode(NewStringTreeNode('a', 10)) Expect(root.Left).NotTo(BeNil()) Expect(root.Right).To(BeNil()) Expect(root.Left.Char).To(Equal('a')) Expect(root.Left.Value).To(Equal(10)) }) It("should add a node right if rune is greater", func() { root.AddNode(NewStringTreeNode('z', 40)) Expect(root.Left).To(BeNil()) Expect(root.Right).NotTo(BeNil()) Expect(root.Right.Char).To(Equal('z')) Expect(root.Right.Value).To(Equal(40)) }) It("should not modify tree if supplied nil", func() { root.AddNode(nil) Expect(root.Left).To(BeNil()) Expect(root.Right).To(BeNil()) Expect(root.Char).To(Equal('t')) Expect(root.Value).To(Equal(2)) }) }) Describe("Find", func() { var ( root *StringTreeNode a *StringTreeNode b *StringTreeNode z *StringTreeNode ) BeforeEach(func() { root = NewStringTreeNode('t', 2) a = root.Add('a', 1) b = root.Add('b', 5) z = root.Add('z', 10) }) It("should find a node if it exists", func() { var node = root.Find('b') Expect(node).NotTo(BeNil()) Expect(node.Char).To(Equal('b')) Expect(node.Value).To(Equal(5)) }) It("should returnnil if it does not exist", func() { var node = root.Find('p') Expect(node).To(BeNil()) }) }) Describe("Remove", func() { var ( root *StringTreeNode a *StringTreeNode b *StringTreeNode z *StringTreeNode ) BeforeEach(func() { root = NewStringTreeNode('t', 2) a = root.Add('a', 1) b = root.Add('b', 5) z = root.Add('z', 10) }) It("should remove a value and retain the tree", func() { root = root.Remove('b', nil) Expect(root.Char).To(Equal('t')) Expect(root.Left).NotTo(BeNil()) Expect(root.Left.Char).To(Equal('a')) Expect(root.Left.Left).To(BeNil()) Expect(root.Left.Right).To(BeNil()) Expect(root.Right).NotTo(BeNil()) Expect(root.Right.Char).To(Equal('z')) Expect(root.Right.Left).To(BeNil()) Expect(root.Right.Right).To(BeNil()) }) It("should remove the root value and reassign root", func() { root = root.Remove('t', nil) Expect(root.Char).To(Equal('a')) Expect(root.Left).To(BeNil()) Expect(root.Right.Char).To(Equal('b')) Expect(root.Right.Right.Char).To(Equal('z')) }) It("should remove a leaf value", func() { root = root.Remove('z', nil) Expect(root.Left).NotTo(BeNil()) Expect(root.Left.Char).To(Equal('a')) Expect(root.Left.Left).To(BeNil()) Expect(root.Left.Right).NotTo(BeNil()) Expect(root.Left.Right.Char).To(Equal('b')) Expect(root.Right).To(BeNil()) }) }) })
package core import ( "testing" "bytes" "crypto/sha256" "github.com/stretchr/testify/assert" "golang.org/x/crypto/ripemd160" ) func TestNewWallet(t *testing.T) { private, public := newKeyPair() wallet := &Wallet{private, public} twallet := NewWallet(private, public) assert.Equal( t, wallet, twallet, "Level 1 hash 1 is correct", ) } func TestWallet_GetAddress(t *testing.T) { } func TestHashPubKey(t *testing.T) { _, pubKey := newKeyPair() ripemd160Hash := ripemd160.New() sha256PubKey := sha256.Sum256(pubKey) _, err := ripemd160Hash.Write(sha256PubKey[:]) if err != nil { t.Error("ripemd160Hash Error", err) } expectedRes := ripemd160Hash.Sum(nil) testRes := HashPubKey(pubKey) if !bytes.Equal(expectedRes, testRes) { t.Error("Expected", expectedRes, " got ", testRes) } } func TestValidateAddress(t *testing.T) { }
package midi import ( "fmt" "github.com/telyn/midi/msgs" ) type ChannelSplitHandler map[uint8]msgs.Handler func (csh ChannelSplitHandler) Handle(msg msgs.Message) error { if !msg.Kind.HasChannel() { return fmt.Errorf("%v messages don't have channels - a ChannelSplitHandler is a mistake", msg.Kind) } if h, ok := csh[msg.Channel]; ok { return h.Handle(msg) } return fmt.Errorf("No handler available for channel %d", msg.Channel) }
package gomet import ( "time" ) // Event is the stat object that Meter sends to Collector each time Meter's Method is called. // Collector has representation of current meter state and changes it according to Event. type Event struct { Group string Worker int64 State string Time time.Time }
package main import ( "fmt" ) const ( float32_precision = 0.0000001 ) func square(num uint32, precision uint32) float32 { // get the intger var i float32 = 0 for i*i <= float32(num) { if i*i == float32(num) { return i } i = i + 1 } i = float32(i - 1) // calc the precision var multi float32 = 1 for precision > 0 { precision-- multi *= 10 unit := 1 / multi for i*i <= float32(num) { if i*i >= float32(num) { return i } i = i + unit } i = i - unit if unit <= float32_precision { break } } return i } func main() { fmt.Println("Welcome to the playground!") num := uint32(2) fmt.Println("Result for item position:", square(num, uint32(7))) }
package mr import ( "encoding/json" "fmt" "hash/fnv" "io/ioutil" "log" "net/rpc" "os" "sort" "time" ) // for sorting by key. type ByKey []KeyValue // for sorting by key. func (a ByKey) Len() int { return len(a) } func (a ByKey) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByKey) Less(i, j int) bool { return a[i].Key < a[j].Key } // // Map functions return a slice of KeyValue. // type KeyValue struct { Key string Value string } // // use ihash(key) % NReduce to choose the reduce // task number for each KeyValue emitted by Map. // func ihash(key string) int { h := fnv.New32a() h.Write([]byte(key)) return int(h.Sum32() & 0x7fffffff) } // // main/mrworker.go calls this function. // func Worker(mapf func(string, string) []KeyValue, reducef func(string, []string) string) { // Your worker implementation here. for { time.Sleep(1 * time.Second) if Done() { break } reply := RequestTask() fmt.Printf("Ask for task, this reply is %v\n", reply) if !reply.HasTask { continue } if reply.IsMapTask { mapTask := Task{ IsMapTask: reply.IsMapTask, FilePath: reply.MapFile, Index: reply.Index, } Map(mapf, mapTask, reply.NReducer) fmt.Print("Finish the mapping task") } else { reduceTask := Task{ IsMapTask: reply.IsMapTask, Index: reply.Index, } Reduce(reducef, reduceTask, reply.NMapper) fmt.Print("Finish the reducing task") } SubmitTask(reply.Index, reply.IsMapTask) } } // Map is to map key value into a file with mr-%v-%v.json format func Map(mapf func(string, string) []KeyValue, mapTask Task, NReducer int) { encs := make([]*json.Encoder, NReducer) fs := make([]*os.File, NReducer) for i := 0; i < NReducer; i++ { oname := fmt.Sprintf("mr-%v-%v.json", mapTask.Index, i) f, err := os.Create(oname) if err != nil { log.Fatalf("Cannot open file %v", oname) } enc := json.NewEncoder(f) fs[i] = f encs[i] = enc } file, err := os.Open(mapTask.FilePath) defer file.Close() if err != nil { log.Fatalf("cannot open %v", mapTask.FilePath) } content, err := ioutil.ReadAll(file) if err != nil { log.Fatalf("cannot read %v", mapTask.FilePath) } kva := mapf(mapTask.FilePath, string(content)) for _, kv := range kva { id := ihash(kv.Key) % NReducer enc := encs[id] err := enc.Encode(&kv) if err != nil { log.Fatalf("Cannot encode Key-Value pair %v", kv) } } for i := 0; i < NReducer; i++ { fs[i].Close() } } // Reduce function is to sort the key in files and reduce func Reduce(reducef func(string, []string) string, reduceTask Task, NMap int) { kva := make([]KeyValue, 0) for i := 0; i < NMap; i++ { oname := fmt.Sprintf("mr-%v-%v.json", i, reduceTask.Index) f, err := os.Open(oname) defer f.Close() if err != nil { log.Fatalf("cannot open %v", oname) } dec := json.NewDecoder(f) for { var kv KeyValue if err := dec.Decode(&kv); err != nil { break } kva = append(kva, kv) } } sort.Sort(ByKey(kva)) oname := fmt.Sprintf("mr-out-%v", reduceTask.Index) ofile, _ := os.Create(oname) i := 0 for i < len(kva) { j := i + 1 for j < len(kva) && kva[j].Key == kva[i].Key { j++ } values := []string{} for k := i; k < j; k++ { values = append(values, kva[k].Value) } output := reducef(kva[i].Key, values) // this is the correct format for each line of Reduce output. fmt.Fprintf(ofile, "%v %v\n", kva[i].Key, output) i = j } ofile.Close() } // // example function to show how to make an RPC call to the master. // // the RPC argument and reply types are defined in rpc.go. // func RequestTask() RequestTaskReply { args := RequestTaskArgs{} reply := RequestTaskReply{} call("Master.RequestTask", &args, &reply) return reply } // func SubmitTask(index int, isMap bool) { args := SubmitTaskArgs{} reply := SubmitTaskReply{} args.IsMapTask = isMap args.Index = index call("Master.SubmitTask", &args, &reply) // no reply need } // func Done() bool { args := DoneArgs{} reply := DoneReply{} call("Master.DoneQuery", &args, &reply) return reply.IsDone } // // send an RPC request to the master, wait for the response. // usually returns true. // returns false if something goes wrong. // func call(rpcname string, args interface{}, reply interface{}) bool { // c, err := rpc.DialHTTP("tcp", "127.0.0.1"+":1234") sockname := masterSock() c, err := rpc.DialHTTP("unix", sockname) if err != nil { log.Fatal("dialing:", err) } defer c.Close() err = c.Call(rpcname, args, reply) if err == nil { return true } fmt.Println(err) return false }
package main import ( "bufio" "fmt" "math/big" "os" "strconv" ) func main() { scan := func() func() int { scan := bufio.NewScanner(os.Stdin) scan.Split(bufio.ScanWords) return func() int { scan.Scan() i, _ := strconv.Atoi(scan.Text()) return i } }() a := big.NewInt(int64(scan())) b := big.NewInt(int64(scan())) n := scan() for ; n >= 3; n-- { c := big.NewInt(0) a.Add(c.Mul(b, b), a) a, b = b, a } fmt.Println(b) }
package main // 文字列からint, floatへは直接変換できないのでstrconvパッケージを使う必要がある import "fmt" import "strconv" func main() { var s string = "14" i, err := strconv.Atoi(s) if err != nil { fmt.Println("err") } fmt.Printf("%T %v", i, i) }
package service import ( "bufio" "bytes" "errors" "os" "os/exec" "path/filepath" "strings" "k8s.io/utils/mount" "github.com/container-storage-interface/spec/lib/go/csi" "github.com/ovirt/csi-driver/internal/ovirt" ovirtsdk "github.com/ovirt/go-ovirt" "golang.org/x/net/context" "k8s.io/klog" ) type NodeService struct { nodeId string ovirtClient *ovirt.Client } var NodeCaps = []csi.NodeServiceCapability_RPC_Type{ csi.NodeServiceCapability_RPC_STAGE_UNSTAGE_VOLUME, } func baseDevicePathByInterface(diskInterface ovirtsdk.DiskInterface) (string, error) { switch diskInterface { case ovirtsdk.DISKINTERFACE_VIRTIO: return "/dev/disk/by-id/virtio-", nil case ovirtsdk.DISKINTERFACE_VIRTIO_SCSI: return "/dev/disk/by-id/scsi-0QEMU_QEMU_HARDDISK_", nil } return "", errors.New("device type is unsupported") } func (n *NodeService) NodeStageVolume(_ context.Context, req *csi.NodeStageVolumeRequest) (*csi.NodeStageVolumeResponse, error) { klog.Infof("Staging volume %s with %+v", req.VolumeId, req) conn, err := n.ovirtClient.GetConnection() if err != nil { klog.Errorf("Failed to get ovirt client connection") return nil, err } device, err := getDeviceByAttachmentId(req.VolumeId, n.nodeId, conn) if err != nil { klog.Errorf("Failed to fetch device by attachment-id for volume %s on node %s", req.VolumeId, n.nodeId) return nil, err } // is there a filesystem on this device? filesystem, err := getDeviceInfo(device) if err != nil { klog.Errorf("Failed to fetch device info for volume %s on node %s", req.VolumeId, n.nodeId) return nil, err } if filesystem != "" { klog.Infof("Detected fs %s, returning", filesystem) return &csi.NodeStageVolumeResponse{}, nil } fsType := req.VolumeCapability.GetMount().FsType // no filesystem - create it klog.Infof("Creating FS %s on device %s", fsType, device) err = makeFS(device, fsType) if err != nil { klog.Errorf("Could not create filesystem %s on %s", fsType, device) return nil, err } return &csi.NodeStageVolumeResponse{}, nil } func (n *NodeService) NodeUnstageVolume(ctx context.Context, req *csi.NodeUnstageVolumeRequest) (*csi.NodeUnstageVolumeResponse, error) { return &csi.NodeUnstageVolumeResponse{}, nil } func (n *NodeService) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) { conn, err := n.ovirtClient.GetConnection() if err != nil { klog.Errorf("Failed to get ovirt client connection") return nil, err } device, err := getDeviceByAttachmentId(req.VolumeId, n.nodeId, conn) if err != nil { klog.Errorf("Failed to fetch device by attachment-id for volume %s on node %s", req.VolumeId, n.nodeId) return nil, err } targetPath := req.GetTargetPath() err = os.MkdirAll(targetPath, 0750) if err != nil { return nil, errors.New(err.Error()) } fsType := req.VolumeCapability.GetMount().FsType klog.Infof("Mounting devicePath %s, on targetPath: %s with FS type: %s", device, targetPath, fsType) mounter := mount.New("") err = mounter.Mount(device, targetPath, fsType, []string{}) if err != nil { klog.Errorf("Failed mounting %v", err) return nil, err } return &csi.NodePublishVolumeResponse{}, nil } func (n *NodeService) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) { mounter := mount.New("") klog.Infof("Unmounting %s", req.GetTargetPath()) err := mounter.Unmount(req.GetTargetPath()) if err != nil { klog.Infof("Failed to unmount") return nil, err } return &csi.NodeUnpublishVolumeResponse{}, nil } func (n *NodeService) NodeGetVolumeStats(context.Context, *csi.NodeGetVolumeStatsRequest) (*csi.NodeGetVolumeStatsResponse, error) { panic("implement me") } func (n *NodeService) NodeExpandVolume(context.Context, *csi.NodeExpandVolumeRequest) (*csi.NodeExpandVolumeResponse, error) { panic("implement me") } func (n *NodeService) NodeGetInfo(context.Context, *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) { return &csi.NodeGetInfoResponse{NodeId: n.nodeId}, nil } func (n *NodeService) NodeGetCapabilities(context.Context, *csi.NodeGetCapabilitiesRequest) (*csi.NodeGetCapabilitiesResponse, error) { caps := make([]*csi.NodeServiceCapability, 0, len(NodeCaps)) for _, c := range NodeCaps { caps = append( caps, &csi.NodeServiceCapability{ Type: &csi.NodeServiceCapability_Rpc{ Rpc: &csi.NodeServiceCapability_RPC{ Type: c, }, }, }, ) } return &csi.NodeGetCapabilitiesResponse{Capabilities: caps}, nil } func getDeviceByAttachmentId(volumeID, nodeID string, conn *ovirtsdk.Connection) (string, error) { attachment, err := diskAttachmentByVmAndDisk(conn, nodeID, volumeID) if err != nil { return "", err } klog.Infof("Extracting pvc volume name %s", volumeID) disk, _ := conn.FollowLink(attachment.MustDisk()) d, ok := disk.(*ovirtsdk.Disk) if !ok { return "", errors.New("couldn't retrieve disk from attachment") } klog.Infof("Extracted disk ID from PVC %s", d.MustId()) baseDevicePath, err := baseDevicePathByInterface(attachment.MustInterface()) if err != nil { return "", err } // verify the device path exists device := baseDevicePath + d.MustId() _, err = os.Stat(device) if err == nil { klog.Infof("Device path %s exists", device) return device, nil } if os.IsNotExist(err) { // try with short disk ID, where the serial ID is only 20 chars long (controlled by udev) shortDevice := baseDevicePath + d.MustId()[:20] _, err = os.Stat(shortDevice) if err == nil { klog.Infof("Device path %s exists", shortDevice) return shortDevice, nil } } klog.Errorf("Device path for disk ID %s does not exists", d.MustId()) return "", errors.New("device was not found") } // getDeviceInfo will return the first Device which is a partition and its filesystem. // if the given Device disk has no partition then an empty zero valued device will return func getDeviceInfo(device string) (string, error) { devicePath, err := filepath.EvalSymlinks(device) if err != nil { klog.Errorf("Unable to evaluate symlink for device %s", device) return "", errors.New(err.Error()) } klog.Info("lsblk -nro FSTYPE ", devicePath) cmd := exec.Command("lsblk", "-nro", "FSTYPE", devicePath) out, err := cmd.Output() exitError, incompleteCmd := err.(*exec.ExitError) if err != nil && incompleteCmd { return "", errors.New(err.Error() + "lsblk failed with " + string(exitError.Stderr)) } reader := bufio.NewReader(bytes.NewReader(out)) line, _, err := reader.ReadLine() if err != nil { klog.Errorf("Error occured while trying to read lsblk output") return "", err } return string(line), nil } func makeFS(device string, fsType string) error { // caution, use -F to force creating the filesystem if it doesn't exit. May not be portable for fs other // than ext family klog.Infof("Mounting device %s, with FS %s", device, fsType) var force string if strings.HasPrefix(fsType, "ext") { force = "-F" } cmd := exec.Command("mkfs", force, "-t", fsType, device) err := cmd.Run() exitError, incompleteCmd := err.(*exec.ExitError) if err != nil && incompleteCmd { return errors.New(err.Error() + " mkfs failed with " + string(exitError.Error())) } return nil } // isMountpoint find out if a given directory is a real mount point func isMountpoint(mountDir string) bool { cmd := exec.Command("findmnt", mountDir) var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() if err != nil { return false } return true }
package config import ( "bufio" "fmt" "io" "os" "strings" ) func Parse(filename string) (*Parser, error) { p := NewParser(filename) err := p.Parse() return p, err } func NewParser(filename string) *Parser { p := &Parser{ filename: filename, Config: NewConfig(), } return p } type Parser struct { filename string Config *Config } type state struct { currentSection string parsefunc func(line Line, state *state) error currentBackend *Backend currentServer *Server currentFrontend *Frontend } func (me *Parser) Parse() error { log.Tracef("parsing %s", me.filename) f, err := os.Open(me.filename) if err != nil { return err } defer f.Close() bf := bufio.NewReader(f) state := &state{} for { line, err := bf.ReadBytes('\n') if err != nil { if err == io.EOF { break } log.Warnf("read bytes: %s", err) break } sline := strings.Trim(string(line), "\n \t") if len(sline) == 0 { continue } if strings.HasPrefix(sline, "#") { continue } pline, err := me.parseLine(sline) if err != nil { log.Warnf("parseLine %q: %s", sline, err) break } // log.Tracef("%#v", pline) if pline.Command() == "global" { state.currentSection = "global" state.parsefunc = me.globalSection continue } else if pline.Command() == "defaults" { state.currentSection = "defaults" state.parsefunc = me.defaultSection continue } else if pline.Command() == "frontend" { state.currentSection = "frontend" state.parsefunc = me.frontendSection state.currentFrontend = NewFrontend() state.currentFrontend.Name = pline.Arg(1) log.Tracef("new frontend %+v", state.currentFrontend) me.Config.Frontend = append(me.Config.Frontend, state.currentFrontend) continue } else if pline.Command() == "backend" { state.currentSection = "backend" state.parsefunc = me.backendSection state.currentBackend = NewBackend() state.currentBackend.Name = pline.Arg(1) log.Tracef("new backend %+v", state.currentBackend) me.Config.Backend = append(me.Config.Backend, state.currentBackend) continue } if state.parsefunc != nil { err = state.parsefunc(pline, state) if err != nil { log.Warnf("parseLine %q: %s", sline, err) break } } } return nil } var ( space = ' ' tab = '\t' singleQuote = '\'' doubleQuote = '"' ) func (me *Parser) parseLine(line string) (Line, error) { ret := make([]string, 0) token := "" for i := 0; i < len(line); i++ { r := rune(line[i]) switch r { case space, tab: if len(token) > 0 { ret = append(ret, token) } token = "" case singleQuote: // keep consuming until next quote (ending) endFound := false for j := i + 1; j < len(line); j++ { if rune(line[j]) == singleQuote { endFound = true break } } if endFound == false { return ret, fmt.Errorf("no end quote found") } default: token += string(line[i]) } } if len(token) > 0 { ret = append(ret, token) } return Line(ret), nil } // represents a tokenized configuration line type Line []string // returns the command name func (me Line) Command() string { return me[0] } func (me Line) Len() int { return len(me) } func (me Line) Arg(i int) string { l := len(me) if i > l-1 { return "" } return me[i] }
package main import ( "encoding/json" "html/template" "io/ioutil" "log" "net/http" "regexp" "strings" "github.com/go-redis/redis" ) var templates = template.Must(template.ParseFiles("templates/edit.html", "templates/view.html", "templates/index.html")) var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$") type Page struct { Title string Body []byte } type IndexPage struct { Title string Titles []string } type redisStore struct { client *redis.Client } func NewRedisStore() Store { client := redis.NewClient(&redis.Options{ Addr: "192.168.1.28:6379", Password: "", // no password set DB: 0, // use default DB }) _, err := client.Ping().Result() if err != nil { log.Fatalf("Failed to ping Redis: %v", err) } return &redisStore{ client: client, } } func (r redisStore) Set(id string, session Session) error { bs, err := json.Marshal(session) if err != nil { return errors.Wrap(err, "failed to save session to redis") } if err := r.client.Set(id, bs, 0).Err(); err != nil { return errors.Wrap(err, "failed to save session to redis") } return nil } func (r redisStore) Get(id string) (Session, error) { var session Session bs, err := r.client.Get(id).Bytes() if err != nil { return session, errors.Wrap(err, "failed to get session from redis") } if err := json.Unmarshal(bs, &session); err != nil { return session, errors.Wrap(err, "failed to unmarshall session data") } return session, nil } func (p *Page) save() error { filename := "pages/" + p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600) } func welcome() (*IndexPage, error) { return &IndexPage{Title: "Welcome to BSG"}, nil } func listPages() (*IndexPage, error) { files, err := ioutil.ReadDir("pages/") if err != nil { return nil, err } var cleanFiles []string for _, f := range files { cleanFiles = append(cleanFiles, strings.Split(f.Name(), ".")[0]) } return &IndexPage{Title: "Welcome Mofos", Titles: cleanFiles}, nil } func loadPage(title string) (*Page, error) { filename := "pages/" + title + ".txt" body, err := ioutil.ReadFile(filename) if err != nil { return nil, err } return &Page{Title: title, Body: body}, nil } func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { err := templates.ExecuteTemplate(w, tmpl+".html", p) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func indexHandler(w http.ResponseWriter, r *http.Request) { page, err := welcome() err = templates.ExecuteTemplate(w, "index.html", page) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func viewHandler(w http.ResponseWriter, r *http.Request, title string) { p, err := loadPage(title) if err != nil { http.Redirect(w, r, "/edit/"+title, http.StatusFound) return } renderTemplate(w, "view", p) } func editHandler(w http.ResponseWriter, r *http.Request, title string) { p, err := loadPage(title) if err != nil { p = &Page{Title: title} } renderTemplate(w, "edit", p) } func saveHandler(w http.ResponseWriter, r *http.Request, title string) { body := r.FormValue("body") p := &Page{Title: title, Body: []byte(body)} err := p.save() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/view/"+title, http.StatusFound) } func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { m := validPath.FindStringSubmatch(r.URL.Path) if m == nil { http.NotFound(w, r) return } fn(w, r, m[2]) } } func main() { sessionsStore = sessions.NewRedisStore() http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("images")))) http.HandleFunc("/", indexHandler) http.HandleFunc("/view/", makeHandler(viewHandler)) http.HandleFunc("/edit/", makeHandler(editHandler)) http.HandleFunc("/save/", makeHandler(saveHandler)) log.Fatal(http.ListenAndServe(":8080", nil)) }
//go:build go1.18 // +build go1.18 package toml import ( "bytes" "testing" ) func FuzzDecode(f *testing.F) { buf := make([]byte, 0, 2048) f.Add(` # This is an example TOML document which shows most of its features. # Simple key/value with a string. title = "TOML example \U0001F60A" desc = """ An example TOML document. \ """ # Array with integers and floats in the various allowed formats. integers = [42, 0x42, 0o42, 0b0110] floats = [1.42, 1e-02] # Array with supported datetime formats. times = [ 2021-11-09T15:16:17+01:00, # datetime with timezone. 2021-11-09T15:16:17Z, # UTC datetime. 2021-11-09T15:16:17, # local datetime. 2021-11-09, # local date. 15:16:17, # local time. ] # Durations. duration = ["4m49s", "8m03s", "1231h15m55s"] # Table with inline tables. distros = [ {name = "Arch Linux", packages = "pacman"}, {name = "Void Linux", packages = "xbps"}, {name = "Debian", packages = "apt"}, ] # Create new table; note the "servers" table is created implicitly. [servers.alpha] # You can indent as you please, tabs or spaces. ip = '10.0.0.1' hostname = 'server1' enabled = false [servers.beta] ip = '10.0.0.2' hostname = 'server2' enabled = true # Start a new table array; note that the "characters" table is created implicitly. [[characters.star-trek]] name = "James Kirk" rank = "Captain\u0012 \t" [[characters.star-trek]] name = "Spock" rank = "Science officer" [undecoded] # To show the MetaData.Undecoded() feature. key = "This table intentionally left undecoded" `) f.Fuzz(func(t *testing.T, file string) { var m map[string]interface{} _, err := Decode(file, &m) if err != nil { t.Skip() } NewEncoder(bytes.NewBuffer(buf)).Encode(m) // TODO: should check if the output is equal to the input, too, but some // information is lost when encoding. }) }
package main import ( "github.com/yjagdale/siem-data-producer/app" ) func main() { app.StartApp() }
package charts import ( "github.com/go-echarts/go-echarts/v2/opts" "github.com/go-echarts/go-echarts/v2/render" "github.com/go-echarts/go-echarts/v2/types" ) // WordCloud represents a word cloud chart. type WordCloud struct { BaseConfiguration BaseActions } // Type returns the chart type. func (*WordCloud) Type() string { return types.ChartWordCloud } var wcTextColor = `function () { return 'rgb(' + [ Math.round(Math.random() * 160), Math.round(Math.random() * 160), Math.round(Math.random() * 160)].join(',') + ')'; }` // NewWordCloud creates a new word cloud chart. func NewWordCloud() *WordCloud { c := &WordCloud{} c.initBaseConfiguration() c.Renderer = render.NewChartRender(c, c.Validate) c.JSAssets.Add("echarts-wordcloud.min.js") return c } // AddSeries adds new data sets. func (c *WordCloud) AddSeries(name string, data []opts.WordCloudData, options ...SeriesOpts) *WordCloud { series := SingleSeries{Name: name, Type: types.ChartWordCloud, Data: data} series.ConfigureSeriesOpts(options...) // set default random color for WordCloud chart if series.TextStyle == nil { series.TextStyle = &opts.TextStyle{Normal: &opts.TextStyle{}} } if series.TextStyle.Normal.Color == "" { series.TextStyle.Normal.Color = opts.FuncOpts(wcTextColor) } c.MultiSeries = append(c.MultiSeries, series) return c } // SetGlobalOptions sets options for the WordCloud instance. func (c *WordCloud) SetGlobalOptions(options ...GlobalOpts) *WordCloud { c.BaseConfiguration.setBaseGlobalOptions(options...) return c } // SetDispatchActions sets actions for the WordCloud instance. func (c *WordCloud) SetDispatchActions(actions ...GlobalActions) *WordCloud { c.BaseActions.setBaseGlobalActions(actions...) return c } // Validate validates the given configuration. func (c *WordCloud) Validate() { c.Assets.Validate(c.AssetsHost) }
package main import ( "fmt" "strings" ) type coords struct{ x, y int } func main() { rows := strings.Split(input, "\n") var changes []coords grid := map[coords]rune{} for y, row := range rows { for x, s := range row { grid[coords{x, y}] = s } } for k, v := range grid { if v == 'L' && !canSeeOccupied(k.x, k.y, grid, 1) { changes = append(changes, k) continue } if v == '#' && canSeeOccupied(k.x, k.y, grid, 5) { changes = append(changes, k) } } numChanges := len(changes) loops := 1 for numChanges > 0 { fmt.Printf("loop: %d\n", loops) for _, c := range changes { if grid[coords{c.x, c.y}] == 'L' { grid[coords{c.x, c.y}] = '#' continue } if grid[coords{c.x, c.y}] == '#' { grid[coords{c.x, c.y}] = 'L' } } printGrid(grid, len(rows[0]), len(rows)) changes = []coords{} for k, v := range grid { if v == 'L' && !canSeeOccupied(k.x, k.y, grid, 1) { changes = append(changes, k) continue } if v == '#' && canSeeOccupied(k.x, k.y, grid, 5) { changes = append(changes, k) } } numChanges = len(changes) loops++ } occupied := 0 for _, v := range grid { if v == '#' { occupied++ } } fmt.Println(occupied) } func canSeeOccupied(x int, y int, grid map[coords]rune, threshold int) bool { var count int ops := []func(x, y int) (int, int){ func(x, y int) (int, int) { return x - 1, y - 1 }, // NW func(x, y int) (int, int) { return x, y - 1 }, // N func(x, y int) (int, int) { return x + 1, y - 1 }, // NE func(x, y int) (int, int) { return x - 1, y }, // W func(x, y int) (int, int) { return x + 1, y }, // E func(x, y int) (int, int) { return x - 1, y + 1 }, // SW func(x, y int) (int, int) { return x, y + 1 }, // S func(x, y int) (int, int) { return x + 1, y + 1 }, // SE } for _, op := range ops { ix, iy := op(x,y) for val, ok := grid[coords{ix, iy}]; ok; val, ok = grid[coords{ix, iy}] { if val == '#' { count++ if count >= threshold { return true } break } if val == 'L' { break } ix, iy = op(ix, iy) } } return false } func main_1() { rows := strings.Split(input, "\n") var changes []coords grid := map[coords]rune{} for y, row := range rows { for x, s := range row { grid[coords{x, y}] = s } } for k, v := range grid { if v == 'L' && !isAdjacentOccupied(k.x, k.y, grid, 1) { changes = append(changes, k) continue } if v == '#' && isAdjacentOccupied(k.x, k.y, grid, 4) { changes = append(changes, k) } } numChanges := len(changes) loops := 1 for numChanges > 0 { fmt.Printf("loop: %d\n", loops) for _, c := range changes { if grid[coords{c.x, c.y}] == 'L' { grid[coords{c.x, c.y}] = '#' continue } if grid[coords{c.x, c.y}] == '#' { grid[coords{c.x, c.y}] = 'L' } } printGrid(grid, len(rows[0]), len(rows)) changes = []coords{} for k, v := range grid { if v == 'L' && !isAdjacentOccupied(k.x, k.y, grid, 1) { changes = append(changes, k) continue } if v == '#' && isAdjacentOccupied(k.x, k.y, grid, 4) { changes = append(changes, k) } } numChanges = len(changes) loops++ } occupied := 0 for _, v := range grid { if v == '#' { occupied++ } } fmt.Println(occupied) } func printGrid(grid map[coords]rune, lenX, lenY int) { for y := 0; y < lenY; y++ { for x := 0; x < lenX; x++ { if val, ok := grid[coords{x, y}]; ok { fmt.Printf("%c", val) } } fmt.Println("") } } func isAdjacentOccupied(x int, y int, grid map[coords]rune, threshold int) bool { var count int for _, iy := range []int{y - 1, y, y + 1} { for _, ix := range []int{x - 1, x, x + 1} { if iy == y && ix == x { continue } if val, ok := grid[coords{ix, iy}]; ok { if val == '#' { count++ if count >= threshold { return true } } } } } return false } const sample = `L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL` const input = `LLLLL.LLLLLLLLLLLLLLLLL.LLLLLL.LLLLL.L.LLLLLL.LLLLLL.LLL.LLLLLLLL.LLLLL.L.LLLLLLLLLLLLLLLL.LLLLLLL LLLLL.LLLLLLLLLLL.LLLLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLL.LLL.LLLLLLLLLLLLL.L.LLLLLLLLLL.LLLLLL.LLLLLLL LLLLLLLLLLLLLLL.LLLLLLLLLLLLLL.LLLLL.LLLLL.LLL..LLLLLLLL.LLLLLLLL.LLLLLLL.LLLLLLLLL.LLLLLL.LLLLLLL LLLLLLLL.LLLLLL.LLLLLLLLLLLLLL.LLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLLLL.LLLLL.L.LLLLLLLLLLLLLLLL.LLLLL.L LLLLL.LLLLLLLLL.LLLLLLL.LLLL.L.LLLLL.LLLLLLLLL.LLLLLLLLL.LLLLLLLLLLLLL.LLLLLLLLLLLLL.LLLLLLLLLLLLL L.LLLLLLLLLLLLL.LLLLLLL.LLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LL.LLLL.LLLLLLLLL.LLLLLL.LLLLLLL LLLLL.LLLLLLLLL.LLLLLLL.LL.LLLLLLLLL.LLLLLLLLL.LLLLLLLLL.LLLLLLLL.LLLLLLLLLLLLLL.LLLLLLLLL.LLLLLLL LLLLLLLLLLLLLLLLLLL.LLL.LLLLLL.L.LLL.LLLLLLLLL.LLLLLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLL.LL.LLLL LLLLL.LLLLLLLLL.LLLLLLLLLLL.LL.LLLLL.LLLLLL.LL.LLLLLLLL..LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLL.LLLLLLL LL.LL.LLL.LLLLLLLLLLLLL.LLLL.L.LLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLL.LLLL.L.LLLLLLL ......L....L...L...L.....L........LLL..LL..LL..L.L..LL.L..L.....LL......L.LLL.L..L....LLL.......LL LLLLL.LLLLLLLL.LLLLLLLL.LLLLL..LLLLL.LLL.LLLL..LLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL LLLLL.LLLLLLLLL.LL.LLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLL.LLLLLL.LL..L.L LLLLL.LLLLLLL...LLLLLLLLLLLLLL.LLLLL.LLLLLLLLL.LLLLLLLLL.LLLLLLL.LLLL.LLLLLLLLLLLLL.LLLLLL.LLLLLLL LLLLL.LLLLLLLL..LLLLLLL.LLLLL.LL.LLL.LLLLLLLLL.LLL.LLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLL.LLLLLLL LLLLL.LLLLLLLLL.LLLL.LL.LLLLLLLLLLLL..LLLLLLLL.LLLLLLLLL.LLLLLLLLLLL.LLLL.LL.LLLLLL.LLLLLL.LLLLLLL LLLLL.LLLLLLLLLLLLLLLLL.LLLLLLLLL.LL.LLLLLLLLL.LLLLLLLLL.LLLLLLLL.LLLLLLLLLLLLLLLLL.LLLLLL.LL.LLLL L.LL..LLLLLLLLL.LLLLLLL.L.LLLLLLLLLLLL.LLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLL..LLLLLLLLL.LLLLLLLLLLLLLL .L.......L..LL.....L.L.....L..............L.L.L.LL..LL.L.L..LLL.L..LL.............LLL.L......L.LL. LLLLL.LLLLLLLLL.LLLLLLL.LLLLLLLLLLL.LLLLLLLLLLLLLL.LLLLL.LLLLLLLL.LLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLL LLLLL.LLLLLLLLL.LLLLLLL.LLLLLL.LLLLL.LL.LLLLLL.LLLLLLLLL.LLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL LLLLL.LLLLLLLLL.LLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.L.LLLL.LLLLLLL LLLLL.LLL.LLLLL.LLLLLLL.LLLLLL..LLLLLLLLLLLLLLLLLLLL.LLL.L.LLLLLLLLLLLLLL.LLLLLLLLLL.LLLLL..L.LLLL LLLLL.LLLLLLLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLLLLL.LLLLLLL.LLLLLLLLLL..LLLLLL.LLLLLLLLL.LLLLLLL.LL.LL. LLLLL.LLLLLLLLL.LLLLLLL.LLLLLL.LLLLL.LLLLLLL.L.LL.LLLLL..L..LLL.L.LLLLLLL..LLLLLLLL..LLLLL.LLLLLLL LLLLL.LLL.LLLLLLLLLLLLL.LLLLLL.LLLLL.LLLLLLLLL.LLLLL.LLL.LLLLL.LL.LL.LLLL.LLLLLL.LL.LLLLLL.LLLLLLL LLLLL.LLLLLLLLL.LLLLLLL.LLLLL..LLLLLLLLLLLLL.L.LLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLL.LL.LLLL LLLLL.LLLLLLLLLLLLLLLLLLLLLLLL.L.LLL.LLLLLL.LL.LLLLLLLLL.LLLLLLLL.LLLLLLL.LLLLLLLLL.LLL.LLLLLLLLLL ......L.....L...LL.L.L..L...L....L...LLL...LLLLL..L.....L.....L..L......L...L.L.......L..L.LL...L. LL.LLL.LLLLLLLLLLLLLLLL.LLLLLL.LLLLL.LLLLLLLLLLLLLLLLLLL.LLLLLLLL.LL.LLLL.LLLLLLLLL.LL.LLLLLLLLLLL LLLLL.LLLLLLLLL.LLLLLLL.LLLLLLLLLLL..LLLLLLLLL..LLLLLLLL.LLLL.LLL..LLLLLLLLLLLLLLLL.LLLL.L.LLLLLLL LLLLL.LLLLLLLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLLLLL.LLLLLLLLL.LLLLLLLL..LLLLLL.LLLLLL.LLLLLL.LL.LLLLLLL LLLLL..LL.LLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLL.LLLLLLLL.LLLLLLL.LLLLLLLLLL.LLLL..LLLLLLL .LLL...LL.....L.L..L.LL..LL......LL.L.L........L.L.....LLLL.L.L.......L......LL.....LLLL....L.L.LL LLLLL.LLLLLLLLL.LLLLLLL.LLLLLL.LLLLL.LLLLLLLLL.LLLLLLLLL.LLLLLLLL.LL.LLLL.LLLLLLLLLLLLLLLL.LLLLLLL LLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLL.LLLLLLLLLLLL.LLLL.LLLLLLLLLLLLLL LLLL..LLLLLLLLL.LLLLLLLLLLLLLL.LLLLLLLLLLLLLLL.LLLLLLL.L..LLLLLLL..LLLL.L.LLLLLLLLL.LLLLLL.LLLLLLL LLLLLLLLLLLL.LL.LLLLLLL.LLLL.L.LLLLLLLLLLLL.LL.LLLLLLLLL.LLLLLLLL.LLLLLLL.LLLLLLLLL..LLLLL.LLLLLLL LLLLLLLLLLL.LLL.LLLLLLLL.LLLLL.LLLLL.LLLLLLLLLLLLLLLLLLL.LLLL.LLL.LLLLLLLLLLLLLLL.L.LLLLLLLLLLLLLL .L.L...L...L.....L...LLLLLLL.LL....LL..LLL...L...L.LLL..L.L...L.L.L....L.LL.LLL..L....L..LL..L...L LLLLLLLLLLL.LL..LLLL..L.LLLLLL.LLLLLLLLLLLL.LL.LLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLL....LLLLLLLLLLL LLLLLLLLLLLLLLLLLLLLL.LLLLLLLL.LLLLL.LL.LLLLLL.LLLLLLLLL.LLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL LLLLL.LLLLLLLLL.LLLLL.LLLLLLLL.LLLL..LLL.LLLLLLLLLLLLLLL.LLLLLL.L.LLLL.LL.LLLL.LLLLLLLLLL..LLLLLLL LLLLL..LLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLLLL.LLLLL.LLLLLLLLLLLLLL LLLLL.LLLLLLLLL.LLLL.LLLLLLLLL.LLLLL.LLLLLLLLL.LLLLLLLLL.LLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLL. LLLLL.LLLLLLLLLLLLL.LLL.LLLLLL..LLLL.LLLLLLLLL.LLLLLLLLL.LLLLLLLL.LLLLLL..LLLL.LLLL.LLLLLL.LLLLLLL LLLLL.LLLLLLLLL.LLLLLLL.LLLLLL.LLLLL.LLLLLLLLL.LLLLLLLLL.LLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL LLLLLLLLLLLLLLL.LLLLLLL.LLLLLL.LLL.L.LLLLLLLLL..LLLLL.LL..LLLLLLL.LLLLLLL.LLLLLLLLL.LLLLLL.LLLLLLL L..L.L.LLL.LL.......LL.LL..LL.L...L..LLL........L.LL....LL...LL.L.....LL......L.L.L...L.L.L..L..L. LLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLLLL.LLLL.LLLL.LLLLLLLLLLLLLLLLL..LLLL.LL.LLLLLLLLL.LLLLLL.LLLLLLL LL.LLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLLLLL.LLLLLLLLL.LLLLLLLL.LLLLLLL.LLLL.LLLL.LLLLLL.L.LLLLL LLLLL.LLLLLLL.L.L.L.LLL..LLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLL.LLLLLLLLLLLLLL.LLLLL LL....LLLLLLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLLL.LLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLL L.LLL.LLLLLLLLL.LL.LL.L.LLLLLL.LLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLL..LLLLLL.LLLLLLLLL.LLLLLL.LLLLLLL LLLLLLLLLLLLLLL.LLLLLLLLLLLLLL..LLLL.LLLLLLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLL.LLLLLLL LLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLL..LLLLLLLLLLLLLL.LLLL.LLLLLLLL..LLLLLLLLLLLLLLL..LLLLLL..L.LLLL LLLLL.LLL.LL.LL.L.LLLLLLLLLLLLL.LLLLLLLLLLLLLL.LLLL.LLLLLLLLLLLL..LLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLL ..LL....L.LL...L.......L.L...L.L..LLL....L...L.L..L...L......L...LLL.L.L...L..L.LL...L..L..L.L...L LLLLL.LLLLLL....LLLLLLL.LLLLLL.LLLLLLLLLLL.LLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLLLLL.LLL..LLLLLL.LLLLLLL LLLLL..LLLLLLL.LLLLLLLLLLLLLLL.LLLLLL.LL.LLLLLLLLLL.LLLL..LLLLLLLLLLLLL.L.LLLLLLLLLLLLLLLL.LLLL.LL LLLLLLLLLLLLLLL.LLLLLLL.LLLLLLLLLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLLLLLL.LLLL.L.LLLLLLL LLLLL.LLLLLLLLL.L.LLLLL.LLLLLL.LLLLL.LLLLLLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLLLLLL.LLLLL..LLLLL.LLLLLLL LLLL..LLLLLLLLLLLLLLLLL.LLLLLL.LLLLL.LLL.LLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLL.LLLLLL.LLLLL.L LLLLL.LLLLLLLLLLLLLLLLL.LLLLLL.LLLLLLLLLLLLLLLL.LLLLLLLL.LLLLLLLL.LLL.LLLLLLLLLLLLL.LLLLLLLLLLLL.L LLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLL.LLLL.LLLLLLLLL.LLLLLLLLL.LLLLL..LLLLLLLLL.LLLLLL.LLLLLLL LLLLLLLLLLLLLLLLLLLLLLL.LL.LLL.LLLLL.LLLLLLLLL.LLLL.LLLL.LLLLLLLL.LLLLLLL.LLLLLLLLL.LLLLLL.LLLL.LL LLLLL.LLLLLLLLL.LLLLLLL..LLLLL.LLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLLL.LLLLLLL.LLLLLLLLL.L.LLLL.LLLL.LL .L.....L.LL.......L.L..L.L...LLL.L.LL..LLL..L.L....L........L..L.L...L....L...L.LL..L.....L..LL..L LLLLL.LLLLLLLLL.LLLLLLL.LLLL.LLL.LLLLLLLLLLLLL.LLLLLLLLL.LL.LLLLL.LLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLL LLLLLLLLLLLLLLL.LL.LLLL.LLLLLL.LLLLL.LL.LLLLLL.LLLLLLLLL.LLLLLLLL.LLLLLLLLLLL.LLLLL.LLLLLL.LLLLLLL LLLLL.LLLL..LLL.LLLLLLL.LL.LLLLLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLL..LL.LLL LLLLL.LLLLLLLLLLLLLLLLLLLLLL.L.LLLLLL.L.LLLLLLLLLLL.LLLL.LL.LLLLLLLLLLLLL.LLLLLLLLLLLLLLL..LLLLLLL LLLLL.L.LLLLLL..LLLLL.L.LLLLLL.LLLLLLLLLLLLLLLLLLLLLLLL..LLLLLLLL.LLLLLL..LLLLLLLLLLLLLLLLLLLLLLLL LL.LL.LLLLLLLL.LLLLLLL.LLL.LLL...LLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLL.LLLLLLLLLLLL.LL.L.LLLLLL.LLLLLLL LLLLL.LLLLLLLLL.LLLLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLLLL.LLLLLLLLLLLL.LLLLLLL.LLLLLL.LL.LLLLLL.LL.LLLL LLLLL.LLLLLLLLL.LLLLLLL.LLLLL..LLLLL.LLL.LLLLLLLLL.LLLLL.LLLLLL.L.LLLLLLL.LLLLLL.LL.LLLLL.LLLLLLLL LLLLL.LLL.LLLLL.LLLLLLLLLL.LLL.LLLLL.LLLLLLLLLLLLL.LLLLLLLLLLL..LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL ........LL..LLL.....L.L...LLL...L.........L.L...L..L...LL.L.....L....L....L.....L....L....L.LLL... LLLLL.LLLLL..LLLLLLLLLLLLL.LLL.LLLLL.LLLLLLLLL.LLLLLL.LLLLLLLLLLL.LLLLL.LLLLLLLLLLL.LLL.LL.LLLLLLL LLLLL.LLLLLLLLLLLLLLLLL.LLLLLL.LLLLL.LLLLLLLLL.LLLLLLLLL.LLLLLLLL.LLLLLLL.LLLLLLLLLLLLL.LLLL.LL.LL LL.LL.LLLLLLLL.LLLLL.LLLLLLLL.LLLLLL.LLLLLLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLL..LLLLLLLLLLLLLLLLLLLLLLL LLLLL.LLLLLLLLLLLLLLLLL.LLLLLL.LLLLL.LLLL.LLLLLL.LLLLLLL.LLLLLLLL.LLLLLLL.LLLLLLLLLLLLLLLL.LLLLL.L LLLLL..LLLLLLLL.LLLLLLL.LLLLLLLLL.LL.LLLLLLLLL.LLLLLLLLL.LLLLLLLL.LLLLLLL.LLLLLLLLL.LLLLLL.LLLLLLL LLLLLLLLLLLLLLL.LLLLLL..LLLLLL.LLLLL.LLLLLLLL.LL.LLLLLLL.LLLLL.LL.LLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLL L.LL.....LL......LL.L.LL...LL..........LL.LLL...L..L..LL....L......L.....LL.....LL.L..L.LL.L.L.... LLLLL.LLLLLLLLLL.LLLLLL.LLLLLL.LLLLLLLLLLLLLLL.LLLL.LL.L.LLLLL.LLLLLLLLLL.LLLLLLLLLLLLLL.L.LLLLLLL LLLLLLL.LLLLLLL.LLLLLLL.LLLLLL.LL.LLLLLLLLLLLL.LLLLLLLLL.L.LLLLLL.LLLLLLLLLLLLLLLLL.LLLLLL.LLLLLLL LLLLLLLLLLLLLLL.LL.LLLL.LLLLLL.LL.LL.LLL.LLLLL.LLLLLLLLLLLLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLL.LLLLLLL LLLLL.LLLLLLLLL.LLLLLL..LLL.LL.LLLLL.LLLLLLLLLLLLL.LLLLL.LLLLLLLL.LLLLLLL.LLLLLLLLLLLLLLLL.LLLL.L. LLLLL.LLLLLLLLL.LLLLLLL.LLLLL.LLLLLLLLLLLLLLLL.LLLLLLLLLLLLLLLLLL.LLLLLLL.LLLLLLLLL.LLLLLL.LLLL.LL LLLLL.LLLLLLLLL..LLLLLL.LLLLLL.LLLL.LLLLLL.LLL.LLLLL.LLL.LLLLLLL..LLLLLLLLLLLLL.LLLLLLLLLL.LLLLLLL`
package main import "fmt" var d2 = [][]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} func numIslands(grid [][]byte) int { var m = len(grid) res := 0 for i := 0; i < m; i++ { for j := 0; j < len(grid[0]); j++ { if grid[i][j] == '1' { res++ dfs3(grid, i, j) } } } return res } func dfs3(grid [][]byte, x int, y int) { grid[x][y] = '2' //标记为2代表已经被访问过 for i := 0; i < 4; i++ { newX := x + d2[i][0] newY := y + d2[i][1] if newX >= 0 && newX < len(grid) && newY >= 0 && newY < len(grid[0]) && grid[newX][newY] == '1' { dfs3(grid, newX, newY) } } return } func main(){ grid := [][]byte{{'1','1','0','0','0'},{'1','1','0','0','0'},{'0','0','1','0','0'},{'0','0','0','1','1'}} fmt.Println(numIslands(grid)) }
// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later package controllerrpc import ( "context" "fmt" "github.com/swinslow/peridot-core/internal/controller" pbc "github.com/swinslow/peridot-core/pkg/controller" ) // Start corresponds to the Start endpoint for pkg/controller. func (cs *CServer) Start(ctx context.Context, req *pbc.StartReq) (*pbc.StartResp, error) { err := cs.C.Start() if err == nil { return &pbc.StartResp{Starting: true}, nil } return &pbc.StartResp{ Starting: false, ErrorMsg: err.Error(), }, nil } // GetStatus corresponds to the GetStatus endpoint for pkg/controller. func (cs *CServer) GetStatus(ctx context.Context, req *pbc.GetStatusReq) (*pbc.GetStatusResp, error) { runStatus, healthStatus, outputMsg, errorMsg := cs.C.GetStatus() return &pbc.GetStatusResp{ RunStatus: runStatus, HealthStatus: healthStatus, OutputMsg: outputMsg, ErrorMsg: errorMsg, }, nil } // Stop corresponds to the Stop endpoint for pkg/controller. func (cs *CServer) Stop(ctx context.Context, req *pbc.StopReq) (*pbc.StopResp, error) { cs.C.Stop() return &pbc.StopResp{}, nil } // AddAgent corresponds to the AddAgent endpoint for pkg/controller. func (cs *CServer) AddAgent(ctx context.Context, req *pbc.AddAgentReq) (*pbc.AddAgentResp, error) { err := cs.C.AddAgent(req.Cfg) if err != nil { return &pbc.AddAgentResp{ Success: false, ErrorMsg: err.Error(), }, nil } return &pbc.AddAgentResp{Success: true}, nil } // GetAgent corresponds to the GetAgent endpoint for pkg/controller. func (cs *CServer) GetAgent(ctx context.Context, req *pbc.GetAgentReq) (*pbc.GetAgentResp, error) { cfg, err := cs.C.GetAgent(req.Name) if err != nil { return &pbc.GetAgentResp{ Success: false, ErrorMsg: err.Error(), }, nil } return &pbc.GetAgentResp{ Success: true, Cfg: cfg, }, nil } // GetAllAgents corresponds to the GetAllAgents endpoint for pkg/controller. func (cs *CServer) GetAllAgents(ctx context.Context, req *pbc.GetAllAgentsReq) (*pbc.GetAllAgentsResp, error) { cfgs := cs.C.GetAllAgents() return &pbc.GetAllAgentsResp{Cfgs: cfgs}, nil } func createStepTemplateFromProtoSteps(inSteps []*pbc.StepTemplate) []*controller.StepTemplate { steps := []*controller.StepTemplate{} for _, inStep := range inSteps { newStep := &controller.StepTemplate{} switch x := inStep.S.(type) { case *pbc.StepTemplate_Agent: newStep.T = controller.StepTypeAgent newStep.AgentName = x.Agent.Name case *pbc.StepTemplate_Jobset: newStep.T = controller.StepTypeJobSet newStep.JSTemplateName = x.Jobset.Name case *pbc.StepTemplate_Concurrent: newStep.T = controller.StepTypeConcurrent newStep.ConcurrentStepTemplates = createStepTemplateFromProtoSteps(x.Concurrent.Steps) } steps = append(steps, newStep) } return steps } func createProtoStepsFromStepTemplate(inSteps []*controller.StepTemplate) []*pbc.StepTemplate { steps := []*pbc.StepTemplate{} for _, inStep := range inSteps { newStep := &pbc.StepTemplate{} switch inStep.T { case controller.StepTypeAgent: newStep.S = &pbc.StepTemplate_Agent{Agent: &pbc.StepAgentTemplate{Name: inStep.AgentName}} case controller.StepTypeJobSet: newStep.S = &pbc.StepTemplate_Jobset{Jobset: &pbc.StepJobSetTemplate{Name: inStep.JSTemplateName}} case controller.StepTypeConcurrent: subSteps := createProtoStepsFromStepTemplate(inStep.ConcurrentStepTemplates) newStep.S = &pbc.StepTemplate_Concurrent{Concurrent: &pbc.StepConcurrentTemplate{Steps: subSteps}} } steps = append(steps, newStep) } return steps } // AddJobSetTemplate corresponds to the AddJobSetTemplate endpoint for pkg/controller. func (cs *CServer) AddJobSetTemplate(ctx context.Context, req *pbc.AddJobSetTemplateReq) (*pbc.AddJobSetTemplateResp, error) { // build the jobSetTemplate structure to send to the controller name := req.Jst.Name steps := createStepTemplateFromProtoSteps(req.Jst.Steps) err := cs.C.AddJobSetTemplate(name, steps) if err != nil { return &pbc.AddJobSetTemplateResp{ Success: false, ErrorMsg: err.Error(), }, nil } return &pbc.AddJobSetTemplateResp{Success: true}, nil } // GetJobSetTemplate corresponds to the GetJobSetTemplate endpoint for pkg/controller. func (cs *CServer) GetJobSetTemplate(ctx context.Context, req *pbc.GetJobSetTemplateReq) (*pbc.GetJobSetTemplateResp, error) { steps, err := cs.C.GetJobSetTemplate(req.Name) if err != nil { return &pbc.GetJobSetTemplateResp{ Success: false, ErrorMsg: err.Error(), }, nil } jst := &pbc.JobSetTemplate{ Name: req.Name, Steps: createProtoStepsFromStepTemplate(steps), } return &pbc.GetJobSetTemplateResp{ Success: true, Jst: jst, }, nil } // GetAllJobSetTemplates corresponds to the GetAllJobSetTemplates endpoint for pkg/controller. func (cs *CServer) GetAllJobSetTemplates(ctx context.Context, req *pbc.GetAllJobSetTemplatesReq) (*pbc.GetAllJobSetTemplatesResp, error) { templates := cs.C.GetAllJobSetTemplates() protoTemplates := []*pbc.JobSetTemplate{} for name, steps := range templates { jst := &pbc.JobSetTemplate{ Name: name, Steps: createProtoStepsFromStepTemplate(steps), } protoTemplates = append(protoTemplates, jst) } return &pbc.GetAllJobSetTemplatesResp{Jsts: protoTemplates}, nil } // GetJob corresponds to the GetJob endpoint for pkg/controller. func (cs *CServer) GetJob(ctx context.Context, req *pbc.GetJobReq) (*pbc.GetJobResp, error) { job, err := cs.C.GetJob(req.JobID) if err != nil { return &pbc.GetJobResp{ Success: false, ErrorMsg: err.Error(), }, nil } jd := &pbc.JobDetails{ JobID: job.JobID, JobSetID: job.JobSetID, JobSetStepID: job.JobSetStepID, JobSetStepOrder: job.JobSetStepOrder, AgentName: job.AgentName, Cfg: &job.Cfg, St: &job.Status, } return &pbc.GetJobResp{ Success: true, Job: jd, }, nil } // GetAllJobs corresponds to the GetAllJobs endpoint for pkg/controller. func (cs *CServer) GetAllJobs(ctx context.Context, req *pbc.GetAllJobsReq) (*pbc.GetAllJobsResp, error) { jobs := cs.C.GetAllJobs() jds := []*pbc.JobDetails{} for _, job := range jobs { jd := &pbc.JobDetails{ JobID: job.JobID, JobSetID: job.JobSetID, JobSetStepID: job.JobSetStepID, JobSetStepOrder: job.JobSetStepOrder, AgentName: job.AgentName, Cfg: &job.Cfg, St: &job.Status, } jds = append(jds, jd) } return &pbc.GetAllJobsResp{Jobs: jds}, nil } // GetAllJobsForJobSet corresponds to the GetAllJobsForJobSet endpoint for pkg/controller. func (cs *CServer) GetAllJobsForJobSet(ctx context.Context, req *pbc.GetAllJobsForJobSetReq) (*pbc.GetAllJobsForJobSetResp, error) { jobs := cs.C.GetAllJobsForJobSet(req.JobSetID) jds := []*pbc.JobDetails{} for _, job := range jobs { jd := &pbc.JobDetails{ JobID: job.JobID, JobSetID: job.JobSetID, JobSetStepID: job.JobSetStepID, JobSetStepOrder: job.JobSetStepOrder, AgentName: job.AgentName, Cfg: &job.Cfg, St: &job.Status, } jds = append(jds, jd) } return &pbc.GetAllJobsForJobSetResp{Jobs: jds}, nil } func createProtoStepsFromSteps(inSteps []*controller.Step) []*pbc.Step { steps := []*pbc.Step{} for _, inStep := range inSteps { newStep := &pbc.Step{ StepID: inStep.StepID, StepOrder: inStep.StepOrder, RunStatus: inStep.RunStatus, HealthStatus: inStep.HealthStatus, } switch inStep.T { case controller.StepTypeAgent: newStep.S = &pbc.Step_Agent{Agent: &pbc.StepAgent{AgentName: inStep.AgentName, JobID: inStep.AgentJobID}} case controller.StepTypeJobSet: newStep.S = &pbc.Step_Jobset{Jobset: &pbc.StepJobSet{TemplateName: inStep.SubJobSetTemplateName, JobSetID: inStep.SubJobSetID}} case controller.StepTypeConcurrent: subSteps := createProtoStepsFromSteps(inStep.ConcurrentSteps) newStep.S = &pbc.Step_Concurrent{Concurrent: &pbc.StepConcurrent{Steps: subSteps}} } steps = append(steps, newStep) } return steps } // StartJobSet corresponds to the StartJobSet endpoint for pkg/controller. func (cs *CServer) StartJobSet(ctx context.Context, req *pbc.StartJobSetReq) (*pbc.StartJobSetResp, error) { fmt.Printf("In StartJobSet, req is %#v\n", req) for _, cfg := range req.Cfgs { fmt.Printf(" - key: %s\n", cfg.Key) fmt.Printf(" value: %s\n", cfg.Value) } jobSetID, err := cs.C.StartJobSet(req.JstName, req.Cfgs) if err != nil { return &pbc.StartJobSetResp{ Success: false, ErrorMsg: err.Error(), }, nil } return &pbc.StartJobSetResp{ Success: true, JobSetID: jobSetID, }, nil } // GetJobSet corresponds to the GetJobSet endpoint for pkg/controller. func (cs *CServer) GetJobSet(ctx context.Context, req *pbc.GetJobSetReq) (*pbc.GetJobSetResp, error) { js, err := cs.C.GetJobSet(req.JobSetID) if err != nil { return &pbc.GetJobSetResp{ Success: false, ErrorMsg: err.Error(), }, nil } st := &pbc.JobSetStatusReport{ RunStatus: js.RunStatus, HealthStatus: js.HealthStatus, TimeStarted: js.TimeStarted.Unix(), TimeFinished: js.TimeFinished.Unix(), OutputMessages: js.OutputMessages, ErrorMessages: js.ErrorMessages, } steps := createProtoStepsFromSteps(js.Steps) jsd := &pbc.JobSetDetails{ JobSetID: js.JobSetID, TemplateName: js.TemplateName, St: st, Steps: steps, } return &pbc.GetJobSetResp{ Success: true, JobSet: jsd, }, nil } // GetAllJobSets corresponds to the GetAllJobSets endpoint for pkg/controller. func (cs *CServer) GetAllJobSets(ctx context.Context, req *pbc.GetAllJobSetsReq) (*pbc.GetAllJobSetsResp, error) { jss := cs.C.GetAllJobSets() jobSets := []*pbc.JobSetDetails{} for _, js := range jss { st := &pbc.JobSetStatusReport{ RunStatus: js.RunStatus, HealthStatus: js.HealthStatus, TimeStarted: js.TimeStarted.Unix(), TimeFinished: js.TimeFinished.Unix(), OutputMessages: js.OutputMessages, ErrorMessages: js.ErrorMessages, } steps := createProtoStepsFromSteps(js.Steps) jsd := &pbc.JobSetDetails{ JobSetID: js.JobSetID, TemplateName: js.TemplateName, St: st, Steps: steps, } jobSets = append(jobSets, jsd) } return &pbc.GetAllJobSetsResp{JobSets: jobSets}, nil }
package main import "fmt" func main() { fmt.Println("Good morning!") }
// Package rbtree 实现了红黑树 package rbtree type Color int8 type Comparation = func(a, b interface{}) int const ( RED = itoa, BLACK ) type Node struct { data interface{} left, right, parent *Node color Color } func (n *Node) grandparent() *Node { return n.parent.parent } func (n *Node) uncle() { if } type RBTree struct { root *Node len int compare Comparation } // New 创建一个红黑树 func New (compare Comparation) *RBTree { return &RBTree{ compare: compare, } } // Len 返回红黑树元素数量 func (t *RBTree) Len() int { return t.len } func (t *RBTree) Insert(data interface{}) { if t.root == nil { // Case 1: 空树 t.root = &Node{data: data, color: BLACK} t.len++ } else { t.insert(data, &t.root) } } func (t *RBTree) insert(data interface{}, n **Node) *Node{ var nnode *Node node := *n ndata := node.data cmpval := t.compare(data, ndata) if cmpval > 0 { // 插入右分支 if node.right == nil { nnode = &Node{ data: data, color: RED, parent: node, } node.right = nnode t.len++ return nnode } else { nnode = t.insert(data, &node.right) } // TODO: 检查 } else if cmpval < 0 { // 插入左分支 if node.left == nil { nnode = &Node{ data: data, color: RED, parent: node, } node.left = nnode t.len++ return nnode } else { nnode = t.insert(data, &node.left) } // TODO: 检查 } else { // 相等 // 不作处理 node.data = data return nil } } func (t *RBTree) adjust(node *Node) { if node.parent.color == BLACK { // case 2 return } }
// Copyright (c) 2013 The Gocov Authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. package main import ( "flag" "fmt" "testing" ) const testdata = "github.com/SunRunAway/gocov/gocov/testdata" func cloneFlagSet(f *flag.FlagSet) *flag.FlagSet { clone := flag.NewFlagSet("", flag.ContinueOnError) f.VisitAll(func(f *flag.Flag) { clone.Var(f.Value, f.Name, f.Usage) }) return clone } func TestTestFlags(t *testing.T) { flags := cloneFlagSet(testFlags) extraArgs := []string{"pkg1", "pkg2", "-extra"} err := flags.Parse(append([]string{"-tags=test"}, extraArgs...)) if err != nil { t.Fatal(err) } tagsFlag := flags.Lookup("tags") if tagsFlag == nil { t.Fatalf("'tags' flag not found in FlagSet") } if value := tagsFlag.Value.String(); value != "test" { t.Fatalf("Expected -tags=%q, found %q", "test", value) } nargs := flags.NArg() if nargs != len(extraArgs) { t.Errorf("Expected %d args, found %d", len(extraArgs), nargs) } for i := 0; i < nargs; i++ { exp := extraArgs[i] act := flags.Arg(i) if act != exp { t.Errorf("Unexpected arg #d: expected %q, found %q", i+1, exp, act) } } } func checkSlices(t *testing.T, prefix, typ string, expected, actual []string) { nexp, nact := len(expected), len(actual) if nexp != nact { t.Errorf("%s: expected %d %ss (%v), received %d (%v)", prefix, nexp, typ, expected, nact, actual) } else { for j, exp := range expected { act := actual[j] if exp != act { t.Errorf("%s: Expected %s %q, received %q", prefix, typ, exp, act) } } } } func TestPackagesAndTestargs(t *testing.T) { type testcase struct { args []string packages []string testargs []string } testcases := []testcase{ { []string{"-tags=tag1", testdata + "/tags"}, []string{testdata + "/tags"}, nil, }, { []string{"-tags", "tag1", testdata + "/tags"}, []string{testdata + "/tags"}, nil, }, { []string{testdata +"/tags", "-tags", "tag1"}, []string{testdata + "/tags"}, []string{"-tags", "tag1"}, }, { []string{testdata +"/tags", "-tags=tag1"}, []string{testdata + "/tags"}, []string{"-tags=tag1"}, }, } for i, tc := range testcases { *testTagsFlag = "" prefix := fmt.Sprintf("[Test #%d]", i+1) if err := testFlags.Parse(tc.args); err != nil { t.Errorf("%s: Failed to parse args %v: %v", prefix, tc.args, err) continue } packages, testargs, err := packagesAndTestargs() if err != nil { t.Errorf("%s: packagesAndTestargs failed: %v", prefix, err) continue } checkSlices(t, prefix, "package", packages, tc.packages) checkSlices(t, prefix, "testarg", testargs, tc.testargs) } }
package virgo // IService 服务接口 type IService interface { OnInit(*Procedure) OnRelease() } // Launch 启动服务 func Launch(s IService) { p := NewProcedure(s) p.Start() p.waitQuit() }
package database import "context" // ReadOnlyDB used to get database object from any database implementation. // For consistency reason both TransactionDB and ReadOnlyDB will seek database object under the context params type ReadOnlyDB interface { GetDatabase(ctx context.Context) (context.Context, error) }
package models type ArrayLine struct { Cells []string }
package auth import "context" type Interactor interface { Signup(context.Context, *User) (*Session, error) }
package main import ( "math" ) func divide(dividend int, divisor int) int { if dividend == math.MinInt32 && divisor == -1 { return math.MaxInt32 } flag := true if dividend^divisor < 0 { flag = false } if divisor > 0 { divisor = -divisor } if dividend > 0 { dividend = -dividend } res := 0 multiple := 1 tmp_divisor := divisor for dividend <= tmp_divisor { if dividend <= divisor { //每次除数成倍数递增,减少减法运算次数 res += multiple dividend -= divisor divisor += divisor multiple += multiple } else { //超出时,就是是除数大于被除数重新计算 divisor = tmp_divisor multiple = 1 } } if flag { return res } return -res }
package rtrclient import ( "bytes" "net" "time" "github.com/cpusoft/goutil/belogs" "github.com/cpusoft/goutil/convert" "github.com/cpusoft/goutil/jsonutil" rtrserver "rpstir2-rtrserver" ) type RtrTcpClientProcessFunc struct { } func (rq *RtrTcpClientProcessFunc) ActiveSend(conn *net.TCPConn, tcpClientProcessChan string) (err error) { start := time.Now() var rtrPduModel rtrserver.RtrPduModel if "resetquery" == tcpClientProcessChan { rtrPduModel = rtrserver.NewRtrResetQueryModel(rtrserver.PDU_PROTOCOL_VERSION_2) } else if "serialquery" == tcpClientProcessChan { rtrPduModel = rtrserver.NewRtrSerialQueryModel(rtrserver.PDU_PROTOCOL_VERSION_2, rtrClientSerialQueryModel.SessionId, rtrClientSerialQueryModel.SerialNumber) } sendBytes := rtrPduModel.Bytes() belogs.Debug("ActiveSend():client:", convert.Bytes2String(sendBytes)) _, err = conn.Write(sendBytes) if err != nil { belogs.Debug("ActiveSend():client: conn.Write() fail, ", convert.Bytes2String(sendBytes), err) return err } belogs.Info("ActiveSend(): client send:", jsonutil.MarshalJson(rtrPduModel), " time(s):", time.Since(start)) return nil } func (rq *RtrTcpClientProcessFunc) OnReceive(conn *net.TCPConn, receiveData []byte) (err error) { go func() { start := time.Now() belogs.Debug("OnReceive():client,bytes\n" + convert.PrintBytes(receiveData, 8)) buf := bytes.NewReader(receiveData) rtrPduModel, err := rtrserver.ParseToRtrPduModel(buf) if err != nil { return } belogs.Info("OnReceive(): client receive bytes:\n"+convert.PrintBytes(receiveData, 8)+"\n parseTo:", jsonutil.MarshalJson(rtrPduModel), " time(s):", time.Since(start)) }() return nil }
package api import ( "github.com/gin-gonic/gin" db "github.com/minhphong306/mindX/db/sqlc" "net/http" ) type createLocationHistoryRequest struct { UserId int64 `json:"user_id" binding:"required"` Type int32 `json:"type" binding:"required"` LocationId int32 `json:"location_id"` ManualInput string `json:"manual_input" binding:"required"` } func (server *Server) createLocationHistory(ctx *gin.Context) { var req createLocationHistoryRequest if err := ctx.ShouldBindJSON(&req); err != nil { ctx.JSON(http.StatusBadRequest, errorResponse(err)) return } arg := db.CreateLocationHistoryParams{ UserID: req.UserId, Type: req.Type, LocationID: req.LocationId, ManualInput: req.ManualInput, } history, err := server.store.CreateLocationHistory(ctx, arg) if err != nil { ctx.JSON(http.StatusInternalServerError, errorResponse(err)) return } ctx.JSON(http.StatusOK, history) }
package surisoc // Error is a custom error struct for the SuriSock package type Error struct { Message string } // Error gives back the error message func (e *Error) Error() string { return e.Message }
package status import ( "log" "testing" "time" "github.com/golang/mock/gomock" ) func init() { log.SetFlags(log.LstdFlags | log.Lshortfile) } func Test2FriendsJoining(t *testing.T) { incomingCh := make(chan workIn) startConsumer(incomingCh) defer close(incomingCh) ctrl := gomock.NewController(t) ClientA := NewMockResponder(ctrl) ClientB := NewMockResponder(ctrl) //Expectation ClientA.EXPECT().IsStateless().Return(false).AnyTimes() ClientB.EXPECT().IsStateless().Return(false).AnyTimes() ClientA.EXPECT().Reply(&friendResponse{ UserID: 2, Online: false, }).Return(nil).Times(1) ClientA.EXPECT().Reply(&friendResponse{ UserID: 2, Online: true, }).Return(nil).Times(1) ClientB.EXPECT().Reply(&friendResponse{ UserID: 1, Online: true, }).Return(nil).Times(1) incomingCh <- workIn{ action: Joining, payload: &userContext{ Responder: ClientA, ID: 1, Friends: []int{2}, }, } incomingCh <- workIn{ action: Joining, payload: &userContext{ Responder: ClientB, ID: 2, Friends: []int{1}, }, } //wait for goroutines to finish - could operate a waitgroup to aid this. time.Sleep(20 * time.Millisecond) ctrl.Finish() } func Test2FriendsJoiningAndLeaving(t *testing.T) { incomingCh := make(chan workIn) startConsumer(incomingCh) defer close(incomingCh) ctrl := gomock.NewController(t) ClientA := NewMockResponder(ctrl) ClientB := NewMockResponder(ctrl) //Expectation ClientA.EXPECT().IsStateless().Return(false).AnyTimes() ClientB.EXPECT().IsStateless().Return(false).AnyTimes() ClientA.EXPECT().Reply(&friendResponse{ UserID: 2, Online: false, }).Return(nil).Times(1) ClientA.EXPECT().Reply(&friendResponse{ UserID: 2, Online: true, }).Return(nil).Times(1) ClientB.EXPECT().Reply(&friendResponse{ UserID: 1, Online: true, }).Return(nil).Times(1) ClientB.EXPECT().Reply(&friendResponse{ UserID: 1, Online: false, }).Return(nil).Times(1) incomingCh <- workIn{ action: Joining, payload: &userContext{ Responder: ClientA, ID: 1, Friends: []int{2}, }, } incomingCh <- workIn{ action: Joining, payload: &userContext{ Responder: ClientB, ID: 2, Friends: []int{1}, }, } incomingCh <- workIn{ action: Leaving, payload: &userContext{ Responder: ClientA, ID: 1, Friends: []int{2}, }, } incomingCh <- workIn{ action: Leaving, payload: &userContext{ Responder: ClientB, ID: 2, Friends: []int{1}, }, } //wait for goroutines to finish - could operate a waitgroup to aid this. time.Sleep(20 * time.Millisecond) ctrl.Finish() } func TestStatelessTimeout(t *testing.T) { incomingCh := make(chan workIn) startConsumer(incomingCh) defer close(incomingCh) ctrl := gomock.NewController(t) ClientA := NewMockResponder(ctrl) ClientB := NewMockResponder(ctrl) //monkey patching ttl := OnlineTTL OnlineTTL = time.Duration(time.Millisecond * 5) defer func() { OnlineTTL = ttl }() //Expectation ClientA.EXPECT().IsStateless().Return(true).AnyTimes() ClientB.EXPECT().IsStateless().Return(false).AnyTimes() ClientA.EXPECT().Reply(&friendResponse{ UserID: 2, Online: false, }).Return(nil).Times(1) ClientA.EXPECT().Reply(&friendResponse{ UserID: 2, Online: true, }).Return(nil).Times(1) ClientB.EXPECT().Reply(&friendResponse{ UserID: 1, Online: true, }).Return(nil).Times(1) //CLIENT A should timeout ClientB.EXPECT().Reply(&friendResponse{ UserID: 1, Online: false, }).Return(nil).Times(1) incomingCh <- workIn{ action: Joining, payload: &userContext{ Responder: ClientA, ID: 1, Friends: []int{2}, }, } incomingCh <- workIn{ action: Joining, payload: &userContext{ Responder: ClientB, ID: 2, Friends: []int{1}, }, } //ClientA should time out time.Sleep(50 * time.Millisecond) ctrl.Finish() }
package sol func maxSubArray(nums []int) int { if len(nums) == 0 { return 0 } if len(nums) == 1 { return nums[0] } i := 0 maxNum := nums[0] partialTol := 0 for i < len(nums) { partialTol += nums[i] if partialTol > maxNum { maxNum = partialTol } if partialTol < 0 { partialTol = 0 } i++ } return maxNum }
package auth import ( "context" "net/http" "strings" ) type ExternalUser struct { AuthType string `json:"authType"` ExternalId string `json:"externalId"` Email NullString `json:"email"` Login NullString `json:"login"` Name NullString `json:"name"` } type NullString struct { Valid bool String string } type OAuth2 interface { GetUser(ctx context.Context, state string, code string) (*ExternalUser, error) HandleLogin(w http.ResponseWriter, r *http.Request) HandleCallback(w http.ResponseWriter, r *http.Request) } func (t *NullString) UnmarshalJSON(data []byte) error { t.String = string(data) t.String = strings.Replace(t.String, "\"", "", -1) if t.String != "" { t.Valid = true } return nil }
package toolkit import ( "strings" "testing" ) func TestConvertToSmallCamelCase(t *testing.T) { var ans = "helloWorldZhongGuo" if actual := ConvertToSmallCamelCase("hello world zhong guo"); actual != ans { t.Errorf("got %s, expected %s\n", actual, ans) } } func TestConvertToBigCamelCase(t *testing.T) { var ans = "HelloWorldZhongGuo" if actual := ConvertToBigCamelCase("hello world zhong guo"); actual != ans { t.Errorf("got %s, expected %s\n", actual, ans) } } func TestUnderline2SmallCamelCase(t *testing.T) { var ans = "helloWorldZhongGuo" if actual := Underline2SmallCamelCase("hello world zhong guo"); actual != ans { t.Errorf("got %s, expected %s\n", actual, ans) } } func TestUnderline2BigCamelCase(t *testing.T) { var ans = "HelloWorldZhongGuo" if actual := Underline2BigCamelCase("hello world zhong guo"); actual != ans { t.Errorf("got %s, expected %s\n", actual, ans) } } func TestAllowCapitalGenerateSlice(t *testing.T) { var ans1 = strings.Join([]string{"hello", "world", "zhong", "guo"}, "-") if actual := AllowCapitalGenerateSlice("helloWorldZhongGuo"); strings.Join(actual, "-") != ans1 { t.Errorf("got %s, expected %s\n", actual, ans1) } if actual := AllowCapitalGenerateSlice("HelloWorldZhongGuo"); strings.Join(actual, "-") != ans1 { t.Errorf("got %s, expected %s\n", actual, ans1) } } func TestCamelCase2Underline(t *testing.T) { ans := "hello_world_user_info" if actual := CamelCase2Underline("HelloWorldUserInfo"); actual != ans { t.Errorf("got %s, expected %s\n", actual, ans) } } func TestSmallCamelCase2BigCamelCase(t *testing.T) { ans := "HelloWorldUserInfo" if actual := SmallCamelCase2BigCamelCase("helloWorldUserInfo"); actual != ans { t.Errorf("got %s, expected %s\n", actual, ans) } } func TestBigCamelCase2SmallCamelCase(t *testing.T) { ans := "helloWorldUserInfo" if actual := BigCamelCase2SmallCamelCase("HelloWorldUserInfo"); actual != ans { t.Errorf("got %s, expected %s\n", actual, ans) } }
package repository import ( "arep/model" "context" ) type StoreRepository interface { UpdateStore(context.Context, string, bool) error GetStores(context.Context, []int64) (*[]model.Store, error) }
/* * @lc app=leetcode.cn id=32 lang=golang * * [32] 最长有效括号 */ // @lc code=start package main import "fmt" func longestValidParentheses(s string) int { // stack := []byte{} // maxCount := 0 // count := 0 // for i := 0 ; i < len(s) ; i++ { // if s[i] == '(' { // stack = append(stack , s[i]) // // fmt.Printf("first i is %d, s[i] is %s, stack are %s, maxCount is %d, count is %d\n",i, string(s[i]), string(stack), maxCount, count) // } else if len(stack) == 0 && s[i] == ')' { // maxCount = max(maxCount, count) // count = 0 // // fmt.Printf("second, i is %d, s[i] is %s, stack are %s, maxCount is %d, count is %d\n",i, string(s[i]), string(stack), maxCount, count) // } else if s[i] == ')' { // prev := stack[len(stack)-1] // if prev == '(' { // stack = stack[:len(stack)-1] // } // if len(stack) == 0 { // count +=2 // } else { // } // // fmt.Printf("3rd, i is %d, s[i] is %s, stack are %s, maxCount is %d, count is %d\n",i, string(s[i]), string(stack), maxCount, count) // } // } // return max(maxCount,count) maxAns := 0 stack := []int{} stack = append(stack, -1) for i := 0; i < len(s); i++ { if s[i] == '(' { stack = append(stack, i) } else { stack = stack[:len(stack)-1] if len(stack) == 0 { stack = append(stack, i) } else { maxAns = max(maxAns, i - stack[len(stack)-1]) } } } return maxAns } func max(a, b int) int { if a > b { return a } else { return b } } // @lc code=end func main (){ a := ")()())" fmt.Printf("%s, %d\n", a, longestValidParentheses(a)) a = "()(())(()" fmt.Printf("%s, %d\n", a, longestValidParentheses(a)) }
package main func subs(w win) [][]byte { if w.size()%2 == 0 { return evenSubs(w) } return oddSubs(w) } func evenSubs(w win) [][]byte { // L:=0: center between leftmost and second left char if w.size() == 2 { return [][]byte{ w.val(), } } return nil } func oddSubs(w win) [][]byte { if w.even { return nil } // L=0: center at leftmost char if w.size() <= 2 { return [][]byte{ []byte{ w.chars[w.L()], }, } } subsubs := make([][]byte, 0) for _, ww := range w.subWindows() { subsubs = append(subsubs, subs(ww)...) } // tmp := win{ // chars: w.chars, // even: false, // } // // slide center point from left to right: // for i := w.L(); i < w.R(); i++ { // subsubs = append(subsubs, subs(tmp)...) // // collapse window 1 char per side: // tmp.l = w.l + 1 // tmp.r = w.r + 1 // // spaceLeft := i // // spaceRight = // } return subsubs }
package controller import ( "github.com/labstack/echo" "net/http" ) func MainPage(e echo.Context) error{ return e.Redirect(http.StatusTemporaryRedirect,"http://52.78.172.184:8081/index.html") }
package coredb import ( "testing" "time" "github.com/graphql-go/graphql" "github.com/zhs007/ankadb" "github.com/zhs007/jarviscore/coredb/proto" "github.com/zhs007/jarviscore/crypto" ) func TestBaseFunc(t *testing.T) { //------------------------------------------------------------------------ // initial ankaDB cfg := ankadb.NewConfig() cfg.PathDBRoot = "../test/coredbbasefunc" cfg.ListDB = append(cfg.ListDB, ankadb.DBConfig{ Name: CoreDBName, Engine: "leveldb", PathDB: CoreDBName, }) dblogic, err := ankadb.NewBaseDBLogic(graphql.SchemaConfig{ Query: typeQuery, Mutation: typeMutation, }) if err != nil { t.Fatalf("TestBaseFunc NewBaseDBLogic %v", err) return } ankaDB, err := ankadb.NewAnkaDB(cfg, dblogic) if ankaDB == nil { t.Fatalf("TestBaseFunc NewAnkaDB %v", err) return } //------------------------------------------------------------------------ // newPrivateData privKey := jarviscrypto.GenerateKey() pd, err := newPrivateData(ankaDB, jarviscrypto.Base58Encode(privKey.ToPrivateBytes()), jarviscrypto.Base58Encode(privKey.ToPublicBytes()), privKey.ToAddress(), time.Now().Unix()) if err != nil { t.Fatalf("TestBaseFunc newPrivateData %v", err) return } if pd.PriKey != nil || pd.PubKey != nil || pd.StrPriKey != "" { t.Fatalf("TestBaseFunc getPrivateKey return PriKey or PubKey or StrPriKey is non-nil") return } if pd.StrPubKey != jarviscrypto.Base58Encode(privKey.ToPublicBytes()) { t.Fatalf("TestBaseFunc newPrivateData return StrPubKey fail! (%v - %v)", pd.StrPubKey, jarviscrypto.Base58Encode(privKey.ToPublicBytes())) return } //------------------------------------------------------------------------ // getPrivateKey pd, err = getPrivateKey(ankaDB) if err != nil { t.Fatalf("TestBaseFunc getPrivateKey %v", err) return } if pd.PriKey != nil || pd.PubKey != nil { t.Fatalf("TestBaseFunc getPrivateKey return PriKey or PubKey is non-nil") return } if pd.StrPubKey != jarviscrypto.Base58Encode(privKey.ToPublicBytes()) { t.Fatalf("TestBaseFunc getPrivateKey return StrPubKey fail! (%v - %v)", pd.StrPubKey, jarviscrypto.Base58Encode(privKey.ToPublicBytes())) return } if pd.StrPriKey != jarviscrypto.Base58Encode(privKey.ToPrivateBytes()) { t.Fatalf("TestBaseFunc getPrivateKey return StrPriKey fail! (%v - %v)", pd.StrPriKey, jarviscrypto.Base58Encode(privKey.ToPublicBytes())) return } //------------------------------------------------------------------------ // getPrivateData pd, err = getPrivateData(ankaDB) if err != nil { t.Fatalf("TestBaseFunc getPrivateData %v", err) return } if pd.PriKey != nil || pd.PubKey != nil || pd.StrPriKey != "" { t.Fatalf("TestBaseFunc getPrivateData return PriKey or PubKey or StrPriKey is non-nil") return } if pd.StrPubKey != jarviscrypto.Base58Encode(privKey.ToPublicBytes()) { t.Fatalf("TestBaseFunc getPrivateData return StrPubKey fail! (%v - %v)", pd.StrPubKey, jarviscrypto.Base58Encode(privKey.ToPublicBytes())) return } //------------------------------------------------------------------------ // updPrivateData pd, err = updPrivateData(ankaDB, int64(100)) if err != nil { t.Fatalf("TestBaseFunc updPrivateData %v", err) return } if pd.PriKey != nil || pd.PubKey != nil || pd.StrPriKey != "" { t.Fatalf("TestBaseFunc updPrivateData return PriKey or PubKey or StrPriKey is non-nil") return } if pd.StrPubKey != jarviscrypto.Base58Encode(privKey.ToPublicBytes()) { t.Fatalf("TestBaseFunc updPrivateData return StrPubKey fail! (%v - %v)", pd.StrPubKey, jarviscrypto.Base58Encode(privKey.ToPublicBytes())) return } //------------------------------------------------------------------------ // updNodeInfo test001 test001PriKey := jarviscrypto.GenerateKey() cni1 := &coredbpb.NodeInfo{ ServAddr: "127.0.0.1", Addr: test001PriKey.ToAddress(), Name: "test001", ConnectNums: 0, ConnectedNums: 0, // CtrlID: 0, LstClientAddr: nil, AddTime: time.Now().Unix(), ConnectMe: false, NodeTypeVersion: "0.1.0", NodeType: "normal", CoreVersion: "0.1.0", LastRecvMsgID: 1, ConnType: coredbpb.CONNECTTYPE_UNKNOWN_CONN, } cn1, err := updNodeInfo(ankaDB, cni1) if err != nil { t.Fatalf("TestBaseFunc updNodeInfo %v", err) return } if cni1.ServAddr != cn1.ServAddr { t.Fatalf("TestBaseFunc updNodeInfo return ServAddr fail! (%v - %v)", cni1.ServAddr, cn1.ServAddr) return } if cni1.Addr != cn1.Addr { t.Fatalf("TestBaseFunc updNodeInfo return Addr fail! (%v - %v)", cni1.Addr, cn1.Addr) return } if cni1.Name != cn1.Name { t.Fatalf("TestBaseFunc updNodeInfo return Name fail! (%v - %v)", cni1.Name, cn1.Name) return } if cni1.ConnectNums != cn1.ConnectNums { t.Fatalf("TestBaseFunc updNodeInfo return ConnectNums fail! (%v - %v)", cni1.ConnectNums, cn1.ConnectNums) return } if cni1.ConnectedNums != cn1.ConnectedNums { t.Fatalf("TestBaseFunc updNodeInfo return ConnectedNums fail! (%v - %v)", cni1.ConnectedNums, cn1.ConnectedNums) return } // if cni1.CtrlID != cn1.CtrlID { // t.Fatalf("TestBaseFunc updNodeInfo return CtrlID fail! (%v - %v)", cni1.CtrlID, cn1.CtrlID) // return // } if cni1.ConnectedNums != cn1.ConnectedNums { t.Fatalf("TestBaseFunc updNodeInfo return ConnectedNums fail! (%v - %v)", cni1.ConnectedNums, cn1.ConnectedNums) return } if cni1.AddTime != cn1.AddTime { t.Fatalf("TestBaseFunc updNodeInfo return AddTime fail! (%v - %v)", cni1.AddTime, cn1.AddTime) return } if cni1.ConnectMe != cn1.ConnectMe { t.Fatalf("TestBaseFunc updNodeInfo return ConnectMe fail! (%v - %v)", cni1.ConnectMe, cn1.ConnectMe) return } if cni1.ConnType != cn1.ConnType { t.Fatalf("TestBaseFunc updNodeInfo return ConnType fail! (%v - %v)", cni1.ConnType, cn1.ConnType) return } if cni1.NodeTypeVersion != cn1.NodeTypeVersion { t.Fatalf("TestBaseFunc updNodeInfo return NodeTypeVersion fail! (%v - %v)", cni1.NodeTypeVersion, cn1.NodeTypeVersion) return } if cni1.NodeType != cn1.NodeType { t.Fatalf("TestBaseFunc updNodeInfo return NodeType fail! (%v - %v)", cni1.NodeType, cn1.NodeType) return } if cni1.CoreVersion != cn1.CoreVersion { t.Fatalf("TestBaseFunc updNodeInfo return CoreVersion fail! (%v - %v)", cni1.CoreVersion, cn1.CoreVersion) return } if cni1.LastRecvMsgID != cn1.LastRecvMsgID { t.Fatalf("TestBaseFunc updNodeInfo return LastRecvMsgID fail! (%v - %v)", cni1.LastRecvMsgID, cn1.LastRecvMsgID) return } //------------------------------------------------------------------------ // updNodeInfo test002 test002PriKey := jarviscrypto.GenerateKey() cni2 := &coredbpb.NodeInfo{ ServAddr: "127.0.0.1", Addr: test002PriKey.ToAddress(), Name: "test002", ConnectNums: 0, ConnectedNums: 0, // CtrlID: 0, LstClientAddr: nil, AddTime: time.Now().Unix(), ConnectMe: false, NodeTypeVersion: "0.1.0", NodeType: "normal", CoreVersion: "0.1.0", LastRecvMsgID: 1, ConnType: coredbpb.CONNECTTYPE_UNKNOWN_CONN, } cn2, err := updNodeInfo(ankaDB, cni2) if err != nil { t.Fatalf("TestBaseFunc updNodeInfo %v", err) return } if cni2.ServAddr != cn2.ServAddr { t.Fatalf("TestBaseFunc updNodeInfo return ServAddr fail! (%v - %v)", cni2.ServAddr, cn2.ServAddr) return } if cni2.Addr != cn2.Addr { t.Fatalf("TestBaseFunc updNodeInfo return Addr fail! (%v - %v)", cni2.Addr, cn2.Addr) return } if cni2.Name != cn2.Name { t.Fatalf("TestBaseFunc updNodeInfo return Name fail! (%v - %v)", cni2.Name, cn2.Name) return } if cni2.ConnectNums != cn2.ConnectNums { t.Fatalf("TestBaseFunc updNodeInfo return ConnectNums fail! (%v - %v)", cni2.ConnectNums, cn2.ConnectNums) return } if cni2.ConnectedNums != cn2.ConnectedNums { t.Fatalf("TestBaseFunc updNodeInfo return ConnectedNums fail! (%v - %v)", cni2.ConnectedNums, cn2.ConnectedNums) return } // if cni2.CtrlID != cn2.CtrlID { // t.Fatalf("TestBaseFunc updNodeInfo return CtrlID fail! (%v - %v)", cni2.CtrlID, cn2.CtrlID) // return // } if cni2.ConnectedNums != cn2.ConnectedNums { t.Fatalf("TestBaseFunc updNodeInfo return ConnectedNums fail! (%v - %v)", cni2.ConnectedNums, cn2.ConnectedNums) return } if cni2.AddTime != cn2.AddTime { t.Fatalf("TestBaseFunc updNodeInfo return AddTime fail! (%v - %v)", cni2.AddTime, cn2.AddTime) return } if cni2.ConnectMe != cn2.ConnectMe { t.Fatalf("TestBaseFunc updNodeInfo return ConnectMe fail! (%v - %v)", cni2.ConnectMe, cn2.ConnectMe) return } if cni2.ConnType != cn2.ConnType { t.Fatalf("TestBaseFunc updNodeInfo return ConnType fail! (%v - %v)", cni2.ConnType, cn2.ConnType) return } if cni2.NodeTypeVersion != cn2.NodeTypeVersion { t.Fatalf("TestBaseFunc updNodeInfo return NodeTypeVersion fail! (%v - %v)", cni2.NodeTypeVersion, cn2.NodeTypeVersion) return } if cni2.NodeType != cn2.NodeType { t.Fatalf("TestBaseFunc updNodeInfo return NodeType fail! (%v - %v)", cni2.NodeType, cn2.NodeType) return } if cni2.CoreVersion != cn2.CoreVersion { t.Fatalf("TestBaseFunc updNodeInfo return CoreVersion fail! (%v - %v)", cni2.CoreVersion, cn2.CoreVersion) return } if cni2.LastRecvMsgID != cn2.LastRecvMsgID { t.Fatalf("TestBaseFunc updNodeInfo return LastRecvMsgID fail! (%v - %v)", cni2.LastRecvMsgID, cn2.LastRecvMsgID) return } //------------------------------------------------------------------------ // trustNode pd, err = trustNode(ankaDB, test001PriKey.ToAddress()) if err != nil { t.Fatalf("TestBaseFunc trustNode %v", err) return } if pd.PriKey != nil || pd.PubKey != nil || pd.StrPriKey != "" { t.Fatalf("TestBaseFunc trustNode return PriKey or PubKey or StrPriKey is non-nil") return } if pd.StrPubKey != jarviscrypto.Base58Encode(privKey.ToPublicBytes()) { t.Fatalf("TestBaseFunc trustNode return StrPubKey fail! (%v - %v)", pd.StrPubKey, jarviscrypto.Base58Encode(privKey.ToPublicBytes())) return } //------------------------------------------------------------------------ // getNodeInfo test001 cn1, err = getNodeInfo(ankaDB, test001PriKey.ToAddress()) if err != nil { t.Fatalf("TestBaseFunc getNodeInfo %v", err) return } if cni1.ServAddr != cn1.ServAddr { t.Fatalf("TestBaseFunc getNodeInfo return ServAddr fail! (%v - %v)", cni1.ServAddr, cn1.ServAddr) return } if cni1.Addr != cn1.Addr { t.Fatalf("TestBaseFunc getNodeInfo return Addr fail! (%v - %v)", cni1.Addr, cn1.Addr) return } if cni1.Name != cn1.Name { t.Fatalf("TestBaseFunc getNodeInfo return Name fail! (%v - %v)", cni1.Name, cn1.Name) return } if cni1.ConnectNums != cn1.ConnectNums { t.Fatalf("TestBaseFunc getNodeInfo return ConnectNums fail! (%v - %v)", cni1.ConnectNums, cn1.ConnectNums) return } if cni1.ConnectedNums != cn1.ConnectedNums { t.Fatalf("TestBaseFunc getNodeInfo return ConnectedNums fail! (%v - %v)", cni1.ConnectedNums, cn1.ConnectedNums) return } // if cni1.CtrlID != cn1.CtrlID { // t.Fatalf("TestBaseFunc getNodeInfo return CtrlID fail! (%v - %v)", cni1.CtrlID, cn1.CtrlID) // return // } if cni1.ConnectedNums != cn1.ConnectedNums { t.Fatalf("TestBaseFunc getNodeInfo return ConnectedNums fail! (%v - %v)", cni1.ConnectedNums, cn1.ConnectedNums) return } if cni1.AddTime != cn1.AddTime { t.Fatalf("TestBaseFunc getNodeInfo return AddTime fail! (%v - %v)", cni1.AddTime, cn1.AddTime) return } if cni1.ConnectMe != cn1.ConnectMe { t.Fatalf("TestBaseFunc getNodeInfo return ConnectMe fail! (%v - %v)", cni1.ConnectMe, cn1.ConnectMe) return } if cni1.ConnType != cn1.ConnType { t.Fatalf("TestBaseFunc getNodeInfo return ConnType fail! (%v - %v)", cni1.ConnType, cn1.ConnType) return } if cni1.NodeTypeVersion != cn1.NodeTypeVersion { t.Fatalf("TestBaseFunc getNodeInfo return NodeTypeVersion fail! (%v - %v)", cni1.NodeTypeVersion, cn1.NodeTypeVersion) return } if cni1.NodeType != cn1.NodeType { t.Fatalf("TestBaseFunc getNodeInfo return NodeType fail! (%v - %v)", cni1.NodeType, cn1.NodeType) return } if cni1.CoreVersion != cn1.CoreVersion { t.Fatalf("TestBaseFunc getNodeInfo return CoreVersion fail! (%v - %v)", cni1.CoreVersion, cn1.CoreVersion) return } if cni1.LastRecvMsgID != cn1.LastRecvMsgID { t.Fatalf("TestBaseFunc getNodeInfo return LastRecvMsgID fail! (%v - %v)", cni1.LastRecvMsgID, cn1.LastRecvMsgID) return } //------------------------------------------------------------------------ // getNodeInfo test002 cn2, err = getNodeInfo(ankaDB, test002PriKey.ToAddress()) if err != nil { t.Fatalf("TestBaseFunc getNodeInfo %v", err) return } if cni2.ServAddr != cn2.ServAddr { t.Fatalf("TestBaseFunc getNodeInfo return ServAddr fail! (%v - %v)", cni2.ServAddr, cn2.ServAddr) return } if cni2.Addr != cn2.Addr { t.Fatalf("TestBaseFunc getNodeInfo return Addr fail! (%v - %v)", cni2.Addr, cn2.Addr) return } if cni2.Name != cn2.Name { t.Fatalf("TestBaseFunc getNodeInfo return Name fail! (%v - %v)", cni2.Name, cn2.Name) return } if cni2.ConnectNums != cn2.ConnectNums { t.Fatalf("TestBaseFunc getNodeInfo return ConnectNums fail! (%v - %v)", cni2.ConnectNums, cn2.ConnectNums) return } if cni2.ConnectedNums != cn2.ConnectedNums { t.Fatalf("TestBaseFunc getNodeInfo return ConnectedNums fail! (%v - %v)", cni2.ConnectedNums, cn2.ConnectedNums) return } // if cni2.CtrlID != cn2.CtrlID { // t.Fatalf("TestBaseFunc getNodeInfo return CtrlID fail! (%v - %v)", cni2.CtrlID, cn2.CtrlID) // return // } if cni2.ConnectedNums != cn2.ConnectedNums { t.Fatalf("TestBaseFunc getNodeInfo return ConnectedNums fail! (%v - %v)", cni2.ConnectedNums, cn2.ConnectedNums) return } if cni2.AddTime != cn2.AddTime { t.Fatalf("TestBaseFunc getNodeInfo return AddTime fail! (%v - %v)", cni2.AddTime, cn2.AddTime) return } if cni2.ConnectMe != cn2.ConnectMe { t.Fatalf("TestBaseFunc getNodeInfo return ConnectMe fail! (%v - %v)", cni2.ConnectMe, cn2.ConnectMe) return } if cni2.ConnType != cn2.ConnType { t.Fatalf("TestBaseFunc getNodeInfo return ConnType fail! (%v - %v)", cni2.ConnType, cn2.ConnType) return } if cni2.NodeTypeVersion != cn2.NodeTypeVersion { t.Fatalf("TestBaseFunc getNodeInfo return NodeTypeVersion fail! (%v - %v)", cni2.NodeTypeVersion, cn2.NodeTypeVersion) return } if cni2.NodeType != cn2.NodeType { t.Fatalf("TestBaseFunc getNodeInfo return NodeType fail! (%v - %v)", cni2.NodeType, cn2.NodeType) return } if cni2.CoreVersion != cn2.CoreVersion { t.Fatalf("TestBaseFunc getNodeInfo return CoreVersion fail! (%v - %v)", cni2.CoreVersion, cn2.CoreVersion) return } if cni2.LastRecvMsgID != cn2.LastRecvMsgID { t.Fatalf("TestBaseFunc getNodeInfo return LastRecvMsgID fail! (%v - %v)", cni2.LastRecvMsgID, cn2.LastRecvMsgID) return } //------------------------------------------------------------------------ // getNodeInfos test002 lstnode, err := getNodeInfos(ankaDB, -1, 0, 100) if err != nil { t.Fatalf("TestBaseFunc getNodeInfos %v", err) return } for i := 0; i < len(lstnode.Nodes); i++ { if lstnode.Nodes[i].Addr == cni1.Addr { cn1 = lstnode.Nodes[i] if cni1.ServAddr != cn1.ServAddr { t.Fatalf("TestBaseFunc getNodeInfos return ServAddr fail! (%v - %v)", cni1.ServAddr, cn1.ServAddr) return } if cni1.Addr != cn1.Addr { t.Fatalf("TestBaseFunc getNodeInfos return Addr fail! (%v - %v)", cni1.Addr, cn1.Addr) return } if cni1.Name != cn1.Name { t.Fatalf("TestBaseFunc getNodeInfos return Name fail! (%v - %v)", cni1.Name, cn1.Name) return } if cni1.ConnectNums != cn1.ConnectNums { t.Fatalf("TestBaseFunc getNodeInfos return ConnectNums fail! (%v - %v)", cni1.ConnectNums, cn1.ConnectNums) return } if cni1.ConnectedNums != cn1.ConnectedNums { t.Fatalf("TestBaseFunc getNodeInfos return ConnectedNums fail! (%v - %v)", cni1.ConnectedNums, cn1.ConnectedNums) return } // if cni1.CtrlID != cn1.CtrlID { // t.Fatalf("TestBaseFunc getNodeInfos return CtrlID fail! (%v - %v)", cni1.CtrlID, cn1.CtrlID) // return // } if cni1.ConnectedNums != cn1.ConnectedNums { t.Fatalf("TestBaseFunc getNodeInfos return ConnectedNums fail! (%v - %v)", cni1.ConnectedNums, cn1.ConnectedNums) return } if cni1.AddTime != cn1.AddTime { t.Fatalf("TestBaseFunc getNodeInfos return AddTime fail! (%v - %v)", cni1.AddTime, cn1.AddTime) return } if cni1.ConnectMe != cn1.ConnectMe { t.Fatalf("TestBaseFunc getNodeInfos return ConnectMe fail! (%v - %v)", cni1.ConnectMe, cn1.ConnectMe) return } if cni1.ConnType != cn1.ConnType { t.Fatalf("TestBaseFunc getNodeInfos return ConnType fail! (%v - %v)", cni1.ConnType, cn1.ConnType) return } if cni1.NodeTypeVersion != cn1.NodeTypeVersion { t.Fatalf("TestBaseFunc getNodeInfos return NodeTypeVersion fail! (%v - %v)", cni1.NodeTypeVersion, cn1.NodeTypeVersion) return } if cni1.NodeType != cn1.NodeType { t.Fatalf("TestBaseFunc getNodeInfos return NodeType fail! (%v - %v)", cni1.NodeType, cn1.NodeType) return } if cni1.CoreVersion != cn1.CoreVersion { t.Fatalf("TestBaseFunc getNodeInfos return CoreVersion fail! (%v - %v)", cni1.CoreVersion, cn1.CoreVersion) return } if cni1.LastRecvMsgID != cn1.LastRecvMsgID { t.Fatalf("TestBaseFunc getNodeInfos return LastRecvMsgID fail! (%v - %v)", cni1.LastRecvMsgID, cn1.LastRecvMsgID) return } } else if lstnode.Nodes[i].Addr == cni2.Addr { cn2 = lstnode.Nodes[i] if cni2.ServAddr != cn2.ServAddr { t.Fatalf("TestBaseFunc getNodeInfos return ServAddr fail! (%v - %v)", cni2.ServAddr, cn2.ServAddr) return } if cni2.Addr != cn2.Addr { t.Fatalf("TestBaseFunc getNodeInfos return Addr fail! (%v - %v)", cni2.Addr, cn2.Addr) return } if cni2.Name != cn2.Name { t.Fatalf("TestBaseFunc getNodeInfos return Name fail! (%v - %v)", cni2.Name, cn2.Name) return } if cni2.ConnectNums != cn2.ConnectNums { t.Fatalf("TestBaseFunc getNodeInfos return ConnectNums fail! (%v - %v)", cni2.ConnectNums, cn2.ConnectNums) return } if cni2.ConnectedNums != cn2.ConnectedNums { t.Fatalf("TestBaseFunc getNodeInfos return ConnectedNums fail! (%v - %v)", cni2.ConnectedNums, cn2.ConnectedNums) return } // if cni2.CtrlID != cn2.CtrlID { // t.Fatalf("TestBaseFunc getNodeInfos return CtrlID fail! (%v - %v)", cni2.CtrlID, cn2.CtrlID) // return // } if cni2.ConnectedNums != cn2.ConnectedNums { t.Fatalf("TestBaseFunc getNodeInfos return ConnectedNums fail! (%v - %v)", cni2.ConnectedNums, cn2.ConnectedNums) return } if cni2.AddTime != cn2.AddTime { t.Fatalf("TestBaseFunc getNodeInfos return AddTime fail! (%v - %v)", cni2.AddTime, cn2.AddTime) return } if cni2.ConnectMe != cn2.ConnectMe { t.Fatalf("TestBaseFunc getNodeInfos return ConnectMe fail! (%v - %v)", cni2.ConnectMe, cn2.ConnectMe) return } if cni2.ConnType != cn2.ConnType { t.Fatalf("TestBaseFunc getNodeInfos return ConnType fail! (%v - %v)", cni2.ConnType, cn2.ConnType) return } if cni2.NodeTypeVersion != cn2.NodeTypeVersion { t.Fatalf("TestBaseFunc getNodeInfos return NodeTypeVersion fail! (%v - %v)", cni2.NodeTypeVersion, cn2.NodeTypeVersion) return } if cni2.NodeType != cn2.NodeType { t.Fatalf("TestBaseFunc getNodeInfos return NodeType fail! (%v - %v)", cni2.NodeType, cn2.NodeType) return } if cni2.CoreVersion != cn2.CoreVersion { t.Fatalf("TestBaseFunc getNodeInfos return CoreVersion fail! (%v - %v)", cni2.CoreVersion, cn2.CoreVersion) return } if cni2.LastRecvMsgID != cn2.LastRecvMsgID { t.Fatalf("TestBaseFunc getNodeInfos return LastRecvMsgID fail! (%v - %v)", cni2.LastRecvMsgID, cn2.LastRecvMsgID) return } } } t.Logf("TestBaseFunc is OK") }
package common import ( "bytes" "database/sql" "errors" "fmt" "reflect" "strings" ) type Dao struct { DB *sql.DB } const ( TABLE = "DB_TABLE" COL = "DB_COL" PK = "DB_PK" ) func (_self *Dao) Insert(sql string, args ...interface{}) (int64, int64, error) { stmt, err := _self.DB.Prepare(sql) if err != nil { return 0, 0, err } return _self.insertWithStmt(stmt, args) } func (_self *Dao) InsertWithTx(tx *sql.Tx, sql string, args ...interface{}) (int64, int64, error) { stmt, err := tx.Prepare(sql) if err != nil { return 0, 0, err } return _self.insertWithStmt(stmt, args) } func (_self *Dao) insertWithStmt(stmt *sql.Stmt, args []interface{}) (int64, int64, error) { res, err := stmt.Exec(args...) if err != nil { return 0, 0, err } lastId, err := res.LastInsertId() if err != nil { return 0, 0, err } rowCnt, err := res.RowsAffected() if err != nil { return 0, 0, err } return lastId, rowCnt, err } func (_self *Dao) Exec(sql string, args ...interface{}) (int64, error) { stmt, err := _self.DB.Prepare(sql) if err != nil { return 0, err } return _self.execWithStmt(stmt, args) } func (_self *Dao) ExecWithTx(tx *sql.Tx, sql string, args ...interface{}) (int64, error) { stmt, err := tx.Prepare(sql) if err != nil { return 0, err } return _self.execWithStmt(stmt, args) } func (_self *Dao) execWithStmt(stmt *sql.Stmt, args []interface{}) (int64, error) { res, err := stmt.Exec(args...) if err != nil { return 0, err } rowCnt, err := res.RowsAffected() if err != nil { return 0, err } return rowCnt, err } func (_self *Dao) Query(sql string, args ...interface{}) (*sql.Rows, error) { return _self.DB.Query(sql, args...) } func (_self *Dao) QueryWithTx(tx *sql.Tx, sql string, args ...interface{}) (*sql.Rows, error) { return tx.Query(sql, args...) } func (_self *Dao) Count(sql string, args ...interface{}) int64 { row := _self.DB.QueryRow(sql, args...) count := int64(0) err := row.Scan(&count) if err != nil { return 0 } return count } func (_self *Dao) StructInsert(src interface{}, usePK bool) (int64, error) { // Parse struct Insert pk, mapper, sql, values := _self.structInsertParse(src, usePK) // Exec sql lastId, rowCnt, err := _self.Insert(sql, values...) if err != nil { return 0, err } if pk != "" && !usePK { mapper[pk].Set(reflect.ValueOf(lastId)) } return rowCnt, nil } func (_self *Dao) StructInsertWithTx(tx *sql.Tx, src interface{}, usePK bool) (int64, error) { // Parse struct Insert pk, mapper, sql, values := _self.structInsertParse(src, usePK) // Exec sql lastId, rowCnt, err := _self.InsertWithTx(tx, sql, values...) if err != nil { return 0, err } if pk != "" && !usePK { mapper[pk].Set(reflect.ValueOf(lastId)) } return rowCnt, nil } func (_self *Dao) structInsertParse(src interface{}, usePK bool) (string, map[string]reflect.Value, string, []interface{}) { // Get COL Mapper table, pk, mapper := _self.structReflect(src) // Concat sql string var col bytes.Buffer var val bytes.Buffer values := make([]interface{}, 0) for k, v := range mapper { if pk == k && !usePK { continue } col.WriteString(fmt.Sprintf("`%s`, ", k)) val.WriteString("?, ") values = append(values, v.Addr().Interface()) } sql := fmt.Sprintf("INSERT INTO `%s` (%s) VALUES (%s) ", table, strings.Trim(col.String(), ", "), strings.Trim(val.String(), ", ")) return pk, mapper, sql, values } func (_self *Dao) StructBatchInsert(usePK bool, beans ...interface{}) (int64, error) { if len(beans) < 1 { return 0, errors.New("no element") } // Concat table string keys := make([]string, 0) var col bytes.Buffer table, pk, mapper := _self.structReflect(beans[0]) for k := range mapper { if pk == k && !usePK { continue } col.WriteString(fmt.Sprintf("`%s`, ", k)) keys = append(keys, k) } sql := fmt.Sprintf("INSERT INTO `%s` (%s) VALUES ", table, strings.Trim(col.String(), ", ")) // Concat values string values := make([]interface{}, 0) for _, bean := range beans { _, _, mapper := _self.structReflect(bean) var val bytes.Buffer for _, key := range keys { val.WriteString("?, ") values = append(values, mapper[key].Addr().Interface()) } sql = sql + fmt.Sprintf("(%s), ", strings.Trim(val.String(), ", ")) } sql = strings.Trim(sql, ", ") // Exec sql _, rowCnt, err := _self.Insert(sql, values...) if err != nil { return 0, err } return rowCnt, nil } func (_self *Dao) StructUpdateByPK(src interface{}) (int64, error) { table, pk, mapper := _self.structReflect(src) // Concat sql string var col bytes.Buffer var pv interface{} values := make([]interface{}, 0) for k, v := range mapper { if pk == k { pv = v.Addr().Interface() continue } col.WriteString(fmt.Sprintf("`%s` = ?, ", k)) values = append(values, v.Addr().Interface()) } values = append(values, pv) sql := fmt.Sprintf("UPDATE `%s` SET %s WHERE %s = ?", table, strings.Trim(col.String(), ", "), pk) // Exec sql rowCnt, err := _self.Exec(sql, values...) if err != nil { return 0, err } return rowCnt, nil } func (_self *Dao) StructUpsert(src interface{}) (int64, error) { // Parse upsert param sql, values := _self.structUpsertParse(src) // Exec sql rowCnt, err := _self.Exec(sql, values...) if err != nil { return 0, err } return rowCnt, nil } func (_self *Dao) StructUpsertWithTx(tx *sql.Tx, src interface{}) (int64, error) { // Parse upsert param sql, values := _self.structUpsertParse(src) // Exec sql rowCnt, err := _self.ExecWithTx(tx, sql, values...) if err != nil { return 0, err } return rowCnt, nil } func (_self *Dao) structUpsertParse(src interface{}) (string, []interface{}) { // Get COL Mapper table, _, mapper := _self.structReflect(src) // Concat sql string var col1 bytes.Buffer var col2 bytes.Buffer var val bytes.Buffer values1 := make([]interface{}, 0) values2 := make([]interface{}, 0) for k, v := range mapper { col1.WriteString(fmt.Sprintf("`%s`, ", k)) col2.WriteString(fmt.Sprintf("`%s` = ?, ", k)) val.WriteString("?, ") values1 = append(values1, v.Addr().Interface()) values2 = append(values2, v.Addr().Interface()) } sql := fmt.Sprintf("INSERT INTO `%s` (%s) VALUES (%s) ON DUPLICATE KEY UPDATE %s", table, strings.Trim(col1.String(), ", "), strings.Trim(val.String(), ", "), strings.Trim(col2.String(), ", ")) values1 = append(values1, values2...) return sql, values1 } func (_self *Dao) StructSelectByPK(dst interface{}, arg interface{}) (bool, error) { table, pk, _ := _self.structReflect(dst) sql := fmt.Sprintf("SELECT * FROM `%s` WHERE %s = ?", table, pk) rows, err := _self.Query(sql, arg) if err != nil { return false, nil } defer rows.Close() for rows.Next() { err := _self.structScan(rows, dst) if err != nil { return false, err } return true, nil } return false, nil } func (_self *Dao) StructSelectByPKWithTx(tx *sql.Tx, dst interface{}, arg interface{}) (bool, error) { table, pk, _ := _self.structReflect(dst) sql := fmt.Sprintf("SELECT * FROM `%s` WHERE %s = ?", table, pk) rows, err := _self.QueryWithTx(tx, sql, arg) if err != nil { return false, err } defer rows.Close() for rows.Next() { err := _self.structScan(rows, dst) if err != nil { return false, err } return true, nil } return false, nil } func (_self *Dao) StructSelect(dst interface{}, sql string, args ...interface{}) (bool, error) { value := reflect.ValueOf(dst) if value.Kind() != reflect.Ptr || value.IsNil() || value.Elem().Type().Kind() != reflect.Slice { return false, errors.New("must pass a none nil slice pointer") } direct := reflect.Indirect(value) slice := reflect.Indirect(value.Elem()) elemType := reflect.TypeOf(dst).Elem().Elem() isPtr := elemType.Kind() == reflect.Ptr rows, err := _self.Query(sql, args...) if err != nil { return false, err } defer rows.Close() // Start scan for rows.Next() { // New struct var elem reflect.Value if isPtr { elem = reflect.New(elemType.Elem()) } else { elem = reflect.New(elemType) } // Scan row data err := _self.structScan(rows, elem.Interface()) if err != nil { return false, err } // Append to slice if isPtr { slice = reflect.Append(slice, elem) } else { slice = reflect.Append(slice, reflect.Indirect(elem)) } } direct.Set(slice) return true, nil } func (_self *Dao) structScan(rows *sql.Rows, dst interface{}) error { // Get COL Mapper _, _, mapper := _self.structReflect(dst) // Get columns description columns, err := rows.Columns() if err != nil { return err } // Receive data values := make([]interface{}, len(columns)) for i, column := range columns { if v, ok := mapper[column]; ok { values[i] = v.Addr().Interface() } else { values[i] = new(sql.RawBytes) } } // Scan data err = rows.Scan(values...) if err != nil { return err } return nil } func (_self *Dao) structReflect(dst interface{}) (string, string, map[string]reflect.Value) { var table, pk string mapper := make(map[string]reflect.Value) elem := reflect.ValueOf(dst).Elem() for i := 0; i < elem.NumField(); i++ { if table == "" { table = elem.Type().Field(i).Tag.Get(TABLE) } if pk == "" { pk = elem.Type().Field(i).Tag.Get(PK) } tag := elem.Type().Field(i).Tag.Get(COL) if tag != "" { mapper[tag] = elem.Field(i) } } return table, pk, mapper }
package accounting import ( "log" "tddbudget/repository" "time" ) // Budget 預算 type Budget struct { yearMonth string amount float64 first time.Time last time.Time } // getBudgets 取得預算 func getBudgets() (budgets []*Budget) { data := repository.GetBudgets() for yearMonth, amount := range data { // 取得每個月的第一天 first, err := time.Parse("20060102", yearMonth+"01") if err != nil { log.Println("[ Err ] parse date error :", err) continue } // 取得每個月的最後一天 date, err := time.Parse("200601", yearMonth) if err != nil { log.Println("[ Err ] parse date error :", err) continue } last := time.Date(date.Year(), date.Month()+1, 0, 0, 0, 0, 0, time.UTC) budgets = append(budgets, &Budget{yearMonth, amount, first, last}) } return } // dailyAmount 取得每日金額 func (b *Budget) dailyAmount() float64 { return b.amount / float64(b.last.Day()) }
package main import ( "testing" ) func benchmark(b *testing.B, f func(int, string) string) { var str = randomString(10) for i := 0; i < b.N; i++ { f(10000, str) } } //BenchmarkPlusConcat //BenchmarkPlusConcat-8 14 75699414 ns/op //BenchmarkSprintfConcat //BenchmarkSprintfConcat-8 8 155750225 ns/op //BenchmarkBuilderConcat //BenchmarkBuilderConcat-8 7500 150379 ns/op //BenchmarkBufferConcat //BenchmarkBufferConcat-8 7999 139929 ns/op //BenchmarkByteConcat //BenchmarkByteConcat-8 7999 147742 ns/op //BenchmarkPreByteConcat //BenchmarkPreByteConcat-8 14065 71526 ns/op func BenchmarkPlusConcat(b *testing.B) { benchmark(b, plusConcat) } func BenchmarkSprintfConcat(b *testing.B) { benchmark(b, sprintfConcat) } func BenchmarkBuilderConcat(b *testing.B) { benchmark(b, builderConcat) } func BenchmarkBufferConcat(b *testing.B) { benchmark(b, bufferConcat) } func BenchmarkByteConcat(b *testing.B) { benchmark(b, byteConcat) } func BenchmarkPreByteConcat(b *testing.B) { benchmark(b, preByteConcat) }
package main import ( "strings" "testing" ) var input = []string{"hello", "bye", "asdf", "1234567890", "-1", "-2"} func echo1(args []string) string { var s, sep string for i := 0; i < len(args); i++ { s += sep + args[i] sep = " " } return s } func echo2(args []string) string { return strings.Join(args, " ") } func BenchmarkEcho1(b *testing.B) { for i := 0; i < b.N; i++ { _ = echo1(input) } } func BenchmarkEcho2(b *testing.B) { for i := 0; i < b.N; i++ { _ = echo2(input) } }
package core import ( "fmt" "time" "github.com/enriquebris/goconcurrentqueue" "github.com/reactivex/rxgo/v2" "gopkg.in/jeevatkm/go-model.v1" ) // Builder Object for EventBus type eventBusBuilder struct { mediator *mediator messaging messagingAdapter cbSettings CircuitBreakerSettings settings EventBusSettings } // Constructor for EventBusBuilder func NewEventBusBuilder() *eventBusBuilder { o := new(eventBusBuilder) o.cbSettings = CircuitBreakerSettings{ AllowedRequestInHalfOpen: 1, DurationOfBreak: time.Duration(60 * time.Second), SamplingDuration: time.Duration(60 * time.Second), SamplingFailureCount: 5, } o.settings = EventBusSettings{ BufferedEventBufferCount: 1000, BufferedEventBufferTime: time.Duration(1 * time.Second), BufferedEventTimeout: time.Duration(5 * time.Second), ConnectionTimeout: time.Duration(10 * time.Second), } return o } // Build Method which creates EventBus func (b *eventBusBuilder) Build() *eventBus { if eventBusInstance != nil { panic("eventBus already created") } eventBusInstance = b.Create() return eventBusInstance } // Build Method which creates EventBus func (b *eventBusBuilder) Create() *eventBus { if b.messaging == nil { panic("messaging adapter is required") } if b.mediator == nil { b.mediator = GetMediator() } instance := &eventBus{ mediator: b.mediator, domainEvents: goconcurrentqueue.NewFIFO(), ch: make(chan rxgo.Item, 1), messaging: b.messaging, settings: b.settings, } instance.cb = b.cbSettings.ToCircuitBreaker("eventbus", instance.onCircuitOpen) instance.initialize() return instance } // Builder method to set the field messaging in EventBusBuilder func (b *eventBusBuilder) Settings(settings EventBusSettings) *eventBusBuilder { err := model.Copy(&b.settings, settings) if err != nil { panic(fmt.Errorf("settings mapping errors occurred: %v", err)) } return b } // Builder method to set the field messaging in EventBusBuilder func (b *eventBusBuilder) CircuitBreaker(settings CircuitBreakerSettings) *eventBusBuilder { err := model.Copy(&b.cbSettings, settings) if err != nil { panic(fmt.Errorf("cb settings mapping errors occurred: %v", err)) } return b } // Builder method to set the field messaging in EventBusBuilder func (b *eventBusBuilder) CustomMediator(mediator *mediator) *eventBusBuilder { if mediator == nil { panic("mediator is required") } b.mediator = mediator return b } // Builder method to set the field messaging in EventBusBuilder func (b *eventBusBuilder) MessaingAdapter(adapter messagingAdapter) *eventBusBuilder { if adapter == nil { panic("adapter is required") } b.messaging = adapter return b }
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. // License: https://creativecommons.org/licenses/by-nc-sa/4.0/ // See page 61. //!+ // Mandelbrot emits a PNG image of the Mandelbrot fractal. package main import ( "image" "image/color" "image/png" "math/cmplx" "os" ) func main() { const ( xmin, ymin, xmax, ymax = -2, -2, +2, +2 width, height = 1024, 1024 ) // 画像を4倍のサイズに img4 := image.NewRGBA(image.Rect(0, 0, width*2, height*2)) for py := 0; py < (height * 2); py++ { y := float64(py)/(height*2)*(ymax-ymin) + ymin for px := 0; px < (width * 2); px++ { x := float64(px)/(width*2)*(xmax-xmin) + xmin z := complex(x, y) // Image point (px, py) represents complex value z. img4.Set(px, py, mandelbrot(z)) } } // サブピクセルの色を決める img := image.NewRGBA(image.Rect(0, 0, width, height)) for py := 0; py < height*2; py = py + 2 { for px := 0; px < width*2; px = px + 2 { var c = []color.RGBA{ img4.RGBAAt(px, py), img4.RGBAAt(px+1, py), img4.RGBAAt(px, py+1), img4.RGBAAt(px+1, py+1), } var pr, pg, pb, pa int for n := 0; n < 4; n++ { pr += int(c[n].R) pg += int(c[n].G) pb += int(c[n].B) pa += int(c[n].A) } img.SetRGBA(px/2, py/2, color.RGBA{uint8(pr / 4), uint8(pg / 4), uint8(pb / 4), uint8(pa / 4)}) } } png.Encode(os.Stdout, img) // NOTE: ignoring errors } func mandelbrot(z complex128) color.RGBA { const iterations = 200 const contrast = 15 var v complex128 for n := uint8(0); n < iterations; n++ { v = v*v + z if cmplx.Abs(v) > 2 { return color.RGBA{contrast * (n + 8), contrast * (n + 4), contrast * n, 255} } } return color.RGBA{255, 255, 255, 255} } //!- // Some other interesting functions: func acos(z complex128) color.Color { v := cmplx.Acos(z) blue := uint8(real(v)*128) + 127 red := uint8(imag(v)*128) + 127 return color.YCbCr{192, blue, red} } func sqrt(z complex128) color.Color { v := cmplx.Sqrt(z) blue := uint8(real(v)*128) + 127 red := uint8(imag(v)*128) + 127 return color.YCbCr{128, blue, red} } // f(x) = x^4 - 1 // // z' = z - f(z)/f'(z) // = z - (z^4 - 1) / (4 * z^3) // = z - (z - 1/z^3) / 4 func newton(z complex128) color.Color { const iterations = 37 const contrast = 7 for i := uint8(0); i < iterations; i++ { z -= (z - 1/(z*z*z)) / 4 if cmplx.Abs(z*z*z*z-1) < 1e-6 { return color.Gray{255 - contrast*i} } } return color.Black }
package queue type Item interface{} type Interface interface { Peek() Item Enqueue(Item) Dequeue() Item Len() int }
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "github.com/julienschmidt/httprouter" "github.com/olugbokikisemiu/Meant4Task/calculate" ) func main() { router := httprouter.New() router.POST("/calculate", Index) m := calculate.NewRequestMiddleware(router) fmt.Println("Server started and listening on port :8989") http.ListenAndServe(":8989", m) } func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { w.Header().Set("Content-Type", "application/json") var req calculate.Request requestData, err := ioutil.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write(calculate.HandleError()) return } json.Unmarshal(requestData, &req) w.WriteHeader(http.StatusOK) fmt.Fprint(w, calculate.Calculate(req.A, req.B)) }
package main import ( "fmt" "math/rand" "time" "reflect" ) // simulate flipping a fair coin func FlipCoin() string { rand.Seed(time.Now().UnixNano()) if flipint := rand.Intn(2); flipint == 0 { return "tails" } return "heads" } // flip until condition is met func FlipCondition() int { flips := [2]string{FlipCoin(), FlipCoin()} previous := 0 current := 1 s := flips[previous: current+1] cond := []string{"heads","heads"} numflips := 2 for !reflect.DeepEqual(s, cond) { s[previous] = s[current] s[current] = FlipCoin() numflips +=1 } return numflips } // mean function func mean(vals[]int) float64 { tot := 0.0 for _, v := range vals{ tot += float64(v) } return tot/float64(len(vals)) } // run multiple trials func FlippityFlip(numtrials int) []int { vals := make([]int, numtrials) for i := 0; i < numtrials; i++ { vals[i] = FlipCondition() } return vals } func main() { trials := FlippityFlip(10000) fmt.Println(mean(trials)) }
package main import "fmt" func main(){ x := [6]float64{98,93,77,82,83} // var x [5]float64 = [5]float64{98,93,77,82,83} var total float64 = 0 for i,value := range x { total += value fmt.Println(x[i]) } fmt.Println(total/float64(len(x))) }
package slack import ( "encoding/json" "sync/atomic" "time" "github.com/pkg/errors" "github.com/valyala/fasthttp" ws "golang.org/x/net/websocket" ) // Slack URL consts const ( methodGET = "GET" methodPOST = "POST" contentEncoded = "application/x-www-form-urlencoded; charset=utf-8" contentJSON = "application/json; charset=utf-8" apiURL = "https://api.slack.com/" startURL = "https://slack.com/api/rtm.start" ) var ( reqTimeout = 2 * time.Second wsDeadline = 100 * time.Millisecond retryCount = 3 ) var msgCounter uint64 // GetWSMessage receives a message from RTM API func GetWSMessage(conn *ws.Conn) (m Message, err error) { if err = conn.SetReadDeadline(time.Now().Add(wsDeadline)); err != nil { return } err = ws.JSON.Receive(conn, &m) return } // SendWSMessage sends a message with RTM API func SendWSMessage(conn *ws.Conn, m Message) error { m.ID = atomic.AddUint64(&msgCounter, 1) return ws.JSON.Send(conn, m) } // InitWSConfig creates a websocket-based Real Time API session // and returns the websocket config and the ID of the bot/user whom the token belongs to. func InitWSConfig(token string) (config *ws.Config, userID string, err error) { var response struct { OK bool `json:"ok"` Error string `json:"error"` URL string `json:"url"` Self struct { ID string `json:"id"` } `json:"self"` } params := map[string]string{"token": token} respBody, err := makeRequest(startURL, methodGET, contentEncoded, nil, params, nil) if err != nil { err = errors.Wrap(err, "unable to make GET request") return } if err = json.Unmarshal(respBody, &response); err != nil { err = errors.Wrap(err, "unable to unmarshal response") return } if !response.OK { err = errors.Wrap(err, "request was unsuccessful") return } if config, err = ws.NewConfig(response.URL, apiURL); err != nil { err = errors.Wrap(err, "unable to create websocket config") return } userID = response.Self.ID return } // DialWS wraps ws.DialConfig func DialWS(config *ws.Config) (conn *ws.Conn, err error) { if conn, err = ws.DialConfig(config); err != nil { err = errors.Wrap(err, "unable to dial Slack's websocket") } return } func makeRequest(url, method, contentType string, body []byte, params, headers map[string]string) ([]byte, error) { req := fasthttp.AcquireRequest() defer fasthttp.ReleaseRequest(req) req.Header.SetMethod(method) req.Header.SetContentType(contentType) if len(headers) > 0 { for k, v := range headers { req.Header.Set(k, v) } } req.SetRequestURI(url) if len(params) > 0 { for k, v := range params { req.URI().QueryArgs().Add(k, v) } } if body != nil { req.SetBody(body) } resp := fasthttp.AcquireResponse() defer fasthttp.ReleaseResponse(resp) var ( err error count int ) for count = 0; count < retryCount; count++ { if err = fasthttp.DoTimeout(req, resp, reqTimeout); err == nil { code := resp.StatusCode() if code == fasthttp.StatusOK { break } err = errors.Errorf("%d: %s", code, fasthttp.StatusMessage(code)) } } if err != nil { return nil, errors.Wrapf(err, "request failed after %d retries", count) } respBody := make([]byte, len(resp.Body())) copy(respBody, resp.Body()) return respBody, nil }
package helpers import ( "encoding/json" "fmt" "io/ioutil" "os" ) // JSONConfig consists json object type JSONConfig struct { ConfigJSON map[string]interface{} } var instance *JSONConfig // GetConfig to get CloudConfig singelton session func GetConfig(filePath string, encrypted bool, encrytionFilePath ...string) *JSONConfig { if encrypted { decryptConfig(encrytionFilePath[0], filePath) } configJSON := loadConfig(filePath) return &JSONConfig{configJSON} } func decryptConfig(encrytionFilePath string, decrytionFilePath string) { cipher, _ := os.Open(encrytionFilePath) data, _ := ioutil.ReadAll(cipher) kms := os.Getenv("GCP_KMS_NAME") if kms == "" { LogError("GCP_KMS_NAME environment variable must be set.") } KmsClient().DecryptSymmetric(decrytionFilePath, kms, data) } // LoadConfig reads json file path and return the json object func loadConfig(filePath string) map[string]interface{} { var configJSON map[string]interface{} jsonFile, err := os.Open(filePath) if err != nil { fmt.Println(err) } data, err := ioutil.ReadAll(jsonFile) if err != nil { LogError("Error loading " + filePath + " file") } json.Unmarshal([]byte(data), &configJSON) return configJSON }
package compiler import ( "github.com/davyxu/tabtoy/v3/model" "github.com/davyxu/tabtoy/v3/report" ) func loadVariantTables(globals *model.Globals, kvList, dataList *model.DataTableList) error { report.Log.Debugln("Loading tables...") // 遍历索引里的每一行配置 for _, pragma := range globals.IndexList { if pragma.Kind == model.TableKind_Data && globals.MatchTag != "" && !pragma.MatchTag(globals.MatchTag) { continue } report.Log.Debugf(" (%s) %s", pragma.TableType, pragma.TableFileName) switch pragma.Kind { case model.TableKind_Data: tablist, err := LoadDataTable(globals.TableGetter, pragma.TableFileName, pragma.TableType, pragma.TableType, globals.Types) if err != nil { return err } for _, tab := range tablist { dataList.AddDataTable(tab) } case model.TableKind_Type: err := LoadTypeTable(globals.Types, globals.TableGetter, pragma.TableFileName) if err != nil { return err } case model.TableKind_KeyValue: tablist, err := LoadDataTable(globals.TableGetter, pragma.TableFileName, pragma.TableType, "KVDefine", globals.Types) if err != nil { return err } for _, tab := range tablist { kvList.AddDataTable(tab) } } } return nil }
package agent import ( "encoding/json" "fmt" "net/http" "github.com/bryanl/dolb/service" ) func ServiceCreateHandler(c interface{}, r *http.Request) service.Response { config := c.(*Config) defer r.Body.Close() var ereq service.ServiceCreateRequest err := json.NewDecoder(r.Body).Decode(&ereq) if err != nil { return service.Response{Body: fmt.Errorf("could not decode json: %v", err), Status: 422} } config.GetLogger().WithField("ereq", fmt.Sprintf("%#v", ereq)).Info("service create request") sm := config.ServiceManagerFactory(config) err = sm.Create(ereq) if err != nil { config.GetLogger().WithError(err).Error("could not create service") return service.Response{Body: err, Status: 400} } resp := service.ServiceCreateResponse{ Name: ereq.Name, Port: ereq.Port, Domain: ereq.Domain, Regex: ereq.Regex, } return service.Response{Body: resp, Status: http.StatusCreated} }
package main import ( "fmt" "sync" "time" ) func main() { var mutex sync.Mutex cond :=sync.Cond{L:&mutex} condition :=false go func() { time.Sleep(1*time.Second) cond.L.Lock() fmt.Println("子goroutine更改条件") condition =true cond.Signal() fmt.Println("子goroutine解锁.....") cond.L.Unlock() }() cond.L.Lock() fmt.Println("main ...已经锁定........") if !condition{ fmt.Println("main ...即将等待........") cond.Wait() fmt.Println("main ...被唤醒........") } fmt.Println("main ...继续........") fmt.Println("main ...解锁........") cond.L.Unlock() }
package db import ( "dev-framework-go/conf" "fmt" "github.com/jinzhu/gorm" "github.com/wonderivan/logger" "strings" ) import _ "github.com/lib/pq" var DBPool *gorm.DB var err error func InitDatabasePool() { psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+ "password=%s dbname=%s sslmode=disable", conf.DB_HOST, conf.DB_PORT, conf.DB_USER, conf.DB_PASS, conf.DB_NAME) DBPool, err = gorm.Open("postgres", psqlInfo) //DBPool, err = sql.Open("postgres", psqlInfo) if err != nil { panic(err) } DBPool.DB().SetMaxIdleConns(conf.DB_MaxIdleConns) DBPool.DB().SetMaxOpenConns(conf.DB_MaxOpenConns) DBPool.LogMode(conf.PG_SQL_PRINT) //DBPool.SetMaxOpenConns(conf.DB_MaxOpenConns) //DBPool.SetMaxIdleConns(conf.DB_MaxIdleConns) //defer dbPool.Close() err = DBPool.DB().Ping() if err != nil { panic(err) } logger.Debug("[INIT DB POOL SUCCESS]") } func SelectSql(table string, select_item []string, condtion map[string]interface{}, orderBy string, limit, offset string) string { sqlstring := "" if select_item == nil { sqlstring = "*" } else { sqlstring = fmt.Sprintf("\"%s\"", strings.Join(select_item, "\",\"")) } var where string sqlstring = fmt.Sprintf("select %s from %s", sqlstring, table) if condtion != nil { where = " WHERE" for k, v := range condtion { where += fmt.Sprintf(" \"%s\"='%v' AND", k, v) } where = where[:len(where)-3] } res := sqlstring + where if orderBy != "" { res += orderBy } if limit != "" { res += fmt.Sprintf(" LIMIT %s", limit) } if offset != "" { res += fmt.Sprintf(" OFFSET %s", offset) } return res } func InsertSql(table string, insert_item map[string]interface{}) string { var insertKey string var insertValue string for k, v := range insert_item { insertKey += fmt.Sprintf("\"%s\",", k) insertValue += fmt.Sprintf("'%v',", v) } insertKey = fmt.Sprintf("(%s)", insertKey[:len(insertKey)-1]) fmt.Println(insertKey) fmt.Println(insertValue) sqlstring := fmt.Sprintf("INSERT INTO %s%s VALUES(%s)", table, insertKey, insertValue[:len(insertValue)-1]) return sqlstring } func UpdateSql(table string, update_item map[string]interface{}, condtion map[string]interface{}) string { var updateStr string for k, v := range update_item { updateStr += fmt.Sprintf("\"%s\"='%v',", k, v) } sqlstring := fmt.Sprintf("UPDATE %s SET %s", table, updateStr[:len(updateStr)-1]) if condtion != nil { var cond string for k, v := range condtion { cond += fmt.Sprintf(" \"%s\"='%v' AND", k, v) } sqlstring += fmt.Sprintf(" WHERE %s", cond[:len(cond)-3]) } return sqlstring }
package datastore import ( "github.com/jinzhu/gorm" "github.com/taniwhy/mochi-match-rest/domain/models" "github.com/taniwhy/mochi-match-rest/domain/repository" ) type roomDatastore struct { db *gorm.DB } // NewRoomDatastore : UserPersistenseを生成. func NewRoomDatastore(db *gorm.DB) repository.RoomRepository { return &roomDatastore{db} } func (rD roomDatastore) FindAllRoom() ([]*models.Room, error) { rooms := []*models.Room{} err := rD.db.Find(&rooms).Error if err != nil { return nil, err } return rooms, nil } func (rD roomDatastore) FindRoomByID(id int64) (*models.Room, error) { room := models.Room{ID: id} err := rD.db.Take(&room).Error if err != nil { return nil, err } return &room, nil } func (rD roomDatastore) InsertRoom(room *models.Room) error { return rD.db.Create(room).Error } func (rD roomDatastore) UpdateRoom(room *models.Room) error { return rD.db.Updates(room).Error } func (rD roomDatastore) DeleteRoom(room *models.Room) error { err := rD.db.Take(&room).Error if err != nil { return err } return rD.db.Delete(room).Error }
// cache package bookcache import ( "container/list" "fmt" "time" ) type Lru struct { mp map[string]*list.Element //book_id:pElement lst *list.List //type entry cap int //capacity } type entry struct { //list item key string value string } var cache *Lru = newCache(1000) func newCache(capacity int) *Lru { return &Lru{make(map[string]*list.Element), list.New(), capacity} } func (lru *Lru) get(key string) (val string, ok bool) { //only touch,no move ele, ok := lru.mp[key] if ok { ent := ele.Value.(entry) val = ent.value } return } func (lru *Lru) set(key, val string) { ele, ok := lru.mp[key] if ok { ent := ele.Value.(entry) ent.value = val } } func (lru *Lru) addToFront(key, val string) { //check if exist _, ok := lru.get(key) if ok { lru.moveToFront(key) } else { count := lru.lst.Len() if count >= lru.cap { //full,remove last lru.removeBack() } //add new to front ele := lru.lst.PushFront(entry{key, val}) lru.mp[key] = ele } } func (lru *Lru) moveToFront(key string) { ele, ok := lru.mp[key] if ok { lru.lst.MoveToFront(ele) } } func (lru *Lru) removeBack() { ent := lru.lst.Remove(lru.lst.Back()) delete(lru.mp, ent.(entry).key) } func (lru *Lru) remove(key string) { ele, ok := lru.mp[key] if ok { lru.lst.Remove(ele) delete(lru.mp, key) } } func (lru *Lru) Get(key string) (contents string, err error) { val, ok := lru.get(key) if !ok { //read from disk val, err = ReadFile(key) if err != nil { //not exist return } //cache it lru.addToFront(key, val) } else { //hit,move to front lru.moveToFront(key) } return val, nil } func (lru *Lru) Put(key, val string) (err error) { //write to disk any way err = SaveFile(key, val) if err != nil { return } //catch it lru.addToFront(key, val) //move to top of list return } ////////////////////////////////////////////////////////////////////////// //for concurrent sync const ( READ int = iota WRITE ) type Message struct { Type int //READ or WRITE Value string Key string Error error RespChan chan Message //response channel } var requestChannel = make(chan Message) func NewMessage(typ int) Message { return Message{Type: typ, RespChan: make(chan Message), Error: nil} } func Init(capacity int) { cache = newCache(capacity) } func StartLoop() { go doLoop() } func doLoop() { //waiting at RequestChannel for { msg := <-requestChannel switch msg.Type { case READ: msg.Value, msg.Error = cache.Get(msg.Key) fmt.Printf("msg READ key=%v map=%v, list=%v time=%v\n", msg.Key, len(cache.mp), cache.lst.Len(), time.Now().Unix()) case WRITE: msg.Error = cache.Put(msg.Key, msg.Value) fmt.Printf("msg WRITE key=%v map=%v, list=%v time=%v\n", msg.Key, len(cache.mp), cache.lst.Len(), time.Now().Unix()) } go sendToChannel(msg.RespChan, msg) //return result } } func sendToChannel(ch chan Message, msg Message) { ch <- msg } func SendMessage(msg Message) Message { go sendToChannel(requestChannel, msg) return <-msg.RespChan //waiting result } // //////////////////////////////////////////////////////////////////////////
package types import ( "bytes" "text/template" ) // Template wraps a text template for generating strings type Template struct { template.Template } // ParseTemplate creates a new template from the string func ParseTemplate(s string) (*Template, error) { t := &Template{} err := t.UnmarshalString(s) if err != nil { return nil, err } return t, nil } // MustParseTemplate creates a new template from the string and panics on failiure. func MustParseTemplate(s string) *Template { t, err := ParseTemplate(s) if err != nil { panic(err) } return t } // UnmarshalText parses the template from text func (t *Template) UnmarshalText(text []byte) error { return t.UnmarshalString(string(text)) } // UnmarshalString parses the template from a string func (t *Template) UnmarshalString(s string) error { templ := template.New("template") templ, err := templ.Parse(s) if err != nil { return err } t.Template = *templ return nil } // On performs the template on data func (t *Template) On(data interface{}) (string, error) { buf := new(bytes.Buffer) err := t.Execute(buf, data) if err != nil { return "", err } return string(buf.Bytes()), nil }
package tsmt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00400102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsmt.004.001.02 Document"` Message *ActivityReportSetUpRequestV02 `xml:"ActvtyRptSetUpReq"` } func (d *Document00400102) AddMessage() *ActivityReportSetUpRequestV02 { d.Message = new(ActivityReportSetUpRequestV02) return d.Message } // Scope // The ActivityReportSetUpRequest message is sent by any party involved in a transaction to the matching application. // The ActivityReportSetUpRequest message can be sent to request the reset of the pre-determined time at which the daily production of the activity report should take place. // Usage // This message is sent to the matching application by a bank, in order to set the UTC offset specifying the hour when the matching application will generate every day an activity report covering the last 24 hours and send it. By default, this offset is equal to 0. type ActivityReportSetUpRequestV02 struct { // Identifies the request message. RequestIdentification *iso20022.MessageIdentification1 `xml:"ReqId"` // Specifies the parameters to calculate the local reporting time. UTCOffset *iso20022.UTCOffset1 `xml:"UTCOffset"` } func (a *ActivityReportSetUpRequestV02) AddRequestIdentification() *iso20022.MessageIdentification1 { a.RequestIdentification = new(iso20022.MessageIdentification1) return a.RequestIdentification } func (a *ActivityReportSetUpRequestV02) AddUTCOffset() *iso20022.UTCOffset1 { a.UTCOffset = new(iso20022.UTCOffset1) return a.UTCOffset }
/** *@Author: haoxiongxiao *@Date: 2019/3/25 *@Description: CREATE GO FILE admin */ package admin import ( "bysj/models" "bysj/services" "github.com/kataras/iris" ) type DashBoardController struct { Ctx iris.Context Service *services.DashBoardService Common } func NewDashBoardController() *DashBoardController { return &DashBoardController{Service: services.NewDashBoardService()} } //今日订单成交量 func (this *DashBoardController) PostOrderCount() { count := this.Service.OrderCount() this.ReturnSuccess("data", count) } //新增用户数 func (this *DashBoardController) PostUserCount() { count := this.Service.UserCount() this.ReturnSuccess("data", count) } //今日流水 func (this *DashBoardController) PostAmountFlow() { flow := this.Service.AmountFlow() this.ReturnSuccess("data", flow) } //最近七日订单成交量 func (this *DashBoardController) PostOrderTrend() { var orderVolume []models.OrderVolume this.Service.OrderTrend(&orderVolume) this.ReturnSuccess("data", orderVolume) }
package webdav import ( "encoding/xml" "strings" "time" ) // Allow parsing the last modified time type LastModifiedTime struct { time.Time } // Unmarshal the xml func (lmt *LastModifiedTime) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { value := "" err := d.DecodeElement(&value, &start) if err != nil { return err } parsed, err := time.Parse(time.RFC1123, value) if err != nil { return err } *lmt = LastModifiedTime{parsed} return nil } // The lockentry type type LockEntry struct { Scope LockScope `xml:"lockscope"` Type LockType `xml:"locktype"` } // The lockscope type type LockScope struct { Exclusive *string `xml:"exclusive"` Shared *string `xml:"shared"` } // Return true if this LockScope is exclusive func (scope *LockScope) IsExclusive() bool { return scope.Exclusive != nil } // Return true if this LockScope is shared func (scope *LockScope) IsShared() bool { return scope.Shared != nil } // The locktype type type LockType struct { Read *string `xml:"read"` Write *string `xml:"write"` } // Return true if this LockType is read func (scope *LockType) IsRead() bool { return scope.Read != nil } // Return true if this LockType is write func (scope *LockType) IsWrite() bool { return scope.Write != nil } // The multistatus type type MultiStatus struct { Responses []Response `xml:"response"` } // Create a new MultiStatus instance from the given data func NewMultiStatusFromData(data []byte) (*MultiStatus, error) { ms := &MultiStatus{} err := xml.Unmarshal(data, ms) if err != nil { return nil, err } return ms, nil } // The propstat type type PropStat struct { Props []Prop `xml:"prop"` Status string `xml:"status"` } // The prop type type Prop struct { ContentLength uint64 `xml:"getcontentlength"` CreationDate time.Time `xml:"creationdate"` Etag string `xml:"getetag"` Executable bool `xml:"executable"` LastModified LastModifiedTime `xml:"getlastmodified"` ResourceType ResourceType `xml:"resourcetype"` SupportedLock SupportedLock `xml:"supportedlock"` } // The resourcetype type type ResourceType struct { Collection *string `xml:"collection"` } // Return true if this ResourceType is a collection func (rt *ResourceType) IsCollection() bool { return rt.Collection != nil } // The response type type Response struct { Href string `xml:"href"` PropStat PropStat `xml:"propstat"` } // Return the location for this Response func (res *Response) Location(base string) string { return strings.Replace(res.Href, base, "", 1) } // The supportedlock type type SupportedLock struct { LockEntries []LockEntry `xml:"lockentry"` }
package keeper import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/fadeev/files/x/files/types" ) func (k Keeper) CreateClaim(ctx sdk.Context, claim types.Claim) { store := ctx.KVStore(k.storeKey) key := []byte(types.ClaimPrefix + claim.Proof) value := k.cdc.MustMarshalBinaryLengthPrefixed(claim) store.Set(key, value) } func (k Keeper) DeleteClaim(ctx sdk.Context, claim types.Claim) { store := ctx.KVStore(k.storeKey) key := []byte(types.ClaimPrefix + claim.Proof) store.Delete(key) } func listClaim(ctx sdk.Context, k Keeper) ([]byte, error) { var claimList []types.Claim store := ctx.KVStore(k.storeKey) iterator := sdk.KVStorePrefixIterator(store, []byte(types.ClaimPrefix)) for ; iterator.Valid(); iterator.Next() { var claim types.Claim k.cdc.MustUnmarshalBinaryLengthPrefixed(store.Get(iterator.Key()), &claim) claimList = append(claimList, claim) } res := codec.MustMarshalJSONIndent(k.cdc, claimList) return res, nil } func (k Keeper) GetClaim(ctx sdk.Context, claim types.Claim) (types.Claim, error) { store := ctx.KVStore(k.storeKey) byteKey := []byte(types.ClaimPrefix + claim.Proof) err := k.cdc.UnmarshalBinaryLengthPrefixed(store.Get(byteKey), &claim) if err != nil { return claim, err } return claim, nil }
package models // github.com/growlog/things-server/internal/models import ( "database/sql" "fmt" // "github.com/growlog/things-server/internal/utils" ) type TimeSeriesDatum struct { Id int64 `db:"id"` TenantId int64 `db:"tenant_id"` SensorId int64 `db:"sensor_id"` Value float64 `db:"value"` Timestamp int64 `db:"timestamp"` } // Special Thanks: // * https://jmoiron.github.io/sqlx/ // * http://wysocki.in/golang-sqlx/ /** * Function will create the `data` table in the database. */ func (dal *DataAccessLayer) CreateTimeSeriesDatumTable(dropExistingTable bool) { if dropExistingTable { drop_stmt := "DROP TABLE data;" results, err := dal.db.Exec(drop_stmt) if err != nil { fmt.Println("TimeSeriesDatum table dropped with error:", results, err) } else { fmt.Println("TimeSeriesDatum table dropped and re-created") } } // Special thanks: // * http://www.postgresqltutorial.com/postgresql-create-table/ // * https://www.postgresql.org/docs/9.5/datatype.html stmt := `CREATE TABLE data ( id bigserial PRIMARY KEY, tenant_id bigint NOT NULL, sensor_id BIGINT NOT NULL, value FLOAT NULL, timestamp BIGINT NOT NULL, unique (tenant_id, sensor_id, timestamp) );` results, err := dal.db.Exec(stmt) if err != nil { fmt.Println("TimeSeriesDatum Model", results, err) } return } /** * Function will return the `thing` struct if it exists in the database or * return an error. */ func (dal *DataAccessLayer) GetTimeSeriesDatumByTenantIdAndCreatedAt(tenantId int64, timestamp int64) (*TimeSeriesDatum, error) { thing := TimeSeriesDatum{} // The struct which will be populated from the database. // DEVELOPERS NOTE: // (1) Lookup the thing based on the id. // (2) PostgreSQL uses an enumerated $1, $2, etc bindvar syntax err := dal.db.Get(&thing, "SELECT * FROM data WHERE timestamp = $1 AND tenant_id = $2", timestamp, tenantId) // Handling non existing item if err == sql.ErrNoRows { return nil, nil } else if err != nil { return nil, err } return &thing, nil } /** * Function will create a thing, if validation passess, and reutrns the `thing` * struct else returns the error. */ func (dal *DataAccessLayer) CreateTimeSeriesDatum(tenantId int64, sensorId int64, value float64, timestamp int64) (*TimeSeriesDatum, error) { // Step 1: Generate SQL statement for creating a new `user` in `postgres`. statement := `INSERT INTO data (tenant_id, sensor_id, value, timestamp) VALUES ($1, $2, $3, $4)` // Step 2: Execute our SQL statement and either return our new user or // our error. _, err := dal.db.Exec(statement, tenantId, sensorId, value, timestamp) if err != nil { return nil, err } // Step 3: return dal.GetTimeSeriesDatumByTenantIdAndCreatedAt(tenantId, timestamp) }