code
stringlengths
67
15.9k
labels
listlengths
1
4
package main import ( "MyTest/EmployeeTestpb" "MyTest/TrZeroMQMsgpb" "fmt" "github.com/golang/protobuf/proto" zmq "github.com/pebbe/zmq4" ) func main() { zctx, _ := zmq.NewContext() s, _ := zctx.NewSocket(zmq.REP) s.Bind("tcp://*:9527") for { // Wait for next request from client msg, _ := s.Recv(0) //log.Printf("Recieved %s\n", msg) // Do some 'work' //time.Sleep(time.Second * 1) topData := &TrZeroMQMsgpb.TopData{} proto.Unmarshal([]byte(msg), topData) if topData.GetType() == "Employee" { theData := &EmployeeTestpb.Employee{} proto.Unmarshal(topData.GetRawData(), theData) fmt.Println(theData.GetId(), theData.GetAge(), theData.GetName()) } // Send reply back to client s.Send("World", 0) } }
[ 3 ]
package main import ( "bufio" "bytes" "flag" "fmt" "log" "os" "regexp" "strings" "sync" ) // Configuration var leet_dict string var wordlist_file string var verbose bool var show_help bool // In-Memory Storage var dictionary map[string][]string var regex_wordlist []regexp.Regexp // Parallelism var wg sync.WaitGroup // Convert word to match using dictionary func wordToRegex(word string) string { var result bytes.Buffer word = strings.TrimSpace(word) lower := strings.ToLower(word) upper := strings.ToUpper(word) result.WriteString("(") result.WriteString(lower) result.WriteString("|") result.WriteString(upper) // Add additional parts here! result.WriteString("|") result.WriteString("(") for _, c := range word { var possible_matches_char []string possible_matches_char = append(possible_matches_char, string(c)) if string(c) == strings.ToUpper(string(c)) { possible_matches_char = append(possible_matches_char, strings.ToLower(string(c))) } else { possible_matches_char = append(possible_matches_char, strings.ToUpper(string(c))) } for _, item := range dictionary[string(c)] { if len(item) < 1 { continue } if verbose { fmt.Printf("\t%s\n", item) } r := strings.NewReplacer( "[", "\\[", "]", "\\]", "\\", "[\\\\]", "|", "\\|", "(", "\\(", ")", "\\)", "}", "\\}", "{", "\\{", "+", "\\+", "*", "\\*", ) item = r.Replace(item) possible_matches_char = append(possible_matches_char, item) } result.WriteString("(") result.WriteString(strings.Join(possible_matches_char, "|")) result.WriteString(")") } result.WriteString(")") result.WriteString(")") return result.String() } /* * Returns true if successful, false with error if not. */ func loadDictionary() (bool, error) { dictionary = make(map[string][]string) f, err := os.Open(leet_dict) if err != nil { return false, err } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { line := scanner.Text() key_val := strings.Split(line, ":") if len(key_val) <= 1 { log.Println(key_val) log.Printf("Can't split `%s` on semicolon. Skipping.\n", line) continue } possible_repls := strings.Split(key_val[1], ",") // Trim all words for i, v := range possible_repls { possible_repls[i] = strings.TrimSpace(v) } if verbose { fmt.Printf("Adding %s:%s\n", key_val[0], strings.Join(possible_repls, ",")) } // Store upper and lowercase, just in case. :p dictionary[strings.ToUpper(key_val[0])] = possible_repls dictionary[strings.ToLower(key_val[0])] = possible_repls } return true, nil } /* * Returns true if successful, false with error if not. */ func loadWordlist() (bool, error) { regex_wordlist = []regexp.Regexp{} // Use dictionary to generate list of regexes for matching replacements f, err := os.Open(wordlist_file) if err != nil { return false, err } defer f.Close() wordscanner := bufio.NewScanner(f) for wordscanner.Scan() { word := wordscanner.Text() // Skip empty lines if len(word) == 0 { continue } word = wordToRegex(word) if verbose { fmt.Printf("Adding regex:%s\n", word) } word_regex := regexp.MustCompile(word) regex_wordlist = append(regex_wordlist, *word_regex) } return true, nil } func printHighlight(line string, subword string) { loc := strings.Index(line, subword) if loc == -1 { log.Printf("Error, %s not in %s\n", subword, line) return } fmt.Printf("%s", line[:loc]) fmt.Printf("\x1B[31m%s\x1B[0m", subword) fmt.Printf("%s", line[loc+len(subword):]) fmt.Println() } func readLoop() { scanIn := bufio.NewScanner(os.Stdin) onlyalpha := regexp.MustCompile("[A-Za-z]+") for scanIn.Scan() { line := scanIn.Text() // Skip empty lines if len(line) == 0 { continue } for _, regex := range regex_wordlist { matches := regex.FindAll([]byte(line), -1) if len(matches) > 0 { for _, match := range matches { alpha_text := onlyalpha.Find(match) if alpha_text != nil && string(alpha_text) == string(match) { // Skip if not 1337 speak. continue } printHighlight(line, string(match)) } } } } } func init() { flag.StringVar(&leet_dict, "d", "list.dict", "Detection dictionary.") flag.StringVar(&wordlist_file, "w", "words.txt", "Wordlist to detect on.") flag.BoolVar(&verbose, "v", false, "Verbose mode.") flag.BoolVar(&show_help, "h", false, "Show help menu.") } func main() { flag.Parse() if show_help { flag.PrintDefaults() return } loadDictionary() fmt.Printf("Dict size:%d\n", len(dictionary)) loadWordlist() fmt.Printf("Wordlist size:%d\n", len(regex_wordlist)) readLoop() }
[ 6 ]
package jwt // // // // *************************** *************************** ********* ************************ // ***************************** ****************************** ********* ************************* // ***************************** ******************************* ********* ************************* // ********* ********* ******* ********* ********* // ******** ********* ******** ********* ******** // ******** ****************** ********* ********************* ********* ********* // ******** ***************** ********* ******************** ********* ******** // ******** **************** ********* **************** ********* ********* // ******** ********* ******** ********* ******** // ********* ********* ****** ********* ********* // ****************************** ********* ******* ********* ************************* // **************************** ********* ******* ********* ************************* // ************************** ********* ****** ********* ********************* // // import ( "errors" jwt "github.com/dgrijalva/jwt-go" "github.com/go-redis/redis" "go-blog/common" "time" ) const ( jwtIss = "" jwtAudience = "" jwtJti = "" jwtSecretKey = "EricBlog:" jwtTokenKey = "login:token:" jwtTokenLife = 3 ) type Param struct { DefaultIss string DefaultAudience string DefaultJti string SecretKey string TokenKey string TokenLife time.Duration RedisCache *redis.Client } func (jp *Param) SetTokenKey(tk string) func(jp *Param) interface{} { return func(jp *Param) interface{} { i := jp.TokenKey jp.TokenKey = tk return i } } func (jp *Param) SetTokenLife(tl time.Duration) func(jp *Param) interface{} { return func(jp *Param) interface{} { i := jp.TokenLife jp.TokenLife = tl return i } } func (jp *Param) SetDefaultIss(iss string) func(jp *Param) interface{} { return func(jp *Param) interface{} { i := jp.DefaultIss jp.DefaultIss = iss return i } } func (jp *Param) SetDefaultAudience(ad string) func(jp *Param) interface{} { return func(jp *Param) interface{} { i := jp.DefaultAudience jp.DefaultAudience = ad return i } } func (jp *Param) SetDefaultJti(jti string) func(jp *Param) interface{} { return func(jp *Param) interface{} { i := jp.DefaultJti jp.DefaultJti = jti return i } } func (jp *Param) SetDefaultSecretKey(sk string) func(jp *Param) interface{} { return func(jp *Param) interface{} { i := jp.SecretKey jp.SecretKey = sk return i } } func (jp *Param) SetRedisCache(rc *redis.Client) func(jp *Param) interface{} { return func(jp *Param) interface{} { i := jp.RedisCache jp.RedisCache = rc return i } } var jwtParam *Param func (jp *Param) JwtInit(options ...func(jp *Param) interface{}) error { q := &Param{ DefaultJti: jwtJti, DefaultAudience: jwtAudience, DefaultIss: jwtIss, SecretKey: jwtSecretKey, TokenLife: jwtTokenLife, TokenKey: jwtTokenKey, } for _, option := range options { option(q) } jwtParam = q return nil } func CreateToken(userIdString string) (token string, err error) { // iss: jwt签发者 // sub: jwt所面向的用户 // aud: 接收jwt的一方 // exp: jwt的过期时间,这个过期时间必须要大于签发时间 // nbf: 定义在什么时间之前,该jwt都是不可用的. // iat: jwt的签发时间 // jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击。 tk := jwt.New(jwt.SigningMethodHS256) claims := make(jwt.MapClaims) //claims["exp"] = time.Now().Add(time.Hour * time.Duration(72)).Unix() claims["iat"] = time.Now().Unix() claims["iss"] = jwtParam.DefaultIss claims["sub"] = userIdString claims["aud"] = jwtParam.DefaultAudience claims["jti"] = common.Md5(jwtParam.DefaultJti + jwtParam.DefaultIss) tk.Claims = claims SecretKey := jwtParam.SecretKey tokenString, err := tk.SignedString([]byte(SecretKey)) if err != nil { return "", err } err = jwtParam.RedisCache.Set(jwtParam.TokenKey+userIdString, tokenString, jwtParam.TokenLife).Err() if err != nil { return "", err } return tokenString, nil } func ParseToken(myToken string) (userId string, err error) { token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) { return []byte(jwtParam.SecretKey), nil }) if err != nil { return "", err } if !token.Valid { return "", err } claims := token.Claims.(jwt.MapClaims) sub, ok := claims["sub"].(string) if !ok { return "", errors.New("claims duan yan is error") } res, err := jwtParam.RedisCache.Get(jwtParam.TokenKey + sub).Result() if err != nil { return "", err } if res == "" || res != myToken { return "", errors.New("token is invalid") } //refresh the token life time err = jwtParam.RedisCache.Set(jwtParam.TokenKey+sub, myToken, jwtParam.TokenLife).Err() if err != nil { return "", err } return sub, nil } func UnsetToken(myToken string) (bool, error) { token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) { return []byte(jwtParam.SecretKey), nil }) if err != nil { return false, err } claims := token.Claims.(jwt.MapClaims) sub, ok := claims["sub"].(string) if !ok { return false, errors.New("claims duan yan is error") } err = jwtParam.RedisCache.Del(jwtParam.TokenKey + sub).Err() if err != nil { return false, err } return true, nil }
[ 3 ]
package token import ( "encoding/json" "io/ioutil" "net/http" "time" ) var api = "https://api.hititbet1000.com:2053/api/v1/token" type ApiResponse struct { Token struct { Token string `json:"token"` ClientId string `json:"clientId"` } } var tokenResponse *ApiResponse var lastSync time.Time func GetToken() (*ApiResponse, error) { elapsed := time.Since(lastSync) if 10*time.Second > elapsed && tokenResponse != nil { return tokenResponse, nil } req, createError := http.NewRequest(http.MethodGet, api, nil) if createError != nil { return nil, createError } req.Header.Add("x-hititbet-aboutme", "ec983929-6dfa-4a01-a0ff-4c31616d3671") req.Header.Add("x-hititbet-locale", "en") req.Header.Add("referer", "https://hititbet47.com/") req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36") client := &http.Client{} response, callErr := client.Do(req) if callErr != nil { return nil, callErr } defer response.Body.Close() apiResp := &ApiResponse{} bytes, _ := ioutil.ReadAll(response.Body) _ = json.Unmarshal(bytes, &apiResp) lastSync = time.Now() tokenResponse = apiResp //log.Println("Token cache flushed") return apiResp, callErr }
[ 3 ]
package main import ( "fmt" ) func main() { //Delcare a slice called myCourses //slice of strings w/ length of 5 and a capacity of 10 //mySlice := make([]int, 1, 4) //gets init with zero values mySlice := []int{1, 2, 3, 4, 5} //gets init with zero values //myCourses := []string{"Docker", "Puppet", "Python"} fmt.Println(mySlice) fmt.Printf("Length is %d. \nCapacity is: %d\n", len(mySlice), cap(mySlice)) //for i := 1; i < 17; i++ { // mySlice = append(mySlice, i) // fmt.Printf("\nCapacity is: %d", cap(mySlice)) //} for _, i := range mySlice { fmt.Println("for range loop:", i) } newSlice := []int{10, 20, 30} mySlice = append(mySlice, newSlice...) //this appends all the elements to the slice fmt.Println(mySlice) }
[ 3 ]
package main import ( "database/sql" "encoding/json" "fmt" "net/http" "github.com/gorilla/mux" _ "github.com/lib/pq" ) const ( host = "localhost" port = 5432 user = "clothes" password = "clothes" dbname = "clothes" ) var db *sql.DB type Cloth struct { ID string `json:"id"` Type string `json:"type"` Colour string `json:"colour"` Fit string `json:"fit"` Owner string `json:"owner"` } // var data = []Cloth{ // Cloth{ID: "1", Type: "Blouse", Colour: "Blue", Fit: "Tight", Owner: "Michaila"}, // Cloth{ID: "2", Type: "Blouse", Colour: "White", Fit: "Loose", Owner: "Maria"}, // Cloth{ID: "3", Type: "Blouse", Colour: "Black", Fit: "Loose", Owner: "Maria"}, // Cloth{ID: "4", Type: "Jeans", Colour: "Blue", Fit: "Tight", Owner: "Michaila"}, // Cloth{ID: "5", Type: "Trousers", Colour: "Beige", Fit: "Tight", Owner: "Katerina"}, // } func getAllClothes(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") rows, err := db.Query("SELECT * FROM clothes") if err != nil { // handle this error better than this panic(err) } defer rows.Close() myRetList := make([]Cloth, 0) for rows.Next() { var cloth = Cloth{} err = rows.Scan(&cloth.ID, &cloth.Type, &cloth.Colour, &cloth.Fit, &cloth.Owner) if err != nil { // handle this error panic(err) } myRetList = append(myRetList, cloth) } bd, _ := json.Marshal(myRetList) w.Write(bd) // get any error encountered during iteration err = rows.Err() if err != nil { panic(err) } } func getClothByID(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") vars := mux.Vars(r) cloth, err := findCloth(vars["id"]) if err != nil { w.WriteHeader(http.StatusNotFound) w.Write([]byte(err.Error())) return } bd, err := json.Marshal(cloth) w.Write(bd) } func findCloth(id string) (Cloth, error) { sqlStatement := `SELECT * FROM clothes WHERE id=$1;` var cloth = Cloth{} row := db.QueryRow(sqlStatement, id) err := row.Scan(&cloth.ID, &cloth.Type, &cloth.Colour, &cloth.Fit, &cloth.Owner) switch err { case sql.ErrNoRows: fmt.Println("No rows were returned!") return Cloth{}, err case nil: return cloth, nil default: return Cloth{}, err } } func deleteCloth(id string) { sqlStatement := `DELETE FROM clothes WHERE id = $1;` _, err := db.Exec(sqlStatement, id) if err != nil { panic(err) } } func deleteClothByID(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") vars := mux.Vars(r) deleteCloth(vars["id"]) w.WriteHeader(http.StatusNoContent) } func updateClothByIDOLD(w http.ResponseWriter, r *http.Request) { u := make(map[string]interface{}) b, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } err = json.Unmarshal(b, &u) if err != nil { panic(err) } vars := mux.Vars(r) strTmpl := `UPDATE clothes SET %s WHERE id = $1;` vals := make([]interface{}, 0) vals = append(vals, vars["id"]) strstr := "" strcomma := "" cntVal := 2 for k, v := range u { fmt.Printf("%v => %v\n", k, v) strstr = strstr + strcomma + fmt.Sprintf("%s=$%d", k, cntVal) //fmt.Sprintf("%s %s %s = $%d", strcomma, strstr, k, cntVal) cntVal = cntVal + 1 strcomma = "," vals = append(vals, v) } fmt.Println(strstr) strQuery := fmt.Sprintf(strTmpl, strstr) fmt.Printf("%s\n%v\n", strQuery, vals) w.WriteHeader(http.StatusOK) } func updateClothByID(w http.ResponseWriter, r *http.Request) { var myCloth = Cloth{} vars := mux.Vars(r) clothID := vars["id"] b, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } u := make(map[string]interface{}) err = json.Unmarshal(b, &u) var requiredFields = []string{"colour", "fit", "type", "owner"} var missingFields = make([]string, 0) allFound := true for _, k := range requiredFields { if _, ok := u[k]; !ok { allFound = false missingFields = append(missingFields, k) } } if !allFound { w.WriteHeader(http.StatusBadRequest) bd := fmt.Sprintf("Missing fields: %v", missingFields) w.Write([]byte(bd)) return } err = json.Unmarshal(b, &myCloth) if err != nil { panic(err) } strSQL := `UPDATE clothes SET type=$1, colour=$2, fit=$3, owner=$4 WHERE id=$5; ` _, err = db.Exec(strSQL, myCloth.Type, myCloth.Colour, myCloth.Fit, myCloth.Owner, clothID) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } cloclo, err := findCloth(clothID) if err != nil { w.WriteHeader(http.StatusNotFound) bdExplain := fmt.Sprintf("Error while retrieving cloth with id %s: %v", clothID, err.Error()) w.Write([]byte(bdExplain)) return } bd, err := json.Marshal(cloclo) w.WriteHeader(http.StatusOK) w.Write(bd) } func main() { psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+"password=%s dbname=%s sslmode=disable", host, port, user, password, dbname) var err error db, err = sql.Open("postgres", psqlInfo) if err != nil { panic(err) } defer db.Close() err = db.Ping() if err != nil { panic(err) } fmt.Println("Successfully connected!") r := mux.NewRouter() r.HandleFunc("/clothes", getAllClothes).Methods("GET") r.HandleFunc("/clothes/{id}", getClothByID).Methods("GET") r.HandleFunc("/clothes/{id}", deleteClothByID).Methods("DELETE") r.HandleFunc("/clothes/{id}", updateClothByID).Methods("PUT") http.ListenAndServe("0.0.0.0:8080", r) }
[ 0, 3 ]
package main import ( "regexp" "fmt" ) const text = ` My email [email protected] My email [email protected] My email [email protected] ` func main() { //simpleRegex() cityName() } func cityName() { test := "http://www.zhenai.com/zhenghun/aba" //test = "http://www.zhenai.com/zhenghun/alashanmeng" var cityPinyinRe = regexp.MustCompile(`http://www.zhenai.com/zhenghun/([^/]+)`) reult := cityPinyinRe.FindStringSubmatch(test) fmt.Println(reult[1]) } func publicRegex() { //regx := `[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+` // ()表示正则提取 regx := `([a-zA-Z0-9]+)@([a-zA-Z0-9]+)(\.[a-zA-Z0-9.]+)` re :=regexp.MustCompile(regx) //match := re.FindString(text) //match := re.FindAllString(text,-1) match := re.FindAllStringSubmatch(text,-1) for _,m := range match { fmt.Println(m) } fmt.Println(match) } func simpleRegex() { testText := `<tr> <td><span class="label">性别:</span><span field="">女</span></td> <td><span class="label">生肖:</span><span field="">蛇</span></td> </tr> <tr>` regx := `<td><span class="label">性别:</span><span field="">([^<]+)</span></td>` re :=regexp.MustCompile(regx) match := re.FindStringSubmatch(testText) fmt.Println(len(match)) for _,m := range match { fmt.Println(m) } }
[ 3 ]
package blocks import ( "bytes" "io" "io/ioutil" "math/rand" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var letters = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") func randBytes(min, max int) []byte { n := rand.Intn(max) + 1 b := make([]byte, n) for i := range b { b[i] = letters[rand.Intn(len(letters))] } return b } func readAll(t *testing.T, r io.Reader) string { b, err := ioutil.ReadAll(r) require.NoError(t, err) return string(b) } func TestBlock(t *testing.T) { tmpDir, err := ioutil.TempDir("", "sequins-test-") require.NoError(t, err, "creating a test tmpdir") bw, err := newBlock(tmpDir, 1, "snappy", 8192) require.NoError(t, err, "initializing a block") err = bw.add([]byte("foo"), []byte("bar")) require.NoError(t, err, "writing a key") err = bw.add([]byte("baz"), []byte("qux")) require.NoError(t, err, "writing a key") block, err := bw.save() require.NoError(t, err, "saving the block") assert.Equal(t, 1, block.Partition, "the partition should be carried through") assert.Equal(t, "foo", string(block.maxKey), "the maxKey should be correct") assert.Equal(t, "baz", string(block.minKey), "the minKey should be correct") record, err := block.get([]byte("foo")) require.NoError(t, err, "fetching reader for 'foo'") assert.NotNil(t, record, "the record should exist") buf := new(bytes.Buffer) _, err = record.WriteTo(buf) assert.NoError(t, err, "WriteTo should work, too") assert.Equal(t, "bar", readAll(t, buf), "fetching value for 'foo'") record, err = block.get([]byte("nonexistent")) require.NoError(t, err, "fetching reader for 'nonexistent'") assert.Nil(t, record, "the record should not exist") res, err := block.Get([]byte("foo")) require.NoError(t, err, "fetching value for 'foo'") assert.Equal(t, "bar", readAll(t, res), "fetching value for 'foo'") res, err = block.Get([]byte("baz")) require.NoError(t, err, "fetching value for 'baz'") assert.Equal(t, "qux", readAll(t, res), "fetching value for 'baz'") // Close the block and load it from the manifest. manifest := block.manifest() require.NotNil(t, manifest, "manifest shouldn't be nil") block.Close() block, err = loadBlock(tmpDir, manifest) require.NoError(t, err, "loading the block from a manifest") assert.Equal(t, 1, block.Partition, "the partition should be loaded") assert.Equal(t, "foo", string(block.maxKey), "the maxKey should be loaded") assert.Equal(t, "baz", string(block.minKey), "the minKey should be loaded") res, err = block.Get([]byte("foo")) require.NoError(t, err, "fetching value for 'foo'") assert.Equal(t, "bar", readAll(t, res), "fetching value for 'foo'") res, err = block.Get([]byte("baz")) require.NoError(t, err, "fetching value for 'baz'") assert.Equal(t, "qux", readAll(t, res), "fetching value for 'baz'") } func TestBlockParallelReads(t *testing.T) { if testing.Short() { t.Skip("skipping block reads test in short mode.") } tmpDir, err := ioutil.TempDir("", "sequins-test-") require.NoError(t, err, "creating a test tmpdir") bw, err := newBlock(tmpDir, 1, "snappy", 8192) require.NoError(t, err, "initializing a block") expected := make([][][]byte, 0, 100) for i := 0; i < cap(expected); i++ { key := randBytes(1, 32) value := randBytes(0, 1024*1024) err := bw.add(key, value) require.NoError(t, err) expected = append(expected, [][]byte{key, value}) } block, err := bw.save() require.NoError(t, err, "saving the block") var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { shuffled := make([][][]byte, len(expected)*5) for i, v := range rand.Perm(len(expected) * 5) { shuffled[v] = expected[i%len(expected)] } for _, record := range shuffled { val, err := block.Get(record[0]) require.NoError(t, err) assert.Equal(t, string(record[1]), readAll(t, val)) time.Sleep(time.Duration(rand.Intn(10)) * time.Millisecond) } wg.Done() }() } wg.Wait() }
[ 1 ]
/* Example compress-events shows how to manipulate the xevent package's event queue to compress events that arrive more often than you'd like to process them. This example in particular shows how to compress MotionNotify events, but the same approach could be used to compress ConfigureNotify events. Note that we show the difference between compressed and uncompressed MotionNotify events by displaying two windows that listen for MotionNotify events. The green window compresses them while the red window does not. Hovering over each window will print the x and y positions in each MotionNotify event received. You should notice that the red window lags behind the pointer (particularly if you moved the pointer quickly in and out of the window) while the green window always keeps up, regardless of the speed of the pointer. In each case, we simulate work by sleeping for some amount of time. (The whole point of compressing events is that there is too much work to be done for each event.) Note that when compressing events, you should always make sure that the event you're compressing *ought* to be compressed. For example, with MotionNotify events, if the Event field changes, then it applies to a different window and probably shouldn't be compressed with MotionNotify events for other windows. Finally, compressing events implicitly assumes that the event handler doing the compression is the *only* event handler for a particular (event, window) tuple. If there is more than one event handler for a single (event, window) tuple and one of them does compression, the other will be left out in the cold. (Since the main event loop is subverted and won't process the compressed events in the usual way.) N.B. This functionality isn't included in xgbutil because event compression isn't something that is always desirable, and the conditions under which compression happens can vary. In particular, compressing ConfigureRequest events from the perspective of the window manager can be faulty, since changes to other properties (like WM_NORMAL_HINTS) can change the semantics of a ConfigureRequest event. (i.e., your compression would need to specifically look for events that could change future ConfigureRequest events.) */ package main import ( "fmt" "log" "time" "github.com/BurntSushi/xgb/xproto" "github.com/BurntSushi/xgbutil" "github.com/BurntSushi/xgbutil/xevent" "github.com/BurntSushi/xgbutil/xwindow" ) // workTime is the amount of time to sleep to simulate "work" in response to // MotionNotify events. Increasing this will exacerbate the difference // between the green and red windows. But if you increase it too much, // the red window starts to *really* lag, and you'll probably have to kill // the program. var workTime = 50 * time.Millisecond // newWindow creates a new window that listens to MotionNotify events with // the given backgroundcolor. func newWindow(X *xgbutil.XUtil, color uint32) *xwindow.Window { win, err := xwindow.Generate(X) if err != nil { log.Fatal(err) } err = win.CreateChecked(X.RootWin(), 0, 0, 400, 400, xproto.CwBackPixel|xproto.CwEventMask, color, xproto.EventMaskPointerMotion) if err != nil { log.Fatal(err) } win.Map() return win } // compressMotionNotify takes a MotionNotify event, and inspects the event // queue for any future MotionNotify events that can be received without // blocking. The most recent MotionNotify event is then returned. // Note that we need to make sure that the Event, Child, Detail, State, Root // and SameScreen fields are the same to ensure the same window/action is // generating events. That is, we are only compressing the RootX, RootY, // EventX and EventY fields. // This function is not thread safe, since Peek returns a *copy* of the // event queue---which could be out of date by the time we dequeue events. func compressMotionNotify(X *xgbutil.XUtil, ev xevent.MotionNotifyEvent) xevent.MotionNotifyEvent { // We force a round trip request so that we make sure to read all // available events. X.Sync() xevent.Read(X, false) // The most recent MotionNotify event that we'll end up returning. laste := ev // Look through each event in the queue. If it's an event and it matches // all the fields in 'ev' that are detailed above, then set it to 'laste'. // In which case, we'll also dequeue the event, otherwise it will be // processed twice! // N.B. If our only goal was to find the most recent relevant MotionNotify // event, we could traverse the event queue backwards and simply use // the first MotionNotify we see. However, this could potentially leave // other MotionNotify events in the queue, which we *don't* want to be // processed. So we stride along and just pick off MotionNotify events // until we don't see any more. for i, ee := range xevent.Peek(X) { if ee.Err != nil { // This is an error, skip it. continue } // Use type assertion to make sure this is a MotionNotify event. if mn, ok := ee.Event.(xproto.MotionNotifyEvent); ok { // Now make sure all appropriate fields are equivalent. if ev.Event == mn.Event && ev.Child == mn.Child && ev.Detail == mn.Detail && ev.State == mn.State && ev.Root == mn.Root && ev.SameScreen == mn.SameScreen { // Set the most recent/valid motion notify event. laste = xevent.MotionNotifyEvent{&mn} // We cheat and use the stack semantics of defer to dequeue // most recent motion notify events first, so that the indices // don't become invalid. (If we dequeued oldest first, we'd // have to account for all future events shifting to the left // by one.) defer func(i int) { xevent.DequeueAt(X, i) }(i) } } } // This isn't strictly necessary, but is correct. We should update // xgbutil's sense of time with the most recent event processed. // This is typically done in the main event loop, but since we are // subverting the main event loop, we should take care of it. X.TimeSet(laste.Time) return laste } func main() { X, err := xgbutil.NewConn() if err != nil { log.Fatal(err) } // Create window for receiving compressed MotionNotify events. cwin := newWindow(X, 0x00ff00) // Attach event handler for MotionNotify that compresses events. xevent.MotionNotifyFun( func(X *xgbutil.XUtil, ev xevent.MotionNotifyEvent) { ev = compressMotionNotify(X, ev) fmt.Printf("COMPRESSED: (EventX %d, EventY %d)\n", ev.EventX, ev.EventY) time.Sleep(workTime) }).Connect(X, cwin.Id) // Create window for receiving uncompressed MotionNotify events. uwin := newWindow(X, 0xff0000) // Attach event handler for MotionNotify that does not compress events. xevent.MotionNotifyFun( func(X *xgbutil.XUtil, ev xevent.MotionNotifyEvent) { fmt.Printf("UNCOMPRESSED: (EventX %d, EventY %d)\n", ev.EventX, ev.EventY) time.Sleep(workTime) }).Connect(X, uwin.Id) xevent.Main(X) }
[ 2 ]
package socket import ( "gopkg.in/olahol/melody.v1" "github.com/gin-gonic/gin" "log" "errors" "fmt" ) const ( AUTHENTICATE_MESSAGE = "authenticate" AUTHORIZED_MESSAGE = "authorized" CONNECTED = "connected" DISCONNECTED = "disconnected" ) type Socket struct { m *melody.Melody r *gin.Engine NS map[string]*Namespace } func New(router *gin.Engine) *Socket{ return &Socket{ m : melody.New(), r : router, NS : make(map[string]*Namespace), } } func (s *Socket) Start() { s.r.GET("/ws", func(context *gin.Context) { s.m.HandleRequest(context.Writer, context.Request) }) s.r.GET("/ns/:name/ws", func(context *gin.Context) { s.m.HandleRequest(context.Writer, context.Request) }) s.NS["global"] = NewNameSpace() funcListenHandler := func(ses *melody.Session, byteData []byte) { session := newSession(ses) ns := session.GetNameSpace() namespace := s.NS[ns] if namespace != nil { msg,err := NewMessage(byteData) if err == nil { if namespace.isAuthen && msg.TypeMessage != AUTHENTICATE_MESSAGE{ if _, isAuthorized := session.Get(AUTHORIZED_MESSAGE); !isAuthorized { log.Println("This session need authorized first!") return } } handle, isExist := namespace.h[msg.TypeMessage] if isExist { handle(session, msg.Data) } else { log.Println("Type message does not exist in this namespace! - ", msg.TypeMessage, " - ", ns) } } else { log.Println(err) } } else { log.Println("This namespace does not exist! - ", ns) } } s.m.HandleMessage(funcListenHandler) s.m.HandleMessageBinary(funcListenHandler) s.m.HandleConnect(func(ses *melody.Session) { session := newSession(ses) namespace := session.GetNameSpace() if s.NS[namespace] != nil { if !s.NS[namespace].isAuthen { s.NS[namespace].l = append(s.NS[namespace].l, session) if handleConnected, ok := s.NS[namespace].h[CONNECTED]; ok { handleConnected(session, map[string]interface{}{}) } } } }) s.m.HandleDisconnect(func(ses *melody.Session) { session := newSession(ses) ns := session.GetNameSpace() if s.NS[ns] != nil { index := indexInListSession(session, s.NS[ns].l) if index >= 0 { s.NS[ns].l = append(s.NS[ns].l[:index], s.NS[ns].l[index+1:]...) if handleDisconnected,ok := s.NS[ns].h[DISCONNECTED]; ok { handleDisconnected(session, map[string]interface{}{}) } } } }) } func (s *Socket) AddNameSpace(ns string) { s.NS[ns] = NewNameSpace() } func (s *Socket) AddNameSpaceWithSecret(ns string, secret string) { s.NS[ns] = NewNameSpaceWithSecret(secret) } func (s *Socket) broadcastToList(msg []byte, list []*Session) error { for _, session := range list { if err := session.Write(msg); err != nil { return err } } return nil } func (s *Socket) BroadcastToNs(namespace string, key string, data interface{}) error{ msg := prepareData(key, data) if s.NS[namespace] != nil { return s.broadcastToList(msg, s.NS[namespace].l) } else { return errors.New(fmt.Sprintf("This namespace does not exist! - %s", namespace)) } } func (s *Socket) BroadcastOtherInNs(namespace string, key string, data interface{}, session *Session) error{ msg := prepareData(key, data) if s.NS[namespace] != nil { list := []*Session{} for _, val := range s.NS[namespace].l { if val.Session != session.Session { list = append(list, val) } } return s.broadcastToList(msg, list) } else { return errors.New(fmt.Sprintf("This namespace does not exist! - %s", namespace)) } } func (s *Socket) On(namespace string,key string, handle FuncListen) { if namespace != "" { s.NS[namespace].On(key, handle) } else { for n,_ := range s.NS { s.NS[n].On(key, handle) } } } func indexInListSession(session *Session, list []*Session) int { for i:=0; i < len(list); i ++ { if session == list[i] { return i } } return -1 }
[ 6 ]
package apiserver import ( "encoding/json" "errors" "fmt" "io" "io/ioutil" "log" "net/http" "sync/atomic" "github.com/felixge/httpsnoop" "github.com/gorilla/mux" "github.com/openaustralia/yinyo/pkg/commands" "github.com/openaustralia/yinyo/pkg/integrationclient" "github.com/openaustralia/yinyo/pkg/protocol" ) func (server *Server) createRun(w http.ResponseWriter, r *http.Request) error { createResult, err := server.app.CreateRun(protocol.CreateRunOptions{APIKey: r.URL.Query().Get("api_key")}) if err != nil { if errors.Is(err, integrationclient.ErrNotAllowed) { return newHTTPError(err, http.StatusUnauthorized, err.Error()) } return err } w.Header().Set("Content-Type", "application/json") return json.NewEncoder(w).Encode(createResult) } func (server *Server) getApp(w http.ResponseWriter, r *http.Request) error { runID := mux.Vars(r)["id"] w.Header().Set("Content-Type", "application/gzip") reader, err := server.app.GetApp(runID) if err != nil { // Returns 404 if there is no app if errors.Is(err, commands.ErrNotFound) { return newHTTPError(err, http.StatusNotFound, err.Error()) } return err } _, err = io.Copy(w, reader) return err } func (server *Server) putApp(w http.ResponseWriter, r *http.Request) error { runID := mux.Vars(r)["id"] err := server.app.PutApp(runID, r.Body, r.ContentLength) if errors.Is(err, commands.ErrArchiveFormat) { return newHTTPError(err, http.StatusBadRequest, err.Error()) } return err } func (server *Server) getCache(w http.ResponseWriter, r *http.Request) error { runID := mux.Vars(r)["id"] reader, err := server.app.GetCache(runID) if err != nil { // Returns 404 if there is no cache if errors.Is(err, commands.ErrNotFound) { return newHTTPError(err, http.StatusNotFound, err.Error()) } return err } w.Header().Set("Content-Type", "application/gzip") _, err = io.Copy(w, reader) return err } func (server *Server) putCache(w http.ResponseWriter, r *http.Request) error { runID := mux.Vars(r)["id"] return server.app.PutCache(runID, r.Body, r.ContentLength) } func (server *Server) getOutput(w http.ResponseWriter, r *http.Request) error { runID := mux.Vars(r)["id"] reader, err := server.app.GetOutput(runID) if err != nil { // Returns 404 if there is no output if errors.Is(err, commands.ErrNotFound) { return newHTTPError(err, http.StatusNotFound, err.Error()) } return err } w.Header().Set("Content-Type", "application/octet-stream") _, err = io.Copy(w, reader) return err } func (server *Server) putOutput(w http.ResponseWriter, r *http.Request) error { runID := mux.Vars(r)["id"] return server.app.PutOutput(runID, r.Body, r.ContentLength) } func (server *Server) getExitData(w http.ResponseWriter, r *http.Request) error { runID := mux.Vars(r)["id"] exitData, err := server.app.GetExitData(runID) if err != nil { return err } w.Header().Set("Content-Type", "application/json") enc := json.NewEncoder(w) return enc.Encode(exitData) } func (server *Server) startRun(w http.ResponseWriter, r *http.Request) error { runID := mux.Vars(r)["id"] decoder := json.NewDecoder(r.Body) var options protocol.StartRunOptions err := decoder.Decode(&options) if err != nil { return newHTTPError(err, http.StatusBadRequest, "JSON in body not correctly formatted") } if options.MaxRunTime == 0 { options.MaxRunTime = server.defaultMaxRunTime } else if options.MaxRunTime > server.maxRunTime { return newHTTPError(err, http.StatusBadRequest, fmt.Sprintf("max_run_time should not be larger than %v", server.maxRunTime)) } if options.Memory == 0 { options.Memory = server.defaultMemory } else if options.Memory > server.maxMemory { return newHTTPError(err, http.StatusBadRequest, fmt.Sprintf("memory should not be larger than %v", server.maxMemory)) } env := make(map[string]string) for _, keyvalue := range options.Env { env[keyvalue.Name] = keyvalue.Value } err = server.app.StartRun(runID, server.runDockerImage, options) if errors.Is(err, commands.ErrAppNotAvailable) { err = newHTTPError(err, http.StatusBadRequest, "app needs to be uploaded before starting a run") } else if errors.Is(err, integrationclient.ErrNotAllowed) { err = newHTTPError(err, http.StatusUnauthorized, err.Error()) } return err } func (server *Server) getEvents(w http.ResponseWriter, r *http.Request) error { runID := mux.Vars(r)["id"] lastID := r.URL.Query().Get("last_id") if lastID == "" { lastID = "0" } w.Header().Set("Content-Type", "application/ld+json") flusher, ok := w.(http.Flusher) if !ok { return errors.New("couldn't access the flusher") } events := server.app.GetEvents(runID, lastID) enc := json.NewEncoder(w) for events.More() { e, err := events.Next() if err != nil { return err } err = enc.Encode(e) if err != nil { return err } flusher.Flush() } return nil } func (server *Server) createEvent(w http.ResponseWriter, r *http.Request) error { runID := mux.Vars(r)["id"] // Read json message as is into a string // TODO: Switch over to json decoder buf, err := ioutil.ReadAll(r.Body) if err != nil { return err } // Check the form of the JSON by interpreting it var event protocol.Event err = json.Unmarshal(buf, &event) if err != nil { return newHTTPError(err, http.StatusBadRequest, "JSON in body not correctly formatted") } return server.app.CreateEvent(runID, event) } func (server *Server) delete(w http.ResponseWriter, r *http.Request) error { runID := mux.Vars(r)["id"] return server.app.DeleteRun(runID) } func (server *Server) hello(w http.ResponseWriter, r *http.Request) error { hello := protocol.Hello{ Message: "Hello from Yinyo!", MaxRunTime: protocol.DefaultAndMax{ Default: server.defaultMaxRunTime, Max: server.maxRunTime, }, Memory: protocol.DefaultAndMax{ Default: server.defaultMemory, Max: server.maxMemory, }, Version: server.version, RunnerImage: server.runDockerImage, } w.Header().Set("Content-Type", "application/json") enc := json.NewEncoder(w) return enc.Encode(hello) } // isExternal returns true if the request has arrived via the public internet. This relies // on the requests from the internet coming in via a load balancer (which sets the // X-Forwarded-For header) and internal requests not coming via a load balancer // This is used in measuring network traffic func isExternal(request *http.Request) bool { return request.Header.Get("X-Forwarded-For") != "" } // Middleware that logs the request uri func logRequests(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var source string if isExternal(r) { source = "external" } else { source = "internal" } log.Println(source, r.Method, r.RequestURI) // Call the next handler, which can be another middleware in the chain, or the final handler. next.ServeHTTP(w, r) }) } type readMeasurer struct { rc io.ReadCloser BytesRead int64 } func newReadMeasurer(rc io.ReadCloser) *readMeasurer { return &readMeasurer{rc: rc} } func (r *readMeasurer) Read(p []byte) (n int, err error) { n, err = r.rc.Read(p) atomic.AddInt64(&r.BytesRead, int64(n)) return } func (r *readMeasurer) Close() error { return r.rc.Close() } func (server *Server) recordTraffic(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { runID := mux.Vars(r)["id"] readMeasurer := newReadMeasurer(r.Body) r.Body = readMeasurer m := httpsnoop.CaptureMetrics(next, w, r) if runID != "" && isExternal(r) { err := server.app.ReportAPINetworkUsage(runID, uint64(readMeasurer.BytesRead), uint64(m.Written)) if err != nil { // TODO: Will this actually work here logAndReturnError(err, w) return } } }) } // Middleware function, which will be called for each request // TODO: Refactor checkRunCreated method to return an error func (server *Server) checkRunCreated(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { runID := mux.Vars(r)["id"] created, err := server.app.IsRunCreated(runID) if err != nil { log.Println(err) logAndReturnError(err, w) return } if !created { err = newHTTPError(err, http.StatusNotFound, fmt.Sprintf("run %v: not found", runID)) logAndReturnError(err, w) return } next.ServeHTTP(w, r) }) } func logAndReturnError(err error, w http.ResponseWriter) { log.Println(err) err2, ok := err.(clientError) if !ok { // TODO: Factor out common code with other error handling w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(http.StatusInternalServerError) //nolint:errcheck // ignore error while logging an error //skipcq: GSC-G104 w.Write([]byte(`{"error":"Internal server error"}`)) return } body, err := err2.ResponseBody() if err != nil { log.Println(err) w.WriteHeader(http.StatusInternalServerError) return } status, headers := err2.ResponseHeaders() for k, v := range headers { w.Header().Set(k, v) } w.WriteHeader(status) //nolint:errcheck // ignore error while logging an error //skipcq: GSC-G104 w.Write(body) } type appHandler func(http.ResponseWriter, *http.Request) error // Error handling func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { err := fn(w, r) if err != nil { logAndReturnError(err, w) } } // Server holds the internal state for the server type Server struct { router *mux.Router app commands.App defaultMaxRunTime int64 // If the user doesn't specify the max run time for a run this is what is used maxRunTime int64 // the global maximum run time in seconds that every run can not exceed defaultMemory int64 // If the user doesn't specify memory for a run this is what is used maxMemory int64 // The user can't get memory for a run above this value. Probably limit this to what is schedulable on a single kubernetes worker node runDockerImage string version string } // Initialise the server's state func (server *Server) Initialise(startupOptions *commands.StartupOptions, defaultMaxRunTime, maxRunTime, defaultMemory, maxMemory int64, runDockerImage string, version string) error { app, err := commands.New(startupOptions) if err != nil { return err } server.app = app server.defaultMaxRunTime = defaultMaxRunTime server.maxRunTime = maxRunTime server.defaultMemory = defaultMemory server.maxMemory = maxMemory server.runDockerImage = runDockerImage server.version = version server.InitialiseRoutes() return nil } // InitialiseRoutes sets up the routes func (server *Server) InitialiseRoutes() { server.router = mux.NewRouter().StrictSlash(true) server.router.Handle("/", appHandler(server.hello)) server.router.Handle("/runs", appHandler(server.createRun)).Methods("POST") runRouter := server.router.PathPrefix("/runs/{id}").Subrouter() runRouter.Handle("/app", appHandler(server.getApp)).Methods("GET") runRouter.Handle("/app", appHandler(server.putApp)).Methods("PUT") runRouter.Handle("/cache", appHandler(server.getCache)).Methods("GET") runRouter.Handle("/cache", appHandler(server.putCache)).Methods("PUT") runRouter.Handle("/output", appHandler(server.getOutput)).Methods("GET") runRouter.Handle("/output", appHandler(server.putOutput)).Methods("PUT") runRouter.Handle("/exit-data", appHandler(server.getExitData)).Methods("GET") runRouter.Handle("/start", appHandler(server.startRun)).Methods("POST") runRouter.Handle("/events", appHandler(server.getEvents)).Methods("GET") runRouter.Handle("/events", appHandler(server.createEvent)).Methods("POST") runRouter.Handle("", appHandler(server.delete)).Methods("DELETE") server.router.Use(server.recordTraffic) runRouter.Use(server.checkRunCreated) server.router.Use(logRequests) } // Run runs the server. This blocks until the server quits func (server *Server) Run(addr string) { log.Println("Yinyo is ready and waiting.") log.Fatal(http.ListenAndServe(addr, server.router)) }
[ 6 ]
package k8shandler import ( "reflect" "testing" configv1 "github.com/openshift/api/config/v1" logging "github.com/openshift/cluster-logging-operator/pkg/apis/logging/v1" logforward "github.com/openshift/cluster-logging-operator/pkg/apis/logging/v1alpha1" "github.com/openshift/cluster-logging-operator/pkg/utils" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func TestNewFluentdPodSpecWhenFieldsAreUndefined(t *testing.T) { cluster := &logging.ClusterLogging{} podSpec := newFluentdPodSpec(cluster, "test-app-name", "test-infra-name", nil, logforward.ForwardingSpec{}) if len(podSpec.Containers) != 1 { t.Error("Exp. there to be 1 fluentd container") } resources := podSpec.Containers[0].Resources if resources.Limits[v1.ResourceMemory] != defaultFluentdMemory { t.Errorf("Exp. the default memory limit to be %v", defaultFluentdMemory) } if resources.Requests[v1.ResourceMemory] != defaultFluentdMemory { t.Errorf("Exp. the default memory request to be %v", defaultFluentdMemory) } if resources.Requests[v1.ResourceCPU] != defaultFluentdCpuRequest { t.Errorf("Exp. the default CPU request to be %v", defaultFluentdCpuRequest) } CheckIfThereIsOnlyTheLinuxSelector(podSpec, t) } func TestNewFluentdPodSpecWhenResourcesAreDefined(t *testing.T) { limitMemory := resource.MustParse("100Gi") requestMemory := resource.MustParse("120Gi") requestCPU := resource.MustParse("500m") cluster := &logging.ClusterLogging{ Spec: logging.ClusterLoggingSpec{ Collection: &logging.CollectionSpec{ logging.LogCollectionSpec{ Type: "fluentd", FluentdSpec: logging.FluentdSpec{ Resources: newResourceRequirements("100Gi", "", "120Gi", "500m"), }, }, }, }, } podSpec := newFluentdPodSpec(cluster, "test-app-name", "test-infra-name", nil, logforward.ForwardingSpec{}) if len(podSpec.Containers) != 1 { t.Error("Exp. there to be 1 fluentd container") } resources := podSpec.Containers[0].Resources if resources.Limits[v1.ResourceMemory] != limitMemory { t.Errorf("Exp. the spec memory limit to be %v", limitMemory) } if resources.Requests[v1.ResourceMemory] != requestMemory { t.Errorf("Exp. the spec memory request to be %v", requestMemory) } if resources.Requests[v1.ResourceCPU] != requestCPU { t.Errorf("Exp. the spec CPU request to be %v", requestCPU) } } func TestFluentdPodSpecHasTaintTolerations(t *testing.T) { expectedTolerations := []v1.Toleration{ v1.Toleration{ Key: "node-role.kubernetes.io/master", Operator: v1.TolerationOpExists, Effect: v1.TaintEffectNoSchedule, }, v1.Toleration{ Key: "node.kubernetes.io/disk-pressure", Operator: v1.TolerationOpExists, Effect: v1.TaintEffectNoSchedule, }, } cluster := &logging.ClusterLogging{ Spec: logging.ClusterLoggingSpec{ Collection: &logging.CollectionSpec{ logging.LogCollectionSpec{ Type: "fluentd", }, }, }, } podSpec := newFluentdPodSpec(cluster, "test-app-name", "test-infra-name", nil, logforward.ForwardingSpec{}) if !reflect.DeepEqual(podSpec.Tolerations, expectedTolerations) { t.Errorf("Exp. the tolerations to be %v but was %v", expectedTolerations, podSpec.Tolerations) } } func TestNewFluentdPodSpecWhenSelectorIsDefined(t *testing.T) { expSelector := map[string]string{ "foo": "bar", } cluster := &logging.ClusterLogging{ Spec: logging.ClusterLoggingSpec{ Collection: &logging.CollectionSpec{ logging.LogCollectionSpec{ Type: "fluentd", FluentdSpec: logging.FluentdSpec{ NodeSelector: expSelector, }, }, }, }, } podSpec := newFluentdPodSpec(cluster, "test-app-name", "test-infra-name", nil, logforward.ForwardingSpec{}) if !reflect.DeepEqual(podSpec.NodeSelector, expSelector) { t.Errorf("Exp. the nodeSelector to be %q but was %q", expSelector, podSpec.NodeSelector) } } func TestNewFluentdPodNoTolerations(t *testing.T) { expTolerations := []v1.Toleration{ v1.Toleration{ Key: "node-role.kubernetes.io/master", Operator: v1.TolerationOpExists, Effect: v1.TaintEffectNoSchedule, }, v1.Toleration{ Key: "node.kubernetes.io/disk-pressure", Operator: v1.TolerationOpExists, Effect: v1.TaintEffectNoSchedule, }, } cluster := &logging.ClusterLogging{ Spec: logging.ClusterLoggingSpec{ Collection: &logging.CollectionSpec{ logging.LogCollectionSpec{ Type: "fluentd", FluentdSpec: logging.FluentdSpec{}, }, }, }, } podSpec := newFluentdPodSpec(cluster, "test-app-name", "test-infra-name", nil, logforward.ForwardingSpec{}) tolerations := podSpec.Tolerations if !utils.AreTolerationsSame(tolerations, expTolerations) { t.Errorf("Exp. the tolerations to be %v but was %v", expTolerations, tolerations) } } func TestNewFluentdPodWithTolerations(t *testing.T) { providedToleration := v1.Toleration{ Key: "test", Operator: v1.TolerationOpExists, Effect: v1.TaintEffectNoSchedule, } expTolerations := []v1.Toleration{ providedToleration, v1.Toleration{ Key: "node-role.kubernetes.io/master", Operator: v1.TolerationOpExists, Effect: v1.TaintEffectNoSchedule, }, v1.Toleration{ Key: "node.kubernetes.io/disk-pressure", Operator: v1.TolerationOpExists, Effect: v1.TaintEffectNoSchedule, }, } cluster := &logging.ClusterLogging{ Spec: logging.ClusterLoggingSpec{ Collection: &logging.CollectionSpec{ logging.LogCollectionSpec{ Type: "fluentd", FluentdSpec: logging.FluentdSpec{ Tolerations: []v1.Toleration{ providedToleration, }, }, }, }, }, } podSpec := newFluentdPodSpec(cluster, "test-app-name", "test-infra-name", nil, logforward.ForwardingSpec{}) tolerations := podSpec.Tolerations if !utils.AreTolerationsSame(tolerations, expTolerations) { t.Errorf("Exp. the tolerations to be %v but was %v", expTolerations, tolerations) } } func TestNewFluentdPodSpecWhenProxyConfigExists(t *testing.T) { cluster := &logging.ClusterLogging{} httpproxy := "http://[email protected]/3128/" noproxy := ".cluster.local,localhost" trustedca := "user-ca-bundle" podSpec := newFluentdPodSpec(cluster, "test-app-name", "test-infra-name", &configv1.Proxy{ TypeMeta: metav1.TypeMeta{ Kind: "Proxy", APIVersion: "config.openshift.io/v1", }, Spec: configv1.ProxySpec{ HTTPProxy: httpproxy, HTTPSProxy: httpproxy, TrustedCA: configv1.ConfigMapNameReference{ Name: trustedca, }, }, Status: configv1.ProxyStatus{ HTTPProxy: httpproxy, HTTPSProxy: httpproxy, NoProxy: noproxy, }, }, logforward.ForwardingSpec{}, ) if len(podSpec.Containers) != 1 { t.Error("Exp. there to be 1 fluentd container") } checkProxyEnvVar(t, podSpec, "HTTP_PROXY", httpproxy) checkProxyEnvVar(t, podSpec, "HTTPS_PROXY", httpproxy) checkProxyEnvVar(t, podSpec, "NO_PROXY", noproxy) checkProxyVolumesAndVolumeMounts(t, podSpec, trustedca) } func checkProxyEnvVar(t *testing.T, podSpec v1.PodSpec, name string, value string) { env := podSpec.Containers[0].Env found := false for _, elem := range env { if elem.Name == name { found = true if elem.Value != value { t.Errorf("EnvVar %s: expected %s, actual %s", name, value, elem.Value) } } } if !found { t.Errorf("EnvVar %s not found", name) } } func checkProxyVolumesAndVolumeMounts(t *testing.T, podSpec v1.PodSpec, trustedca string) { name := "proxytrustedca" volumes := podSpec.Volumes found := false for _, elem := range volumes { if elem.Name == name { found = true if elem.VolumeSource.Secret.SecretName != trustedca { t.Errorf("Volume %s: expected %s, actual %s", name, trustedca, elem.VolumeSource.Secret.SecretName) } } } if !found { t.Errorf("Volume %s not found", name) } volumemounts := podSpec.Containers[0].VolumeMounts value := "/etc/fluent/proxy" found = false for _, elem := range volumemounts { if elem.Name == name { found = true if elem.MountPath != value { t.Errorf("VolumeMounts %s: expected %s, actual %s", name, value, elem.MountPath) } } } if !found { t.Errorf("VolumeMounts %s not found", name) } }
[ 6 ]
// Code generated by mockery v2.9.4. DO NOT EDIT. package mocks import ( activities "aprian1337/thukul-service/business/activities" context "context" mock "github.com/stretchr/testify/mock" ) // Usecase is an autogenerated mock type for the Usecase type type Usecase struct { mock.Mock } // Create provides a mock function with given fields: ctx, domain, pocketId func (_m *Usecase) Create(ctx context.Context, domain activities.Domain, pocketId int) (activities.Domain, error) { ret := _m.Called(ctx, domain, pocketId) var r0 activities.Domain if rf, ok := ret.Get(0).(func(context.Context, activities.Domain, int) activities.Domain); ok { r0 = rf(ctx, domain, pocketId) } else { r0 = ret.Get(0).(activities.Domain) } var r1 error if rf, ok := ret.Get(1).(func(context.Context, activities.Domain, int) error); ok { r1 = rf(ctx, domain, pocketId) } else { r1 = ret.Error(1) } return r0, r1 } // Delete provides a mock function with given fields: ctx, id, pocketId func (_m *Usecase) Delete(ctx context.Context, id int, pocketId int) error { ret := _m.Called(ctx, id, pocketId) var r0 error if rf, ok := ret.Get(0).(func(context.Context, int, int) error); ok { r0 = rf(ctx, id, pocketId) } else { r0 = ret.Error(0) } return r0 } // GetById provides a mock function with given fields: ctx, pocketId, id func (_m *Usecase) GetById(ctx context.Context, pocketId int, id int) (activities.Domain, error) { ret := _m.Called(ctx, pocketId, id) var r0 activities.Domain if rf, ok := ret.Get(0).(func(context.Context, int, int) activities.Domain); ok { r0 = rf(ctx, pocketId, id) } else { r0 = ret.Get(0).(activities.Domain) } var r1 error if rf, ok := ret.Get(1).(func(context.Context, int, int) error); ok { r1 = rf(ctx, pocketId, id) } else { r1 = ret.Error(1) } return r0, r1 } // GetList provides a mock function with given fields: ctx, pocketId func (_m *Usecase) GetList(ctx context.Context, pocketId int) ([]activities.Domain, error) { ret := _m.Called(ctx, pocketId) var r0 []activities.Domain if rf, ok := ret.Get(0).(func(context.Context, int) []activities.Domain); ok { r0 = rf(ctx, pocketId) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]activities.Domain) } } var r1 error if rf, ok := ret.Get(1).(func(context.Context, int) error); ok { r1 = rf(ctx, pocketId) } else { r1 = ret.Error(1) } return r0, r1 } // GetTotal provides a mock function with given fields: ctx, userId, pocketId, kind func (_m *Usecase) GetTotal(ctx context.Context, userId int, pocketId int, kind string) (int64, error) { ret := _m.Called(ctx, userId, pocketId, kind) var r0 int64 if rf, ok := ret.Get(0).(func(context.Context, int, int, string) int64); ok { r0 = rf(ctx, userId, pocketId, kind) } else { r0 = ret.Get(0).(int64) } var r1 error if rf, ok := ret.Get(1).(func(context.Context, int, int, string) error); ok { r1 = rf(ctx, userId, pocketId, kind) } else { r1 = ret.Error(1) } return r0, r1 } // Update provides a mock function with given fields: ctx, domain, pocketId, id func (_m *Usecase) Update(ctx context.Context, domain activities.Domain, pocketId int, id int) (activities.Domain, error) { ret := _m.Called(ctx, domain, pocketId, id) var r0 activities.Domain if rf, ok := ret.Get(0).(func(context.Context, activities.Domain, int, int) activities.Domain); ok { r0 = rf(ctx, domain, pocketId, id) } else { r0 = ret.Get(0).(activities.Domain) } var r1 error if rf, ok := ret.Get(1).(func(context.Context, activities.Domain, int, int) error); ok { r1 = rf(ctx, domain, pocketId, id) } else { r1 = ret.Error(1) } return r0, r1 }
[ 4, 6 ]
// +build unit package util import ( "net" "net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/assert" ) // transport for testing, using easy to spot values var testTransport http.RoundTripper = &http.Transport{ DialContext: (&net.Dialer{ Timeout: 7 * time.Second, KeepAlive: 7 * time.Second, DualStack: false, }).DialContext, MaxIdleConns: 7, IdleConnTimeout: 7 * time.Second, TLSHandshakeTimeout: 7 * time.Second, ExpectContinueTimeout: 7 * time.Second, } func TestGetClient(t *testing.T) { t.Parallel() // verify that default client timeout is correct myClient := GetClient() assert.Equal(t, time.Duration(getIntFromEnv("DEFAULT_HTTP_REQUEST_TIMEOUT", 30))*time.Second, myClient.Timeout) // verify that it times out properly timeoutClient := GetClientWithTimeout(3 * time.Second) assert.Equal(t, 3*time.Second, timeoutClient.Timeout) handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(10 * time.Second) w.WriteHeader(http.StatusOK) }) backend := httptest.NewServer(handlerFunc) response, err := timeoutClient.Get(backend.URL) if err == nil { defer response.Body.Close() t.Error("Request should have timed out") } else if err, ok := err.(net.Error); ok && !err.Timeout() { t.Errorf("Error making request to test server: %s", err.Error()) } // verify using custom Transport customClient := GetCustomClient(testTransport, 7) assert.Equal(t, 7*time.Second, customClient.Timeout) //assert.Equal(t, customClient.Transport.(http.Transport).MaxIdleConns, 7) response, err = customClient.Get(backend.URL) if err == nil { defer response.Body.Close() t.Error("Request should have timed out") } else if err, ok := err.(net.Error); ok && !err.Timeout() { t.Errorf("Error making request to test server: %s", err.Error()) } // sanity check assert.NotEqual(t, http.Client{}, myClient) assert.NotEqual(t, http.Client{}.Timeout, myClient.Timeout) assert.NotEqual(t, http.Client{}.Timeout, timeoutClient.Timeout) assert.NotEqual(t, http.Client{}.Timeout, customClient.Timeout) assert.NotEqual(t, myClient.Timeout, timeoutClient.Timeout) assert.NotEqual(t, myClient.Timeout, customClient.Timeout) assert.NotEqual(t, customClient.Timeout, timeoutClient.Timeout) myClient2 := GetClient() assert.Equal(t, myClient, myClient2) }
[ 3 ]
package Models import ( "github.com/gocql/gocql" "golang.org/x/crypto/bcrypt" "snap/Database/Cassandra" "time" ) type Driver struct { Name string `cql:"name"` Lastname string `cql:"lastname"` Vehicle_no string `cql:"vehicle_no"` Balance int `cql:"Balance"` Profile_pic string `cql:"profile_pic"` } type User struct { Cassandra.TableMetaData Id gocql.UUID Phone string Password string Balance int Driver_details Driver Created_at time.Time } var Users = User{ TableMetaData: Cassandra.TableMetaData{ Table: "users", Columns: map[string]struct{}{ "id": {}, "phone": {}, "balance": {}, "driver_details": {}, "created_at": {}, }, Pk: map[string]struct{}{"id": {}}, Keyspace: "snap", }, } func (u User) GetDriverDetails(conditions map[string]interface{}) (user User, err error) { statement := u.GetSelectStatement(conditions, []string{"Id", "Driver_details"}) err = statement.Scan(&user.Id, &user.Driver_details) return } func (u User) NewUser(user User) error { usr := map[string]interface{}{} password, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost) switch err != nil { case true: return err } batch := Users.Connection.NewBatch(gocql.LoggedBatch) usr["id"] = user.Id.String() usr["balance"] = 0 usr["phone"] = user.Phone usr["password"] = string(password) usr["driver_details"] = user.Driver_details usr["created_at"] = time.Now() Users.NewRecord(usr, batch) userPkPhone := map[string]interface{}{} userPkPhone["phone"] = usr["phone"] userPkPhone["id"] = usr["id"] userPkPhone["password"] = usr["password"] UserPkPhone.NewRecord(userPkPhone, batch) err = u.Connection.ExecuteBatch(batch) return err }
[ 7 ]
//Package main is a terminal program to run an app session like USSD package main import ( "bufio" "fmt" "io" "os" "os/signal" "reflect" "strings" "syscall" "github.com/go-msvc/errors" japp "github.com/go-msvc/japp/msg" jclihttp "github.com/go-msvc/jcli/http" ) func main() { appURL := "http://localhost:12345/app" cli, err := jclihttp.New(appURL) if err != nil { panic(errors.Wrapf(err, "failed to create client")) } //start session in app //loop to communicate with app res, err := cli.Call("start", japp.StartRequest{}, reflect.TypeOf(japp.StartResponse{})) if err != nil { fmt.Fprintf(os.Stderr, "FAILED to start session: %+v\n", err) os.Exit(1) } startRes := res.(japp.StartResponse) //create a user input channel used for all console input //so we can constantly read the terminal userInputChan := make(chan string) go func(userInputChan chan string) { reader := bufio.NewReader(os.Stdin) for { input, _ := reader.ReadString('\n') input = strings.Replace(input, "\n", "", -1) userInputChan <- input } }(userInputChan) signalChannel := make(chan os.Signal, 1) signal.Notify(signalChannel, syscall.SIGINT) //<ctrl><C> go func() { <-signalChannel userInputChan <- "exit" }() fmt.Fprintf(os.Stdout, "\n") fmt.Fprintf(os.Stdout, "===== J - C O N S O L E ===============\n") //main loop lastContent := startRes.Content for { //show content fmt.Fprintf(os.Stdout, "---------------------------------------\n") if err := renderContent(os.Stdout, lastContent); err != nil { fmt.Fprintf(os.Stderr, "failed to render: %+v\n", err) os.Exit(1) } if lastContent.Final { fmt.Fprintf(os.Stdout, "\nDone.\n") os.Exit(0) } //wait for next user input input := "" for len(input) == 0 { fmt.Fprintf(os.Stdout, "J-Console> ") input = <-userInputChan } if input == "exit" { fmt.Fprintf(os.Stdout, "Terminated.\n") break } //send input to app contReq := japp.ContinueRequest{ SessionID: startRes.SessionID, StepID: lastContent.StepID, Data: map[string]interface{}{"input": input}, } res, err := cli.Call("cont", contReq, reflect.TypeOf(japp.ContinueResponse{})) if err != nil { fmt.Printf("Failed to continue app: %+v", err) continue } contRes := res.(japp.ContinueResponse) lastContent = contRes.Content } //for main loop } //main() func renderContent(w io.Writer, c japp.Content) error { if m := c.Message; m != nil { fmt.Fprintf(w, "Message: %s\n", m.Text) return nil } if p := c.Prompt; p != nil { fmt.Fprintf(w, "Prompt: %s\n", p.Text) return nil } if c := c.Choice; c != nil { fmt.Fprintf(w, "Choice: %s\n", c.Header) for _, o := range c.Options { fmt.Fprintf(w, "%s) %s\n", o.ID, o.Text) } return nil } //unexpected type of content return errors.Errorf("Cannot render content: %+v", c) }
[ 3 ]
package main import "fmt" //声明接口 type test interface { String(input string) } //声明函数echo type Echo func(input string) //函数实现接口 func (e Echo) String(input string) { e(input) } func main() { //使用Echo()将echoInstance转为Echo类型 echo := Echo(echoInstance) var test1 test = echo Print(echo) Print(test1) } func Print(test2 test) error { test2.String("test") return nil } func echoInstance(input string) { fmt.Println(input) }
[ 3 ]
package v3 import ( "encoding/json" "fmt" "log" "net/http" "net/url" "github.com/gorilla/websocket" "github.com/apache/servicecomb-service-center/server/core/proto" "github.com/chinx/helloworld/rest/common/config" "github.com/chinx/helloworld/rest/common/restful" ) var ( // 接口 API 定义 microServices = "/registry/v3/microservices" microServiceItem = "/registry/v3/microservices/%s" svcInstances = "/registry/v3/microservices/%s/instances" svcInstanceItem = "/registry/v3/microservices/%s/instances/%s" discovery = "/registry/v3/instances" existence = "/registry/v3/existence" heartbeats = "/registry/v3/heartbeats" watcher = "/registry/v3/microservices/%s/watcher" microServiceType sourceType = "microservice" schemaType sourceType = "schema" ) type sourceType string type Client struct { rawURL string domain string } func NewClient(addr string, domain string) *Client { return &Client{rawURL: addr, domain: domain} } // 查询微服务是否存在 func (c *Client) existence(params url.Values) (*proto.GetExistenceResponse, error) { reqURL := c.rawURL + existence + "?" + params.Encode() req, err := restful.NewRequest(http.MethodGet, reqURL, c.DefaultHeaders(), nil) if err == nil { respData := &proto.GetExistenceResponse{} err = restful.DoRequest(req, respData) if err == nil { return respData, nil } } return nil, err } // 获取微服务服务ID func (c *Client) GetServiceID(svc *config.ServiceConf) (string, error) { val := url.Values{} val.Set("type", string(microServiceType)) val.Set("appId", svc.AppID) val.Set("serviceName", svc.Name) val.Set("version", svc.Version) respData, err := c.existence(val) if err == nil { return respData.ServiceId, nil } return "", fmt.Errorf("[GetServiceID]: %s", err) } // 注册微服务 func (c *Client) RegisterService(svc *config.ServiceConf) (string, error) { ms := &proto.CreateServiceRequest{ Service: &proto.MicroService{ AppId: svc.AppID, ServiceName: svc.Name, Version: svc.Version, }, } reqURL := c.rawURL + microServices req, err := restful.NewRequest(http.MethodPost, reqURL, c.DefaultHeaders(), ms) if err == nil { respData := &proto.CreateServiceResponse{} err = restful.DoRequest(req, respData) if err == nil { return respData.ServiceId, nil } } return "", fmt.Errorf("[RegisterService]: %s", err) } // 注销微服务 func (c *Client) UnRegisterService(svcID string) error { reqURL := c.rawURL + fmt.Sprintf(microServiceItem, svcID) req, err := restful.NewRequest(http.MethodDelete, reqURL, c.DefaultHeaders(), nil) if err == nil { err = restful.DoRequest(req, nil) if err == nil { return nil } } return fmt.Errorf("[UNRegisterService]: %s", err) } // 注册微服务实例 func (c *Client) RegisterInstance(svcID string, ins *config.InstanceConf) (string, error) { endpoint := ins.Protocol + "://" + ins.ListenAddress ms := &proto.RegisterInstanceRequest{ Instance: &proto.MicroServiceInstance{ HostName: ins.Hostname, Endpoints: []string{endpoint}, }, } reqURL := c.rawURL + fmt.Sprintf(svcInstances, svcID) req, err := restful.NewRequest(http.MethodPost, reqURL, c.DefaultHeaders(), ms) if err == nil { respData := &proto.RegisterInstanceResponse{} err = restful.DoRequest(req, respData) if err == nil { return respData.InstanceId, nil } } return "", fmt.Errorf("[RegisterInstance]: %s", err) } // 注销微服务实例 func (c *Client) UnRegisterInstance(svcID , insID string) (error) { reqURL := c.rawURL + fmt.Sprintf(svcInstanceItem, svcID, insID) req, err := restful.NewRequest(http.MethodDelete, reqURL, c.DefaultHeaders(), nil) if err == nil { err = restful.DoRequest(req, nil) if err == nil { return nil } } return fmt.Errorf("[UNRegisterInstance]: %s", err) } // 心跳保活 func (c *Client) Heartbeat(svcID, insID string) error { hb := &proto.HeartbeatSetRequest{ Instances: []*proto.HeartbeatSetElement{ {ServiceId: svcID, InstanceId: insID}, }, } reqURL := c.rawURL + heartbeats req, err := restful.NewRequest(http.MethodPut, reqURL, c.DefaultHeaders(), hb) if err == nil { err = restful.DoRequest(req, nil) } if err != nil { return fmt.Errorf("[Heartbeat]: %s", err) } return nil } // 服务发现 func (c *Client) Discovery(conID string, svc *config.ServiceConf) ([]*proto.MicroServiceInstance, error) { val := url.Values{} val.Set("appId", svc.AppID) val.Set("serviceName", svc.Name) val.Set("version", svc.Version) reqURL := c.rawURL + discovery + "?" + val.Encode() req, err := restful.NewRequest(http.MethodGet, reqURL, c.DefaultHeaders(), nil) if err == nil { req.Header.Set("x-consumerid", conID) respData := &proto.GetInstancesResponse{} err = restful.DoRequest(req, respData) if err == nil { return respData.Instances, nil } } return nil, fmt.Errorf("[Discovery]: %s", err) } // 服务订阅 func (c *Client) WatchService(svcID string, callback func(*proto.WatchInstanceResponse)) error { addr, err:= url.Parse(c.rawURL + fmt.Sprintf(watcher, svcID)) if err != nil { return fmt.Errorf("[WatchService]: parse repositry url faild: %s", err) } // 注: watch接口使用了 websocket 长连接 addr.Scheme = "ws" conn, _, err := (&websocket.Dialer{}).Dial(addr.String(),c.DefaultHeaders()) if err != nil { return fmt.Errorf("[WatchService]: start websocket faild: %s", err) } for { messageType, message, err := conn.ReadMessage() if err != nil { log.Println(err) break } if messageType == websocket.TextMessage { data := &proto.WatchInstanceResponse{} err := json.Unmarshal(message, data) if err != nil { log.Println(err) break } callback(data) } } return fmt.Errorf("[WatchService]: receive message faild: %s", err) } // 设置默认头部 func (c *Client) DefaultHeaders() http.Header { headers := http.Header{ "Content-Type": []string{"application/json"}, "X-Domain-Name": []string{"default"}, } if c.domain != "" { headers.Set("X-Domain-Name", c.domain) } return headers }
[ 6 ]
package db //import ( // "commonPackage" // "testing" //) //func TestAddCash(t *testing.T) { // IniTable() // f := &UploadingFile{} // f.CRC = commonPackage.GetUnixTime() // err := AddCash(f) // if err != nil { // t.Error(err) // } //}
[ 3 ]
package main import ( "bytes" "encoding/xml" "fmt" "github.com/bwmarrin/discordgo" log "github.com/sirupsen/logrus" "github.com/spf13/viper" "golang.org/x/net/html/charset" "io/ioutil" "net/http" "regexp" "runtime" "strings" "time" ) const wfurl = "http://content.warframe.com/dynamic/rss.php" type WFRSS struct { XMLName xml.Name `xml:"rss"` Item []WFItem `xml:"channel>item"` } type WFItem struct { Guid string `xml:"guid"` Title string `xml:"title"` Author string `xml:"author"` Description string `xml:"description"` PubDate string `xml:"pubDate"` ExpiryDate string `xml:"expiry"` PubDateTime time.Time `xml:"-"` ExpiryDateTime time.Time `xml:"-"` } var token, webhookID, webhookToken string var msg string var wfrss *WFRSS var data chan *WFRSS var pattern *regexp.Regexp var ignoreExp map[string]bool = make(map[string]bool, 1) var ignorePub map[string]bool = make(map[string]bool, 1) var ignorePubAnt map[string]bool = make(map[string]bool, 1) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) pattern = regexp.MustCompile(`[\/: ]`) ignoreExp = make(map[string]bool, 1) ignorePub = make(map[string]bool, 1) ignorePubAnt = make(map[string]bool, 1) done := make(chan bool) data = make(chan *WFRSS) wfrss = new(WFRSS) dg, err := discordgo.New("Bot " + token) if err != nil { log.Fatalln("Error creating Discord session", err) } go discord(dg) go retrieveData(dg, data) go processData(dg, data) go notification(dg, data) dg.Close() <-done } func init() { viper.SetConfigFile("./credentials.json") if err := viper.ReadInConfig(); err != nil { log.Fatalf("Error reading config file, %s", err) } token = viper.GetString("botToken") webhookID = viper.GetString("webhookID") webhookToken = viper.GetString("webhookToken") } func discord(dg *discordgo.Session) { dg.AddHandler(messageCreate) err := dg.Open() if err != nil { log.Errorln("Error opening connection", err) return } log.Infoln("Bot is now running. Press CTRL-C to exit.") } func retrieveData(dg *discordgo.Session, data chan<- *WFRSS) { resp, err := http.Get(wfurl) wf := &WFRSS{} if err != nil { log.Errorf("Cannot retrieve the content of %s\n", wfurl) log.Errorln(err) } respReader, err := ioutil.ReadAll(resp.Body) if err != nil { log.Errorln(err) } resp.Body.Close() err = parseXML(respReader, wf) if err != nil { log.Errorln(err) } err = parseDate(wf) if err != nil { log.Errorln(err) } data <- wf if data != nil { c := time.Tick(1 * time.Minute) for now := range c { log.Infoln("Retrieving infos of rss at: ", now) go retrieveData(dg, nil) } } } func processData(dg *discordgo.Session, data chan *WFRSS) { wf := <-data now := time.Now() expiryIndex, rateExp := nearestExpiryDate(wf.Item) pubIndex, ratePub := nearestPubDate(wf.Item) wfi := wf.Item[expiryIndex] if ignoreExp[wfi.Guid] == false { if rateExp == 1.00 { msg = fmt.Sprintf("**EXPIRADO!!!!**\n%s", alertMessage(now, &wfi)) dg.WebhookExecute(webhookID, webhookToken, false, &discordgo.WebhookParams{ Content: msg, }) ignoreExp[wfi.Guid] = true } } wfi = wf.Item[pubIndex] if ignorePubAnt[wfi.Guid] == false { minute := 10 tmpMsg := fmt.Sprintf("**ALERTA!!!!!**\n%s\n", alertMessage(now, &wfi)) if now.Unix() == wfi.PubDateTime.Add(time.Duration(-minute)*time.Minute).Unix() { dg.WebhookExecute(webhookID, webhookToken, false, &discordgo.WebhookParams{ Content: tmpMsg, }) } ignorePubAnt[wfi.Guid] = true } msg = alertMessage(now, &wfi) if ignorePub[wfi.Guid] == false { if ratePub == 1.00 { log.Info("Sending content to webhook") dg.WebhookExecute(webhookID, webhookToken, false, &discordgo.WebhookParams{ Content: msg, }) ignorePub[wfi.Guid] = true } } wfrss = wf data <- wf } func notification(dg *discordgo.Session, data chan *WFRSS) { c := time.Tick(200 * time.Millisecond) for now := range c { now.Second() //log.Info("Processing notification at: ", now) go processData(dg, data) } } func parseXML(xmlDoc []byte, target interface{}) error { reader := bytes.NewReader(xmlDoc) decoder := xml.NewDecoder(reader) decoder.CharsetReader = charset.NewReaderLabel if err := decoder.Decode(target); err != nil { return err } return nil } func parseDate(wf *WFRSS) error { var err error for i, _ := range wf.Item { err = strDateToTime(&wf.Item[i]) if err != nil { return err } } return nil } func strDateToTime(wf *WFItem) error { var err error if wf.ExpiryDate != "" { wf.PubDateTime, err = time.Parse(time.RFC1123Z, wf.PubDate) wf.ExpiryDateTime, err = time.Parse(time.RFC1123Z, wf.ExpiryDate) wf.PubDateTime = wf.PubDateTime.Local() wf.ExpiryDateTime = wf.ExpiryDateTime.Local() if err != nil { return err } } return nil } func nearestPubDate(wf []WFItem) (int, float32) { var max float32 = 0.00 var index int = 0 now := time.Now() for i, el := range wf { nowUnix := now.Unix() pubUnix := el.PubDateTime.Unix() if el.PubDate != "" { var value float32 = float32(nowUnix) / float32(pubUnix) if value > max { max = value index = i } } } return index, max } func nearestExpiryDate(wf []WFItem) (int, float32) { var max float32 = 0.00 var index int = 0 now := time.Now() for i, el := range wf { nowUnix := now.Unix() expiryUnix := el.ExpiryDateTime.Unix() if el.ExpiryDate != "" { var value float32 = float32(nowUnix) / float32(expiryUnix) if value > max { max = value index = i } } } return index, max } func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { c := m.Content if strings.HasPrefix(c, "wf!") { if strings.HasSuffix(c, "alert") { s.ChannelMessageSend(m.ChannelID, msg) } if strings.HasSuffix(c, "alerts") { var tmpMsg string now := time.Now() for _, el := range wfrss.Item { if el.PubDate != "" && el.ExpiryDate != "" { tmpMsg += alertMessage(now, &el) } } s.ChannelMessageSend(m.ChannelID, tmpMsg) } } } func alertMessage(t time.Time, item *WFItem) string { lp := item.PubDateTime.Local() le := item.ExpiryDateTime.Local() start := "JA COMECOU CARA!!!" expiry := "PERDEU PLAYBOY!" subPub := item.PubDateTime.Sub(t) subExp := item.ExpiryDateTime.Sub(t) if m := subPub.Minutes(); m >= 0.00 { start = fmt.Sprintf("***%dm***", int(m)) } if m := subExp.Minutes(); m >= 0.00 { expiry = fmt.Sprintf("***%dm***", int(m)) } starts := fmt.Sprintf("%d/%d/%d %d:%d:%d", lp.Day(), lp.Month(), lp.Year(), lp.Hour(), lp.Minute(), lp.Second()) ends := fmt.Sprintf("%d/%d/%d %d:%d:%d", le.Day(), le.Month(), le.Year(), le.Hour(), le.Minute(), le.Second()) starts = addZerosToDateHours(pattern, starts) ends = addZerosToDateHours(pattern, ends) ret := fmt.Sprintf("**Titulo:** %s\n**Inicia em:** %s *(%s)*\n**Expira em:** %s *(%s)*\n**Tipo:** %s\n\n", item.Title, start, starts, expiry, ends, item.Author) return ret } func addZerosToDateHours(r *regexp.Regexp, s string) string { array := r.Split(s, -1) for i := range array { if len(array[i]) == 1 { array[i] = "0" + array[i] } } return fmt.Sprintf("%s/%s/%s %s:%s:%s", array[0], array[1], array[2], array[3], array[4], array[5]) }
[ 1, 3 ]
package engine import ( "fmt" "log" "redspider/fetcher" ) type Processor func(request Request) (ParseResult, error) type ConcurrentEngine struct { Scheduler Scheduler WorkCount int ItemChan chan Item RequestProcessor Processor } type Scheduler interface { Submit(Request) //configureWorkChan() Run() WorkReady(chan Request) } func (e *ConcurrentEngine) Run(seeds ...Request) { out := make(chan ParseResult) e.Scheduler.Run() for i := 0; i < e.WorkCount; i++ { e.CreateWork(out, e.Scheduler) } for _, r := range seeds { e.Scheduler.Submit(r) } //itemCount := 0 for { result := <-out for _, item := range result.Items { //log.Printf("Got item:%d,%v", itemCount, item) //itemCount++ go func() { e.ItemChan <- item }() } for _, request := range result.Requests { e.Scheduler.Submit(request) } } } func (e *ConcurrentEngine) CreateWork(out chan ParseResult, s Scheduler) { in := make(chan Request) go func() { for { s.WorkReady(in) request := <-in result, err := e.RequestProcessor(request) if err != nil { continue } out <- result } }() } func Worker(request Request) (ParseResult, error) { fmt.Printf("Fetch url:%s\n", request.Url) body, err := fetcher.Fetch(request.Url) if err != nil { log.Printf("Fetch Error:%s\n", request.Url) return ParseResult{}, err } return request.Parse.Parser(body, request.Url), nil }
[ 3 ]
package traversal // TODO template in Go2.0 is expected // Breadth First Search func TraversalBFS(ele interface{}, filterFn func(ele interface{}, depth int) (gotoNextLayer bool), processFn func(ele interface{}, depth int) (gotoNextLayer bool)) { traversalBFS([]Node{{ ele: ele, }}, func(node Node) (gotoNextLayer bool) { if filterFn == nil { // traversal every node return true } return filterFn(node.ele, node.depth) }, func(node Node) (gotoNextLayer bool) { if processFn == nil { // traversal no node return false } return processFn(node.ele, node.depth) }, true) } // isRoot root needs to be filtered first time func traversalBFS(current []Node, filterFn func(node Node) (gotoNextLayer bool), processFn func(node Node) (gotoNextLayer bool), isRoot bool) (gotoNextLayer bool) { if len(current) == 0 { return false } // Step 1: brothers layer nextBrothers := []Node{} for _, node := range current { // filter root if isRoot { if !filterFn(node) { return false } } if !processFn(node) { return false } // filter brothers nextBrothers = append(nextBrothers, node) } // Step 2: children layer nextChildren := []Node{} // filter children for _, node := range nextBrothers { // Scan node for nodes to include. nextChildren = append(nextChildren, filterChildren(node, node.LeftNodes(), filterFn)...) nextChildren = append(nextChildren, filterChildren(node, node.MiddleNodes(), filterFn)...) nextChildren = append(nextChildren, filterChildren(node, node.RightNodes(), filterFn)...) } traversalBFS(nextChildren, filterFn, processFn, false) return true }
[ 6 ]
/* BitArray for Golang. */ package bitarray import ( "bytes" "encoding/binary" "errors" "fmt" ) type BitArray struct { lenpad int length int bytes []byte } const ( _BytesPW int = 8 BitsPW int = _BytesPW * 8 ) var msbmask = [8]byte{0xFF, 0xFE, 0xFC, 0xF8, 0xF0, 0xE0, 0xC0, 0x80} var lsbmask = [8]byte{0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF} // var count = [16]int{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4} func nbytes(length int) int { return (((length + 7) & (^7)) / 8) // (length/8) + ((length%8)? 1:0) } func nwords(length int) int { return (((length + BitsPW - 1) & (^(BitsPW - 1))) / BitsPW) } func bytes2word(bs []byte) uint64 { var n uint64 buf := bytes.NewBuffer(bs) err := binary.Read(buf, binary.BigEndian, &n) if err != nil { panic(err) } return n } // https://en.wikipedia.org/wiki/Hamming_weight func countbits64(n uint64) int { n -= (n >> 1) & 0x5555555555555555 n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333) n = (n + (n >> 4)) & 0x0f0f0f0f0f0f0f0f return int((n * 0x0101010101010101) >> 56) } // New create a new BitArray with length(bits). func New(length int) *BitArray { lenpad := nwords(length) * _BytesPW return &BitArray{ lenpad: lenpad, length: length, bytes: make([]byte, lenpad, lenpad), } } // Len return the length of the BitArray. func (bits *BitArray) Len() int { return bits.length } // Count return the count of bit 1. func (bits *BitArray) Count() int { length := 0 for i := 0; i < bits.lenpad; i += _BytesPW { w := bytes2word(bits.bytes[i : i+_BytesPW]) length += countbits64(w) } return length } func (bits *BitArray) indexOutOfRange(idx int) error { if idx < 0 || idx >= bits.length { msg := fmt.Sprintf("index %d out of range [%d, %d)", idx, 0, bits.length) return errors.New(msg) } return nil } // Get return the bit by index n. // If index out of range [0, BitArray.Len()), return error. func (bits *BitArray) Get(n int) (int, error) { if err := bits.indexOutOfRange(n); err != nil { return 0, err } return int((bits.bytes[n/8] >> byte(n%8)) & 1), nil } // Put set the nth bit with 0/1, and return the old value of nth bit. // If index out of range [0, BitArray.Len()), return error. func (bits *BitArray) Put(n int, bit int) (int, error) { if err := bits.indexOutOfRange(n); err != nil { return 0, err } prev, _ := bits.Get(n) if bit == 1 { bits.bytes[n/8] |= 1 << byte(n%8) } else { bits.bytes[n/8] &= ^(1 << byte(n%8)) } return prev, nil } // Set the value of all bits to 1, which index range between low and high, // both low and high included. // low must less than high, and low/high cannot out of range [0, BitArray.Len()). func (bits *BitArray) Set(low int, high int) error { if low > high { msg := fmt.Sprintf("low %d should less than high %d", low, high) return errors.New(msg) } for _, idx := range []int{low, high} { if err := bits.indexOutOfRange(idx); err != nil { return err } } lb, hb := low/8, high/8 if lb < hb { bits.bytes[lb] |= msbmask[low%8] for i := lb + 1; i < hb; i++ { bits.bytes[i] = 0xFF } bits.bytes[hb] |= lsbmask[high%8] } else { bits.bytes[lb] |= (msbmask[low%8] & lsbmask[high%8]) } return nil } // Clear set the value of all bits to 0, which index range between low and high, // both low and high included. // low must less than high, and low/high cannot out of range [0, BitArray.Len()). func (bits *BitArray) Clear(low int, high int) error { if low > high { msg := fmt.Sprintf("low %d should less than high %d", low, high) return errors.New(msg) } for _, idx := range []int{low, high} { if err := bits.indexOutOfRange(idx); err != nil { return err } } lb, hb := low/8, high/8 if lb < hb { bits.bytes[lb] &= ^msbmask[low%8] for i := lb + 1; i < hb; i++ { bits.bytes[i] = 0 } bits.bytes[hb] &= ^lsbmask[high%8] } else { bits.bytes[lb] &= ^(msbmask[low%8] & lsbmask[high%8]) } return nil } // Not flips the value of all bits, which index range between low and high, // both low and high included. // low must less than high, and low/high cannot out of range [0, BitArray.Len()). func (bits *BitArray) Not(low int, high int) error { if low > high { msg := fmt.Sprintf("low %d should less than high %d", low, high) return errors.New(msg) } for _, idx := range []int{low, high} { if err := bits.indexOutOfRange(idx); err != nil { return err } } lb, hb := low/8, high/8 if lb < hb { bits.bytes[lb] ^= msbmask[low%8] for i := lb + 1; i < hb; i++ { bits.bytes[i] ^= 0xFF } bits.bytes[hb] ^= lsbmask[high%8] } else { bits.bytes[lb] ^= (msbmask[low%8] & lsbmask[high%8]) } return nil } // Eq check whether the BitArray is equal to another BitArray. // If length isn't same, return false. func (bits *BitArray) Eq(obits *BitArray) bool { if bits.length != obits.length { return false } for i := 0; i < bits.lenpad; i += _BytesPW { wself := bytes2word(bits.bytes[i : i+_BytesPW]) wother := bytes2word(obits.bytes[i : i+_BytesPW]) if wself != wother { return false } } return true } // Leq check whether the BitArray is the subset of the another. // If length isn't same, return false. func (bits *BitArray) Leq(obits *BitArray) bool { if bits.length != obits.length { return false } for i := 0; i < bits.lenpad; i += _BytesPW { wself := bytes2word(bits.bytes[i : i+_BytesPW]) wother := bytes2word(obits.bytes[i : i+_BytesPW]) if (wself & ^wother) != 0 { return false } } return true } // Lt check whether the BitArray is the proper subset of the another. // If length isn't same, return false. func (bits *BitArray) Lt(obits *BitArray) bool { if bits.length != obits.length { return false } lt := 0 for i := 0; i < bits.lenpad; i += _BytesPW { wself := bytes2word(bits.bytes[i : i+_BytesPW]) wother := bytes2word(obits.bytes[i : i+_BytesPW]) if (wself & ^wother) != 0 { return false } else if wself != wother { // at least one word does not equal lt |= 1 } } if lt == 0 { return false } return true } // Convert the BitArray to a array of integers, and return. func (bits *BitArray) ToArray() []int { ints := make([]int, bits.length, bits.length) for i := 0; i < bits.length; i++ { ints[i], _ = bits.Get(i) } return ints }
[ 6 ]
package job import ( "encoding/json" "github.com/m-o-s-e-s/mgm/core/persist" "github.com/m-o-s-e-s/mgm/mgm" "github.com/satori/go.uuid" ) type jobDatabase struct { mysql persist.Database } // GetJobByID retrieve a job record using the id of the job func (db jobDatabase) GetJobByID(id int) (mgm.Job, error) { con, err := db.mysql.GetConnection() if err != nil { return mgm.Job{}, err } defer con.Close() j := mgm.Job{} err = con.QueryRow("SELECT * FROM jobs WHERE id=?", id).Scan(&j.ID, &j.Timestamp, &j.Type, &j.User, &j.Data) if err != nil { return mgm.Job{}, err } return j, nil } // UpdateJob record an updated job record func (db jobDatabase) UpdateJob(job mgm.Job) error { con, err := db.mysql.GetConnection() if err != nil { return err } defer con.Close() //The function states update job, but only the data field ever changes _, err = con.Exec("UPDATE jobs SET data=?", job.Data) if err != nil { return err } return nil } // DeleteJob purges a job record from the database func (db jobDatabase) DeleteJob(job mgm.Job) error { con, err := db.mysql.GetConnection() if err != nil { return err } defer con.Close() _, err = con.Exec("DELETE FROM jobs WHERE id=?", job.ID) if err != nil { return err } return nil } // GetJobsForUser get all job records for a particular user func (db jobDatabase) GetJobsForUser(userID uuid.UUID) ([]mgm.Job, error) { con, err := db.mysql.GetConnection() if err != nil { return nil, err } defer con.Close() rows, err := con.Query("SELECT * FROM jobs WHERE user=?", userID.String()) defer rows.Close() if err != nil { return nil, err } var jobs []mgm.Job for rows.Next() { j := mgm.Job{} err = rows.Scan( &j.ID, &j.Timestamp, &j.Type, &j.User, &j.Data, ) if err != nil { rows.Close() return nil, err } jobs = append(jobs, j) } return jobs, nil } // CreateLoadIarJob utility function to create job of type load_iar func (db jobDatabase) CreateLoadIarJob(owner uuid.UUID, inventoryPath string) (mgm.Job, error) { loadIar := LoadIarJob{InventoryPath: "/"} data, err := json.Marshal(loadIar) if err != nil { return mgm.Job{}, err } return db.CreateJob("load_iar", owner, string(data)) } // CreateJob create a new job record, returning the created job func (db jobDatabase) CreateJob(taskType string, userID uuid.UUID, data string) (mgm.Job, error) { con, err := db.mysql.GetConnection() if err != nil { return mgm.Job{}, err } defer con.Close() res, err := con.Exec("INSERT INTO jobs (type, user, data) VALUES (?,?,?)", taskType, userID.String(), data) if err != nil { return mgm.Job{}, err } id, _ := res.LastInsertId() j := mgm.Job{} err = con.QueryRow("SELECT * FROM jobs WHERE id=?", id).Scan(&j.ID, &j.Timestamp, &j.Type, &j.User, &j.Data) if err != nil { return mgm.Job{}, err } return j, nil }
[ 3 ]
// using SendGrid's Go Library // https://github.com/sendgrid/sendgrid-go package sendgrid import ( "encoding/json" "os" "github.com/sendgrid/rest" "github.com/sendgrid/sendgrid-go" ) type requestBody struct { Personalizations []personalization `json:"personalizations"` From emailAdd `json:"from"` Body []content `json:"content"` } type content struct { Type string `json:"type"` Value string `json:"value"` } type emailAdd struct { Email string `json:"email"` } type personalization struct { To []emailAdd `json:"to"` Subject string `json:"subject"` } func getPersonlizations(subject string, to []string) []personalization { receipients := make([]emailAdd, len(to)) for index, email := range to { receipients[index] = emailAdd{email} } personalizationInstance := personalization{receipients, subject} personalizations := []personalization{personalizationInstance} return personalizations } func Mail(from string, subject string, to []string, body string) (*rest.Response, error) { sender := emailAdd{from} contentText := content{"text/plain", body} contentBody := []content{contentText} personalizations := getPersonlizations(subject, to) reqBody := requestBody{personalizations, sender, contentBody} request := sendgrid.GetRequest(os.Getenv("SENDGRID_API_KEY"), "/v3/mail/send", "https://api.sendgrid.com") request.Method = "POST" request.Body, _ = json.Marshal(reqBody) response, err := sendgrid.API(request) return response, err }
[ 6 ]
package _009 func isPalindrome(x int) bool { if x < 0 { return false } if x == 0 { return true } nums := make([]int, 0) for x != 0 { nums = append(nums, x%10) x = x / 10 } for i, j := 0, len(nums)-1; i <= j; { if nums[i] != nums[j] { return false } i++ j-- } return true } func isPalindromeV2(x int) bool { if x < 0 { return false } if x == 0 { return true } shang := 1 y := x for y != 0 { shang *= 10 y = y / 10 } shang /= 10 for shang != 1 { if x/shang != x%10 { return false } shang /= 100 x = (x/10 - x%10) / 10 } return true }
[ 0 ]
package main import ( "encoding/json" "io/ioutil" "os" "fmt" "strings" "github.com/yosuke-furukawa/programming-go-study/ch04/ex12/xkcd" ) var xkcds []xkcd.Xkcd func init() { data, _ := ioutil.ReadFile("./files/all.json") json.Unmarshal(data, &xkcds) } func main() { //err := xkcd.Download("./files/all.json") //if err != nil { // fmt.Errorf("download error %v", err) //} query := os.Args[1] for _, xkcd := range xkcds { if strings.Contains(xkcd.Transcript, query) { fmt.Println(xkcd.Img) } } }
[ 3 ]
package ecloud import ( "bytes" "context" "crypto/hmac" "crypto/sha1" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "sort" "strings" "time" "github.com/google/uuid" "github.com/sirupsen/logrus" ) type Address struct { IPVersion string `json:"ipVersion"` IPAddress string `json:"ipAddress"` } type Node struct { NodeID string `json:"nodeID"` Name string `json:"name"` Labels map[string]string `json:"labels"` CPU int `json:"cpu"` Memory int `json:"memory"` Addresses []Address `json:"Addresses"` Taints bool `json:"taints"` Schedulable bool `json:"schedulable"` Role string `json:"role"` Status string `json:"status"` ProviderID string `json:"providerID"` CreatedTime string `json:"createdTime"` } type NodeList struct { Total int `json:"total"` Nodes []Node `json:"nodes"` } type VMVolume struct { Size int `json:"size"` VolumeType string `json:"volumeType"` } type VMVolumes struct { SystemDisk VMVolume `json:"systemDisk"` DataDisk VMVolume `json:"dataDisk"` } type VMInfrastructure struct { Flavor string `json:"flavor,omitempty"` ServerType string `json:"serverType,omitempty"` ServerVmType string `json:"serverVmType,omitempty"` ImageId string `json:"imageId,omitempty"` CPU int `json:"cpu"` Disk int `json:"disk"` Ram int `json:"ram"` Password string `json:"password,omitempty"` Keypair string `json:"keypair,omitempty"` Volumes VMVolumes `json:"volumes"` SpecsName string `json:"SpecsName"` MaxBandWidth string `json:"maxbandwidth,omitempty"` } type EcloudClient struct { host string accessKey string secretKey string } func NewEcloudClient( host string, accessKey string, secretKey string, ) (*EcloudClient, error) { client := &EcloudClient{ host: host, accessKey: accessKey, secretKey: secretKey, } if err := valideEcloudClient(client); err != nil { return nil, err } return client, nil } type NodeResponse struct { RequestID string `json:"requestId"` State string `json:"state"` Body NodeList `json:"body"` } func (c *EcloudClient) Nodes( ctx context.Context, logger *logrus.Logger, cluster string, pageParam ...int, ) (*NodeList, error) { query := url.Values{} query.Add("page", "1") query.Add("pageSize", "100") // set default page and pageSize if len(pageParam) >= 2 { query.Set("page", fmt.Sprintf("%d", pageParam[0])) query.Set("pageSize", fmt.Sprintf("%d", pageParam[1])) } else if len(pageParam) == 1 { query.Set("page", fmt.Sprintf("%d", pageParam[0])) } path := fmt.Sprintf("/api/kcs/v2/clusters/%s/nodes", cluster) request, err := c.cookHTTPRequest(ctx, c.host, path, http.MethodGet, query, nil, ) if err != nil { logger.WithField("err", err).Errorf("cook HTTP request error") return nil, err } logger.Infof("GET %s", request.URL) res, err := http.DefaultClient.Do(request) if err != nil { logger.WithField("err", err).Error("Nodes error") return nil, err } defer res.Body.Close() if err := checkHTTPStatusCode(res); err != nil { logger.WithField("err", err).Errorf("http response error") return nil, err } nr := &NodeResponse{} if err := json.NewDecoder(res.Body).Decode(nr); err != nil { logger.WithField("err", err).Errorf("decode NodeResponse error") return nil, err } logger.Infof("requestId: %s, state: %s, total nodes: %d", nr.RequestID, nr.State, nr.Body.Total) return &nr.Body, nil } type AddNodeRequest struct { AddType string `json:"addType"` ClusterID string `json:"cluster_id"` Infrastructure VMInfrastructure `json:"infrastructure"` } type AddNodeRes struct { RequestID string `json:"requestId"` State string `json:"state"` ErrorCode string `json:"errorCode"` ErrorMessage string `json:"errorMessage"` } func (c *EcloudClient) AddNode( ctx context.Context, logger *logrus.Logger, cluster string, ifr *VMInfrastructure, ) error { playload := &AddNodeRequest{ AddType: "new", ClusterID: cluster, Infrastructure: *ifr, } buffer := bytes.NewBuffer(nil) if err := json.NewEncoder(buffer).Encode(playload); err != nil { return err } path := fmt.Sprintf("/api/kcs/v2/clusters/%s/nodes", cluster) request, err := c.cookHTTPRequest(ctx, c.host, path, http.MethodPost, nil, buffer, ) if err != nil { logger.WithField("err", err).Error("cook http request error") return err } logger.Infof("POST %s", request.URL) res, err := http.DefaultClient.Do(request) if err != nil { logger.WithField("err", err).Error("AddNode error") return err } defer res.Body.Close() if err := checkHTTPStatusCode(res); err != nil { logger.WithField("err", err).Errorf("http response error") return err } anr := &AddNodeRes{} if err := json.NewDecoder(res.Body).Decode(anr); err != nil { logger.WithField("err", err).Errorf("decode AddNodeRes error") return err } logger.Infof("AddNodeRes: %v", *anr) if anr.State != "OK" { return errors.New(anr.ErrorMessage) } return nil } func (c *EcloudClient) cookHTTPRequest( ctx context.Context, host, path, method string, query url.Values, body io.Reader, ) (*http.Request, error) { if query == nil { query = url.Values{} } request, err := http.NewRequestWithContext(ctx, method, concatenateUrl(host, path), body) if err != nil { return nil, err } request.Header.Add("Content-Type", "application/json") query.Add("Timestamp", time.Now().Local().Format("2006-01-02T15:04:05Z")) query.Add("AccessKey", c.accessKey) query.Add("SignatureNonce", uuid.New().String()) query.Add("SignatureMethod", "HmacSHA1") query.Add("SignatureVersion", "V2.0") if signature, err := c.doSign(method, path, query); err != nil { return nil, err } else { query.Add("Signature", signature) } request.URL.RawQuery = query.Encode() return request, nil } func (c *EcloudClient) doSign(method, path string, query url.Values) (string, error) { type queryKey struct { key string value []string } // sort query key queryArr := make([]queryKey, 0, len(query)) for k, v := range query { queryArr = append(queryArr, queryKey{k, v}) } sort.Slice(queryArr, func(i, j int) bool { return queryArr[i].key < queryArr[j].key }) tmpCanonicalizedQueryArr := []string{} for i := range queryArr { k := percentEncode(url.QueryEscape(queryArr[i].key)) v := percentEncode(url.QueryEscape(queryArr[i].value[0])) tmpCanonicalizedQueryArr = append(tmpCanonicalizedQueryArr, k+"="+v) } canonicalizedQueryStr := strings.Join(tmpCanonicalizedQueryArr, "&") // generate str to sign sha := sha256.New() _, err := sha.Write([]byte(canonicalizedQueryStr)) if err != nil { return "", err } cqssha := hex.EncodeToString(sha.Sum(nil)) stringToSign := method + "\n" + percentEncode(url.QueryEscape(path)) + "\n" + cqssha // generate signature key := "BC_SIGNATURE&" + c.secretKey hm := hmac.New(sha1.New, []byte(key)) _, err = hm.Write([]byte(stringToSign)) if err != nil { return "", err } signature := hex.EncodeToString(hm.Sum(nil)) return signature, nil } func concatenateUrl(host, path string) string { return fmt.Sprintf("https://%s%s", host, path) } func valideEcloudClient(c *EcloudClient) error { if c.host == "" { return errors.New("host is empty") } if c.accessKey == "" { return errors.New("access_key is empty") } if c.secretKey == "" { return errors.New("secret_key is empty") } return nil } func percentEncode(s string) string { s = strings.ReplaceAll(s, "+", "%20") s = strings.ReplaceAll(s, "*", "%2A") s = strings.ReplaceAll(s, "%7E", "~") return s } func checkHTTPStatusCode(res *http.Response) error { if res.StatusCode != http.StatusOK { return fmt.Errorf("http request return %d status code", res.StatusCode) } return nil }
[ 6 ]
package zapi import ( "bytes" "fmt" "io/ioutil" //"log" "encoding/json" "net/http" "net/url" //"strings" "time" ) type Client struct { Url string `json:"url"` Username string `json:"username"` Password string `json:"password"` Token string `json:"token"` httpClient *http.Client `json:"-"` } func NewClientFromFile(path string) (client Client, err error) { data, err := ioutil.ReadFile(path) if err != nil { return client, err } if err := json.Unmarshal(data, &client); err != nil { return client, err } client.httpClient = &http.Client{} return client, err } func NewPasswordClient(url, username, password string) Client { return Client{ Username: username, Password: password, httpClient: &http.Client{Transport: &http.Transport{}}, } } func NewTokenClient(url, username, token string) Client { return Client{ Username: username, Token: token, httpClient: &http.Client{Transport: &http.Transport{}}, } } type Filter struct { Key string Value string } type Filters []Filter func (filters Filters) toParams(vals *url.Values) *url.Values { for _, filter := range filters { vals.Add(filter.Key, filter.Value) } return vals } type Date time.Time func (d *Date) MarshalJSON() ([]byte, error) { t := time.Time(*d).Format(fmt.Sprintf("\"%s\"", time.RFC3339)) return []byte(t), nil } func (d *Date) UnmarshalJSON(b []byte) error { t, err := time.Parse(fmt.Sprintf("\"%s\"", time.RFC3339), string(b)) if err != nil { return err } *d = Date(t) return nil } func (c *Client) Do(req *http.Request) ([]byte, error) { req.Header.Add("Content-Type", "application/json") if c.Token == "" { req.SetBasicAuth(c.Username, c.Password) } else { req.SetBasicAuth(fmt.Sprintf("%s/token", c.Username), c.Token) } //fmt.Printf("%#v\n", req.URL) //fmt.Printf("%#v\n", req) resp, err := c.httpClient.Do(req) //fmt.Printf("%#v\n", resp) if err != nil { return nil, err } defer resp.Body.Close() return ioutil.ReadAll(resp.Body) } func (client *Client) Get(path string, params *url.Values) ([]byte, error) { urlPath := fmt.Sprintf("%s%s", client.Url, path) urlRaw, err := url.Parse(urlPath) if err != nil { return nil, err } if params != nil { urlRaw.RawQuery = params.Encode() } //fmt.Printf("%s\n", urlRaw.String()) req, err := http.NewRequest("GET", urlRaw.String(), nil) if err != nil { return nil, err } return client.Do(req) } func (client *Client) Put(path string, params *url.Values, requestBody []byte) ([]byte, error) { urlPath := fmt.Sprintf("%s%s", client.Url, path) urlRaw, err := url.Parse(urlPath) if err != nil { return nil, err } if params != nil { urlRaw.RawQuery = params.Encode() } //fmt.Printf("%s\n", urlRaw.String()) req, err := http.NewRequest("PUT", urlRaw.String(), bytes.NewBufferString(string(requestBody))) if err != nil { return nil, err } return client.Do(req) } func (client *Client) Post(path string, params *url.Values, requestBody []byte) ([]byte, error) { urlPath := fmt.Sprintf("%s%s", client.Url, path) urlRaw, err := url.Parse(urlPath) if err != nil { return nil, err } if params != nil { urlRaw.RawQuery = params.Encode() } //fmt.Printf("%s\n", urlRaw.String()) req, err := http.NewRequest("POST", urlRaw.String(), bytes.NewBufferString(string(requestBody))) if err != nil { return nil, err } return client.Do(req) }
[ 3 ]
package main import ( "os" "github.com/sirupsen/logrus" ) func main() { //https://github.com/sirupsen/logrus/blob/master/example_basic_test.go var log = logrus.New() log.Formatter = new(logrus.TextFormatter) log.Out = os.Stdout log.Formatter.(*logrus.TextFormatter).DisableColors = true // remove colors //log.Formatter.(*logrus.TextFormatter).DisableTimestamp = true // remove timestamp from test output log.WithFields(logrus.Fields{ "animal": "walrus", }).Info("A walrus appears") }
[ 3 ]
package main import ( "flag" "fmt" ) /** 使用指针变量获取命令行的输入信息\ Go语言的flag包中,定义的指令以指针类型返回.通过学习flag包,可以深入了解指针变量在设计上的方便之处 使用命令:go run flagparse.go --mode=fast 打印结果为:fast */ //通过flag.String,定义一个mode变量,这个变量的类型是*string.后面3个参数分别如下. //参数名称:在给应用输入参数时,使用这个名称 //参数值的默认值:与flag所使用的函数创建变量类型对应,String对应字符串.Int对应整型.Bool对应布尔型 //参数说明:使用-help时,会出现在说明中 var mode = flag.String("mode", "", "processMode") func main() { //解析命令行参数,并将结果写入创建的指令变量mode中 flag.Parse() //输出命令行参数,打印mode指针所指向的变量 fmt.Println(*mode) }
[ 3 ]
package services import ( "github.com/camolezi/MicroservicesGolang/src/model" "github.com/camolezi/MicroservicesGolang/src/services/data" "golang.org/x/crypto/bcrypt" ) //CreateNewUser is the service that creates new users - for now only func CreateNewUser(user model.User, password string) error { //Maybe we want to do this asynchronous hash, err := bcrypt.GenerateFromPassword([]byte(password), 12) if err != nil { return err } user.HashedPassword = hash access := data.CreateDataAccess() err = access.CreateUser(user) if err != nil { return err } //Created return nil }
[ 3 ]
package serviprov import ( "bytes" co "contler" ds "dbs/serviprov" "encoding/json" "fmt" //"log" "net/http" //s "strings" ) func BidOrderHandler(w http.ResponseWriter, r *http.Request, ctx *co.AppContext) { var ( //sp common.SrvProv bor ds.BidOrderResponse ) bor.Status = ctx.Status if ctx.Status == "success" { if r.Body != nil { //var p []byte buf := new(bytes.Buffer) buf.ReadFrom(r.Body) //s := buf.String() // Does a complete copy of the bytes in the buffer. //fmt.Fprintf(w, "n = %s", s) //var byt []byte //r.Body.Read(byt) // res := Response1{} //var dat map[string]interface{} res := ds.BidOrderParam{} //if err := json.Unmarshal(buf.Bytes(), &dat); err != nil { if err := json.Unmarshal(buf.Bytes(), &res); err != nil { // panic(err) s := err.Error() bor.Status = s } else { switch res.Vertical_id { case 1: ds.BidOrderGlam(ctx.Db, &res, &bor) break case 4: ds.BidOrderAuto(ctx.Db, &res, &bor) } //fmt.Printf("phonex = %v", res) /*lr.Service_provider.Phone = res.Sp_phone //fmt.Printf("phonep = %s", res.Sp_phone) ds.LoadSP(ctx.Db, &lr) if lr.Status == "success" { ds.LoadSPServices(ctx.Db, &lr) if lr.Status == "success" { ds.LoadSPEquip(ctx.Db, &lr) } }*/ } // fmt.Println(res) // fmt.Println(res.Page) } else { bor.Status = "Error parameter in body required" } } //lr.Service_provider = sp //fmt.Printf("s= %v\n", lr) resp, err := json.Marshal(bor) if err == nil { fmt.Fprintf(w, bytes.NewBuffer(resp).String()) } else { fmt.Fprintf(w, "{ \"Status\" : \""+err.Error()+"\"}") } } func GetOrderList(w http.ResponseWriter, r *http.Request, ctx *co.AppContext) { var olr ds.OrderListResponse olr.Status = ctx.Status if ctx.Status == "success" { if r.Body != nil { //var p []byte buf := new(bytes.Buffer) buf.ReadFrom(r.Body) //s := buf.String() // Does a complete copy of the bytes in the buffer. //fmt.Fprintf(w, "n = %s", s) //var byt []byte //r.Body.Read(byt) // res := Response1{} //var dat map[string]interface{} res := ds.OrderParam{} //if err := json.Unmarshal(buf.Bytes(), &dat); err != nil { if err := json.Unmarshal(buf.Bytes(), &res); err != nil { // panic(err) s := err.Error() olr.Status = s } else { ds.GetOrderList(ctx.Db, &res, &olr) //fmt.Printf("phonex = %v", res) /*lr.Service_provider.Phone = res.Sp_phone //fmt.Printf("phonep = %s", res.Sp_phone) ds.LoadSP(ctx.Db, &lr) if lr.Status == "success" { ds.LoadSPServices(ctx.Db, &lr) if lr.Status == "success" { ds.LoadSPEquip(ctx.Db, &lr) } }*/ } // fmt.Println(res) // fmt.Println(res.Page) } else { olr.Status = "Error parameter in body required" } } //lr.Service_provider = sp //fmt.Printf("s= %v\n", lr) resp, err := json.Marshal(olr) if err == nil { fmt.Fprintf(w, bytes.NewBuffer(resp).String()) } else { fmt.Fprintf(w, "{ \"Status\" : \""+err.Error()+"\"}") } } func GetOrderHistory(w http.ResponseWriter, r *http.Request, ctx *co.AppContext) { var ohr ds.OrderHistoryResponse ohr.Status = ctx.Status if ctx.Status == "success" { if r.Body != nil { //var p []byte buf := new(bytes.Buffer) buf.ReadFrom(r.Body) //s := buf.String() // Does a complete copy of the bytes in the buffer. //fmt.Fprintf(w, "n = %s", s) //var byt []byte //r.Body.Read(byt) // res := Response1{} //var dat map[string]interface{} res := ds.OrderHistoryParam{} //if err := json.Unmarshal(buf.Bytes(), &dat); err != nil { if err := json.Unmarshal(buf.Bytes(), &res); err != nil { // panic(err) s := err.Error() ohr.Status = s } else { ds.GetOrderHistory(ctx.Db, &res, &ohr) //fmt.Printf("phonex = %v", res) /*lr.Service_provider.Phone = res.Sp_phone //fmt.Printf("phonep = %s", res.Sp_phone) ds.LoadSP(ctx.Db, &lr) if lr.Status == "success" { ds.LoadSPServices(ctx.Db, &lr) if lr.Status == "success" { ds.LoadSPEquip(ctx.Db, &lr) } }*/ } // fmt.Println(res) // fmt.Println(res.Page) } else { ohr.Status = "Error parameter in body required" } } //lr.Service_provider = sp //fmt.Printf("s= %v\n", lr) resp, err := json.Marshal(ohr) if err == nil { fmt.Fprintf(w, bytes.NewBuffer(resp).String()) } else { fmt.Fprintf(w, "{ \"Status\" : \""+err.Error()+"\"}") } }
[ 3 ]
package apply import ( "fmt" "strings" "time" "github.com/Mirantis/k8s-apps/helm-apply/kubeutils" "k8s.io/helm/cmd/helm/installer" "k8s.io/helm/pkg/helm" "k8s.io/helm/pkg/helm/portforwarder" "k8s.io/helm/pkg/kube" ) func (cluster *Cluster) GetHelmClient() (*helm.Client, error) { if cluster.helmClient != nil { return cluster.helmClient, nil } for attempts := 60; attempts > 0; attempts-- { tunnel, err := cluster.newTunnel() if err != nil { if strings.Contains(err.Error(), "could not find tiller") { err = cluster.initTiller() if err != nil { return nil, err } time.Sleep(5 * time.Second) continue } else if strings.Contains(err.Error(), "could not find a ready tiller pod") { time.Sleep(3 * time.Second) continue } else { return nil, err } } tillerHost := fmt.Sprintf("127.0.0.1:%d", tunnel.Local) cluster.helmClient = helm.NewClient(helm.Host(tillerHost)) return cluster.helmClient, nil } return nil, fmt.Errorf("wasn't able to establish connection with "+ "tiller for cluster \"%s\"", cluster.Name) } func (cluster *Cluster) initTiller() error { fmt.Printf("Initializing tiller for cluster \"%s\"...\n", cluster.Name) _, client, err := cluster.GetKubeClient() if err != nil { return err } namespace := "kube-system" if len(cluster.TillerNamespace) > 0 { namespace = cluster.TillerNamespace } err = kubeutils.EnsureNamespace(client, namespace) if err != nil { return err } err = kubeutils.CreateServiceAccount(client, namespace) if err != nil { return err } err = kubeutils.CreateClusterRoleBinding(client, namespace) if err != nil { return err } err = installer.Install(client, &installer.Options{ Namespace: namespace, ImageSpec: "gcr.io/kubernetes-helm/tiller:v2.7.2", ServiceAccount: "tiller-" + namespace}) if err != nil { return err } return nil } func (cluster *Cluster) newTunnel() (*kube.Tunnel, error) { config, client, err := cluster.GetKubeClient() if err != nil { return nil, err } namespace := "kube-system" if len(cluster.TillerNamespace) > 0 { namespace = cluster.TillerNamespace } tunnel, err := portforwarder.New(namespace, client, config) if err != nil { return nil, err } return tunnel, nil }
[ 5 ]
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package fabricca import ( "io/ioutil" "os" "strings" "testing" "time" "github.com/golang/mock/gomock" "github.com/hyperledger/fabric-sdk-go/api/apiconfig/mocks" "github.com/pkg/errors" config "github.com/hyperledger/fabric-sdk-go/api/apiconfig" ca "github.com/hyperledger/fabric-sdk-go/api/apifabca" "github.com/hyperledger/fabric-sdk-go/api/apicryptosuite" "github.com/hyperledger/fabric-sdk-go/pkg/cryptosuite" cryptosuiteimpl "github.com/hyperledger/fabric-sdk-go/pkg/cryptosuite/bccsp/sw" bccspwrapper "github.com/hyperledger/fabric-sdk-go/pkg/cryptosuite/bccsp/wrapper" "github.com/hyperledger/fabric-sdk-go/pkg/fabric-ca-client/mocks" ) var configImp config.Config var cryptoSuiteProvider apicryptosuite.CryptoSuite var org1 = "peerorg1" var caServerURL = "http://localhost:8090" var wrongCAServerURL = "http://localhost:8091" // TestMain Load testing config func TestMain(m *testing.M) { configImp = mocks.NewMockConfig(caServerURL) cryptoSuiteProvider, _ = cryptosuiteimpl.GetSuiteByConfig(configImp) if cryptoSuiteProvider == nil { panic("Failed initialize cryptoSuiteProvider") } // Start Http Server go mocks.StartFabricCAMockServer(strings.TrimPrefix(caServerURL, "http://")) // Allow HTTP server to start time.Sleep(1 * time.Second) os.Exit(m.Run()) } // TestEnroll will test multiple enrol scenarios func TestEnroll(t *testing.T) { fabricCAClient, err := NewFabricCAClient(org1, configImp, cryptoSuiteProvider) if err != nil { t.Fatalf("NewFabricCAClient return error: %v", err) } _, _, err = fabricCAClient.Enroll("", "user1") if err == nil { t.Fatalf("Enroll didn't return error") } if err.Error() != "enrollmentID required" { t.Fatalf("Enroll didn't return right error") } _, _, err = fabricCAClient.Enroll("test", "") if err == nil { t.Fatalf("Enroll didn't return error") } if err.Error() != "enrollmentSecret required" { t.Fatalf("Enroll didn't return right error") } _, _, err = fabricCAClient.Enroll("enrollmentID", "enrollmentSecret") if err != nil { t.Fatalf("fabricCAClient Enroll return error %v", err) } wrongConfigImp := mocks.NewMockConfig(wrongCAServerURL) fabricCAClient, err = NewFabricCAClient(org1, wrongConfigImp, cryptoSuiteProvider) if err != nil { t.Fatalf("NewFabricCAClient return error: %v", err) } _, _, err = fabricCAClient.Enroll("enrollmentID", "enrollmentSecret") if err == nil { t.Fatalf("Enroll didn't return error") } if !strings.Contains(err.Error(), "enroll failed") { t.Fatalf("Expected error enroll failed. Got: %s", err) } } // TestRegister tests multiple scenarios of registering a test (mocked or nil user) and their certs func TestRegister(t *testing.T) { fabricCAClient, err := NewFabricCAClient(org1, configImp, cryptoSuiteProvider) if err != nil { t.Fatalf("NewFabricCAClient returned error: %v", err) } user := mocks.NewMockUser("test") // Register with nil request _, err = fabricCAClient.Register(user, nil) if err == nil { t.Fatalf("Expected error with nil request") } if err.Error() != "registration request required" { t.Fatalf("Expected error registration request required. Got: %s", err.Error()) } //Register with nil user _, err = fabricCAClient.Register(nil, &ca.RegistrationRequest{}) if err == nil { t.Fatalf("Expected error with nil user") } if !strings.Contains(err.Error(), "failed to create request for signing identity") { t.Fatalf("Expected error failed to create request for signing identity. Got: %s", err.Error()) } // Register with nil user cert and key _, err = fabricCAClient.Register(user, &ca.RegistrationRequest{}) if err == nil { t.Fatalf("Expected error without user enrolment information") } if !strings.Contains(err.Error(), "failed to create request for signing identity") { t.Fatalf("Expected error failed to create request for signing identity. Got: %s", err.Error()) } user.SetEnrollmentCertificate(readCert(t)) key, err := cryptosuite.GetDefault().KeyGen(cryptosuite.GetECDSAP256KeyGenOpts(true)) if err != nil { t.Fatalf("KeyGen return error %v", err) } user.SetPrivateKey(key) // Register without registration name parameter _, err = fabricCAClient.Register(user, &ca.RegistrationRequest{}) if !strings.Contains(err.Error(), "failed to register user") { t.Fatalf("Expected error failed to register user. Got: %s", err.Error()) } // Register with valid request var attributes []ca.Attribute attributes = append(attributes, ca.Attribute{Key: "test1", Value: "test2"}) attributes = append(attributes, ca.Attribute{Key: "test2", Value: "test3"}) secret, err := fabricCAClient.Register(user, &ca.RegistrationRequest{Name: "test", Affiliation: "test", Attributes: attributes}) if err != nil { t.Fatalf("fabricCAClient Register return error %v", err) } if secret != "mockSecretValue" { t.Fatalf("fabricCAClient Register return wrong value %s", secret) } } // TestRevoke will test multiple revoking a user with a nil request or a nil user func TestRevoke(t *testing.T) { cryptoSuiteProvider, err := cryptosuiteimpl.GetSuiteByConfig(configImp) if err != nil { t.Fatalf("cryptosuite.GetSuiteByConfig returned error: %v", err) } fabricCAClient, err := NewFabricCAClient(org1, configImp, cryptoSuiteProvider) if err != nil { t.Fatalf("NewFabricCAClient returned error: %v", err) } mockKey := bccspwrapper.GetKey(&mocks.MockKey{}) user := mocks.NewMockUser("test") // Revoke with nil request _, err = fabricCAClient.Revoke(user, nil) if err == nil { t.Fatalf("Expected error with nil request") } if err.Error() != "revocation request required" { t.Fatalf("Expected error revocation request required. Got: %s", err.Error()) } //Revoke with nil user _, err = fabricCAClient.Revoke(nil, &ca.RevocationRequest{}) if err == nil { t.Fatalf("Expected error with nil user") } if !strings.Contains(err.Error(), "failed to create request for signing identity") { t.Fatalf("Expected error failed to create request for signing identity. Got: %s", err.Error()) } user.SetEnrollmentCertificate(readCert(t)) user.SetPrivateKey(mockKey) _, err = fabricCAClient.Revoke(user, &ca.RevocationRequest{}) if err == nil { t.Fatalf("Expected decoding error with test cert") } } // TestReenroll will test multiple scenarios of re enrolling a user func TestReenroll(t *testing.T) { fabricCAClient, err := NewFabricCAClient(org1, configImp, cryptoSuiteProvider) if err != nil { t.Fatalf("NewFabricCAClient returned error: %v", err) } user := mocks.NewMockUser("") // Reenroll with nil user _, _, err = fabricCAClient.Reenroll(nil) if err == nil { t.Fatalf("Expected error with nil user") } if err.Error() != "user required" { t.Fatalf("Expected error user required. Got: %s", err.Error()) } // Reenroll with user.Name is empty _, _, err = fabricCAClient.Reenroll(user) if err == nil { t.Fatalf("Expected error with user.Name is empty") } if err.Error() != "user name missing" { t.Fatalf("Expected error user name missing. Got: %s", err.Error()) } // Reenroll with user.EnrollmentCertificate is empty user = mocks.NewMockUser("testUser") _, _, err = fabricCAClient.Reenroll(user) if err == nil { t.Fatalf("Expected error with user.EnrollmentCertificate is empty") } if !strings.Contains(err.Error(), "createSigningIdentity failed") { t.Fatalf("Expected error createSigningIdentity failed. Got: %s", err.Error()) } // Reenroll with appropriate user user.SetEnrollmentCertificate(readCert(t)) key, err := cryptosuite.GetDefault().KeyGen(cryptosuite.GetECDSAP256KeyGenOpts(true)) if err != nil { t.Fatalf("KeyGen return error %v", err) } user.SetPrivateKey(key) _, _, err = fabricCAClient.Reenroll(user) if err != nil { t.Fatalf("Reenroll return error %v", err) } // Reenroll with wrong fabric-ca server url wrongConfigImp := mocks.NewMockConfig(wrongCAServerURL) fabricCAClient, err = NewFabricCAClient(org1, wrongConfigImp, cryptoSuiteProvider) if err != nil { t.Fatalf("NewFabricCAClient return error: %v", err) } _, _, err = fabricCAClient.Reenroll(user) if err == nil { t.Fatalf("Expected error with wrong fabric-ca server url") } if !strings.Contains(err.Error(), "reenroll failed") { t.Fatalf("Expected error with wrong fabric-ca server url. Got: %s", err.Error()) } } // TestGetCAName will test the CAName is properly created once a new FabricCAClient is created func TestGetCAName(t *testing.T) { fabricCAClient, err := NewFabricCAClient(org1, configImp, cryptoSuiteProvider) if err != nil { t.Fatalf("NewFabricCAClient returned error: %v", err) } if fabricCAClient.CAName() != "test" { t.Fatalf("CAName returned wrong value: %s", fabricCAClient.CAName()) } } // TestCreateNewFabricCAClientOrgAndConfigMissingFailure tests for newFabricCA Client creation with a missing Config and Org func TestCreateNewFabricCAClientOrgAndConfigMissingFailure(t *testing.T) { _, err := NewFabricCAClient("", configImp, cryptoSuiteProvider) if err.Error() != "organization, config and cryptoSuite are required to load CA config" { t.Fatalf("Expected error without oganization information. Got: %s", err.Error()) } _, err = NewFabricCAClient(org1, nil, cryptoSuiteProvider) if err.Error() != "organization, config and cryptoSuite are required to load CA config" { t.Fatalf("Expected error without config information. Got: %s", err.Error()) } _, err = NewFabricCAClient(org1, configImp, nil) if err.Error() != "organization, config and cryptoSuite are required to load CA config" { t.Fatalf("Expected error without cryptosuite information. Got: %s", err.Error()) } } // TestCreateNewFabricCAClientCAConfigMissingFailure will test newFabricCA Client creation with with CAConfig func TestCreateNewFabricCAClientCAConfigMissingFailure(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() mockConfig := mock_apiconfig.NewMockConfig(mockCtrl) mockConfig.EXPECT().CAConfig(org1).Return(nil, errors.New("CAConfig error")) _, err := NewFabricCAClient(org1, mockConfig, cryptoSuiteProvider) if err.Error() != "CAConfig error" { t.Fatalf("Expected error from CAConfig. Got: %s", err.Error()) } } // TestCreateNewFabricCAClientCertFilesMissingFailure will test newFabricCA Client creation with missing CA Cert files func TestCreateNewFabricCAClientCertFilesMissingFailure(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() mockConfig := mock_apiconfig.NewMockConfig(mockCtrl) mockConfig.EXPECT().CAConfig(org1).Return(&config.CAConfig{URL: ""}, nil) mockConfig.EXPECT().CAServerCertPaths(org1).Return(nil, errors.New("CAServerCertPaths error")) _, err := NewFabricCAClient(org1, mockConfig, cryptoSuiteProvider) if err.Error() != "CAServerCertPaths error" { t.Fatalf("Expected error from CAServerCertPaths. Got: %s", err.Error()) } } // TestCreateNewFabricCAClientCertFileErrorFailure will test newFabricCA Client creation with missing CA Cert files, additional scenario func TestCreateNewFabricCAClientCertFileErrorFailure(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() mockConfig := mock_apiconfig.NewMockConfig(mockCtrl) mockConfig.EXPECT().CAConfig(org1).Return(&config.CAConfig{URL: ""}, nil) mockConfig.EXPECT().CAServerCertPaths(org1).Return([]string{"test"}, nil) mockConfig.EXPECT().CAClientCertPath(org1).Return("", errors.New("CAClientCertPath error")) _, err := NewFabricCAClient(org1, mockConfig, cryptoSuiteProvider) if err.Error() != "CAClientCertPath error" { t.Fatalf("Expected error from CAClientCertPath. Got: %s", err.Error()) } } // TestCreateNewFabricCAClientKeyFileErrorFailure will test newFabricCA Client creation with missing CA Cert files and missing key func TestCreateNewFabricCAClientKeyFileErrorFailure(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() mockConfig := mock_apiconfig.NewMockConfig(mockCtrl) mockConfig.EXPECT().CAConfig(org1).Return(&config.CAConfig{URL: ""}, nil) mockConfig.EXPECT().CAServerCertPaths(org1).Return([]string{"test"}, nil) mockConfig.EXPECT().CAClientCertPath(org1).Return("", nil) mockConfig.EXPECT().CAClientKeyPath(org1).Return("", errors.New("CAClientKeyPath error")) _, err := NewFabricCAClient(org1, mockConfig, cryptoSuiteProvider) if err.Error() != "CAClientKeyPath error" { t.Fatalf("Expected error from CAClientKeyPath. Got: %s", err.Error()) } } // TestCreateValidBCCSPOptsForNewFabricClient test newFabricCA Client creation with valid inputs, successful scenario func TestCreateValidBCCSPOptsForNewFabricClient(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() mockConfig := mock_apiconfig.NewMockConfig(mockCtrl) clientMockObject := &config.ClientConfig{Organization: "org1", Logging: config.LoggingType{Level: "info"}, CryptoConfig: config.CCType{Path: "test/path"}} mockConfig.EXPECT().CAConfig(org1).Return(&config.CAConfig{}, nil) mockConfig.EXPECT().CAServerCertPaths(org1).Return([]string{"test"}, nil) mockConfig.EXPECT().CAClientCertPath(org1).Return("", nil) mockConfig.EXPECT().CAClientKeyPath(org1).Return("", nil) mockConfig.EXPECT().CAKeyStorePath().Return(os.TempDir()) mockConfig.EXPECT().Client().Return(clientMockObject, nil) mockConfig.EXPECT().SecurityProvider().Return("SW") mockConfig.EXPECT().SecurityAlgorithm().Return("SHA2") mockConfig.EXPECT().SecurityLevel().Return(256) mockConfig.EXPECT().KeyStorePath().Return("/tmp/msp") mockConfig.EXPECT().Ephemeral().Return(false) newCryptosuiteProvider, err := cryptosuiteimpl.GetSuiteByConfig(mockConfig) if err != nil { t.Fatalf("Expected fabric client ryptosuite to be created with SW BCCS provider, but got %v", err.Error()) } _, err = NewFabricCAClient(org1, mockConfig, newCryptosuiteProvider) if err != nil { t.Fatalf("Expected fabric client to be created with SW BCCS provider, but got %v", err.Error()) } } // readCert Reads a random cert for testing func readCert(t *testing.T) []byte { cert, err := ioutil.ReadFile("testdata/root.pem") if err != nil { t.Fatalf("Error reading cert: %s", err.Error()) } return cert } // TestInterfaces will test if the interface instantiation happens properly, ie no nil returned func TestInterfaces(t *testing.T) { var apiCA ca.FabricCAClient var ca FabricCA apiCA = &ca if apiCA == nil { t.Fatalf("this shouldn't happen.") } }
[ 3 ]
package azureCosmos import ( "encoding/json" "log" "users/internal/userDB/adapter" . "github.com/Azure/azure-sdk-for-go/services/cosmos-db/mongodb" "github.com/globalsign/mgo" "github.com/globalsign/mgo/bson" ) const filePath string = "config/azureConfig.json" type AzureCosmos struct { session *mgo.Session database *mgo.Database } func (azure *AzureCosmos) Connect() error { access := adapter.ReadJSONConfig(filePath) s, err := NewMongoDBClientWithCredentials( access.User, access.Password, access.Host, ) if err != nil { log.Fatal(err) } err = s.Ping() if err != nil { log.Fatal(err) } azure.session = s azure.database = s.DB(access.Database) return nil } func (azure *AzureCosmos) Disconnect() error { azure.database.Session.Close() return nil } func (azure *AzureCosmos) Insert(collection string, obj interface{}) error { insertErr := azure.database.C(collection).Insert(obj) return insertErr } func (azure *AzureCosmos) Update(collection string, id string, obj interface{}) error { updErr := azure.database.C(collection).UpdateId(id, obj) return updErr } func (azure *AzureCosmos) Get(collection string, id string) ([]byte, error) { var data *interface{} getErr := azure.database.C(collection).FindId(id).One(&data) if getErr != nil { // no entrie found return nil, getErr } bytes, parseErr := json.Marshal(data) return bytes, parseErr } func (azure *AzureCosmos) Find(collection string, fieldname string, value string) ([]byte, error) { var data *interface{} getErr := azure.database.C(collection).Find(bson.D{{fieldname, value}}).One(&data) if getErr != nil { // no entrie found return nil, getErr } bytes, parseErr := json.Marshal(data) return bytes, parseErr } func (azure *AzureCosmos) Delete(collection string, id string) error { remErr := azure.database.C(collection).RemoveId(id) return remErr }
[ 6 ]
package main import ( "fmt" "math" ) const N = 10001 // Taken from 3.go. // See https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes. func sieve(n int) []int { // Populate 2 to n. +1 size so indexes coincide with values for readabililty. tmp := make([]int, n+1) for i := 2; i <= n; i++ { tmp[i] = i } curr := 2 for curr < n { // 0 represents a 'crossed out' value. for i := 2 * curr; i <= n; i += curr { tmp[i] = 0 } // Skip to next prime number. for curr = curr + 1; curr < n && tmp[curr] == 0; curr++ { } } // Now filter our crossed out set. var ret []int for _, n := range tmp { if n > 0 { ret = append(ret, n) } } return ret } // Get n primes. func primes(n int) []int { // The nth prime is roughly n log n. estimate := n * int(math.Log(float64(n))) var ret []int // Double estimate until we have the primes we need. for len(ret) < n { ret = sieve(estimate) estimate *= 2 } return ret[:n] } func main() { fmt.Println(primes(N)[N-1]) }
[ 0 ]
package main import "fmt" func main() { len := lengthOfLongestSubstring("abcabcbb") fmt.Println("len=", len) len1 := lengthOfLongestSubstring1("abcabcbb") fmt.Println("len=", len1) } func lengthOfLongestSubstring(s string) int { maxStrLen := 0 charMap := make(map[int32]int, 128) //减少内存分配 p := 0 //重复字符的上次出现的索引,上一个重复字符和和当前重复字符的之间的子串即有效子串 for i, char := range s { j, ok := charMap[char] if ok { //字符重复,从重复字符下一位开始重新算子串 if j > p { p = j } } //防止字符串长度为1时,i-p=0 if i+1-p > maxStrLen { maxStrLen = i + 1 - p } charMap[char] = i + 1 } return maxStrLen } func lengthOfLongestSubstring1(s string) int { // 哈希集合,记录每个字符是否出现过 m := map[byte]int{} n := len(s) // 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动 rk, ans := -1, 0 for i := 0; i < n; i++ { if i != 0 { // 左指针向右移动一格,移除一个字符 delete(m, s[i-1]) } for rk+1 < n && m[s[rk+1]] == 0 { // 不断地移动右指针 m[s[rk+1]]++ rk++ } // 第 i 到 rk 个字符是一个极长的无重复字符子串 ans = max(ans, rk-i+1) } return ans } func max(x, y int) int { if x < y { return y } return x }
[ 3 ]
// Code generated by mockery v2.32.0. DO NOT EDIT. package mocks import ( context "context" grpc "google.golang.org/grpc" mock "github.com/stretchr/testify/mock" v1 "k8s.io/kubelet/pkg/apis/podresources/v1" ) // PodResourcesListerClient is an autogenerated mock type for the PodResourcesListerClient type type PodResourcesListerClient struct { mock.Mock } // Get provides a mock function with given fields: ctx, in, opts func (_m *PodResourcesListerClient) Get(ctx context.Context, in *v1.GetPodResourcesRequest, opts ...grpc.CallOption) (*v1.GetPodResourcesResponse, error) { _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] } var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *v1.GetPodResourcesResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.GetPodResourcesRequest, ...grpc.CallOption) (*v1.GetPodResourcesResponse, error)); ok { return rf(ctx, in, opts...) } if rf, ok := ret.Get(0).(func(context.Context, *v1.GetPodResourcesRequest, ...grpc.CallOption) *v1.GetPodResourcesResponse); ok { r0 = rf(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.GetPodResourcesResponse) } } if rf, ok := ret.Get(1).(func(context.Context, *v1.GetPodResourcesRequest, ...grpc.CallOption) error); ok { r1 = rf(ctx, in, opts...) } else { r1 = ret.Error(1) } return r0, r1 } // GetAllocatableResources provides a mock function with given fields: ctx, in, opts func (_m *PodResourcesListerClient) GetAllocatableResources(ctx context.Context, in *v1.AllocatableResourcesRequest, opts ...grpc.CallOption) (*v1.AllocatableResourcesResponse, error) { _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] } var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *v1.AllocatableResourcesResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.AllocatableResourcesRequest, ...grpc.CallOption) (*v1.AllocatableResourcesResponse, error)); ok { return rf(ctx, in, opts...) } if rf, ok := ret.Get(0).(func(context.Context, *v1.AllocatableResourcesRequest, ...grpc.CallOption) *v1.AllocatableResourcesResponse); ok { r0 = rf(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.AllocatableResourcesResponse) } } if rf, ok := ret.Get(1).(func(context.Context, *v1.AllocatableResourcesRequest, ...grpc.CallOption) error); ok { r1 = rf(ctx, in, opts...) } else { r1 = ret.Error(1) } return r0, r1 } // List provides a mock function with given fields: ctx, in, opts func (_m *PodResourcesListerClient) List(ctx context.Context, in *v1.ListPodResourcesRequest, opts ...grpc.CallOption) (*v1.ListPodResourcesResponse, error) { _va := make([]interface{}, len(opts)) for _i := range opts { _va[_i] = opts[_i] } var _ca []interface{} _ca = append(_ca, ctx, in) _ca = append(_ca, _va...) ret := _m.Called(_ca...) var r0 *v1.ListPodResourcesResponse var r1 error if rf, ok := ret.Get(0).(func(context.Context, *v1.ListPodResourcesRequest, ...grpc.CallOption) (*v1.ListPodResourcesResponse, error)); ok { return rf(ctx, in, opts...) } if rf, ok := ret.Get(0).(func(context.Context, *v1.ListPodResourcesRequest, ...grpc.CallOption) *v1.ListPodResourcesResponse); ok { r0 = rf(ctx, in, opts...) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*v1.ListPodResourcesResponse) } } if rf, ok := ret.Get(1).(func(context.Context, *v1.ListPodResourcesRequest, ...grpc.CallOption) error); ok { r1 = rf(ctx, in, opts...) } else { r1 = ret.Error(1) } return r0, r1 } // NewPodResourcesListerClient creates a new instance of PodResourcesListerClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewPodResourcesListerClient(t interface { mock.TestingT Cleanup(func()) }) *PodResourcesListerClient { mock := &PodResourcesListerClient{} mock.Mock.Test(t) t.Cleanup(func() { mock.AssertExpectations(t) }) return mock }
[ 4 ]
package timerDeal //cron // c := cron.New() // c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") }) // c.AddFunc("@hourly", func() { fmt.Println("Every hour") }) // c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") }) // c.Start()
[ 3 ]
/* 327. Count of Range Sum Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive. Note: A naive algorithm of O(n2) is trivial. You MUST do better than that. Example: Input: nums = [-2,5,-1], lower = -2, upper = 2, Output: 3 Explanation: The three ranges are : [0,0], [2,2], [0,2] and their respective sums are: -2, -1, 2. */ package main import "fmt" func main() { nums := []int{-2, 5, -1} fmt.Println(countRangeSum(nums, -2, 2)) } // method 1 ,Time Limit Exceeded func countRangeSum1(nums []int, lower int, upper int) int { rst := 0 for i := 0; i < len(nums); i++ { for j := i; j < len(nums); j++ { tmp := 0 for k := i; k <= j; k++ { // s(i,j) tmp += nums[k] } if tmp <= upper && tmp >= lower { rst++ } } } return rst } func countRangeSum(nums []int, lower int, upper int) int { rst := 0 lenNums := len(nums) for i := 0; i < lenNums; i++ { tmp := 0 for j := i; j < lenNums; j++ { if i == j { tmp = nums[i] } else { tmp = tmp + nums[j] } if tmp <= upper && tmp >= lower { rst++ } } } return rst }
[ 0, 6 ]
package utils func GetDirAndFileName(path string) (dir string, fileName string) { dirEndIndex := -1 for i := 0; i < len(path); i++ { if string(path[i]) == "/" { dirEndIndex = i } } if dirEndIndex == -1 { return ".", path } return path[0:dirEndIndex], path[dirEndIndex+1:] }
[ 6 ]
package sharetype import ( "sync" "time" "github.com/sirupsen/logrus" _ "gopkg.in/yaml.v2" ) type ( //DrillDataType drill basic data struct DrillDataType struct { OperationList []OperationOne Summarysheet []SummarysheetT SteamCh chan OperationOne ScapeDataCh chan ScapeDataD ErrCh chan error DoneCh chan struct{} Done chan struct{} TimelimitCh chan struct{} DoneSummary chan struct{} ScapeFullData bool LastScapeData ScapeDataD ScapeData ScapeDataD ActiveOperation int Temp struct { LastToolDepht float32 LastTimeToolDepht time.Time StartDepht float32 LastStartData ScapeDataD LastTripData ScapeDataD FlagChangeTrip int } StartActiveOperation time.Time //Operationtype OperationtypeD Log *logrus.Logger Mu *sync.RWMutex Cfg *ConfigDt } //SummarysheetT -type result list SummarysheetT struct { Sheet OperationOne Details []OperationOne } //OperationtypeD array drilling type operation /* 0 - Бурение 1 - Наращивание 2 - Промывка 3 - Проработка 4 - Подъем 5 - Спуск 6 - Работа т/с 7 - Бурение ротор 8 - Бурение (слайд) 9 - ПЗР 10- КНБК */ OperationtypeD [15]string //ScapeDataD time series data ScapeDataD struct { Id string Time time.Time Count int Values [20]float32 /*0-Дата Время 1-Время Дата 2=Глубина забоя 3=Положение долота 4=Давление на манифольде 5=Расход на входе 6=Нагрузка на долото 7=Вес на крюке 8=Крутящий момент на роторе 9=Число оборотов ротора в мин. 10=Число свечей 11=Положение долота по свечам */ } //OperationOne description of one operation OperationOne struct { Status string StartData, StopData, MaxData, MinData, Agv ScapeDataD Lastchangeoperation string Count int Operaton string Params string } ) /* var DrillOperationConst = [15]string{"Бурение", "Наращивание", "Промывка", "Проработка", "Подъем", "Спуск", "Работа т/с", "Бурение (ротор)", "Бурение (слайд)", "ПЗР", "", "", "", "", ""} */ //ScapeParamtype - scape parametrs yaml type ScapeParamtype struct { Name string `yaml:"Name"` Gid int `yaml:"Gid"` Delta float32 `yaml:"Delta"` } //ConfigDt - configuration structure yaml type type ConfigDt struct { Pmin float32 `yaml:"Pmin"` Flowmin float32 `yaml:"Flowmin"` Rotationmin float32 `yaml:"Rotationmin"` PresFlowCheck int `yaml:"PresFlowCheck"` DephtTool float32 `yaml:"DephtTool"` RotorSl int `yaml:"RotorSl "` DirectionalCheck int `yaml:"DirectionalCheck"` BeforeDrillString string `yaml:"BeforeDrillString"` ShowParamRotSl int `yaml:"ShowParamRotSl "` ShowParamCircl int `yaml:"ShowParamCircl"` ShowParamWiper int `yaml:"ShowParamWiper"` ChangeCircWiperfromDrill int `yaml:"ChangeCircWiperfromDrill"` Avgstand float32 `yaml:"Avgstand"` Wbitmax float32 `yaml:"Wbitmax"` Pressmax float32 `yaml:"Pressmax"` TimeIntervalAll int `yaml:"TimeIntervalAll"` TimeIntervalMkTrip int `yaml:"TimeIntervalMkTrip"` TimeIntervalMaxMkconn int `yaml:"TimeIntervalMaxMkconn"` TimeIntervalKNBK int `yaml:"TimeIntervalKNBK"` MinLenforTrip int `yaml:"MinLenforTrip"` ScapeParam []ScapeParamtype `yaml:"Scapeparam"` Operationtype [15]string `yaml:"Operationtype"` } /* type ConfigDt struct { Pmin float32 `json:"Pmin"` Flowmin float32 `json:"Flowmin"` PresFlowCheck int `json:"PresFlowCheck"` DephtTool float32 `json:"DephtTool"` RotorSl int `json:"RotorSl"` DirectionalCheck int `json:"DirectionalCheck"` BeforeDrillString string ShowParamRotSl int `json:"ShowParamRotSl"` ShowParamCircl int `json:"ShowParamCircl"` ShowParamWiper int `json:"ShowParamWiper"` ChangeCircWiperfromDrill int `json:"ChangeCircWiperfromDrill"` Avgstand float32 `json:"Avgstand"` Wbitmax float32 `json:"Wbitmax"` Pressmax float32 `json:"Pressmax"` TimeIntervalAll int `json:"TimeIntervalAll"` TimeIntervalMkTrip int `json:"TimeIntervalMkTrip"` MinLenforTrip int `json:"MinLenforTrip"` ScapeParam []ScapeParamtype Operationtype [15]string } */
[ 3 ]
package protocol import ( "github.com/kaspanet/kaspad/app/protocol/flows/rejects" "github.com/kaspanet/kaspad/infrastructure/network/connmanager" "sync" "sync/atomic" "github.com/kaspanet/kaspad/app/appmessage" "github.com/kaspanet/kaspad/app/protocol/flows/addressexchange" "github.com/kaspanet/kaspad/app/protocol/flows/blockrelay" "github.com/kaspanet/kaspad/app/protocol/flows/handshake" "github.com/kaspanet/kaspad/app/protocol/flows/ping" "github.com/kaspanet/kaspad/app/protocol/flows/transactionrelay" peerpkg "github.com/kaspanet/kaspad/app/protocol/peer" "github.com/kaspanet/kaspad/app/protocol/protocolerrors" "github.com/kaspanet/kaspad/infrastructure/network/addressmanager" "github.com/kaspanet/kaspad/infrastructure/network/netadapter" routerpkg "github.com/kaspanet/kaspad/infrastructure/network/netadapter/router" "github.com/pkg/errors" ) type flowInitializeFunc func(route *routerpkg.Route, peer *peerpkg.Peer) error type flowExecuteFunc func(peer *peerpkg.Peer) type flow struct { name string executeFunc flowExecuteFunc } func (m *Manager) routerInitializer(router *routerpkg.Router, netConnection *netadapter.NetConnection) { // isStopping flag is raised the moment that the connection associated with this router is disconnected // errChan is used by the flow goroutines to return to runFlows when an error occurs. // They are both initialized here and passed to register flows. isStopping := uint32(0) errChan := make(chan error) flows := m.registerFlows(router, errChan, &isStopping) receiveVersionRoute, sendVersionRoute := registerHandshakeRoutes(router) // After flows were registered - spawn a new thread that will wait for connection to finish initializing // and start receiving messages spawn("routerInitializer-runFlows", func() { m.routersWaitGroup.Add(1) defer m.routersWaitGroup.Done() if atomic.LoadUint32(&m.isClosed) == 1 { panic(errors.Errorf("tried to initialize router when the protocol manager is closed")) } isBanned, err := m.context.ConnectionManager().IsBanned(netConnection) if err != nil && !errors.Is(err, addressmanager.ErrAddressNotFound) { panic(err) } if isBanned { log.Infof("Peer %s is banned. Disconnecting...", netConnection) netConnection.Disconnect() return } netConnection.SetOnInvalidMessageHandler(func(err error) { if atomic.AddUint32(&isStopping, 1) == 1 { errChan <- protocolerrors.Wrap(true, err, "received bad message") } }) peer, err := handshake.HandleHandshake(m.context, netConnection, receiveVersionRoute, sendVersionRoute, router.OutgoingRoute()) if err != nil { // non-blocking read from channel select { case innerError := <-errChan: if errors.Is(err, routerpkg.ErrRouteClosed) { m.handleError(innerError, netConnection, router.OutgoingRoute()) } else { log.Errorf("Peer %s sent invalid message: %s", netConnection, innerError) m.handleError(err, netConnection, router.OutgoingRoute()) } default: m.handleError(err, netConnection, router.OutgoingRoute()) } return } defer m.context.RemoveFromPeers(peer) removeHandshakeRoutes(router) flowsWaitGroup := &sync.WaitGroup{} err = m.runFlows(flows, peer, errChan, flowsWaitGroup) if err != nil { m.handleError(err, netConnection, router.OutgoingRoute()) // We call `flowsWaitGroup.Wait()` in two places instead of deferring, because // we already defer `m.routersWaitGroup.Done()`, so we try to avoid error prone // and confusing use of multiple dependent defers. flowsWaitGroup.Wait() return } flowsWaitGroup.Wait() }) } func (m *Manager) handleError(err error, netConnection *netadapter.NetConnection, outgoingRoute *routerpkg.Route) { if protocolErr := (protocolerrors.ProtocolError{}); errors.As(err, &protocolErr) { if !m.context.Config().DisableBanning && protocolErr.ShouldBan { log.Warnf("Banning %s (reason: %s)", netConnection, protocolErr.Cause) err := m.context.ConnectionManager().Ban(netConnection) if !errors.Is(err, connmanager.ErrCannotBanPermanent) { panic(err) } err = outgoingRoute.Enqueue(appmessage.NewMsgReject(protocolErr.Error())) if err != nil && !errors.Is(err, routerpkg.ErrRouteClosed) { panic(err) } } log.Infof("Disconnecting from %s (reason: %s)", netConnection, protocolErr.Cause) netConnection.Disconnect() return } if errors.Is(err, routerpkg.ErrTimeout) { log.Warnf("Got timeout from %s. Disconnecting...", netConnection) netConnection.Disconnect() return } if errors.Is(err, routerpkg.ErrRouteClosed) { return } panic(err) } func (m *Manager) registerFlows(router *routerpkg.Router, errChan chan error, isStopping *uint32) (flows []*flow) { flows = m.registerAddressFlows(router, isStopping, errChan) flows = append(flows, m.registerBlockRelayFlows(router, isStopping, errChan)...) flows = append(flows, m.registerPingFlows(router, isStopping, errChan)...) flows = append(flows, m.registerTransactionRelayFlow(router, isStopping, errChan)...) flows = append(flows, m.registerRejectsFlow(router, isStopping, errChan)...) return flows } func (m *Manager) registerAddressFlows(router *routerpkg.Router, isStopping *uint32, errChan chan error) []*flow { outgoingRoute := router.OutgoingRoute() return []*flow{ m.registerFlow("SendAddresses", router, []appmessage.MessageCommand{appmessage.CmdRequestAddresses}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return addressexchange.SendAddresses(m.context, incomingRoute, outgoingRoute) }, ), m.registerOneTimeFlow("ReceiveAddresses", router, []appmessage.MessageCommand{appmessage.CmdAddresses}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return addressexchange.ReceiveAddresses(m.context, incomingRoute, outgoingRoute, peer) }, ), } } func (m *Manager) registerBlockRelayFlows(router *routerpkg.Router, isStopping *uint32, errChan chan error) []*flow { outgoingRoute := router.OutgoingRoute() return []*flow{ m.registerOneTimeFlow("SendVirtualSelectedParentInv", router, []appmessage.MessageCommand{}, isStopping, errChan, func(route *routerpkg.Route, peer *peerpkg.Peer) error { return blockrelay.SendVirtualSelectedParentInv(m.context, outgoingRoute, peer) }), m.registerFlow("HandleRelayInvs", router, []appmessage.MessageCommand{ appmessage.CmdInvRelayBlock, appmessage.CmdBlock, appmessage.CmdBlockLocator, appmessage.CmdIBDBlock, appmessage.CmdDoneHeaders, appmessage.CmdUnexpectedPruningPoint, appmessage.CmdPruningPointUTXOSetChunk, appmessage.CmdBlockHeaders, appmessage.CmdPruningPointHash, appmessage.CmdIBDBlockLocatorHighestHash, appmessage.CmdIBDBlockLocatorHighestHashNotFound, appmessage.CmdDonePruningPointUTXOSetChunks}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return blockrelay.HandleRelayInvs(m.context, incomingRoute, outgoingRoute, peer) }, ), m.registerFlow("HandleRelayBlockRequests", router, []appmessage.MessageCommand{appmessage.CmdRequestRelayBlocks}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return blockrelay.HandleRelayBlockRequests(m.context, incomingRoute, outgoingRoute, peer) }, ), m.registerFlow("HandleRequestBlockLocator", router, []appmessage.MessageCommand{appmessage.CmdRequestBlockLocator}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return blockrelay.HandleRequestBlockLocator(m.context, incomingRoute, outgoingRoute) }, ), m.registerFlow("HandleRequestHeaders", router, []appmessage.MessageCommand{appmessage.CmdRequestHeaders, appmessage.CmdRequestNextHeaders}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return blockrelay.HandleRequestHeaders(m.context, incomingRoute, outgoingRoute, peer) }, ), m.registerFlow("HandleRequestPruningPointUTXOSetAndBlock", router, []appmessage.MessageCommand{appmessage.CmdRequestPruningPointUTXOSetAndBlock, appmessage.CmdRequestNextPruningPointUTXOSetChunk}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return blockrelay.HandleRequestPruningPointUTXOSetAndBlock(m.context, incomingRoute, outgoingRoute) }, ), m.registerFlow("HandleIBDBlockRequests", router, []appmessage.MessageCommand{appmessage.CmdRequestIBDBlocks}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return blockrelay.HandleIBDBlockRequests(m.context, incomingRoute, outgoingRoute) }, ), m.registerFlow("HandlePruningPointHashRequests", router, []appmessage.MessageCommand{appmessage.CmdRequestPruningPointHash}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return blockrelay.HandlePruningPointHashRequests(m.context, incomingRoute, outgoingRoute) }, ), m.registerFlow("HandleIBDBlockLocator", router, []appmessage.MessageCommand{appmessage.CmdIBDBlockLocator}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return blockrelay.HandleIBDBlockLocator(m.context, incomingRoute, outgoingRoute, peer) }, ), } } func (m *Manager) registerPingFlows(router *routerpkg.Router, isStopping *uint32, errChan chan error) []*flow { outgoingRoute := router.OutgoingRoute() return []*flow{ m.registerFlow("ReceivePings", router, []appmessage.MessageCommand{appmessage.CmdPing}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return ping.ReceivePings(m.context, incomingRoute, outgoingRoute) }, ), m.registerFlow("SendPings", router, []appmessage.MessageCommand{appmessage.CmdPong}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return ping.SendPings(m.context, incomingRoute, outgoingRoute, peer) }, ), } } func (m *Manager) registerTransactionRelayFlow(router *routerpkg.Router, isStopping *uint32, errChan chan error) []*flow { outgoingRoute := router.OutgoingRoute() return []*flow{ m.registerFlowWithCapacity("HandleRelayedTransactions", 10_000, router, []appmessage.MessageCommand{appmessage.CmdInvTransaction, appmessage.CmdTx, appmessage.CmdTransactionNotFound}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return transactionrelay.HandleRelayedTransactions(m.context, incomingRoute, outgoingRoute) }, ), m.registerFlow("HandleRequestTransactions", router, []appmessage.MessageCommand{appmessage.CmdRequestTransactions}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return transactionrelay.HandleRequestedTransactions(m.context, incomingRoute, outgoingRoute) }, ), } } func (m *Manager) registerRejectsFlow(router *routerpkg.Router, isStopping *uint32, errChan chan error) []*flow { outgoingRoute := router.OutgoingRoute() return []*flow{ m.registerFlow("HandleRejects", router, []appmessage.MessageCommand{appmessage.CmdReject}, isStopping, errChan, func(incomingRoute *routerpkg.Route, peer *peerpkg.Peer) error { return rejects.HandleRejects(m.context, incomingRoute, outgoingRoute) }, ), } } func (m *Manager) registerFlow(name string, router *routerpkg.Router, messageTypes []appmessage.MessageCommand, isStopping *uint32, errChan chan error, initializeFunc flowInitializeFunc) *flow { route, err := router.AddIncomingRoute(messageTypes) if err != nil { panic(err) } return m.registerFlowForRoute(route, name, isStopping, errChan, initializeFunc) } func (m *Manager) registerFlowWithCapacity(name string, capacity int, router *routerpkg.Router, messageTypes []appmessage.MessageCommand, isStopping *uint32, errChan chan error, initializeFunc flowInitializeFunc) *flow { route, err := router.AddIncomingRouteWithCapacity(capacity, messageTypes) if err != nil { panic(err) } return m.registerFlowForRoute(route, name, isStopping, errChan, initializeFunc) } func (m *Manager) registerFlowForRoute(route *routerpkg.Route, name string, isStopping *uint32, errChan chan error, initializeFunc flowInitializeFunc) *flow { return &flow{ name: name, executeFunc: func(peer *peerpkg.Peer) { err := initializeFunc(route, peer) if err != nil { m.context.HandleError(err, name, isStopping, errChan) return } }, } } func (m *Manager) registerOneTimeFlow(name string, router *routerpkg.Router, messageTypes []appmessage.MessageCommand, isStopping *uint32, stopChan chan error, initializeFunc flowInitializeFunc) *flow { route, err := router.AddIncomingRoute(messageTypes) if err != nil { panic(err) } return &flow{ name: name, executeFunc: func(peer *peerpkg.Peer) { defer func() { err := router.RemoveRoute(messageTypes) if err != nil { panic(err) } }() err := initializeFunc(route, peer) if err != nil { m.context.HandleError(err, name, isStopping, stopChan) return } }, } } func registerHandshakeRoutes(router *routerpkg.Router) ( receiveVersionRoute *routerpkg.Route, sendVersionRoute *routerpkg.Route) { receiveVersionRoute, err := router.AddIncomingRoute([]appmessage.MessageCommand{appmessage.CmdVersion}) if err != nil { panic(err) } sendVersionRoute, err = router.AddIncomingRoute([]appmessage.MessageCommand{appmessage.CmdVerAck}) if err != nil { panic(err) } return receiveVersionRoute, sendVersionRoute } func removeHandshakeRoutes(router *routerpkg.Router) { err := router.RemoveRoute([]appmessage.MessageCommand{appmessage.CmdVersion, appmessage.CmdVerAck}) if err != nil { panic(err) } }
[ 6 ]
// Package task4 Реализовать набор из N воркеров, // которые читают из канала произвольные данные и выводят в stdout. // Данные в канал пишутся из главного потока. // Необходима возможность выбора кол-во воркеров при старте, // а также способ завершения работы всех воркеров. package task4 import ( "context" "fmt" "os" "os/signal" "sync" "syscall" ) // Start with workerPoolSize param func Start(workerPoolSize int) { consumer := Consumer{ inputChan: make(chan int, workerPoolSize*10), jobsChan: make(chan int, workerPoolSize), } //generator := Generator{callbackFunc: consumer.callbackFunc} generator := FiniteGenerator{consumer} ctx, cancelFunc := context.WithCancel(context.Background()) wg := &sync.WaitGroup{} generator.start() //go generator.start(ctx) go consumer.startConsumer(ctx, cancelFunc) wg.Add(workerPoolSize) for i := 0; i < workerPoolSize; i++ { go consumer.workerFunc(wg, i) } // chan for terminated signals termChan := make(chan os.Signal, 1) signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGTSTP) select { case <-termChan: // if terminated fmt.Println("=========Shutdown Signal=========") cancelFunc() case <-ctx.Done(): // if normally exited fmt.Println("=========Normally exited==========") } // Wait until all workers gracefully interupted wg.Wait() fmt.Println("==============All workers done!========") }
[ 3 ]
package main import ( "flag" "net/http" "os" "time" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/common/promlog" "github.com/prometheus/common/version" ) const ( AVI_API_VERSION = "18.2.1" AVI_TENANT = "*" ) var ( hosturl = flag.String(os.Getenv("AVI_CLUSTER"), "", "AVI Cluster URL.") listenAddress = flag.String("web.listen-address", ":9300", "Address to listen on for web interface and telemetry.") metricsPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.") aviDuration = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "avi_collection_durations_seconds", Help: "Duration of collections by the AVI exporter", }, []string{"controller"}, ) aviRequestErrors = prometheus.NewCounter( prometheus.CounterOpts{ Name: "avi_request_errors_total", Help: "Errors in requests to the AVI exporter", }, ) ) func init() { prometheus.MustRegister(aviDuration) prometheus.MustRegister(aviRequestErrors) prometheus.MustRegister(version.NewCollector("avi_exporter")) } func handler(w http.ResponseWriter, r *http.Request, username string, password string, logger log.Logger) { query := r.URL.Query() // Gather controller name from query string controller := query.Get("controller") if (len(query["controller"]) != 1) || (controller == "") { http.Error(w, "'controller' parameter must be specified once.", 400) aviRequestErrors.Inc() return } // Gather tenant information from query string tenant := query.Get("tenant") if len(query["tenant"]) > 1 { http.Error(w, "'tenant' parameter can only be specified once.", 400) aviRequestErrors.Inc() return } if tenant == "" { tenant = AVI_TENANT } // Gather AVI API Version from query string api_version := query.Get("api_version") if len(query["api_version"]) > 1 { http.Error(w, "'api_version' parameter can only be specified once.", 400) aviRequestErrors.Inc() return } if api_version == "" { api_version = AVI_API_VERSION } logger = log.With(logger, "controller", controller, "tenant", tenant, "api_version", api_version) level.Debug(logger).Log("msg", "Starting scrape") start := time.Now() registry := prometheus.NewRegistry() collector := collector{ctx: r.Context(), controller: controller, tenant: tenant, api_version: api_version, username: username, password: password, logger: logger} registry.MustRegister(collector) // Delegate http serving to Prometheus client library, which will calll collector.Collect h := promhttp.HandlerFor(registry, promhttp.HandlerOpts{}) h.ServeHTTP(w, r) duration := time.Since(start).Seconds() aviDuration.WithLabelValues(controller).Observe(duration) level.Debug(logger).Log("msg", "Finished scrape", "duration_seconds", duration) } func main() { logLevel := &promlog.AllowedLevel{} logLevel.Set("debug") logFormat := &promlog.AllowedFormat{} promlogConfig := &promlog.Config{Level: logLevel, Format: logFormat} flag.Parse() logger := promlog.New(promlogConfig) username := os.Getenv("AVI_USERNAME") password := os.Getenv("AVI_PASSWORD") if username == "" { level.Error(logger).Log("msg", "AVI_USERNAME environment variable must be set.") os.Exit(1) } else if password == "" { level.Error(logger).Log("msg", "AVI_PASSWORD environment variable must be set.") os.Exit(1) } level.Info(logger).Log("msg", "Starting avi_exporter", "version", version.Info()) level.Info(logger).Log("build_context", version.BuildContext()) // Set various http endpoints. http.Handle("/metrics", promhttp.Handler()) http.HandleFunc("/avi", func(w http.ResponseWriter, r *http.Request) { handler(w, r, username, password, logger) }) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`<html> <head> <title>AVI Exporter</title> <style> label{ display:inline-block; width:75px; } form label { margin: 10px; } form input { margin: 10px; } </style> </head> <body> <h1>AVI Exporter</h1> <p><a href='` + *metricsPath + `'>Metrics</a></p> <form action="/avi"> <label>Controller:</label><input type="text" name="controller" placeholder="avi.hostname" value="avi.hostname"><br> <label>API Version:</label><input type="text" name="api_version" placeholder="20.1.4" value="20.1.4"><br> <label>Tenant:</label><input type="text" name="tenant" placeholder="admin" value="admin"><br> <input type="submit" value="Submit"> </form> </body> </html>`)) }) level.Info(logger).Log("msg", "Listening on address", "address", *listenAddress) if err := http.ListenAndServe(*listenAddress, nil); err != nil { level.Error(logger).Log("msg", "Error starting HTTP server", "err", err) os.Exit(1) } }
[ 6 ]
package services import ( "context" "net/http" "strings" "time" "wallawire/logging" "wallawire/model" ) const ( componentUserService = "UserService" ) type UserRepository interface { GetUser(context.Context, model.ReadOnlyTransaction, string) (*model.User, error) GetActiveUserByUsername(context.Context, model.ReadOnlyTransaction, string) (*model.User, error) GetUserRoles(context.Context, model.ReadOnlyTransaction, string, *time.Time) ([]model.UserRole, error) IsUsernameAvailable(context.Context, model.ReadOnlyTransaction, string) (bool, error) SetUser(context.Context, model.WriteOnlyTransaction, model.User) error } type IdGenerator interface { NewID() string } // TODO: need policy func isValidPassword(password string) bool { if l := len(strings.TrimSpace(password)); l >= 8 && l <= 72 { return true } return false } // TODO: need policy func isValidUsername(username string) bool { if l := len(strings.TrimSpace(username)); l >= 3 && l <= 64 { return true } return false } type UserService struct { db model.Database userRepo UserRepository idgen IdGenerator } func NewUserService(db model.Database, userRepo UserRepository, idgen IdGenerator) *UserService { return &UserService{ db: db, userRepo: userRepo, idgen: idgen, } } func (z *UserService) ChangeUsername(ctx context.Context, req model.ChangeUsernameRequest) model.ChangeUsernameResponse { logger := logging.New(ctx, componentUserService, "ChangeUsername") var user *model.User var roles []model.UserRole err := z.db.Run(func(tx model.Transaction) error { u, errGet := z.userRepo.GetUser(ctx, tx, req.UserID) if errGet != nil { logger.Error().Err(errGet).Msg("repo GetUser") return errGet // 500 } if u == nil { return model.NewNotFoundError("user not found") // 404 } if !u.MatchPassword(req.Password) { return model.NewValidationError("password incorrect") // 400 } // validation of cur if !isValidUsername(req.NewUsername) { return model.NewValidationError("username not valid") // 400 } ok, errCheckUsername := z.userRepo.IsUsernameAvailable(ctx, tx, req.NewUsername) if errCheckUsername != nil { logger.Error().Err(errCheckUsername).Msg("repo IsUsernameAvailable") return errCheckUsername // 500 } if !ok { return model.NewValidationError("username not available") // 400 } u.Username = req.NewUsername if err := z.userRepo.SetUser(ctx, tx, *u); err != nil { logger.Error().Err(err).Msg("repo SetUser") return err // 500 } now := time.Now() rs, errRoles := z.userRepo.GetUserRoles(ctx, tx, u.ID, &now) if errRoles != nil { return errRoles } user = u roles = rs return nil }) rsp := model.ChangeUsernameResponse{} if err != nil { logger.Debug().Err(err).Msg("cannot change username") rsp.Message = err.Error() if model.IsValidationError(err) { rsp.Code = http.StatusBadRequest } else if model.IsNotFoundError(err) { rsp.Code = http.StatusNotFound } else { rsp.Code = http.StatusInternalServerError } } else { logger.Debug().Msg("username updated") suc := model.TokenFromContext(ctx) su := model.ToSessionToken(suc.SessionID, user, roles, suc.Issued, suc.Expires) rsp.Code = http.StatusOK rsp.SessionToken = su } return rsp } func (z *UserService) ChangePassword(ctx context.Context, req model.ChangePasswordRequest) model.ChangePasswordResponse { logger := logging.New(ctx, componentUserService, "ChangePassword") var user *model.User var roles []model.UserRole err := z.db.Run(func(tx model.Transaction) error { u, errGet := z.userRepo.GetUser(ctx, tx, req.UserID) if errGet != nil { logger.Error().Err(errGet).Msg("repo GetUser") return errGet // 500 } if u == nil { return model.NewNotFoundError("user not found") // 404 } if !u.MatchPassword(req.Password) { return model.NewValidationError("password incorrect") // 400 } if !isValidPassword(req.NewPassword) { return model.NewValidationError("invalid new password") // 400 } if err := u.SetPassword(req.NewPassword); err != nil { logger.Error().Err(err).Msg("user SetPassword") return err // 500 } if err := z.userRepo.SetUser(ctx, tx, *u); err != nil { logger.Error().Err(err).Msg("repo SetUser") return err // 500 } now := time.Now() rs, errRoles := z.userRepo.GetUserRoles(ctx, tx, u.ID, &now) if errRoles != nil { return errRoles } user = u roles = rs return nil }); rsp := model.ChangePasswordResponse{} if err != nil { logger.Debug().Err(err).Msg("password NOT updated") rsp.Message = err.Error() if model.IsValidationError(err) { rsp.Code = http.StatusBadRequest } else if model.IsNotFoundError(err) { rsp.Code = http.StatusNotFound } else { rsp.Code = http.StatusInternalServerError } } else { logger.Debug().Msg("password updated") suc := model.TokenFromContext(ctx) su := model.ToSessionToken(suc.SessionID, user, roles, suc.Issued, suc.Expires) rsp.Code = http.StatusOK rsp.SessionToken = su } return rsp } func (z *UserService) ChangeProfile(ctx context.Context, req model.ChangeProfileRequest) model.ChangeProfileResponse { logger := logging.New(ctx, componentUserService, "ChangeProfile") var user *model.User var roles []model.UserRole err := z.db.Run(func(tx model.Transaction) error { u, errGet := z.userRepo.GetUser(ctx, tx, req.UserID) if errGet != nil { logger.Error().Err(errGet).Msg("repo GetUser") return errGet // 500 } if u == nil { return model.NewNotFoundError("user not found") // 404 } // validation of cur if !isValidUsername(req.Displayname) { return model.NewValidationError("displayname not valid") // 400 } u.Name = req.Displayname if err := z.userRepo.SetUser(ctx, tx, *u); err != nil { logger.Error().Err(err).Msg("repo SetUser") return err // 500 } now := time.Now() rs, errRoles := z.userRepo.GetUserRoles(ctx, tx, u.ID, &now) if errRoles != nil { return errRoles } user = u roles = rs return nil }) rsp := model.ChangeProfileResponse{} if err != nil { logger.Debug().Err(err).Msg("cannot change profile") rsp.Message = err.Error() if model.IsValidationError(err) { rsp.Code = http.StatusBadRequest } else if model.IsNotFoundError(err) { rsp.Code = http.StatusNotFound } else { rsp.Code = http.StatusInternalServerError } } else { logger.Debug().Msg("profile updated") rsp.Code = http.StatusOK suc := model.TokenFromContext(ctx) su := model.ToSessionToken(suc.SessionID, user, roles, suc.Issued, suc.Expires) rsp.SessionToken = su } return rsp } func (z *UserService) Login(ctx context.Context, req model.LoginRequest) model.LoginResponse { logger := logging.New(ctx, componentUserService, "Login") // db username field is 64, go bcrypt max is 72 if x, y := len(req.Username), len(req.Password); x == 0 || y == 0 || x > 64 || y > 72 { msg := "invalid username/password" logger.Debug().Msg(msg) return model.LoginResponse{ Code: http.StatusBadRequest, Message: msg, } } var user *model.User var roles []model.UserRole err := z.db.Run(func(tx model.Transaction) error { usr, errGet := z.userRepo.GetActiveUserByUsername(ctx, tx, req.Username) if errGet != nil { logger.Error().Err(errGet).Msg("repo GetActiveUserByUsername") return errGet // 500 } if usr == nil { // 400 - do not give out info that user does not exist at login return model.NewValidationError("invalid username/password") } if !usr.MatchPassword(req.Password) { return model.NewValidationError("invalid username/password") // 400 } now := time.Now() rs, errRoles := z.userRepo.GetUserRoles(ctx, tx, usr.ID, &now) if errRoles != nil { return errRoles } user = usr roles = rs return nil }); rsp := model.LoginResponse{} if err != nil { logger.Debug().Err(err).Msg("cannot login") rsp.Message = err.Error() if model.IsValidationError(err) { rsp.Code = http.StatusBadRequest } else { rsp.Code = http.StatusInternalServerError } } else { sessionID := z.idgen.NewID() rsp.Code = http.StatusOK issued := time.Now().Truncate(time.Minute) expires := issued.Add(model.LoginTimeout) rsp.SessionToken = model.ToSessionToken(sessionID, user, roles, issued, expires) logger.Info().Str("username", user.Username).Str("UserID", user.ID).Str("SessionID", sessionID).Msg("login") } return rsp }
[ 5 ]
package main import ( "bytes" "crypto/sha1" "encoding/base64" "encoding/csv" "fmt" "github.com/antchfx/htmlquery" "io/ioutil" "log" "net/http" "os" "strings" ) func getURL(url string) (string, error) { resp, err := http.Get(url) if err != nil { return "", fmt.Errorf("error downloading url: %v", err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("error during readall operation for url: %v", err) } return string(body), nil } func getURLExtended(url string, method string, content string, hdr map[string]string) (string, error) { if (method != "GET") && (method != "POST") { return "", fmt.Errorf("unsupported HTTP method [%s]", method) } req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(content))) if err != nil { return "", fmt.Errorf("cannot init HTTP Request to %s with error: %v", url, err) } // Fill headers for k, v := range hdr { req.Header.Set(k, v) } client := &http.Client{} resp, err := client.Do(req) if err != nil { return "", fmt.Errorf("error during HTTP request to page [%s] with error: %v", url, err) } defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) return string(body), nil } func getEntryURLs(baseurl string) (list []string, err error) { var count int for { data, err := getURLExtended(baseurl, "GET", "", map[string]string{"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0"}) if err != nil { if count < 1 { fmt.Println("Cannot download first url:", baseurl) return list, err } return list, err } r := bytes.NewReader([]byte(data)) doc, err := htmlquery.Parse(r) if err != nil { if count < 1 { fmt.Println("Cannot load HTML for first url:", baseurl) return list, err } // Don't treat as error if we cannot download 2nd or more url return list, nil } nodes, err := htmlquery.QueryAll(doc, "//li/a/@href") if (err != nil) || (nodes == nil) { if count < 1 { fmt.Println("Cannot parse first url:", baseurl) return list, err } } for _, node := range nodes { list = append(list, htmlquery.InnerText(node)) // fmt.Println(htmlquery.InnerText(node)) } count++ node, err := htmlquery.Query(doc, "//button[@href]/@href") if (err == nil) && (node != nil) { baseurl = htmlquery.InnerText(node) //fmt.Println("Next page: ", htmlquery.InnerText(node)) continue } break } err = nil return } func getEntry(url string) (map[string]string, error) { list := make(map[string]string) // Try to use cache cacheFileName := fmt.Sprintf("%s/%x", *CacheDir, sha1.Sum([]byte(url))) data, err := loadCacheFile(cacheFileName) if err != nil { data, err = getURLExtended(url, "GET", "", map[string]string{"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0"}) if err != nil { return list, fmt.Errorf("error downloading entry [%s]: %v", url, err) } saveCacheFile(cacheFileName, data) } r := bytes.NewReader([]byte(data)) doc, err := htmlquery.Parse(r) if err != nil { return list, fmt.Errorf("error parsing entry [%s]: %v", url, err) } // Id list["Id"] = "" // Name if node, err := htmlquery.Query(doc, "//h1"); (err == nil) && (node != nil) { list["Name"] = htmlquery.InnerText(node) } // DateOfCase<br>PlaseOfCase if node, err := htmlquery.Query(doc, "//p[@class=\"summary\"]"); (err == nil) && (node != nil) { s := strings.Split(htmlquery.OutputHTML(node, false), "<br/>") list["DateOfCase"] = s[0] // PlaceOfCase if len(s) > 1 { list["PlaceOfCase"] = s[1] } } if nodes, err := htmlquery.QueryAll(doc, "//div[@class=\"lightbox-content\"]/img/@src"); (err == nil) && (nodes != nil) { // PicUrl // PicBase64 if len(nodes) > 0 { list["PicUrl"] = htmlquery.InnerText(nodes[0]) _, picBase64, _ := downloadImage(*CacheDir, list["PicUrl"]) list["PicBase64"] = picBase64 } // AdditionalPicUrl // AdditionalPicBase64 if len(nodes) > 1 { list["AdditionalPicUrl"] = htmlquery.InnerText(nodes[1]) _, picBase64, _ := downloadImage(*CacheDir, list["AdditionalPicUrl"]) list["AdditionalPicBase64"] = picBase64 } } // Extra params if nodes, err := htmlquery.QueryAll(doc, "//table[@class=\"table table-striped wanted-person-description\"]/tbody/tr"); (err == nil) && (nodes != nil) { for _, node := range nodes { if nodes2, err := htmlquery.QueryAll(node, "//td"); (err == nil) && (nodes2 != nil) { if len(nodes2) == 2 { k := htmlquery.InnerText(nodes2[0]) v := htmlquery.InnerText(nodes2[1]) // fmt.Printf("%s = %s\n", k, v) switch k { // DateOfBirth case "Date(s) of Birth Used": list["DateOfBirth"] = v // PlaceOfBirth case "Place of Birth": list["PlaceOfBirth"] = v // Hair case "Hair": list["Hair"] = v // Eyes case "Eyes": list["Eyes"] = v // Height case "Height": list["Height"] = v // Weight case "Weight": list["Weight"] = v // Sex case "Sex": list["Sex"] = v // Race case "Race": list["Race"] = v // Nationality case "Nationality": list["Nationality"] = v } } } } } // Reward if node, err := htmlquery.Query(doc, "//div[@class=\"wanted-person-reward\"]/p"); (err == nil) && (node != nil) { list["Reward"] = htmlquery.InnerText(node) } // Details if node, err := htmlquery.Query(doc, "//div[@class=\"wanted-person-details\"]/p"); (err == nil) && (node != nil) { list["Details"] = htmlquery.InnerText(node) } // FieldOffice if node, err := htmlquery.Query(doc, "//span[@class=\"field-office\"]/p"); (err == nil) && (node != nil) { list["FieldOffice"] = htmlquery.InnerText(node) } // Source list["Source"] = url // Remarks // Related Case return list, nil } func saveCacheFile(fname string, content string) error { f, err := os.OpenFile(fname, os.O_CREATE|os.O_RDWR, 0755) if err != nil { return err } _, err = f.WriteString(content) defer f.Close() return err } func loadCacheFile(fname string) (string, error) { f, err := os.Open(fname) if err != nil { return "", fmt.Errorf("cannot read datafile [%s] with error: %v", fname, err) } defer f.Close() r, err := ioutil.ReadAll(f) if err != nil { return "", fmt.Errorf("error during reading datafile [%s] with error: %v", fname, err) } return string(r), nil } func generateCSV(fname string, list []map[string]string) { // Create output file if fname == "" { log.Fatal("Output file is not specified, skipping result generation") } fOut, err := os.OpenFile(fname, os.O_CREATE|os.O_RDWR, 0755) if err != nil { log.Fatal("Error creating output file [", *Output, "]: ", err) } csvWriter := csv.NewWriter(fOut) defer fOut.Close() //full answer //csvFieldList := []string{"Id", "Name", "DateOfCase", "PlaceOfCase", "PicUrl", "PicBase64", "AdditionalPicUrl", // "AdditionalPicBase64", "DateOfBirth", "PlaceOfBirth", "Hair", "Eyes", "Height", "Weight", "Sex", "Race", "Nationality", "Reward", // "Remarks", "Details", "FieldOffice", "RelatedCase", "Source"} //for site csvFieldList := []string{"Id","Name","Sex","DateOfBirth","PlaceOfBirth","Nationality","PlaceOfCase","DateOfCase","Details","Height","Hair","Eyes","Source"} csvWriter.Write(csvFieldList) for _, e := range list { output := []string{} for _, k := range csvFieldList { output = append(output, e[k]) } csvWriter.Write(output) /* output := []string{ strconv.FormatInt(r.MissingSince, 10), // DateOfCase fmt.Sprintf("%s,%s,%s", r.Country, r.State, r.City), // PlaceOfCase strconv.FormatInt(chld.BirthDate.int64, 10), // DateOfBirth fmt.Sprintf("%s %s", chld.Height, chld.HeightUnit), // Height fmt.Sprintf("%s %s", chld.Weight, chld.WeightUnit), // Weight fmt.Sprintf("%s%s", *URLCase, r.CaseId), // Source } */ } } func downloadImage(cacheDir, url string) (cacheFileName, dataBase64 string, err error) { // Check for cached image if cacheDir != "" { cacheFileName = fmt.Sprintf("%s/%x", cacheDir, sha1.Sum([]byte(url))) f, err := os.Open(cacheFileName) if err == nil { defer f.Close() r, err := ioutil.ReadAll(f) if err == nil { return cacheFileName, base64.StdEncoding.EncodeToString(r), nil } } } resp, err := http.Get(url) if err != nil { return "", "", fmt.Errorf("error downloading image: %v", err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", "", fmt.Errorf("error during readall operation for image: %v", err) } if cacheDir != "" { if saveCacheFile(cacheFileName, string(body)) == nil { return cacheFileName, base64.StdEncoding.EncodeToString([]byte(body)), nil } } return "", base64.StdEncoding.EncodeToString([]byte(body)), nil }
[ 3, 6 ]
//English description is not available for the problem. Please switch to //Chinese. Related Topics 位运算 数组 哈希表 数学 二分查找 👍 170 👎 0 //一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。 //示例 1: //输入: [0,1,3] //输出: 2 //示例2: //输入: [0,1,2,3,4,5,6,7,9] //输出: 8 //限制: //1 <= 数组长度 <= 10000 package main import "fmt" //leetcode submit region begin(Prohibit modification and deletion) // TODO 二分 //func missingNumber(nums []int) int { // if len(nums) == 1 && nums[0] != 0 { // return 0 // } // l, r := 0, len(nums)-1 // for l < r { // mid := (l + r) / 2 // // } //} func missingNumber(nums []int) int { for i := 0; i < len(nums); i++ { if nums[i] != i { return i } } return nums[len(nums)-1] + 1 } //leetcode submit region end(Prohibit modification and deletion) func main() { fmt.Println(missingNumber([]int{0})) fmt.Println(missingNumber([]int{0, 1})) }
[ 3 ]
package main import ( "CatLegends/events" "CatLegends/utils" "github.com/go-telegram-bot-api/telegram-bot-api/v5" _ "github.com/joho/godotenv/autoload" log "github.com/sirupsen/logrus" "os" "strconv" "strings" ) func init() { log.SetFormatter(&utils.Formatter{}) log.SetReportCaller(true) } func main() { log.Info("Startup") utils.InitDB() defer utils.CloseDB() bot, err := tgbotapi.NewBotAPI(os.Getenv("TOKEN")) if err != nil { log.Fatal(err) } log.Info("Telegram Bot authorized: ", bot.Self.UserName) //bot.Debug = true u := tgbotapi.NewUpdate(0) u.Timeout = 60 updates := bot.GetUpdatesChan(u) for update := range updates { if update.Message != nil && update.Message.Chat.IsPrivate() { chatId := update.Message.Chat.ID msg := tgbotapi.NewMessage(chatId, "") if update.Message.IsCommand() { switch update.Message.Command() { case "start": events.Start(&msg, &update) case "help": events.Help(&msg) case "stats": events.Stats(&msg, chatId) case "inventory": events.Inventory(&msg, chatId, 0) case "battle": events.Battle(&msg, chatId) default: msg.Text = events.UnknownCommandMessage } } else if update.Message.Dice != nil { switch update.Message.Dice.Emoji { case "🎲": events.EscapeStatus(&msg, &update) default: msg.Text = events.UnknownMessage } } else { msg.Text = events.UnknownMessage } if _, err := bot.Send(msg); err != nil { log.Error(err) } continue } if update.CallbackQuery != nil && update.CallbackQuery.Message != nil && update.CallbackQuery.Message.Chat.IsPrivate() { chatId := update.CallbackQuery.Message.Chat.ID msgId := update.CallbackQuery.Message.MessageID cb := tgbotapi.NewCallback(update.CallbackQuery.ID, "") msg := tgbotapi.NewMessage(chatId, "") queryData := strings.Split(update.CallbackQuery.Data, "_") switch queryData[0] { case events.NewPlayerCallback: events.NewPlayer(&cb, chatId, msgId, bot) case events.PlayerStatsCallback: events.Stats(&msg, chatId) cb.Text = "Статистика" case events.PlayerInventoryCallback: events.Inventory(&msg, chatId, 0) cb.Text = "Інвентар" case events.NewBattleCallback: cb.Text = "Бій" case events.NewEscapeCallback: events.Escape(&msg) cb.Text = "Втеча" case "page": page, err := strconv.ParseInt(queryData[1], 10, 32) if err != nil { log.Error(err) cb.Text = events.ErrorText } else { ok := events.UpdateInventory(msgId, chatId, int(page), bot) if !ok { cb.Text = events.NoPlayerText } } case "item": itemInd, err := strconv.ParseInt(queryData[1], 10, 32) if err != nil { log.Error(err) cb.Text = events.ErrorText } else { ok := events.ShowItem(msgId, chatId, int(itemInd), bot) if !ok { cb.Text = events.ErrorText } } default: cb.Text = events.UnknownCallback } if msg.Text != "" { if _, err := bot.Send(msg); err != nil { log.Error(err) cb.Text = events.ErrorText } } if _, err := bot.Send(cb); err != nil { log.Error(err) } continue } } }
[ 3, 5 ]
package http import ( "context" "fmt" "github.com/dgrijalva/jwt-go" "github.com/emeli-frank/pick_go/pkg/domain/user" "github.com/emeli-frank/pick_go/pkg/util/log" "net/http" "strings" ) func (s server) recoverPanic(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { w.Header().Set("Connection", "Close") log.ServerError(w, fmt.Errorf("%s", err), nil) } }() next.ServeHTTP(w, r) }) } func (s server) checkJWT(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { bearerTokenSlice := strings.Split(r.Header.Get("Authorization"), " ") if len(bearerTokenSlice) != 2 || bearerTokenSlice[0] != "Bearer" { //fmt.Println("token not formed properly in header") next.ServeHTTP(w, r) return } tokenStr := bearerTokenSlice[1] type claims struct { User user.User jwt.StandardClaims } c := &claims{} _, err := jwt.ParseWithClaims(tokenStr, c, func(token *jwt.Token) (interface{}, error) { return []byte("my_secrete_key"), nil }) if err != nil { // todo:: add this commented part to the part that fails when no valid jwt is provided /*log.ClientError(w, http.StatusForbidden, []string{"bad authorization blah blah ..."}) return*/ //fmt.Println("invalid token") next.ServeHTTP(w, r) return } u := c.User ctx := context.WithValue(r.Context(), user.ContextKeyUser, &u) next.ServeHTTP(w, r.WithContext(ctx)) }) } /*func (s server) authenticatedOnly(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { bearerTokenSlice := strings.Split(r.Header.Get("Authorization"), " ") if len(bearerTokenSlice) != 2 || bearerTokenSlice[0] != "Bearer"{ err := errors.New("bad authorization blah blah ...") err = errors2.Wrap(err, "authenticatedOnly", "bearers token") // todo:: fix s.response.ClientError(w, http.StatusForbidden, err) return } tokenStr := bearerTokenSlice[1] type claims struct { User user.User jwt.StandardClaims } c := &claims{} _, err := jwt.ParseWithClaims(tokenStr, c, func(token *jwt.Token) (interface{}, error) { return []byte("my_secrete_key"), nil }) if err != nil { log.ClientError(w, http.StatusForbidden, []string{"bad authorization blah blah ..."}) return } next.ServeHTTP(w, r) }) }*/ func (s server) authenticatedOnly(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { u, ok := r.Context().Value(user.ContextKeyUser).(*user.User) if !ok { w.WriteHeader(http.StatusUnauthorized) //fmt.Println("Unauthorized request") return } _ = u //fmt.Println("Authenticated user:", u,) next.ServeHTTP(w, r) }) } func (s server) logRequest(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s.infoLog.Printf("%s - %s %s %s", r.RemoteAddr, r.Proto, r.Method, r.URL) next.ServeHTTP(w, r) }) }
[ 3 ]
package main import "fmt" func maxProduct(nums []int) int { if len(nums) < 1 { return 0 } maxDP := make([]int, len(nums)) minDP := make([]int, len(nums)) maxDP[0] = nums[0] minDP[0] = nums[0] result := nums[0] for i:=1; i<len(nums); i++{ maxDP[i] = max(nums[i], maxDP[i-1]*nums[i], minDP[i-1]*nums[i]) minDP[i] = min(nums[i], maxDP[i-1]*nums[i], minDP[i-1]*nums[i]) if result < maxDP[i] { result = maxDP[i] } } return result } func max(a int, b int, c int) int { if a >= b && a >= c { return a } if b >= a && b >= c { return b } return c } func min(a int, b int, c int) int { if a <= b && a <= c { return a } if b <= a && b <= c { return b } return c } func main() { fmt.Println(maxProduct([]int{-1,-1,-2,-2})) }
[ 6 ]
package main import "fmt" func merge(array []int) ([]int) { if len(array) <= 1 { return array } middle := len(array) / 2 left := merge(array[:middle]) right := merge(array[middle:]) return merge_segs(left, right) } func merge_segs(left []int, right []int) ([]int) { var result []int for len(left) > 0 && len(right) > 0 { if left[0] <= right[0] { result = append(result, left[0]) left = left[1:] } else { result = append(result, right[0]) right = right[1:] } } for len(right) > 0 { result = append(result, right[0]) right = right[1:] } for len(left) > 0 { result = append(result, left[0]) left = left[1:] } return result } /* Testing function */ func main() { array := []int{11, 6, 8, 1, 2, 2, 4, 9} fmt.Println("Unsorted array") fmt.Println(array) fmt.Println("\n Post Merge basic") array = merge(array) fmt.Println(array) }
[ 6 ]
package utils import ( "context" "crypto/rand" "fmt" "io" "log" mrand "math/rand" "github.com/libp2p/go-libp2p" "github.com/libp2p/go-libp2p-core/crypto" "github.com/libp2p/go-libp2p-core/host" plaintext "github.com/libp2p/go-libp2p-core/sec/insecure" noise "github.com/libp2p/go-libp2p-noise" secio "github.com/libp2p/go-libp2p-secio" ma "github.com/multiformats/go-multiaddr" ) // MakeBasicHost creates a LibP2P host with a random peer ID listening on the // given multiaddress. It won't encrypt the connection if insecure is true. func MakeBasicHost(listenPort int, protocolID string, randseed int64) (host.Host, error) { // If the seed is zero, use real cryptographic randomness. Otherwise, use a // deterministic randomness source to make generated keys stay the same // across multiple runs var r io.Reader if randseed == 0 { r = rand.Reader } else { r = mrand.New(mrand.NewSource(randseed)) } // Generate a key pair for this host. We will use it at least // to obtain a valid host ID. priv, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, r) if err != nil { return nil, err } opts := []libp2p.Option{ libp2p.ListenAddrStrings(fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", listenPort)), libp2p.Identity(priv), libp2p.DisableRelay(), } if protocolID == plaintext.ID { opts = append(opts, libp2p.NoSecurity) } else if protocolID == noise.ID { tpt, err := noise.New(priv) if err != nil { return nil, err } opts = append(opts, libp2p.Security(protocolID, tpt)) } else if protocolID == secio.ID { tpt, err := secio.New(priv) if err != nil { return nil, err } opts = append(opts, libp2p.Security(protocolID, tpt)) } else { return nil, fmt.Errorf("security protocolID '%s' is not supported", protocolID) } basicHost, err := libp2p.New(context.Background(), opts...) if err != nil { return nil, err } // Build host multiaddress hostAddr, _ := ma.NewMultiaddr(fmt.Sprintf("/ipfs/%s", basicHost.ID().Pretty())) // Now we can build a full multiaddress to reach this host // by encapsulating both addresses: addr := basicHost.Addrs()[0] fullAddr := addr.Encapsulate(hostAddr) log.Printf("I am %s\n", fullAddr) log.Printf("Now run \"./echo -l %d -d %s -security %s\" on a different terminal\n", listenPort+1, fullAddr, protocolID) return basicHost, nil }
[ 5 ]
package game import ( "math/rand" "time" tl "github.com/JoelOtter/termloop" ) func NewFood() *Target { food := new(Target) food.Entity = tl.NewEntity(1, 1, 2, 2) food.MoveFood() return food } // MoveFood moves the food into a new random position. func (food *Target) MoveFood() { NewX := RandomInsideArena(gameWidth-5, 5) NewY := RandomInsideArena(gameHeight-5, 5) // Changes the X and Y coordinates of the food. food.Foodposition.X = NewX food.Foodposition.Y = NewY food.Emoji = RandomFood() food.SetPosition(food.Foodposition.X, food.Foodposition.Y) } // RandomFood will use the ASCII-charset to pick a random rune from the slice and print it out as food. func RandomFood() rune { emoji := []rune{ 'R', // Favourite dish, extra points!!! '👿', '🍍', '🍑', '🍇', '🍏', '🍌', '🍫', '🍭', '🍕', '🍩', '🍗', '🍖', '🍬', '🍤', '🍪', 'S', // You do not want to eat the skull } rand.Seed(time.Now().UnixNano()) return emoji[rand.Intn(len(emoji))] } // Draw will print out the food on the screen. func (food *Target) Draw(screen *tl.Screen) { screen.RenderCell(food.Foodposition.X, food.Foodposition.Y, &tl.Cell{ Ch: food.Emoji, }) } // Contains checks if food contains the coordinates, if so this will return a bool. func (food *Target) Contains(c Coordinates) bool { return (c.X == food.Foodposition.X || c.X == (food.Foodposition.X+1)) && c.Y == food.Foodposition.Y } // RandomInsideArena will the minimal, which is just inside the border and the maximal, being the arena width or height. func RandomInsideArena(iMax int, iMin int) int { rand.Seed(time.Now().UnixNano()) return rand.Intn(iMax-iMin) + iMin }
[ 6 ]
package jmessage import ( "encoding/json" "errors" "fmt" "io/ioutil" "time" "github.com/franela/goreq" ) // JMUser 用户信息 返回信息 type JMUser struct { Username string `json:"username"` //(必填 Byte(4~128) 开头:字母或者数字 字母、数字、下划线英文点、减号、@ Password string `json:"password"` //(必填) Byte(4~128) 用户密码。极光IM服务器会MD5加密保存 Nickname string `json:"nickname,omitempty"` //Byte(0~64) 不支持的字符:英文字符: \n \r\n Avatar string `json:"avatar,omitempty"` //(选填)头像 需要填上从文件上传接口获得的media_id Birthday string `json:"star,omitempty"` //(选填)生日 example: 1990-01-24 Gender int `json:"gender,omitempty"` //性别 0 - 未知, 1 - 男 ,2 - 女 Signature string `json:"signature,omitempty"` //用户签名 Byte(0~250) Region string `json:"region,omitempty"` //(选填)地区 用户所属地区 Byte(0~250) Address string `json:"address,omitempty"` //(选填)地址 用户详细地址 Byte(0~250) Mtime int `json:"mtime,omitempty"` //用户最后修改时间 Ctime int `json:"ctime,omitempty"` //用户创建时间 Error *JMError `json:"error,omitempty"` } type JMResponse struct { Error *JMError `json:"error,omitempty"` } type JMError struct { Code int `json:"code,omitempty"` Message string `json:"message,omitempty"` } func (e *JMError) Error() string { return fmt.Sprintf("%d - %s", e.Code, e.Message) } //RegisterUsers 批量注册用户 func (jclient *JMessageClient) RegisterUsers(users []*JMUser) ([]*JMUser, error) { rusers := []*JMUser{} if nil == users || len(users) == 0 { return rusers, errors.New("no user to register") } if len(jclient.appKey) != KEY_LENGTH || len(jclient.masterSecret) != KEY_LENGTH { return rusers, fmt.Errorf("invalidate appkey/masterSecret") } req := goreq.Request{ Method: "POST", Uri: JMESSAGE_IM_URL + REGIST_USER_URL, Accept: "application/json", ContentType: "application/json", UserAgent: "JMessage-API-GO-Client", BasicAuthUsername: jclient.appKey, BasicAuthPassword: jclient.masterSecret, Timeout: 30 * time.Second, //30s } req.Body = users req.ShowDebug = jclient.showDebug res, err := req.Do() if err != nil { return rusers, err } defer res.Body.Close() ibytes, err := ioutil.ReadAll(res.Body) if nil != err { return rusers, err } if jclient.showDebug { fmt.Println("respone:", string(ibytes)) } err = json.Unmarshal(ibytes, &rusers) if nil != err { return rusers, err } return rusers, nil } //RegisterUser 注册用户 func (jclient *JMessageClient) RegisterUser(username string, nickName string, password string, avatar string) (*JMUser, *JMError, error) { user := JMUser{ Username: username, Password: password, Nickname: nickName, Avatar: avatar, } users, err := jclient.RegisterUsers([]*JMUser{&user}) if nil != err { return nil, nil, err } if len(users) == 1 { jmuser := users[0] if nil == jmuser.Error || jmuser.Error.Code == 0 { return jmuser, nil, nil } return nil, jmuser.Error, jmuser.Error } return nil, nil, errors.New("response failed") } func (jclient *JMessageClient) RegisterAdmin(username string, nickName string, password string, avatar string) (*JMUser, *JMError, error) { user := JMUser{ Username: username, Password: password, Nickname: nickName, Avatar: avatar, } if len(jclient.appKey) != KEY_LENGTH || len(jclient.masterSecret) != KEY_LENGTH { return nil, nil, fmt.Errorf("invalidate appkey/masterSecret") } req := goreq.Request{ Method: "POST", Uri: JMESSAGE_IM_URL + REGIST_ADMIN_URL, Accept: "application/json", ContentType: "application/json", UserAgent: "JMessage-API-GO-Client", BasicAuthUsername: jclient.appKey, BasicAuthPassword: jclient.masterSecret, Timeout: 30 * time.Second, //30s } req.Body = user req.ShowDebug = jclient.showDebug res, err := req.Do() if err != nil { return nil, nil, err } defer res.Body.Close() ibytes, err := ioutil.ReadAll(res.Body) if nil != err { return nil, nil, err } if jclient.showDebug { fmt.Println("respone:", string(ibytes)) } if string(ibytes) == "" { return &user, nil, nil } jmResult := JMResponse{} err = json.Unmarshal(ibytes, &jmResult) if nil != err { return nil, nil, err } if nil != jmResult.Error { return nil, jmResult.Error, jmResult.Error } return &user, nil, nil } func (jclient *JMessageClient) UpdatePasswd(username string, passwd string) error { req := goreq.Request{ Method: "PUT", Uri: JMESSAGE_IM_URL + REGIST_USER_URL + username + "/password", Accept: "application/json", ContentType: "application/json", UserAgent: "JMessage-API-GO-Client", BasicAuthUsername: jclient.appKey, BasicAuthPassword: jclient.masterSecret, Timeout: 30 * time.Second, //30s } req.ShowDebug = jclient.showDebug req.Body = map[string]string{"new_password": passwd} res, err := req.Do() if err != nil { return err } defer res.Body.Close() ibytes, err := ioutil.ReadAll(res.Body) if nil != err { return err } if jclient.showDebug { fmt.Println("respone:", string(ibytes)) } if string(ibytes) == "" { return nil } jmResult := JMResponse{} err = json.Unmarshal(ibytes, &jmResult) if nil != err { return err } if nil != jmResult.Error { return jmResult.Error } return nil } func (jclient *JMessageClient) UpdateProfile(username string, nickname, avatar, birthday string, signature, gender, region, address string, extras string) error { req := goreq.Request{ Method: "PUT", Uri: JMESSAGE_IM_URL + REGIST_USER_URL + username, Accept: "application/json", ContentType: "application/json", UserAgent: "JMessage-API-GO-Client", BasicAuthUsername: jclient.appKey, BasicAuthPassword: jclient.masterSecret, Timeout: 30 * time.Second, //30s } req.ShowDebug = jclient.showDebug params := map[string]string{} if nickname != "" { params["nickname"] = nickname } if avatar != "" { params["avatar"] = avatar } if birthday != "" { params["birthday"] = birthday } if signature != "" { params["signature"] = signature } if gender != "" { params["gender"] = gender } if region != "" { params["region"] = region } if address != "" { params["address"] = address } if extras != "" { params["extras"] = extras } req.Body = params res, err := req.Do() if err != nil { return err } defer res.Body.Close() ibytes, err := ioutil.ReadAll(res.Body) if nil != err { return err } if jclient.showDebug { fmt.Println("respone:", string(ibytes)) } if string(ibytes) == "" { return nil } jmResult := JMResponse{} err = json.Unmarshal(ibytes, &jmResult) if nil != err { return err } if nil != jmResult.Error { return jmResult.Error } return nil } func (jclient *JMessageClient) DeleteUser(username string) error { req := goreq.Request{ Method: "DELETE", Uri: JMESSAGE_IM_URL + REGIST_USER_URL + username, Accept: "application/json", ContentType: "application/json", UserAgent: "JMessage-API-GO-Client", BasicAuthUsername: jclient.appKey, BasicAuthPassword: jclient.masterSecret, Timeout: 30 * time.Second, //30s } req.ShowDebug = jclient.showDebug res, err := req.Do() if err != nil { return err } defer res.Body.Close() ibytes, err := ioutil.ReadAll(res.Body) if nil != err { return err } if jclient.showDebug { fmt.Println("respone:", string(ibytes)) } if string(ibytes) == "" { return nil } jmResult := JMResponse{} err = json.Unmarshal(ibytes, &jmResult) if nil != err { return err } if nil != jmResult.Error { return jmResult.Error } return nil } //BlackUsers 添加黑名单 func (jclient *JMessageClient) BlackUsers(fromUsername string, blackUserNames []string) error { if len(blackUserNames) == 0 { return errors.New("empty blackUserNames") } res, err := jclient.request(JMESSAGE_IM_URL+REGIST_USER_URL+fromUsername+"/blacklist", "PUT", blackUserNames) if nil != err { return err } defer res.Body.Close() ibytes, err := ioutil.ReadAll(res.Body) if nil != err { return err } if jclient.showDebug { fmt.Println("respone:", string(ibytes)) } return nil } //DeleteBlackUsers 删除黑名单 func (jclient *JMessageClient) DeleteBlackUsers(fromUsername string, blackUserNames []string) error { if len(blackUserNames) == 0 { return errors.New("empty blackUserNames") } res, err := jclient.request(JMESSAGE_IM_URL+REGIST_USER_URL+fromUsername+"/blacklist", "DELETE", blackUserNames) if nil != err { return err } defer res.Body.Close() ibytes, err := ioutil.ReadAll(res.Body) if nil != err { return err } if jclient.showDebug { fmt.Println("respone:", string(ibytes)) } return nil } //GetBlackUsers 获取黑名单 func (jclient *JMessageClient) GetBlackUsers(fromUsername string) ([]string, error) { users := []string{} res, err := jclient.request(JMESSAGE_IM_URL+REGIST_USER_URL+fromUsername+"/blacklist", "Get", nil) if nil != err { return users, err } defer res.Body.Close() ibytes, err := ioutil.ReadAll(res.Body) if nil != err { return users, err } if jclient.showDebug { fmt.Println("respone:", string(ibytes)) } err = json.Unmarshal(ibytes, &users) return users, err } //ForbiddenUser 禁用/解除禁用 func (jclient *JMessageClient) ForbiddenUser(username string, forbidden bool) error { url := JMESSAGE_IM_URL + REGIST_USER_URL + username + "/forbidden?disable=" if forbidden { url += "true" } else { url += "false" } res, err := jclient.request(url, "PUT", nil) if nil != err { return err } defer res.Body.Close() ibytes, err := ioutil.ReadAll(res.Body) if nil != err { return err } if jclient.showDebug { fmt.Println("respone:", string(ibytes)) } return nil }
[ 3, 6 ]
package main import ( "fmt" "log" "strings" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/spf13/viper" "go.uber.org/zap" "github.com/transcom/mymove/pkg/appcontext" "github.com/transcom/mymove/pkg/cli" "github.com/transcom/mymove/pkg/logging" "github.com/transcom/mymove/pkg/services/ghcdieselfuelprice" ) func checkSaveGHCFuelPriceConfig(v *viper.Viper, logger *zap.Logger) error { logger.Debug("checking config") err := cli.CheckEIA(v) if err != nil { return err } err = cli.CheckDatabase(v, logger) if err != nil { return err } return nil } func initSaveGHCFuelPriceFlags(flag *pflag.FlagSet) { //DB Config cli.InitDatabaseFlags(flag) // EIA Open Data API cli.InitEIAFlags(flag) // Logging Levels cli.InitLoggingFlags(flag) // Don't sort flags flag.SortFlags = false } // Command: go run github.com/transcom/mymove/cmd/milmove-tasks/save_ghc_fuel_price_data func saveGHCFuelPriceData(cmd *cobra.Command, args []string) error { err := cmd.ParseFlags(args) if err != nil { return fmt.Errorf("could not parse args: %w", err) } flags := cmd.Flags() v := viper.New() err = v.BindPFlags(flags) if err != nil { return fmt.Errorf("could not bind flags: %w", err) } v.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) v.AutomaticEnv() dbEnv := v.GetString(cli.DbEnvFlag) logger, _, err := logging.Config( logging.WithEnvironment(dbEnv), logging.WithLoggingLevel(v.GetString(cli.LoggingLevelFlag)), logging.WithStacktraceLength(v.GetInt(cli.StacktraceLengthFlag)), ) if err != nil { log.Fatalf("Failed to initialize Zap logging due to %v", err) } zap.ReplaceGlobals(logger) err = checkSaveGHCFuelPriceConfig(v, logger) if err != nil { logger.Fatal("invalid configuration", zap.Error(err)) } // Create a connection to the DB dbConnection, err := cli.InitDatabase(v, logger) if err != nil { logger.Fatal("Connecting to DB", zap.Error(err)) } appCtx := appcontext.NewAppContext(dbConnection, logger, nil) eiaURL := v.GetString(cli.EIAURLFlag) eiaKey := v.GetString(cli.EIAKeyFlag) newDieselFuelPriceInfo := ghcdieselfuelprice.NewDieselFuelPriceInfo(eiaURL, eiaKey, ghcdieselfuelprice.FetchEIAData, logger) err = newDieselFuelPriceInfo.RunFetcher(appCtx) if err != nil { logger.Fatal("error returned by RunFetcher function in ghcdieselfuelprice service", zap.Error(err)) } err = newDieselFuelPriceInfo.RunStorer(appCtx) if err != nil { logger.Fatal("error returned by RunStorer function in ghcdieselfuelprice service", zap.Error(err)) } return nil }
[ 3 ]
package main import ( "fmt" "initializer/core" "os" ) func main() { manager, err := core.NewServiceManager(os.Args[1]) if err != nil { fmt.Println(err) os.Exit(2) } //manager.ConnectSignals() manager.Start() }
[ 3 ]
package setpipelinehelpers import ( "fmt" "io/ioutil" "net/url" "os" yaml "gopkg.in/yaml.v2" "github.com/cloudfoundry/bosh-cli/director/template" "github.com/concourse/concourse/atc" "github.com/concourse/concourse/fly/commands/internal/displayhelpers" "github.com/concourse/concourse/fly/commands/internal/flaghelpers" temp "github.com/concourse/concourse/fly/template" "github.com/concourse/concourse/fly/ui" "github.com/concourse/concourse/go-concourse/concourse" "github.com/onsi/gomega/gexec" "github.com/vito/go-interact/interact" ) type ATCConfig struct { PipelineName string Team concourse.Team Target string SkipInteraction bool CheckCredentials bool } func (atcConfig ATCConfig) ApplyConfigInteraction() bool { if atcConfig.SkipInteraction { return true } confirm := false err := interact.NewInteraction("apply configuration?").Resolve(&confirm) if err != nil { return false } return confirm } func (atcConfig ATCConfig) Validate( configPath atc.PathFlag, templateVariables []flaghelpers.VariablePairFlag, yamlTemplateVariables []flaghelpers.YAMLVariablePairFlag, templateVariablesFiles []atc.PathFlag, strict bool, output bool, ) error { newConfig, err := atcConfig.newConfig(configPath, templateVariablesFiles, templateVariables, yamlTemplateVariables, true, strict) if err != nil { return err } var new atc.Config if strict { // UnmarshalStrict will pick up fields in structs that have the wrong names, as well as any duplicate keys in maps // we should consider always using this everywhere in a later release... if err := yaml.UnmarshalStrict([]byte(newConfig), &new); err != nil { return err } } else { if err := yaml.Unmarshal([]byte(newConfig), &new); err != nil { return err } } warnings, errorMessages := new.Validate() if len(warnings) > 0 { configWarnings := make([]concourse.ConfigWarning, len(warnings)) for idx, warning := range warnings { configWarnings[idx] = concourse.ConfigWarning(warning) } atcConfig.showWarnings(configWarnings) } if len(errorMessages) > 0 { atcConfig.showPipelineConfigErrors(errorMessages) } if len(errorMessages) > 0 || (strict && len(warnings) > 0) { displayhelpers.Failf("configuration invalid") } if output { fmt.Println(string(newConfig)) } else { fmt.Println("looks good") } return nil } func (atcConfig ATCConfig) Set(configPath atc.PathFlag, templateVariables []flaghelpers.VariablePairFlag, yamlTemplateVariables []flaghelpers.YAMLVariablePairFlag, templateVariablesFiles []atc.PathFlag) error { newConfig, err := atcConfig.newConfig(configPath, templateVariablesFiles, templateVariables, yamlTemplateVariables, false, false) if err != nil { return err } existingConfig, _, existingConfigVersion, _, err := atcConfig.Team.PipelineConfig(atcConfig.PipelineName) errorMessages := []string{} if err != nil { if configError, ok := err.(concourse.PipelineConfigError); ok { errorMessages = configError.ErrorMessages } else { return err } } var new atc.Config err = yaml.Unmarshal([]byte(newConfig), &new) if err != nil { return err } diffExists := diff(existingConfig, new) if len(errorMessages) > 0 { atcConfig.showPipelineConfigErrors(errorMessages) } if !diffExists { fmt.Println("no changes to apply") return nil } if !atcConfig.ApplyConfigInteraction() { fmt.Println("bailing out") return nil } created, updated, warnings, err := atcConfig.Team.CreateOrUpdatePipelineConfig( atcConfig.PipelineName, existingConfigVersion, newConfig, atcConfig.CheckCredentials, ) if err != nil { return err } if len(warnings) > 0 { atcConfig.showWarnings(warnings) } atcConfig.showHelpfulMessage(created, updated) return nil } func (atcConfig ATCConfig) newConfig( configPath atc.PathFlag, templateVariablesFiles []atc.PathFlag, templateVariables []flaghelpers.VariablePairFlag, yamlTemplateVariables []flaghelpers.YAMLVariablePairFlag, allowEmpty bool, strict bool, ) ([]byte, error) { evaluatedConfig, err := ioutil.ReadFile(string(configPath)) if err != nil { return nil, fmt.Errorf("could not read config file: %s", err.Error()) } if strict { // We use a generic map here, since templates are not evaluated yet. // (else a template string may cause an error when a struct is expected) // If we don't check Strict now, then the subsequent steps will mask any // duplicate key errors. // We should consider being strict throughout the entire stack by default. err = yaml.UnmarshalStrict(evaluatedConfig, make(map[string]interface{})) if err != nil { return nil, fmt.Errorf("error parsing yaml before applying templates: %s", err.Error()) } } var paramPayloads [][]byte for _, path := range templateVariablesFiles { templateVars, err := ioutil.ReadFile(string(path)) if err != nil { return nil, fmt.Errorf("could not read template variables file (%s): %s", string(path), err.Error()) } paramPayloads = append(paramPayloads, templateVars) } if temp.Present(evaluatedConfig) { evaluatedConfig, err = atcConfig.resolveDeprecatedTemplateStyle(evaluatedConfig, paramPayloads, templateVariables, yamlTemplateVariables, allowEmpty) if err != nil { return nil, fmt.Errorf("could not resolve old-style template vars: %s", err.Error()) } } evaluatedConfig, err = atcConfig.resolveTemplates(evaluatedConfig, paramPayloads, templateVariables, yamlTemplateVariables) if err != nil { return nil, fmt.Errorf("could not resolve template vars: %s", err.Error()) } return evaluatedConfig, nil } func (atcConfig ATCConfig) resolveTemplates(configPayload []byte, paramPayloads [][]byte, variables []flaghelpers.VariablePairFlag, yamlVariables []flaghelpers.YAMLVariablePairFlag) ([]byte, error) { tpl := template.NewTemplate(configPayload) flagVars := template.StaticVariables{} for _, f := range variables { flagVars[f.Name] = f.Value } for _, f := range yamlVariables { flagVars[f.Name] = f.Value } vars := []template.Variables{flagVars} for i := len(paramPayloads) - 1; i >= 0; i-- { payload := paramPayloads[i] var staticVars template.StaticVariables err := yaml.Unmarshal(payload, &staticVars) if err != nil { return nil, err } vars = append(vars, staticVars) } bytes, err := tpl.Evaluate(template.NewMultiVars(vars), nil, template.EvaluateOpts{}) if err != nil { return nil, err } return bytes, nil } func (atcConfig ATCConfig) resolveDeprecatedTemplateStyle( configPayload []byte, paramPayloads [][]byte, variables []flaghelpers.VariablePairFlag, yamlVariables []flaghelpers.YAMLVariablePairFlag, allowEmpty bool, ) ([]byte, error) { vars := temp.Variables{} for _, payload := range paramPayloads { var payloadVars temp.Variables err := yaml.Unmarshal(payload, &payloadVars) if err != nil { return nil, err } vars = vars.Merge(payloadVars) } flagVars := temp.Variables{} for _, flag := range variables { flagVars[flag.Name] = flag.Value } vars = vars.Merge(flagVars) return temp.Evaluate(configPayload, vars, allowEmpty) } func (atcConfig ATCConfig) showPipelineConfigErrors(errorMessages []string) { fmt.Fprintln(ui.Stderr, "") displayhelpers.PrintWarningHeader() fmt.Fprintln(ui.Stderr, "Error loading existing config:") for _, errorMessage := range errorMessages { fmt.Fprintf(ui.Stderr, " - %s\n", errorMessage) } fmt.Fprintln(ui.Stderr, "") } func (atcConfig ATCConfig) showWarnings(warnings []concourse.ConfigWarning) { fmt.Fprintln(ui.Stderr, "") displayhelpers.PrintDeprecationWarningHeader() for _, warning := range warnings { fmt.Fprintf(ui.Stderr, " - %s\n", warning.Message) } fmt.Fprintln(ui.Stderr, "") } func (atcConfig ATCConfig) showHelpfulMessage(created bool, updated bool) { if updated { fmt.Println("configuration updated") } else if created { targetURL, err := url.Parse(atcConfig.Target) if err != nil { fmt.Println("Could not parse targetURL") } pipelineURL, err := url.Parse("/teams/" + atcConfig.Team.Name() + "/pipelines/" + atcConfig.PipelineName) if err != nil { fmt.Println("Could not parse pipelineURL") } fmt.Println("pipeline created!") fmt.Printf("you can view your pipeline here: %s\n", targetURL.ResolveReference(pipelineURL)) fmt.Println("") fmt.Println("the pipeline is currently paused. to unpause, either:") fmt.Println(" - run the unpause-pipeline command") fmt.Println(" - click play next to the pipeline in the web ui") } else { panic("Something really went wrong!") } } func diff(existingConfig atc.Config, newConfig atc.Config) bool { var diffExists bool indent := gexec.NewPrefixedWriter(" ", os.Stdout) groupDiffs := groupDiffIndices(GroupIndex(existingConfig.Groups), GroupIndex(newConfig.Groups)) if len(groupDiffs) > 0 { diffExists = true fmt.Println("groups:") for _, diff := range groupDiffs { diff.Render(indent, "group") } } resourceDiffs := diffIndices(ResourceIndex(existingConfig.Resources), ResourceIndex(newConfig.Resources)) if len(resourceDiffs) > 0 { diffExists = true fmt.Println("resources:") for _, diff := range resourceDiffs { diff.Render(indent, "resource") } } resourceTypeDiffs := diffIndices(ResourceTypeIndex(existingConfig.ResourceTypes), ResourceTypeIndex(newConfig.ResourceTypes)) if len(resourceTypeDiffs) > 0 { diffExists = true fmt.Println("resource types:") for _, diff := range resourceTypeDiffs { diff.Render(indent, "resource type") } } jobDiffs := diffIndices(JobIndex(existingConfig.Jobs), JobIndex(newConfig.Jobs)) if len(jobDiffs) > 0 { diffExists = true fmt.Println("jobs:") for _, diff := range jobDiffs { diff.Render(indent, "job") } } return diffExists }
[ 1, 5, 6 ]
package island //给你一个 m x n 的矩阵 board ,由若干字符 'X' 和 'O' ,找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充 //。 // // // // // // // // 示例 1: // // //输入:board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O", //"X","X"]] //输出:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]] //解释:被围绕的区间不会存在于边界上,换句话说,任何边界上的'O'都不会被填充为'X'。 任何不在边界上,或不与边界上的'O'相连的'O'最终都 //会被填充为'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。 // // // 示例 2: // // //输入:board = [["X"]] //输出:[["X"]] // // // // // 提示: // // // m == board.length // n == board[i].length // 1 <= m, n <= 200 // board[i][j] 为 'X' 或 'O' // // // Related Topics 深度优先搜索 广度优先搜索 并查集 数组 矩阵 func solve(board [][]byte) { tmpVal, replacedVal, targetVal := byte('1'), byte('O'), byte('X') directs := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} rowLen, colLen := len(board), len(board[0]) var dfs func(i, j int, replaced, target byte) dfs = func(i, j int, replaced, target byte) { if i < 0 || j < 0 || i >= rowLen || j >= colLen || board[i][j] != replaced { return } board[i][j] = target for _, direct := range directs { dfs(i+direct[0], j+direct[1], replaced, target) } } for i := 0; i < colLen; i++ { dfs(0, i, replacedVal, tmpVal) dfs(rowLen-1, i, replacedVal, tmpVal) } for i := 0; i < rowLen; i++ { dfs(i, 0, replacedVal, tmpVal) dfs(i, colLen-1, replacedVal, tmpVal) } for i := 0; i < rowLen; i++ { for j := 0; j < colLen; j++ { if board[i][j] == replacedVal { dfs(i, j, replacedVal, targetVal) } } } for i := 0; i < rowLen; i++ { for j := 0; j < colLen; j++ { if board[i][j] == tmpVal { board[i][j] = replacedVal } } } } func solveFillSimply(board [][]byte) { tmpVal, replacedVal, targetVal := byte('1'), byte('O'), byte('X') directs := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} rowLen, colLen := len(board), len(board[0]) var dfs func(i, j int) dfs = func(i, j int) { if i < 0 || j < 0 || i >= rowLen || j >= colLen || board[i][j] != replacedVal { return } board[i][j] = tmpVal for _, direct := range directs { dfs(i+direct[0], j+direct[1]) } } for i := 0; i < colLen; i++ { dfs(0, i) dfs(rowLen-1, i) } for i := 0; i < rowLen; i++ { dfs(i, 0) dfs(i, colLen-1) } for i := 0; i < rowLen; i++ { for j := 0; j < colLen; j++ { if board[i][j] == replacedVal { // 这里已经不需要用dfs去填充了,直接遍历即可(根本原因是不用标记重复访问) board[i][j] = targetVal continue } if board[i][j] == tmpVal { board[i][j] = replacedVal } } } }
[ 3 ]
package keeper_test // noalias import ( "bytes" "encoding/hex" "math/rand" "strconv" "testing" "github.com/KuChainNetwork/kuchain/chain/types" "github.com/KuChainNetwork/kuchain/test/simapp" "github.com/KuChainNetwork/kuchain/chain/config" "github.com/KuChainNetwork/kuchain/chain/constants" sdk "github.com/cosmos/cosmos-sdk/types" . "github.com/smartystreets/goconvey/convey" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" stakingTypes "github.com/KuChainNetwork/kuchain/x/staking/types" ) // dummy addresses used for testing // nolint:unused, deadcode var ( Addrs = createTestAddrs(500) PKs = createTestPubKeys(500) Accd = createTestAccount(500) Accdel = createTestAccount(500) addrDels = []sdk.AccAddress{ Addrs[0], Addrs[1], } addrVals = []sdk.ValAddress{ sdk.ValAddress(Addrs[2]), sdk.ValAddress(Addrs[3]), sdk.ValAddress(Addrs[4]), sdk.ValAddress(Addrs[5]), sdk.ValAddress(Addrs[6]), } ) // Hogpodge of all sorts of input required for testing. // `initPower` is converted to an amount of tokens. // If `initPower` is 0, no addrs get created. func NewTestApp(wallet *simapp.Wallet) (addAlice, addJack, addValidator sdk.AccAddress, accAlice, accJack, accValidator types.AccountID, app *simapp.SimApp) { addAlice = wallet.NewAccAddress() addJack = wallet.NewAccAddress() addValidator = wallet.NewAccAddress() accAlice = types.MustAccountID("alice@ok") accJack = types.MustAccountID("jack@ok") accValidator = types.MustAccountID("validator@ok") resInt, succ := sdk.NewIntFromString("100000000000000000000000") if !succ { resInt = sdk.NewInt(10000000000000000) } otherCoinDenom := types.CoinDenom(types.MustName("foo"),types.MustName("coin")) initAsset := types.NewCoin(constants.DefaultBondDenom, resInt) asset1 := types.Coins{ types.NewInt64Coin(otherCoinDenom, 67), initAsset} asset2 := types.Coins{ types.NewInt64Coin(otherCoinDenom, 67), types.NewInt64Coin(constants.DefaultBondDenom, 10000000)} genAlice := simapp.NewSimGenesisAccount(accAlice, addAlice).WithAsset(asset1) genJack := simapp.NewSimGenesisAccount(accJack, addJack).WithAsset(asset1) genValidator := simapp.NewSimGenesisAccount(accValidator, addValidator).WithAsset(asset2) genAccs := simapp.NewGenesisAccounts(wallet.GetRootAuth(), genAlice, genJack, genValidator) app = simapp.SetupWithGenesisAccounts(genAccs) ctxCheck := app.BaseApp.NewContext(true, abci.Header{Height: app.LastBlockHeight() + 1}) accountAlice := app.AccountKeeper().GetAccount(ctxCheck, accAlice) accountJack := app.AccountKeeper().GetAccount(ctxCheck, accJack) accountValidator := app.AccountKeeper().GetAccount(ctxCheck, accValidator) So(accountAlice, ShouldNotBeNil) So(genAlice.GetID().Eq(accountAlice.GetID()), ShouldBeTrue) So(genAlice.GetAuth().Equals(accountAlice.GetAuth()), ShouldBeTrue) So(accountJack, ShouldNotBeNil) So(genJack.GetID().Eq(accountJack.GetID()), ShouldBeTrue) So(genJack.GetAuth().Equals(accountJack.GetAuth()), ShouldBeTrue) So(accountValidator, ShouldNotBeNil) So(genValidator.GetID().Eq(accountValidator.GetID()), ShouldBeTrue) So(genValidator.GetAuth().Equals(accountValidator.GetAuth()), ShouldBeTrue) return addAlice, addJack, addValidator, accAlice, accJack, accValidator, app } func NewPubKey(pk string) (res crypto.PubKey) { pkBytes, err := hex.DecodeString(pk) if err != nil { panic(err) } //res, err = crypto.PubKeyFromBytes(pkBytes) var pkEd ed25519.PubKeyEd25519 copy(pkEd[:], pkBytes) return pkEd } // for incode address generation func GetTestAddr(addr string, bech string) sdk.AccAddress { res, err := sdk.AccAddressFromHex(addr) if err != nil { panic(err) } bechexpected := res.String() if bech != bechexpected { panic("Bech encoding doesn't match reference") } bechres, err := sdk.AccAddressFromBech32(bech) if err != nil { panic(err) } if !bytes.Equal(bechres, res) { panic("Bech decode and hex decode don't match") } return res } // nolint: unparam func createTestAddrs(numAddrs int) []sdk.AccAddress { var addresses []sdk.AccAddress var buffer bytes.Buffer // start at 100 so we can make up to 999 test addresses with valid test addresses for i := 100; i < (numAddrs + 100); i++ { numString := strconv.Itoa(i) buffer.WriteString("A58856F0FD53BF058B4909A21AEC019107BA6") //base address string buffer.WriteString(numString) //adding on final two digits to make addresses unique res, _ := sdk.AccAddressFromHex(buffer.String()) bech := res.String() addresses = append(addresses, GetTestAddr(buffer.String(), bech)) buffer.Reset() } return addresses } func createTestAccount(numAddrs int) []types.AccountID { var accountID []types.AccountID var buffer bytes.Buffer for i := 100; i < (numAddrs + 100); i++ { numString := strconv.Itoa(i) buffer.WriteString("testaccount") //base address string buffer.WriteString(numString) //adding on final two digits to make addresses unique tmpAccount := types.MustAccountID(buffer.String()) accountID = append(accountID, tmpAccount) buffer.Reset() } return accountID } // nolint: unparam func createTestPubKeys(numPubKeys int) []crypto.PubKey { var publicKeys []crypto.PubKey var buffer bytes.Buffer //start at 10 to avoid changing 1 to 01, 2 to 02, etc for i := 100; i < (numPubKeys + 100); i++ { numString := strconv.Itoa(i) buffer.WriteString("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AF") //base pubkey string buffer.WriteString(numString) //adding on final two digits to make pubkeys unique publicKeys = append(publicKeys, NewPubKey(buffer.String())) buffer.Reset() } return publicKeys } //_____________________________________________________________________________________ // does a certain by-power index record exist // func ValidatorByPowerIndexExists(ctx sdk.Context, keeper Keeper, power []byte) bool { // store := ctx.KVStore(keeper.storeKey) // return store.Has(power) // } // update validator for testing func TestingUpdateValidator(app *simapp.SimApp, ctx sdk.Context, validator stakingTypes.Validator, apply bool) stakingTypes.Validator { keeper := app.StakeKeeper() keeper.SetValidator(ctx, validator) keeper.SetValidatorByPowerIndex(ctx, validator) if apply { keeper.ApplyAndReturnValidatorSetUpdates(ctx) validator, found := keeper.GetValidator(ctx, validator.OperatorAccount) if !found { panic("validator expected but not found") } return validator } cachectx, _ := ctx.CacheContext() keeper.ApplyAndReturnValidatorSetUpdates(cachectx) validator, found := keeper.GetValidator(cachectx, validator.OperatorAccount) if !found { panic("validator expected but not found") } return validator } // nolint:deadcode, unused func validatorByPowerIndexExists(app *simapp.SimApp, ctx sdk.Context, power []byte) bool { storkey := sdk.NewKVStoreKey(stakingTypes.StoreKey) store := ctx.KVStore(storkey) return store.Has(power) } // RandomValidator returns a random validator given access to the keeper and ctx func RandomValidator(r *rand.Rand, app *simapp.SimApp, ctx sdk.Context) (val stakingTypes.Validator, ok bool) { keeper := app.StakeKeeper() vals := keeper.GetAllValidators(ctx) if len(vals) == 0 { return stakingTypes.Validator{}, false } i := r.Intn(len(vals)) return vals[i], true } func TestInit(t *testing.T) { config.SealChainConfig() }
[ 3, 6 ]
package mario // s.length == t.length // 题目只要求s->t单向1:1的映射关系 func isIsomorphic(s string, t string) bool { m := make(map[byte]byte, len(s)) mReverse := make(map[byte]byte, len(s)) isValid := true for i := range s { v, ok := m[s[i]] if !ok { _, isExist := mReverse[t[i]] if isExist { isValid = false break } m[s[i]] = t[i] mReverse[t[i]] = s[i] } else if t[i] != v { isValid = false break } } return isValid }
[ 6 ]
package main import ( "io/ioutil" "os" "path/filepath" "strings" "gopkg.in/yaml.v2" ) //scanProject scans a whole project and returns all go filepaths in the path tree. func scanProject(scanPath string) ([]string, error) { goFilesPath := make([]string, 0) e := filepath.Walk(scanPath, func(path string, f os.FileInfo, err error) error { if ext := strings.SplitN(path, ".", 2); len(ext) == 2 && ext[1] == "go" { goFilesPath = append(goFilesPath, path) } return err }) if e != nil { return nil, e } return goFilesPath, nil } //YamlConf holds the configuration that will drive ts files creation. type YamlConf struct { OutputDirPath string ContextList []string Pending []string FilenameContextsMap map[string][]string BatchesInterface map[string][]TsInterface BatchesEnums [][]Enum } //GenerateConfigYaml generate a GototoConf.yaml that will drive the generateTS command. func GenerateConfigYaml(scanPath string, outputDir string) { files, err := scanProject(scanPath) if err != nil { panic(err) } if outputDir == "" { outputDir = "./ModelsTS" } contextSlice, batches := parsingProject(files) //Building conf yamlStruct := YamlConf{OutputDirPath: outputDir, FilenameContextsMap: make(map[string][]string), ContextList: contextSlice, BatchesInterface: batches} appendEnumInYaml(files, &yamlStruct) for _, s := range contextSlice { l := make([]string, 0) l = append(l, strings.ToLower(s)) yamlStruct.FilenameContextsMap[strings.Title(s)+"Model"] = l } yamlStruct.marshallAndWrite(scanPath + "/gototoConf.yaml") } //Update a YAML config. It keeps modifications of filenames but do not keep batches file modification.Can update directory path too. func UpdateConfigYaml(scanPath string, outputDir string, noMoreFiles bool) { var currentConf YamlConf _, err := currentConf.GetYamlConfig(scanPath) Check(err) //Modifying outputDir if option is not "" if outputDir != "" { currentConf.OutputDirPath = outputDir } //Scanning files, err := scanProject(scanPath) if err != nil { panic(err) } //Parsing contextSlice, batches := parsingProject(files) missing_contexts := currentConf.getMissingContexts(contextSlice) /* Handling contexts update */ if missing_contexts != nil { //If no more files then we add these contexts to pending and do not add filenames for new contexts //Note that generateTS won't work if some contexts are still pending (except if --ignore-pending) if noMoreFiles { currentConf.Pending = append(currentConf.Pending, missing_contexts...) } else { for _, mc := range missing_contexts { l := make([]string, 0) l = append(l, strings.ToLower(mc)) currentConf.FilenameContextsMap[strings.Title(mc)+"Model"] = l } } } /* Handling batches update */ currentConf.BatchesInterface = batches currentConf.marshallAndWrite(scanPath + "/gototoConf.yaml") } //Parsing all files in project and return all the contexts and batches func parsingProject(files []string) ([]string, map[string][]TsInterface) { contextSlice := make([]string, 0) batches := make(map[string][]TsInterface) for _, gof := range files { localBatch := ParseGoFile(gof, &contextSlice) for c, i := range localBatch { if _, keyInMap := batches[c]; keyInMap { batches[c] = append(batches[c], i...) } else { batches[c] = i } } } SetifyString(&contextSlice) return contextSlice, batches } func appendEnumInYaml(files []string, y *YamlConf) { for _, f := range files { if s := strings.SplitN(f, "\\", -1); s[len(s)-1] == "enums.go" { y.BatchesEnums = append(y.BatchesEnums, ParseEnumsGoFile(f)) } } } //GetYamlConfig gets the Yaml configuration from the file if it does exists. func (y *YamlConf) GetYamlConfig(scanPath string) (*YamlConf, error) { configPath := scanPath + "/gototoConf.yaml" configFile, err := ioutil.ReadFile(configPath) if err != nil { return nil, err } err = yaml.Unmarshal(configFile, y) Check(err) return y, nil } //Get the missing contexts and append them to the conf func (y *YamlConf) getMissingContexts(contexts []string) []string { var diff []string for _, nc := range contexts { found := false for _, cc := range y.ContextList { if nc == cc { found = true break } } if !found { diff = append(diff, nc) y.ContextList = append(y.ContextList, nc) } } return diff } func (y *YamlConf) marshallAndWrite(path string) { //Marshalling contexts yamlStructConf, err := yaml.Marshal(y) Check(err) //writing file fconf, err := os.Create(path) Check(err) _, err = fconf.Write(yamlStructConf) Check(err) fconf.Close() }
[ 3, 6 ]
package reddit import ( "strings" "net/url" "strconv" ) func (r Reddit) GetListing(options ListingOptions) (posts *ListingResponse, err error) { err = options.Validate() if err != nil { return posts, err } q := url.Values{} if options.After != "" { q.Set("after", options.After) } if options.Before != "" { q.Set("before", options.Before) } if options.Count > 0 { q.Set("count", strconv.Itoa(options.Count)) } if options.Limit > 0 { q.Set("limit", strconv.Itoa(options.Limit)) } if options.Show { q.Set("show", "all") } if options.Detail { q.Set("sr_detail", "") } if options.Time == SortTop || options.Time == SortControversial { q.Set("t", string(options.Time)) } var u string if options.Reddit != "" { u = u + "r/" + options.Reddit } if options.Sort != "" { u = u + "/" + string(options.Sort) } posts = new(ListingResponse) err = r.fetchGet(u, q, posts) if err != nil { return posts, err } return posts, err } type ListingOptions struct { After string Before string Count int Limit int Show bool Detail bool Location ListingLocation // Hot only Time ListingTime // Top & Controversial only Sort ListingSort Reddit string } func (l ListingOptions) Validate() error { return nil } type ListingResponse struct { Kind string `json:"kind"` Data struct { Modhash string `json:"modhash"` Dist int `json:"dist"` Children []ListingPost `json:"children"` After string `json:"after"` Before interface{} `json:"before"` } `json:"data"` } type ListingPost struct { Kind string `json:"kind"` Data ListingPostData `json:"data"` } type ListingPostData struct { ApprovedAtUtc interface{} `json:"approved_at_utc"` Subreddit string `json:"subreddit"` Selftext string `json:"selftext"` UserReports []interface{} `json:"user_reports"` IsSaved bool `json:"saved"` ModReasonTitle interface{} `json:"mod_reason_title"` Gilded int `json:"gilded"` IsClicked bool `json:"clicked"` Title string `json:"title"` LinkFlairRichtext []struct { E string `json:"e"` T string `json:"t"` } `json:"link_flair_richtext"` SubredditNamePrefixed string `json:"subreddit_name_prefixed"` IsHidden bool `json:"hidden"` Pwls int `json:"pwls"` LinkFlairCSSClass string `json:"link_flair_css_class"` Downs int `json:"downs"` ThumbnailHeight int `json:"thumbnail_height"` ParentWhitelistStatus string `json:"parent_whitelist_status"` HideScore bool `json:"hide_score"` Name string `json:"name"` Quarantine bool `json:"quarantine"` LinkFlairTextColor string `json:"link_flair_text_color"` AuthorFlairBackgroundColor interface{} `json:"author_flair_background_color"` SubredditType string `json:"subreddit_type"` Ups int `json:"ups"` Domain string `json:"domain"` MediaEmbed struct { } `json:"media_embed"` ThumbnailWidth int `json:"thumbnail_width"` AuthorFlairTemplateID interface{} `json:"author_flair_template_id"` IsOriginalContent bool `json:"is_original_content"` SecureMedia interface{} `json:"secure_media"` IsRedditMediaDomain bool `json:"is_reddit_media_domain"` Category interface{} `json:"category"` SecureMediaEmbed struct { } `json:"secure_media_embed"` LinkFlairText string `json:"link_flair_text"` CanModPost bool `json:"can_mod_post"` Score int `json:"score"` ApprovedBy interface{} `json:"approved_by"` Thumbnail string `json:"thumbnail"` //Edited bool `json:"edited"` // Timestamp or false AuthorFlairCSSClass string `json:"author_flair_css_class"` AuthorFlairRichtext []interface{} `json:"author_flair_richtext"` PostHint string `json:"post_hint"` IsSelf bool `json:"is_self"` ModNote interface{} `json:"mod_note"` Created float64 `json:"created"` LinkFlairType string `json:"link_flair_type"` Wls int `json:"wls"` PostCategories interface{} `json:"post_categories"` BannedBy interface{} `json:"banned_by"` AuthorFlairType string `json:"author_flair_type"` ContestMode bool `json:"contest_mode"` SelftextHTML interface{} `json:"selftext_html"` Likes interface{} `json:"likes"` SuggestedSort interface{} `json:"suggested_sort"` BannedAtUtc interface{} `json:"banned_at_utc"` ViewCount interface{} `json:"view_count"` Archived bool `json:"archived"` NoFollow bool `json:"no_follow"` IsCrosspostable bool `json:"is_crosspostable"` Pinned bool `json:"pinned"` IsOver18 bool `json:"over_18"` Preview struct { Images []struct { Source struct { URL string `json:"url"` Width int `json:"width"` Height int `json:"height"` } `json:"source"` Resolutions []struct { URL string `json:"url"` Width int `json:"width"` Height int `json:"height"` } `json:"resolutions"` Variants struct { } `json:"variants"` ID string `json:"id"` } `json:"images"` Enabled bool `json:"enabled"` } `json:"preview"` CanGild bool `json:"can_gild"` IsSpoiler bool `json:"spoiler"` Locked bool `json:"locked"` AuthorFlairText string `json:"author_flair_text"` RteMode string `json:"rte_mode"` IsVisited bool `json:"visited"` NumReports interface{} `json:"num_reports"` Distinguished interface{} `json:"distinguished"` SubredditID string `json:"subreddit_id"` ModReasonBy interface{} `json:"mod_reason_by"` RemovalReason interface{} `json:"removal_reason"` ID string `json:"id"` ReportReasons interface{} `json:"report_reasons"` Author string `json:"author"` NumCrossposts int `json:"num_crossposts"` NumComments int `json:"num_comments"` SendReplies bool `json:"send_replies"` ModReports []interface{} `json:"mod_reports"` AuthorFlairTextColor interface{} `json:"author_flair_text_color"` Permalink string `json:"permalink"` WhitelistStatus string `json:"whitelist_status"` Stickied bool `json:"stickied"` URL string `json:"url"` SubredditSubscribers int `json:"subreddit_subscribers"` CreatedUtc float64 `json:"created_utc"` Media interface{} `json:"media"` IsVideo bool `json:"is_video"` } func (d ListingPostData) IsImage() bool { return strings.HasSuffix(d.URL, ".jpg") || strings.HasSuffix(d.URL, ".jpeg") || strings.HasSuffix(d.URL, ".png") || strings.HasSuffix(d.URL, ".gif") } func (r Reddit) Save(id string, category string) (err error) { q := url.Values{} q.Set("id", id) q.Set("category", category) err = r.fetchPost("api/save", q, nil) if err != nil { return err } return nil } func (r Reddit) Unsave(id string) (err error) { q := url.Values{} q.Set("id", id) err = r.fetchPost("api/unsave", q, nil) if err != nil { return err } return err }
[ 3, 6 ]
package main import "fmt" import "math/rand" import "time" func main() { var guess int r1 := rand.New(rand.NewSource(time.Now().UnixNano())) score := r1.Intn(1000) for { fmt.Println("Type your proposition:") _, err := fmt.Scanf("%d", &guess) if err != nil { fmt.Println(err) break } if score == guess { fmt.Println("You win!!") fmt.Print("\n\n") break } else if score > guess { fmt.Println("Too small") } else { fmt.Println("Too big") } fmt.Print("\n") } }
[ 5 ]
package commands import ( "github.com/abiosoft/ishell" "github.com/go-lumen/lumen-cli/utils" "github.com/serenize/snaker" "github.com/spf13/cobra" "os" ) // Model is a structure that holds characteristics of model type Model struct { Name string Fields []*Field } // Field is a structure that holds characteristics of field type Field struct { Name string Type string IsId bool Required bool } // ModelCmd holds functions to generate model func ModelCmd(cmd *cobra.Command, args []string) { var fields []*Field model := Model{"", fields} //fmt.Println("Generating Model: " + strings.Join(args, " ")) shell := ishell.New() // Step 0: choosing model name, if not already done if len(args) == 1 { shell.Print("Generating Model ") shell.Println(`"` + args[0] + `"`) model.Name = args[0] } else { shell.Println("Generating Model") shell.Print("Name: ") model.Name = shell.ReadLine() } propertyNum := 0 for propertyNum < 10 { // Step 1: choosing property name shell.Print("Enter the property name: ") field := Field{"", "", false, false} field.Name = shell.ReadLine() // Step 2: choosing property type choice := shell.MultiChoice([]string{ "string", "int", "float", "bool", }, "Property "+field.Name+" Type: ") switch choice { case 0: field.Type = "string" break case 1: field.Type = "int" break case 2: field.Type = "float" break case 3: field.Type = "bool" break default: field.Type = "string" break } shell.Println(field.Type) // Step 3: choosing if property is required if shell.MultiChoice([]string{"yes", "no"}, "Is "+field.Name+" required?") == 0 { field.Required = true } // Step 4: choosing if property is the ID one if shell.MultiChoice([]string{"yes", "no"}, "Is "+field.Name+" the ID property?") == 0 { field.IsId = true } model.Fields = append(model.Fields, &field) propertyNum += 1 if shell.MultiChoice([]string{"yes", "no"}, "Do you want to add a new property?") == 1 { utils.GenerateFile("model.tmpl", "models/"+snaker.CamelToSnake(model.Name)+".go", model) os.Exit(1) } } shell.Run() }
[ 3 ]
package products //Products estructura representativa de un producto type Products struct { Name string Description string Price float32 }
[ 3 ]
package router import ( "encoding/json" "io/ioutil" "net/http" "github.com/julienschmidt/httprouter" ) //Action - handle context type Action func(hc *HTTPContext) //Interceptor - http filter. type Interceptor func(hc *HTTPContext) bool //KV - map type KV map[string]interface{} //HTTPContext web request. type HTTPContext struct { W http.ResponseWriter R *http.Request PS httprouter.Params } //Header - write header. func (hc *HTTPContext) Header(key, value string) { hc.W.Header()[key] = []string{value} } //GetHeader - get header value. func (hc *HTTPContext) GetHeader(key string) string { return hc.R.Header[key][0] } //BodyData - read body data. func (hc *HTTPContext) BodyData() ([]byte, error) { defer hc.R.Body.Close() return ioutil.ReadAll(hc.R.Body) } //GetParam get request parameter or path parameter. func (hc *HTTPContext) GetParam(key string) string { params := httprouter.ParamsFromContext(hc.R.Context()) return params.ByName(key) } //Write - data. func (hc *HTTPContext) Write(bs []byte) { hc.W.Write(bs) hc.W.WriteHeader(http.StatusOK) } //WriteCode - write http status. func (hc *HTTPContext) WriteCode(code int) { hc.W.WriteHeader(code) } //WriteString - write string value. func (hc *HTTPContext) WriteString(data string) { hc.W.Write([]byte(data)) } //WriteJSON - write key value to json. func (hc *HTTPContext) WriteJSON(kv KV) { bs, err := json.Marshal(kv) if err != nil { hc.W.WriteHeader(http.StatusBadRequest) hc.W.Write([]byte(err.Error())) return } hc.W.Write(bs) }
[ 3 ]
package main import ( "fmt" "math" ) func main() { var i int fmt.Scan(&i) n := 1 for ; i >= n*n; n += 2 { } fmt.Printf("n = %d\n", n) var dist, pivot int dist = (n - 1) / 2 if (i > n*n - n + 1) { // Bottom pivot = n*n - (n-1)/2 fmt.Printf("A Dist(%d), Pivot(%d)\n", dist, pivot) dist += int(math.Abs(float64(i - pivot))) } else if (i > n*n - 2*n + 2) { // Left pivot = n*n - (3*(n-1))/2 fmt.Printf("B Dist(%d), Pivot(%d)\n", dist, pivot) dist += int(math.Abs(float64(i - pivot))) } else if (i > n*n - 3*n + 3) { // Top pivot = n*n - (5*(n-1))/2 fmt.Printf("C Dist(%d), Pivot(%d)\n", dist, pivot) dist += int(math.Abs(float64(i - pivot))) } else { // Right pivot = n*n - (7*(n-1))/2 fmt.Printf("D Dist(%d), Pivot(%d)\n", dist, pivot) dist += int(math.Abs(float64(i - pivot))) } fmt.Printf("Distance: %d\n", dist) }
[ 5 ]
package makeweb import ( "fmt" "gopkg.in/russross/blackfriday.v2" ) func toHTML(page Page) (Page, error) { format, ok := page.Vars["format"].(string) if ok { if format == "markdown" || format == "md" { page.Content = md2html(page.Content) } else if format == "html" { page.Content = html2html(page.Content) } else { return Page{}, fmt.Errorf("unknown format: %v", format) } } else { // undefined format, use html page.Vars["format"] = "html" page.Content = html2html(page.Content) } return page, nil } func md2html(text string) string { content := string(blackfriday.Run([]byte(text))) return content } func html2html(text string) string { return text }
[ 5 ]
package main import ( "fmt" "strconv" "strings" ) /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type deque []*TreeNode func (d deque) PushBack(v *TreeNode) deque { return append(d, v) } func (d deque) PushFront(v *TreeNode) deque { // todo: reimplement return append(d, v) } func (d deque) PopBack() (deque, *TreeNode) { // todo: length check? l := len(d) return d[:l-1], d[l-1] } func (d deque) PopFront() (deque, *TreeNode) { // l := len(d) // todo: length check? return d[1:], d[0] } type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func insert(node *TreeNode, val int, level int, curLevel int) bool { if curLevel > level { return false } // fmt.Printf("Loking to insert at %d: %d\n", level, curLevel) // find first vacant slot on this level if curLevel == level { if node.Left == nil { node.Left = &TreeNode{Val: val} return true } if node.Right == nil { node.Right = &TreeNode{Val: val} return true } } inserted := false // traverse tree further, this order is important if !inserted && node.Right != nil { inserted = insert(node.Right, val, level, curLevel+1) } if !inserted && node.Left != nil { inserted = insert(node.Left, val, level, curLevel+1) } return inserted } func runeVal(ch rune) int { val, _ := strconv.Atoi(fmt.Sprintf("%c", ch)) return val } type Pair struct { Value int Level int } func extractPairs(t string) []Pair { result := make([]Pair, 0) isLevel := func(c rune) bool { return c != '-' } isNotLevel := func(c rune) bool { return c == '-' } levels := strings.FieldsFunc(t, isLevel) values := strings.FieldsFunc(t, isNotLevel) // insert root value, _ := strconv.Atoi(values[0]) result = append(result, Pair{Value: value, Level: 0}) for i, l := range levels { level := len(l) value, _ = strconv.Atoi(values[i+1]) result = append(result, Pair{Value: value, Level: level}) } for _, p := range result { fmt.Println(p.Value, p.Level) } return result } func recoverFromPreorder(traversal string) *TreeNode { pairs := extractPairs(traversal) var root TreeNode = TreeNode{Val: pairs[0].Value} for _, p := range pairs[1:] { insert(&root, p.Value, p.Level, 1) } return &root } func treeToList(t *TreeNode) (res []int) { dq := make(deque, 0) dq = dq.PushBack(t) var current *TreeNode for len(dq) > 0 { dq, current = dq.PopFront() // fmt.Println(current.Val) if current.Left != nil { dq = dq.PushBack(current.Left) } if current.Right != nil { dq = dq.PushBack(current.Right) } res = append(res, current.Val) } return res } func treeToPrint(t *TreeNode) (res []*TreeNode) { dq := make(deque, 0) dq = dq.PushBack(t) var current *TreeNode for len(dq) > 0 { dq, current = dq.PopFront() fmt.Println(current) res = append(res, current) if current == nil { continue } if current.Left == nil && current.Right == nil { continue } if current.Left != nil { dq = dq.PushBack(current.Left) } else { dq = dq.PushBack(nil) } if current.Right != nil { dq = dq.PushBack(current.Right) } else { dq = dq.PushBack(nil) } } for _, t := range res { if t == nil { fmt.Print("null ") } else { fmt.Printf("%d ", t.Val) } } fmt.Println("") return res } func main() { var t1, t2, t3 TreeNode t1.Val = 0 t2.Val = 1 t3.Val = 2 t1.Left = &t2 t2.Left = &t3 // root := &t1 // fmt.Println(treeToList(root)) // head := recoverFromPreorder("1-2--3--4-5--6--7") // fmt.Println(treeToList(head)) // [1,2,5,3,4,6,7] // head = recoverFromPreorder("1-2--3---4-5--6---7") // fmt.Println(treeToList(head)) // [1,2,5,3,null,6,null,4,null,7] // head = recoverFromPreorder("1-401--349---90--88") // fmt.Println(treeToList(head)) // [1,401,null,349,88,90] head := recoverFromPreorder("1-2--3---4-5--6---7") treeToPrint(head) // [1,2,5,3,null,6,null,4,null,7] }
[ 6 ]
package user import ( "fmt" ) type User struct{ Id int Username string Sex string Age int Mobile string Email string } func NewUser(id int,username string,sex string,age int,mobile string,email string) User{ return User{ Id:id, Username: username, Sex:sex, Age: age, Mobile: mobile, Email: email, } } func (user *User) List(){ str := fmt.Sprintf("%v\t%v\t%v\t%v\t%v\t%v",user.Id,user.Username,user.Sex,user.Age,user.Mobile,user.Email) fmt.Println(str) }
[ 6 ]
package net import ( "fmt" "math" "net" "strconv" "strings" "github.com/taktv6/tflow2/convert" ) // Prefix represents an IPv4 prefix type Prefix struct { addr uint32 pfxlen uint8 } // NewPfx creates a new Prefix func NewPfx(addr uint32, pfxlen uint8) Prefix { return Prefix{ addr: addr, pfxlen: pfxlen, } } // StrToAddr converts an IP address string to it's uint32 representation func StrToAddr(x string) (uint32, error) { parts := strings.Split(x, ".") if len(parts) != 4 { return 0, fmt.Errorf("Invalid format") } ret := uint32(0) for i := 0; i < 4; i++ { y, err := strconv.Atoi(parts[i]) if err != nil { return 0, fmt.Errorf("Unable to convert %q to int: %v", parts[i], err) } if y > 255 { return 0, fmt.Errorf("%d is too big for a uint8", y) } ret += uint32(math.Pow(256, float64(3-i))) * uint32(y) } return ret, nil } // Addr returns the address of the prefix func (pfx Prefix) Addr() uint32 { return pfx.addr } // Pfxlen returns the length of the prefix func (pfx Prefix) Pfxlen() uint8 { return pfx.pfxlen } // String returns a string representation of pfx func (pfx Prefix) String() string { return fmt.Sprintf("%s/%d", net.IP(convert.Uint32Byte(pfx.addr)), pfx.pfxlen) } // Contains checks if x is a subnet of or equal to pfx func (pfx Prefix) Contains(x Prefix) bool { if x.pfxlen <= pfx.pfxlen { return false } mask := (uint32(1) << (32 - pfx.pfxlen)) return (pfx.addr & mask) == (x.addr & mask) } // Equal checks if pfx and x are equal func (pfx Prefix) Equal(x Prefix) bool { return pfx == x } // GetSupernet gets the next common supernet of pfx and x func (pfx Prefix) GetSupernet(x Prefix) Prefix { maxPfxLen := min(pfx.pfxlen, x.pfxlen) - 1 a := pfx.addr >> (32 - maxPfxLen) b := x.addr >> (32 - maxPfxLen) for i := 0; a != b; i++ { a = a >> 1 b = b >> 1 maxPfxLen-- } return Prefix{ addr: a << (32 - maxPfxLen), pfxlen: maxPfxLen, } } func min(a uint8, b uint8) uint8 { if a < b { return a } return b }
[ 0, 6 ]
package main import ( "bufio" "fmt" "os" ) func generateKey3D(row int, col int, depth int) string { return fmt.Sprintf("%d,%d,%d", col, row, depth) } func getCoordinate3D(coordinate string) (int, int, int) { var actCol, actRow, actDepth int fmt.Sscanf(coordinate, "%d,%d,%d", &actCol, &actRow, &actDepth) return actRow, actCol, actDepth } func generateKey4D(row int, col int, depth int, w int) string { return fmt.Sprintf("%d,%d,%d,%d", col, row, depth, w) } func getCoordinate4D(coordinate string) (int, int, int, int) { var actCol, actRow, actDepth, actW int fmt.Sscanf(coordinate, "%d,%d,%d,%d", &actCol, &actRow, &actDepth, &actW) return actRow, actCol, actDepth, actW } func neigborActiveCubes3D(cubeMap map[string]rune, row int, col, depth int) int { active := 0 for actCol := -1; actCol < 2; actCol++ { for actRow := -1; actRow < 2; actRow++ { for actDepth := -1; actDepth < 2; actDepth++ { if actCol == 0 && actDepth == 0 && actRow == 0 { continue } coordinate := generateKey3D(actRow+row, actCol+col, actDepth+depth) val, ok := cubeMap[coordinate] if ok && val == '#' { active++ } } } } return active } func addMissingNeighbors3D(cubeMap map[string]rune, row int, col, depth int) { for actCol := -1; actCol < 2; actCol++ { for actRow := -1; actRow < 2; actRow++ { for actDepth := -1; actDepth < 2; actDepth++ { if actCol == 0 && actDepth == 0 && actRow == 0 { continue } coordinate := generateKey3D(actRow+row, actCol+col, actDepth+depth) _, ok := cubeMap[coordinate] if !ok { cubeMap[coordinate] = '.' } } } } } func neigborActiveCubes4D(cubeMap map[string]rune, row int, col, depth int, w int) int { active := 0 for actCol := -1; actCol < 2; actCol++ { for actRow := -1; actRow < 2; actRow++ { for actDepth := -1; actDepth < 2; actDepth++ { for actW := -1; actW < 2; actW++ { if actCol == 0 && actDepth == 0 && actRow == 0 && actW == 0 { continue } coordinate := generateKey4D(actRow+row, actCol+col, actDepth+depth, actW+w) val, ok := cubeMap[coordinate] if ok && val == '#' { active++ } } } } } return active } func addMissingNeighbors4D(cubeMap map[string]rune, row int, col, depth int, w int) { for actCol := -1; actCol < 2; actCol++ { for actRow := -1; actRow < 2; actRow++ { for actDepth := -1; actDepth < 2; actDepth++ { for actW := -1; actW < 2; actW++ { if actCol == 0 && actDepth == 0 && actRow == 0 && actW == 0 { continue } coordinate := generateKey4D(actRow+row, actCol+col, actDepth+depth, actW+w) _, ok := cubeMap[coordinate] if !ok { cubeMap[coordinate] = '.' } } } } } } func cntActiveCubes(cubeMap map[string]rune) int { active := 0 for _, val := range cubeMap { if val == '#' { active++ } } return active } func main() { file, _ := os.Open("./input.txt") scanner := bufio.NewScanner(file) cubeMaps := [2]map[string]rune{{}, {}} cubeMaps4D := [2]map[string]rune{{}, {}} row := 0 activeMap := 0 nextMap := 1 for scanner.Scan() { // read the line line := scanner.Text() for col, val := range line { coordinate := generateKey3D(row, col, 0) coordinate4D := generateKey4D(row, col, 0, 0) cubeMaps[activeMap][coordinate] = val cubeMaps4D[activeMap][coordinate4D] = val addMissingNeighbors3D(cubeMaps[activeMap], row, col, 0) addMissingNeighbors4D(cubeMaps4D[activeMap], row, col, 0, 0) } row++ } for iteration := 1; iteration < 7; iteration++ { // part 1 for key, val := range cubeMaps[activeMap] { actRow, actCol, actDepth := getCoordinate3D(key) neighbors := neigborActiveCubes3D(cubeMaps[activeMap], actRow, actCol, actDepth) if val == '#' { if neighbors == 2 || neighbors == 3 { cubeMaps[nextMap][key] = '#' } else { cubeMaps[nextMap][key] = '.' } } else { if neighbors == 3 { cubeMaps[nextMap][key] = '#' } else { cubeMaps[nextMap][key] = '.' } } addMissingNeighbors3D(cubeMaps[nextMap], actRow, actCol, actDepth) } // part 2 for key, val := range cubeMaps4D[activeMap] { actRow, actCol, actDepth, actW := getCoordinate4D(key) neighbors := neigborActiveCubes4D(cubeMaps4D[activeMap], actRow, actCol, actDepth, actW) if val == '#' { if neighbors == 2 || neighbors == 3 { cubeMaps4D[nextMap][key] = '#' } else { cubeMaps4D[nextMap][key] = '.' } } else { if neighbors == 3 { cubeMaps4D[nextMap][key] = '#' } else { cubeMaps4D[nextMap][key] = '.' } } addMissingNeighbors4D(cubeMaps4D[nextMap], actRow, actCol, actDepth, actW) } activeMap = 1 - activeMap nextMap = 1 - nextMap } fmt.Printf("%d\n", cntActiveCubes(cubeMaps[activeMap])) fmt.Printf("%d\n", cntActiveCubes(cubeMaps4D[activeMap])) }
[ 6 ]
package cli import ( "sort" "strings" "fmt" ) type state struct { id int terminal bool transitions transitions cmd *Cmd } type transition struct { matcher upMatcher next *state } type transitions []*transition func (t transitions) Len() int { return len(t) } func (t transitions) Swap(i, j int) { t[i], t[j] = t[j], t[i] } func (t transitions) Less(i, j int) bool { a, _ := t[i].matcher, t[j].matcher switch a.(type) { case upShortcut: return false case upOptsEnd: return false case *arg: return false default: return true } } var _id = 0 func newState(cmd *Cmd) *state { _id++ return &state{_id, false, []*transition{}, cmd} } func (s *state) t(matcher upMatcher, next *state) *state { s.transitions = append(s.transitions, &transition{matcher, next}) return next } func (s *state) has(tr *transition) bool { for _, t := range s.transitions { if t.next == tr.next && t.matcher == tr.matcher { return true } } return false } func incoming(s, into *state, visited map[*state]bool) []*transition { res := []*transition{} if visited[s] { return res } visited[s] = true for _, tr := range s.transitions { if tr.next == into { res = append(res, tr) } res = append(res, incoming(tr.next, into, visited)...) } return res } func removeItemAt(idx int, arr transitions) transitions { res := make([]*transition, len(arr)-1) copy(res, arr[:idx]) copy(res[idx:], arr[idx+1:]) return res } func fsmCopy(s, e *state) (*state, *state) { cache := map[*state]*state{} s.copy(cache) return cache[s], cache[e] } func (s *state) copy(cache map[*state]*state) *state { c := newState(s.cmd) c.terminal = s.terminal cache[s] = c for _, tr := range s.transitions { dest := tr.next if destCopy, found := cache[dest]; found { c.transitions = append(c.transitions, &transition{tr.matcher, destCopy}) continue } c.transitions = append(c.transitions, &transition{tr.matcher, dest.copy(cache)}) } return c } func (s *state) simplify() { simplify(s, s, map[*state]bool{}) } func simplify(start, s *state, visited map[*state]bool) { if visited[s] { return } visited[s] = true for _, tr := range s.transitions { simplify(start, tr.next, visited) } for s.simplifySelf(start) { } } func (s *state) simplifySelf(start *state) bool { for idx, tr := range s.transitions { if _, ok := tr.matcher.(upShortcut); ok { next := tr.next s.transitions = removeItemAt(idx, s.transitions) for _, tr := range next.transitions { if !s.has(tr) { s.transitions = append(s.transitions, tr) } } if next.terminal { s.terminal = true } return true } } return false } func (s *state) onlyOpts() bool { return onlyOpts(s, map[*state]bool{}) } func onlyOpts(s *state, visited map[*state]bool) bool { if visited[s] { return true } visited[s] = true for _, tr := range s.transitions { switch tr.matcher.(type) { case *arg: return false } if !onlyOpts(tr.next, visited) { return false } } return true } func (s *state) dot() string { trs := dot(s, map[*state]bool{}) return fmt.Sprintf("digraph G {\n\trankdir=LR\n%s\n}\n", strings.Join(trs, "\n")) } func dot(s *state, visited map[*state]bool) []string { res := []string{} if visited[s] { return res } visited[s] = true for _, tr := range s.transitions { res = append(res, fmt.Sprintf("\tS%d -> S%d [label=\"%v\"]", s.id, tr.next.id, tr.matcher)) res = append(res, dot(tr.next, visited)...) } if s.terminal { res = append(res, fmt.Sprintf("\tS%d [peripheries=2]", s.id)) } return res } type parseContext struct { args map[*arg][]string opts map[*opt][]string rejectOptions bool } func newParseContext() parseContext { return parseContext{map[*arg][]string{}, map[*opt][]string{}, false} } func (pc parseContext) merge(o parseContext) { for k, vs := range o.args { pc.args[k] = append(pc.args[k], vs...) } for k, vs := range o.opts { pc.opts[k] = append(pc.opts[k], vs...) } } func (s *state) parse(args []string) error { pc := newParseContext() ok, err := s.apply(args, pc) if err != nil { return err } if !ok { return fmt.Errorf("incorrect usage") } for opt, vs := range pc.opts { for _, v := range vs { if err := opt.set(v); err != nil { return err } } } for arg, vs := range pc.args { for _, v := range vs { if err := arg.set(v); err != nil { return err } } } return nil } func (s *state) apply(args []string, pc parseContext) (bool, error) { if s.terminal && len(args) == 0 { return true, nil } sort.Sort(s.transitions) if len(args) > 0 { arg := args[0] if !pc.rejectOptions && arg == "--" { pc.rejectOptions = true args = args[1:] } } type match struct { tr *transition rem []string pc parseContext } matches := []*match{} for _, tr := range s.transitions { fresh := newParseContext() fresh.rejectOptions = pc.rejectOptions if ok, rem := tr.matcher.match(args, &fresh); ok { matches = append(matches, &match{tr, rem, fresh}) } } for _, m := range matches { ok, err := m.tr.next.apply(m.rem, m.pc) if err != nil { return false, err } if ok { pc.merge(m.pc) return true, nil } } return false, nil }
[ 7 ]
package main import ( "fmt" "io/ioutil" "strings" ) func readfile(filename string) []byte { filedata, err := ioutil.ReadFile(filename) if err != nil { fmt.Println("could not read file") return nil } return filedata } func part1(input []byte) int { ilen := len(input) // take this here // create an empty array // used for clearing in go with a copy (sneaky) emptyarray := make([]byte, ilen) //fmt.Println("part1 ilen is", ilen) tmpinput := make([]byte, len(input)) cleartmpinput := func() { // slowest //for i := 0; i < len(input); i++ { // tmpinput[i] = 0 //} // faster //for i := range input { // tmpinput[i] = 0 //} // fastest!!! copy(tmpinput, emptyarray) } movetotmp := func() { counter := 0 for i := 0; i < ilen; i++ { if input[i] != 0 { tmpinput[counter] = input[i] counter++ } } } clearinput := func() { copy(input, emptyarray) //for i := 0; i < ilen; i++ { // input[i] = 0 //} } movetoinput := func() { // slow compared to copy //for i := 0; i < ilen; i++ { // input[i] = tmpinput[i] //} copy(input, tmpinput) } for { cleartmpinput() gotone := false //fmt.Println("input before cycle", string(input)) for i := 0; i < ilen-1; i++ { c1 := input[i] c2 := input[i+1] if c1 == c2+32 || c1+32 == c2 { //fmt.Println("got one", i, c1, c2) input[i] = 0 input[i+1] = 0 gotone = true break } } //fmt.Println("input after clear", string(input)) // compress it movetotmp() // clear it clearinput() // put it back movetoinput() // need to compress gaps here if gotone { ilen -= 2 } if !gotone { //fmt.Println("QUITING") break } } // clear all the input here not trimmed down amount // being careful for i := 0; i < len(input); i++ { if input[i] == 0 { input[i] = 32 } } tmp := string(input) tmp2 := strings.Trim(tmp, " ") //fmt.Println("ENDCOMPRESS", tmp2) //fmt.Println(len(tmp2)) //fmt.Println(len(tmp2)) return len(tmp2) } func removeP(c byte, input []byte) []byte { // remove a specific item and compress // then return it size := len(input) for i := 0; i < len(input); i++ { if input[i] == c || input[i] == c-32 { input[i] = 0 size-- } } var tmpinput []byte = make([]byte, size) // now compress it counter := 0 for i := 0; i < len(input); i++ { if input[i] != 0 { tmpinput[counter] = input[i] counter++ } } return tmpinput } func part2() { input := readfile("./input") //input := readfile("./input-example") //fmt.Println("original input here", input) //fmt.Println(string(input)) //originputlen := len(input) savedinput := make([]byte, len(input)) //for i := 0; i < len(input); i++ { // savedinput[i] = input[i] //} copy(savedinput, input) restoreinput := func() { //for i := 0; i < originputlen; i++ { // input[i] = savedinput[i] //} copy(input, savedinput) } smallest := 90000000 mychars := []byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'} //mychars := []byte{'c'} for ii := 0; ii < len(mychars); ii++ { restoreinput() cc := mychars[ii] newinput := removeP(cc, input) //fmt.Println(string(input)) //fmt.Println(string(newinput)) res := part1(newinput) if res < smallest { smallest = res } //fmt.Println("compressed", cc, part1(newinput)) } fmt.Println("smallest is", smallest) } func main() { part2() }
[ 3 ]
// Copyright 2022 The CubeFS 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 servicemgr import ( "context" "sync" "sync/atomic" "time" "github.com/cubefs/cubefs/blobstore/api/clustermgr" "github.com/cubefs/cubefs/blobstore/clustermgr/base" "github.com/cubefs/cubefs/blobstore/clustermgr/persistence/normaldb" "github.com/cubefs/cubefs/blobstore/common/trace" "github.com/cubefs/cubefs/blobstore/util/log" ) const ( defaultApplyConcurrency = 20 moduleName = "service manager" ) const ( OpRegister int32 = iota + 1 OpUnregister OpHeartbeat ) type dbOpType uint8 const ( DbPut dbOpType = iota DbDelete ) type serviceNode struct { ClusterID uint64 `json:"cluster_id"` Name string `json:"moduleName"` Host string `json:"host"` Idc string `json:"idc"` Timeout int `json:"timeout"` Expires time.Time `json:"expires"` } type service struct { sync.RWMutex // key: host nodes map[string]serviceNode } type nodeName struct { name string host string } type ServiceMgr struct { moduleName string tbl *normaldb.ServiceTable cache sync.Map dirty atomic.Value taskPool *base.TaskDistribution } func NewServiceMgr(t *normaldb.ServiceTable) *ServiceMgr { _, ctx := trace.StartSpanFromContext(context.Background(), "NewServiceMgr") mgr := &ServiceMgr{ moduleName: moduleName, tbl: t, taskPool: base.NewTaskDistribution(defaultApplyConcurrency, 1), } mgr.dirty.Store(&sync.Map{}) if err := mgr.LoadData(ctx); err != nil { log.Panic("reload data error", err) } return mgr } func (s *ServiceMgr) GetServiceInfo(sname string) (info clustermgr.ServiceInfo) { val, hit := s.cache.Load(sname) if !hit { return } sv := val.(*service) sv.RLock() defer sv.RUnlock() for _, val := range sv.nodes { if time.Until(val.Expires) <= 0 { continue } node := clustermgr.ServiceNode{ ClusterID: val.ClusterID, Name: val.Name, Host: val.Host, Idc: val.Idc, } info.Nodes = append(info.Nodes, node) } return } func (s *ServiceMgr) ListServiceInfo() (info clustermgr.ServiceInfo, err error) { s.cache.Range(func(key, value interface{}) bool { sv := value.(*service) sv.RLock() for _, val := range sv.nodes { node := clustermgr.ServiceNode{ ClusterID: val.ClusterID, Name: val.Name, Host: val.Host, Idc: val.Idc, } info.Nodes = append(info.Nodes, node) } sv.RUnlock() return true }) return } func (s *ServiceMgr) handleRegister(ctx context.Context, arg clustermgr.RegisterArgs) (err error) { info := serviceNode{ ClusterID: arg.ClusterID, Name: arg.Name, Host: arg.Host, Idc: arg.Idc, Timeout: arg.Timeout, Expires: time.Now().Add(time.Duration(arg.Timeout) * time.Second), } key := nodeName{arg.Name, arg.Host} // lookup service in cache v, _ := s.cache.LoadOrStore(info.Name, &service{ nodes: make(map[string]serviceNode), }) sv := v.(*service) sv.Lock() sv.nodes[info.Host] = info s.dirty.Load().(*sync.Map).Store(key, DbPut) sv.Unlock() return nil } func (s *ServiceMgr) handleUnregister(ctx context.Context, sname, host string) error { key := nodeName{sname, host} val, hit := s.cache.Load(sname) if !hit { return nil } sv := val.(*service) sv.Lock() defer sv.Unlock() delete(sv.nodes, host) s.dirty.Load().(*sync.Map).Store(key, DbDelete) return nil } func (s *ServiceMgr) handleHeartbeat(ctx context.Context, sname, host string) (err error) { val, hit := s.cache.Load(sname) if !hit { return } sv := val.(*service) key := nodeName{sname, host} sv.Lock() defer sv.Unlock() node, hit := sv.nodes[host] if !hit { return } node.Expires = time.Now().Add(time.Duration(node.Timeout) * time.Second) sv.nodes[host] = node s.dirty.Load().(*sync.Map).Store(key, DbPut) return nil } func (s *ServiceMgr) IsRegistered(name string, host string) bool { val, hit := s.cache.Load(name) if !hit { return false } sv := val.(*service) sv.RLock() defer sv.RUnlock() for _, val := range sv.nodes { if val.Host == host { return true } } return false }
[ 6 ]
package main import ( "bufio" "fmt" "net/rpc" "os" ) func client() { c, err := rpc.Dial("tcp", "127.0.0.1:9999") if err != nil { fmt.Println(err) return } var op int64 for { fmt.Println("1) Registrar un alumno, materia, calificación") fmt.Println("2) Promedio por alumno") fmt.Println("3) Promedio por materia") fmt.Println("4) Promedio general de alumnos") fmt.Println("0) Salir") fmt.Scanln(&op) switch op { case 1: //m := make(map[string]string) var name string var assignature string var grade string reader := bufio.NewReader(os.Stdin) fmt.Print("Nombre: ") name, _ = reader.ReadString('\n') //fmt.Scanln(&name) reader = bufio.NewReader(os.Stdin) fmt.Print("Materia: ") assignature, _ = reader.ReadString('\n') fmt.Print("Calificación:") fmt.Scanln(&grade) //m[subject] = grade slice := []string{name, assignature, grade} var result string err = c.Call("Server.Register", slice, &result) if err != nil { fmt.Println(err) } else { fmt.Println("Server.Register =", result) } case 2: var name string reader := bufio.NewReader(os.Stdin) fmt.Print("Introduzca nombre de alumno: ") name, _ = reader.ReadString('\n') var result string err = c.Call("Server.StudentGrade", name, &result) if err != nil { fmt.Println(err) } else { fmt.Println("Server.StudentGrade", name, "=", result) } case 3: var op string reader := bufio.NewReader(os.Stdin) fmt.Print("¿De que materia quiere el promedio? ") op, _ = reader.ReadString('\n') var result string err = c.Call("Server.Assignature", op, &result) if err != nil { fmt.Println(err) } else { fmt.Println("Server.Assignature", op, "=", result) } case 4: var b bool b = true var result string err = c.Call("Server.EveryoneGrade", b, &result) if err != nil { fmt.Println(err) } else { fmt.Println("Server.EveryoneGrade", b, "=", result) } case 0: return } } } func main() { client() }
[ 3 ]
//go:build go1.18 // +build go1.18 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // DO NOT EDIT. package armtestbase import ( "context" "errors" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "net/http" "net/url" "strings" ) // AnalysisResultsClient contains the methods for the AnalysisResults group. // Don't use this type directly, use NewAnalysisResultsClient() instead. type AnalysisResultsClient struct { internal *arm.Client subscriptionID string } // NewAnalysisResultsClient creates a new instance of AnalysisResultsClient with the specified values. // - subscriptionID - The Azure subscription ID. This is a GUID-formatted string. // - credential - used to authorize requests. Usually a credential from azidentity. // - options - pass nil to accept the default values. func NewAnalysisResultsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AnalysisResultsClient, error) { cl, err := arm.NewClient(moduleName+".AnalysisResultsClient", moduleVersion, credential, options) if err != nil { return nil, err } client := &AnalysisResultsClient{ subscriptionID: subscriptionID, internal: cl, } return client, nil } // Get - Gets an Analysis Result of a Test Result by name. // If the operation fails it returns an *azcore.ResponseError type. // // Generated from API version 2020-12-16-preview // - resourceGroupName - The name of the resource group that contains the resource. // - testBaseAccountName - The resource name of the Test Base Account. // - packageName - The resource name of the Test Base Package. // - testResultName - The Test Result Name. It equals to {osName}-{TestResultId} string. // - analysisResultName - The name of the Analysis Result of a Test Result. // - options - AnalysisResultsClientGetOptions contains the optional parameters for the AnalysisResultsClient.Get method. func (client *AnalysisResultsClient) Get(ctx context.Context, resourceGroupName string, testBaseAccountName string, packageName string, testResultName string, analysisResultName AnalysisResultName, options *AnalysisResultsClientGetOptions) (AnalysisResultsClientGetResponse, error) { req, err := client.getCreateRequest(ctx, resourceGroupName, testBaseAccountName, packageName, testResultName, analysisResultName, options) if err != nil { return AnalysisResultsClientGetResponse{}, err } resp, err := client.internal.Pipeline().Do(req) if err != nil { return AnalysisResultsClientGetResponse{}, err } if !runtime.HasStatusCode(resp, http.StatusOK) { return AnalysisResultsClientGetResponse{}, runtime.NewResponseError(resp) } return client.getHandleResponse(resp) } // getCreateRequest creates the Get request. func (client *AnalysisResultsClient) getCreateRequest(ctx context.Context, resourceGroupName string, testBaseAccountName string, packageName string, testResultName string, analysisResultName AnalysisResultName, options *AnalysisResultsClientGetOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.TestBase/testBaseAccounts/{testBaseAccountName}/packages/{packageName}/testResults/{testResultName}/analysisResults/{analysisResultName}" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if testBaseAccountName == "" { return nil, errors.New("parameter testBaseAccountName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{testBaseAccountName}", url.PathEscape(testBaseAccountName)) if packageName == "" { return nil, errors.New("parameter packageName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{packageName}", url.PathEscape(packageName)) if testResultName == "" { return nil, errors.New("parameter testResultName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{testResultName}", url.PathEscape(testResultName)) if analysisResultName == "" { return nil, errors.New("parameter analysisResultName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{analysisResultName}", url.PathEscape(string(analysisResultName))) req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("api-version", "2020-12-16-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil } // getHandleResponse handles the Get response. func (client *AnalysisResultsClient) getHandleResponse(resp *http.Response) (AnalysisResultsClientGetResponse, error) { result := AnalysisResultsClientGetResponse{} if err := runtime.UnmarshalAsJSON(resp, &result.AnalysisResultSingletonResource); err != nil { return AnalysisResultsClientGetResponse{}, err } return result, nil } // NewListPager - Lists the Analysis Results of a Test Result. The result collection will only contain one element as all // the data will be nested in a singleton object. // // Generated from API version 2020-12-16-preview // - resourceGroupName - The name of the resource group that contains the resource. // - testBaseAccountName - The resource name of the Test Base Account. // - packageName - The resource name of the Test Base Package. // - testResultName - The Test Result Name. It equals to {osName}-{TestResultId} string. // - analysisResultType - The type of the Analysis Result of a Test Result. // - options - AnalysisResultsClientListOptions contains the optional parameters for the AnalysisResultsClient.NewListPager // method. func (client *AnalysisResultsClient) NewListPager(resourceGroupName string, testBaseAccountName string, packageName string, testResultName string, analysisResultType AnalysisResultType, options *AnalysisResultsClientListOptions) *runtime.Pager[AnalysisResultsClientListResponse] { return runtime.NewPager(runtime.PagingHandler[AnalysisResultsClientListResponse]{ More: func(page AnalysisResultsClientListResponse) bool { return false }, Fetcher: func(ctx context.Context, page *AnalysisResultsClientListResponse) (AnalysisResultsClientListResponse, error) { req, err := client.listCreateRequest(ctx, resourceGroupName, testBaseAccountName, packageName, testResultName, analysisResultType, options) if err != nil { return AnalysisResultsClientListResponse{}, err } resp, err := client.internal.Pipeline().Do(req) if err != nil { return AnalysisResultsClientListResponse{}, err } if !runtime.HasStatusCode(resp, http.StatusOK) { return AnalysisResultsClientListResponse{}, runtime.NewResponseError(resp) } return client.listHandleResponse(resp) }, }) } // listCreateRequest creates the List request. func (client *AnalysisResultsClient) listCreateRequest(ctx context.Context, resourceGroupName string, testBaseAccountName string, packageName string, testResultName string, analysisResultType AnalysisResultType, options *AnalysisResultsClientListOptions) (*policy.Request, error) { urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.TestBase/testBaseAccounts/{testBaseAccountName}/packages/{packageName}/testResults/{testResultName}/analysisResults" if client.subscriptionID == "" { return nil, errors.New("parameter client.subscriptionID cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) if resourceGroupName == "" { return nil, errors.New("parameter resourceGroupName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) if testBaseAccountName == "" { return nil, errors.New("parameter testBaseAccountName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{testBaseAccountName}", url.PathEscape(testBaseAccountName)) if packageName == "" { return nil, errors.New("parameter packageName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{packageName}", url.PathEscape(packageName)) if testResultName == "" { return nil, errors.New("parameter testResultName cannot be empty") } urlPath = strings.ReplaceAll(urlPath, "{testResultName}", url.PathEscape(testResultName)) req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) if err != nil { return nil, err } reqQP := req.Raw().URL.Query() reqQP.Set("analysisResultType", string(analysisResultType)) reqQP.Set("api-version", "2020-12-16-preview") req.Raw().URL.RawQuery = reqQP.Encode() req.Raw().Header["Accept"] = []string{"application/json"} return req, nil } // listHandleResponse handles the List response. func (client *AnalysisResultsClient) listHandleResponse(resp *http.Response) (AnalysisResultsClientListResponse, error) { result := AnalysisResultsClientListResponse{} if err := runtime.UnmarshalAsJSON(resp, &result.AnalysisResultListResult); err != nil { return AnalysisResultsClientListResponse{}, err } return result, nil }
[ 6 ]
package jianshu_image_uploader import ( "io/ioutil" http2 "net/http" "os" "path/filepath" "strings" "github.com/ddliu/go-httpclient" "github.com/fatih/color" "github.com/tidwall/gjson" ) var httpClient *httpclient.HttpClient func init() { httpClient = httpclient.NewHttpClient().Defaults(httpclient.Map{ httpclient.OPT_REFERER: "https://www.jianshu.com/writer", httpclient.OPT_USERAGENT: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:64. 0) Gecko/20100101 Firefox/64.0", //httpclient.OPT_USERAGENT: "Mozilla/5.0 (Windows NT 6.1; rv:24.0) Gecko/20100101 Firefox/24.0", httpclient.OPT_UNSAFE_TLS: true, }) } func GetToken(cookies []*http2.Cookie, fileName string) (token string, key string) { data := map[string]string{"filename": fileName} url := "https://www.jianshu.com/upload_images/token.json" res, _ := httpClient.Begin().WithCookie(cookies...).Get(url, data) body, _ := res.ToString() json := gjson.Parse(body) return json.Get("token").String(), json.Get("key").String() } func UploadImg(filePath string, token string, key string) (body string) { if strings.HasPrefix(filePath, "http://") == true || strings.HasPrefix(filePath, "https://") == true { color.Green("从远程下载图片") res, _ := httpClient.Begin().Get(filePath) bodyBytes, _ := ioutil.ReadAll(res.Body) res.Body.Close() filePath = getImageName(filePath) file, _ := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, os.ModePerm|os.ModeAppend) file.Write(bodyBytes) defer file.Close() defer os.Remove(filePath) } postData := map[string]string{} postData["token"] = token postData["key"] = key postData["@file"] = filePath res, _ := httpClient.Begin().Post("http://upload.qiniup.com", postData) bodyBytes, _ := ioutil.ReadAll(res.Body) json := gjson.ParseBytes(bodyBytes) return json.Get("url").String() } func getImageName(imagePath string) string { return filepath.Base(imagePath) }
[ 3, 6 ]
// Code generated by counterfeiter. DO NOT EDIT. package v7fakes import ( "sync" "code.cloudfoundry.org/cli/actor/v7action" v7 "code.cloudfoundry.org/cli/command/v7" ) type FakeCancelDeploymentActor struct { CancelDeploymentStub func(string) (v7action.Warnings, error) cancelDeploymentMutex sync.RWMutex cancelDeploymentArgsForCall []struct { arg1 string } cancelDeploymentReturns struct { result1 v7action.Warnings result2 error } cancelDeploymentReturnsOnCall map[int]struct { result1 v7action.Warnings result2 error } GetApplicationByNameAndSpaceStub func(string, string) (v7action.Application, v7action.Warnings, error) getApplicationByNameAndSpaceMutex sync.RWMutex getApplicationByNameAndSpaceArgsForCall []struct { arg1 string arg2 string } getApplicationByNameAndSpaceReturns struct { result1 v7action.Application result2 v7action.Warnings result3 error } getApplicationByNameAndSpaceReturnsOnCall map[int]struct { result1 v7action.Application result2 v7action.Warnings result3 error } GetLatestDeploymentForAppStub func(string) (v7action.Deployment, v7action.Warnings, error) getLatestDeploymentForAppMutex sync.RWMutex getLatestDeploymentForAppArgsForCall []struct { arg1 string } getLatestDeploymentForAppReturns struct { result1 v7action.Deployment result2 v7action.Warnings result3 error } getLatestDeploymentForAppReturnsOnCall map[int]struct { result1 v7action.Deployment result2 v7action.Warnings result3 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *FakeCancelDeploymentActor) CancelDeployment(arg1 string) (v7action.Warnings, error) { fake.cancelDeploymentMutex.Lock() ret, specificReturn := fake.cancelDeploymentReturnsOnCall[len(fake.cancelDeploymentArgsForCall)] fake.cancelDeploymentArgsForCall = append(fake.cancelDeploymentArgsForCall, struct { arg1 string }{arg1}) fake.recordInvocation("CancelDeployment", []interface{}{arg1}) fake.cancelDeploymentMutex.Unlock() if fake.CancelDeploymentStub != nil { return fake.CancelDeploymentStub(arg1) } if specificReturn { return ret.result1, ret.result2 } fakeReturns := fake.cancelDeploymentReturns return fakeReturns.result1, fakeReturns.result2 } func (fake *FakeCancelDeploymentActor) CancelDeploymentCallCount() int { fake.cancelDeploymentMutex.RLock() defer fake.cancelDeploymentMutex.RUnlock() return len(fake.cancelDeploymentArgsForCall) } func (fake *FakeCancelDeploymentActor) CancelDeploymentCalls(stub func(string) (v7action.Warnings, error)) { fake.cancelDeploymentMutex.Lock() defer fake.cancelDeploymentMutex.Unlock() fake.CancelDeploymentStub = stub } func (fake *FakeCancelDeploymentActor) CancelDeploymentArgsForCall(i int) string { fake.cancelDeploymentMutex.RLock() defer fake.cancelDeploymentMutex.RUnlock() argsForCall := fake.cancelDeploymentArgsForCall[i] return argsForCall.arg1 } func (fake *FakeCancelDeploymentActor) CancelDeploymentReturns(result1 v7action.Warnings, result2 error) { fake.cancelDeploymentMutex.Lock() defer fake.cancelDeploymentMutex.Unlock() fake.CancelDeploymentStub = nil fake.cancelDeploymentReturns = struct { result1 v7action.Warnings result2 error }{result1, result2} } func (fake *FakeCancelDeploymentActor) CancelDeploymentReturnsOnCall(i int, result1 v7action.Warnings, result2 error) { fake.cancelDeploymentMutex.Lock() defer fake.cancelDeploymentMutex.Unlock() fake.CancelDeploymentStub = nil if fake.cancelDeploymentReturnsOnCall == nil { fake.cancelDeploymentReturnsOnCall = make(map[int]struct { result1 v7action.Warnings result2 error }) } fake.cancelDeploymentReturnsOnCall[i] = struct { result1 v7action.Warnings result2 error }{result1, result2} } func (fake *FakeCancelDeploymentActor) GetApplicationByNameAndSpace(arg1 string, arg2 string) (v7action.Application, v7action.Warnings, error) { fake.getApplicationByNameAndSpaceMutex.Lock() ret, specificReturn := fake.getApplicationByNameAndSpaceReturnsOnCall[len(fake.getApplicationByNameAndSpaceArgsForCall)] fake.getApplicationByNameAndSpaceArgsForCall = append(fake.getApplicationByNameAndSpaceArgsForCall, struct { arg1 string arg2 string }{arg1, arg2}) fake.recordInvocation("GetApplicationByNameAndSpace", []interface{}{arg1, arg2}) fake.getApplicationByNameAndSpaceMutex.Unlock() if fake.GetApplicationByNameAndSpaceStub != nil { return fake.GetApplicationByNameAndSpaceStub(arg1, arg2) } if specificReturn { return ret.result1, ret.result2, ret.result3 } fakeReturns := fake.getApplicationByNameAndSpaceReturns return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3 } func (fake *FakeCancelDeploymentActor) GetApplicationByNameAndSpaceCallCount() int { fake.getApplicationByNameAndSpaceMutex.RLock() defer fake.getApplicationByNameAndSpaceMutex.RUnlock() return len(fake.getApplicationByNameAndSpaceArgsForCall) } func (fake *FakeCancelDeploymentActor) GetApplicationByNameAndSpaceCalls(stub func(string, string) (v7action.Application, v7action.Warnings, error)) { fake.getApplicationByNameAndSpaceMutex.Lock() defer fake.getApplicationByNameAndSpaceMutex.Unlock() fake.GetApplicationByNameAndSpaceStub = stub } func (fake *FakeCancelDeploymentActor) GetApplicationByNameAndSpaceArgsForCall(i int) (string, string) { fake.getApplicationByNameAndSpaceMutex.RLock() defer fake.getApplicationByNameAndSpaceMutex.RUnlock() argsForCall := fake.getApplicationByNameAndSpaceArgsForCall[i] return argsForCall.arg1, argsForCall.arg2 } func (fake *FakeCancelDeploymentActor) GetApplicationByNameAndSpaceReturns(result1 v7action.Application, result2 v7action.Warnings, result3 error) { fake.getApplicationByNameAndSpaceMutex.Lock() defer fake.getApplicationByNameAndSpaceMutex.Unlock() fake.GetApplicationByNameAndSpaceStub = nil fake.getApplicationByNameAndSpaceReturns = struct { result1 v7action.Application result2 v7action.Warnings result3 error }{result1, result2, result3} } func (fake *FakeCancelDeploymentActor) GetApplicationByNameAndSpaceReturnsOnCall(i int, result1 v7action.Application, result2 v7action.Warnings, result3 error) { fake.getApplicationByNameAndSpaceMutex.Lock() defer fake.getApplicationByNameAndSpaceMutex.Unlock() fake.GetApplicationByNameAndSpaceStub = nil if fake.getApplicationByNameAndSpaceReturnsOnCall == nil { fake.getApplicationByNameAndSpaceReturnsOnCall = make(map[int]struct { result1 v7action.Application result2 v7action.Warnings result3 error }) } fake.getApplicationByNameAndSpaceReturnsOnCall[i] = struct { result1 v7action.Application result2 v7action.Warnings result3 error }{result1, result2, result3} } func (fake *FakeCancelDeploymentActor) GetLatestDeploymentForApp(arg1 string) (v7action.Deployment, v7action.Warnings, error) { fake.getLatestDeploymentForAppMutex.Lock() ret, specificReturn := fake.getLatestDeploymentForAppReturnsOnCall[len(fake.getLatestDeploymentForAppArgsForCall)] fake.getLatestDeploymentForAppArgsForCall = append(fake.getLatestDeploymentForAppArgsForCall, struct { arg1 string }{arg1}) fake.recordInvocation("GetLatestDeploymentForApp", []interface{}{arg1}) fake.getLatestDeploymentForAppMutex.Unlock() if fake.GetLatestDeploymentForAppStub != nil { return fake.GetLatestDeploymentForAppStub(arg1) } if specificReturn { return ret.result1, ret.result2, ret.result3 } fakeReturns := fake.getLatestDeploymentForAppReturns return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3 } func (fake *FakeCancelDeploymentActor) GetLatestDeploymentForAppCallCount() int { fake.getLatestDeploymentForAppMutex.RLock() defer fake.getLatestDeploymentForAppMutex.RUnlock() return len(fake.getLatestDeploymentForAppArgsForCall) } func (fake *FakeCancelDeploymentActor) GetLatestDeploymentForAppCalls(stub func(string) (v7action.Deployment, v7action.Warnings, error)) { fake.getLatestDeploymentForAppMutex.Lock() defer fake.getLatestDeploymentForAppMutex.Unlock() fake.GetLatestDeploymentForAppStub = stub } func (fake *FakeCancelDeploymentActor) GetLatestDeploymentForAppArgsForCall(i int) string { fake.getLatestDeploymentForAppMutex.RLock() defer fake.getLatestDeploymentForAppMutex.RUnlock() argsForCall := fake.getLatestDeploymentForAppArgsForCall[i] return argsForCall.arg1 } func (fake *FakeCancelDeploymentActor) GetLatestDeploymentForAppReturns(result1 v7action.Deployment, result2 v7action.Warnings, result3 error) { fake.getLatestDeploymentForAppMutex.Lock() defer fake.getLatestDeploymentForAppMutex.Unlock() fake.GetLatestDeploymentForAppStub = nil fake.getLatestDeploymentForAppReturns = struct { result1 v7action.Deployment result2 v7action.Warnings result3 error }{result1, result2, result3} } func (fake *FakeCancelDeploymentActor) GetLatestDeploymentForAppReturnsOnCall(i int, result1 v7action.Deployment, result2 v7action.Warnings, result3 error) { fake.getLatestDeploymentForAppMutex.Lock() defer fake.getLatestDeploymentForAppMutex.Unlock() fake.GetLatestDeploymentForAppStub = nil if fake.getLatestDeploymentForAppReturnsOnCall == nil { fake.getLatestDeploymentForAppReturnsOnCall = make(map[int]struct { result1 v7action.Deployment result2 v7action.Warnings result3 error }) } fake.getLatestDeploymentForAppReturnsOnCall[i] = struct { result1 v7action.Deployment result2 v7action.Warnings result3 error }{result1, result2, result3} } func (fake *FakeCancelDeploymentActor) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.cancelDeploymentMutex.RLock() defer fake.cancelDeploymentMutex.RUnlock() fake.getApplicationByNameAndSpaceMutex.RLock() defer fake.getApplicationByNameAndSpaceMutex.RUnlock() fake.getLatestDeploymentForAppMutex.RLock() defer fake.getLatestDeploymentForAppMutex.RUnlock() copiedInvocations := map[string][][]interface{}{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } func (fake *FakeCancelDeploymentActor) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { fake.invocations = map[string][][]interface{}{} } if fake.invocations[key] == nil { fake.invocations[key] = [][]interface{}{} } fake.invocations[key] = append(fake.invocations[key], args) } var _ v7.CancelDeploymentActor = new(FakeCancelDeploymentActor)
[ 6 ]
package handler import ( "encoding/json" "io/ioutil" "net/http" "github.com/gorilla/mux" "github.com/l3vick/go-pharmacy/db" "github.com/l3vick/go-pharmacy/error" "github.com/l3vick/go-pharmacy/model" "github.com/l3vick/go-pharmacy/util" ) func GetTreatmentsCustom(nID string, w http.ResponseWriter, r *http.Request) ([]*model.TreatmentCustomResponse, model.RequestResponse) { var treatmentsCustomResponse []*model.TreatmentCustomResponse var response model.RequestResponse //rows, err := db.DB.Raw("SELECT id, id_med, (SELECT name FROM pharmacy_sh.med WHERE id = id_med) as name, time, alarm, start_treatment, end_treatment, period FROM pharmacy_sh.treatment_custom WHERE id_user = " + nID +"").Rows() rows, err := db.DB.Table("treatment_custom").Select("treatment_custom.id, treatment_custom.id_med, med.name, treatment_custom.time, treatment_custom.alarm, treatment_custom.start_treatment, treatment_custom.end_treatment, treatment_custom.period ").Joins("INNER JOIN med ON med.id = treatment_custom.id_med").Where("id_user = ?", nID).Rows() defer rows.Close() util.CheckErr(err) if err != nil { response = error.HandleMysqlError(err) } else { var count = 0 for rows.Next() { count = count + 1 var id, idMed, period int var name, time, startTreatment, endTreatment, alarm string rows.Scan(&id, &idMed, &name, &time, &alarm, &startTreatment, &endTreatment, &period) treatmentsCustom := model.TreatmentCustomResponse{ ID: id, IDMed: idMed, Name: name, Time: time, Alarm: alarm, StartTreatment: startTreatment, EndTreatment: endTreatment, Period: period, } treatmentsCustomResponse = append(treatmentsCustomResponse, &treatmentsCustom) } response = error.HandleNoRowsError(count, error.SELECT, util.TITLE_TREATMENTCUSTOM) } return treatmentsCustomResponse, response } func CreateTreatmentCustom(w http.ResponseWriter, r *http.Request) { var treatmentCustom model.TreatmentCustom var response model.RequestResponse b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { http.Error(w, err.Error(), 500) return } err = json.Unmarshal(b, &treatmentCustom) if err != nil { http.Error(w, err.Error(), 500) return } db := db.DB.Table("treatment_custom").Create(&treatmentCustom) util.CheckErr(db.Error) if db.Error != nil { response = error.HandleMysqlError(db.Error) } else { response = error.HandleEmptyRowsError(db.RowsAffected, error.INSERT, util.TITLE_TREATMENTCUSTOM) } output, err := json.Marshal(response) if err != nil { http.Error(w, err.Error(), 501) return } w.Write(output) } func UpdateTreatmentCustom(w http.ResponseWriter, r *http.Request) { var response model.RequestResponse vars := mux.Vars(r) nID := vars["id"] b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if err != nil { http.Error(w, err.Error(), 500) return } var treatmentCustom model.TreatmentCustom err = json.Unmarshal(b, &treatmentCustom) if err != nil { http.Error(w, err.Error(), 500) return } db := db.DB.Table("treatment_custom").Where("id = ?", nID).Updates(&treatmentCustom) util.CheckErr(db.Error) if err != nil { response = error.HandleMysqlError(db.Error) } else { response = error.HandleEmptyRowsError(db.RowsAffected, error.Update, util.TITLE_TREATMENTCUSTOM) } output, err := json.Marshal(response) if err != nil { http.Error(w, err.Error(), 501) return } w.Write(output) } func DeleteTreatmentCustom(w http.ResponseWriter, r *http.Request) { var response model.RequestResponse vars := mux.Vars(r) nID := vars["id"] db := db.DB.Table("treatment_custom").Where("id= ?", nID).Delete(&model.TreatmentCustom{}) util.CheckErr(db.Error) if db.Error != nil { response = error.HandleMysqlError(db.Error) } else { response = error.HandleNotExistError(int(db.RowsAffected), error.DELETE, util.TITLE_TREATMENTCUSTOM) } output, err := json.Marshal(response) if err != nil { http.Error(w, err.Error(), 501) return } w.Write(output) }
[ 0, 3 ]
package adapter import ( "fmt" "net/http" "github.com/kcwebapply/svad/infrastructure/http_wrapper" ) func ProxyRequest(requestURL string, contentType string, request *http.Request) (*http.Response, error) { return doRequest(requestURL, contentType, request) } func doRequest(requestURL string, contentType string, request *http.Request) (*http.Response, error) { switch request.Method { case http.MethodGet: response, err := http_wrapper.GetRequest(requestURL, request) return response, err case http.MethodPost: response, err := http_wrapper.PostRequest(requestURL, contentType, request) return response, err case http.MethodPut: response, err := http_wrapper.PutRequest(requestURL, contentType, request) return response, err case http.MethodDelete: response, err := http_wrapper.DeleteRequest(requestURL, contentType, request) return response, err } return nil, fmt.Errorf("request method %s doesn't supporeted on this server", request.Method) }
[ 6 ]
package main import ( "github.com/gorilla/websocket" "log" "net/http" ) const ( ALPHAPOINT_DEFAULT_WEBSOCKET_URL = "wss://sim3.alphapoint.com:8401/v1/GetTicker/" ) type AlphapointWebsocketTicker struct { MessageType string `json:"messageType"` ProductPair string `json:"prodPair"` High float64 `json:"high"` Low float64 `json:"low"` Last float64 `json:"last"` Volume float64 `json:"volume"` Volume24Hrs float64 `json:"volume24hrs"` Volume24HrsProduct2 float64 `json:"volume24hrsProduct2"` Total24HrQtyTraded float64 `json:"Total24HrQtyTraded"` Total24HrProduct2Traded float64 `json:"Total24HrProduct2Traded"` Total24HrNumTrades float64 `json:"Total24HrNumTrades"` Bid float64 `json:"bid"` Ask float64 `json:"ask"` BuyOrderCount int `json:"buyOrderCount"` SellOrderCount int `json:"sellOrderCount"` } func (a *Alphapoint) WebsocketClient() { for a.ExchangeEnabled && a.WebsocketEnabled { var Dialer websocket.Dialer var err error a.WebsocketConn, _, err = Dialer.Dial(a.WebsocketURL, http.Header{}) if err != nil { log.Printf("%s Unable to connect to Websocket. Error: %s\n", a.ExchangeName, err) continue } if a.Verbose { log.Printf("%s Connected to Websocket.\n", a.ExchangeName) } err = a.WebsocketConn.WriteMessage(websocket.TextMessage, []byte(`{"messageType": "logon"}`)) if err != nil { log.Println(err) return } for a.ExchangeEnabled && a.WebsocketEnabled { msgType, resp, err := a.WebsocketConn.ReadMessage() if err != nil { log.Println(err) break } switch msgType { case websocket.TextMessage: type MsgType struct { MessageType string `json:"messageType"` } msgType := MsgType{} err := JSONDecode(resp, &msgType) if err != nil { log.Println(err) continue } switch msgType.MessageType { case "Ticker": ticker := AlphapointWebsocketTicker{} err = JSONDecode(resp, &ticker) if err != nil { log.Println(err) continue } } } } a.WebsocketConn.Close() log.Printf("%s Websocket client disconnected.", a.ExchangeName) } }
[ 7 ]
package dev_dir import ( "fmt" "github.com/pkg/errors" "github.com/syndtr/goleveldb/leveldb" "gopkg.in/yaml.v3" "nocalhost/internal/nhctl/common/base" "nocalhost/internal/nhctl/dbutils" "nocalhost/internal/nhctl/nocalhost_path" "nocalhost/pkg/nhctl/log" "os" "strings" ) var ( DefaultKey = "DefaultKey" splitter = "-/-" ) func Update(fun func(dirMapping *DevDirMapping, // be careful, this map is immutable !!!! // it is a map generate from #PathToDefaultPackKey and #PackToPath // when we change #PathToDefaultPackKey or #PackToPath, we should // regenerate this map pathToPack map[DevPath][]*SvcPack) error) error { return doGetOrModify(fun, false) } func Get(fun func(dirMapping *DevDirMapping, pathToPack map[DevPath][]*SvcPack) error) error { return doGetOrModify(fun, true) } // for test only! it is dangeruas func ClearAllData() { doGetOrModify( func(dirMapping *DevDirMapping, pathToPack map[DevPath][]*SvcPack) error { dirMapping.PathToDefaultPackKey = map[DevPath]SvcPackKey{} dirMapping.PackToPath = map[SvcPackKey]DevPath{} return nil }, false, ) } // getOrModify true is read only, and false will save the [dirMapping *DevDirMapping] into db func doGetOrModify(fun func(dirMapping *DevDirMapping, pathToPack map[DevPath][]*SvcPack) error, readOnly bool) error { var path string if os.Getenv("TEST") == "" { path = nocalhost_path.GetNocalhostDevDirMapping() } else { path = nocalhost_path.GetTestNocalhostDevDirMapping() } _ = dbutils.CreateLevelDB(path, false) db, err := dbutils.OpenLevelDB(path, readOnly) if err != nil { _ = db.Close() return err } defer db.Close() result := &DevDirMapping{} bys, err := db.Get([]byte(DefaultKey)) if err != nil { if errors.Is(err, leveldb.ErrNotFound) { result, err := db.ListAll() if err != nil { _ = db.Close() return err } for key, val := range result { if strings.Contains(key, DefaultKey) { bys = []byte(val) break } } } else { _ = db.Close() return errors.Wrap(err, "") } } if len(bys) == 0 { result = &DevDirMapping{} } else { err = yaml.Unmarshal(bys, result) if err != nil { _ = db.Close() return errors.Wrap(err, "") } } if result.PathToDefaultPackKey == nil { result.PathToDefaultPackKey = map[DevPath]SvcPackKey{} } if result.PackToPath == nil { result.PackToPath = map[SvcPackKey]DevPath{} } if result.PackToKubeConfigBytes == nil { result.PackToKubeConfigBytes = map[SvcPackKey]string{} } if result.PackToKubeConfigServer == nil { result.PackToKubeConfigServer = map[SvcPackKey]string{} } if err := fun(result, result.genPathToPackMap()); err != nil { return err } if !readOnly { bys, err := yaml.Marshal(result) if err != nil { return errors.Wrap(err, "") } return db.Put([]byte(DefaultKey), bys) } return nil } type DevDirMapping struct { PathToDefaultPackKey map[DevPath]SvcPackKey `yaml:"path_to_default_pack_key"` PackToPath map[SvcPackKey]DevPath `yaml:"pack_to_path"` PackToKubeConfigBytes map[SvcPackKey]string `yaml:"pack_to_kube_config_bytes"` PackToKubeConfigServer map[SvcPackKey]string `yaml:"pack_to_kube_config_server"` } // be careful, this map is immutable !!!! // it is a map generate from #PathToDefaultPackKey and #PackToPath // when we change #PathToDefaultPackKey or #PackToPath, we should // regenerate this map func (devDirMapping *DevDirMapping) genPathToPackMap() map[DevPath][]*SvcPack { pathToPack := make(map[DevPath][]*SvcPack, 0) for pack, path := range devDirMapping.PackToPath { if _, ok := pathToPack[path]; !ok { pathToPack[path] = make([]*SvcPack, 0) } toPack := pack.toPack() if toPack == nil { log.Logf(fmt.Sprintf("Pack can not case to svcPack %v", pack)) continue } pathToPack[path] = append(pathToPack[path], toPack) } return pathToPack } type SvcPackKey string type DevPath string func (d DevPath) ToString() string { return string(d) } type AllSvcPackAssociateByPath struct { Packs map[SvcPackKey]*SvcPack Kubeconfigs map[SvcPackKey]string ServerMapping map[SvcPackKey]string DefaultSvcPackKey SvcPackKey } func NewSvcPack(ns string, nid string, app string, svcType base.SvcType, svc string, container string) *SvcPack { return &SvcPack{ Ns: ns, Nid: nid, App: app, SvcType: svcType, Svc: svc, Container: container, } } type SvcPack struct { Ns string `yaml:"ns" json:"ns"` Nid string `yaml:"nid" json:"nid"` App string `yaml:"app" json:"app"` SvcType base.SvcType `yaml:"svc_type" json:"svc_type"` Svc string `yaml:"svc" json:"svc"` Container string `yaml:"container" json:"container"` } func (svcPackKey *SvcPackKey) toPack() *SvcPack { array := strings.Split(string(*svcPackKey), splitter) if len(array) < 5 { return nil } // nid is supported later version // so need to special compatibility handling nid := "" if len(array) > 5 { nid = array[5] } return &SvcPack{ Ns: array[0], Nid: nid, App: array[1], SvcType: base.SvcType(array[2]), Svc: array[3], Container: array[4], } } func (svcPackKey SvcPackKey) WithoutNid() SvcPackKey { str := string(svcPackKey) if len(strings.Split(str, splitter)) > 5 { return SvcPackKey(str[:strings.LastIndex(str, splitter)]) } return svcPackKey } func (svcPack SvcPack) Key() SvcPackKey { if svcPack.Container == "" { return svcPack.KeyWithoutContainer() } return SvcPackKey( fmt.Sprintf( "%s"+splitter+"%s"+splitter+"%s"+splitter+"%s"+splitter+"%s"+splitter+"%s", svcPack.Ns, svcPack.App, svcPack.SvcType, svcPack.Svc, svcPack.Container, svcPack.Nid, ), ) } func (svcPack SvcPack) KeyWithoutContainer() SvcPackKey { return SvcPackKey( fmt.Sprintf( "%s"+splitter+"%s"+splitter+"%s"+splitter+"%s"+splitter+"%s"+splitter+"%s", svcPack.Ns, svcPack.App, svcPack.SvcType, svcPack.Svc, "", svcPack.Nid, ), ) }
[ 6 ]
package main import ( "bytes" "flag" "fmt" "io" "os" "os/exec" "regexp" "strconv" "strings" "time" ) //super visor func SuperVisor(cmd string,blankTime int32) { //先查找这个进程是否存在 不设置退出的条件 //处理掉命令中多余的空格 newCmd := DeleteExtraSpace(cmd) pid := 0 for{ for { if cmd != newCmd{ pid = GetServicePid(cmd) }else{ pid = GetServicePid(newCmd) } if 0 == pid{ break } // fmt.Println(cmd," exist ",pid) time.Sleep(time.Duration(time.Second * time.Duration(blankTime))) } //进程不存在了 执行启动命令 启动不需要等待 fmt.Println("do cmd ",newCmd) err := DoLinuxCmd(newCmd) if nil != err{ fmt.Println("do cmd fail ",newCmd,err) } // fmt.Println("start cmd ",cmd,err) // time.Sleep(time.Duration(time.Second * time.Duration(blankTime))) } } //do cmd func DoLinuxCmd(cmd string)error{ args := strings.Split(cmd," ") execCmd := exec.Command(args[0],args[1:]...) return execCmd.Run() } //get app info by ps func GetServicePsInfo(serviceCmd string) string{ ps := exec.Command("ps","-aux") grep := exec.Command("grep",serviceCmd) p,g := io.Pipe() defer p.Close() defer g.Close() ps.Stdout = g grep.Stdin = p var buffer bytes.Buffer grep.Stdout = &buffer _ = ps.Start() _ = grep.Start() io.Copy(os.Stdout,&buffer) ps.Wait() g.Close() grep.Wait() return DeleteExtraSpace(buffer.String()) } //get the process pid by app name or start cmd func GetServicePid(serviceCmd string)int{ res := GetServicePsInfo(serviceCmd) if "" == res{ return 0 } resSplit := strings.Split(res," ") if len(resSplit) < 2{ return 0 } val,_ := strconv.Atoi(resSplit[1]) return val } //delete the space where bigger than 2 func DeleteExtraSpace(src string) string { //删除字符串中的多余空格,有多个空格时,仅保留一个空格 newSrc := strings.Replace(src, " ", " ", -1) //替换tab为空格 regStr := "\\s{2,}" //两个及两个以上空格的正则表达式 reg, _ := regexp.Compile(regStr) //编译正则表达式 res := make([]byte, len(newSrc)) //定义字符数组切片 copy(res, newSrc) //将字符串复制到切片 spcIndex := reg.FindStringIndex(string(res)) //在字符串中搜索 for len(spcIndex) > 0 { //找到适配项 res = append(res[:spcIndex[0]+1], res[spcIndex[1]:]...) //删除多余空格 spcIndex = reg.FindStringIndex(string(res)) //继续在字符串中搜索 } return string(res) } //kill process by app name or start cmd func KillProcess(serviceCmd string){ err := DoLinuxCmd(fmt.Sprintf("kill -9 %d",GetServicePid(serviceCmd))) fmt.Println(err) } func main() { var serviceCmd string flag.StringVar(&serviceCmd,"c","","") flag.Parse() if serviceCmd == ""{ panic("empty") } serviceCmd += " ../winwinlog" fmt.Println(GetServicePid(serviceCmd)) SuperVisor(serviceCmd,3) }
[ 3 ]
package goclone import ( "fmt" "os/exec" "github.com/imthaghost/goclone/pkg/crawler" "github.com/imthaghost/goclone/pkg/file" "github.com/imthaghost/goclone/pkg/html" "github.com/imthaghost/goclone/pkg/parser" "github.com/imthaghost/goclone/pkg/server" ) // Clone the given site :) func cloneSite(args []string) { url := args[0] if Serve == true { // grab the url from the if !parser.ValidateURL(url) && !parser.ValidateDomain(url) { fmt.Println("goclone <url>") } else if parser.ValidateDomain(url) { // use the domain as the project name name := url // CreateProject projectPath := file.CreateProject(name) // create the url validURL := parser.CreateURL(name) // Crawler crawler.Crawl(validURL, projectPath) // Restructure html html.LinkRestructure(projectPath) err := exec.Command("open", "http://localhost:5000").Start() if err != nil { panic(err) } server.Serve(projectPath) } else if parser.ValidateURL(url) { // get the hostname name := parser.GetDomain(url) // create project projectPath := file.CreateProject(name) // Crawler crawler.Crawl(url, projectPath) // Restructure html html.LinkRestructure(projectPath) err := exec.Command("open", "http://localhost:5000").Start() if err != nil { panic(err) } server.Serve(projectPath) } else { fmt.Print(url) } } else { // grab the url from the if !parser.ValidateURL(url) && !parser.ValidateDomain(url) { fmt.Println("goclone <url>") } else if parser.ValidateDomain(url) { // use the domain as the project name name := url // CreateProject projectPath := file.CreateProject(name) // create the url validURL := parser.CreateURL(name) // Crawler crawler.Crawl(validURL, projectPath) // Restructure html html.LinkRestructure(projectPath) if Open { // automatically open project err := exec.Command("open", projectPath+"/index.html").Start() if err != nil { panic(err) } } } else if parser.ValidateURL(url) { // get the hostname name := parser.GetDomain(url) // create project projectPath := file.CreateProject(name) // Crawler crawler.Crawl(url, projectPath) // Restructure html html.LinkRestructure(projectPath) if Open { err := exec.Command("open", projectPath+"/index.html").Start() if err != nil { panic(err) } } } else { fmt.Print(url) } } }
[ 5 ]
// Package protox // Created by xuzhuoxi // on 2019-05-20. // @author xuzhuoxi // package protox import "fmt" // IProtoHeader // 协议参数头接口 type IProtoHeader interface { // ProtoGroup // 协议分组 ProtoGroup() string // ProtoId // 协议标识 ProtoId() string // ClientId // 客户端标识 ClientId() string // ClientAddress // 客户端地址 ClientAddress() string // SetHeader // 设置参数头信息 SetHeader(extensionName string, protoId string, clientId string, clientAddress string) // GetHeaderInfo 取头信息 GetHeaderInfo() IProtoHeader } type ProtoHeader struct { PGroup string PId string CId string CAddress string } func (h *ProtoHeader) String() string { return fmt.Sprintf("Header{ENmae='%s', PId='%s', CID='%s', CAddr='%s'}", h.PGroup, h.PId, h.CId, h.CAddress) } func (h *ProtoHeader) GetHeaderInfo() IProtoHeader { return h } func (h *ProtoHeader) ProtoGroup() string { return h.PGroup } func (h *ProtoHeader) ProtoId() string { return h.PId } func (h *ProtoHeader) ClientId() string { return h.CId } func (h *ProtoHeader) ClientAddress() string { return h.CAddress } func (h *ProtoHeader) SetHeader(extensionName string, protoId string, clientId string, clientAddress string) { h.PGroup, h.PId, h.CId, h.CAddress = extensionName, protoId, clientId, clientAddress }
[ 6 ]
package core import ( "fmt" "log" "testing" "word_concurrence/nlp" ) func TestFPNode_Insert(t *testing.T) { //tree := &FPTree{} root := &FPRoot{} p := (*FPNode)(root) node1 := FPNode{word: "apple", count: 3, parent: nil, next: nil} p.Insert(&node1) node2 := FPNode{word: "banana", count: 4, parent: nil, next: nil} p.Insert(&node2) log.Println(root) } func TestFPTree_BuildFPTree(t *testing.T) { wordBase := nlp.Preprocess("../test/validate.txt", false, "../data/stop_words.txt", 10) wordCount := nlp.WordCount(wordBase) _, headAddr := BuildHeadElems(wordCount, 2) filteredWordBase := FilterWordBase(headAddr, wordBase) log.Println(filteredWordBase) root := &FPRoot{} root.BuildFPTree(filteredWordBase, headAddr) log.Println(fmt.Sprint(root)) } func TestFPTree_ConditionalPattern(t *testing.T) { wordBase := nlp.Preprocess("../test/validate.txt", false, "../data/stop_words.txt", 10) wordCount := nlp.WordCount(wordBase) headElems, headAddr := BuildHeadElems(wordCount, 2) filteredWordBase := FilterWordBase(headAddr, wordBase) root := &FPRoot{} root.BuildFPTree(filteredWordBase, headAddr) root.ConditionalPattern(headElems, 2, headAddr, 10) for word, elem := range headAddr { log.Println(word, elem.pattern) } }
[ 3 ]
package main import ( "encoding/json" "fmt" "net/http" "os" "sync" "time" _ "net/http/pprof" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/benclapp/updog/checks" "github.com/benclapp/updog/config" ) const SPACE = " " var version string var logger log.Logger = level.NewFilter(log.NewLogfmtLogger(os.Stdout), level.AllowInfo()) var cfg config.Configurable var checkersRegistry []checks.Checker var ( httpDurationsHistogram = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "updog_http_request_duration_seconds", Help: "HTTP Latency histogram", }, []string{"path"}, ) healthCheckDependencyDuration = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "updog_dependency_duration_seconds", Help: "Duration of a health check dependency in seconds", }, []string{"dependency", "dependency_type"}, ) healthChecksTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "updog_dependency_checks_total", Help: "Count of total health checks per dependency", }, []string{"dependency", "dependency_type"}, ) healthChecksFailuresTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "updog_dependency_check_failures_total", Help: "Count of total health check failures per dependency", }, []string{"dependency", "dependency_type"}, ) ) func init() { config.Version = version cfg = config.NewConfig() prometheus.MustRegister( httpDurationsHistogram, healthCheckDependencyDuration, healthChecksTotal, healthChecksFailuresTotal, ) //Create Checkers level.Info(logger).Log("msg", "Configured Dependencies...") for _, dep := range cfg.GetDependencies().HTTP { checkersRegistry = append(checkersRegistry, checks.NewHttpChecker(dep.Name, dep.HTTPEndpoint, cfg.GetTimeout())) initMetrics(dep.Name, checks.HTTP_TYPE) } for _, dep := range cfg.GetDependencies().Redis { checkersRegistry = append(checkersRegistry, checks.NewRedisChecker(dep.Name, dep.Address, dep.Password, cfg.GetTimeout(), dep.Ssl)) initMetrics(dep.Name, checks.REDIS_TYPE) } for _, dep := range cfg.GetDependencies().SQL { checkersRegistry = append(checkersRegistry, checks.NewSqlChecker(dep.Name, dep.Type, dep.ConnectionString)) initMetrics(dep.Name, checks.SQL_TYPE) } level.Info(logger).Log("msg", "Finished initialisation") } func initMetrics(name string, typez string) { healthCheckDependencyDuration.WithLabelValues(name, typez).Observe(0) healthChecksTotal.WithLabelValues(name, typez).Add(0) healthChecksFailuresTotal.WithLabelValues(name, typez).Add(0) } func main() { http.Handle("/metrics", promhttp.Handler()) http.HandleFunc("/ping", handlePing) http.HandleFunc("/updog", handleHealth) http.HandleFunc("/health", handleHealth) level.Error(logger).Log("err", http.ListenAndServe(cfg.GetAddress(), nil)) } func handlePing(w http.ResponseWriter, r *http.Request) { start := time.Now() fmt.Fprintf(w, "pong") httpDurationsHistogram.WithLabelValues("/ping").Observe(time.Since(start).Seconds()) } func handleHealth(w http.ResponseWriter, r *http.Request) { level.Debug(logger).Log("msg", "handleHealth") start := time.Now() defer func() { httpDurationsHistogram.WithLabelValues(r.RequestURI).Observe(time.Since(start).Seconds()) }() //loop registered checkers resultChan := make(chan checks.Result) var wg sync.WaitGroup // Start health checks concurrently //FIXME https://stackoverflow.com/questions/46010836/using-goroutines-to-process-values-and-gather-results-into-a-slice for _, checker := range checkersRegistry { wg.Add(1) // Process each item with a goroutine and send output to resultChan go func(checker checks.Checker) { defer wg.Done() resultChan <- checker.Check() }(checker) } //Use countdown latch to close after checks return go func() { wg.Wait() close(resultChan) }() results := make(map[string]checks.Result) pass := true for r := range resultChan { level.Debug(logger).Log("msg", "Dependency returned", r.Name, r.Success) pass = pass && r.Success results[r.Name] = r healthCheckDependencyDuration.WithLabelValues(r.Name, r.Typez).Observe(r.Duration) healthChecksTotal.WithLabelValues(r.Name, r.Typez).Inc() if r.Err != nil { healthChecksFailuresTotal.WithLabelValues(r.Name, r.Typez).Inc() } } // Return 503 if any of the dependencies failed if pass == false { level.Warn(logger).Log("msg", "StatusServiceUnavailable") w.WriteHeader(http.StatusServiceUnavailable) } response, _ := json.MarshalIndent(&results, "", SPACE) fmt.Fprintf(w, string(response)) }
[ 3, 6 ]
/* Copyright 2022 The Koordinator 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 util import ( "encoding/json" "errors" "sort" "strconv" "strings" "time" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/strategicpatch" "k8s.io/klog/v2" "sigs.k8s.io/scheduler-plugins/pkg/apis/scheduling/v1alpha1" "github.com/koordinator-sh/koordinator/apis/extension" ) func GetGangGroupId(s []string) string { sort.Strings(s) return strings.Join(s, ",") } func GetId(namespace, name string) string { return namespace + "/" + name } func GetGangNameByPod(pod *v1.Pod) string { if pod == nil { return "" } var gangName string if gangName = pod.Labels[v1alpha1.PodGroupLabel]; gangName == "" { // nolint:staticcheck // SA1019: extension.LabelLightweightCoschedulingPodGroupName is deprecated if gangName = pod.Labels[extension.LabelLightweightCoschedulingPodGroupName]; gangName == "" { gangName = extension.GetGangName(pod) } } return gangName } func GetGangMinNumFromPod(pod *v1.Pod) (minNum int, err error) { // nolint:staticcheck // SA1019: extension.LabelLightweightCoschedulingPodGroupMinAvailable is deprecated if s := pod.Labels[extension.LabelLightweightCoschedulingPodGroupMinAvailable]; s != "" { val, err := strconv.ParseInt(pod.Labels[extension.LabelLightweightCoschedulingPodGroupMinAvailable], 10, 32) return int(val), err } if _, ok := pod.Annotations[extension.AnnotationGangMinNum]; ok { return extension.GetMinNum(pod) } return 0, errors.New("missing min available") } func IsPodNeedGang(pod *v1.Pod) bool { return GetGangNameByPod(pod) != "" } // GetWaitTimeDuration returns a wait timeout based on the following precedences: // 1. spec.scheduleTimeoutSeconds of the given pg, if specified // 2. fall back to defaultTimeout func GetWaitTimeDuration(pg *v1alpha1.PodGroup, defaultTimeout time.Duration) time.Duration { if pg != nil && pg.Spec.ScheduleTimeoutSeconds != nil { if *pg.Spec.ScheduleTimeoutSeconds >= 0 { return time.Duration(*pg.Spec.ScheduleTimeoutSeconds) * time.Second } else { klog.Errorf("podGroup's ScheduleTimeoutSeconds illegal, podGroupName: %s", klog.KObj(pg)) } } return defaultTimeout } // StringToGangGroupSlice // Parse gang group's annotation like :"["nsA/gangA","nsB/gangB"]" => goLang slice : []string{"nsA/gangA"."nsB/gangB"} func StringToGangGroupSlice(s string) ([]string, error) { gangGroup := make([]string, 0) err := json.Unmarshal([]byte(s), &gangGroup) if err != nil { return gangGroup, err } return gangGroup, nil } // CreateMergePatch return patch generated from original and new interfaces func CreateMergePatch(original, new interface{}) ([]byte, error) { pvByte, err := json.Marshal(original) if err != nil { return nil, err } cloneByte, err := json.Marshal(new) if err != nil { return nil, err } patch, err := strategicpatch.CreateTwoWayMergePatch(pvByte, cloneByte, original) if err != nil { return nil, err } return patch, nil }
[ 1 ]
package reverse_pair import "testing" import "fmt" func traverse(head *ListNode) { p1 := head fmt.Println("begin:") for p1 != nil { fmt.Println(p1.Val) p1 = p1.Next } fmt.Println("end") } func append(head *ListNode, node *ListNode) { node.Next = head.Next head.Next = node } func Test_Reverse_Pair(t *testing.T) { var head ListNode head.Val = 1 head.Next = nil var listNode4 ListNode listNode4.Val = 6 var listNode5 ListNode listNode5.Val = 5 var listNode1 ListNode listNode1.Val = 4 var listNode2 ListNode listNode2.Val = 3 var listNode3 ListNode listNode3.Val = 2 //append(&head, &listNode4) append(&head, &listNode5) append(&head, &listNode1) append(&head, &listNode2) append(&head, &listNode3) traverse(&head) traverse(reverse_pair(&head)) } func Test_Reverse_Pair2(t *testing.T) { var head ListNode head.Val = 1 head.Next = nil // var listNode4 ListNode // listNode4.Val = 6 // append(&head, &listNode4) // traverse(&head) traverse(reverse_pair(&head)) }
[ 3, 6 ]
package main import ( "fmt" "strconv" ) func main() { fmt.Println("Generic Sum fn") fmt.Println(sum(10, 20)) //=> 30 fmt.Println(sum(10, 20, 30, 40)) //=> 100 fmt.Println(sum(10)) //=> 10 fmt.Println(sum()) //=> 0 fmt.Println(sum(10, "20", 30, "40")) //=> 100 fmt.Println(sum(10, "20", 30, "40", "abc")) //=> 100 fmt.Println(sum(10, 20, []int{30, 40})) //=> 100 fmt.Println(sum(10, 20, []interface{}{30, 40, []int{10, 20}})) //=> 130 fmt.Println(sum(10, 20, []interface{}{30, 40, []interface{}{10, "20"}})) //=> 130 } func sum(nos ...interface{}) int { result := 0 for _, val := range nos { switch val.(type) { case int: result += val.(int) case string: if x, err := strconv.Atoi(val.(string)); err != nil { result += x } case []int: values := val.([]int) intValList := make([]interface{}, len(values)) for idx, x := range values { intValList[idx] = x } result += sum(intValList...) case []interface{}: result += sum(val.([]interface{})...) } } return result }
[ 3 ]
package userRepository import ( "../models" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) var db *mgo.Database const COLLECTION = "Users" func InitDb(session *mgo.Session) { db = session.DB(COLLECTION) } func FindByUserNameAndPassword(username string, password string) (*models.User, error) { var user *models.User err := db.C(COLLECTION).Find(bson.M{"username": username, "password": password}).One(&user) if err != nil && err != mgo.ErrNotFound { return nil, err } return user, nil } func FindByUserName(username string) (*models.UserInfo, error) { var user *models.UserInfo err := db.C(COLLECTION).Find(bson.M{"username": username}).One(&user) if err != nil && err != mgo.ErrNotFound { return nil, err } return user, nil } func Insert(user *models.User) error { user.ID = bson.NewObjectId() err := db.C(COLLECTION).Insert(&user) return err } func Delete(user models.User) error { err := db.C(COLLECTION).Remove(&user) return err } func Update(user models.User) error { err := db.C(COLLECTION).UpdateId(user.ID, &user) return err }
[ 6 ]
package utils import ( "log" "math/rand" "strconv" "strings" ) func FailOnError(err error, msg string) { if err != nil { log.Fatalf("%s:%s", msg, err) } } func BodyForm(args []string) string { var s string if len(args) < 2 || args[1] == "" { s = "hello" } else { s = strings.Join(args[1:], " ") } return s } func BodyForm2(args []string) string { var s string if len(args) < 3 || args[2] == "" { s = "hello" } else { s = strings.Join(args[2:], " ") } return s } func BodyForm3(args []string) int { var s string if len(args) < 2 || args[1] == "" { s = "30" } else { s = strings.Join(args[1:], " ") } n, err := strconv.Atoi(s) FailOnError(err, "Failed to convert arg to integer") return n } func SeverityForm(args []string) string { var s string if len(args) < 2 || args[1] == "" { s = "info" } else { s = args[1] } return s } func RandInt(min, max int) int { return min + rand.Intn(max-min) } func RandomString(l int) string { bytes := make([]byte, l) for i := 0; i < l; i++ { bytes = append(bytes, byte(RandInt(65, 90))) } return string(bytes) }
[ 1 ]
package main import "fmt" const con string = "Paul's tutorials ROCK!" func main() { values() variables() constants() ifthen() cases() forloop() arrays() } func values() { fmt.Println("Hello" + " " + "Paul\n") fmt.Println("My Age: ", 16*10, "\n") fmt.Println("My float: ", 10/5) fmt.Println("Am I a male? ", (!true)) } func variables() { var s1, s2 string = "Hi", "Paul" fmt.Println(s1, s2) var i int = 1 fmt.Println(i) s3 := "How are you?" fmt.Println(s3) i2 := 12345 i2 = i2 *3 fmt.Println(i2) } func constants() { fmt.Println(con) const con2 int = 50 fmt.Println(con2) } func ifthen() { i := 30 x := 300 if i == x { fmt.Println("The numbers are perfect") } else if i < x { fmt.Println(i, "is less than", x) } else if i > x { fmt.Println(x, "is less than", i) } else { fmt.Println("Not so perect, try again") } if(x%i == 0){ fmt.Println(x, "is divisiable by", i) } } func cases() { i := 1 switch i { case 1: fmt.Println("This is 1") case 2: fmt.Println("This is 2") default: fmt.Println("none of the above") } whatTypeIsUsed := func(iface interface{}) { switch x := iface.(type) { case int: fmt.Println("This is an int") case bool: fmt.Println("this is a bool") default: fmt.Printf("Please tell me what %X is", x) } } whatTypeIsUsed("Hey Paul") } func forloop() { for i := 0; i <=10; i++ { fmt.Println(i) } for i := 0; i <=10000; i++ { if i == 13 { break } fmt.Println(i) } } func arrays() { var arr [10]string arr[1] = "Paul" arr[2] = "Wilson" arr[3] = "June" arr[4] = "16" arr[5] = "Howdy" st := [2]string{"hi", "there"} fmt.Println(st) fmt.Println(arr) i := [5]int{1, 2, 3, 4, 5} fmt.Println(i) }
[ 0, 5 ]
// Code generated by copypasta/template/leetcode/generator_test.go package main import ( "github.com/EndlessCheng/codeforces-go/leetcode/testutil" testutil2 "github.com/EndlessCheng/codeforces-go/main/testutil" "strconv" "testing" ) func Test_b(t *testing.T) { targetCaseNum := -1 if err := testutil.RunLeetCodeFuncWithFile(t, largestPalindromic, "b.txt", targetCaseNum); err != nil { t.Fatal(err) } } // https://leetcode.cn/contest/weekly-contest-307/problems/largest-palindromic-number/ func TestCompareInf(t *testing.T) { testutil.DebugTLE = 0 inputGenerator := func() (s string) { rg := testutil2.NewRandGenerator() s = rg.Str(1,5,'0','9') return } permutations := func(n, r int, do func(ids []int) (Break bool)) { ids := make([]int, n) for i := range ids { ids[i] = i } if do(ids[:r]) { return } cycles := make([]int, r) for i := range cycles { cycles[i] = n - i } for { i := r - 1 for ; i >= 0; i-- { cycles[i]-- if cycles[i] == 0 { tmp := ids[i] copy(ids[i:], ids[i+1:]) ids[n-1] = tmp cycles[i] = n - i } else { j := cycles[i] ids[i], ids[n-j] = ids[n-j], ids[i] if do(ids[:r]) { return } break } } if i == -1 { return } } } runAC := func(s string) (ans string) { // 若要修改 a,必须先 copy 一份,在 copied 上修改 num := 0 for r := 1; r <= len(s); r++ { permutations(len(s), r, func(ids []int) (Break bool) { t := []byte{} for _, id := range ids { t = append(t, s[id]) } if len(t) > 1 && t[0] == '0' { return } for i, n := 0, len(t); i < n/2; i++ { v, w := t[i], t[n-1-i] if v != w { return } } tt := string(t) v, _ := strconv.Atoi(tt) if v > num { num = v } return }) } ans = strconv.Itoa(num) return } // test examples first //if err := testutil.RunLeetCodeFuncWithFile(t, runAC, "b.txt", 0); err != nil { // t.Fatal(err) //} //return testutil.CompareInf(t, inputGenerator, runAC, largestPalindromic) }
[ 3 ]
package platformclientv2 import ( "encoding/json" "fmt" "github.com/tidwall/pretty" "io" "log" "net/http" "os" "strconv" "strings" "time" ) var ( traceLogger *log.Logger debugLogger *log.Logger errorLogger *log.Logger ) type LoggingLevel int const ( LTrace LoggingLevel = iota LDebug LError LNone ) type LoggingFormat int const ( JSON LoggingFormat = iota Text ) func loggingFormatFromString(value string) *LoggingFormat { var logFormat LoggingFormat switch value { case "text": logFormat = Text case "json": logFormat = JSON default: return nil } return &logFormat } func loggingLevelFromString(value string) *LoggingLevel { var logLevel LoggingLevel switch value { case "trace": logLevel = LTrace case "debug": logLevel = LDebug case "error": logLevel = LError case "none": logLevel = LNone default: return nil } return &logLevel } type logStatement struct { Date *time.Time `json:"date,omitempty"` Level string `json:"level,omitempty"` Method string `json:"method,omitempty"` URL string `json:"url,omitempty"` RequestHeaders http.Header `json:"requestHeaders,omitempty"` ResponseHeaders http.Header `json:"responseHeaders,omitempty"` CorrelationId string `json:"correlationId,omitempty"` StatusCode int `json:"statusCode,omitempty"` RequestBody string `json:"requestBody,omitempty"` ResponseBody string `json:"responseBody,omitempty"` } func (s *logStatement) string(format LoggingFormat, logRequestBody, logResponseBody bool) string { if len(s.RequestHeaders["Authorization"]) > 0 { s.RequestHeaders["Authorization"] = []string{"[REDACTED]"} } if !logRequestBody { s.RequestBody = "" } if !logResponseBody { s.ResponseBody = "" } if format == Text { return fmt.Sprintf(` === REQUEST ===%v%v%v%v === RESPONSE ===%v%v%v%v`, formatValue("URL", s.URL), formatValue("Method", s.Method), formatValue("Headers", formatHeaders(s.RequestHeaders)), formatValue("Body", s.RequestBody), formatValue("Status", fmt.Sprintf("%v", s.StatusCode)), formatValue("Headers", formatHeaders(s.ResponseHeaders)), formatValue("CorrelationId", s.CorrelationId), formatValue("Body", s.ResponseBody)) } j, _ := json.Marshal(s) str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\u`, `\u`, -1)) return strings.TrimRight(string(pretty.Ugly([]byte(str))), "\n") } func (c *LoggingConfiguration) configureLogging() { var f *os.File if c.logFilePath != "" { f, _ = os.OpenFile(c.logFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) } var stdoutWrt io.Writer var stderrWrt io.Writer if f != nil && c.logToConsole { // Logging to console and file stdoutWrt = io.MultiWriter(f, os.Stdout) stderrWrt = io.MultiWriter(f, os.Stderr) } else if f == nil && c.logToConsole { // Logging to console stdoutWrt = io.MultiWriter(os.Stdout) stderrWrt = io.MultiWriter(os.Stderr) } else if f != nil && !c.logToConsole { // Logging to file stdoutWrt = io.MultiWriter(f) stderrWrt = io.MultiWriter(f) } else { // Cannot log to anything traceLogger = nil debugLogger = nil errorLogger = nil return } flags := 0 tracePrefix := "" debugPrefix := "" errorPrefix := "" if c.logFormat == Text { flags = log.Ldate | log.Ltime tracePrefix = "TRACE: " debugPrefix = "DEBUG: " errorPrefix = "ERROR: " } traceLogger = log.New(stdoutWrt, tracePrefix, flags) debugLogger = log.New(stdoutWrt, debugPrefix, flags) errorLogger = log.New(stderrWrt, errorPrefix, flags) } func (c *LoggingConfiguration) trace(method, URL string, requestBody []byte, statusCode int, requestHeaders, responseHeaders http.Header) { now := time.Now() logStatement := &logStatement{ Date: &now, Level: "trace", Method: method, URL: URL, RequestBody: string(requestBody), CorrelationId: getCorrelationId(responseHeaders), StatusCode: statusCode, RequestHeaders: requestHeaders, ResponseHeaders: responseHeaders, } c.log(traceLogger, LTrace, logStatement.string(c.logFormat, c.LogRequestBody, c.LogResponseBody)) } func (c *LoggingConfiguration) debug(method, URL string, requestBody []byte, statusCode int, requestHeaders http.Header) { now := time.Now() logStatement := &logStatement{ Date: &now, Level: "debug", Method: method, URL: URL, RequestBody: string(requestBody), StatusCode: statusCode, RequestHeaders: requestHeaders, } c.log(debugLogger, LDebug, logStatement.string(c.logFormat, c.LogRequestBody, c.LogResponseBody)) } func (c *LoggingConfiguration) error(method, URL string, requestBody, responseBody []byte, statusCode int, requestHeaders, responseHeaders http.Header) { now := time.Now() logStatement := &logStatement{ &now, "error", method, URL, requestHeaders, responseHeaders, getCorrelationId(responseHeaders), statusCode, string(requestBody), string(responseBody), } c.log(errorLogger, LError, logStatement.string(c.logFormat, c.LogRequestBody, c.LogResponseBody)) } func (c *LoggingConfiguration) log(logger *log.Logger, logLevel LoggingLevel, v ...interface{}) { if logLevel >= c.LogLevel && logger != nil { logger.Println(v...) } } func getCorrelationId(headers http.Header) string { for key, values := range headers { if strings.ToLower(key) == "inin-correlation-id" { for _, value := range values { if value != "" { return value } } } } return "" } // Returns each header key value pair indented by one tab func formatHeaders(headers http.Header) string { var result string for key, values := range headers { var valuesString string for _, value := range values { valuesString = fmt.Sprintf("%v, %v", valuesString, value) } valuesString = strings.TrimLeft(valuesString, ", ") result = fmt.Sprintf("%v\n\t%v: %v", result, key, valuesString) } return result } // Used to only print values that aren't empty func formatValue(name, value string) string { if value != "" { return fmt.Sprintf("\n%v: %v", name, value) } return "" }
[ 2, 5 ]
package main import ( "fmt" "net" "server/gameServer/game" "server/share/protocol" "sync" "github.com/game_engine/cache/redis" "github.com/golang/protobuf/proto" ) type Deal2A struct { server_note_address string //通知玩家需要登录的游戏服 server_count int32 //在线人数 server_id int32 //游戏服务器具体id编号 deal2amx *sync.RWMutex } func (this *Deal2A) Init() { this.deal2amx = new(sync.RWMutex) this.server_note_address = sys_config.ServerNoteAddress this.server_id = sys_config.GameId this.server_count = 0 } func (this *Deal2A) send2AccountMenber() { this.server_count += 1 result2A := &protocol.Account_GameResult{ Count: proto.Int32(this.server_count), GameId: proto.Int32(this.server_id), GameAddress: proto.String(this.server_note_address), } encObj, _ := proto.Marshal(result2A) SendPackage(conn2a, 101, encObj) } func (this *Deal2A) Task(pid int32, buf []byte, n int) { switch pid { case 102: //账号服务器登陆成功后往 game服务器写入 playerid sn get_note := new(protocol.Account_NoteGame) if err := proto.Unmarshal(buf[0:n], get_note); err == nil { player_id := get_note.GetPlayerId() game.Log.Info("player_id + server_id %d", player_id+this.server_id*1000000) this.NoteGame(int64(player_id + this.server_id*1000000)) } default: } } //防外挂 逻辑更严密 func (this *Deal2A) NoteGame(player_id int64) { this.deal2amx.Lock() defer this.deal2amx.Unlock() is_exists, _ := redis.Exists(player_id) if !is_exists { redis.Modify(player_id, "") } fmt.Println("通知账号服务", player_id) } //账号服务器通知game服务器 消息下发 func (this *Deal2A) Handler2A(conn net.Conn) { defer conn.Close() const MAXLEN = 1024 buf := make([]byte, MAXLEN) for { n, err := conn.Read(buf) //接收具体消息 if err != nil { return } if n > MAXLEN { game.Log.Error("recive error n> MAXLEN") return } //接收包头 _, head_pid := GetHead(buf) go this.Task(head_pid, buf[8:], n-8) } }
[ 3 ]
package errorx type ServiceError struct { Errcode int Errmsg string } func (se ServiceError) Error() string { return se.Errmsg } func (se ServiceError) Equal(dest ServiceError) bool { return se.Errmsg == dest.Errmsg && se.Errcode == dest.Errcode } func NewServiceError(errmsg string, errcode int) ServiceError { return ServiceError{ Errcode: errcode, Errmsg: errmsg, } } // IsServiceErr is used to handle service error. // Case below will be regarded as service error and return se,true func IsServiceErr(src error, dest ...error) (ServiceError, bool) { if len(dest) == 0 { se, ok := src.(ServiceError) if ok { return se, true } e, ok2 := src.(Error) if ok2 && e.isServiceErr == true { return ServiceError{ Errmsg: e.serviceErrmsg, Errcode: e.serviceErrcode, }, true } return ServiceError{}, false } for i, _ := range dest { if se, ok := isServiceErr(src, dest[i]); ok { return se, ok } } return ServiceError{}, false } func isServiceErr(src error, dest error) (ServiceError, bool) { if src == nil { return ServiceError{}, false } if dest == nil { return ServiceError{}, false } destS, ok := dest.(ServiceError) if src.Error() == dest.Error() && !ok { return NewServiceError(src.Error(), 0), true } if src.Error() == dest.Error() && ok { return destS, true } if !ok { if isBasicErr(dest) { return isServiceErr(src, NewServiceError(dest.Error(), 0)) } return ServiceError{}, false } switch v := src.(type) { case Error: if v.E.Error() == dest.Error() { return destS, true } return ServiceError{}, false case ServiceError: if v.Equal(destS) { return destS, true } return v, false case error: return ServiceError{}, false } return ServiceError{}, false }
[ 6 ]