text
stringlengths
11
4.05M
package main import ( "os" "path/filepath" "testing" "github.com/AdityaVallabh/swagger_meqa/meqa/mqutil" ) func TestMqgo(t *testing.T) { var baseURL, username, password, apitoken string wd, _ := os.Getwd() meqaPath := filepath.Join(wd, "../../testdata") swaggerPath := filepath.Join(meqaPath, "petstore_meqa.yml") planPath := filepath.Join(meqaPath, "simple.yml") resultPath := filepath.Join(meqaPath, "result.yml") testToRun := "all" baseURL, username, password, apitoken, dataset := "", "", "", "", "" fuzzType := "none" batchSize := 0 repro, verbose := false, false mqutil.Logger = mqutil.NewFileLogger(filepath.Join(meqaPath, "mqgo.log")) runMeqa(&meqaPath, &swaggerPath, &planPath, &resultPath, &testToRun, &username, &password, &apitoken, &baseURL, &dataset, &fuzzType, &batchSize, &repro, &verbose) } func TestMain(m *testing.M) { os.Exit(m.Run()) }
package parser import ( "bytes" "fmt" "math/big" "net" "strings" ) const ( TYPE_IPV4 = "ipv4" TYPE_IPV6 = "ipv6" ) type CIDRInfo struct { t string ipNet *net.IPNet Network net.IP // []byte Mask net.IPMask // []byte ones int bits int SrcCIDR string HostNum int Min net.IP // []byte Max net.IP // []byte Broadcast net.IP // []byte } func Parse(srcCIDR string) (CIDRInfo, error) { var cidr CIDRInfo ip, ipNet, eParse := net.ParseCIDR(srcCIDR) if eParse != nil { return cidr, eParse } t, eType := getType(ip) if eType != nil { return cidr, eType } cidr.t = t cidr.SrcCIDR = srcCIDR cidr.ipNet = ipNet cidr.Network = ipNet.IP cidr.Mask = ipNet.Mask cidr.ones, cidr.bits = cidr.Mask.Size() if cidr.t == TYPE_IPV4 { // calculate cidr.calcIPv4() } return cidr, nil } func getType(ip net.IP) (string, error) { if ip4 := ip.To4(); len(ip4) == net.IPv4len { return TYPE_IPV4, nil } else if ip6 := ip.To16(); len(ip6) == net.IPv6len { // TODO ipv6 return "", fmt.Errorf("ip %+v is not IPv4\n", ip) } else { return "", fmt.Errorf("ip %+v is not IPv4\n", ip) } } func (cidr *CIDRInfo) calcIPv4() { // Host Num cidr.calcHostNumV4() // Min, Max, Broadcast if cidr.HostNum > 1 { cidr.calcAddressesV4() } } func (cidr *CIDRInfo) calcHostNumV4() { var hostNum int if cidr.ones == cidr.bits { hostNum = 1 } else if cidr.ones == cidr.bits-1 { hostNum = 2 } else { hostNum = int(new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(cidr.bits-cidr.ones)), nil).Int64()) - 2 } cidr.HostNum = hostNum } func (cidr *CIDRInfo) calcAddressesV4() { // Broadcast Address cidr.calcBroadCast() // Min IP Address if cidr.ones == 31 { // XXX cidr.Min = cidr.Network } else { minIp := makeIpV4(cidr.Network) minIp[3] += 1 cidr.Min = minIp } // Max IP Address if cidr.ones == 31 { // XXX cidr.Max = cidr.Broadcast } else { maxIp := makeIpV4(cidr.Broadcast) maxIp[3] -= 1 cidr.Max = maxIp } } func (cidr *CIDRInfo) calcBroadCast() { var buf bytes.Buffer for _, octet := range cidr.Network { buf.WriteString(byte2binstr(octet)) } bcBinStr := buf.String()[:cidr.ones] + strings.Repeat("1", cidr.bits-cidr.ones) broad := make([]byte, 4) for i, f, t := 0, 0, 8; i < 4; i, f, t = i+1, f+8, t+8 { broad[i] = binstr2byte(bcBinStr[f:t]) } cidr.Broadcast = makeIpV4(broad) } func byte2binstr(b byte) string { return fmt.Sprintf("%08b", b) } func binstr2byte(binstr string) byte { var i, j int var bv byte for i, j = len(binstr)-1, 0; i >= 0; i, j = i-1, j+1 { if binstr[i] != '0' { bv |= (1 << uint(j)) } } return bv } func binstr2hexstr(binstr string) string { return fmt.Sprintf("%02x", binstr2byte(binstr)) } func makeIpV4(src []byte) net.IP { dst := make(net.IP, net.IPv4len) copy(dst, src) return dst } func (cidr *CIDRInfo) Contains(srcIP string) bool { return cidr.ipNet.Contains(net.ParseIP(srcIP)) }
package repositories import ( "testing" "github.com/stretchr/testify/assert" ) func TestNewUsersRepository(t *testing.T) { r := newUsersRepositoryMock() _, ok := r.(*MockUsersRepository) assert.True(t, ok) }
package main import "fmt" import "math/rand" type SkipList struct { next *SkipList down *SkipList value *int } func (sl *SkipList) height () int { if (sl == nil) { return 0 } else { return 1 + sl.down.height() } } func (sl *SkipList) find (i int) (*SkipList, *SkipList, []*SkipList) { previous := make([]*SkipList, sl.height()) return sl.findWithPrevious(i, previous, 0) } func (sl *SkipList) findWithPrevious (i int, previous []*SkipList, index int) (*SkipList, *SkipList, []*SkipList) { current, prev := sl.findInRow(i) if current != nil || prev.down == nil { return current, prev, previous } else { previous[index] = prev return prev.down.findWithPrevious(i, previous, index + 1) } } func (sl *SkipList) add (i int) (*SkipList) { _, prev, _ := sl.find(i) newNode := prev.addToRow(i) for rand.Intn(3) == 0 { fmt.Printf("%d would be promoted\n", i) } return newNode } func (sl *SkipList) findInRow (i int) (*SkipList, *SkipList) { var previous *SkipList current := sl for current != nil && current.value != nil && *current.value < i { previous = current current = current.next } if current != nil && current.value != nil && *current.value != i { current = nil } return current, previous } func (sl *SkipList) addToRow (i int) (*SkipList) { if sl != nil && sl.value != nil { newNode := new(SkipList) newNode.value = &i _, loc := sl.findInRow(i) if loc != nil { newNode.next = loc.next loc.next = newNode } else { newNode.value = sl.value newNode.next = sl.next sl.next = newNode sl.value = &i newNode = sl } return newNode } else if sl != nil { sl.value = &i return sl } return nil } func (sl SkipList) printNode() { if (sl.value != nil) { fmt.Printf(" --> %d", *sl.value) if (sl.next != nil) { sl.next.printNode() } } } func (sl SkipList) printList() { if (sl.value != nil) { fmt.Printf("%d", *sl.value) if (sl.next != nil) { sl.next.printNode() } } fmt.Printf("\n") } func main() { sl := new(SkipList) sl.add(2) sl.printList() sl.add(4) sl.printList() sl.add(1) sl.printList() sl.add(5) sl.printList() sl.add(3) sl.printList() a, b, _ := sl.find(4) fmt.Printf("Head %d\n", *sl.value) fmt.Printf("Current %d\n", *a.value) fmt.Printf("Previous %d\n", *b.value) }
package lib import ( "fmt" ) var block = "lib" func Print() { fmt.Printf("The lib block is %s.\n", block) }
package piper import "strconv" type testData struct { id string value int } func newTestData(value int) *testData { return &testData{ id: strconv.Itoa(value), value: value, } } func (d *testData) GetID() string { return d.id }
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "github.com/golang/glog" "k8s.io/api/admission/v1beta1" "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) //GrumpyServerHandler listen to admission requests and serve responses type GrumpyServerHandler struct { } func (gs *GrumpyServerHandler) serve(w http.ResponseWriter, r *http.Request) { var body []byte if r.Body != nil { if data, err := ioutil.ReadAll(r.Body); err == nil { body = data } } if len(body) == 0 { glog.Error("empty body") http.Error(w, "empty body", http.StatusBadRequest) return } glog.Info("Received request") if r.URL.Path != "/validate" { glog.Error("no validate") http.Error(w, "no validate", http.StatusBadRequest) return } arRequest := v1beta1.AdmissionReview{} if err := json.Unmarshal(body, &arRequest); err != nil { glog.Error("incorrect body") http.Error(w, "incorrect body", http.StatusBadRequest) } raw := arRequest.Request.Object.Raw pod := v1.Pod{} if err := json.Unmarshal(raw, &pod); err != nil { glog.Error("error deserializing pod") return } if pod.Name == "smooth-app" { return } arResponse := v1beta1.AdmissionReview{ Response: &v1beta1.AdmissionResponse{ Allowed: false, Result: &metav1.Status{ Message: "Keep calm and not add more crap in the cluster!", }, }, } resp, err := json.Marshal(arResponse) if err != nil { glog.Errorf("Can't encode response: %v", err) http.Error(w, fmt.Sprintf("could not encode response: %v", err), http.StatusInternalServerError) } glog.Infof("Ready to write reponse ...") if _, err := w.Write(resp); err != nil { glog.Errorf("Can't write response: %v", err) http.Error(w, fmt.Sprintf("could not write response: %v", err), http.StatusInternalServerError) } }
package tickets import ( "encoding/json" "log" "net/http" // Mongo DB "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type BookingConfig struct { ID int `json:"id"` // Number of days tickets are on sale NDays int `json:"ndays"` // Typical number of tickets in the morning session NMorningTickets int `json:"nmorningtickets"` // Typical number of tickets in the evening session NAfternoonTickets int `json:"nafternoontickets"` // Exclude dates ExcludeDates []string `json:"excludedates, omitempty"` // Exclude days (0 - Sunday, 6 - Saturday) ExcludeDays []bool `json:"excludedays, omitempty"` // Booking dates BookingDates []string `json:"bookingdates, omitempty"` } // ConfigBookingDates assign excludedays and dates func ConfigBookingDates(s *mgo.Session, test bool) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { session := s.Copy() defer session.Close() var config BookingConfig // Decode POST JSON file decoder := json.NewDecoder(r.Body) err := decoder.Decode(&config) if err != nil { ErrorWithJSON(w, "Incorrect body", http.StatusBadRequest) return } // Test Config DB or Production config var configtable string if test { configtable = "testconfig" } else { configtable = "config" } // Open config collections dbc := session.DB("tickets").C(configtable) // Try to update if configuration is found err = dbc.Update(bson.M{"id": 0}, &config) if err != nil { switch err { default: ErrorWithJSON(w, "Database error", http.StatusInternalServerError) log.Println("Failed to update config: ", err) return // Configuration is not present, do an insert case mgo.ErrNotFound: log.Println("Config not present, creating a new config") err = dbc.Insert(&config) if err != nil { ErrorWithJSON(w, "Database error", http.StatusInternalServerError) log.Println("Failed to insert config: ", err) return } } } err = createBookingDates(session, test) if err != nil { switch err { default: ErrorWithJSON(w, "Database error, failed to update project", http.StatusInternalServerError) return case mgo.ErrNotFound: ErrorWithJSON(w, "Project not found", http.StatusNotFound) return } } // Write response w.Header().Set("Content-Type", "application/json") w.Header().Set("Location", r.URL.Path+"/0") w.WriteHeader(http.StatusCreated) } } // BookingDates return allowable booking days func GetConfigDates(s *mgo.Session, test bool) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { // Copy and launch a Mongo session session := s.Copy() defer session.Close() // Test Config DB or Production config var configtable string if test { configtable = "testconfig" } else { configtable = "config" } // Open config collections dbc := session.DB("tickets").C(configtable) var config BookingConfig // Find the configuration file err := dbc.Find(bson.M{"id": 0}).One(&config) if err != nil { ErrorWithJSON(w, "Database error, failed to find config!", http.StatusInternalServerError) log.Println("Failed to find config: ", err) return } // Marshall booking dates respBody, err := json.MarshalIndent(config, "", " ") if err != nil { log.Fatal(err) } ResponseWithJSON(w, respBody, http.StatusOK) } }
package tools import ( "os" "strings" "mime/multipart" "io" "fmt" "strconv" "github.com/astaxie/beego" ) //保存文件 func SaveFile(file multipart.File, handler *multipart.FileHeader, num int64, filePath string) (name string, path string, err error) { if err != nil { return } defer file.Close() if !IsDirExist(filePath) { os.MkdirAll(filePath, 0777) } var fileName string n := strings.Split(handler.Filename, ".") if num > 0 { for i := 0; i < len(n)-1; i++ { fileName = fileName + n[i] } fileName = fileName + "(" + strconv.FormatInt(num, 10) + ")." + n[len(n)-1] }else { fileName = handler.Filename } dir := filePath + "/" + fileName f, err := os.Create(dir) CheckError(err) defer f.Close() a, err := io.Copy(f, file) fmt.Println(a) return fileName, dir, err } //保存文件 func SaveUserHeadImage(file multipart.File, handler *multipart.FileHeader, id int64, filePath string) (path string, err error) { if err != nil { return } defer file.Close() if !IsDirExist(filePath) { os.MkdirAll(filePath, 0777) } var fileName string n := strings.Split(handler.Filename, ".") t := strings.Replace(FormatDate(TimeNow())," ", "_", 1) t = strings.Replace(FormatDate(TimeNow()),":", "_", 2) fileName = strconv.FormatInt(id, 10) + t + "." + n[len(n)-1] dir := filePath + fileName f, err := os.Create(dir) CheckError(err) defer f.Close() a, err := io.Copy(f, file) beego.Informational(a) return dir, err } //删除图片 func DeleteImageWithPath(path string) (err error) { p := strings.Split(path, "/") filePath := "."+"/"+p[len(p)-3]+"/"+p[len(p)-2]+"/"+p[len(p)-1] if err := os.Remove(filePath);err !=nil { return nil }else { CheckError(err) return err } } //删除文件 func DeleteFileWithPath(path string) (err error) { p := strings.Split(path, "/") filePath := "."+"/"+p[len(p)-4] + "/"+p[len(p)-3]+"/"+p[len(p)-2]+"/"+p[len(p)-1] if err := os.Remove(filePath);err !=nil { return nil }else { CheckError(err) return err } }
package fibonacci import ( "fmt" "testing" ) var table = []struct { arg int want int }{ {0, 0}, {1, 1}, {10, 55}, {20, 6765}, } const N = 20 var sink int func TestFibCycle(t *testing.T) { for _, entry := range table { got := FibCycle(entry.arg) if got != entry.want { t.Errorf("For %d got %d want %d", entry.arg, got, entry.want) } } } func BenchmarkFibCycle(b *testing.B) { var res int for i := 0; i < b.N; i++ { res = FibCycle(N) } sink = res } func ExampleFibCycle() { fmt.Println(FibCycle(20)) // Output: 6765 } func TestFibRecursion(t *testing.T) { for _, entry := range table { got := FibRecursion(entry.arg) if got != entry.want { t.Errorf("For %d got %d want %d", entry.arg, got, entry.want) } } } func BenchmarkFibRecursion(b *testing.B) { var res int for i := 0; i < b.N; i++ { res = FibRecursion(N) } sink = res } func ExampleFibRecursion() { fmt.Println(FibRecursion(20)) // Output: 6765 } func TestFibSlice(t *testing.T) { for _, entry := range table { got := FibSlice(entry.arg) if got != entry.want { t.Errorf("For %d got %d want %d", entry.arg, got, entry.want) } } } func BenchmarkFibSlice(b *testing.B) { var res int for i := 0; i < b.N; i++ { res = FibSlice(N) } sink = res } func ExampleFibSlice() { fmt.Println(FibSlice(20)) // Output: 6765 } func TestFibMap(t *testing.T) { for _, entry := range table { got := FibMap(entry.arg) if got != entry.want { t.Errorf("For %d got %d want %d", entry.arg, got, entry.want) } } } func BenchmarkFibMap(b *testing.B) { var res int for i := 0; i < b.N; i++ { res = FibMap(N) } sink = res } func ExampleFibMap() { fmt.Println(FibMap(20)) // Output: 6765 } func TestFibMapV2(t *testing.T) { for _, entry := range table { got := FibMapV2(entry.arg) if got != entry.want { t.Errorf("For %d got %d want %d", entry.arg, got, entry.want) } } } func BenchmarkFibMapV2(b *testing.B) { var res int for i := 0; i < b.N; i++ { res = FibMapV2(N) } sink = res } func ExampleFibMapV2() { fmt.Println(FibMapV2(20)) // Output: 6765 } func TestFibCache(t *testing.T) { for _, entry := range table { got := FibCache(entry.arg) if got != entry.want { t.Errorf("For %d got %d want %d", entry.arg, got, entry.want) } } } func BenchmarkFibCache(b *testing.B) { var res int for i := 0; i < b.N; i++ { res = FibCache(N) } sink = res } func ExampleFibCache() { fmt.Println(FibCache(20)) // Output: 6765 }
package component import ( "github.com/rivo/tview" ) func CreateDescription() *tview.TextView { textView := tview.NewTextView() textView.SetBorder(true) textView.SetTitle("description") textView.SetText("(left or right): move dir (up or down): change file") return textView }
package database import ( "log" "loranet20181205/exception" ) type TbMeterList struct { NO uint `gorm:"column:no"` MeterUniqueID string `gorm:"column:meterUniqueID"` MeterID string `gorm:"column:meterID"` CustomerID string `gorm:"column:customerId"` AK string `gorm:"column:AK"` GUK string `gorm:"column:GUK"` } func (TbMeterList) TableName() string { return "tb_meter_list" } func GetMeterList(MeterID string) TbMeterList { var meterList []TbMeterList db, err := DbConnect() exception.CheckError(err) defer db.Close() db.Where("meterID = ?", MeterID).Find(&meterList) if len(meterList) == 0 { log.Print("ERROR: Invalid MeterID") } // log.Print("AK:", meterList[0].AK, " GUK:", meterList[0].GUK) return meterList[0] }
package main import ( "database/sql" "html/template" "io/ioutil" "log" _ "mysql" "net/http" "router" "strings" "user" ) var ( DB *sql.DB Path string ) func main() { //init() Path = "C:/Users/Д/Go/fls" var err error log.SetFlags(log.Lshortfile) DB, err = sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/chat") if err != nil { log.Fatal(err) } defer DB.Close() //router settings router := httprouter.New() router.GET("/", mainHandler) router.POST("/auth", authHandler) router.POST("/signup", signupHandler) router.POST("/signup/uniquelogin", uLoginHandler) router.POST("/signup/uniquenick", uNickHandler) router.POST("/auth/changeavatar", changeAvatarHandler) router.NotFound = http.HandlerFunc(fsHandler) //start server http.ListenAndServe(":80", router) } //Main Handler func mainHandler(wr http.ResponseWriter, r *http.Request, _ httprouter.Params) { User := user.Get(wr, r, DB) tPath := Path + "/templates" t, err := template.ParseFiles(tPath+"/index.html", tPath+"/chat.html", tPath+"/login.html") if err != nil { log.Fatal(err) } t.Execute(wr, User) } //Authorization Handler func authHandler(wr http.ResponseWriter, r *http.Request, _ httprouter.Params) { user.Auth(wr, r, DB) } //Register Handler func signupHandler(wr http.ResponseWriter, r *http.Request, _ httprouter.Params) { user.SignUp(wr, r, DB) } //It's Unique? func uLoginHandler(wr http.ResponseWriter, r *http.Request, _ httprouter.Params) { login := r.FormValue("login") is := user.UniqueLogin(login, DB) if is { wr.Write([]byte("yes")) } else { wr.Write([]byte("no")) } } func uNickHandler(wr http.ResponseWriter, r *http.Request, _ httprouter.Params) { nick := r.FormValue("nick") is := user.UniqueLogin(nick, DB) if is { wr.Write([]byte("yes")) } else { wr.Write([]byte("no")) } } //Change Avatar Handler func changeAvatarHandler(wr http.ResponseWriter, r *http.Request, _ httprouter.Params) { del := r.FormValue("delete") if del != "Delete avatar" { //Change avatar err := user.ChangeAvatar(wr, r, DB, Path) if err != nil { log.Print(err) http.Redirect(wr, r, "/#caerr", 301) } else { http.Redirect(wr, r, "/#casuc", 301) } } else { //Delete avatar err := user.DeleteAvatar(wr, r, DB, Path) if err != nil { log.Print(err) http.Redirect(wr, r, "/#delava", 301) } else { http.Redirect(wr, r, "/#delava", 301) } } } //File System Handler func fsHandler(wr http.ResponseWriter, r *http.Request) { file, err := ioutil.ReadFile(Path + "/files/" + r.URL.Path) if err != nil { notFound(wr, r) } else { var ct string if strings.HasSuffix(r.URL.Path, ".css") { ct = "text/css" } else if strings.HasSuffix(r.URL.Path, ".js") { ct = "application/javascript" } else if strings.HasSuffix(r.URL.Path, ".png") { ct = "image/png" } else if strings.HasSuffix(r.URL.Path, "jpg") || strings.HasSuffix(r.URL.Path, "jpeg") { ct = "image/jpeg" } else { ct = "text/plain" } wr.Header().Set("Content-Type", ct) wr.Write(file) } } //notfound handler func notFound(wr http.ResponseWriter, r *http.Request) { wr.WriteHeader(http.StatusNotFound) wr.Write([]byte("I love animegirls")) }
package handlers import ( "bytes" "challenge-backend/models" "database/sql" "encoding/json" "io" "log" "net/http" "net/url" "os/exec" "reflect" "strings" "github.com/PuerkitoBio/goquery" "github.com/valyala/fasthttp" ) // GetDomains : handler for get domain collection from database func GetDomains(db *sql.DB) fasthttp.RequestHandler { return func(ctx *fasthttp.RequestCtx) { action := ctx.QueryArgs().Peek("action") cursor := ctx.QueryArgs().Peek("cursor") domains, err := models.GetDomains(db, string(action), string(cursor)) if err != nil { log.Println(err) ctx.Error("The domains can't be consulted", 500) } if err := json.NewEncoder(ctx).Encode(domains); err != nil { log.Println(err) ctx.Error("The domains can't be consulted", 500) } } } // GetPageInfo : method to get the web page information, like icon and title func GetPageInfo(domain string) (models.ScrapingResponse, error) { // Request the HTML page. var route = "http://" + domain res, err := http.Get(route) if err != nil { log.Println(err) return models.ScrapingResponse{}, err } defer res.Body.Close() if res.StatusCode != 200 { log.Println("status code error: ", res.StatusCode, res.Status) return models.ScrapingResponse{}, err } // Load the HTML document doc, err := goquery.NewDocumentFromReader(res.Body) if err != nil { log.Println(err) return models.ScrapingResponse{}, err } var scrapingResponse models.ScrapingResponse // Find the head doc.Find("head").Each(func(i int, s *goquery.Selection) { // For each item found, get the rel and href s.Find("link").Each(func(j int, l *goquery.Selection) { rel, _ := l.Attr("rel") if strings.Contains(rel, "icon") { href, _ := l.Attr("href") if strings.Contains(href, "http://") || strings.Contains(href, "https://") { scrapingResponse.Icon = href } else { strTrim := strings.TrimLeft(href, "/") scrapingResponse.Icon = route + "/" + strTrim } } }) title := s.Find("title").Text() scrapingResponse.Title = strings.Trim(title, "\t \n") }) return scrapingResponse, nil } // GetOwnerData : get the owner data of the web site func GetOwnerData(address string, key string) string { // get the owner data trough piped command between whois command and grep // to get the exact key information that is been searched output := exec.Command("whois", address) output2 := exec.Command("grep", "-m 1", key) // create the pipe for read and write exec command response reader, writer := io.Pipe() // buffer that stores response var buf bytes.Buffer // read and write response for outputs output.Stdout = writer output2.Stdin = reader output2.Stdout = &buf // starts commands in cmd output.Start() output2.Start() output.Wait() writer.Close() output2.Wait() reader.Close() // read buffer for loking response var name = buf.String() // delete spaces an tabs from response strTrim := strings.Trim(name, key+": \t \n") strTrim2 := strings.TrimLeft(strTrim, "\t \n") return strTrim2 } // CalculateGrade : calculate current grade func CalculateGrade(currentGrade string) string { previousGrade := 0 finalGrade := "" // check if grade is set if len(currentGrade) > 0 { // convert current grade to ascii equivalent sslGrade := int([]rune(currentGrade)[0]) // calculate value for grade ej: if grade A+ = 65 - 43 if len(currentGrade) > 1 { for i := 1; i < len(currentGrade); i++ { sslGrade -= int([]rune(currentGrade)[i]) } if sslGrade > previousGrade { previousGrade = sslGrade finalGrade = currentGrade } } else { if sslGrade > previousGrade { previousGrade = sslGrade finalGrade = currentGrade } } } return finalGrade } // setDomainState : set the domain state func setDomainState(db *sql.DB, domain string) error { // if the system can't get any information from ssl server for a domain // then the domain is updated to unreachable (is_down = true) previousData, err := models.CheckIfDomainExists(db, domain) if err != nil { return err } if !reflect.DeepEqual(models.Domain{}, previousData) { previousData.Data.IsDown = true previousData.Data.ServerChanged = true _, err := models.UpdateDomain(db, previousData.ID, previousData.Data) if err != nil { return err } } return nil } // ConsultDomain : handler for get all the information required for an user domain request func ConsultDomain(db *sql.DB) fasthttp.RequestHandler { return func(ctx *fasthttp.RequestCtx) { var response models.Response var badRequest models.BadRequest var sendResponse = true strTrim := string(ctx.FormValue("domain")) // get domain from request domain := url.QueryEscape(strTrim) // get the info of domain from ssllabs url := "https://api.ssllabs.com/api/v3/analyze?host=" + domain resp, err := http.Get(url) if err != nil { // if domain is unrecheable, set is_down = true err = setDomainState(db, domain) if err != nil { ctx.SetStatusCode(500) log.Println(err) badRequest.Response = "Theres not info available for this domain" } sendResponse = false log.Println(err) ctx.SetStatusCode(500) badRequest.Response = "The domain can't be consulted" } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { var sslResponse models.Endpoints err := json.NewDecoder(resp.Body).Decode(&sslResponse) if err != nil { sendResponse = false log.Println(err) ctx.SetStatusCode(500) badRequest.Response = "The domain can't be consulted" } if len(sslResponse.Endpoints) > 0 { finalGrade := "" for i := 0; i < len(sslResponse.Endpoints); i++ { // get the owner data var owner = GetOwnerData(sslResponse.Endpoints[i].Address, "OrgName") var country = GetOwnerData(sslResponse.Endpoints[i].Address, "Country") sslResponse.Endpoints[i].Owner = owner sslResponse.Endpoints[i].Country = country currentGrade := sslResponse.Endpoints[i].Grade // calculate the biggest grade finalGrade = CalculateGrade(currentGrade) } var pageInfo, err = GetPageInfo(domain) if err != nil { // if domain is unrecheable, set is_down = true err = setDomainState(db, domain) if err != nil { ctx.SetStatusCode(500) log.Println(err) badRequest.Response = "Theres not info available for this domain" } sendResponse = false log.Println(err) ctx.SetStatusCode(500) badRequest.Response = "The domain information can't be consulted" } else { response.Servers = sslResponse.Endpoints response.SslGrade = finalGrade response.Logo = pageInfo.Icon response.Title = pageInfo.Title response.IsDown = false // check if domain exists. then deside if create or update the info in database previousData, err := models.CheckIfDomainExists(db, domain) switch { case reflect.DeepEqual(models.Domain{}, previousData): response.ServerChanged = false response.PreviousSslGrade = finalGrade _, err := models.CreateDomain(db, domain, response) if err != nil { sendResponse = false log.Println(err) ctx.SetStatusCode(500) badRequest.Response = "The domain can't be created" } case err != nil: sendResponse = false log.Println(err) ctx.SetStatusCode(500) badRequest.Response = "The database can't be reached" default: response.ServerChanged = previousData.Data.ServerChanged response.PreviousSslGrade = previousData.Data.SslGrade if reflect.DeepEqual(previousData.Data, response) { response.ServerChanged = false _, err := models.UpdateDomain(db, previousData.ID, response) if err != nil { sendResponse = false log.Println(err) ctx.SetStatusCode(500) badRequest.Response = "The domain can't be updated" } } else { response.ServerChanged = true response.PreviousSslGrade = previousData.Data.SslGrade _, err := models.UpdateDomain(db, previousData.ID, response) if err != nil { sendResponse = false log.Println(err) ctx.SetStatusCode(500) badRequest.Response = "The domain can't be updated" } } } } } else { // if domain is unrecheable, set is_down = true err = setDomainState(db, domain) if err != nil { ctx.SetStatusCode(500) log.Println(err) badRequest.Response = "Theres not info available for this domain" } sendResponse = false ctx.SetStatusCode(500) log.Println("There's not info available for this domain") badRequest.Response = "Theres not info available for this domain" } } else { sendResponse = false log.Println("The ssl database can't be reached") ctx.SetStatusCode(500) badRequest.Response = "The ssl database can't be reached" } if sendResponse { if err := json.NewEncoder(ctx).Encode(response); err != nil { log.Println(err) } } else { if err := json.NewEncoder(ctx).Encode(badRequest); err != nil { log.Println(err) } } } }
package crypto const ( SignRLen = 28 SignSLen = 28 PublicKeyLen = 230 )
package filter import ( "exodus/graphicsmagick" ) // HashFile generates hash from image by filename // returns emtpy hash, and error on error // returns hash and nil on success func HashFile(fname string) (h Hash, err error) { var img *graphicsmagick.Image img, err = graphicsmagick.LoadImage(fname) if err == nil { err = img.Resize(HashRows, HashCols) if err == nil { //err = img.Quant(HashDepth) //if err == nil { data := img.Raster() // TODO: bounds check copy(h[:], data) //} } img.Close() } return }
package collections import ( "bytes" "errors" "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/balance" "github.com/iotaledger/wasp/packages/kv" "github.com/iotaledger/wasp/packages/util" ) // Map represents a dynamic key-value collection in a kv.KVStore. type Map struct { *ImmutableMap kvw kv.KVStoreWriter } // ImmutableMap provides read-only access to a Map in a kv.KVStoreReader. type ImmutableMap struct { kvr kv.KVStoreReader name string } const ( mapSizeKeyCode = byte(0) mapElemKeyCode = byte(1) ) func NewMap(kv kv.KVStore, name string) *Map { return &Map{ ImmutableMap: NewMapReadOnly(kv, name), kvw: kv, } } func NewMapReadOnly(kv kv.KVStoreReader, name string) *ImmutableMap { return &ImmutableMap{ kvr: kv, name: name, } } func (m *Map) Immutable() *ImmutableMap { return m.ImmutableMap } func (m *ImmutableMap) Name() string { return m.name } func (m *ImmutableMap) getSizeKey() kv.Key { var buf bytes.Buffer buf.Write([]byte(m.name)) buf.WriteByte(mapSizeKeyCode) return kv.Key(buf.Bytes()) } func (m *ImmutableMap) getElemKey(key []byte) kv.Key { var buf bytes.Buffer buf.Write([]byte(m.name)) buf.WriteByte(mapElemKeyCode) buf.Write(key) return kv.Key(buf.Bytes()) } func (m *Map) addToSize(amount int) error { n, err := m.Len() if err != nil { return err } n = uint32(int(n) + amount) if n == 0 { m.kvw.Del(m.getSizeKey()) } else { m.kvw.Set(m.getSizeKey(), util.Uint32To4Bytes(n)) } return nil } func (m *ImmutableMap) GetAt(key []byte) ([]byte, error) { ret, err := m.kvr.Get(m.getElemKey(key)) if err != nil { return nil, err } return ret, nil } func (m *ImmutableMap) MustGetAt(key []byte) []byte { ret, err := m.GetAt(key) if err != nil { panic(err) } return ret } func (m *Map) SetAt(key []byte, value []byte) error { ok, err := m.HasAt(key) if err != nil { return err } if !ok { err = m.addToSize(1) if err != nil { return err } } m.kvw.Set(m.getElemKey(key), value) return nil } func (m *Map) MustSetAt(key []byte, value []byte) { err := m.SetAt(key, value) if err != nil { panic(err) } } func (m *Map) DelAt(key []byte) error { ok, err := m.HasAt(key) if err != nil { return err } if ok { err = m.addToSize(-1) if err != nil { return err } } m.kvw.Del(m.getElemKey(key)) return nil } func (m *Map) MustDelAt(key []byte) { err := m.DelAt(key) if err != nil { panic(err) } } func (m *ImmutableMap) HasAt(key []byte) (bool, error) { return m.kvr.Has(m.getElemKey(key)) } func (m *ImmutableMap) MustHasAt(key []byte) bool { ret, err := m.HasAt(key) if err != nil { panic(err) } return ret } func (m *ImmutableMap) MustLen() uint32 { n, err := m.Len() if err != nil { panic(err) } return n } func (m *ImmutableMap) Len() (uint32, error) { v, err := m.kvr.Get(m.getSizeKey()) if err != nil { return 0, err } if v == nil { return 0, nil } if len(v) != 4 { return 0, errors.New("corrupted data") } return util.MustUint32From4Bytes(v), nil } func (m *Map) Erase() { // TODO needs DelPrefix method in KVStore panic("implement me") } // Iterate non-deterministic func (m *ImmutableMap) Iterate(f func(elemKey []byte, value []byte) bool) error { prefix := m.getElemKey(nil) return m.kvr.Iterate(prefix, func(key kv.Key, value []byte) bool { return f([]byte(key)[len(prefix):], value) //return f([]byte(key), value) }) } // Iterate non-deterministic func (m *ImmutableMap) IterateKeys(f func(elemKey []byte) bool) error { prefix := m.getElemKey(nil) return m.kvr.IterateKeys(prefix, func(key kv.Key) bool { return f([]byte(key)[len(prefix):]) }) } // Iterate non-deterministic func (m *ImmutableMap) MustIterate(f func(elemKey []byte, value []byte) bool) { err := m.Iterate(f) if err != nil { panic(err) } } // Iterate non-deterministic func (m *ImmutableMap) MustIterateKeys(f func(elemKey []byte) bool) { err := m.IterateKeys(f) if err != nil { panic(err) } } func (m *ImmutableMap) IterateBalances(f func(color balance.Color, bal int64) bool) error { var err error m.MustIterate(func(elemKey []byte, value []byte) bool { col, _, err := balance.ColorFromBytes(elemKey) if err != nil { return false } v, err := util.Uint64From8Bytes(value) if err != nil { return false } bal := int64(v) return f(col, bal) }) return err }
package services import "github.com/gogo/protobuf/types" //MapToFieldMask returns updated fields masks. func MapToFieldMask(request map[string]interface{}) types.FieldMask { mask := types.FieldMask{} mask.Paths = keys(request, "") return mask } func keys(m map[string]interface{}, prefix string) []string { result := []string{} for key, value := range m { switch v := value.(type) { case map[string]interface{}: if prefix != "" { result = append(result, keys(v, prefix+key+".")...) } else { result = append(result, keys(v, key+".")...) } default: result = append(result, prefix+key) } } return result }
package zstring type ZChar uint8 // it's really 5 bits, but we can only go as low as 8 natively. type Alphabets []string type Alphabet int const ( A0 Alphabet = 0 A1 Alphabet = 1 A2 Alphabet = 2 A2v1 Alphabet = 3 ) type ZSCIIChar uint16 const ( ZSCIITab ZSCIIChar = 9 ZSCIISentenceSpace ZSCIIChar = 11 ZSCIINewline ZSCIIChar = 13 ) // Alphabets begin at index 6. // The final DefaultAlphabets is the A2 variation used by V1 of the Z-machine. var DefaultAlphabets = Alphabets{ "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", " \n0123456789.,!?_#'\"/\\-:()", " 0123456789.,!?_#'\"/\\<-:()", } var UnicodeChars = []ZSCIIChar{ 0x00e4, 0x00f6, 0x00fc, 0x00c4, 0x00d6, 0x00dc, 0x00df, 0x00bb, 0x00ab, 0x00eb, 0x00ef, 0x00ff, 0x00cb, 0x00cf, 0x00e1, 0x00e9, 0x00ed, 0x00f3, 0x00fa, 0x00fd, 0x00c1, 0x00c9, 0x00cd, 0x00d3, 0x00da, 0x00dd, 0x00e0, 0x00e8, 0x00ec, 0x00f2, 0x00f9, 0x00c0, 0x00c8, 0x00cc, 0x00d2, 0x00d9, 0x00e2, 0x00ea, 0x00ee, 0x00f4, 0x00fb, 0x00c2, 0x00ca, 0x00ce, 0x00d4, 0x00db, 0x00e5, 0x00c5, 0x00f8, 0x00d8, 0x00e3, 0x00f1, 0x00f5, 0x00c3, 0x00d1, 0x00d5, 0x00e6, 0x00c6, 0x00e7, 0x00c7, 0x00fe, 0x00f0, 0x00de, 0x00d0, 0x00a3, 0x0153, 0x0152, 0x00a1, 0x00bf, } func transitionsTable() map[Alphabet]map[ZChar]Alphabet { // from A0 from A1 from A2 // Z-char 2 A1 A2 A0 // next char only // Z-char 3 A2 A0 A1 // next char only // Z-char 4 A1 A2 A0 // permanent (<v3) next char only (v3+) // Z-char 5 A2 A0 A1 // permanent (<v3) next char only (v3+) var transitions = map[Alphabet]map[ZChar]Alphabet{} transitions[A0] = make(map[ZChar]Alphabet) transitions[A1] = make(map[ZChar]Alphabet) transitions[A2] = make(map[ZChar]Alphabet) transitions[A0][2] = A1 transitions[A0][3] = A2 transitions[A0][4] = A1 transitions[A0][5] = A2 transitions[A1][2] = A2 transitions[A1][3] = A0 transitions[A1][4] = A2 transitions[A1][5] = A0 transitions[A2][2] = A0 transitions[A2][3] = A1 transitions[A2][4] = A0 transitions[A2][5] = A1 return transitions } var transitions = transitionsTable() func Transition(currAlphabet Alphabet, char ZChar, version int) (newAlphabet Alphabet, lock bool) { newAlphabet = transitions[currAlphabet][char] return newAlphabet, version < 3 && char > 3 }
//author xinbing //time 2018/9/5 13:54 package utilities import ( "fmt" "testing" ) func TestValidPhone(t *testing.T) { fmt.Println(ValidPhone("17417771777")) } func TestValidEmail(t *testing.T) { fmt.Println(ValidEmail("bin-g.xin@cnlaunch.com-a.cn.bb")) } func TestPwdGrade(t *testing.T) { }
package main import ( "fmt" "github.com/TaigaMikami/go-devto/devto" ) //func main() { // opt := &api.RetrieveFollowersOption{ // Page: 1, // PerPage: 1, // } // // client := api.NewClient("") // res, err := client.RetrieveFollowers(opt) // if err != nil { // panic(err) // } // pp.Print(res) //} //func main() { // opt := &api.RetrieveCommentsOption{ // AId: 270180, // } // // client := api.NewClient("") // res, err := client.RetrieveComments(opt) // if err != nil { // panic(err) // } // pp.Print(res) //} //func main() { // opt := &api.DraftArticle{ // Article: api.ArticleContent{ // Title: "Hello, World!", // Published: false, // BodyMarkdown: "Hello DEV, this is my first post", // Tags: []string{"discuss", "javascript"}, // }, // } // // client := api.NewClient("") // res, err := client.AddArticle(opt) // if err != nil { // panic(err) // } // // pp.Print(res) //} //func main() { // opt := &api.RetrieveUserArticlesOption{ // Page: 1, // PerPage: 2, // } // // client := api.NewClient("BvGbopywQrMEFaiNHsNFLsGZ") // res, _ := client.RetrieveUserAllArticles(opt) // pp.Print(res) //} //func main() { // opt := &api.DraftArticle{ // Article: api.ArticleContent{ // Title: "Hello, World! modify", // Published: false, // BodyMarkdown: "Hello DEV, this is my first post modify", // Tags: []string{"discuss", "javascript"}, // }, // } // // client := api.NewClient("") // res, err := client.ModifyArticle(346946, opt) // if err != nil { // panic(err) // } // // pp.Print(res) //} //func main() { // client := api.NewClient("BvGbopywQrMEFaiNHsNFLsGZ") // res, err := client.RetrieveAuthenticatedUser() // if err != nil { // panic(err) // } // // pp.Print(res) //} func main() { opt := &devto.RetrieveArticlesOption{ Page: 1, PerPage: 10, } client := devto.NewClient("") res, err := client.RetrieveArticles(opt) if err != nil { panic(err) } fmt.Println(res[0].Title) }
// The flow package is a framework for Flow-based programming in Go. package flow import ( "fmt" "github.com/Synthace/internal/code.google.com/p/go.net/websocket" "reflect" "sync" ) const ( // ComponentModeUndefined stands for a fallback component mode (Async). ComponentModeUndefined = iota // ComponentModeAsync stands for asynchronous functioning mode. ComponentModeAsync // ComponentModeSync stands for synchronous functioning mode. ComponentModeSync // ComponentModePool stands for async functioning with a fixed pool. ComponentModePool ) // DefaultComponentMode is the preselected functioning mode of all components being run. var DefaultComponentMode = ComponentModeAsync // Component is a generic flow component that has to be contained in concrete components. // It stores network-specific information. type Component struct { // Is running flag indicates that the process is currently running. IsRunning bool // Net is a pointer to network to inform it when the process is started and over // or to change its structure at run time. Net *Graph // Mode is component's functioning mode. Mode int8 // PoolSize is used to define pool size when using ComponentModePool. PoolSize uint8 // Term chan is used to terminate the process immediately without closing // any channels. Term chan struct{} } // Initalizable is the interface implemented by components/graphs with custom initialization code. type Initializable interface { Init() } // Finalizable is the interface implemented by components/graphs with extra finalization code. type Finalizable interface { Finish() } // Shutdowner is the interface implemented by components overriding default Shutdown() behavior. type Shutdowner interface { Shutdown() } // postHandler is used to bind handlers to a port type portHandler struct { onRecv reflect.Value onClose reflect.Value } // inputCounter keeps track of total additions and decrements have occured // on inputsClose var inputCounter = 0 // RunProc runs event handling loop on component ports. // It returns true on success or panics with error message and returns false on error. func RunProc(c interface{}) bool { // Check if passed interface is a valid pointer to struct v := reflect.ValueOf(c) if v.Kind() != reflect.Ptr || v.IsNil() { panic("Argument of flow.Run() is not a valid pointer") return false } vp := v v = v.Elem() if v.Kind() != reflect.Struct { panic("Argument of flow.Run() is not a valid pointer to structure. Got type: " + vp.Type().Name()) return false } t := v.Type() // Get internal state lock if available hasLock := false var locker sync.Locker if lockField := v.FieldByName("StateLock"); lockField.IsValid() && lockField.Elem().IsValid() { locker, hasLock = lockField.Interface().(sync.Locker) } // Call user init function if exists if initable, ok := c.(Initializable); ok { initable.Init() } // A group to wait for all inputs to be closed inputsClose := new(sync.WaitGroup) // A group to wait for all recv handlers to finish handlersDone := new(sync.WaitGroup) // Get the embedded flow.Component vCom := v.FieldByName("Component") isComponent := vCom.IsValid() && vCom.Type().Name() == "Component" if !isComponent { panic("Argument of flow.Run() is not a flow.Component") } // Get the component mode componentMode := DefaultComponentMode var poolSize uint8 = 0 if vComMode := vCom.FieldByName("Mode"); vComMode.IsValid() { componentMode = int(vComMode.Int()) } if vComPoolSize := vCom.FieldByName("PoolSize"); vComPoolSize.IsValid() { poolSize = uint8(vComPoolSize.Uint()) } // Create a slice of select cases and port handlers cases := make([]reflect.SelectCase, 0, t.NumField()) handlers := make([]portHandler, 0, t.NumField()) // Make and listen on termination channel vCom.FieldByName("Term").Set(reflect.MakeChan(vCom.FieldByName("Term").Type(), 0)) cases = append(cases, reflect.SelectCase{Dir: reflect.SelectRecv, Chan: vCom.FieldByName("Term")}) handlers = append(handlers, portHandler{}) // Iterate over struct fields and bind handlers inputCount := 0 for i := 0; i < t.NumField(); i++ { fv := v.Field(i) ff := t.Field(i) ft := fv.Type() // Detect control channels if fv.IsValid() && fv.Kind() == reflect.Chan && !fv.IsNil() && (ft.ChanDir()&reflect.RecvDir) != 0 { // Bind handlers for an input channel cases = append(cases, reflect.SelectCase{Dir: reflect.SelectRecv, Chan: fv}) h := portHandler{onRecv: vp.MethodByName("On" + ff.Name), onClose: vp.MethodByName("On" + ff.Name + "Close")} handlers = append(handlers, h) if h.onClose.IsValid() || h.onRecv.IsValid() { // Add the input to the wait group inputsClose.Add(1) inputCount++ inputCounter++ } } } if inputCount == 0 { panic("Components with no input ports are not supported") } // Prepare handler closures recvHandler := func(onRecv, value reflect.Value) { if hasLock { locker.Lock() } valArr := [1]reflect.Value{value} onRecv.Call(valArr[:]) if hasLock { locker.Unlock() } handlersDone.Done() } closeHandler := func(onClose reflect.Value) { if onClose.IsValid() { // Lock the state and call OnClose handler if hasLock { locker.Lock() } onClose.Call([]reflect.Value{}) if hasLock { locker.Unlock() } } inputsClose.Done() } terminate := func() { if !vCom.FieldByName("IsRunning").Bool() { return } vCom.FieldByName("IsRunning").SetBool(false) for i := 0; i < inputCount; i++ { inputsClose.Done() } } // closePorts closes all output channels of a process. closePorts := func() { // Iterate over struct fields for i := 0; i < t.NumField(); i++ { fv := v.Field(i) ft := fv.Type() vNet := vCom.FieldByName("Net") // Detect and close send-only channels if fv.IsValid() { if fv.Kind() == reflect.Chan && (ft.ChanDir()&reflect.SendDir) != 0 && (ft.ChanDir()&reflect.RecvDir) == 0 { if vNet.IsValid() && !vNet.IsNil() { if vNet.Interface().(*Graph).DecSendChanRefCount(fv) { fv.Close() } } else { fv.Close() } } else if fv.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Chan { ll := fv.Len() if vNet.IsValid() && !vNet.IsNil() { for i := 0; i < ll; i += 1 { if vNet.Interface().(*Graph).DecSendChanRefCount(fv.Index(i)) { fv.Index(i).Close() } } } else { for i := 0; i < ll; i += 1 { fv.Index(i).Close() } } } } } } // shutdown represents a standard process shutdown procedure. shutdown := func() { if s, ok := c.(Shutdowner); ok { // Custom shutdown behavior s.Shutdown() } else { // Call user finish function if exists if finable, ok := c.(Finalizable); ok { finable.Finish() } // Close all output ports if the process is still running if vCom.FieldByName("IsRunning").Bool() { closePorts() } } } // Run the port handlers depending on component mode if componentMode == ComponentModePool && poolSize > 0 { // Pool mode, prefork limited goroutine pool for all inputs var poolIndex uint8 poolWait := new(sync.WaitGroup) once := new(sync.Once) for poolIndex = 0; poolIndex < poolSize; poolIndex++ { poolWait.Add(1) go func() { for { chosen, recv, recvOK := reflect.Select(cases) if !recvOK { poolWait.Done() if chosen == 0 { // Term signal terminate() } else { // Port has been closed once.Do(func() { // Wait for other workers poolWait.Wait() // Close output down closeHandler(handlers[chosen].onClose) }) } return // TODO: Debug how to ensure enough shutdowns for inputs // in the pool mode case. for now, pool mode won't work properly } if handlers[chosen].onRecv.IsValid() { handlersDone.Add(1) recvHandler(handlers[chosen].onRecv, recv) } } }() } } else { for i := 0; i < inputCount; i++ { go func() { for { chosen, recv, recvOK := reflect.Select(cases) if !recvOK { if chosen == 0 { // Term signal terminate() } else { // Port has been closed closeHandler(handlers[chosen].onClose) } return } if handlers[chosen].onRecv.IsValid() { handlersDone.Add(1) if componentMode == ComponentModeAsync || componentMode == ComponentModeUndefined && DefaultComponentMode == ComponentModeAsync { // Async mode go recvHandler(handlers[chosen].onRecv, recv) } else { // Sync mode recvHandler(handlers[chosen].onRecv, recv) } } } }() } } // Indicate the process as running vCom.FieldByName("IsRunning").SetBool(true) go func() { // Wait for all inputs to be closed inputsClose.Wait() // Wait all inport handlers to finish their job handlersDone.Wait() // Call shutdown handler (user or default) shutdown() // Get the embedded flow.Component and check if it belongs to a network if vNet := vCom.FieldByName("Net"); vNet.IsValid() && !vNet.IsNil() { if vNetCtr, hasNet := vNet.Interface().(netController); hasNet { // Remove the instance from the network's WaitGroup vNetCtr.getWait().Done() } } }() return true } // StopProc terminates the process if it is running. // It doesn't close any in or out ports of the process, so it can be // replaced without side effects. func StopProc(c interface{}) bool { // Check if passed interface is a valid pointer to struct v := reflect.ValueOf(c) if v.Kind() != reflect.Ptr || v.IsNil() { panic("Argument of TermProc() is not a valid pointer") return false } vp := v v = v.Elem() if v.Kind() != reflect.Struct { panic("Argument of TermProc() is not a valid pointer to structure. Got type: " + vp.Type().Name()) return false } // Get the embedded flow.Component vCom := v.FieldByName("Component") isComponent := vCom.IsValid() && vCom.Type().Name() == "Component" if !isComponent { panic("Argument of TermProc() is not a flow.Component") } // Send the termination signal vCom.FieldByName("Term").Close() return true } type components struct { Component []componentInfo `json:""` } /* type componentInfo struct { Name string `json:"name"` Description string `json:"description"` Icon string `json:"icon"` Subgraph string `json:"subgraph"` Inports []portz `json:"inPorts"` Outports []portz `json:"outPorts"` }*/ /* type portz struct { Id string `json:"id"` Type string `json:"type"` Description string `json:"description"` Addressable string `json:"addressable"` Required string `json:"required"` Values interface{} `json:"values"` Default string `json:"default"` }*/ func (r *Runtime) componentList(ws *websocket.Conn, payload interface{}) { fmt.Println("handle component.list") websocket.JSON.Send(ws, wsSend{"component", "component", componentInfo{"Greeter", "Manually Entered Greeter Element for Like, Y'know, Testing or Whatever", "", false, []portInfo{{"Name", "string", "", false, false, nil, ""}, {"Title", "string", "", false, false, nil, ""}, }, []portInfo{{"Res", "string", "", false, false, nil, ""}, }, }}) websocket.JSON.Send(ws, wsSend{"component", "component", componentInfo{"Printer", "Manually Entered Printer Element", "", false, []portInfo{{"Line", "string", "", false, false, nil, ""}, }, []portInfo{{"", "", "", false, false, nil, ""}, }, }}) }
package jsonschema_test import ( "bytes" "context" "fmt" "reflect" "testing" "github.com/ory/jsonschema/v3" ) func TestErrorsContext(t *testing.T) { for k, tc := range []struct { path string doc string expected interface{} }{ { path: "testdata/errors/required.json#/0", doc: `{}`, expected: &jsonschema.ValidationErrorContextRequired{Missing: []string{"#/bar"}}, }, { path: "testdata/errors/required.json#/0", doc: `{"bar":{}}`, expected: &jsonschema.ValidationErrorContextRequired{ Missing: []string{"#/bar/foo"}, }, }, { path: "testdata/errors/required.json#/1", doc: `{"object":{"object":{"foo":"foo"}}}`, expected: &jsonschema.ValidationErrorContextRequired{ Missing: []string{"#/object/object/bar"}, }, }, { path: "testdata/errors/required.json#/1", doc: `{"object":{"object":{"bar":"bar"}}}`, expected: &jsonschema.ValidationErrorContextRequired{ Missing: []string{"#/object/object/foo"}, }, }, { path: "testdata/errors/required.json#/1", doc: `{"object":{"object":{}}}`, expected: &jsonschema.ValidationErrorContextRequired{ Missing: []string{"#/object/object/foo", "#/object/object/bar"}, }, }, { path: "testdata/errors/required.json#/1", doc: `{"object":{}}`, expected: &jsonschema.ValidationErrorContextRequired{ Missing: []string{"#/object/object"}, }, }, { path: "testdata/errors/required.json#/1", doc: `{}`, expected: &jsonschema.ValidationErrorContextRequired{ Missing: []string{"#/object"}, }, }, } { t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) { ctx := context.Background() var ( schema = jsonschema.MustCompile(ctx, tc.path) err = schema.Validate(bytes.NewBufferString(tc.doc)) ) if err == nil { t.Errorf("Expected error but got nil") return } var ( actual = err.(*jsonschema.ValidationError).Context ) if !reflect.DeepEqual(tc.expected, actual) { t.Errorf("expected:\t%#v\n\tactual:\t%#v", tc.expected, actual) } }) } }
package bimap import ( "log" "sync" "testing" ) type BiMap64To16 struct { key uint64 value uint16 } var ( k1 uint64 = 10000 v1 uint16 = 10001 k2 uint64 = 20000 v2 uint16 = 20001 k3 uint16 = 30000 v3 uint64 = 30001 k4 uint16 = 40000 v4 uint64 = 40001 ) var biMap = New() func init() { err := biMap.Put(k1, v1) if err != nil { log.Fatalln(err) } err = biMap.Put(k2, v2) if err != nil { log.Fatalln(err) } err = biMap.Put(k3, v3) if err != nil { log.Fatalln(err) } err = biMap.Put(k4, v4) if err != nil { log.Fatalln(err) } } func TestBiMap(t *testing.T) { wg := new(sync.WaitGroup) wg.Add(4) go func() { defer wg.Done() if v_1, ok := biMap.Get(k1); !ok { t.Errorf("k: %d\n", k1) } else { log.Printf("k: %d -> v: %d\n", k1, v_1) } if k_1, ok := biMap.Get(v1); !ok { t.Errorf("v: %d\n", v1) } else { log.Printf("v: %d -> k: %d\n", v1, k_1) } }() go func() { defer wg.Done() if v_2, ok := biMap.Get(k2); !ok { t.Errorf("k: %d\n", k2) } else { log.Printf("k: %d -> v: %d\n", k2, v_2) } if k_2, ok := biMap.Get(v2); !ok { t.Errorf("v: %d\n", v2) } else { log.Printf("v: %d -> k: %d\n", v2, k_2) } }() go func() { defer wg.Done() if v_3, ok := biMap.Get(k3); !ok { t.Errorf("k: %d\n", k3) } else { log.Printf("k: %d -> v: %d\n", k3, v_3) } if k_3, ok := biMap.Get(v3); !ok { t.Errorf("v: %d\n", v3) } else { log.Printf("v: %d -> k: %d\n", v3, k_3) } }() go func() { defer wg.Done() if v_4, ok := biMap.Get(k4); !ok { t.Errorf("k: %d\n", k4) } else { log.Printf("k: %d -> v: %d\n", k4, v_4) } if k_4, ok := biMap.Get(v4); !ok { t.Errorf("v: %d\n", v4) } else { log.Printf("v: %d -> k: %d\n", v4, k_4) } }() wg.Wait() } func TestBiMap_Del(t *testing.T) { if v_1, ok := biMap.Get(k1); ok { log.Println("get v1:", v_1) } else { t.Error("should get v1") } biMap.Del(k1) if v_1, ok := biMap.Get(k1); ok { t.Error("should not get v1:", v_1) } if k_1, ok := biMap.Get(v1); ok { t.Error("should not get k1:", k_1) } }
package storage import ( "errors" ) var ( // ErrNoAuthenticationLogs error thrown when no matching authentication logs hve been found in DB. ErrNoAuthenticationLogs = errors.New("no matching authentication logs found") // ErrNoTOTPConfiguration error thrown when no TOTP configuration has been found in DB. ErrNoTOTPConfiguration = errors.New("no TOTP configuration for user") // ErrNoWebAuthnDevice error thrown when no WebAuthn device handle has been found in DB. ErrNoWebAuthnDevice = errors.New("no WebAuthn device found") // ErrNoDuoDevice error thrown when no Duo device and method has been found in DB. ErrNoDuoDevice = errors.New("no Duo device and method saved") // ErrNoAvailableMigrations is returned when no available migrations can be found. ErrNoAvailableMigrations = errors.New("no available migrations") // ErrMigrateCurrentVersionSameAsTarget is returned when the target version is the same as the current. ErrMigrateCurrentVersionSameAsTarget = errors.New("current version is same as migration target, no action being taken") // ErrSchemaAlreadyUpToDate is returned when the schema is already up to date. ErrSchemaAlreadyUpToDate = errors.New("schema already up to date") // ErrNoMigrationsFound is returned when no migrations were found. ErrNoMigrationsFound = errors.New("no schema migrations found") // ErrSchemaEncryptionVersionUnsupported is returned when the schema is checked if the encryption key is valid for // the database but the schema doesn't support encryption. ErrSchemaEncryptionVersionUnsupported = errors.New("schema version doesn't support encryption") // ErrSchemaEncryptionInvalidKey is returned when the schema is checked if the encryption key is valid for // the database but the key doesn't appear to be valid. ErrSchemaEncryptionInvalidKey = errors.New("the configured encryption key does not appear to be valid for this database which may occur if the encryption key was changed in the configuration without using the cli to change it in the database") ) // Error formats for the storage provider. const ( ErrFmtMigrateUpTargetLessThanCurrent = "schema up migration target version %d is less then the current version %d" ErrFmtMigrateUpTargetGreaterThanLatest = "schema up migration target version %d is greater then the latest version %d which indicates it doesn't exist" ErrFmtMigrateDownTargetGreaterThanCurrent = "schema down migration target version %d is greater than the current version %d" ErrFmtMigrateDownTargetLessThanMinimum = "schema down migration target version %d is less than the minimum version" ErrFmtMigrateAlreadyOnTargetVersion = "schema migration target version %d is the same current version %d" ) const ( errFmtFailedMigration = "schema migration %d (%s) failed: %w" errFmtSchemaCurrentGreaterThanLatestKnown = "current schema version is greater than the latest known schema " + "version, you must downgrade to schema version %d before you can use this version of Authelia" ) const ( logFmtMigrationFromTo = "Storage schema migration from %s to %s is being attempted" logFmtMigrationComplete = "Storage schema migration from %s to %s is complete" logFmtErrClosingConn = "Error occurred closing SQL connection: %v" ) const ( errFmtMigrationPre1 = "schema migration %s pre1 is no longer supported: you must use an older version of authelia to perform this migration: %s" errFmtMigrationPre1SuggestedVersion = "the suggested authelia version is 4.37.2" )
// Copyright 2021 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package placement import ( "fmt" "strings" "gopkg.in/yaml.v2" ) // Constraints is a slice of constraints. type Constraints []Constraint // NewConstraints will check each labels, and build the Constraints. func NewConstraints(labels []string) (Constraints, error) { if len(labels) == 0 { return nil, nil } constraints := make(Constraints, 0, len(labels)) for _, str := range labels { label, err := NewConstraint(strings.TrimSpace(str)) if err != nil { return constraints, err } err = constraints.Add(label) if err != nil { return constraints, err } } return constraints, nil } // NewConstraintsFromYaml will transform parse the raw 'array' constraints and call NewConstraints. // Refer to https://github.com/pingcap/tidb/blob/master/docs/design/2020-06-24-placement-rules-in-sql.md. func NewConstraintsFromYaml(c []byte) (Constraints, error) { constraints := []string{} err := yaml.UnmarshalStrict(c, &constraints) if err != nil { return nil, ErrInvalidConstraintsFormat } return NewConstraints(constraints) } // NewConstraintsDirect is a helper for creating new constraints from individual constraint. func NewConstraintsDirect(c ...Constraint) Constraints { return c } // Restore converts label constraints to a string. func (constraints *Constraints) Restore() (string, error) { var sb strings.Builder for i, constraint := range *constraints { if i > 0 { sb.WriteByte(',') } sb.WriteByte('"') conStr, err := constraint.Restore() if err != nil { return "", err } sb.WriteString(conStr) sb.WriteByte('"') } return sb.String(), nil } // Add will add a new label constraint, with validation of all constraints. // Note that Add does not validate one single constraint. func (constraints *Constraints) Add(label Constraint) error { pass := true for i := range *constraints { cnst := (*constraints)[i] res := label.CompatibleWith(&cnst) if res == ConstraintCompatible { continue } if res == ConstraintDuplicated { pass = false continue } s1, err := label.Restore() if err != nil { s1 = err.Error() } s2, err := cnst.Restore() if err != nil { s2 = err.Error() } return fmt.Errorf("%w: '%s' and '%s'", ErrConflictingConstraints, s1, s2) } if pass { *constraints = append(*constraints, label) } return nil }
package main import "fmt" import "rsc.io/quote" import "example.com/greetings" func main() { fmt.Println(quote.Go()) messages, err := greetings.Hellos([]string{"Test", "", "Stuff"}) if err != nil { fmt.Println("error", err) } for _, message := range messages { fmt.Println(message) } }
package bus import ( "fmt" "testing" "time" "github.com/tmtx/erp/pkg/validator" ) type testErrorHandler struct { err error messages validator.Messages } func (eh *testErrorHandler) Handle(err error, messages validator.Messages) { eh.err = err eh.messages = messages } // TestErrorHandle tests if error is handled func TestErrorHandle(t *testing.T) { var testErrorHandleMessageKey MessageKey = "test_error_handle_message_key" expectedErrorMessage := "1234" v := validator.StringNonEmpty{ Value: "", } vg := validator.Group{ "test": []validator.Validator{v}, } eh := testErrorHandler{} messageBus := NewBasicMessageBus(&eh) messageBus.Subscribe( testErrorHandleMessageKey, func(p MessageParams) (validator.Messages, error) { isValid, messages := validator.ValidateGroup(vg) if isValid { t.Errorf("Expected validation to fail") } return messages, fmt.Errorf(expectedErrorMessage) }, ) messageBus.Listen() messageBus.Dispatch(Message{testErrorHandleMessageKey, MessageParams{}, CommandMessage}) time.Sleep(time.Millisecond * 5) if eh.err.Error() != expectedErrorMessage { t.Errorf("Expected: '%s', got: '%s'", expectedErrorMessage, eh.err.Error()) } } // TestDispatch tests if multiple dispatch calls work properly func TestDispatch(t *testing.T) { var testDispatchMessageKey MessageKey = "test_trigger_message_key" expectedResult := 5 result := 0 messageBus := NewBasicMessageBus(&testErrorHandler{}) messageBus.Subscribe( testDispatchMessageKey, func(p MessageParams) (validator.Messages, error) { result++ return nil, nil }, ) messageBus.Listen() m := Message{testDispatchMessageKey, MessageParams{}, CommandMessage} messageBus.Dispatch(m) messageBus.Dispatch(m) messageBus.Dispatch(m) messageBus.Dispatch(m) messageBus.Dispatch(m) time.Sleep(time.Millisecond * 5) if result != expectedResult { t.Errorf("Expected: '%d', got: '%d'", expectedResult, result) } }
package shortest_path import "testing" func TestGraph_Dijkstra(t *testing.T) { graph := NewGraph(6) AddEdge(0, 1, 10) AddEdge(0, 4, 17) AddEdge(1, 2, 20) AddEdge(2, 3, 15) AddEdge(2, 4, 25) AddEdge(4, 5, 6) Dijkstra(0, 3) }
package provider import ( "fmt" "strings" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mrparkers/terraform-provider-keycloak/keycloak" ) func resourceKeycloakAuthenticationExecutionConfig() *schema.Resource { return &schema.Resource{ Create: resourceKeycloakAuthenticationExecutionConfigCreate, Read: resourceKeycloakAuthenticationExecutionConfigRead, Delete: resourceKeycloakAuthenticationExecutionConfigDelete, Update: resourceKeycloakAuthenticationExecutionConfigUpdate, Importer: &schema.ResourceImporter{ State: resourceKeycloakAuthenticationExecutionConfigImport, }, Schema: map[string]*schema.Schema{ "realm_id": { Type: schema.TypeString, Required: true, ForceNew: true, }, "execution_id": { Type: schema.TypeString, Required: true, ForceNew: true, }, "alias": { Type: schema.TypeString, Required: true, ForceNew: true, }, "config": { Type: schema.TypeMap, Elem: &schema.Schema{Type: schema.TypeString}, Required: true, }, }, } } func getAuthenticationExecutionConfigFromData(data *schema.ResourceData) *keycloak.AuthenticationExecutionConfig { config := make(map[string]string) for key, value := range data.Get("config").(map[string]interface{}) { config[key] = value.(string) } return &keycloak.AuthenticationExecutionConfig{ Id: data.Id(), RealmId: data.Get("realm_id").(string), ExecutionId: data.Get("execution_id").(string), Alias: data.Get("alias").(string), Config: config, } } func setAuthenticationExecutionConfigData(data *schema.ResourceData, config *keycloak.AuthenticationExecutionConfig) { data.SetId(config.Id) data.Set("realm_id", config.RealmId) data.Set("execution_id", config.ExecutionId) data.Set("alias", config.Alias) data.Set("config", config.Config) } func resourceKeycloakAuthenticationExecutionConfigCreate(data *schema.ResourceData, meta interface{}) error { keycloakClient := meta.(*keycloak.KeycloakClient) config := getAuthenticationExecutionConfigFromData(data) id, err := keycloakClient.NewAuthenticationExecutionConfig(config) if err != nil { return err } data.SetId(id) return resourceKeycloakAuthenticationExecutionConfigRead(data, meta) } func resourceKeycloakAuthenticationExecutionConfigRead(data *schema.ResourceData, meta interface{}) error { keycloakClient := meta.(*keycloak.KeycloakClient) config := &keycloak.AuthenticationExecutionConfig{ RealmId: data.Get("realm_id").(string), ExecutionId: data.Get("execution_id").(string), Id: data.Id(), } err := keycloakClient.GetAuthenticationExecutionConfig(config) if err != nil { return handleNotFoundError(err, data) } setAuthenticationExecutionConfigData(data, config) return nil } func resourceKeycloakAuthenticationExecutionConfigUpdate(data *schema.ResourceData, meta interface{}) error { keycloakClient := meta.(*keycloak.KeycloakClient) config := getAuthenticationExecutionConfigFromData(data) err := keycloakClient.UpdateAuthenticationExecutionConfig(config) if err != nil { return err } return resourceKeycloakAuthenticationExecutionConfigRead(data, meta) } func resourceKeycloakAuthenticationExecutionConfigDelete(data *schema.ResourceData, meta interface{}) error { keycloakClient := meta.(*keycloak.KeycloakClient) config := &keycloak.AuthenticationExecutionConfig{ RealmId: data.Get("realm_id").(string), Id: data.Id(), } return keycloakClient.DeleteAuthenticationExecutionConfig(config) } func resourceKeycloakAuthenticationExecutionConfigImport(data *schema.ResourceData, _ interface{}) ([]*schema.ResourceData, error) { parts := strings.Split(data.Id(), "/") if len(parts) != 3 || parts[0] == "" || parts[1] == "" || parts[2] == "" { return nil, fmt.Errorf("invalid import. Supported import formats: {{realm}}/{{authenticationExecutionId}}/{{authenticationExecutionConfigId}}") } data.Set("realm_id", parts[0]) data.Set("execution_id", parts[1]) data.SetId(parts[2]) return []*schema.ResourceData{data}, nil }
package twosum2 func solution(target int, nums []int) []int { diffRecords := make(map[int]int) for i, v := range nums { d := target - v if _, ok := diffRecords[d]; ok { return []int{diffRecords[d], i} } diffRecords[v] = i } return nil }
package main import "fmt" func main() { fmt.Println(toLowerCase("AbCdEfG")) } func toLowerCase(str string) string { var result = "" for i := 0; i < len(str); i++ { if int(str[i]) < int('a') && (str[i] <= 'Z' && str[i] >= 'A' || str[i] <= 'z' && str[i] >= 'a') { result += string(int(str[i]) - int('A') + int('a')) } else { result += string(str[i]) } } return result }
package ac import "testing" func compare(a, b []Match) bool { if len(a) != len(b) { return false } for i := 0; i < len(a); i++ { if a[i] != b[i] { return false } } return true } func search(text string, words ...string) []Match { trie := Compile(words) return trie.Search(text) } // Text and indexes // a b x a b c d e f a b // 0 1 2 3 4 5 6 7 8 9 0 func verify(t *testing.T, words []string, expected []Match) { text := "abxabcdefab" res := search(text, words...) if !compare(res, expected) { t.Errorf( "Search(%s, %s) returned %v expected %v", text, words, res, expected, ) } } func TestSearchSinglePosition(t *testing.T) { verify(t, []string{"c"}, []Match{Match{"c", 5, 6}}) } func TestSearchSingleWord(t *testing.T) { verify(t, []string{"abc"}, []Match{Match{"abc", 3, 6}}) } func TestSearchManyWords(t *testing.T) { verify(t, []string{"aac", "ac", "abc", "bca"}, []Match{Match{"abc", 3, 6}}, ) } func TestSearchManyMatches(t *testing.T) { verify(t, []string{"ab"}, []Match{Match{"ab", 0, 2}, Match{"ab", 3, 5}, Match{"ab", 9, 11}}, ) verify(t, []string{"abc", "fab"}, []Match{Match{"abc", 3, 6}, Match{"fab", 8, 11}}, ) verify(t, []string{"ab", "cde"}, []Match{ Match{"ab", 0, 2}, Match{"ab", 3, 5}, Match{"cde", 5, 8}, Match{"ab", 9, 11}}, ) } func TestPrefixWord(t *testing.T) { verify(t, []string{"ab", "abcd"}, []Match{ Match{"ab", 0, 2}, Match{"ab", 3, 5}, Match{"abcd", 3, 7}, Match{"ab", 9, 11}}, ) verify(t, []string{"abcd", "ab"}, []Match{ Match{"ab", 0, 2}, Match{"ab", 3, 5}, Match{"abcd", 3, 7}, Match{"ab", 9, 11}}, ) } func TestPrefixTwice(t *testing.T) { verify(t, []string{"ab", "abc", "abcd"}, []Match{ Match{"ab", 0, 2}, Match{"ab", 3, 5}, Match{"abc", 3, 6}, Match{"abcd", 3, 7}, Match{"ab", 9, 11}}, ) verify(t, []string{"abcd", "abc", "ab"}, []Match{ Match{"ab", 0, 2}, Match{"ab", 3, 5}, Match{"abc", 3, 6}, Match{"abcd", 3, 7}, Match{"ab", 9, 11}}, ) } func TestSuffixWord(t *testing.T) { verify(t, []string{"ab", "b"}, []Match{ Match{"ab", 0, 2}, Match{"b", 1, 2}, Match{"ab", 3, 5}, Match{"b", 4, 5}, Match{"ab", 9, 11}, Match{"b", 10, 11}}, ) verify(t, []string{"abx", "bx"}, []Match{Match{"abx", 0, 3}, Match{"bx", 1, 3}}, ) } func TestSuffixTwice(t *testing.T) { verify(t, []string{"abx", "bx", "x"}, []Match{Match{"abx", 0, 3}, Match{"bx", 1, 3}, Match{"x", 2, 3}}, ) } func TestMoveToSuffix(t *testing.T) { verify(t, []string{"abxb", "bxa"}, []Match{Match{"bxa", 1, 4}}, ) } func TestMoveToSuffixTwice(t *testing.T) { verify(t, []string{"abxb", "bxb", "xa"}, []Match{Match{"xa", 2, 4}}, ) } func TestWikipediaExample(t *testing.T) { // From https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm res := search( "abccab", "a", "ab", "bab", "bc", "bca", "c", "caa") expected := []Match{ Match{"a", 0, 1}, Match{"ab", 0, 2}, Match{"bc", 1, 3}, Match{"c", 2, 3}, Match{"c", 3, 4}, Match{"a", 4, 5}, Match{"ab", 4, 6}, } if !compare(res, expected) { t.Errorf("Got result %v expected %v", res, expected) } }
package main import ( "fmt" "net/http" ) func main() { resp, err := http.Get("http://www.baidu.com") if err != nil { fmt.Printf("err : %v\n", err) } else { fmt.Printf("status %v\n", resp.Status) for { buf := make([]byte, 1024) n, err := resp.Body.Read(buf) if err != nil { fmt.Printf("read err or over: %v\n", err) break } else { fmt.Printf("%v", string(buf[:n])) } } fmt.Printf("\n") } }
package repository import ( "../config" "../utils" "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/firehose" "github.com/aws/aws-sdk-go/service/kinesis" "strconv" "sync" ) const BufferSize = 490 var mu sync.Mutex var hitBuffer = make([]*firehose.Record, 0, BufferSize) //sending the hit data as json string in Kinesis Stream for real time prediction //the data are splitted into shards by using the visitor id partition key. Which means, a same visitor will always be in the same shard. func SendToStream(visitorId uint64, hit []byte) { _, err := utils.AwsKinesis.PutRecord(&kinesis.PutRecordInput{ Data: hit, StreamName: aws.String(config.Config.KinesisStreamName), PartitionKey: aws.String(strconv.FormatUint(visitorId, 10)), }) if err != nil { fmt.Println("kinesis error") panic(err) } } //sending the hit data as json string in Kinesis Stream for real time prediction //this function act as a buffer. The data are sent to Kinsesis Firehose only when the buffer is full. //We do that in order to minimize the number of request across the network, and the performance of the application func SendToFirehose(hit []byte) { mu.Lock() defer mu.Unlock() hitBuffer = append( hitBuffer, &firehose.Record{Data: append(hit, '\n')}, ) //if the buffer if not full we continue to add hits if len(hitBuffer) < BufferSize { return } //else we want to send all the hits we buffered to firehose _, err := utils.AwsFirehose.PutRecordBatch(&firehose.PutRecordBatchInput{ DeliveryStreamName: aws.String(config.Config.FirehoseStreamName), Records: hitBuffer, }, ) if err != nil { fmt.Println("Buffer Size", len(hitBuffer)) panic(err) } fmt.Println("-> sending to firehose") //emptying the slice for the next batch hitBuffer = make([]*firehose.Record, 0, BufferSize) }
package stack import ( "bytes" "errors" "fmt" ) // New a Stack func New() *Stack { return &Stack{} } // Node defines a stack node type Node struct { data interface{} next *Node } // Stack struct type Stack struct { top *Node len int } // Push pushes a value to stack, return full error or nil func (s *Stack) Push(v interface{}) error { s.top = &Node{v, s.top} s.len++ return nil } // Pop popes a value from stack, return value and error func (s *Stack) Pop() (interface{}, error) { if s.top == nil { return nil, errors.New("the stack is empty") } defer func() { s.top = s.top.next; s.len-- }() return s.top.data, nil } // Len return the len func (s *Stack) Len() int { return s.len } func (s *Stack) String() string { var buffer bytes.Buffer buffer.WriteString(fmt.Sprintf("StackBasedLinkedList: length = %d, capacity = ~, ", s.len)) buffer.WriteString("data = [") for n := s.top; n != nil; n = n.next { buffer.WriteString(fmt.Sprint(n.data)) if n.next != nil { buffer.WriteString(",") } } buffer.WriteString(fmt.Sprintf("]")) return buffer.String() }
package 前缀和 // ------------------------- 哈希 + 前缀和 ------------------------- // 执行用时:4 ms, 在所有 Go 提交中击败了 94.44% 的用户 // 内存消耗:3.3 MB, 在所有 Go 提交中击败了 100.00% 的用户 func smallerNumbersThanCurrent(nums []int) []int { countOfNum := getCountOfNum(nums) countOfLessOrEqualNum := getPrefixSum(countOfNum) return getArrayOfCountOfLessNum(nums, countOfLessOrEqualNum) } func getArrayOfCountOfLessNum(nums []int, countOfLessOrEqualNum []int) []int { // 其实可以把结果存在 nums 中,这样能节省一点空间,但也会带来一个问题: nums被修改了。 array := make([]int, len(nums)) for i := 0; i < len(nums); i++ { if nums[i]-1 >= 0 { array[i] = countOfLessOrEqualNum[nums[i]-1] } else { array[i] = 0 } } return array } func getPrefixSum(arr []int) []int { if len(arr) == 0 { return []int{} } prefixSum := make([]int, len(arr)) prefixSum[0] = arr[0] for i := 1; i < len(arr); i++ { prefixSum[i] = prefixSum[i-1] + arr[i] } return prefixSum } func getCountOfNum(nums []int) []int { countOfNum := make([]int, 101) for i := 0; i < len(nums); i++ { countOfNum[nums[i]]++ } return countOfNum }
package committer import ( "fmt" "strings" ) type ( Message string commitType uint8 ) // const that we are using // from unknown to the end, it defines the type of commits // if you want to add another type, please add in alphabetical order for better readability const ( breakingChange commitType = iota // breaking change for our service build // change that build system or external dependencies chore // something else ci // change to our CI configuration files and scripts docs // documentation only changes feat // a new feature fix // a bug fix perf // a code change that improves performance refactor // a code change that neither fixes a bug nor add a feature style // changes that do not affect the meaning of the code (e.g. whitespace) test // adding missing tests or correcting existing tests ) // this String method returns string for each commit type // for example, if the commit type is breakingChange, it returns `BREAKING CHANGE` func (t commitType) String() string { switch t { case breakingChange: return "BREAKING CHANGE" case build: return "build" case chore: return "chore" case ci: return "ci" case docs: return "docs" case feat: return "feat" case fix: return "fix" case perf: return "perf" case refactor: return "refactor" case style: return "style" case test: return "test" default: panic("unexpected error") } } // CheckCommitType check a type of commit out from the commit message func CheckCommitType(m Message) (errMsg string, ok bool) { var b strings.Builder for i, n := 0, len(m); i < n; i++ { c := m[i] // this is attempt to get the type before actual scope or commit message if c == ':' || c == '(' { break } b.WriteByte(c) } // be aware that this switch status use implicit break unlike C // therefore, if the commit message matches the type // it will jump out this switch statement switch b.String() { case breakingChange.String(): case build.String(): case chore.String(): case ci.String(): case docs.String(): case feat.String(): case fix.String(): case perf.String(): case refactor.String(): case style.String(): case test.String(): default: errMsg = fmt.Sprintf( "%v has invalid commit type\n\tavailable commit types are:\n\t%v", m, printTypes(), ) return errMsg, false } return "", true } // getTypes returns available types // this is only used for letting user know when they failed to commit // because of type mismatch issue func printTypes() string { const types = `(BREAKING CHANGE | build | chore | ci | docs | feat | fix | perf | refactor | style | test)` return types }
package module import ( "testing" "buddin.us/eolian/dsp" "gopkg.in/go-playground/assert.v1" ) func TestPatching(t *testing.T) { one, err := newModule(false) assert.Equal(t, err, nil) two, err := newModule(true) assert.Equal(t, err, nil) err = two.Patch("input", Port{one, "output"}) assert.Equal(t, err, nil) actual, expected := one.OutputsActive(true), 1 assert.Equal(t, actual, expected) err = two.Reset() assert.Equal(t, err, nil) actual, expected = one.OutputsActive(true), 0 assert.Equal(t, actual, expected) } func TestPatchingUnknownPort(t *testing.T) { one, err := newModule(false) assert.Equal(t, err, nil) two, err := newModule(true) assert.Equal(t, err, nil) err = two.Patch("input", Port{one, "unknown"}) assert.NotEqual(t, err, nil) actual, expected := one.OutputsActive(true), 0 assert.Equal(t, actual, expected) } func TestListing(t *testing.T) { module, err := newModule(false) assert.Equal(t, err, nil) assert.Equal(t, module.Inputs(), module.inLookup) assert.Equal(t, len(module.Inputs()), 2) assert.Equal(t, module.Outputs(), module.outLookup) assert.Equal(t, len(module.Outputs()), 1) } func TestPatchingValues(t *testing.T) { one, err := newModule(false) assert.Equal(t, err, nil) err = one.Patch("input", 1) assert.Equal(t, err, nil) err = one.Patch("input", "1") assert.Equal(t, err, nil) err = one.Patch("input", 1.0) assert.Equal(t, err, nil) err = one.Patch("input", "1.0") assert.Equal(t, err, nil) err = one.Patch("input", dsp.Duration(200)) assert.Equal(t, err, nil) err = one.Patch("input", dsp.Frequency(440)) assert.Equal(t, err, nil) err = one.Patch("input", "C#4") assert.Equal(t, err, nil) err = one.Patch("input", "Z4") assert.NotEqual(t, err, nil) pitch, err := dsp.ParsePitch("Eb3") assert.Equal(t, err, nil) err = one.Patch("input", pitch) assert.Equal(t, err, nil) err = one.Patch("input", true) assert.NotEqual(t, err, nil) } type mockOutput struct{} func (p mockOutput) Process(dsp.Frame) {} func newModule(forceSinking bool) (*IO, error) { io := &IO{} if err := io.Expose( "Module", []*In{ {Name: "input", Source: dsp.NewBuffer(dsp.Float64(0)), ForceSinking: forceSinking}, {Name: "level", Source: dsp.NewBuffer(dsp.Float64(0))}, }, []*Out{{Name: "output", Provider: dsp.Provide(mockOutput{})}}, ); err != nil { return nil, err } return io, nil } func TestMultipleOutputDestinations(t *testing.T) { one, err := newModule(false) assert.Equal(t, err, nil) two, err := newModule(true) assert.Equal(t, err, nil) three, err := newModule(true) assert.Equal(t, err, nil) err = two.Patch("input", Port{one, "output"}) assert.Equal(t, err, nil) err = three.Patch("input", Port{one, "output"}) assert.Equal(t, err, nil) actual, expected := one.OutputsActive(true), 1 assert.Equal(t, actual, expected) actual, expected = two.OutputsActive(true), 0 assert.Equal(t, actual, expected) actual, expected = three.OutputsActive(true), 0 assert.Equal(t, actual, expected) o, err := one.Output("output") assert.Equal(t, err, nil) assert.Equal(t, len(o.destinations), 2) err = two.Reset() assert.Equal(t, err, nil) actual, expected = one.OutputsActive(true), 1 assert.Equal(t, actual, expected) o, err = one.Output("output") assert.Equal(t, err, nil) assert.Equal(t, len(o.destinations), 1) assert.Equal(t, two.inLookup["input"].Source.(*dsp.Buffer).Processor.(dsp.Float64), dsp.Float64(0)) assert.Equal(t, three.inLookup["input"].Source.(*dsp.Buffer).Processor.(*Out).owner.ID(), one.ID()) err = three.Reset() assert.Equal(t, err, nil) o, err = one.Output("output") assert.Equal(t, err, nil) assert.Equal(t, len(o.destinations), 0) assert.Equal(t, three.inLookup["input"].Source.(*dsp.Buffer).Processor.(dsp.Float64), dsp.Float64(0)) } func TestNormalizeInput(t *testing.T) { one, err := newModule(false) assert.Equal(t, err, nil) two, err := newModule(true) assert.Equal(t, err, nil) three, err := newModule(true) assert.Equal(t, err, nil) err = two.Patch("input", Port{one, "output"}) assert.Equal(t, err, nil) err = three.Patch("input", Port{one, "output"}) assert.Equal(t, err, nil) actual, expected := one.OutputsActive(true), 1 assert.Equal(t, actual, expected) actual, expected = two.OutputsActive(true), 0 assert.Equal(t, actual, expected) actual, expected = three.OutputsActive(true), 0 assert.Equal(t, actual, expected) o, err := one.Output("output") assert.Equal(t, err, nil) assert.Equal(t, len(o.destinations), 2) err = two.inLookup["input"].Close() assert.Equal(t, err, nil) actual, expected = one.OutputsActive(true), 1 assert.Equal(t, actual, expected) err = three.inLookup["input"].Close() assert.Equal(t, err, nil) actual, expected = one.OutputsActive(true), 0 assert.Equal(t, actual, expected) }
/** @description:go-sidecar @author: Angels lose their hair @date: 2021/5/13 @version:v1 **/ package hooks import ( "gopkg.in/natefinch/lumberjack.v2" "io" "sync" "github.com/sirupsen/logrus" ) func NewLogWriterHook(p string) *LogWriterHook { return &LogWriterHook{ lock: new(sync.Mutex), levels: []logrus.Level{ logrus.DebugLevel, logrus.InfoLevel, }, writer: &lumberjack.Logger{ Filename: p+"info.log", MaxSize: 500, // megabytes MaxBackups: 3, MaxAge: 30, //days }, } } func NewLogWriterForErrorHook(p string) *LogWriterHook { return &LogWriterHook{ lock: new(sync.Mutex), levels: []logrus.Level{ logrus.WarnLevel, logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel, }, writer: &lumberjack.Logger{ Filename: p + "error.log", MaxSize: 500, // megabytes MaxBackups: 3, MaxAge: 30, //days }, } } type LogWriterHook struct { levels []logrus.Level writer io.Writer lock *sync.Mutex } func (hook *LogWriterHook) Fire(entry *logrus.Entry) error { hook.lock.Lock() defer hook.lock.Unlock() msg, err := entry.String() if err != nil { return err } else { hook.writer.Write([]byte(msg)) } return nil } func (hook *LogWriterHook) Levels() []logrus.Level { return hook.levels }
package dynamic_programming func numDistinct(s string, t string) int { sLen := len(s) tLen := len(t) dp := make([][]int, tLen+1) for i := range dp { dp[i] = make([]int, sLen+1) } dp[0][0] = 1 // t =="" 时,每个s[i]都有一种匹配 for i := 1; i < len(s); i++ { dp[0][i] = 1 } // s==""时,每个t[i]都不能匹配, default 0 for i := 1; i <= tLen; i++ { for j := 1; j <= sLen; j++ { if t[i-1] == s[j-1] { dp[i][j] = dp[i-1][j-1] + dp[i][j-1] } else { dp[i][j] = dp[i][j-1] // 认为是前匹配的数字 } } } return dp[tLen][sLen] } // 超时 func numDistinct2(s string, t string) int { if len(s) < len(t) || len(s) == 0 { return 0 } res := 0 help115(s, t, &res) return res } func help115(s string, t string, res *int) { if len(t) == 0 { *res++ return } if len(s) < len(t) { return } if s[0] == t[0] { help115(s[1:], t[1:], res) } help115(s[1:], t, res) }
//go:build ignore // +build ignore package main import ( "bytes" "flag" "fmt" "go/format" "io" "io/ioutil" "log" "strings" "text/template" "unicode/utf8" ) var output = flag.String("output", "templates.go", "Where to put the variable declarations") var pkgname = flag.String("package", "main", "What package should the output file belong to") // errWriter wraps an io.Writer and saves the first error it encounters (and // otherwise ignores all write-errors). type errWriter struct { io.Writer err error } // Like strconv.CanBackquote, but allows multi-line backquoted strings (i.e. // does not consider \n in the input a cause to return false). func canBackquote(s string) bool { for len(s) > 0 { r, wid := utf8.DecodeRuneInString(s) s = s[wid:] if wid > 1 { if r == '\ufeff' { return false // BOMs are invisible and should not be quoted. } continue // All other multibyte runes are correctly encoded and assumed printable. } if r == utf8.RuneError { return false } if (r < ' ' && r != '\t' && r != '\n') || r == '`' || r == '\u007F' { return false } } return true } var embeddedTemplateTmpl = template.Must(template.New("embedded").Parse(` package {{ .Package }} // Generated by "go run gentmpl.go {{ .Args }}". // Do not edit manually. import ( "html/template" ) var templates = template.New("all") func init() { {{ range $i, $t := .Templates -}} template.Must(templates.New("{{ $t.Name }}").Parse({{ $t.ContentLiteral }})) {{ end -}} } `)) func main() { flag.Parse() if flag.NArg() < 1 { log.Fatal("Must provide at least one template file to include") } type nameAndContent struct { Name string ContentLiteral string } tmpls := make([]nameAndContent, flag.NArg()) for i := 0; i < flag.NArg(); i++ { n := flag.Arg(i) b, err := ioutil.ReadFile(n + ".html") if err != nil { log.Fatal(err) } // If we can use backquotes, we do — it makes generated files easier to read. var literal string if canBackquote(string(b)) { literal = "`" + string(b) + "`" } else { literal = fmt.Sprintf("%#v", string(b)) } tmpls[i] = nameAndContent{ Name: flag.Arg(i), ContentLiteral: literal, } } var buf bytes.Buffer if err := embeddedTemplateTmpl.Execute(&buf, struct { Package string Args string Templates []nameAndContent }{ Package: *pkgname, Args: strings.Join(flag.Args(), " "), Templates: tmpls, }); err != nil { log.Fatal(err) } outsrc, err := format.Source(buf.Bytes()) if err != nil { log.Fatalf("Could not format output: %v\nOutput:\n%s", buf.String(), err) } if err := ioutil.WriteFile(*output, outsrc, 0644); err != nil { log.Fatalf("Could not write output: %v", err) } }
package main import ( "encoding/json" "net/http" "net/url" "github.com/gorilla/mux" ) type createJobJSON struct { URL string `json:"url"` Secret string `json:"secret"` Maxsize uint `json:"maxsize"` Concurrency int `json:"concurrency"` } type kvJSON struct { Key string `json:"key"` Value interface{} `json:"value"` } func createJob(w http.ResponseWriter, req *http.Request) { defer req.Body.Close() var query createJobJSON if err := json.NewDecoder(req.Body).Decode(&query); err == nil { if u, err := url.Parse(query.URL); err == nil { job := CreateJob(query.Secret, *u, query.Maxsize) job.Start(query.Concurrency) Manager.addJob(job) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(job) return } } w.WriteHeader(http.StatusBadRequest) } func getJob(w http.ResponseWriter, req *http.Request) { id := mux.Vars(req)["id"] job := Manager.getJob(id) if job == nil { w.WriteHeader(http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(job) } func addInput(w http.ResponseWriter, req *http.Request) { defer req.Body.Close() id := mux.Vars(req)["id"] job := Manager.getJob(id) if job == nil { w.WriteHeader(http.StatusNotFound) return } var body []kvJSON if err := json.NewDecoder(req.Body).Decode(&body); err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } for _, eachkv := range body { bytes, _ := json.Marshal(eachkv.Value) if err := job.AddToJob(eachkv.Key, bytes); err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(job) } func allInputSent(w http.ResponseWriter, req *http.Request) { defer req.Body.Close() id := mux.Vars(req)["id"] job := Manager.getJob(id) if job == nil { w.WriteHeader(http.StatusNotFound) return } if err := job.AllInputsWereSent(); err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(err.Error())) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(job) } func getJobOutputs(w http.ResponseWriter, req *http.Request) { defer req.Body.Close() id := mux.Vars(req)["id"] job := Manager.getJob(id) if job == nil { w.WriteHeader(http.StatusNotFound) return } // TODO handle optional nowait, skip, limit options if job.GetInputsCount() != job.GetOutputsCount() { // wait only if we haven't received all outputs <-job.Complete } if job.State != AllOutputReceived { w.WriteHeader(http.StatusExpectationFailed) json.NewEncoder(w).Encode(job) return } res, err := job.GetResults() if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } result := make([]kvJSON, len(res)) for index, eachkv := range res { var value interface{} json.Unmarshal(eachkv.Value, &value) result[index] = kvJSON{ Key: eachkv.Key, Value: value, } } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(result) } func deleteJob(w http.ResponseWriter, req *http.Request) { defer req.Body.Close() id := mux.Vars(req)["id"] Manager.delJob(id) // TODO this will leak if the job isn't finished yet w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) } func routes() *mux.Router { routes := mux.NewRouter() routes.HandleFunc("/job", createJob).Methods("POST") routes.HandleFunc("/job/{id}", getJob).Methods("GET") routes.HandleFunc("/job/{id}/output", getJobOutputs).Methods("GET") routes.HandleFunc("/job/{id}/input", addInput).Methods("PUT") routes.HandleFunc("/job/{id}/complete", allInputSent).Methods("POST") routes.HandleFunc("/job/{id}", deleteJob).Methods("DELETE") return routes // TODO need a route to get more status information // TODO need a way to signal if there's a problem with the backend }
package main import ( "bufio" "fmt" "os" ) func main() { // The *os.File is of var f *os.File f = os.Stdin defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { fmt.Println(">", scanner.Text()) if scanner.Text() == "END" || scanner.Text() == "end" { fmt.Println("The Program stops Now") f.Close() } } }
package flog import "testing" func TestFlog(t *testing.T) { DEBUG.Println(NET, "ss") INFO.Println(PNG, "sddd") WARN.Println(DEC, "sdecg") ERROR.Println(MID, "vde") FATAL.Println(STA, "qqqq") }
package repos import ( "errors" "github.com/jinzhu/gorm" ) // User basic defintion of a User type User struct { gorm.Model Username string `json:"username" binding:"required"` // Password string `json:"password" binding:"required"` DisplayName string `json:"displayName"` DepartmentID int `json:"department"` Created int64 `json:"created"` } // UserRepository - db access for Users type UserRepository struct { DB *gorm.DB } // UserPassword set the password for a user type UserPassword struct { gorm.Model UserID int Password string } // NewUserRepository takes a gorm DB and returns a user repo func NewUserRepository(dbToUse *gorm.DB) UserRepository { // db, err := gorm.Open("sqlite3", "test.db") // if err != nil { // panic("failed to connect database") // } //defer db.Close() repository := UserRepository{DB: dbToUse} return repository } // GetPassword - gets the password for the user func (r *UserRepository) GetPassword(ForUser *User) (string, error) { passwd := UserPassword{} r.DB.Model(&passwd).Where("user_id = ?", ForUser.ID).Find(&passwd) return "", nil } // DeleteUser removes the pecified user func (r *UserRepository) DeleteUser(UserToDelete *User) error { r.DB.Delete(&UserToDelete) return nil } // CreateUser creates a new DB record func (r *UserRepository) CreateUser(UserToAdd *User) error { if r.DB.NewRecord(UserToAdd) { return r.DB.Create(&UserToAdd).Error } return errors.New("Already has a key set") } // UpdateUser updates the specified user func (r *UserRepository) UpdateUser(UserToUpdate *User) error { err := r.DB.Update(UserToUpdate).Error return err } // Find use the specified criteria to locate users func (r *UserRepository) Find(criteriaClause func(*gorm.DB) *gorm.DB) ([]User, error) { var users = []User{} r.withCriteria(criteriaClause).Find(&users) return users, r.DB.Error } // FindAll use the specified criteria to locate users func (r *UserRepository) FindAll() ([]User, error) { var users = []User{} r.DB.Find(&users) return users, r.DB.Error } func (r *UserRepository) withCriteria(criteriaClause func(*gorm.DB) *gorm.DB) *gorm.DB { if criteriaClause == nil { criteriaClause = func(db *gorm.DB) *gorm.DB { return db } } return criteriaClause(r.DB) }
package main import "fmt" type Human struct { name string age int8 sex byte } func main() { //1、初始化Human h1 := Human{"Frank", 28, 1} fmt.Printf("h1: %T , %v, %p \n", h1, h1, &h1) fmt.Println("--------------------") //将结构体对象拷贝 h2 := h1 h2.name = "David" h2.age = 30 fmt.Printf("h2修改后: %T , %v, %p \n", h2, h2, &h2) fmt.Printf("h1: %T , %v, %p \n", h1, h1, &h1) fmt.Println("--------------------") //将结构体对象作为参数传递 changeName(h1) fmt.Printf("h1: %T , %v, %p \n", h1, h1, &h1) } func changeName(h Human) { h.name = "Daniel" h.age = 13 fmt.Printf("函数体内修改后:%T, %v , %p \n", h, h, &h) }
package main import ( "flag" "fmt" "io/ioutil" "log" "strings" "github.com/andywow/golang-lessons/lesson4/dictparser" ) var ( fileName = flag.String("filename", "", "file to use as input") data = flag.String("data", "", "Data to parse") ) func main() { flag.Parse() if *fileName == "" && *data == "" { log.Fatalf("You need specify filename or data parameter") } if *fileName != "" && *data != "" { log.Fatalf("You need specify only one of filename and data parameters") } var result []string if *data != "" { log.Println("Parsing data from input") result = dictparser.Top10(*data) } if *fileName != "" { content, err := ioutil.ReadFile(*fileName) if err != nil { log.Fatalf("%s\n", err) } text := string(content) log.Println("Parsing data from file") result = dictparser.Top10(text) } log.Println("Top10 words:") fmt.Println(strings.Join(result, "\n")) }
package wps import ( `crypto/tls` `github.com/go-resty/resty/v2` ) // NewResty Resty客户端 func NewResty() *resty.Request { return resty.New().SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}).R() }
package saihon import ( "fmt" "reflect" "strings" "testing" "golang.org/x/net/html" ) func TestClassList(t *testing.T) { var expect DOMTokenList expect.List = []string{"foo", "bar", "baz"} expect.Value = strings.Join(expect.List, " ") s := `<!DOCTYPE html><html><head></head><body><div class="` + expect.Value + `"></div></body></html>` doc, _ := html.Parse(strings.NewReader(s)) body := Document{doc}.Body() div := body.FirstElementChild() list := div.ClassList() if list.Length() != expect.Length() || !reflect.DeepEqual(expect.List, list.List) || list.Value != expect.Value { s1 := fmt.Sprintf("Value: %#v, List: %v, Length: %d", list.Value, list.List, list.Length()) s2 := fmt.Sprintf("Value: %#v, List: %v, Length: %d", expect.Value, expect.List, expect.Length()) t.Errorf("\nerror: DOMTokenList:\n actual[%s]\n expect[%s]\n", s1, s2) } }
package queue import ( "container/heap" "math/big" "sync" "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer" ks "gx/ipfs/QmUusaX99BZoELh7dmPgirqRQ1FAmMnmnBn3oiqDFGBUSc/go-keyspace" ) // peerMetric tracks a peer and its distance to something else. type peerMetric struct { // the peer peer peer.ID // big.Int for XOR metric metric *big.Int } // peerMetricHeap implements a heap of peerDistances type peerMetricHeap []*peerMetric func (ph peerMetricHeap) Len() int { return len(ph) } func (ph peerMetricHeap) Less(i, j int) bool { return -1 == ph[i].metric.Cmp(ph[j].metric) } func (ph peerMetricHeap) Swap(i, j int) { ph[i], ph[j] = ph[j], ph[i] } func (ph *peerMetricHeap) Push(x interface{}) { item := x.(*peerMetric) *ph = append(*ph, item) } func (ph *peerMetricHeap) Pop() interface{} { old := *ph n := len(old) item := old[n-1] *ph = old[0 : n-1] return item } // distancePQ implements heap.Interface and PeerQueue type distancePQ struct { // from is the Key this PQ measures against from ks.Key // heap is a heap of peerDistance items heap peerMetricHeap sync.RWMutex } func (pq *distancePQ) Len() int { pq.Lock() defer pq.Unlock() return len(pq.heap) } func (pq *distancePQ) Enqueue(p peer.ID) { pq.Lock() defer pq.Unlock() distance := ks.XORKeySpace.Key([]byte(p)).Distance(pq.from) heap.Push(&pq.heap, &peerMetric{ peer: p, metric: distance, }) } func (pq *distancePQ) Dequeue() peer.ID { pq.Lock() defer pq.Unlock() if len(pq.heap) < 1 { panic("called Dequeue on an empty PeerQueue") // will panic internally anyway, but we can help debug here } o := heap.Pop(&pq.heap) p := o.(*peerMetric) return p.peer } // NewXORDistancePQ returns a PeerQueue which maintains its peers sorted // in terms of their distances to each other in an XORKeySpace (i.e. using // XOR as a metric of distance). func NewXORDistancePQ(from string) PeerQueue { return &distancePQ{ from: ks.XORKeySpace.Key([]byte(from)), heap: peerMetricHeap{}, } }
package main import ( "crypto/ecdsa" "crypto/rand" "encoding/hex" "errors" "github.com/boltdb/bolt" "github.com/ethereum/go-ethereum/crypto/secp256k1" "github.com/labstack/echo" "github.com/ruqqq/blockchainparser/rpc" "github.com/ruqqq/carbonchain" "math/big" "net/http" "strconv" "strings" ) const DEFAULT_BTC_FEE float64 = 0.00002 var ( ErrUsernameEmpty = errors.New("Username cannot be empty") ErrNoAccess = errors.New("Private key has no access") ErrPublicKeyLength = errors.New("Public key (compressed) has to be 33 bytes") ErrPrivateKeyInvalid = errors.New("Private key is invalid") ErrImageNameEmpty = errors.New("ImageName cannot be empty") ErrTagNameEmpty = errors.New("TagName cannot be empty") ErrDigestsEmpty = errors.New("Digests cannot be empty") ErrRootKeyDoesNotExist = errors.New("Root key does not exist") ErrKeyDoesNotExist = errors.New("Key does not exist") ErrSignatureDoesNotExist = errors.New("Signature does not exist") ErrNameInvalid = errors.New("Name has to be in the format of {username}/{image name}:{tag name}") ) const ( StatusRootKeyDoesNotExist = "ROOT_KEY_MISSING" StatusKeyDoesNotExist = "KEY_MISSING" StatusSignatureNotValid = "SIGNATURE_INVALID" StatusSignatureValid = "SIGNATURE_VALID" StatusUnableToVerify = "UNABLE_TO_VERIFY" ) type CustomContext struct { echo.Context BitcoindRpcOptions *rpc.RpcOptions Db *bolt.DB } type CreateKeyPairResponse struct { PrivateKey string `json:"privateKey"` PublicKey string `json:"publicKey"` } type RawSignatureRequest struct { PrivateKey string `json:"privateKey"` Message string `json:"message"` MessageHex string `json:"messageHex"` } type RawSignatureResponse struct { Signature string `json:"signature"` } type VerifyRequest struct { PublicKey string `json:"publicKey"` Message string `json:"message"` MessageHex string `json:"messageHex"` Signature string `json:"signature"` } type VerifyResponse struct { Signature string `json:"signature"` Verified bool `json:"verified"` } type RootKeyRequest struct { PrivateKey string `json:"privateKey"` Username string `json:"username"` PublicKeyCompressed string `json:"publicKey"` } type TxIdResponse struct { Txids []string `json:"txIds"` } type KeyRequest struct { PrivateKey string `json:"privateKey"` Username string `json:"username"` PublicKeyCompressed string `json:"publicKey"` ImageName string `json:"imageName"` KeyId int8 `json:"keyId"` } type SignatureRequest struct { PrivateKey string `json:"privateKey"` Username string `json:"username"` ImageName string `json:"imageName"` TagName string `json:"tagName"` KeyId int8 `json:"keyId"` Digests []string `json:"digests"` } type GetRootPublicKeyForUserResponse struct { PublicKeyCompressed string `json:"publicKey"` Images []string `json:"images"` RegisteredRepo []string `json:"registeredRepo"` } type GetPublicKeysForImageResponse struct { PublicKeys map[int]PublicKeyResponse `json:"publicKeys"` } type PublicKeyResponse struct { PublicKeyCompressed string `json:"publicKey"` Signature string `json:"signature"` Status string `json:"status,omitempty"` } type GetSignatureForTagResponse struct { Name string `json:"name"` Hashes []string `json:"hashes"` KeyId int8 `json:"keyId"` Signature string `json:"signature"` Status string `json:"status,omitempty"` } type ErrorResponse struct { Error string `json:"error"` } var secp256k1Curve = secp256k1.S256() func CreateKeyPair(c echo.Context) error { privateKey, err := ecdsa.GenerateKey(secp256k1Curve, rand.Reader) // this generates a public & private key pair if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } publicKey := privateKey.PublicKey return c.JSONPretty(http.StatusOK, CreateKeyPairResponse{ PrivateKey: hex.EncodeToString(privateKey.D.Bytes()), PublicKey: hex.EncodeToString(SerializePublicKeyCompressed(publicKey)), }, " ") } func SignMessage(c echo.Context) error { request := new(RawSignatureRequest) if err := c.Bind(request); err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } var setSuccess bool privateKey := new(ecdsa.PrivateKey) privateKey.D, setSuccess = new(big.Int).SetString(request.PrivateKey, 16) if !setSuccess { return ShowErrorJSON(c, http.StatusBadRequest, errors.New("Private Key is invalid.")) } privateKey.PublicKey.Curve = secp256k1Curve msg := []byte(request.Message) if request.MessageHex != "" { var err error msg, err = hex.DecodeString(request.MessageHex) if err != nil { return nil } } if len(msg) == 0 { return ShowErrorJSON(c, http.StatusBadRequest, errors.New("Empty message")) } r, s, err := ecdsa.Sign(rand.Reader, privateKey, msg) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } signature := r.Bytes() signature = append(signature, s.Bytes()...) return c.JSONPretty(http.StatusOK, RawSignatureResponse{hex.EncodeToString(signature)}, " ") } func VerifyMessage(c echo.Context) error { request := new(VerifyRequest) if err := c.Bind(request); err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } msg := []byte(request.Message) if request.MessageHex != "" { var err error msg, err = hex.DecodeString(request.MessageHex) if err != nil { return nil } } if len(msg) == 0 { return ShowErrorJSON(c, http.StatusBadRequest, errors.New("Empty message")) } publicKeyCompressed, err := hex.DecodeString(request.PublicKey) if err != nil { return nil } publicKey, err := UnserializePublicKeyCompressed(secp256k1Curve, publicKeyCompressed) if err != nil { return nil } signature, _ := hex.DecodeString(request.Signature) r, _ := big.NewInt(0).SetString(hex.EncodeToString(signature[:32]), 16) s, _ := big.NewInt(0).SetString(hex.EncodeToString(signature[32:]), 16) verify := ecdsa.Verify(&publicKey, msg, r, s) return c.JSONPretty(http.StatusOK, VerifyResponse{Signature: request.Signature, Verified: verify}, " ") } // RegisterRootKey func RegisterRootKey(c echo.Context) error { cc := c.(*CustomContext) request := new(RootKeyRequest) if err := c.Bind(request); err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } request.Username = c.Param("username") data, err := NewRootKeyCommandFromRootKeyRequest(request, TYPE_REGISTER_ROOT_KEY) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } // Do local validation: // Make sure the key is not taken and that if it is a replacing operation, correct private key is provided err = cc.Db.View(func(tx *bolt.Tx) error { bRootKeys := tx.Bucket([]byte(BUCKET_ROOT_KEYS)) existingPubKey := bRootKeys.Get([]byte(data.Username)) if existingPubKey != nil { if request.PrivateKey == "" { return ErrPrivateKeyInvalid } var setSuccess bool privateKey := new(ecdsa.PrivateKey) privateKey.D, setSuccess = new(big.Int).SetString(request.PrivateKey, 16) if !setSuccess { return ErrPrivateKeyInvalid } privateKey.PublicKey.Curve = secp256k1Curve r, s, err := ecdsa.Sign(rand.Reader, privateKey, data.BytesForSigning()) if err != nil { return err } signature := r.Bytes() signature = append(signature, s.Bytes()...) copy(data.Signature[:], signature) publicKey, err := UnserializePublicKeyCompressed(secp256k1Curve, existingPubKey) if err != nil { // TODO: Should I not panic? panic(err) return err } verify := ecdsa.Verify(&publicKey, data.BytesForSigning(), r, s) if !verify { return ErrUsernameTaken } } return nil }) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } response, err := carbonchain.Store(data.Bytes(), PACKET_ID, getFee(c), cc.BitcoindRpcOptions) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } return c.JSONPretty(http.StatusOK, TxIdResponse{response}, " ") } // DeleteRootKey func DeleteRootKey(c echo.Context) error { cc := c.(*CustomContext) request := new(RootKeyRequest) if err := c.Bind(request); err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } request.Username = c.Param("username") data, err := NewRootKeyCommandFromRootKeyRequest(request, TYPE_DELETE_ROOT_KEY) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } if request.PrivateKey == "" { return ErrPrivateKeyInvalid } var setSuccess bool privateKey := new(ecdsa.PrivateKey) privateKey.D, setSuccess = new(big.Int).SetString(request.PrivateKey, 16) if !setSuccess { return ShowErrorJSON(c, http.StatusBadRequest, ErrPrivateKeyInvalid) } privateKey.PublicKey.Curve = secp256k1Curve r, s, err := ecdsa.Sign(rand.Reader, privateKey, data.BytesForSigning()) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } signature := r.Bytes() signature = append(signature, s.Bytes()...) copy(data.Signature[:], signature) // Do local validation err = cc.Db.View(func(tx *bolt.Tx) error { bRootKeys := tx.Bucket([]byte(BUCKET_ROOT_KEYS)) existingPubKey := bRootKeys.Get([]byte(data.Username)) if existingPubKey != nil { publicKey, err := UnserializePublicKeyCompressed(secp256k1Curve, existingPubKey) if err != nil { // TODO: Should I not panic? panic(err) return err } verify := ecdsa.Verify(&publicKey, data.BytesForSigning(), r, s) if !verify { return ErrNoAccess } } else { return ErrRootKeyDoesNotExist } return nil }) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } response, err := carbonchain.Store(data.Bytes(), PACKET_ID, getFee(c), cc.BitcoindRpcOptions) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } return c.JSONPretty(http.StatusOK, TxIdResponse{response}, " ") } // RegisterKey func RegisterKey(c echo.Context) error { cc := c.(*CustomContext) request := new(KeyRequest) if err := c.Bind(request); err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } request.Username = c.Param("username") request.ImageName = c.Param("name") data, err := NewKeyCommandFromKeyRequest(request, TYPE_REGISTER_KEY) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } // Do local validation err = cc.Db.View(func(tx *bolt.Tx) error { bRootKeys := tx.Bucket([]byte(BUCKET_ROOT_KEYS)) existingPubKey := bRootKeys.Get([]byte(data.Username)) if existingPubKey != nil { publicKey, err := UnserializePublicKeyCompressed(secp256k1Curve, existingPubKey) if err != nil { // TODO: Should I not panic? panic(err) return err } r, _ := big.NewInt(0).SetString(hex.EncodeToString(data.Signature[:32]), 16) s, _ := big.NewInt(0).SetString(hex.EncodeToString(data.Signature[32:]), 16) verify := ecdsa.Verify(&publicKey, data.BytesForSigning(), r, s) if !verify { return ErrNoAccess } } else { return ErrRootKeyDoesNotExist } return nil }) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } response, err := carbonchain.Store(data.Bytes(), PACKET_ID, getFee(c), cc.BitcoindRpcOptions) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } return c.JSONPretty(http.StatusOK, TxIdResponse{response}, " ") } // DeleteKey func DeleteKey(c echo.Context) error { cc := c.(*CustomContext) request := new(KeyRequest) if err := c.Bind(request); err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } request.Username = c.Param("username") request.ImageName = c.Param("name") data, err := NewKeyCommandFromKeyRequest(request, TYPE_DELETE_KEY) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } // Do local validation err = cc.Db.View(func(tx *bolt.Tx) error { bRootKeys := tx.Bucket([]byte(BUCKET_ROOT_KEYS)) existingPubKey := bRootKeys.Get([]byte(data.Username)) if existingPubKey != nil { publicKey, err := UnserializePublicKeyCompressed(secp256k1Curve, existingPubKey) if err != nil { // TODO: Should I not panic? panic(err) return err } r, _ := big.NewInt(0).SetString(hex.EncodeToString(data.Signature[:32]), 16) s, _ := big.NewInt(0).SetString(hex.EncodeToString(data.Signature[32:]), 16) verify := ecdsa.Verify(&publicKey, data.BytesForSigning(), r, s) if !verify { return ErrNoAccess } } else { return ErrRootKeyDoesNotExist } return nil }) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } response, err := carbonchain.Store(data.Bytes(), PACKET_ID, getFee(c), cc.BitcoindRpcOptions) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } return c.JSONPretty(http.StatusOK, TxIdResponse{response}, " ") } // RegisterSignature func RegisterSignature(c echo.Context) error { cc := c.(*CustomContext) request := new(SignatureRequest) if err := c.Bind(request); err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } request.Username = c.Param("username") name := strings.Split(c.Param("name"), ":") request.ImageName = name[0] request.TagName = name[1] data := SignatureCommand{} data.Type = TYPE_REGISTER_SIGNATURE data.Username = request.Username if len(data.Username) == 0 { return ShowErrorJSON(c, http.StatusBadRequest, ErrUsernameEmpty) } data.ImageName = request.ImageName if len(data.ImageName) == 0 { return ShowErrorJSON(c, http.StatusBadRequest, ErrImageNameEmpty) } data.TagName = request.TagName if len(data.TagName) == 0 { return ShowErrorJSON(c, http.StatusBadRequest, ErrTagNameEmpty) } data.KeyId = request.KeyId data.Digests = request.Digests if len(data.Digests) == 0 { return ShowErrorJSON(c, http.StatusBadRequest, ErrDigestsEmpty) } for _, digest := range data.Digests { split := strings.Split(digest, ":") if len(split) != 2 { return ShowErrorJSON(c, http.StatusBadRequest, ErrDigestFormat) } _, err := hex.DecodeString(split[1]) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, ErrDigestFormat) } } var setSuccess bool privateKey := new(ecdsa.PrivateKey) privateKey.D, setSuccess = new(big.Int).SetString(request.PrivateKey, 16) if !setSuccess { return ShowErrorJSON(c, http.StatusBadRequest, ErrPrivateKeyInvalid) } privateKey.PublicKey.Curve = secp256k1Curve r, s, err := ecdsa.Sign(rand.Reader, privateKey, data.BytesForSigning()) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } signature := r.Bytes() signature = append(signature, s.Bytes()...) copy(data.Signature[:], signature) // Do local validation err = cc.Db.View(func(tx *bolt.Tx) error { bKeys := tx.Bucket([]byte(BUCKET_KEYS)) bUsername := bKeys.Bucket([]byte(data.Username)) if bUsername == nil { return ErrKeyNotFound } bImageName := bUsername.Bucket([]byte(data.ImageName)) if bImageName == nil { return ErrKeyNotFound } existingPubKey := bImageName.Get([]byte{byte(data.KeyId)}) if existingPubKey != nil { publicKey, err := UnserializePublicKeyCompressed(secp256k1Curve, existingPubKey) if err != nil { // TODO: Should I not panic? panic(err) return err } verify := ecdsa.Verify(&publicKey, data.BytesForSigning(), r, s) if !verify { return ErrNoAccess } } else { return ErrKeyDoesNotExist } return nil }) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } response, err := carbonchain.Store(data.Bytes(), PACKET_ID, getFee(c), cc.BitcoindRpcOptions) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } return c.JSONPretty(http.StatusOK, TxIdResponse{response}, " ") } // DeleteSignature func DeleteSignature(c echo.Context) error { cc := c.(*CustomContext) request := new(SignatureRequest) if err := c.Bind(request); err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } request.Username = c.Param("username") name := strings.Split(c.Param("name"), ":") request.ImageName = name[0] request.TagName = name[1] data := SignatureCommand{} data.Type = TYPE_DELETE_SIGNATURE data.Username = request.Username if len(data.Username) == 0 { return ShowErrorJSON(c, http.StatusBadRequest, ErrUsernameEmpty) } data.ImageName = request.ImageName if len(data.ImageName) == 0 { return ShowErrorJSON(c, http.StatusBadRequest, ErrImageNameEmpty) } data.TagName = request.TagName if len(data.TagName) == 0 { return ShowErrorJSON(c, http.StatusBadRequest, ErrTagNameEmpty) } data.KeyId = request.KeyId var setSuccess bool privateKey := new(ecdsa.PrivateKey) privateKey.D, setSuccess = new(big.Int).SetString(request.PrivateKey, 16) if !setSuccess { return ShowErrorJSON(c, http.StatusBadRequest, ErrPrivateKeyInvalid) } privateKey.PublicKey.Curve = secp256k1Curve r, s, err := ecdsa.Sign(rand.Reader, privateKey, data.BytesForSigning()) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } signature := r.Bytes() signature = append(signature, s.Bytes()...) copy(data.Signature[:], signature) // Do local validation err = cc.Db.View(func(tx *bolt.Tx) error { bKeys := tx.Bucket([]byte(BUCKET_KEYS)) bUsername := bKeys.Bucket([]byte(data.Username)) if bUsername == nil { return ErrKeyNotFound } bImageName := bUsername.Bucket([]byte(data.ImageName)) if bImageName == nil { return ErrKeyNotFound } existingPubKey := bImageName.Get([]byte{byte(data.KeyId)}) if existingPubKey != nil { publicKey, err := UnserializePublicKeyCompressed(secp256k1Curve, existingPubKey) if err != nil { // TODO: Should I not panic? panic(err) return err } verify := ecdsa.Verify(&publicKey, data.BytesForSigning(), r, s) if !verify { return ErrNoAccess } } else { return ErrKeyDoesNotExist } bSignatures := tx.Bucket([]byte(BUCKET_SIGNATURES)) bUsername = bSignatures.Bucket([]byte(data.Username)) if bUsername == nil { return ErrSignatureDoesNotExist } bImage := bUsername.Bucket([]byte(data.ImageName)) if bImage == nil { return ErrSignatureDoesNotExist } bTag := bImage.Bucket([]byte(data.TagName)) if bTag == nil { return ErrSignatureDoesNotExist } return nil }) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } response, err := carbonchain.Store(data.Bytes(), PACKET_ID, getFee(c), cc.BitcoindRpcOptions) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } return c.JSONPretty(http.StatusOK, TxIdResponse{response}, " ") } // GetRootPublicKeyForUser func GetRootPublicKeyForUser(c echo.Context) error { cc := c.(*CustomContext) username := c.Param("username") if username == "" { return ShowErrorJSON(c, http.StatusBadRequest, ErrNameInvalid) } var publicKey string images := make([]string, 0) registeredRepo := make([]string, 0) err := cc.Db.View(func(tx *bolt.Tx) error { bRootKeys := tx.Bucket([]byte(BUCKET_ROOT_KEYS)) rootPublicKey := bRootKeys.Get([]byte(username)) if rootPublicKey == nil { return ErrRootKeyNotFound } publicKey = hex.EncodeToString(rootPublicKey) bKeys := tx.Bucket([]byte(BUCKET_KEYS)) bUsername := bKeys.Bucket([]byte(username)) if bUsername == nil { return nil } bUsername.ForEach(func(k, v []byte) error { if v == nil { if bUsername.Bucket(k).Stats().KeyN > 0 && bUsername.Bucket(k).Stats().KeyN != bUsername.Bucket(k).Stats().BucketN-1 { registeredRepo = append(registeredRepo, string(k)) } bSignatures := tx.Bucket([]byte(BUCKET_SIGNATURES)) bUsername := bSignatures.Bucket([]byte(username)) if bUsername == nil { return nil } bImage := bUsername.Bucket(k) if bImage == nil { return nil } bImage.ForEach(func(k2, v2 []byte) error { if v2 == nil { images = append(images, string(k)+":"+string(k2)) } return nil }) } return nil }) return nil }) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } return c.JSONPretty(http.StatusOK, GetRootPublicKeyForUserResponse{PublicKeyCompressed: publicKey, Images: images, RegisteredRepo: registeredRepo}, " ") } // GetPublicKeysForImage func GetPublicKeysForImage(c echo.Context) error { cc := c.(*CustomContext) username := c.Param("username") if username == "" { return ShowErrorJSON(c, http.StatusBadRequest, ErrNameInvalid) } imageName := c.Param("name") if imageName == "" { return ShowErrorJSON(c, http.StatusBadRequest, ErrNameInvalid) } publicKeys := make(map[int]PublicKeyResponse, 0) err := cc.Db.View(func(tx *bolt.Tx) error { bKeys := tx.Bucket([]byte(BUCKET_KEYS)) bUsername := bKeys.Bucket([]byte(username)) if bUsername == nil { return ErrKeyNotFound } bImageName := bUsername.Bucket([]byte(imageName)) if bImageName == nil { return ErrKeyNotFound } bMeta := bImageName.Bucket([]byte(BUCKET_META)) if bMeta == nil { return ErrKeyNotFound } // Used for checking signature later command := KeyCommand{} command.Type = TYPE_REGISTER_KEY command.Username = username command.ImageName = imageName c := bImageName.Cursor() for keyId, publicKey := c.First(); keyId != nil; keyId, publicKey = c.Next() { // Not sure why we need to check for zero bytes if len(publicKey) == 0 { continue } copy(command.PublicKeyCompressed[:], publicKey) status := StatusUnableToVerify // Get signatureBytes key := append([]byte("signature_"), keyId[0]) signatureBytes := bMeta.Get(key) if signatureBytes == nil { status = StatusSignatureNotValid } else { // Verify signatureBytes to check if expired func() { bRootKeys := tx.Bucket([]byte(BUCKET_ROOT_KEYS)) rootPubKey := bRootKeys.Get([]byte(username)) if rootPubKey == nil { status = StatusRootKeyDoesNotExist return } command.KeyId = int8(keyId[0]) publicKey, err := UnserializePublicKeyCompressed(secp256k1Curve, rootPubKey) if err != nil { // TODO: Should I not panic? panic(err) return } r, _ := big.NewInt(0).SetString(hex.EncodeToString(signatureBytes[:32]), 16) s, _ := big.NewInt(0).SetString(hex.EncodeToString(signatureBytes[32:]), 16) verify := ecdsa.Verify(&publicKey, command.BytesForSigning(), r, s) if verify { status = StatusSignatureValid return } else { status = StatusSignatureNotValid return } }() } publicKeys[int(keyId[0])] = PublicKeyResponse{ PublicKeyCompressed: hex.EncodeToString(publicKey), Signature: hex.EncodeToString(signatureBytes), Status: status, } } return nil }) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } if len(publicKeys) == 0 { return ShowErrorJSON(c, http.StatusNotFound, ErrKeyNotFound) } return c.JSONPretty(http.StatusOK, GetPublicKeysForImageResponse{PublicKeys: publicKeys}, " ") } // GetSignatureForTag func GetSignatureForTag(c echo.Context) error { cc := c.(*CustomContext) username := c.Param("username") if username == "" { return ShowErrorJSON(c, http.StatusBadRequest, ErrNameInvalid) } imageTagName := c.Param("name") imageTagNameSplit := strings.Split(imageTagName, ":") if len(imageTagNameSplit) != 2 { return ShowErrorJSON(c, http.StatusBadRequest, ErrNameInvalid) } imageName := imageTagNameSplit[0] tagName := imageTagNameSplit[1] hashes := make([]string, 0) var signatureBytes []byte keyId := int8(0) status := StatusUnableToVerify err := cc.Db.View(func(tx *bolt.Tx) error { bSignatures := tx.Bucket([]byte(BUCKET_SIGNATURES)) bUsername := bSignatures.Bucket([]byte(username)) if bUsername == nil { return ErrSignatureDoesNotExist } bImage := bUsername.Bucket([]byte(imageName)) if bImage == nil { return ErrSignatureDoesNotExist } bTag := bImage.Bucket([]byte(tagName)) if bTag == nil { return ErrSignatureDoesNotExist } c := bTag.Cursor() for i, hash := c.First(); i != nil; i, hash = c.Next() { // Not sure why we need to check for zero bytes if len(hash) == 0 { continue } hashes = append(hashes, string(hash)) } bMeta := bTag.Bucket([]byte(BUCKET_META)) if bMeta == nil { } keyIdBytes := bMeta.Get([]byte("keyId")) if keyIdBytes == nil { return ErrSignatureDoesNotExist } keyId = int8(keyIdBytes[0]) signatureBytes = bMeta.Get([]byte("signature")) if signatureBytes == nil { return ErrSignatureDoesNotExist } // Verify signature to check if expired command := SignatureCommand{} command.Type = TYPE_REGISTER_SIGNATURE command.Username = username command.ImageName = imageName command.TagName = tagName command.KeyId = keyId command.Digests = hashes bKeys := tx.Bucket([]byte(BUCKET_KEYS)) bUsername = bKeys.Bucket([]byte(username)) if bUsername == nil { status = StatusRootKeyDoesNotExist return nil } bImageName := bUsername.Bucket([]byte(imageName)) if bImageName == nil { status = StatusKeyDoesNotExist return nil } existingPubKey := bImageName.Get([]byte{byte(keyId)}) if existingPubKey != nil { publicKey, err := UnserializePublicKeyCompressed(secp256k1Curve, existingPubKey) if err != nil { // TODO: Should I not panic? panic(err) return err } r, _ := big.NewInt(0).SetString(hex.EncodeToString(signatureBytes[:32]), 16) s, _ := big.NewInt(0).SetString(hex.EncodeToString(signatureBytes[32:]), 16) verify := ecdsa.Verify(&publicKey, command.BytesForSigning(), r, s) if verify { status = StatusSignatureValid } else { status = StatusSignatureNotValid } } else { status = StatusKeyDoesNotExist return nil } return nil }) if err != nil { return ShowErrorJSON(c, http.StatusBadRequest, err) } return c.JSONPretty(http.StatusOK, GetSignatureForTagResponse{Name: username + "/" + imageTagName, Hashes: hashes, KeyId: keyId, Signature: hex.EncodeToString(signatureBytes), Status: status}, " ") } func ShowErrorJSON(c echo.Context, code int, err error) error { c.JSONPretty(code, ErrorResponse{err.Error()}, " ") return err } func getFee(c echo.Context) float64 { if c.Request().Header.Get("X-BTC-FEE") == "" { return DEFAULT_BTC_FEE } fee, err := strconv.ParseFloat(c.Request().Header.Get("X-BTC-FEE"), 64) if err != nil { return DEFAULT_BTC_FEE } return fee }
package sql import ( "bytes" "errors" "fmt" "strings" "time" ) // DataType represents the primitive data types available in MessageQL. type DataType int const ( // Unknown primitive data type. Unknown DataType = 0 // Float means the data type is a float Float = 1 // Integer means the data type is a integer Integer = 2 // Boolean means the data type is a boolean. Boolean = 3 // String means the data type is a string of text. String = 4 // Time means the data type is a time. Time = 5 // Duration means the data type is a duration of time. Duration = 6 ) // InspectDataType returns the data type of a given value. func InspectDataType(v interface{}) DataType { switch v.(type) { case float64: return Float case int64, int32, int: return Integer case bool: return Boolean case string: return String case time.Time: return Time case time.Duration: return Duration default: return Unknown } } func (d DataType) String() string { switch d { case Float: return "float" case Integer: return "integer" case Boolean: return "boolean" case String: return "string" case Time: return "time" case Duration: return "duration" } return "unknown" } // Node represents a node in the MessageDB abstract syntax tree. type Node interface { node() String() string } func (*Query) node() {} func (Statements) node() {} func (*AlterRetentionPolicyStatement) node() {} func (*CreateDatabaseStatement) node() {} func (*CreateRetentionPolicyStatement) node() {} func (*CreateUserStatement) node() {} func (*DeleteStatement) node() {} func (*DropDatabaseStatement) node() {} func (*DropRetentionPolicyStatement) node() {} func (*DropOrganizationStatement) node() {} func (*DropConversationStatement) node() {} func (*DropUserStatement) node() {} func (*GrantStatement) node() {} func (*GrantAdminStatement) node() {} func (*RevokeStatement) node() {} func (*RevokeAdminStatement) node() {} func (*SelectStatement) node() {} func (*SetPasswordUserStatement) node() {} func (*ShowGrantsForUserStatement) node() {} func (*ShowDevicesForUserStatement) node() {} func (*ShowServersStatement) node() {} func (*ShowDatabasesStatement) node() {} func (*ShowRetentionPoliciesStatement) node() {} func (*ShowConversationsStatement) node() {} func (*ShowOrganizationsStatement) node() {} func (*ShowOrganizationMembersStatement) node() {} func (*ShowStatsStatement) node() {} func (*ShowDiagnosticsStatement) node() {} func (*ShowUsersStatement) node() {} func (*BinaryExpr) node() {} func (*BooleanLiteral) node() {} func (*Call) node() {} func (*Dimension) node() {} func (Dimensions) node() {} func (*DurationLiteral) node() {} func (*Field) node() {} func (Fields) node() {} func (*Conversation) node() {} func (Conversations) node() {} func (*nilLiteral) node() {} func (*NumberLiteral) node() {} func (*ParenExpr) node() {} func (*RegexLiteral) node() {} func (*SortField) node() {} func (SortFields) node() {} func (Sources) node() {} func (*StringLiteral) node() {} func (*TimeLiteral) node() {} func (*VarRef) node() {} func (*Wildcard) node() {} // Expr represents an expression that can be evaluated to a value. type Expr interface { Node expr() } func (*BinaryExpr) expr() {} func (*BooleanLiteral) expr() {} func (*Call) expr() {} func (*DurationLiteral) expr() {} func (*nilLiteral) expr() {} func (*NumberLiteral) expr() {} func (*ParenExpr) expr() {} func (*RegexLiteral) expr() {} func (*StringLiteral) expr() {} func (*TimeLiteral) expr() {} func (*VarRef) expr() {} func (*Wildcard) expr() {} // Source represents a source of data for a statement. type Source interface { Node source() } func (*Conversation) source() {} // Sources represents a list of sources. type Sources []Source // String returns a string representation of a Sources array. func (a Sources) String() string { var buf bytes.Buffer ubound := len(a) - 1 for i, src := range a { _, _ = buf.WriteString(src.String()) if i < ubound { _, _ = buf.WriteString(", ") } } return buf.String() } // SortField represents a field to sort results by. type SortField struct { // Name of the field Name string // Sort order. Ascending bool } // String returns a string representation of a sort field func (field *SortField) String() string { var buf bytes.Buffer if field.Name == "" { _, _ = buf.WriteString(field.Name) _, _ = buf.WriteString(" ") } if field.Ascending { _, _ = buf.WriteString("ASC") } else { _, _ = buf.WriteString("DESC") } return buf.String() } // SortFields represents an ordered list of ORDER BY fields type SortFields []*SortField // String returns a string representation of sort fields func (a SortFields) String() string { fields := make([]string, 0, len(a)) for _, field := range a { fields = append(fields, field.String()) } return strings.Join(fields, ", ") } // Fields represents a list of fields. type Fields []*Field // String returns a string representation of the fields. func (ff Fields) String() string { var str []string for _, f := range ff { str = append(str, f.String()) } return strings.Join(str, ", ") } // Sort Interface for Fields func (ff Fields) Len() int { return len(ff) } func (ff Fields) Less(i, j int) bool { return ff[i].Name() < ff[j].Name() } func (ff Fields) Swap(i, j int) { ff[i], ff[j] = ff[j], ff[i] } // Field represents an expression retrieved from a select statement. type Field struct { Expr Expr Alias string } // Name returns the name of the field. Returns alias, if set. // Otherwise uses the function name or variable name. func (f *Field) Name() string { // Return alias, if set. if f.Alias != "" { return f.Alias } // Return the function name or variable name, if available. switch expr := f.Expr.(type) { case *Call: return expr.Name case *VarRef: return expr.Val } // Otherwise return a blank name. return "" } // String returns a string representation of the field. func (f *Field) String() string { if f.Alias == "" { return f.Expr.String() } return fmt.Sprintf("%s AS %s", f.Expr.String(), f.Alias) } // Dimensions represents a list of dimensions. type Dimensions []*Dimension // String returns a string representation of the dimensions. func (a Dimensions) String() string { var str []string for _, d := range a { str = append(str, d.String()) } return strings.Join(str, ", ") } // Normalize returns the interval and tag dimensions separately. // Returns 0 if no time interval is specified. // Returns an error if multiple time dimensions exist or if non-VarRef dimensions are specified. func (a Dimensions) Normalize() (time.Duration, []string, error) { var dur time.Duration var tags []string for _, dim := range a { switch expr := dim.Expr.(type) { case *Call: // Ensure the call is time() and it only has one duration argument. // If we already have a duration if expr.Name != "time" { return 0, nil, errors.New("only time() calls allowed in dimensions") } else if len(expr.Args) != 1 { return 0, nil, errors.New("time dimension expected one argument") } else if lit, ok := expr.Args[0].(*DurationLiteral); !ok { return 0, nil, errors.New("time dimension must have one duration argument") } else if dur != 0 { return 0, nil, errors.New("multiple time dimensions not allowed") } else { dur = lit.Val } case *VarRef: tags = append(tags, expr.Val) default: return 0, nil, errors.New("only time and tag dimensions allowed") } } return dur, tags, nil } // Dimension represents an expression that a select statement is grouped by. type Dimension struct { Expr Expr } // String returns a string representation of the dimension. func (d *Dimension) String() string { return d.Expr.String() } // VarRef represents a reference to a variable. type VarRef struct { Val string } // Call represents a function call. type Call struct { Name string Args []Expr } // String returns a string representation of the call. func (c *Call) String() string { // Join arguments. var str []string for _, arg := range c.Args { str = append(str, arg.String()) } // Write function name and args. return fmt.Sprintf("%s(%s)", c.Name, strings.Join(str, ", ")) } // Organizations represents a list of organizations type Organizations []*Organization // String returns a string representation of the organizations. func (oo Organizations) String() string { var str []string for _, o := range oo { str = append(str, o.String()) } return strings.Join(str, ", ") } // Organization represents a single organization used as a datasource. type Organization struct { Database string RetentionPolicy string Name string Regex *RegexLiteral } // String returns a string representation of the conversation. func (o *Organization) String() string { var buf bytes.Buffer if o.Database != "" { _, _ = buf.WriteString(`"`) _, _ = buf.WriteString(o.Database) _, _ = buf.WriteString(`".`) } if o.RetentionPolicy != "" { _, _ = buf.WriteString(`"`) _, _ = buf.WriteString(o.RetentionPolicy) _, _ = buf.WriteString(`"`) } if o.Database != "" || o.RetentionPolicy != "" { _, _ = buf.WriteString(`.`) } if o.Name != "" { _, _ = buf.WriteString(QuoteIdent(o.Name)) } else if o.Regex != nil { _, _ = buf.WriteString(o.Regex.String()) } return buf.String() } // Conversations represents a list of conversations. type Conversations []*Conversation // String returns a string representation of the conversations. func (a Conversations) String() string { var str []string for _, m := range a { str = append(str, m.String()) } return strings.Join(str, ", ") } // Conversation represents a single conversation used as a datasource. type Conversation struct { Database string RetentionPolicy string Name string Regex *RegexLiteral } // String returns a string representation of the conversation. func (m *Conversation) String() string { var buf bytes.Buffer if m.Database != "" { _, _ = buf.WriteString(`"`) _, _ = buf.WriteString(m.Database) _, _ = buf.WriteString(`".`) } if m.RetentionPolicy != "" { _, _ = buf.WriteString(`"`) _, _ = buf.WriteString(m.RetentionPolicy) _, _ = buf.WriteString(`"`) } if m.Database != "" || m.RetentionPolicy != "" { _, _ = buf.WriteString(`.`) } if m.Name != "" { _, _ = buf.WriteString(QuoteIdent(m.Name)) } else if m.Regex != nil { _, _ = buf.WriteString(m.Regex.String()) } return buf.String() } // BinaryExpr represents an operation between two expressions. type BinaryExpr struct { Op Token LHS Expr RHS Expr } // String returns a string representation of the binary expression. func (e *BinaryExpr) String() string { return fmt.Sprintf("%s %s %s", e.LHS.String(), e.Op.String(), e.RHS.String()) } // ParenExpr represents a parenthesized expression. type ParenExpr struct { Expr Expr } // String returns a string representation of the parenthesized expression. func (e *ParenExpr) String() string { return fmt.Sprintf("(%s)", e.Expr.String()) } // Wildcard represents a wild card expression. type Wildcard struct{} // String returns a string representation of the wildcard. func (e *Wildcard) String() string { return "*" } // CloneExpr returns a deep copy of the expression. func CloneExpr(expr Expr) Expr { if expr == nil { return nil } switch expr := expr.(type) { case *BinaryExpr: return &BinaryExpr{Op: expr.Op, LHS: CloneExpr(expr.LHS), RHS: CloneExpr(expr.RHS)} case *BooleanLiteral: return &BooleanLiteral{Val: expr.Val} case *DurationLiteral: return &DurationLiteral{Val: expr.Val} case *NumberLiteral: return &NumberLiteral{Val: expr.Val} case *ParenExpr: return &ParenExpr{Expr: CloneExpr(expr.Expr)} case *RegexLiteral: return &RegexLiteral{Val: expr.Val} case *StringLiteral: return &StringLiteral{Val: expr.Val} case *TimeLiteral: return &TimeLiteral{Val: expr.Val} case *VarRef: return &VarRef{Val: expr.Val} case *Wildcard: return &Wildcard{} } panic("unreachable") } // TimeRange returns the minimum and maximum times specified by an expression. // Returns zero times if there is no bound. func TimeRange(expr Expr) (min, max time.Time) { WalkFunc(expr, func(n Node) { if n, ok := n.(*BinaryExpr); ok { // Extract literal expression & operator on LHS. // Check for "time" on the left-hand side first. // Otherwise check for for the right-hand side and flip the operator. value, op := timeExprValue(n.LHS, n.RHS), n.Op if value.IsZero() { if value = timeExprValue(n.RHS, n.LHS); value.IsZero() { return } else if op == LT { op = GT } else if op == LTE { op = GTE } else if op == GT { op = LT } else if op == GTE { op = LTE } } // Update the min/max depending on the operator. // The GT & LT update the value by +/- 1µs not make them "not equal". switch op { case GT: if min.IsZero() || value.After(min) { min = value.Add(time.Microsecond) } case GTE: if min.IsZero() || value.After(min) { min = value } case LT: if max.IsZero() || value.Before(max) { max = value.Add(-time.Microsecond) } case LTE: if max.IsZero() || value.Before(max) { max = value } case EQ: if min.IsZero() || value.After(min) { min = value } if max.IsZero() || value.Before(max) { max = value } } } }) return } // Visitor can be called by Walk to traverse an AST hierarchy. // The Visit() function is called once per node. type Visitor interface { Visit(Node) Visitor } // Walk traverses a node hierarchy in depth-first order. func Walk(v Visitor, node Node) { if node == nil { return } if v = v.Visit(node); v == nil { return } switch n := node.(type) { case *BinaryExpr: Walk(v, n.LHS) Walk(v, n.RHS) case *Dimension: Walk(v, n.Expr) case Dimensions: for _, c := range n { Walk(v, c) } case *Field: Walk(v, n.Expr) case Fields: for _, c := range n { Walk(v, c) } case *ParenExpr: Walk(v, n.Expr) case *Query: Walk(v, n.Statements) case *SelectStatement: Walk(v, n.Fields) Walk(v, n.Sources) Walk(v, n.Condition) Walk(v, n.SortFields) case *ShowConversationsStatement: Walk(v, n.Sources) Walk(v, n.Condition) case SortFields: for _, sf := range n { Walk(v, sf) } case Sources: for _, s := range n { Walk(v, s) } case Statements: for _, s := range n { Walk(v, s) } } } // WalkFunc traverses a node hierarchy in depth-first order. func WalkFunc(node Node, fn func(Node)) { Walk(walkFuncVisitor(fn), node) } type walkFuncVisitor func(Node) func (fn walkFuncVisitor) Visit(n Node) Visitor { fn(n); return fn } // Rewriter can be called by Rewrite to replace nodes in the AST hierarchy. // The Rewrite() function is called once per node. type Rewriter interface { Rewrite(Node) Node } // Rewrite recursively invokes the rewriter to replace each node. // Nodes are traversed depth-first and rewritten from leaf to root. func Rewrite(r Rewriter, node Node) Node { switch n := node.(type) { case *Query: n.Statements = Rewrite(r, n.Statements).(Statements) case Statements: for i, s := range n { n[i] = Rewrite(r, s).(Statement) } case *SelectStatement: n.Fields = Rewrite(r, n.Fields).(Fields) n.Sources = Rewrite(r, n.Sources).(Sources) n.Condition = Rewrite(r, n.Condition).(Expr) case Fields: for i, f := range n { n[i] = Rewrite(r, f).(*Field) } case *Field: n.Expr = Rewrite(r, n.Expr).(Expr) case Dimensions: for i, d := range n { n[i] = Rewrite(r, d).(*Dimension) } case *Dimension: n.Expr = Rewrite(r, n.Expr).(Expr) case *BinaryExpr: n.LHS = Rewrite(r, n.LHS).(Expr) n.RHS = Rewrite(r, n.RHS).(Expr) case *ParenExpr: n.Expr = Rewrite(r, n.Expr).(Expr) } return r.Rewrite(node) } // RewriteFunc rewrites a node hierarchy. func RewriteFunc(node Node, fn func(Node) Node) Node { return Rewrite(rewriterFunc(fn), node) } type rewriterFunc func(Node) Node func (fn rewriterFunc) Rewrite(n Node) Node { return fn(n) } // Eval evaluates expr against a map. func Eval(expr Expr, m map[string]interface{}) interface{} { if expr == nil { return nil } switch expr := expr.(type) { case *BinaryExpr: return evalBinaryExpr(expr, m) case *BooleanLiteral: return expr.Val case *NumberLiteral: return expr.Val case *ParenExpr: return Eval(expr.Expr, m) case *StringLiteral: return expr.Val case *VarRef: return m[expr.Val] default: return nil } } func evalBinaryExpr(expr *BinaryExpr, m map[string]interface{}) interface{} { lhs := Eval(expr.LHS, m) rhs := Eval(expr.RHS, m) // Evaluate if both sides are simple types. switch lhs := lhs.(type) { case bool: rhs, _ := rhs.(bool) switch expr.Op { case AND: return lhs && rhs case OR: return lhs || rhs case EQ: return lhs == rhs case NEQ: return lhs != rhs } case float64: rhs, _ := rhs.(float64) switch expr.Op { case EQ: return lhs == rhs case NEQ: return lhs != rhs case LT: return lhs < rhs case LTE: return lhs <= rhs case GT: return lhs > rhs case GTE: return lhs >= rhs case ADD: return lhs + rhs case SUB: return lhs - rhs case MUL: return lhs * rhs case DIV: if rhs == 0 { return float64(0) } return lhs / rhs } case int64: // we parse all number literals as float 64, so we have to convert from // an interface to the float64, then cast to an int64 for comparison rhsf, _ := rhs.(float64) rhs := int64(rhsf) switch expr.Op { case EQ: return lhs == rhs case NEQ: return lhs != rhs case LT: return lhs < rhs case LTE: return lhs <= rhs case GT: return lhs > rhs case GTE: return lhs >= rhs case ADD: return lhs + rhs case SUB: return lhs - rhs case MUL: return lhs * rhs case DIV: if rhs == 0 { return int64(0) } return lhs / rhs } case string: rhs, _ := rhs.(string) switch expr.Op { case EQ: return lhs == rhs case NEQ: return lhs != rhs } } return nil }
package main import ( "fmt" "math" "os" "strconv" "strings" ) var messageChan chan string = make(chan string) func main() { //calculateGivenCipherText("2081 2182") cipherText := encryptMessageRSA("stop this madness", 43, 59, 13) fmt.Println(cipherText) //cipherText = strings.Replace(cipherText, " ", "", -1) //fmt.Println(cipherText) //return sliceOfPrimes := primeTester(100) fmt.Println(sliceOfPrimes) //this contains all possible pairs of all prime numbers up to 100 where there is no pair (x,y) where x = y primePairs := generateAllUniquePrimePairs(sliceOfPrimes) fmt.Println(primePairs) //return //this contains all possible letter pairings that can be encrypted into a byte for lowercase a-z letterPairs := generateAllLetterPairings() fmt.Println(letterPairs) for num, primeSlice := range primePairs { for i := 0; i < len(primeSlice); i++ { //modulus := num * primeSlice[i] if num == 43 && primeSlice[i] == 59 { fmt.Println("made it correctly") for char, letterSlice := range letterPairs { for j := 0; j < len(letterSlice); j++ { byteString := char + letterSlice[j] gcdSlice := getGCDRelativelyPrimes(num, primeSlice[i]) for s:= 0; s < len(gcdSlice); s++ { testCipher := encryptMessageRSA(byteString, num, primeSlice[i], gcdSlice[s]) chunkFromCipher := string(cipherText[0]) + string(cipherText[1]) + string(cipherText[2]) + string(cipherText[3]) // if testCipher == chunkFromCipher { fmt.Println("CIPHERS" + testCipher + chunkFromCipher) plaintext := make([]string, 1, 1) //keys are the order in which the byte appears in the cipher text starting with 0 for first one combosDecryption := make(map[int][]string) matchLetters := getMapOpposite() //fmt.Println(testCipher + " " + strconv.Itoa(num) + " " + strconv.Itoa(primeSlice[i])+ " " + strconv.Itoa(gcdSlice[s])) if num < primeSlice[i] { //fmt.Println("OKCheck") factoredMap := factorize(gcdSlice[s], (num - 1) *(primeSlice[i] - 1)) //factoredMap := factorize(13, 2436) fmt.Println(factoredMap) if factoredMap == nil { continue } //fmt.Println("OK2") inverseValue := factoredMap[gcdSlice[s]] //inverseValue := factoredMap[13] fmt.Println("INVERSE") fmt.Println(inverseValue) //fmt.Println("OK3") for c := 0; c < len(cipherText); c = c + 5 { fmt.Println("C" + strconv.Itoa(c)) check1, _ := strconv.Atoi(string(cipherText[c])) check2, _ := strconv.Atoi(string(cipherText[c + 1])) check3, _ := strconv.Atoi(string(cipherText[c + 2])) check4, _ := strconv.Atoi(string(cipherText[c + 3])) //fmt.Println("OK3") byteFromCipherString := strconv.Itoa(check1) + strconv.Itoa(check2) + strconv.Itoa(check3) + strconv.Itoa(check4) fmt.Printf("%s", byteFromCipherString) if strconv.Itoa(check1) == "0" { byteFromCipherString = strconv.Itoa(check2) + strconv.Itoa(check3) + strconv.Itoa(check4) } fmt.Println(byteFromCipherString) //fmt.Println(byteFromCipherString) byteFromCipherInt, _ := strconv.Atoi(byteFromCipherString) fmt.Printf("%s11", byteFromCipherInt) byteFromCipherInt = modExpon(byteFromCipherInt, inverseValue, num * primeSlice[i]) hasBeenFixed := false /* if byteFromCipherInt == 0 { byteFromCipherInt = 00 hasBeenFixed = true } */ fmt.Printf("%sCC", byteFromCipherInt) //fmt.Printf("%s", byteFromCipherInt) //byteFromCipherInt = byteFromCipherInt % (num * primeSlice[i]) //byteFromCipherIntS := strconv.Itoa(byteFromCipherInt) //fmt.Println(byteFromCipherIntS) //byteFromCipherString := strconv.Itoa(byteFromCipherInt) var char1 string var char2 string byteFromCipherString = strconv.Itoa(byteFromCipherInt) combosDecryption[c/5] = allpossibleDecryptions(byteFromCipherString) fmt.Printf("%sCCCC", byteFromCipherString) if len(byteFromCipherString) == 2 && !hasBeenFixed { fmt.Println("check") //byteFromCipherString = "0" + byteFromCipherString fmt.Println(byteFromCipherString) hasBeenFixed = true } if len(byteFromCipherString) == 1 && !hasBeenFixed { fmt.Println("ERR") fmt.Println(byteFromCipherString) byteFromCipherString = "260" + byteFromCipherString os.Exit(1) } /* for len(byteFromCipherString) < 3 { byteFromCipherString = "0" + byteFromCipherString } */ if len(byteFromCipherString) == 2 { char1 = string(byteFromCipherString[0]) char2 = string(byteFromCipherString[1]) } if len(byteFromCipherString) == 3 { char1 = string(byteFromCipherString[0]) fmt.Printf("%sRR", char1) char2 = string(byteFromCipherString[1]) + string(byteFromCipherString[2]) if string(char2[0]) == "0" { char2 = string(char2[1]) } }else if len(byteFromCipherString) == 4{ char1 = string(byteFromCipherString[0]) + string(byteFromCipherString[1]) if string(char1[0]) == "0" { char1 = string(char1[1]) } char2 = string(byteFromCipherString[2]) + string(byteFromCipherString[3]) if string(char2[0]) == "0" { char2 = string(char2[1]) } } fmt.Println(char1) fmt.Println("BREAK") fmt.Println(char2) fmt.Println(matchLetters[char1]) fmt.Println(matchLetters[char2]) plaintext = append(plaintext, matchLetters[char1]) plaintext = append(plaintext, matchLetters[char2]) //fmt.Println(matchLetters[char1] + matchLetters[char2]) } decodeFromAllCombos(combosDecryption , 0, "", messageChan) go recursionMessage(messageChan) fmt.Println(plaintext[1:]) //decoded := &plaintext //shiftDecodedSliceEveryPosition(decoded) }else{ fmt.Println("NEVER") factoredMap := factorize((primeSlice[i] - 1), (num-1)) inverseValue := factoredMap[primeSlice[i] - 1] for c := 0; c < len(cipherText); c = c + 5 { if inverseValue == 937 { fmt.Println(cipherText) } check1, _ := strconv.Atoi(string(cipherText[c])) check2, _ := strconv.Atoi(string(cipherText[c + 1])) check3, _ := strconv.Atoi(string(cipherText[c + 2])) check4, _ := strconv.Atoi(string(cipherText[c + 3])) byteFromCipherString := strconv.Itoa(check1) + strconv.Itoa(check2) + strconv.Itoa(check3) + strconv.Itoa(check4) fmt.Println(byteFromCipherString) byteFromCipherInt, _ := strconv.Atoi(byteFromCipherString) byteFromCipherInt = myExponFunc(byteFromCipherInt, inverseValue) byteFromCipherInt = byteFromCipherInt % (num * primeSlice[i]) //byteFromCipherString := strconv.Itoa(byteFromCipherInt) char1 := "" char2 := "" /* minusSign := string(byteFromCipherString[0]) if minusSign == "-" { if len(byteFromCipherString) == 4 { char1 = string(byteFromCipherString[1]) char2 = string(byteFromCipherString[2]) + string(byteFromCipherString[3]) if string(char2[0]) == "0" { char2 = string(char2[1]) } }else{ char1 = string(byteFromCipherString[1]) + string(byteFromCipherString[2]) if string(char1[0]) == "0" { char1 = string(char1[1]) } char2 = string(byteFromCipherString[3]) + string(byteFromCipherString[4]) if string(char2[0]) == "0" { char2 = string(char2[1]) } }else */ if len(byteFromCipherString) == 3 { char1 = string(byteFromCipherString[1]) fmt.Println(char1) char2 = string(byteFromCipherString[2]) + string(byteFromCipherString[3]) if string(char2[0]) == "0" { char2 = string(char2[1]) } }else{ char1 = string(byteFromCipherString[1]) if string(char1[0]) == "0" { char1 = string(char1[1]) } char2 = string(byteFromCipherString[2]) + string(byteFromCipherString[3]) if string(char2[0]) == "0" { char2 = string(char2[1]) } } plaintext = append(plaintext, matchLetters[char1] + matchLetters[char2]) //fmt.Println(matchLetters[char1] + matchLetters[char2]) } fmt.Println(plaintext[1:]) } } } } } } } } } func recursionMessage(messageChan chan string){ message := <- messageChan if message == "done" { return }else{ fmt.Println(message) go recursionMessage(messageChan) } } func generateAllLetterPairings() map[string][]string { letterPairs := make(map[string][]string) alphabet := "abcdefghijklmnopqrstuvwxyz " for i := 0; i < len(alphabet); i++ { char := string(alphabet[i]) sliceToAdd := make([]string, 1, 1) for j := 0; j < len(alphabet); j++ { charAdd := string(alphabet[j]) sliceToAdd = append(sliceToAdd, charAdd) } letterPairs[char] = sliceToAdd[1:] } return letterPairs } func calculateGivenCipherText(cipherText string) { //get the number of bytes we are dealing with //ignore spaces and count bytes charCount := 0 byteCount := 0 for i := 0; i < len(cipherText); i++ { char := string(cipherText[i]) if char != " " { charCount++ } if charCount == 4 { byteCount++ charCount = 0 } } } func getMapOpposite() map[string]string{ alphabet := make(map[string]string) alphabet["0"] = "a" alphabet["1"] = "b" alphabet["2"] = "c" alphabet["3"] = "d" alphabet["4"] = "e" alphabet["5"] = "f" alphabet["6"] = "g" alphabet["7"] = "h" alphabet["8"] = "i" alphabet["9"] = "j" alphabet["10"] = "k" alphabet["11"] = "l" alphabet["12"] = "m" alphabet["13"] = "n" alphabet["14"] = "o" alphabet["15"] = "p" alphabet["16"] = "q" alphabet["17"] = "r" alphabet["18"] = "s" alphabet["19"] = "t" alphabet["20"] = "u" alphabet["21"] = "v" alphabet["22"] = "w" alphabet["23"] = "x" alphabet["24"] = "y" alphabet["25"] = "z" alphabet["26"] = " " return alphabet } func getMap() map[string]int{ alphabet := make(map[string]int) alphabet["a"] = 0 alphabet["b"] = 1 alphabet["c"] = 2 alphabet["d"] = 3 alphabet["e"] = 4 alphabet["f"] = 5 alphabet["g"] = 6 alphabet["h"] = 7 alphabet["i"] = 8 alphabet["j"] = 9 alphabet["k"] = 10 alphabet["l"] = 11 alphabet["m"] = 12 alphabet["n"] = 13 alphabet["o"] = 14 alphabet["p"] = 15 alphabet["q"] = 16 alphabet["r"] = 17 alphabet["s"] = 18 alphabet["t"] = 19 alphabet["u"] = 20 alphabet["v"] = 21 alphabet["w"] = 22 alphabet["x"] = 23 alphabet["y"] = 24 alphabet["z"] = 25 alphabet[" "] = 26 return alphabet } func encryptMessageRSA(message string, p int, q int, e int) string{ letterMap := getMap() evenOdd := len(message) % 2 if evenOdd == 0 { }else{ message = message + " " } cipherText := "" for i := 0; i < (len(message)/2); i++ { char1 := string(message[i*2]) char2 := string(message[(i*2) + 1]) //fmt.Println(char1) //fmt.Println(char2) char1Int := letterMap[char1] char2Int := letterMap[char2] byteString := strconv.Itoa(char1Int) + strconv.Itoa(char2Int) byteStringInt, _ := strconv.Atoi(byteString) cipherByte := modExpon(byteStringInt, e, (p * q)) cipherByteString := strconv.Itoa(cipherByte) if len(cipherByteString) == 3 { cipherByteString = "0" + cipherByteString } if len(cipherText) == 0 { cipherText = cipherByteString }else{ cipherText = cipherText + " " + cipherByteString } } return cipherText } func myExponFunc(num int, exp int) int { sum := num if (exp == 0) { return 1 } if exp < 0 { /* for i := 0; i > exp + 1; i = i - 1 { sum = sum * num } */ return 0 } for i := 0; i < exp - 1; i++ { sum = sum * num } return sum } func modExpon(base int, exponent int, mod int) int { if exponent < 0 { return 0 % mod } binaryExpon := fmt.Sprintf("%b", exponent) result := 1 base = base % mod for i := 0; i < len(binaryExpon); i++ { bit, err := strconv.Atoi(binaryExpon[((len(binaryExpon) - 1 - i)):(len(binaryExpon) - i)]) if err != nil { fmt.Println("ERROR PARSING BINARY STRING PROGRAM TERMINATING") fmt.Printf("%s", err) os.Exit(1) } if bit == 1 { result = (result * base) % mod base = myExponFunc(base, 2) % mod }else if bit == 0{ base = myExponFunc(base, 2) % mod } } return result } func primeTester(maxPrime int) []int{ primeSlice := make([]int, 1, 1) for i := 2; i < maxPrime + 1; i++ { currentNum := float64(i) minimumToCheck := math.Sqrt(currentNum) minimumToCheck = math.Round(minimumToCheck) castToInt := int(minimumToCheck) isPrime := checkIfPrime(castToInt, i) if isPrime { primeSlice = append(primeSlice[0:], i) } } return primeSlice[1:] } func checkIfPrime(minimumValue int, checkAgainst int) bool { for i := 2; i < minimumValue + 1; i++ { remainder := checkAgainst % i if remainder == 0 { return false } } return true } func generateAllUniquePrimePairs(primeCandidates []int) map[int][]int { allPairs := make(map[int][]int) var sliceWithoutCheckVal []int for i := 0; i < len(primeCandidates); i++ { //get the prime number to pair with others checkPrime := primeCandidates[i] sliceWithoutCheckVal = nil sliceWithoutCheckVal = primeCandidates[i+1:] sliceAppendTo := make([]int, 1, 1) for j := 0; j < len(sliceWithoutCheckVal); j++ { sliceAppendTo = append(sliceAppendTo[0:], sliceWithoutCheckVal[j]) } allPairs[checkPrime] = sliceAppendTo[1:] } return allPairs } func getGCDRelativelyPrimes(p int, q int) []int { pMinus1 := p - 1 qMinus1 := q - 1 product := pMinus1 * qMinus1 //fmt.Println(product) contendersForE := make([]int, product, product) //start at 2 because 1 is obviously already a contender for i := 2; i < product; i++ { addBool, num := calcGCD(i, product) if addBool { contendersForE = append(contendersForE, num) } } return contendersForE[product:] } func calcGCD(e int, n int) (bool, int) { remainder := 1 divisor := e main := n initialE := e // main = 2436 divisor = 3 remainder = 1 quotient = 0 for remainder != 0 { remainder = main % divisor if remainder == 0 && divisor == 1 { return true, initialE } main = divisor divisor = remainder } return false, -1 } func factorize(numSmall int, numLarge int) map[int]int{ remainderMap := make(map[int][]int) valuesMapL := make(map[int]int) valuesMapR := make(map[int]int) valuesMapL[numLarge] = 0 valuesMapL[numSmall] = 0 valuesMapR[numLarge] = 0 valuesMapR[numSmall] = 0 numToDivide := numLarge numDivisor := numSmall timesItFits := 0 remainder := 1 row := 1 for remainder != 0 { timesItFits = numToDivide / numDivisor valuesMapL[timesItFits] = 0 valuesMapL[numToDivide % numDivisor] = 0 valuesMapR[timesItFits] = 0 valuesMapR[numToDivide % numDivisor] = 0 remainderMap[row] = []int{numToDivide, timesItFits, numDivisor, (numToDivide % numDivisor)} remainder = numToDivide % numDivisor numToDivide = numDivisor numDivisor = remainder row++ } row = row - 1 totalRows := row //fmt.Println(valuesMapL) //fmt.Println(valuesMapR) //fmt.Println(remainderMap) leftSideDone := false //second to last row here row = row - 1 //fmt.Println(row) //set initial left side valuesMapL[remainderMap[row][0]] = 1 valuesMapL[remainderMap[row][2]] = -1 //fmt.Println("initialVals") //fmt.Println(valuesMapL) bool1L := false //focusKey := false key := 0 factorToTrack := 0 valuesMapLCopy := make(map[int]int) affected := make([]int, 0, 0) count := 0 //1 is the special case because if onceOnly := true for !leftSideDone { row = row - 2 //fmt.Println(row) //fmt.Printf("%s", len(remainderMap)) //fmt.Println(remainderMap) if len(remainderMap) <= 1 { fmt.Println("major error") return nil } if len(remainderMap) <= 3 { fmt.Println("specialCase") specialCase := make(map[int]int) smallNumFrequency := remainderMap[1][1] + remainderMap[2][2] fmt.Println(smallNumFrequency) specialCase[numSmall] = smallNumFrequency specialCase[numLarge] = 0 fmt.Println("specialCase") return specialCase } if onceOnly { valuesMapL[remainderMap[row][0]] = 1 valuesMapL[remainderMap[row][2]] = -(remainderMap[row][1]) valuesMapL[remainderMap[row + 2][0]] = 0 //fmt.Println("initialVals") //fmt.Println(valuesMapL) //fmt.Printf("%s", row) onceOnly = false } for keyMap, val := range valuesMapL { //fmt.Println("TEST") //fmt.Println(valuesMapL) if (keyMap != numSmall && keyMap != numLarge) && (val > 0 || val < 0) { for key4, val4 := range remainderMap { if val4[3] == keyMap { row = key4 } } count ++ //fmt.Println(valuesMapL) bool1L = true //focusKey = true //fmt.Println(key) key = keyMap factorToTrack = valuesMapL[key] //fmt.Println(factorToTrack) //row = row + 1 valuesMapLCopy = nil valuesMapLCopy = make(map[int]int) for keyMap2, val2 := range valuesMapL { valuesMapLCopy[keyMap2] = val2 } valuesMapL[keyMap] = 0 valuesMapLCopy, affected = factorUpValOfFocus(numSmall, numLarge, factorToTrack, valuesMapLCopy, remainderMap, row, keyMap) //fmt.Println("BEFORE2") // fmt.Println(valuesMapL) // fmt.Println(len(affected)) for i := 0; i < len(affected); i++ { valuesMapL[affected[i]] = valuesMapL[affected[i]] + valuesMapLCopy[affected[i]] } if checkReturn(valuesMapL, numSmall, numLarge) { return valuesMapL } /* for key3, _ := range valuesMapLCopy { valuesMapL[key3] = valuesMapL[key3] + valuesMapLCopy[key3] } */ //fmt.Println("AFTER2") //fmt.Println(valuesMapL) //fmt.Println(valuesMapL) if count == 1000 { return valuesMapL } break } } if bool1L { bool1L = false continue }else{ leftSideDone = true } } row = totalRows return valuesMapL } func factorUpValOfFocus(numSmall int, numLarge int, factorToTrack int, copyMap map[int]int, remainderMap map[int][]int, row int, valOfFocus int) (map[int]int, []int) { restart := true for key, val := range remainderMap { if val[3] == valOfFocus { row = key } } for key0, _ := range copyMap { if key0 != valOfFocus { copyMap[key0] = 0 } } //fmt.Printf("%s", factorToTrack) //fmt.Println("BEFORE") //fmt.Println(copyMap) keysAffected := make([]int, 1, 1) for restart { //fmt.Println("RESTART") //fmt.Println(remainderMap[row][0]) //fmt.Println(remainderMap[row][2]) //fmt.Println(remainderMap[row + 2][0]) keysAffected = append(keysAffected, remainderMap[row][0]) copyMap[remainderMap[row][0]] = copyMap[remainderMap[row][0]] + 1 keysAffected = append(keysAffected, remainderMap[row][2]) copyMap[remainderMap[row][2]] = copyMap[remainderMap[row][2]] -(remainderMap[row][1]) keysAffected = append(keysAffected, remainderMap[row + 2][0]) copyMap[remainderMap[row + 2][0]] = 0 onlyTwoOfInterest := false for key, val := range copyMap { if key != numSmall && key != numLarge && (val > 0 || val < 0) && key != 2 && false { onlyTwoOfInterest = false break } onlyTwoOfInterest = true if onlyTwoOfInterest { //fmt.Println("After") //fmt.Println(copyMap) for k, _ := range copyMap { copyMap[k] = copyMap[k] * factorToTrack } return copyMap, keysAffected[1:] } } } return nil, nil } func checkReturn(checkMap map[int]int, numSmall int, numLarge int ) bool { canReturn := true for key, val := range checkMap { if key != numSmall && key != numLarge && val != 0 { canReturn = false } } return canReturn } func shiftDecodedSliceEveryPosition(slice *[]string) { copySlice := *slice checkForPlainText(copySlice) copySlice = copySlice[1:] letterToNum := getMap() numToLetter := getMapOpposite() for j := 0; j < 27; j++ { for i := 0; i < len(copySlice); i++ { letter := copySlice[i] valueOfLetterInt := letterToNum[letter] //valueOfLetterInt, _ := strconv.Atoi(valueOfLetter) valueOfLetterInt++ if valueOfLetterInt == 27 { valueOfLetterInt = 0 } stringLetterNum := strconv.Itoa(valueOfLetterInt) copySlice[i] = numToLetter[stringLetterNum] } checkForPlainText(copySlice) fmt.Print(copySlice) } } func checkForPlainText(slice []string) { copySlice := slice wholeSLice := "" for i := 0; i < len(copySlice); i++ { wholeSLice = wholeSLice + copySlice[i] } if strings.Contains(wholeSLice, "s") && strings.Contains(wholeSLice, "t") && strings.Contains(wholeSLice, "o") && strings.Contains(wholeSLice, "p") && strings.Contains(wholeSLice, "t") && strings.Contains(wholeSLice, "h") && strings.Contains(wholeSLice, "i") && strings.Contains(wholeSLice, "s") && strings.Contains(wholeSLice, "m") && strings.Contains(wholeSLice, "a") && strings.Contains(wholeSLice, "d") && strings.Contains(wholeSLice, "n") && strings.Contains(wholeSLice, "e") && strings.Contains(wholeSLice, "s") && strings.Contains(wholeSLice, "s") { fmt.Println(wholeSLice) fmt.Println("Message Decrypted") os.Exit(1) } } func allpossibleDecryptions(decryptedByte string) []string { //allCombos := make([]string, 1, 1) if len(decryptedByte) == 1 { combo1 := "0" + decryptedByte combo2 := decryptedByte + "0" combo3 := decryptedByte + "0" + "0" combo4 := "0" + decryptedByte + "0" combo5 := "0" + "0" + decryptedByte combo6 := decryptedByte + "0" + "0" + "0" combo7 := "0" + decryptedByte + "0" + "0" combo8 := "0" + "0" + decryptedByte + "0" combo9 := "0" + "0" + "0" + decryptedByte return []string{combo1, combo2, combo3, combo4, combo5, combo6, combo7, combo8, combo9} }else if len(decryptedByte) == 2{ char1 := string(decryptedByte[0]) char2 := string(decryptedByte[1]) combo1 := char1 + char2 combo2 := "0" + char1 + char2 combo3 := char1 + "0" + char2 combo4 := char1 + char2 + "0" combo5 := "0" + "0" + char1 + char2 combo6 := "0" + char1 + "0" + char2 combo7 := "0" + char1 + char2 + "0" combo8 := char1 + "0" + char2 + "0" combo9 := char1 + "0" + "0" + char2 combo10 := char1 + char2 + "0" + "0" return []string{combo1, combo2, combo3, combo4, combo5, combo6, combo7, combo8, combo9, combo10} }else if len(decryptedByte) == 3 { char1 := string(decryptedByte[0]) char2 := string(decryptedByte[1]) char3 := string(decryptedByte[2]) combo1 := char1 + char2 + char3 combo2 := "0" + char1 + char2 + char3 combo3 := char1 + "0" + char2 + char3 combo4 := char1 + char2 + "0" + char3 combo5 := char1 + char2 + char3 + "0" return []string{combo1, combo2, combo3, combo4, combo5} }else if len(decryptedByte) == 4 { return []string{decryptedByte} } return nil } func decodeFromAllCombos(allCombos map[int][]string, timesAdded int, finalString string, messageChan chan string) { fmt.Printf("%slength", len(allCombos)) if timesAdded == len(allCombos) { messageChan <- decrypt(finalString) messageChan <- "done" return } timesAddedPlus := timesAdded + 1 sliceToExpand := allCombos[timesAdded] for i := 0; i < len(sliceToExpand); i++{ go decodeFromAllCombos(allCombos, timesAddedPlus, finalString + sliceToExpand[i], messageChan) } } func decrypt(byteFromCipherString string) string{ plaintext := "" matchLetters := getMapOpposite() for c := 0; c < len(byteFromCipherString); c++ { char1 := string(byteFromCipherString[0]) + string(byteFromCipherString[1]) if string(char1[0]) == "0" { char1 = string(char1[1]) } char2 := string(byteFromCipherString[2]) + string(byteFromCipherString[3]) if string(char2[0]) == "0" { char2 = string(char2[1]) } char1 = matchLetters[char1] char2 = matchLetters[char2] plaintext = plaintext + char1 + char2 } return plaintext }
package e2e import ( "testing" ) func Test_Connect(t *testing.T) { c := newWssConnection() defer c.Con.Close() } func Test_Reconnect(t *testing.T) { c := newWssConnection() defer c.Con.Close() c = newWssConnectionWithArgs(DefaultWssEndpoint, c.PlayerId) defer c.Con.Close() }
package game type Manager struct { Games map[string]*Player Players map[string]*Player }
package karatechop // SecondRecursiveChop implements a recursive chop method type SecondRecursiveChop struct{} // Chop searches the target in the sorted array source func (rc *SecondRecursiveChop) Chop(target int, source []int) int { mid := len(source) / 2 max := len(source) - 1 return rc.half(mid, max, target, source) } // half searches the target at mid recursivly in sorted array source // it divides the search area by two at each call func (rc *SecondRecursiveChop) half(mid, max, target int, source []int) int { if mid > max { return -1 } if source[mid] == target { return mid } else if source[mid] < target { return rc.half((mid+(max-mid)/2)+1, max, target, source) } else { return rc.half(mid/2, mid-1, target, source) } }
package client import ( "fmt" "encoding/json" "strings" "tezos-contests.izibi.com/tc-node/sse" ) type Event struct { Channel string `json:"channel"` Payload string `json:"payload"` } type SystemEvent struct { Payload string } type EndOfGameEvent struct { Reason string } type NewBlockEvent struct { Hash string } func (cl *client) Connect() (<-chan interface{}, error) { if cl.eventChannel != nil { panic("Connect() must only be called once!") } key, err := cl.remote.NewStream() if err != nil { return nil, err } evs, err := sse.Connect(fmt.Sprintf("%s/Events/%s", cl.remote.Base, key)) if err != nil { return nil, err } cl.eventsKey = key ech := make(chan interface{}) go func() { defer evs.Close() for { msg := <-evs.C if msg == "" { break } var ev Event err = json.Unmarshal([]byte(msg), &ev) if err != nil { /* XXX report bad event */ continue } if ev.Channel == "system" { ech <- SystemEvent{Payload: ev.Payload} continue } if ev.Channel == cl.gameChannel { var parts = strings.Split(ev.Payload, " ") if len(parts) == 0 { continue } switch parts[0] { case "end": // ["end", reason] ech <- EndOfGameEvent{Reason: parts[1]} case "block": // ["block", hash] ech <- NewBlockEvent{Hash: parts[1]} case "ping": // ["ping" payload] /* Perform PONG request directly, because the worker might be busy doing the PING. */ var ids = make([]uint32, len(cl.bots)) for i, bot := range cl.bots { ids[i] = bot.Id } err = cl.remote.Pong(cl.game.Key, parts[1], ids) if err != nil { ech<- err } } } } }() cl.eventChannel = ech return ech, nil } func (cl *client) subscribe(name string) error { err := cl.remote.Subscribe(cl.eventsKey, []string{name}) if err != nil { return err } return nil }
package main import ( "fmt" ) func main() { s := sum() fmt.Println("The total amount is:", s) } func sum(s ...int) int { fmt.Println(s) sum := 0 for i, v := range s { sum += v fmt.Println("Index position number:", i, "Now adding ", v, "Total became: ", sum) } fmt.Println("The total amount is:", sum) return sum }
// Copyright 2019 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package syncer_test import ( "context" "fmt" "runtime" "testing" "time" "github.com/pingcap/errors" . "github.com/pingcap/tidb/ddl" "github.com/pingcap/tidb/ddl/syncer" util2 "github.com/pingcap/tidb/ddl/util" "github.com/pingcap/tidb/infoschema" "github.com/pingcap/tidb/parser/terror" "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/store/mockstore" "github.com/pingcap/tidb/util" "github.com/stretchr/testify/require" "go.etcd.io/etcd/api/v3/mvccpb" clientv3 "go.etcd.io/etcd/client/v3" "go.etcd.io/etcd/server/v3/etcdserver" "go.etcd.io/etcd/tests/v3/integration" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) const minInterval = 10 * time.Nanosecond // It's used to test timeout. const testLease = 5 * time.Millisecond func TestSyncerSimple(t *testing.T) { variable.EnableMDL.Store(false) if runtime.GOOS == "windows" { t.Skip("integration.NewClusterV3 will create file contains a colon which is not allowed on Windows") } integration.BeforeTestExternal(t) origin := syncer.CheckVersFirstWaitTime syncer.CheckVersFirstWaitTime = 0 defer func() { syncer.CheckVersFirstWaitTime = origin }() store, err := mockstore.NewMockStore() require.NoError(t, err) defer func() { require.NoError(t, store.Close()) }() cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1}) defer cluster.Terminate(t) cli := cluster.RandClient() ctx, cancel := context.WithCancel(context.Background()) defer cancel() ic := infoschema.NewCache(2) ic.Insert(infoschema.MockInfoSchemaWithSchemaVer(nil, 0), 0) d := NewDDL( ctx, WithEtcdClient(cli), WithStore(store), WithLease(testLease), WithInfoCache(ic), ) go func() { require.NoError(t, d.OwnerManager().CampaignOwner()) }() defer d.OwnerManager().Cancel() // for init function require.NoError(t, d.SchemaSyncer().Init(ctx)) resp, err := cli.Get(ctx, util2.DDLAllSchemaVersions, clientv3.WithPrefix()) require.NoError(t, err) defer d.SchemaSyncer().Close() key := util2.DDLAllSchemaVersions + "/" + d.OwnerManager().ID() checkRespKV(t, 1, key, syncer.InitialVersion, resp.Kvs...) ic2 := infoschema.NewCache(2) ic2.Insert(infoschema.MockInfoSchemaWithSchemaVer(nil, 0), 0) d1 := NewDDL( ctx, WithEtcdClient(cli), WithStore(store), WithLease(testLease), WithInfoCache(ic2), ) go func() { require.NoError(t, d1.OwnerManager().CampaignOwner()) }() defer d1.OwnerManager().Cancel() require.NoError(t, d1.SchemaSyncer().Init(ctx)) defer d.SchemaSyncer().Close() // for watchCh var wg util.WaitGroupWrapper currentVer := int64(123) var checkErr string wg.Run(func() { select { case resp := <-d.SchemaSyncer().GlobalVersionCh(): if len(resp.Events) < 1 { checkErr = "get chan events count less than 1" return } checkRespKV(t, 1, util2.DDLGlobalSchemaVersion, fmt.Sprintf("%v", currentVer), resp.Events[0].Kv) case <-time.After(3 * time.Second): checkErr = "get update version failed" return } }) // for update latestSchemaVersion require.NoError(t, d.SchemaSyncer().OwnerUpdateGlobalVersion(ctx, currentVer)) wg.Wait() require.Equal(t, "", checkErr) // for CheckAllVersions childCtx, cancel := context.WithTimeout(ctx, 200*time.Millisecond) require.Error(t, d.SchemaSyncer().OwnerCheckAllVersions(childCtx, 0, currentVer)) cancel() // for UpdateSelfVersion require.NoError(t, d.SchemaSyncer().UpdateSelfVersion(context.Background(), 0, currentVer)) require.NoError(t, d1.SchemaSyncer().UpdateSelfVersion(context.Background(), 0, currentVer)) childCtx, cancel = context.WithTimeout(ctx, minInterval) defer cancel() err = d1.SchemaSyncer().UpdateSelfVersion(childCtx, 0, currentVer) require.True(t, isTimeoutError(err)) // for CheckAllVersions require.NoError(t, d.SchemaSyncer().OwnerCheckAllVersions(context.Background(), 0, currentVer-1)) require.NoError(t, d.SchemaSyncer().OwnerCheckAllVersions(context.Background(), 0, currentVer)) childCtx, cancel = context.WithTimeout(ctx, minInterval) defer cancel() err = d.SchemaSyncer().OwnerCheckAllVersions(childCtx, 0, currentVer) require.True(t, isTimeoutError(err)) // for Close resp, err = cli.Get(context.Background(), key) require.NoError(t, err) currVer := fmt.Sprintf("%v", currentVer) checkRespKV(t, 1, key, currVer, resp.Kvs...) d.SchemaSyncer().Close() resp, err = cli.Get(context.Background(), key) require.NoError(t, err) require.Len(t, resp.Kvs, 0) } func isTimeoutError(err error) bool { return terror.ErrorEqual(err, context.DeadlineExceeded) || status.Code(errors.Cause(err)) == codes.DeadlineExceeded || terror.ErrorEqual(err, etcdserver.ErrTimeout) } func checkRespKV(t *testing.T, kvCount int, key, val string, kvs ...*mvccpb.KeyValue) { require.Len(t, kvs, kvCount) if kvCount == 0 { return } kv := kvs[0] require.Equal(t, key, string(kv.Key)) require.Equal(t, val, string(kv.Value)) }
package main import ( "bufio" "fmt" "io" "os" "strconv" "strings" ) func caesarCipher(s string, k int32) string { var i, j int32 var res string //j is resultant shifting if k >= 26 { j = k % 26 } else { j = k } for i = 0; i < int32(len(s)); i++ { if (int(s[i]) >= 65 && int(s[i]) <= 90) || (int(s[i]) >= 97 && int(s[i]) <= 122) { c := int32(s[i]) + j if c > 90 && int(s[i]) < 97 { c -= 26 } else if c > 122 { c -= 26 } x := string(rune(c)) res += x } else { res += string(s[i]) } } return res } func main() { reader := bufio.NewReaderSize(os.Stdin, 1024*1024) stdout, err := os.Create(os.Getenv("OUTPUT_PATH")) checkError(err) defer stdout.Close() writer := bufio.NewWriterSize(stdout, 1024*1024) nTemp, err := strconv.ParseInt(readLine(reader), 10, 64) checkError(err) n := int32(nTemp) fmt.Println(n) s := readLine(reader) kTemp, err := strconv.ParseInt(readLine(reader), 10, 64) checkError(err) k := int32(kTemp) result := caesarCipher(s, k) fmt.Fprintf(writer, "%s\n", result) writer.Flush() } func readLine(reader *bufio.Reader) string { str, _, err := reader.ReadLine() if err == io.EOF { return "" } return strings.TrimRight(string(str), "\r\n") } func checkError(err error) { if err != nil { panic(err) } }
// +build windows // +build !posix package frida_go import ( "syscall" ) var device_onSpawnAddedPtr = syscall.NewCallbackCDecl(func(o uintptr, rawSpawn uintptr,userdata uintptr) uintptr { return device_onSpawnAddedCallBack(o,rawSpawn,userdata) }) var device_onSpawnRemovedPtr = syscall.NewCallbackCDecl(func(o uintptr, rawSpawn uintptr,userdata uintptr) uintptr { return device_onSpawnRemovedCallBack(o,rawSpawn,userdata) }) var device_onChildAddedPtr = syscall.NewCallbackCDecl(func(o uintptr, rawChild uintptr,userdata uintptr) uintptr { return device_onChildAddedCallBack(o,rawChild,userdata) }) var device_onChildRemovedPtr = syscall.NewCallbackCDecl(func(o uintptr, rawChild uintptr,userdata uintptr) uintptr { return device_onChildRemovedCallBack(o,rawChild,userdata) }) var device_onProcessCrashedPtr = syscall.NewCallbackCDecl(func(o uintptr, rawCrash uintptr,userdata uintptr) uintptr { return device_onProcessCrashedCallBack(o,rawCrash,userdata) }) var device_onOutputPtr = syscall.NewCallbackCDecl(func(o uintptr,pid uintptr,fd uintptr,rawData uintptr,rawDataSize uintptr,userdata uintptr) uintptr { return device_onOutputCallBack(o,pid,fd,rawData,rawDataSize,userdata) }) var device_onUninjectedPtr = syscall.NewCallbackCDecl(func(o uintptr, id uintptr,userdata uintptr) uintptr { return device_onUninjectedCallBack(o,id,userdata) }) var device_onLostPtr = syscall.NewCallbackCDecl(func(o uintptr,userdata uintptr) uintptr { return device_onLostCallBack(o,userdata) })
package user import ( "encoding/json" "errors" "github.com/gin-gonic/gin" "strings" "sync" "time" "yj-app/app/model" "yj-app/app/model/monitor/online" userModel "yj-app/app/model/system/user" "yj-app/app/model/system/user_post" "yj-app/app/model/system/user_role" "yj-app/app/service/middleware/sessions" "yj-app/app/yjgframe/cache" "yj-app/app/yjgframe/db" "yj-app/app/yjgframe/utils/convert" "yj-app/app/yjgframe/utils/gconv" "yj-app/app/yjgframe/utils/gmd5" "yj-app/app/yjgframe/utils/page" "yj-app/app/yjgframe/utils/random" ) //用户session列表 var SessionList sync.Map //根据主键查询用户信息 func SelectRecordById(id int64) (*userModel.Entity, error) { entity := &userModel.Entity{UserId: id} _, err := entity.FindOne() return entity, err } // 根据条件分页查询用户列表 func SelectRecordList(param *userModel.SelectPageReq) ([]userModel.UserListEntity, *page.Paging, error) { return userModel.SelectPageList(param) } // 导出excel func Export(param *userModel.SelectPageReq) (string, error) { head := []string{"用户名", "呢称", "Email", "电话号码", "性别", "部门", "领导", "状态", "删除标记", "创建人", "创建时间", "备注"} col := []string{"u.login_name", "u.user_name", "u.email", "u.phonenumber", "u.sex", "d.dept_name", "d.leader", "u.status", "u.del_flag", "u.create_by", "u.create_time", "u.remark"} return userModel.SelectExportList(param, head, col) } //新增用户 func AddSave(req *userModel.AddReq, c *gin.Context) (int64, error) { var user userModel.Entity user.LoginName = req.LoginName user.UserName = req.UserName user.Email = req.Email user.Phonenumber = req.Phonenumber user.Status = req.Status user.Sex = req.Sex user.DeptId = req.DeptId user.Remark = req.Remark //生成密码 newSalt := random.GenerateSubId(6) newToken := req.LoginName + req.Password + newSalt newToken = gmd5.MustEncryptString(newToken) user.Salt = newSalt user.Password = newToken user.CreateTime = time.Now() createUser := GetProfile(c) if createUser != nil { user.CreateBy = createUser.LoginName } user.DelFlag = "0" session := db.Instance().Engine().NewSession() err := session.Begin() _, err = session.Table(userModel.TableName()).Insert(&user) if err != nil || user.UserId <= 0 { session.Rollback() return 0, err } //增加岗位数据 if req.PostIds != "" { postIds := convert.ToInt64Array(req.PostIds, ",") userPosts := make([]user_post.Entity, 0) for i := range postIds { if postIds[i] > 0 { var userPost user_post.Entity userPost.UserId = user.UserId userPost.PostId = postIds[i] userPosts = append(userPosts, userPost) } } if len(userPosts) > 0 { _, err := session.Table(user_post.TableName()).Insert(userPosts) if err != nil { session.Rollback() return 0, err } } } //增加角色数据 if req.RoleIds != "" { roleIds := convert.ToInt64Array(req.RoleIds, ",") userRoles := make([]user_role.Entity, 0) for i := range roleIds { if roleIds[i] > 0 { var userRole user_role.Entity userRole.UserId = user.UserId userRole.RoleId = roleIds[i] userRoles = append(userRoles, userRole) } } if len(userRoles) > 0 { _, err := session.Table(user_role.TableName()).Insert(userRoles) if err != nil { session.Rollback() return 0, err } } } return user.UserId, session.Commit() } //新增用户 func EditSave(req *userModel.EditReq, c *gin.Context) (int64, error) { user := &userModel.Entity{UserId: req.UserId} ok, err := user.FindOne() if err != nil { return 0, err } if !ok { return 0, errors.New("数据不存在") } user.UserName = req.UserName user.Email = req.Email user.Phonenumber = req.Phonenumber user.Status = req.Status user.Sex = req.Sex user.DeptId = req.DeptId user.Remark = req.Remark user.UpdateTime = time.Now() updateUser := GetProfile(c) if updateUser != nil { user.UpdateBy = updateUser.LoginName } session := db.Instance().Engine().NewSession() tanErr := session.Begin() _, tanErr = session.Table(userModel.TableName()).ID(user.UserId).Update(user) if tanErr != nil { session.Rollback() return 0, tanErr } //增加岗位数据 if req.PostIds != "" { postIds := convert.ToInt64Array(req.PostIds, ",") userPosts := make([]user_post.Entity, 0) for i := range postIds { if postIds[i] > 0 { var userPost user_post.Entity userPost.UserId = user.UserId userPost.PostId = postIds[i] userPosts = append(userPosts, userPost) } } if len(userPosts) > 0 { session.Exec("delete from sys_user_post where user_id=?", user.UserId) _, tanErr = session.Table(user_post.TableName()).Insert(userPosts) if tanErr != nil { session.Rollback() return 0, err } } } //增加角色数据 if req.RoleIds != "" { roleIds := convert.ToInt64Array(req.RoleIds, ",") userRoles := make([]user_role.Entity, 0) for i := range roleIds { if roleIds[i] > 0 { var userRole user_role.Entity userRole.UserId = user.UserId userRole.RoleId = roleIds[i] userRoles = append(userRoles, userRole) } } if len(userRoles) > 0 { session.Exec("delete from sys_user_role where user_id=?", user.UserId) _, err := session.Table(user_role.TableName()).Insert(userRoles) if tanErr != nil { session.Rollback() return 0, err } } } return 1, session.Commit() } //根据主键删除用户信息 func DeleteRecordById(id int64) bool { entity := &userModel.Entity{UserId: id} result, _ := entity.Delete() if result > 0 { return true } return false } //批量删除用户记录 func DeleteRecordByIds(ids string) int64 { idarr := convert.ToInt64Array(ids, ",") result, _ := userModel.DeleteBatch(idarr...) user_role.DeleteBatch(idarr...) user_post.DeleteBatch(idarr...) return result } //判断是否是系统管理员 func IsAdmin(userId int64) bool { if userId == 1 { return true } else { return false } } // 判断用户是否已经登录 func IsSignedIn(c *gin.Context) bool { session := sessions.Default(c) uid := session.Get(model.USER_ID) if uid != nil { return true } return false } // 用户登录,成功返回用户信息,否则返回nil; passport应当会md5值字符串 func SignIn(loginnName, password string, c *gin.Context) (string, error) { //查询用户信息 user := userModel.Entity{LoginName: loginnName} ok, err := user.FindOne() if err != nil { return "", err } if !ok { return "", errors.New("用户名或者密码错误") } //校验密码 token := user.LoginName + password + user.Salt token = gmd5.MustEncryptString(token) if strings.Compare(user.Password, token) == -1 { return "", errors.New("密码错误") } return SaveUserToSession(&user, c), nil } //保存用户信息到session func SaveUserToSession(user *userModel.Entity, c *gin.Context) string { session := sessions.Default(c) session.Set(model.USER_ID, user.UserId) tmp, _ := json.Marshal(user) session.Set(model.USER_SESSION_MARK, string(tmp)) session.Save() sessionId := session.SessionId() SessionList.Store(sessionId, c) return sessionId } //清空用户菜单缓存 func ClearMenuCache(user *userModel.Entity) { if IsAdmin(user.UserId) { cache.Instance().Delete(model.MENU_CACHE) } else { cache.Instance().Delete(model.MENU_CACHE + gconv.String(user.UserId)) } } // 用户注销 func SignOut(c *gin.Context) error { user := GetProfile(c) if user != nil { ClearMenuCache(user) } session := sessions.Default(c) sessionId := session.SessionId() SessionList.Delete(sessionId) entity := online.Entity{Sessionid: sessionId} entity.Delete() session.Delete(model.USER_ID) session.Delete(model.USER_SESSION_MARK) return session.Save() } //强退用户 func ForceLogout(sessionId string) error { var tmp interface{} if v, ok := SessionList.Load(sessionId); ok { tmp = v } if tmp != nil { c := tmp.(*gin.Context) if c != nil { SignOut(c) SessionList.Delete(sessionId) entity := online.Entity{Sessionid: sessionId} entity.Delete() } } return nil } // 检查账号是否符合规范,存在返回false,否则true func CheckPassport(loginName string) bool { entity := userModel.Entity{LoginName: loginName} if ok, err := entity.FindOne(); err != nil || !ok { return false } else { return true } } // 检查登陆名是否存在,存在返回true,否则false func CheckNickName(userName string) bool { entity := userModel.Entity{UserName: userName} if ok, err := entity.FindOne(); err != nil || !ok { return false } else { return true } } // 检查登陆名是否存在,存在返回true,否则false func CheckLoginName(loginName string) bool { entity := userModel.Entity{LoginName: loginName} if ok, err := entity.FindOne(); err != nil || !ok { return false } else { return true } } // 获得用户信息详情 func GetProfile(c *gin.Context) *userModel.Entity { session := sessions.Default(c) tmp := session.Get(model.USER_SESSION_MARK) s := tmp.(string) var u userModel.Entity err := json.Unmarshal([]byte(s), &u) if err != nil { return nil } return &u } //更新用户信息详情 func UpdateProfile(profile *userModel.ProfileReq, c *gin.Context) error { user := GetProfile(c) if profile.UserName != "" { user.UserName = profile.UserName } if profile.Email != "" { user.Email = profile.Email } if profile.Phonenumber != "" { user.Phonenumber = profile.Phonenumber } if profile.Sex != "" { user.Sex = profile.Sex } _, err := user.Update() if err != nil { return errors.New("保存数据失败") } SaveUserToSession(user, c) return nil } //更新用户头像 func UpdateAvatar(avatar string, c *gin.Context) error { user := GetProfile(c) if avatar != "" { user.Avatar = avatar } _, err := user.Update() if err != nil { return errors.New("保存数据失败") } SaveUserToSession(user, c) return nil } //修改用户密码 func UpdatePassword(profile *userModel.PasswordReq, c *gin.Context) error { user := GetProfile(c) if profile.OldPassword == "" { return errors.New("旧密码不能为空") } if profile.NewPassword == "" { return errors.New("新密码不能为空") } if profile.Confirm == "" { return errors.New("确认密码不能为空") } if profile.NewPassword == profile.OldPassword { return errors.New("新旧密码不能相同") } if profile.Confirm != profile.NewPassword { return errors.New("确认密码不一致") } //校验密码 token := user.LoginName + profile.OldPassword + user.Salt token = gmd5.MustEncryptString(token) if token != user.Password { return errors.New("原密码不正确") } //新校验密码 newSalt := random.GenerateSubId(6) newToken := user.LoginName + profile.NewPassword + newSalt newToken = gmd5.MustEncryptString(newToken) user.Salt = newSalt user.Password = newToken _, err := user.Update() if err != nil { return errors.New("保存数据失败") } SaveUserToSession(user, c) return nil } //重置用户密码 func ResetPassword(params *userModel.ResetPwdReq) (bool, error) { user := userModel.Entity{UserId: params.UserId} if ok, err := user.FindOne(); err != nil || !ok { return false, errors.New("用户不存在") } //新校验密码 newSalt := random.GenerateSubId(6) newToken := user.LoginName + params.Password + newSalt newToken = gmd5.MustEncryptString(newToken) user.Salt = newSalt user.Password = newToken if _, err := user.Update(); err != nil { return false, errors.New("保存数据失败") } return true, nil } //校验密码是否正确 func CheckPassword(user *userModel.Entity, password string) bool { if user == nil || user.UserId <= 0 { return false } //校验密码 token := user.LoginName + password + user.Salt token = gmd5.MustEncryptString(token) if strings.Compare(token, user.Password) == 0 { return true } else { return false } } //检查邮箱是否已使用 func CheckEmailUnique(userId int64, email string) bool { return userModel.CheckEmailUnique(userId, email) } //检查邮箱是否存在,存在返回true,否则false func CheckEmailUniqueAll(email string) bool { return userModel.CheckEmailUniqueAll(email) } //检查手机号是否已使用,存在返回true,否则false func CheckPhoneUnique(userId int64, phone string) bool { return userModel.CheckPhoneUnique(userId, phone) } //检查手机号是否已使用 ,存在返回true,否则false func CheckPhoneUniqueAll(phone string) bool { return userModel.CheckPhoneUniqueAll(phone) } //根据登陆名查询用户信息 func SelectUserByLoginName(loginName string) (*userModel.Entity, error) { return userModel.SelectUserByLoginName(loginName) } //根据手机号查询用户信息 func SelectUserByPhoneNumber(phonenumber string) (*userModel.Entity, error) { return userModel.SelectUserByPhoneNumber(phonenumber) } // 查询已分配用户角色列表 func SelectAllocatedList(roleId int64, loginName, phonenumber string) ([]userModel.Entity, error) { return userModel.SelectAllocatedList(roleId, loginName, phonenumber) } // 查询未分配用户角色列表 func SelectUnallocatedList(roleId int64, loginName, phonenumber string) ([]userModel.Entity, error) { return userModel.SelectUnallocatedList(roleId, loginName, phonenumber) }
// TODO: this shouldn't be here package client // ClusteradmCfg is just a placeholder // TODO: this is just a placeholder type ClusteradmCfg struct { Bootstrap string Providers []string }
package user import ( "bytes" "encoding/json" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "github.com/go-kit/kit/log" "github.com/jmoiron/sqlx" "github.com/stretchr/testify/assert" "gopkg.in/DATA-DOG/go-sqlmock.v1" ) //Expample (No working) func TestCreateUserSholdReturnSuccessMess(t *testing.T) { db, mock, err := createDb() assert.NoError(t, err) defer db.Close() user := &User{ Contacts: "Content", Email: "john@email.com", Password: "1234567", Login: "john", } _ = user.BeforeCreate() mock.ExpectQuery(`insert into users \(username, email, encrypted_password, created_at, token, contacts, role, is_active\) values \(\$1, \$2, \$3, \$4, \$5, \$6, \$7, \$8\) returning id$`). WithArgs(user.Login, user.Email, user.EncryptedPassword, user.CreatedAt, user.Token, user.Contacts, user.Role, user.IsActive). WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1)) repo := NewRepo(db) ep := NewEndpoints(NewService(repo)) b, err := json.Marshal(user) assert.NoError(t, err) r := httptest.NewRequest("POST", "/api/v1/create", bytes.NewReader(b)) w := httptest.NewRecorder() NewHTTPTransport(ep, log.NewNopLogger()).ServeHTTP(w, r) assert.Equal(t, http.StatusOK, w.Code) body, err := ioutil.ReadAll(w.Body) assert.NoError(t, err) assert.True(t, strings.Contains(string(body), "Success")) } func createDb() (*sqlx.DB, sqlmock.Sqlmock, error) { db, mock, err := sqlmock.New() if err != nil { return nil, nil, err } dbx := sqlx.NewDb(db, "sqlmock") return dbx, mock, nil }
// The codes here are based on btcd project // ISC License // // Copyright (c) 2013-2017 The btcsuite developers // Copyright (c) 2015-2016 The Decred developers // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. package main import ( "crypto/ecdsa" "fmt" "github.com/ethereum/go-ethereum/crypto/secp256k1" "math/big" ) func SerializePublicKeyCompressed(pubKey ecdsa.PublicKey) []byte { b := make([]byte, 0, 33) format := byte(0x2) if isOdd(pubKey.Y) { format |= 0x1 } b = append(b, format) return append(b, pubKey.X.Bytes()...) } func UnserializePublicKeyCompressed(curve *secp256k1.BitCurve, data []byte) (ecdsa.PublicKey, error) { var err error pubKey := ecdsa.PublicKey{Curve: curve} format := data[0] ybit := (format & 0x1) == 0x1 format &= ^byte(0x1) if format != 0x2 { return pubKey, fmt.Errorf("invalid magic in compressed pubkey string: %d", data[0]) } pubKey.X = new(big.Int).SetBytes(data[1:33]) pubKey.Y, err = decompressPoint(curve, pubKey.X, ybit) if err != nil { return pubKey, err } return pubKey, nil } func isOdd(a *big.Int) bool { return a.Bit(0) == 1 } func decompressPoint(curve *secp256k1.BitCurve, x *big.Int, ybit bool) (*big.Int, error) { // TODO: This will probably only work for secp256k1 due to // optimizations. // Y = +-sqrt(x^3 + B) x3 := new(big.Int).Mul(x, x) x3.Mul(x3, x) x3.Add(x3, curve.Params().B) // now calculate sqrt mod p of x2 + B // This code used to do a full sqrt based on tonelli/shanks, // but this was replaced by the algorithms referenced in // https://bitcointalk.org/index.php?topic=162805.msg1712294#msg1712294 q := new(big.Int).Div(new(big.Int).Add(curve.P, big.NewInt(1)), big.NewInt(4)) y := new(big.Int).Exp(x3, q, curve.Params().P) if ybit != isOdd(y) { y.Sub(curve.Params().P, y) } if ybit != isOdd(y) { return nil, fmt.Errorf("ybit doesn't match oddness") } return y, nil }
// Copyright (C) 2020 The Android Open Source Project // // 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 sdk import ( "testing" "android/soong/android" ) type removeFredTransformation struct { identityTransformation } func (t removeFredTransformation) transformProperty(name string, value interface{}, tag android.BpPropertyTag) (interface{}, android.BpPropertyTag) { if name == "fred" { return nil, nil } return value, tag } func (t removeFredTransformation) transformPropertySetBeforeContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) { if name == "fred" { return nil, nil } return propertySet, tag } func (t removeFredTransformation) transformPropertySetAfterContents(name string, propertySet *bpPropertySet, tag android.BpPropertyTag) (*bpPropertySet, android.BpPropertyTag) { if len(propertySet.properties) == 0 { return nil, nil } return propertySet, tag } func TestTransformRemoveProperty(t *testing.T) { helper := &TestHelper{t} set := newPropertySet() set.AddProperty("name", "name") set.AddProperty("fred", "12") set.transformContents(removeFredTransformation{}) contents := &generatedContents{} outputPropertySet(contents, set) helper.AssertTrimmedStringEquals("removing property failed", "name: \"name\",\n", contents.content.String()) } func TestTransformRemovePropertySet(t *testing.T) { helper := &TestHelper{t} set := newPropertySet() set.AddProperty("name", "name") set.AddPropertySet("fred") set.transformContents(removeFredTransformation{}) contents := &generatedContents{} outputPropertySet(contents, set) helper.AssertTrimmedStringEquals("removing property set failed", "name: \"name\",\n", contents.content.String()) }
package main import ( "context" "log" "myeduate/ent" "myeduate/ent/migrate" "myeduate/resolvers" "myeduate/utils" "net/http" "time" "entgo.io/contrib/entgql" "entgo.io/ent/dialect" "github.com/99designs/gqlgen/graphql/handler" "github.com/99designs/gqlgen/graphql/playground" gohandlers "github.com/gorilla/handlers" "github.com/gorilla/mux" _ "github.com/lib/pq" ) func main() { config, err := utils.LoadConfig(".") if err != nil { log.Printf("cannot load config: %v", err) } // Create an ent.Client with in-memory SQLite database. client, err := ent.Open(dialect.Postgres, config.DbSource) if err != nil { log.Fatalf("failed opening connection to sqlite: %v", err) } defer client.Close() if err := client.Schema.Create( context.Background(), migrate.WithGlobalUniqueID(true), ); err != nil { log.Fatal("opening ent client", err) } // create a new serve mux and register the handlers route := mux.NewRouter() // CORS ch := cors() // create a new server s := http.Server{ Addr: config.ServerAddr, // configure the bind address Handler: ch(route), // set the default handler // ErrorLog: l.StandardLogger(&hclog.StandardLoggerOptions{}), // set the logger for the server ReadTimeout: 5 * time.Second, // max time to read request from the client WriteTimeout: 10 * time.Second, // max time to write response to the client IdleTimeout: 120 * time.Second, // max time for connections using TCP Keep-Alive } // Configure the server and start listening on :8081. srv := handler.NewDefaultServer(resolvers.NewSchema(client)) srv.Use(entgql.Transactioner{TxOpener: client}) route.Handle("/", playground.Handler("myeduate", "/query")) route.Handle("/query", srv) log.Printf("listening on : %v", config.ServerAddr) if err := s.ListenAndServe(); err != nil { log.Fatal("http server terminated", err) } } func cors() mux.MiddlewareFunc { return gohandlers.CORS( gohandlers.AllowedOrigins([]string{"*"}), gohandlers.AllowedHeaders([]string{"Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Origin", "X-Requested-With", "Content-Type", "Accept"}), gohandlers.AllowedMethods([]string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodOptions}), gohandlers.AllowCredentials(), ) }
package main type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func deleteNode(root *TreeNode, key int) *TreeNode { if root == nil { return root } curr := root pre := curr flag := 0 for curr != nil && curr.Val != key { pre = curr if curr.Val < key { curr = curr.Right flag = 1 } else { curr = curr.Left flag = -1 } } if curr ==nil { return root } if root.Val == key { if root.Right != nil { tmp := root.Right rightPre := tmp for tmp != nil { rightPre = tmp tmp = tmp.Left } rightPre.Left = root.Left return root.Right } else { return root.Left } } else { if curr.Right != nil { tmp := curr.Right rightPre := tmp for tmp != nil { rightPre = tmp tmp = tmp.Left } rightPre.Left = curr.Left if flag == -1 { pre.Left = curr.Right } else { pre.Right = curr.Right } } else { if flag == -1 { pre.Left = curr.Left } else { pre.Right = curr.Left } } } return root }
package provisioner import ( "log" "testing" ) var minimalJson = ` { "deviceType":"raspberrypi3", "pubnubSubscribeKey":"sub-c-abc12345-ab1a-12a1-9876-01ab1abcd8zx", "pubnubPublishKey":"pub-c-abc12345-ab1a-12a1-9876-01ab1abcd8zx", "mixpanelToken":"abcdefghijklmnopqrstuvwxyz123456", "ListenPort":"1234" } ` // Ensure the default values are set + not overwritten. func TestParseMinimalConfigJson(t *testing.T) { if conf, err := parseConfig(minimalJson, ""); err != nil { t.Fatalf("Parse failed: ERROR: %s", err) } else { if conf.ListenPort == DefaultConfig.ListenPort { t.Error("ListenPort overwriten by default!") } // TODO: Automate this via reflection. if conf.AppUpdatePollInterval != DefaultConfig.AppUpdatePollInterval { t.Error("MISMATCH: AppUpdatePollInterval") } if conf.VpnPort != DefaultConfig.VpnPort { t.Error("MISMATCH: VpnPort") } if conf.ApiEndpoint != DefaultConfig.ApiEndpoint { t.Error("MISMATCH: ApiEndpoint") } if conf.VpnEndpoint != DefaultConfig.VpnEndpoint { t.Error("MISMATCH: VpnEndpoint") } if conf.RegistryEndpoint != DefaultConfig.RegistryEndpoint { t.Error("MISMATCH: RegistryEndpoint") } if conf.DeltaEndpoint != DefaultConfig.DeltaEndpoint { t.Error("MISMATCH: DeltaEndpoint") } } } func TestGetConfigFromApi(t *testing.T) { var c Config c.ApiEndpoint = "https://api.resin.io" if err := c.GetKeysFromApi(); err != nil { t.Errorf("Error getting from API: %s", err) } else { log.Printf("%v %v %v", c.MixpanelToken, c.PubnubSubscribeKey, c.PubnubPublishKey) if c.MixpanelToken == "" || c.PubnubSubscribeKey == "" || c.PubnubSubscribeKey == "" { t.Error("Empty values after getting from API") } } }
package testsuite import "github.com/kurtosis-tech/kurtosis-client/golang/services" const ( // vvvvvvvvv Update the docs if you change these vvvvvvvvvvv defaultSetupTimeoutSeconds = 180; defaultRunTimeoutSeconds = 180; defaultPartitioningEnabled = false; // ^^^^^^^^^ Update the docs if you change these ^^^^^^^^^^^ ) // Docs available at https://docs.kurtosistech.com/kurtosis-libs/lib-documentation type TestConfigurationBuilder struct { setupTimeoutSeconds uint32 runTimeoutSeconds uint32 isPartioningEnabled bool filesArtifactUrls map[services.FilesArtifactID]string } func NewTestConfigurationBuilder() *TestConfigurationBuilder { return &TestConfigurationBuilder{ setupTimeoutSeconds: defaultSetupTimeoutSeconds, runTimeoutSeconds: defaultRunTimeoutSeconds, isPartioningEnabled: defaultPartitioningEnabled, filesArtifactUrls: map[services.FilesArtifactID]string{}, } } func (builder *TestConfigurationBuilder) WithSetupTimeoutSeconds(setupTimeoutSeconds uint32) *TestConfigurationBuilder { builder.setupTimeoutSeconds = setupTimeoutSeconds return builder } func (builder *TestConfigurationBuilder) WithRunTimeoutSeconds(runTimeoutSeconds uint32) *TestConfigurationBuilder { builder.runTimeoutSeconds = runTimeoutSeconds return builder } func (builder *TestConfigurationBuilder) WithPartitioningEnabled(isPartitioningEnabled bool) *TestConfigurationBuilder { builder.isPartioningEnabled = isPartitioningEnabled return builder } func (builder *TestConfigurationBuilder) WithFilesArtifactUrls(filesArtifactUrls map[services.FilesArtifactID]string) *TestConfigurationBuilder { builder.filesArtifactUrls = filesArtifactUrls return builder } func (builder TestConfigurationBuilder) Build() *TestConfiguration { return &TestConfiguration{ SetupTimeoutSeconds: builder.setupTimeoutSeconds, RunTimeoutSeconds: builder.runTimeoutSeconds, IsPartitioningEnabled: builder.isPartioningEnabled, FilesArtifactUrls: builder.filesArtifactUrls, } }
package myrevenue import ( "fmt" "log" "net/http" "net/http/httputil" "strconv" "strings" "time" ) type Model struct { NetworkName string `json:"network_id"` DateTime time.Time `json:"date_time"` // ISO 8601 Name string `json:"name"` Country string `json:"country"` // 2-letter country code App string `json:"app"` Requests uint64 `json:"requests"` Impressions uint64 `json:"impressions"` Clicks uint64 `json:"clicks"` CTR float64 `json:"ctr"` Revenue float64 `json:"revenue"` ECPM float64 `json:"ecpm"` } func GetRequest(reportURL string, headers map[string]string, debug bool) (*http.Response, error) { // Build the request req, err := http.NewRequest(http.MethodGet, reportURL, nil) if err != nil { return nil, err } return request(req, headers, debug) } func PostRequest(reportURL string, headers map[string]string, data string, debug bool) (*http.Response, error) { req, err := http.NewRequest(http.MethodPost, reportURL, strings.NewReader(data)) if err != nil { return nil, err } return request(req, headers, debug) } func request(req *http.Request, headers map[string]string, debug bool) (*http.Response, error) { if headers != nil { for h := range headers { req.Header.Set(h, headers[h]) } } if debug { for k, v := range headers { fmt.Printf("%s: %s", k, v) } } client := newClient() resp, err := client.Do(req) if err != nil { log.Fatal("Network Error: ", err) return nil, err } if debug { respHeaders, err := httputil.DumpResponse(resp, false) if err == nil { fmt.Printf(string(respHeaders)) } } return resp, nil } func newClient() *http.Client { return &http.Client{} } func DateRangeFromHistory(history string, tz string) (time.Time, time.Time, error) { var startDate time.Time var endDate time.Time loc, e := time.LoadLocation(tz) if e != nil { log.Fatalln(e) } switch history { case "yesterday": tempDate := time.Now().In(loc).AddDate(0, 0, -1) startDate = time.Date(tempDate.Year(), tempDate.Month(), tempDate.Day(), 0, 0, 0, 0, loc) endDate = time.Date(tempDate.Year(), tempDate.Month(), tempDate.Day(), 23, 59, 59, 999999999, loc) case "today": tempDate := time.Now().In(loc) startDate = time.Date(tempDate.Year(), tempDate.Month(), tempDate.Day(), 0, 0, 0, 0, loc) endDate = time.Date(tempDate.Year(), tempDate.Month(), tempDate.Day(), 23, 59, 59, 999999999, loc) case "week": tempDate := time.Now().In(loc).AddDate(0, 0, -7) startDate = time.Date(tempDate.Year(), tempDate.Month(), tempDate.Day(), 0, 0, 0, 0, loc) tempDate = time.Now().In(loc).AddDate(0, 0, -1) endDate = time.Date(tempDate.Year(), tempDate.Month(), tempDate.Day(), 23, 59, 59, 999999999, loc) case "month-to-date": tempDate := time.Now().In(loc).AddDate(0, 0, -1) startDate = time.Date(tempDate.Year(), tempDate.Month(), 1, 0, 0, 0, 0, loc) endDate = time.Date(tempDate.Year(), tempDate.Month(), tempDate.Day(), 23, 59, 59, 999999999, loc) case "last-month": tempDate := time.Date(time.Now().In(loc).Year(), time.Now().In(loc).Month(), 1, 0, 0, 0, 0, loc) startDate = tempDate.AddDate(0, -1, 0) tempDate = time.Date(time.Now().In(loc).Year(), time.Now().In(loc).Month(), 1, 23, 59, 59, 999999999, loc) endDate = tempDate.AddDate(0, 0, -1) default: tempDate, err := time.ParseInLocation("2006-01-02", history, loc) if err == nil { startDate = time.Date(tempDate.Year(), tempDate.Month(), tempDate.Day(), 0, 0, 0, 0, loc) endDate = time.Date(tempDate.Year(), tempDate.Month(), tempDate.Day(), 23, 59, 59, 999999999, loc) } else { days, err := strconv.ParseInt(history, 10, 32) if err != nil { return time.Now().UTC(), time.Now().UTC(), err } tempDate := time.Now().In(loc).AddDate(0, 0, int(days*-1)) startDate = time.Date(tempDate.Year(), tempDate.Month(), tempDate.Day(), 0, 0, 0, 0, loc) endDate = time.Date(tempDate.Year(), tempDate.Month(), tempDate.Day(), 23, 59, 59, 9999, loc) } } return startDate, endDate, nil }
package storage import ( "encoding/json" "fmt" "os" "path/filepath" "strings" ) type FileStorage struct { DataDirectory string } func NewFileStorage(dataDirectory string) FileStorage { return FileStorage{ DataDirectory: dataDirectory, } } func (f FileStorage) Store(r Repository) error { if len(r.Plugins) == 0 { return os.Remove(fmt.Sprintf("%s/%s.json", f.DataDirectory, r.ID)) } file, err := os.OpenFile( fmt.Sprintf("%s/%s.json", f.DataDirectory, r.ID), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600, ) if err != nil { return err } return json.NewEncoder(file).Encode(r) } func (f FileStorage) Load() ([]Repository, error) { var repos []Repository err := filepath.Walk(f.DataDirectory, func(path string, info os.FileInfo, _ error) error { if info.IsDir() && path != f.DataDirectory { return filepath.SkipDir } if strings.HasSuffix(path, ".json") { file, err := os.Open(path) if err != nil { return err } var repo Repository if err := json.NewDecoder(file).Decode(&repo); err != nil { return err } repos = append(repos, repo) } return nil }) if err != nil { return nil, err } return repos, nil }
package main import ( "./levenshtein" "fmt" ) func main() { fmt.Printf("Введите первое слово: ") a := levenshtein.GetLine() fmt.Printf("Введите второе слово: ") b := levenshtein.GetLine() fmt.Println() dLevRec := levenshtein.LevRec(a, b) fmt.Println("Рекурсивный:") fmt.Printf("расстояние: %d\n\n", dLevRec) dLevRecMtr, mtrRec := levenshtein.LevMtrRec(a, b) fmt.Println("Рекурсивный с заполнением матрицы:") levenshtein.OutMatrix(mtrRec) fmt.Printf("расстояние: %d\n\n", dLevRecMtr) dLevMtr, mtrLev := levenshtein.LevMtr(a, b) fmt.Println("Матричный:") levenshtein.OutMatrix(mtrLev) fmt.Printf("расстояние: %d\n\n", dLevMtr) dDamLevMtr, mtrDamLev := levenshtein.DamLevMtr(a, b) fmt.Println("Дамерау-Левенштейн:") levenshtein.OutMatrix(mtrDamLev) fmt.Printf("расстояние: %d\n\n", dDamLevMtr) }
package dog // Breed _ type Breed string func toBreed(val string) Breed { return Breed(val) } // Dog _ type Dog string func toDog(val string) Dog { return Dog(val) }
package bot import ( "time" "github.com/bwmarrin/discordgo" ) type PingCommand struct{} func (c PingCommand) Run(bot *Bot, args string, message *discordgo.Message) Sendable { return Message{Content: "Pong!", Timeout: time.Second * 10} }
package timeshift import ( "time" "github.com/tkuchiki/go-timezone" ) // DateTime structure. type DateTime struct { time.Time } // MarshalCSV returns a time as as a string formatted to RFC3339. func (date *DateTime) MarshalCSV() (string, error) { return date.Time.Format(time.RFC3339), nil } // UnmarshalCSV accepts a string and unmarshals the string into a time.Time // structure. func (date *DateTime) UnmarshalCSV(csv string) (err error) { timeFormat := "1/2/06 3:04:05 PM" timeNameWest := "America/Los_Angeles" timeNameEast := "America/New_York" // Let's load the location we need for each timezone timeLocationWest, _ := time.LoadLocation(timeNameWest) timeLocationEast, _ := time.LoadLocation(timeNameEast) // Leveraging the go-timezone library tz := timezone.New() // Take the given CSV time, and parse it into a Pacific // Standard/Daylight Savings time zone. givenTime, err := time.ParseInLocation(timeFormat, csv, timeLocationWest) isDst := tz.IsDST(givenTime) // Since the go-timezone library looks things up via Abbrevations (e.g. // EST/PDT), we'll need to get the abbreviation for the two timezones // and make sure we're using Standard or Daylight Savings as well. timezoneAbbrWest, _ := tz.GetTimezoneAbbreviation(timeNameWest, isDst) timezoneAbbrEast, _ := tz.GetTimezoneAbbreviation(timeNameEast, isDst) // Once we have that, we can get the offset seconds from UTC and // leverage that number to add the number of seconds to jump // from Pacific to Eastern time. tzAbbrInfosWest, _ := tz.GetTzAbbreviationInfo(timezoneAbbrWest) tzAbbrInfosEast, _ := tz.GetTzAbbreviationInfo(timezoneAbbrEast) offsetInSeconds := tzAbbrInfosWest[0].Offset() - tzAbbrInfosEast[0].Offset() easternTime := givenTime.Add(time.Second * time.Duration(offsetInSeconds)) date.Time = easternTime.In(timeLocationEast) return err }
package main import ( "bufio" "fmt" "os" "strconv" ) func main() { scan := func() func() int { scan := bufio.NewScanner(os.Stdin) scan.Split(bufio.ScanWords) return func() int { scan.Scan() i, _ := strconv.Atoi(scan.Text()) return i } }() n := scan() t := scan() l := make([]int, n) for i := 0; i < n; i++ { l[i] = scan() } for ; t > 0; t-- { a := scan() b := scan() max := 3 for ; a <= b; a++ { if l[a] < max { max = l[a] } if max == 1 { break } } fmt.Println(max) } }
package orm import ( "GoldenTimes-web/models" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" ) func CreateTrack(albumId int64, track *models.Track) (int64, error) { beego.Trace("CreateTrack()") o := orm.NewOrm() num, err := o.Insert(track) return num, err } func ReadTrack(track *models.Track) error { o := orm.NewOrm() err := o.Read(track) if err == nil { numArtists, errArtists := o.LoadRelated(track, "Artists") track.ArtistsCount = numArtists beego.Trace("numArtists", numArtists) beego.Trace("errArtists", errArtists) } return err } func UpdateTrack(track *models.Track) (int64, error) { o := orm.NewOrm() num, err := o.Update(track) return num, err } func DeleteTrack(trackId int64) (num int64, err error) { o := orm.NewOrm() track := models.Track{Id: trackId} num, err = o.Delete(&track) return num, err } func TrackPutArtists(trackId int64, artists []models.Artist) (num int64, err error) { beego.Trace("TrackPutArtists()") o := orm.NewOrm() track := models.Track{Id: trackId} m2m := o.QueryM2M(&track, "Artists") num, err = m2m.Add(artists) return } func TrackDeleteArtists(trackId int64, artists []models.Artist) (num int64, err error) { beego.Trace("TrackDeleteArtists()") o := orm.NewOrm() track := models.Track{Id: trackId} m2m := o.QueryM2M(&track, "Artists") num, err = m2m.Remove(artists) return } func TrackPutArtist(trackId int64, artistId int64) (num int64, err error) { beego.Trace("TrackPutArtist()") o := orm.NewOrm() track := models.Track{Id: trackId} m2m := o.QueryM2M(&track, "Artists") artist := &models.Artist{Id: artistId} num, err = m2m.Add(artist) return } func TrackDeleteArtist(trackId int64, artistId int64) (num int64, err error) { beego.Trace("TrackDeleteArtist()") o := orm.NewOrm() track := models.Track{Id: trackId} m2m := o.QueryM2M(&track, "Artists") artist := &models.Artist{Id: artistId} num, err = m2m.Remove(artist) return }
package handlers import ( "encoding/json" "io/ioutil" "log" "net/http" "github.com/danielhood/quest.server.api/entities" "github.com/danielhood/quest.server.api/repositories" "github.com/danielhood/quest.server.api/services" ) // Device holds DeviceService structure type Device struct { svc services.DeviceService } // DeviceGetRequest holds request parameters for device GET. type DeviceGetRequest struct { Hostname string `json:"hostname"` DeviceKey string `json:"devicekey"` } // NewDevice creates new instance of DeviceService func NewDevice(dr repositories.DeviceRepo) *Device { return &Device{services.NewDeviceService(dr)} } func (h *Device) ServeHTTP(w http.ResponseWriter, req *http.Request) { h.enableCors(&w) switch req.Method { case "OPTIONS": log.Print("/token:OPTIONS") if req.Header.Get("Access-Control-Request-Method") != "" { w.Header().Set("Allow", req.Header.Get("Access-Control-Request-Method")) w.Header().Set("Access-Control-Allow-Methods", req.Header.Get("Access-Control-Request-Method")) } w.Header().Set("Access-Control-Allow-Headers", "authorization,access-control-allow-origin,content-type") case "GET": // Device GET funciton requires device or user level access if req.Header.Get("QUEST_AUTH_TYPE") != "device" && req.Header.Get("QUEST_AUTH_TYPE") != "user" { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } log.Print("/device:GET") var deviceHostname string var deviceKey string deviceHostname = req.URL.Query().Get("hostname") deviceKey = req.URL.Query().Get("key") if len(deviceHostname) == 0 { var deviceGetRequest = h.parseGetRequest(w, req) if deviceGetRequest == nil { return } deviceHostname = deviceGetRequest.Hostname deviceKey = deviceGetRequest.DeviceKey } var deviceBytes []byte if len(deviceHostname) == 0 { // Device GET all funciton requires user level access if req.Header.Get("QUEST_AUTH_TYPE") != "user" { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } deviceList, _ := h.svc.ReadAll() deviceBytes, _ = json.Marshal(deviceList) } else { device, err := h.svc.Read(deviceHostname, deviceKey) if err != nil { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } deviceBytes, _ = json.Marshal(device) } w.Header().Set("Content-Type", "application/json") w.Write(deviceBytes) case "PUT": // Device PUT funciton requires user level access if req.Header.Get("QUEST_AUTH_TYPE") != "user" { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } log.Print("/device:PUT") var device = h.parsePutRequest(w, req) if device == nil { return } _ = h.svc.Update(device) deviceBytes, _ := json.Marshal(device) w.Header().Set("Content-Type", "application/json") w.Write(deviceBytes) default: http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) } } func (h *Device) parseGetRequest(w http.ResponseWriter, req *http.Request) *DeviceGetRequest { requestBody, err := ioutil.ReadAll(req.Body) defer req.Body.Close() if err != nil { http.Error(w, "Unable to parse request body", http.StatusInternalServerError) return nil } if len(requestBody) == 0 { return &DeviceGetRequest{} } var deviceGetRequest DeviceGetRequest if err = json.Unmarshal(requestBody, &deviceGetRequest); err != nil { http.Error(w, "Unable to parse DeviceGetRequest json", http.StatusInternalServerError) return nil } if len(deviceGetRequest.Hostname) == 0 { http.Error(w, "Hostname not specified", http.StatusInternalServerError) return nil } if len(deviceGetRequest.DeviceKey) == 0 { http.Error(w, "DeviceKey not specified", http.StatusInternalServerError) return nil } return &deviceGetRequest } func (h *Device) parsePutRequest(w http.ResponseWriter, req *http.Request) *entities.Device { requestBody, err := ioutil.ReadAll(req.Body) defer req.Body.Close() if err != nil { http.Error(w, "Unable to parse request body", http.StatusInternalServerError) return nil } if len(requestBody) == 0 { http.Error(w, "Empty Device passed", http.StatusInternalServerError) return nil } var device entities.Device if err = json.Unmarshal(requestBody, &device); err != nil { http.Error(w, "Unable to parse Device json", http.StatusInternalServerError) return nil } if len(device.Hostname) == 0 { http.Error(w, "Hostname not specified", http.StatusInternalServerError) return nil } if len(device.DeviceKey) == 0 { http.Error(w, "DeviceKey not specified", http.StatusInternalServerError) return nil } return &device } func (h *Device) enableCors(w *http.ResponseWriter) { (*w).Header().Set("Access-Control-Allow-Origin", "*") }
package model // Menu entity type type Menu struct { ID string `json:"uid,omitempty"` Name string `json:"name,omitempty"` URL string `json:"url"` Parent *[]Menu `json:"parent,omitempty"` Children *[]Menu `json:"children,omitempty"` } // Menus is a map for [id : menu] pair type Menus map[int]Menu var EmptyMenu = Menu{}
/* The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. */ package main import ( "example.com/ben/primes" "fmt" "sort" "strconv" ) func main() { sumOfTruncatablePrimes := 0 cnt := 0 primeNumbers := primes.GetPrimes(1000000) sort.Ints(primeNumbers) primeNumbers = primeNumbers[5:] // Remove 2, 3, 5, 7 since they are 1-digit numbers and cannot be truncated for _, nr := range primeNumbers { if isTruncatablePrime(nr) { sumOfTruncatablePrimes += nr cnt++ fmt.Printf("Found %d\n", nr) } } fmt.Printf("The sum of the truncatable primes is %d, and there are %d of them", sumOfTruncatablePrimes, cnt) } func isTruncatablePrime(nr int) bool { for _, stripFunc := range []func(string) string{fromLeft, fromRight} { truncatedNr := nr for { truncatedNr = removeDigit(stripFunc, truncatedNr) if !primes.IsPrime(truncatedNr) { return false } if truncatedNr < 10 { break } } } return true } func fromLeft(str string) string { return str[1:] } func fromRight(str string) string { return str[:len(str)-1] } func removeDigit(stripFunc func(string) string, nr int) int { str := fmt.Sprintf("%d", nr) truncatedNr, err := strconv.Atoi(stripFunc(str)) if err != nil { panic(err) } return truncatedNr }
package constants import ( "github.com/pkg/errors" ) // Error constants var ( ErrInternalServer = errors.New("Internal server error occurred") ) // MultiPartReaderMaxMemorySize is the maximum memory size used while reading // multipart/form-data content. const MultiPartReaderMaxMemorySize = 10 * 1024 * 1024 const ( // RepoAutoCommitterName represents the commiter name for auto generated // commits in package repo. RepoAutoCommitterName = "GoPx" // RepoAutoCommitterEmail represents the commiter email for auto generated // commits in package repo. RepoAutoCommitterEmail = "gopx@gopx.io" // RepoAutoTaggerName represents the tagger name for auto generated // tags in package repo. RepoAutoTaggerName = "GoPx" // RepoAutoTaggerEmail represents the tagger email for auto generated // tags in package repo. RepoAutoTaggerEmail = "gopx@gopx.io" ) // GitExportRepoFileName is the file name which existence is responsible // for package exporting status. const GitExportRepoFileName = "git-daemon-export-ok"
package main import ( "fmt" "reflect" "testing" "github.com/nlopes/slack" ) const ( SLACK_HOST_NAME = "<http://google.com|google.com>" EXPECTED_HOSTNAME = "google.com" ) func TestParseName(t *testing.T) { result := parseName(SLACK_HOST_NAME) if result != EXPECTED_HOSTNAME { t.Error( "expected", EXPECTED_HOSTNAME, "got", result, ) } } func TestFormatMessage(t *testing.T) { attr := Attribute{ CheckCommand: "apt", DisplayName: "apt", Name: "apt", State: 3.0, CheckTime: 1501416820.43347, HostName: "d0b2c373f2ac", } expectedAttachment := &slack.Attachment{ Title: "Icinga 2 - Dashboard", TitleLink: fmt.Sprintf("http://%s/icingaweb2/dashboard", config.Icinga2.Host), Color: LIST_OF_STATUS[attr.State].Color, Fields: []slack.AttachmentField{ slack.AttachmentField{ Title: "Command", Value: attr.CheckCommand, Short: true, }, slack.AttachmentField{ Title: "Display Name", Value: attr.DisplayName, Short: true, }, slack.AttachmentField{ Title: "Name", Value: attr.Name, Short: true, }, slack.AttachmentField{ Title: "State", Value: LIST_OF_STATUS[attr.State].Label, Short: true, }, slack.AttachmentField{ Title: "Hostname", Value: attr.HostName, Short: true, }, }, Footer: "mlabouardy", FooterIcon: "https://yt3.ggpht.com/-VxW-2wCxzHs/AAAAAAAAAAI/AAAAAAAAAAA/fjyskzeA-VA/s900-c-k-no-mo-rj-c0xffffff/photo.jpg", } resultAttachment := formatMessage(attr, SERVICES) if !reflect.DeepEqual(expectedAttachment, resultAttachment) { t.Error( "expected", expectedAttachment, "got", resultAttachment, ) } }
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved. // // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, // You can obtain one at https://github.com/gogf/gf. // HTTP客户端请求. package ghttp func Get(url string) (*ClientResponse, error) { return DoRequest("GET", url) } func Put(url string, data...string) (*ClientResponse, error) { return DoRequest("PUT", url, data...) } func Post(url string, data...string) (*ClientResponse, error) { return DoRequest("POST", url, data...) } func Delete(url string, data...string) (*ClientResponse, error) { return DoRequest("DELETE", url, data...) } func Head(url string, data...string) (*ClientResponse, error) { return DoRequest("HEAD", url, data...) } func Patch(url string, data...string) (*ClientResponse, error) { return DoRequest("PATCH", url, data...) } func Connect(url string, data...string) (*ClientResponse, error) { return DoRequest("CONNECT", url, data...) } func Options(url string, data...string) (*ClientResponse, error) { return DoRequest("OPTIONS", url, data...) } func Trace(url string, data...string) (*ClientResponse, error) { return DoRequest("TRACE", url, data...) } // 该方法支持二进制提交数据 func DoRequest(method, url string, data...string) (*ClientResponse, error) { return NewClient().DoRequest(method, url, data...) } // GET请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针) func GetContent(url string, data...string) string { return RequestContent("GET", url, data...) } // PUT请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针) func PutContent(url string, data...string) string { return RequestContent("PUT", url, data...) } // POST请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针) func PostContent(url string, data...string) string { return RequestContent("POST", url, data...) } // DELETE请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针) func DeleteContent(url string, data...string) string { return RequestContent("DELETE", url, data...) } func HeadContent(url string, data...string) string { return RequestContent("HEAD", url, data...) } func PatchContent(url string, data...string) string { return RequestContent("PATCH", url, data...) } func ConnectContent(url string, data...string) string { return RequestContent("CONNECT", url, data...) } func OptionsContent(url string, data...string) string { return RequestContent("OPTIONS", url, data...) } func TraceContent(url string, data...string) string { return RequestContent("TRACE", url, data...) } // 请求并返回服务端结果(内部会自动读取服务端返回结果并关闭缓冲区指针) func RequestContent(method string, url string, data...string) string { return NewClient().DoRequestContent(method, url, data...) }
package conflint import ( "bufio" "bytes" "fmt" "io" "io/ioutil" "log" "os" "os/exec" "path/filepath" "strings" yaml "gopkg.in/yaml.v3" ) type Runner struct { Output io.Writer ConfigFile string Errformat string WorkDir string Delim string LogLevel string } type Config struct { Conftest []ConftestConfig `yaml:"conftest"` Kubeval []KubevalConfig `yaml:"kubeval"` } type ConftestConfig struct { Files []string `yaml:"files"` Policy string `yaml:"policy"` Input string `yaml:"input"` Combine bool `yaml:"combine"` FailOnWarn bool `yaml:"failOnWarn"` Data []string `yaml:"data"` AllNamespaces bool `yaml:"allNamespaces` Namespaces []string `yaml:"namespaces"` } type KubevalConfig struct { Files []string `yaml:"files"` Strict bool `yaml:"strict"` SchemaLocations []string `yaml:"schemaLocations"` IgnoreMissingSchemas bool `yaml:"ignoreMissingSchemas"` IgnoredFilenamePatterns []string `yaml:"ignoredFilenamePatterns` SkipKinds []string `yaml:"skipKinds"` } type KubevalOutput = []KubevalFileResult type KubevalFileResult struct { Filename string `yaml:"filename"` Kind string `yaml:"kind"` Status string `yaml:"status"` Errors []string `yaml:"errors"` } type ConftestOutput = []ConftestFileResult type ConftestFileResult struct { Filename string `yaml:"filename"` Warnings []ConftestResult `yaml:"warnings"` Failures []ConftestResult `yaml:"failures"` } type ConftestResult struct { Msg string `yaml:"msg"` } func (r *Runner) Run() error { var config Config file := filepath.Join(r.WorkDir, r.ConfigFile) bs, err := ioutil.ReadFile(file) if err != nil { return err } if err := yaml.Unmarshal(bs, &config); err != nil { return err } var output int if len(config.Conftest) > 0 { _, err := exec.LookPath("conftest") if err != nil { return fmt.Errorf("looking for executable: \"conftest\" not found in PATH") } } for _, ct := range config.Conftest { for _, fp := range ct.Files { files, err := filepath.Glob(filepath.Join(r.WorkDir, fp)) if err != nil { return fmt.Errorf("searching files matching %s: %w", fp, err) } var fs []string for _, f := range files { f = strings.TrimPrefix(f, r.WorkDir) f = strings.TrimPrefix(f, "/") fs = append(fs, f) } args := []string{"test"} args = append(args, fs...) args = append(args, "-p", ct.Policy, "-o", "json") if ct.Input != "" { args = append(args, "-i", ct.Input) } if ct.Combine { args = append(args, "--combine") } if ct.AllNamespaces { args = append(args, "--all-namespaces") } if len(ct.Data) > 0 { args = append(args, "--data", strings.Join(ct.Data, ",")) } if len(ct.Namespaces) > 0 { args = append(args, "--namespace", strings.Join(ct.Namespaces, ",")) } cmd := exec.Command("conftest", args...) cmd.Dir = r.WorkDir out, err := cmd.CombinedOutput() if err != nil && r.LogLevel == "DEBUG" { fmt.Fprintf(os.Stderr, "DEBUG: running conftest %s: %v\n", strings.Join(args, " "), err) } var conftestOut ConftestOutput if err := yaml.Unmarshal(out, &conftestOut); err != nil { return err } for _, res := range conftestOut { handle := func(msg string) error { sub := strings.SplitN(msg, r.Delim, 2) if len(sub) > 1 { line, col, err := getLineColFromJsonpathExpr(filepath.Join(r.WorkDir, res.Filename), "$."+sub[0]) if err != nil { return fmt.Errorf("processing %s: %w", sub[0], err) } if err := r.Print(res.Filename, line, col, sub[1]); err != nil { return fmt.Errorf("printing %s: %w", sub[1], err) } output++ } else { log.Printf("ignoring unsupported output: %s", msg) } return nil } for _, f := range res.Failures { if err := handle(f.Msg); err != nil { return err } } } } } if len(config.Kubeval) > 0 { _, err := exec.LookPath("kubeval") if err != nil { return fmt.Errorf("looking for executable: \"kubeval\" not found in PATH") } } for _, ke := range config.Kubeval { for _, fp := range ke.Files { files, err := filepath.Glob(filepath.Join(r.WorkDir, fp)) if err != nil { return fmt.Errorf("searching files matching %s: %w", fp, err) } for _, f := range files { f = strings.TrimPrefix(f, r.WorkDir) f = strings.TrimPrefix(f, "/") args := []string{f, "-o", "json"} if ke.Strict { args = append(args, "--strict") } if ke.IgnoreMissingSchemas { args = append(args, "--ignore-missing-schemas") } if len(ke.IgnoredFilenamePatterns) > 0 { args = append(args, "--ignored-filename-patterns", strings.Join(ke.IgnoredFilenamePatterns, ",")) } if len(ke.SkipKinds) > 0 { args = append(args, "--skip-kinds", strings.Join(ke.SkipKinds, ",")) } if len(ke.SchemaLocations) > 0 { args = append(args, "--schema-location", ke.SchemaLocations[0]) if len(ke.SchemaLocations) > 1 { args = append(args, "--additional-schema-locations", strings.Join(ke.SchemaLocations[1:], ",")) } } cmd := exec.Command("kubeval", args...) cmd.Dir = r.WorkDir out, err := cmd.CombinedOutput() if err != nil && r.LogLevel == "DEBUG" { fmt.Fprintf(os.Stderr, "DEBUG: running kubeval %s: %v\n", strings.Join(args, " "), err) } var effectiveLines []string allLines := bufio.NewScanner(bytes.NewReader(out)) for allLines.Scan() { line := allLines.Text() if strings.HasPrefix(line, "WARN - Set to ignore missing schemas") { } else { effectiveLines = append(effectiveLines, line) } } var conftestOut KubevalOutput jsonDocText := []byte(strings.Join(effectiveLines, "\n")) if err := yaml.Unmarshal(jsonDocText, &conftestOut); err != nil { fmt.Fprintf(os.Stderr, "kubeeval failed with output:\n%s", string(out)) return fmt.Errorf("unmarshalling yaml: %w", err) } for _, res := range conftestOut { handle := func(msg string) error { sub := strings.SplitN(msg, ": ", 2) if len(sub) > 1 { line, col, err := getLineColFromJsonpathExpr(filepath.Join(r.WorkDir, f), "$."+sub[0]) if err != nil { return fmt.Errorf("processing %s: %w", sub[0], err) } if err := r.Print(f, line, col, sub[1]); err != nil { return fmt.Errorf("printing %s: %w", sub[1], err) } output++ } else { log.Printf("ignoring unsupported output: %s", msg) } return nil } for _, f := range res.Errors { if err := handle(f); err != nil { return err } } } } } } if output > 0 { var word string if output > 1 { word = "errors" } else { word = "error" } return fmt.Errorf("found %d linter %s", output, word) } return nil } func getLineColFromJsonpathExpr(file string, jsonpathExpr string) (int, int, error) { if jsonpathExpr[0] != '$' { return 0, 0, fmt.Errorf("Expression must start with $, but got: %s", jsonpathExpr) } path, err := parseJsonpath(jsonpathExpr) if err != nil { return 0, 0, fmt.Errorf("parsing jsonpath %s: %w", jsonpathExpr, err) } f, err := os.Open(file) if err != nil { return 0, 0, fmt.Errorf("opening file %s: %w", file, err) } defer f.Close() dec := yaml.NewDecoder(f) next := func() (*yaml.Node, error) { doc := &yaml.Node{} if err := dec.Decode(doc); err != nil { if err == io.EOF { return nil, nil } return nil, fmt.Errorf("decoding yaml from %s: %w", file, err) } if doc.Kind != yaml.DocumentNode { panic(fmt.Errorf("the top-level yaml node must be a document node. got %v", doc.Kind)) } node := doc.Content[0] if node.Kind != yaml.MappingNode { panic(fmt.Errorf("the only yaml node in a document must be a mapping node. got %v", node.Kind)) } got, err := path.Get(node) if err != nil { return nil, fmt.Errorf("getting node at %s: %w", jsonpathExpr, err) } return got, nil } var lastErr error for { node, err := next() if node != nil { return node.Line, node.Column, nil } if err == nil { break } lastErr = err } if lastErr != nil { return 0, 0, fmt.Errorf("getting line and column numbers from %s: %w", file, lastErr) } return 0, 0, fmt.Errorf("gettling line and colum numbers from %s: no value found at %s", file, jsonpathExpr) } func (r *Runner) Print(file string, line, col int, msg string) error { // TODO maybe use https://github.com/phayes/checkstyle for additional checkstyle xml output? replacer := strings.NewReplacer("%m", msg, "%f", file, "%l", fmt.Sprintf("%d", line), "%c", fmt.Sprintf("%d", col)) printed := replacer.Replace(r.Errformat) if _, err := r.Output.Write([]byte(printed)); err != nil { return err } if _, err := r.Output.Write([]byte("\n")); err != nil { return err } return nil }
package group_the_people_given_the_group_size_they_belong_to import ( "github.com/stretchr/testify/assert" "testing" ) func Test_GroupThePeople(t *testing.T) { groupSizes := []int{2, 1, 3, 3, 3, 2} assert.ElementsMatch(t, groupThePeople(groupSizes), [][]int{[]int{1}, []int{0, 5}, []int{2, 3, 4}}) groupSizes = []int{3, 3, 3, 3, 3, 1, 3} assert.ElementsMatch(t, groupThePeople(groupSizes), [][]int{[]int{0, 1, 2}, []int{5}, []int{3, 4, 6}}) }
package minecraft import ( "fmt" "strings" "testing" ) var tests = []struct { name string input string want string }{ { name: "plain message", input: "plain message", want: `{"text":"plain message"}`, }, { name: "single sentinel", input: "$$", want: `{"text":"$"}`, }, { name: "random interleaves", input: "this$b has$i some random $s chars put $b throughout $i it $u have fun $r with this", want: `[{"text":"this"},{"text":" has","bold":true},{"text":" some random ","bold":true,"italic":true},` + `{"text":" chars put ","bold":true,"italic":true,"strikethrough":true},` + `{"text":" throughout ","italic":true,"strikethrough":true},{"text":" it ","strikethrough":true},` + //nolint:misspell // minecraft devs cant spell colour either `{"text":" have fun ","underlined":true,"strikethrough":true},{"text":" with this","color":"reset"}]`, }, { name: "colour spam", input: "this $cFFFFFFhas a bunch of $c000000colours in it so$c012345 it can test $r colour barf", //nolint:misspell // minecraft devs cant spell colour either want: `[{"text":"this "},{"text":"has a bunch of ","color":"white"},` + `{"text":"colours in it so","color":"black"},{"text":" it can test ","color":"black"},` + `{"text":" colour barf","color":"reset"}]`, }, { name: "extra formatting", input: "A thing$b with$b$bsome weird$iformats$b$i$i and $b stuff", want: `[{"text":"A thing"},{"text":" with","bold":true},{"text":"some weird","bold":true},` + `{"text":"formats","bold":true,"italic":true},{"text":" and ","italic":true},` + `{"text":" stuff","bold":true,"italic":true}]`, }, { name: "URL test", input: "hey check out this thing! https://awesome-dragon.science/go/goGoGameBot it has cool stuff!", want: `[{"text":"hey check out this thing! "},` + `{"text":"https://awesome-dragon.science/go/goGoGameBot",` + `"underlined":true,"color":"blue","clickEvent":{"action":"open_url",` + //nolint:misspell // no choice `"value":"https://awesome-dragon.science/go/goGoGameBot"}},{"text":" it has cool stuff!"}]`, }, { name: "url test 2", input: "https://google.com", want: `{"text":"https://google.com","underlined":true,"color":"blue",` + `"clickEvent":{"action":"open_url","value":"https://google.com"}}`, }, { name: "url test 3", input: "this is a test https://google.com", want: `[{"text":"this is a test "},` + `{"text":"https://google.com","underlined":true,"color":"blue","clickEvent":` + `{"action":"open_url","value":"https://google.com"}}]`, }, { name: "url leader", input: "https://github.com/ this is a test", want: `[{"text":""},{"text":"https://github.com/","underlined":true,"color":"blue",` + `"clickEvent":{"action":"open_url","value":"https://github.com/"}},{"text":" this is a test"}]`, }, { name: "test using actual line", input: "$c666666$i[#totallynotgames]$rtest message", want: `[{"text":""},{"text":"[#totallynotgames]","italic":true,"color":"dark_gray"},` + //nolint:misspell // no choice `{"text":"test message","color":"reset"}]`, //nolint:misspell // no choice }, } func findFirstDiff(s1, s2 string) { longer := s1 shorter := s2 if len(s1) < len(s2) { longer = s2 shorter = s1 } differencesStartAt := 0 for i := 0; i < len(shorter); i++ { if shorter[i] != longer[i] { differencesStartAt = i break } } if differencesStartAt > 0 { fmt.Println("1:", shorter) fmt.Println("2:", longer) fmt.Println(strings.Repeat(" ", differencesStartAt) + "^") } } func TestTransformer_Transform(t *testing.T) { for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { if got := (Transformer{}).Transform(tt.input); got != tt.want { t.Errorf("Transform(): got %s, want %s", got, tt.want) findFirstDiff(got, tt.want) } }) } }
package mat import ( "math" ) func NewRay(origin Tuple4, direction Tuple4) Ray { return Ray{Origin: origin, Direction: direction} } type Ray struct { Origin Tuple4 Direction Tuple4 } // Position multiplies direction of ray with the passed distance and adds the result onto the origin. // Used for finding the position along a ray. func Position(r Ray, distance float64) Tuple4 { add := MultiplyByScalar(r.Direction, distance) pos := Add(r.Origin, add) return pos } func PositionPtr(r Ray, distance float64, out *Tuple4) { add := MultiplyByScalar(r.Direction, distance) AddPtr(r.Origin, add, out) } // TODO only used by unit tests, fix so tests use IntersectRayWithShapePtr and remove func IntersectRayWithShape(s Shape, r2 Ray) []Intersection { // transform ray with inverse of shape transformation matrix to be able to intersect a translated/rotated/skewed shape r := TransformRay(r2, s.GetInverse()) // Call the intersect function provided by the shape implementation (e.g. Sphere, Plane osv) return s.IntersectLocal(r) } func IntersectRayWithShapePtr(s Shape, r2 Ray, in *Ray) []Intersection { //calcstats.Incr() // transform ray with inverse of shape transformation matrix to be able to intersect a translated/rotated/skewed shape TransformRayPtr(r2, s.GetInverse(), in) // Call the intersect function provided by the shape implementation (e.g. Sphere, Plane osv) return s.IntersectLocal(*in) } // Hit finds the first intersection with a positive T (the passed intersections are assumed to have been sorted already) func Hit(intersections []Intersection) (Intersection, bool) { // Filter out all negatives for i := 0; i < len(intersections); i++ { if intersections[i].T > 0.0 { return intersections[i], true //xs = append(xs, i) } } return Intersection{}, false } func TransformRay(r Ray, m1 Mat4x4) Ray { origin := MultiplyByTuple(m1, r.Origin) direction := MultiplyByTuple(m1, r.Direction) return NewRay(origin, direction) } func TransformRayPtr(r Ray, m1 Mat4x4, out *Ray) { MultiplyByTuplePtr(&m1, &r.Origin, &out.Origin) MultiplyByTuplePtr(&m1, &r.Direction, &out.Direction) } func Schlick(comps Computation) float64 { // find the cosine of the angle between the eye and normal vectors using Dot cos := Dot(comps.EyeVec, comps.NormalVec) // total internal reflection can only occur if n1 > n2 if comps.N1 > comps.N2 { n := comps.N1 / comps.N2 sin2Theta := (n * n) * (1.0 - (cos * cos)) if sin2Theta > 1.0 { return 1.0 } // compute cosine of theta_t using trig identity cosTheta := math.Sqrt(1.0 - sin2Theta) // when n1 > n2, use cos(theta_t) instead cos = cosTheta } temp := (comps.N1 - comps.N2) / (comps.N1 + comps.N2) r0 := temp * temp return r0 + (1-r0)*math.Pow(1-cos, 5) }
package protocol import "fmt" var errHeaderLength = fmt.Errorf(fmt.Sprintf("at least %d bytes", HeaderLength)) type errMessageLength struct { need, actually int } func (p *errMessageLength) Error() string { return fmt.Sprintf("broken message bytes: need=%d, actually=%d", p.need, p.actually) } type errMessageOffset struct { offset, totals int } func (p *errMessageOffset) Error() string { return fmt.Sprintf("broken message: read=%d, total=%d", p.offset, p.totals) }
package main import ( "flag" "fmt" ) const ( r0 = iota r1 r2 wa wb wc xl xr xs ia ra cp ) const ( xt = xs ) var regName = map[int]string{ r0: "r0", r1: "r1", r2: "r2", wa: "wa", wb: "wb", wc: "wc", xl: "xl", xr: "xr", xs: "xs", ia: "ia", ra: "ra", cp: "cp", } /* const ( atn = iota chp cos etx lnf sin sqr tan ) */ /* operation encoded in four parts: _w gives width in bits _m gives mask to extract value operand encod */ const ( op_w = 8 dst_w = 4 src_w = 4 off_w = 16 op_m = 1<<op_w - 1 dst_m = 1<<dst_w - 1 src_m = 1<<src_w - 1 off_m = 1<<off_w - 1 op_ = 0 dst_ = op_ + op_w src_ = dst_ + dst_w off_ = src_ + src_w ) const ( stackLength = 1000 ) var opName = map[int]string{ add: "add", adi: "adi", adr: "adr", anb: "anb", aov: "aov", bct: "bct", beq: "beq", bev: "bev", bge: "bge", bgt: "bgt", bhi: "bhi", ble: "ble", blo: "blo", blt: "blt", bne: "bne", bnz: "bnz", bod: "bod", bri: "bri", brn: "brn", bsw: "bsw", bze: "bze", call: "call", chk: "chk", cmc: "cmc", cne: "cne", cvd: "cvd", cvm: "cvm", dca: "dca", dcv: "dcv", dvi: "dvi", dvr: "dvr", erb: "erb", err: "err", exi: "exi", flc: "flc", ica: "ica", icp: "icp", icv: "icv", ieq: "ieq", ige: "ige", igt: "igt", ile: "ile", ilt: "ilt", ine: "ine", ino: "ino", iov: "iov", itr: "itr", jsrerr: "jsrerr", lcp: "lcp", lcw: "lcw", ldi: "ldi", ldr: "ldr", lei: "lei", load: "load", loadcfp: "loadcfp", loadi: "loadi", lsh: "lsh", mfi: "mfi", mli: "mli", mlr: "mlr", mov: "mov", move: "move", mvc: "mvc", mvw: "mvw", mwb: "mwb", ngi: "ngi", ngr: "ngr", nzb: "nzb", orb: "orb", plc: "plc", pop: "pop", popr: "popr", ppm: "ppm", prc: "prc", psc: "psc", push: "push", pushi: "pushi", pushr: "pushr", realop: "realop", req: "req", rge: "rge", rgt: "rgt", rle: "rle", rlt: "rlt", rmi: "rmi", rne: "rne", rno: "rno", rov: "rov", rsh: "rsh", rti: "rti", sbi: "sbi", sbr: "sbr", scp: "scp", store: "store", sub: "sub", sys: "sys", trc: "trc", xob: "xob", zrb: "zrb", } var ( ip int mem [100000]int reg [16]int stackEnd int memLast int // index of last allocated memory word long1, long2 int64 prcstack [32]int inst, dst, src int off int overflow bool op int // var f1, f2 float32 d1 float64 // itrace traces instructions, strace traces statements, otrace traces osint calls itrace, otrace, strace bool ifileName string instCount = 0 // number of instructions executed stmtCount = 0 // number of statements executed (stmt opcode) instLimit = 100000000 // maximum number of instructions stmtLimit = 100000000 // maximum number of statements stmtTrace = false instTrace = false maxOffset = 0 ) func main() { flag.BoolVar(&itrace, "it", false, "intstruction trace") flag.BoolVar(&otrace, "ot", false, "osint call trace") flag.BoolVar(&strace, "st", false, "statement trace") flag.Parse() if flag.NArg() == 0 { fmt.Println("argument file required") return } ifileName = flag.Arg(0) if itrace || strace { otrace = true } _ = ifileName _ = startup() fmt.Println() fmt.Println("Minimal instructions executed", stmtCount) fmt.Println("Machine instructions executed", instCount) fmt.Println("Maximum offset", maxOffset) }
package types import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/types" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" ) // RegisterLegacyAminoCodec registers concrete types on the Amino codec func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { cdc.RegisterConcrete(&MsgMemorializeContractRequest{}, "provenance/metadata/MemorializeContractRequest", nil) cdc.RegisterConcrete(&MsgChangeOwnershipRequest{}, "provenance/metadata/ChangeOwnershipRequest", nil) cdc.RegisterConcrete(&MsgAddScopeRequest{}, "provenance/metadata/AddScopeRequest", nil) cdc.RegisterConcrete(&MsgDeleteScopeRequest{}, "provenance/metadata/DeleteScopeRequest", nil) cdc.RegisterConcrete(&MsgAddSessionRequest{}, "provenance/metadata/AddSessionRequest", nil) cdc.RegisterConcrete(&MsgAddRecordRequest{}, "provenance/metadata/AddRecordRequest", nil) cdc.RegisterConcrete(&MsgAddScopeSpecificationRequest{}, "provenance/metadata/AddScopeSpecificationRequest", nil) cdc.RegisterConcrete(&MsgDeleteScopeSpecificationRequest{}, "provenance/metadata/DeleteScopeSpecificationRequest", nil) cdc.RegisterConcrete(&MsgAddContractSpecificationRequest{}, "provenance/metadata/AddContractSpecificationRequest", nil) cdc.RegisterConcrete(&MsgDeleteContractSpecificationRequest{}, "provenance/metadata/DeleteContractSpecificationRequest", nil) cdc.RegisterConcrete(&MsgAddRecordSpecificationRequest{}, "provenance/metadata/AddRecordSpecificationRequest", nil) cdc.RegisterConcrete(&MsgDeleteRecordSpecificationRequest{}, "provenance/metadata/DeleteRecordSpecificationRequest", nil) cdc.RegisterConcrete(&MsgAddP8EContractSpecRequest{}, "provenance/metadata/AddP8EContractSpecRequest", nil) } // RegisterInterfaces registers implementations for the tx messages func RegisterInterfaces(registry types.InterfaceRegistry) { registry.RegisterImplementations((*sdk.Msg)(nil), &MsgMemorializeContractRequest{}, &MsgChangeOwnershipRequest{}, &MsgAddScopeRequest{}, &MsgDeleteScopeRequest{}, &MsgAddSessionRequest{}, &MsgAddRecordRequest{}, &MsgAddScopeSpecificationRequest{}, &MsgDeleteScopeSpecificationRequest{}, &MsgAddContractSpecificationRequest{}, &MsgDeleteContractSpecificationRequest{}, &MsgAddRecordSpecificationRequest{}, &MsgDeleteRecordSpecificationRequest{}, &MsgAddP8EContractSpecRequest{}, ) msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) } var ( amino = codec.NewLegacyAmino() // ModuleCdc references the global x/metadata module codec. Note, the codec should // ONLY be used in certain instances of tests and for JSON encoding as Amino is // still used for that purpose. // // The actual codec used for serialization should be provided to x/metadata and // defined at the application level. ModuleCdc = codec.NewAminoCodec(amino) ) func init() { RegisterLegacyAminoCodec(amino) cryptocodec.RegisterCrypto(amino) amino.Seal() }
package problem0020 import "testing" func TestSolve(t *testing.T) { t.Log(isValid("([]))")) t.Log(isValid("[]")) t.Log(isValid("{[()]}")) t.Log(isValid("{}[]()")) t.Log(isValid("({}[])")) }
package main import ( "fmt" "github.com/slack-go/slack" ) // An example how to open a modal with different kinds of input fields func main() { // Create a ModalViewRequest with a header and two inputs titleText := slack.NewTextBlockObject(slack.PlainTextType, "Create channel demo", false, false) closeText := slack.NewTextBlockObject(slack.PlainTextType, "Close", false, false) submitText := slack.NewTextBlockObject(slack.PlainTextType, "Submit", false, false) contextText := slack.NewTextBlockObject(slack.MarkdownType, "This app demonstrates the use of different fields", false, false) contextBlock := slack.NewContextBlock("context", contextText) // Only the inputs in input blocks will be included in view_submission’s view.state.values: https://slack.dev/java-slack-sdk/guides/modals // This means the inputs will not be interactive either because they do not trigger block_actions messages: https://api.slack.com/surfaces/modals/using#interactions channelNameText := slack.NewTextBlockObject(slack.PlainTextType, "Channel Name", false, false) channelNameHint := slack.NewTextBlockObject(slack.PlainTextType, "Channel names may only contain lowercase letters, numbers, hyphens, and underscores, and must be 80 characters or less", false, false) channelPlaceholder := slack.NewTextBlockObject(slack.PlainTextType, "New channel name", false, false) channelNameElement := slack.NewPlainTextInputBlockElement(channelPlaceholder, "channel_name") // Slack channel names can be maximum 80 characters: https://api.slack.com/methods/conversations.create channelNameElement.MaxLength = 80 channelNameBlock := slack.NewInputBlock("channel_name", channelNameText, channelNameHint, channelNameElement) // Provide a static list of users to choose from, those provided now are just made up user IDs // Get user IDs by right clicking on them in Slack, select "Copy link", and inspect the last part of the link // The user ID should start with "U" followed by 8 random characters memberOptions := createOptionBlockObjects([]string{"U9911MMAA", "U2233KKNN", "U00112233"}, true) inviteeText := slack.NewTextBlockObject(slack.PlainTextType, "Invitee from static list", false, false) inviteeOption := slack.NewOptionsSelectBlockElement(slack.OptTypeStatic, nil, "invitee", memberOptions...) inviteeBlock := slack.NewInputBlock("invitee", inviteeText, nil, inviteeOption) // Section with users select - this input will not be included in the view_submission's view.state.values, // but instead be sent as a "block_actions" request additionalInviteeText := slack.NewTextBlockObject(slack.PlainTextType, "Invitee from complete list of users", false, false) additionalInviteeHintText := slack.NewTextBlockObject(slack.PlainTextType, "", false, false) additionalInviteeOption := slack.NewOptionsSelectBlockElement(slack.OptTypeUser, additionalInviteeText, "user") additionalInviteeSection := slack.NewSectionBlock(additionalInviteeText, nil, slack.NewAccessory(additionalInviteeOption)) // Input with users select - this input will be included in the view_submission's view.state.values // It can be fetched as for example "payload.View.State.Values["user"]["user"].SelectedUser" additionalInviteeBlock := slack.NewInputBlock("user", additionalInviteeText, additionalInviteeHintText, additionalInviteeOption) checkboxTxt := slack.NewTextBlockObject(slack.PlainTextType, "Checkbox", false, false) checkboxOptions := createOptionBlockObjects([]string{"option 1", "option 2", "option 3"}, false) checkboxOptionsBlock := slack.NewCheckboxGroupsBlockElement("chkbox", checkboxOptions...) checkboxBlock := slack.NewInputBlock("chkbox", checkboxTxt, nil, checkboxOptionsBlock) summaryText := slack.NewTextBlockObject(slack.PlainTextType, "Summary", false, false) summaryHint := slack.NewTextBlockObject(slack.PlainTextType, "Summary Hint", false, false) summaryPlaceholder := slack.NewTextBlockObject(slack.PlainTextType, "Summary of reason for creating channel", false, false) summaryElement := slack.NewPlainTextInputBlockElement(summaryPlaceholder, "summary") // Just set an arbitrary max length to avoid too prose summary summaryElement.MaxLength = 200 summaryElement.Multiline = true summaryBlock := slack.NewInputBlock("summary", summaryText, summaryHint, summaryElement) blocks := slack.Blocks{ BlockSet: []slack.Block{ contextBlock, channelNameBlock, inviteeBlock, additionalInviteeSection, additionalInviteeBlock, checkboxBlock, summaryBlock, }, } var modalRequest slack.ModalViewRequest modalRequest.Type = slack.ViewType("modal") modalRequest.Title = titleText modalRequest.Close = closeText modalRequest.Submit = submitText modalRequest.Blocks = blocks modalRequest.CallbackID = "create_channel" api := slack.New("YOUR_BOT_TOKEN_HERE") // Using a trigger ID you can open a modal // The trigger ID is provided through certain events and interactions // More information can be found here: https://api.slack.com/interactivity/handling#modal_responses _, err := api.OpenView("YOUR_TRIGGERID_HERE", modalRequest) if err != nil { fmt.Printf("Error opening view: %s", err) } } // createOptionBlockObjects - utility function for generating option block objects func createOptionBlockObjects(options []string, users bool) []*slack.OptionBlockObject { optionBlockObjects := make([]*slack.OptionBlockObject, 0, len(options)) var text string for _, o := range options { if users { text = fmt.Sprintf("<@%s>", o) } else { text = o } optionText := slack.NewTextBlockObject(slack.PlainTextType, text, false, false) optionBlockObjects = append(optionBlockObjects, slack.NewOptionBlockObject(o, optionText, nil)) } return optionBlockObjects }
/* This module provides functionality of adding and combining and parsing custom layer with an actual packet. */ package packaging import ( "github.com/google/gopacket" "net" "github.com/LaundeLapate/RouteIt/pkg" "github.com/google/gopacket/layers" "github.com/sirupsen/logrus" ) // This method allow us to add combine actual // packet with custom layer to make is // transportable from the punched hole over the // NAT. func AddCustomLayerToPacketInfo(dstIP net.IP, dstPort uint16, nonCustomPacket PacketInfo, customLayerParameters CustomLayer) PacketInfo { customPacket := PacketInfo{} newIPLayer := pkg.IPLayerForPrototype newUDPLayer := pkg.UDPLayerForPrototype // Constructing IP layer for a packet. newIPLayer.DstIP = dstIP newIPLayer.SrcIP = pkg.ServerAddr.IP newIPLayer.Protocol = layers.IPProtocolUDP // Creating the custom payload as combination // custom layer and all the value from above // Ethernet layer. payloadFromIPlayer := append(nonCustomPacket.IpLayer.Contents, nonCustomPacket.IpLayer.Payload...) payloadForCustomLayer := append(customLayerParameters.CovertCustomLayerToBytes(), payloadFromIPlayer...) // Constructing Transport layer for the packet. newUDPLayer.SrcPort = layers.UDPPort(pkg.HolePunchPort) customPacket.TspLayer.SrcPort = pkg.HolePunchPort newUDPLayer.DstPort = layers.UDPPort(dstPort) customPacket.TspLayer.DstPort = dstPort newUDPLayer.Payload = payloadForCustomLayer // Updating the lenght of various layers. newUDPLayer.Length += uint16(len(payloadForCustomLayer)) newIPLayer.Length += newUDPLayer.Length // Appending all the parameters to our // custom layer. customPacket.IpLayer = newIPLayer customPacket.TspLayer.TransLayer = &newUDPLayer customPacket.RemainingPayload = payloadForCustomLayer return customPacket } // This method allow us to extract custom layer // from the provided custom packets. func ExtractCustomLayer(customPacket PacketInfo) (PacketInfo, CustomLayer, error) { // custom layer information in bytes. customLayerInformation := customPacket.RemainingPayload[:pkg.CustomLayerByteSize] // Removing bytes corresponding to custom // layer. customPacket.RemainingPayload = customPacket.RemainingPayload[pkg.CustomLayerByteSize:] nonCustomPacketData := append(customPacket.EthernetLayer.Contents, customPacket.RemainingPayload...) // Creating new packet corresponding to the bytes set. newPacketCreated := gopacket.NewPacket(nonCustomPacketData, layers.LayerTypeEthernet, gopacket.Default) ExtractedPacketInfo := &PacketInfo{} // Extracting information from the custom layer. customPacketInfo := CustomLayer{} err := customPacketInfo.CreateLayerFromByte(customLayerInformation) if err != nil { logrus.Debugf("Error during extraction information for the " + "for the custom struct") return *ExtractedPacketInfo, customPacketInfo, err } // Extracting packet information from the byte's data. err = ExtractedPacketInfo.ExtractInformation(newPacketCreated, true) if err != nil { logrus.Debugf("Error during extraction of information " + "from newly created from the custom Packet \n") return *ExtractedPacketInfo, customPacketInfo, err } return *ExtractedPacketInfo, customPacketInfo, nil }
package influxdb import ( "reflect" "regexp" "sort" "testing" ) // Ensure that the index will return a sorted array of measurement names. func TestDatabase_Names(t *testing.T) { idx := databaseWithFixtureData() r := idx.Names() exp := []string{"another_thing", "cpu_load", "key_count", "queue_depth"} if !reflect.DeepEqual(r, exp) { t.Fatalf("Names not equal:\n got: %s\n exp: %s", r, exp) } } // Ensure that we can get the measurement by the series ID. func TestDatabase_MeasurementBySeriesID(t *testing.T) { idx := newDatabase() m := &Measurement{ Name: "cpu_load", } s := &Series{ ID: uint32(1), Tags: map[string]string{"host": "servera.influx.com", "region": "uswest"}, } // add it and see if we can look it up idx.addSeriesToIndex(m.Name, s) mm := idx.MeasurementBySeriesID(uint32(1)) if string(mustMarshalJSON(m)) != string(mustMarshalJSON(mm)) { t.Fatalf("mesurement not equal:\n%v\n%v", m, mm) } // now test that we can add another s = &Series{ ID: uint32(2), Tags: map[string]string{"host": "serverb.influx.com", "region": "uswest"}} idx.addSeriesToIndex(m.Name, s) mm = idx.MeasurementBySeriesID(uint32(2)) if string(mustMarshalJSON(m)) != string(mustMarshalJSON(mm)) { t.Fatalf("mesurement not equal:\n%v\n%v", m, mm) } mm = idx.MeasurementBySeriesID(uint32(1)) if string(mustMarshalJSON(m)) != string(mustMarshalJSON(mm)) { t.Fatalf("mesurement not equal:\n%v\n%v", m, mm) } } // Ensure that we can get an array of unique measurements by a collection of series IDs. func TestDatabase_MeasurementsBySeriesIDs(t *testing.T) { idx := databaseWithFixtureData() ids := SeriesIDs([]uint32{uint32(1), uint32(4)}) names := make([]string, 0) for _, m := range idx.MeasurementsBySeriesIDs(ids) { names = append(names, m.Name) } sort.Strings(names) expected := []string{"cpu_load", "key_count"} if !reflect.DeepEqual(names, expected) { t.Fatalf("wrong measurements:\n exp: %s\n got: %s", expected, names) } } // Ensure that we can get the series object by the series ID. func TestDatabase_SeriesBySeriesID(t *testing.T) { idx := newDatabase() // now test that we can add another s := &Series{ ID: uint32(2), Tags: map[string]string{"host": "serverb.influx.com", "region": "uswest"}} idx.addSeriesToIndex("foo", s) ss := idx.SeriesByID(uint32(2)) if string(mustMarshalJSON(s)) != string(mustMarshalJSON(ss)) { t.Fatalf("series not equal:\n%v\n%v", s, ss) } } // Ensure that we can get the measurement and series objects out based on measurement and tags. func TestDatabase_MeasurementAndSeries(t *testing.T) { idx := newDatabase() m := &Measurement{ Name: "cpu_load", } s := &Series{ ID: uint32(1), Tags: map[string]string{"host": "servera.influx.com", "region": "uswest"}, } // add it and see if we can look it up by name and tags idx.addSeriesToIndex(m.Name, s) mm, ss := idx.MeasurementAndSeries(m.Name, s.Tags) if string(mustMarshalJSON(m)) != string(mustMarshalJSON(mm)) { t.Fatalf("mesurement not equal:\n%v\n%v", m, mm) } else if string(mustMarshalJSON(s)) != string(mustMarshalJSON(ss)) { t.Fatalf("series not equal:\n%v\n%v", s, ss) } // now test that we can add another s = &Series{ ID: uint32(2), Tags: map[string]string{"host": "serverb.influx.com", "region": "uswest"}} idx.addSeriesToIndex(m.Name, s) mm, ss = idx.MeasurementAndSeries(m.Name, s.Tags) if string(mustMarshalJSON(m)) != string(mustMarshalJSON(mm)) { t.Fatalf("mesurement not equal:\n%v\n%v", m, mm) } else if string(mustMarshalJSON(s)) != string(mustMarshalJSON(ss)) { t.Fatalf("series not equal:\n%v\n%v", s, ss) } } // Ensure that we can get the series IDs for measurements without any filters. func TestDatabase_SeriesIDs(t *testing.T) { idx := newDatabase() s := &Series{ ID: uint32(1), Tags: map[string]string{"host": "servera.influx.com", "region": "uswest"}} // add it and see if we can look it up added := idx.addSeriesToIndex("cpu_load", s) if !added { t.Fatal("couldn't add series") } // test that we can't add it again added = idx.addSeriesToIndex("cpu_load", s) if added { t.Fatal("shoulnd't be able to add duplicate series") } // now test that we can add another s = &Series{ ID: uint32(2), Tags: map[string]string{"host": "serverb.influx.com", "region": "uswest"}} added = idx.addSeriesToIndex("cpu_load", s) if !added { t.Fatalf("couldn't add series") } l := idx.SeriesIDs([]string{"cpu_load"}, nil) r := []uint32{1, 2} if !l.Equals(r) { t.Fatalf("series IDs not the same:\n%d\n%d", l, r) } // now add another in a different measurement s = &Series{ ID: uint32(3), Tags: map[string]string{"host": "serverb.influx.com", "region": "uswest"}} added = idx.addSeriesToIndex("network_in", s) if !added { t.Fatalf("couldn't add series") } l = idx.SeriesIDs([]string{"cpu_load"}, nil) r = []uint32{1, 2, 3} if !l.Equals(r) { t.Fatalf("series IDs not the same:\n%d\n%d", l, r) } } func TestDatabase_SeriesIDsWhereTagFilter(t *testing.T) { // TODO corylanou: this test is intermittently failing. Fix and re-enable // trace can be found here for failing test: https://gist.github.com/corylanou/afaf7d5e8508a3e559ea t.Skip() idx := databaseWithFixtureData() var tests = []struct { names []string filters []*TagFilter result []uint32 }{ // match against no tags { names: []string{"cpu_load", "redis"}, result: []uint32{uint32(1), uint32(2), uint32(3), uint32(4), uint32(5), uint32(6), uint32(7), uint32(8)}, }, // match against all tags { names: []string{"cpu_load"}, filters: []*TagFilter{ &TagFilter{Key: "host", Value: "servera.influx.com"}, &TagFilter{Key: "region", Value: "uswest"}, }, result: []uint32{uint32(1)}, }, // match against one tag { names: []string{"cpu_load"}, filters: []*TagFilter{ &TagFilter{Key: "region", Value: "uswest"}, }, result: []uint32{uint32(1), uint32(2)}, }, // match against one tag, single result { names: []string{"cpu_load"}, filters: []*TagFilter{ &TagFilter{Key: "host", Value: "servera.influx.com"}, }, result: []uint32{uint32(1)}, }, // query against tag key that doesn't exist returns empty { names: []string{"cpu_load"}, filters: []*TagFilter{ &TagFilter{Key: "foo", Value: "bar"}, }, result: []uint32{}, }, // query against tag value that doesn't exist returns empty { names: []string{"cpu_load"}, filters: []*TagFilter{ &TagFilter{Key: "host", Value: "foo"}, }, result: []uint32{}, }, // query against a tag NOT value { names: []string{"key_count"}, filters: []*TagFilter{ &TagFilter{Key: "region", Value: "useast", Not: true}, }, result: []uint32{uint32(3)}, }, // query against a tag NOT null { names: []string{"queue_depth"}, filters: []*TagFilter{ &TagFilter{Key: "app", Value: "", Not: true}, }, result: []uint32{uint32(6)}, }, // query against a tag value and another tag NOT value { names: []string{"queue_depth"}, filters: []*TagFilter{ &TagFilter{Key: "name", Value: "high priority"}, &TagFilter{Key: "app", Value: "paultown", Not: true}, }, result: []uint32{uint32(5), uint32(7)}, }, // query against a tag value matching regex { names: []string{"queue_depth"}, filters: []*TagFilter{ &TagFilter{Key: "app", Regex: regexp.MustCompile("paul.*")}, }, result: []uint32{uint32(6), uint32(7)}, }, // query against a tag value matching regex and other tag value matching value { names: []string{"queue_depth"}, filters: []*TagFilter{ &TagFilter{Key: "name", Value: "high priority"}, &TagFilter{Key: "app", Regex: regexp.MustCompile("paul.*")}, }, result: []uint32{uint32(6), uint32(7)}, }, // query against a tag value NOT matching regex { names: []string{"queue_depth"}, filters: []*TagFilter{ &TagFilter{Key: "app", Regex: regexp.MustCompile("paul.*"), Not: true}, }, result: []uint32{uint32(5)}, }, // query against a tag value NOT matching regex and other tag value matching value { names: []string{"queue_depth"}, filters: []*TagFilter{ &TagFilter{Key: "app", Regex: regexp.MustCompile("paul.*"), Not: true}, &TagFilter{Key: "name", Value: "high priority"}, }, result: []uint32{uint32(5)}, }, // query against multiple measurements { names: []string{"cpu_load", "key_count"}, filters: []*TagFilter{ &TagFilter{Key: "region", Value: "uswest"}, }, result: []uint32{uint32(1), uint32(2), uint32(3)}, }, } for i, tt := range tests { r := idx.SeriesIDs(tt.names, tt.filters) expectedIDs := SeriesIDs(tt.result) if !r.Equals(expectedIDs) { t.Fatalf("%d: filters: %s: result mismatch:\n exp=%s\n got=%s", i, mustMarshalJSON(tt.filters), mustMarshalJSON(expectedIDs), mustMarshalJSON(r)) } } } func TestDatabase_TagKeys(t *testing.T) { idx := databaseWithFixtureData() var tests = []struct { names []string result []string }{ { names: nil, result: []string{"a", "app", "host", "name", "region", "service"}, }, { names: []string{"cpu_load"}, result: []string{"host", "region"}, }, { names: []string{"key_count", "queue_depth"}, result: []string{"app", "host", "name", "region", "service"}, }, } for i, tt := range tests { r := idx.TagKeys(tt.names) if !reflect.DeepEqual(r, tt.result) { t.Fatalf("%d: names: %s: result mismatch:\n exp=%s\n got=%s", i, tt.names, tt.result, r) } } } func TestDatabase_TagValuesWhereTagFilter(t *testing.T) { idx := databaseWithFixtureData() var tests = []struct { names []string key string filters []*TagFilter result []string }{ // get the tag values across multiple measurements // get the tag values for a single measurement { names: []string{"key_count"}, key: "region", result: []string{"useast", "uswest"}, }, // get the tag values for a single measurement with where filter { names: []string{"key_count"}, key: "region", filters: []*TagFilter{ &TagFilter{Key: "host", Value: "serverc.influx.com"}, }, result: []string{"uswest"}, }, // get the tag values for a single measurement with a not where filter { names: []string{"key_count"}, key: "region", filters: []*TagFilter{ &TagFilter{Key: "host", Value: "serverc.influx.com", Not: true}, }, result: []string{"useast"}, }, // get the tag values for a single measurement with multiple where filters { names: []string{"key_count"}, key: "region", filters: []*TagFilter{ &TagFilter{Key: "host", Value: "serverc.influx.com"}, &TagFilter{Key: "service", Value: "redis"}, }, result: []string{"uswest"}, }, // get the tag values for a single measurement with regex filter { names: []string{"queue_depth"}, key: "name", filters: []*TagFilter{ &TagFilter{Key: "app", Regex: regexp.MustCompile("paul.*")}, }, result: []string{"high priority"}, }, // get the tag values for a single measurement with a not regex filter { names: []string{"key_count"}, key: "region", filters: []*TagFilter{ &TagFilter{Key: "host", Regex: regexp.MustCompile("serverd.*"), Not: true}, }, result: []string{"uswest"}, }, } for i, tt := range tests { r := idx.TagValues(tt.names, tt.key, tt.filters).ToSlice() if !reflect.DeepEqual(r, tt.result) { t.Fatalf("%d: filters: %s: result mismatch:\n exp=%s\n got=%s", i, mustMarshalJSON(tt.filters), tt.result, r) } } } func TestDatabase_DropSeries(t *testing.T) { t.Skip("pending") } func TestDatabase_DropMeasurement(t *testing.T) { t.Skip("pending") } func TestDatabase_FieldKeys(t *testing.T) { t.Skip("pending") } // databaseWithFixtureData returns a populated Index for use in many of the filtering tests func databaseWithFixtureData() *database { idx := newDatabase() s := &Series{ ID: uint32(1), Tags: map[string]string{"host": "servera.influx.com", "region": "uswest"}} added := idx.addSeriesToIndex("cpu_load", s) if !added { return nil } s = &Series{ ID: uint32(2), Tags: map[string]string{"host": "serverb.influx.com", "region": "uswest"}} added = idx.addSeriesToIndex("cpu_load", s) if !added { return nil } s = &Series{ ID: uint32(3), Tags: map[string]string{"host": "serverc.influx.com", "region": "uswest", "service": "redis"}} added = idx.addSeriesToIndex("key_count", s) if !added { return nil } s = &Series{ ID: uint32(4), Tags: map[string]string{"host": "serverd.influx.com", "region": "useast", "service": "redis"}} added = idx.addSeriesToIndex("key_count", s) if !added { return nil } s = &Series{ ID: uint32(5), Tags: map[string]string{"name": "high priority"}} added = idx.addSeriesToIndex("queue_depth", s) if !added { return nil } s = &Series{ ID: uint32(6), Tags: map[string]string{"name": "high priority", "app": "paultown"}} added = idx.addSeriesToIndex("queue_depth", s) if !added { return nil } s = &Series{ ID: uint32(7), Tags: map[string]string{"name": "high priority", "app": "paulcountry"}} added = idx.addSeriesToIndex("queue_depth", s) if !added { return nil } s = &Series{ ID: uint32(8), Tags: map[string]string{"a": "b"}} added = idx.addSeriesToIndex("another_thing", s) if !added { return nil } return idx } func TestDatabase_SeriesIDsIntersect(t *testing.T) { var tests = []struct { expected []uint32 left []uint32 right []uint32 }{ // both sets empty { expected: []uint32{}, left: []uint32{}, right: []uint32{}, }, // right set empty { expected: []uint32{}, left: []uint32{uint32(1)}, right: []uint32{}, }, // left set empty { expected: []uint32{}, left: []uint32{}, right: []uint32{uint32(1)}, }, // both sides same size { expected: []uint32{uint32(1), uint32(4)}, left: []uint32{uint32(1), uint32(2), uint32(4), uint32(5)}, right: []uint32{uint32(1), uint32(3), uint32(4), uint32(7)}, }, // both sides same size, right boundary checked. { expected: []uint32{}, left: []uint32{uint32(2)}, right: []uint32{uint32(1)}, }, // left side bigger { expected: []uint32{uint32(2)}, left: []uint32{uint32(1), uint32(2), uint32(3)}, right: []uint32{uint32(2)}, }, // right side bigger { expected: []uint32{uint32(4), uint32(8)}, left: []uint32{uint32(2), uint32(3), uint32(4), uint32(8)}, right: []uint32{uint32(1), uint32(4), uint32(7), uint32(8), uint32(9)}, }, } for i, tt := range tests { a := SeriesIDs(tt.left).Intersect(tt.right) if !a.Equals(tt.expected) { t.Fatalf("%d: %v intersect %v: result mismatch:\n exp=%v\n got=%v", i, SeriesIDs(tt.left), SeriesIDs(tt.right), SeriesIDs(tt.expected), SeriesIDs(a)) } } } func TestDatabase_SeriesIDsUnion(t *testing.T) { var tests = []struct { expected []uint32 left []uint32 right []uint32 }{ // both sets empty { expected: []uint32{}, left: []uint32{}, right: []uint32{}, }, // right set empty { expected: []uint32{uint32(1)}, left: []uint32{uint32(1)}, right: []uint32{}, }, // left set empty { expected: []uint32{uint32(1)}, left: []uint32{}, right: []uint32{uint32(1)}, }, // both sides same size { expected: []uint32{uint32(1), uint32(2), uint32(3), uint32(4), uint32(5), uint32(7)}, left: []uint32{uint32(1), uint32(2), uint32(4), uint32(5)}, right: []uint32{uint32(1), uint32(3), uint32(4), uint32(7)}, }, // left side bigger { expected: []uint32{uint32(1), uint32(2), uint32(3)}, left: []uint32{uint32(1), uint32(2), uint32(3)}, right: []uint32{uint32(2)}, }, // right side bigger { expected: []uint32{uint32(1), uint32(2), uint32(3), uint32(4), uint32(7), uint32(8), uint32(9)}, left: []uint32{uint32(2), uint32(3), uint32(4), uint32(8)}, right: []uint32{uint32(1), uint32(4), uint32(7), uint32(8), uint32(9)}, }, } for i, tt := range tests { a := SeriesIDs(tt.left).Union(tt.right) if !a.Equals(tt.expected) { t.Fatalf("%d: %v union %v: result mismatch:\n exp=%v\n got=%v", i, SeriesIDs(tt.left), SeriesIDs(tt.right), SeriesIDs(tt.expected), SeriesIDs(a)) } } } func TestDatabase_SeriesIDsReject(t *testing.T) { var tests = []struct { expected []uint32 left []uint32 right []uint32 }{ // both sets empty { expected: []uint32{}, left: []uint32{}, right: []uint32{}, }, // right set empty { expected: []uint32{uint32(1)}, left: []uint32{uint32(1)}, right: []uint32{}, }, // left set empty { expected: []uint32{}, left: []uint32{}, right: []uint32{uint32(1)}, }, // both sides same size { expected: []uint32{uint32(2), uint32(5)}, left: []uint32{uint32(1), uint32(2), uint32(4), uint32(5)}, right: []uint32{uint32(1), uint32(3), uint32(4), uint32(7)}, }, // left side bigger { expected: []uint32{uint32(1), uint32(3)}, left: []uint32{uint32(1), uint32(2), uint32(3)}, right: []uint32{uint32(2)}, }, // right side bigger { expected: []uint32{uint32(2), uint32(3)}, left: []uint32{uint32(2), uint32(3), uint32(4), uint32(8)}, right: []uint32{uint32(1), uint32(4), uint32(7), uint32(8), uint32(9)}, }, } for i, tt := range tests { a := SeriesIDs(tt.left).Reject(tt.right) if !a.Equals(tt.expected) { t.Fatalf("%d: %v reject %v: result mismatch:\n exp=%v\n got=%v", i, SeriesIDs(tt.left), SeriesIDs(tt.right), SeriesIDs(tt.expected), SeriesIDs(a)) } } }
package schema // ElementType represents the type an element may have type ElementType string const ( ElementTypePaste = ElementType("PASTE") ElementTypeRedirect = ElementType("REDIRECT") ) // Element represents an element type Element struct { Namespace string `json:"namespace"` Key string `json:"key"` Type ElementType `json:"type"` Data map[string]interface{} `json:"public_data"` Views int `json:"views"` MaxViews int `json:"max_views"` ValidFrom int64 `json:"valid_from"` ValidUntil int64 `json:"valid_until"` Created int64 `json:"created"` } // Elements represents a paginated element response type Elements struct { Data []*Element `json:"data"` Metadata *PaginationMetadata `json:"pagination"` } // CreateBaseElementData represents the basic data every element creation request body must have type CreateBaseElementData struct { Key *string `json:"key,omitempty"` MaxViews *int `json:"max_views,omitempty"` ValidFrom *int64 `json:"valid_from,omitempty"` ValidUntil *int64 `json:"valid_until,omitempty"` } // CreatePasteElementData represents the request model required for a paste element creation request type CreatePasteElementData struct { Content string `json:"content"` CreateBaseElementData } // CreateRedirectElementData represents the request model required for a redirect element creation request type CreateRedirectElementData struct { TargetURL string `json:"target_url"` CreateBaseElementData } // PatchElementData represents the request model required for a general element patching request type PatchElementData CreateBaseElementData
package goemon import ( "net/url" "strings" ) type ( Router struct { tree *node } node struct { children []*node component string isNamedParam bool methods map[string]Handle } ) func NewRouter() *Router { node := node{ component: "/", isNamedParam: false, methods: make(map[string]Handle), } return &Router{tree: &node} } func (n *node) Add(method, path string, handler Handle) { if path == "" { panic("Path cannot be empty") } if path[0] != '/' { path = "/" + path } components := strings.Split(path, "/")[1:] for count := len(components); count > 0; count-- { aNode, component := n.traverse(components, nil) if aNode.component == component && count == 1 { aNode.methods[method] = handler return } newNode := node{ component: component, isNamedParam: false, methods: make(map[string]Handle), } if len(component) > 0 && component[0] == ':' { newNode.isNamedParam = true } if count == 1 { newNode.methods[method] = handler } aNode.children = append(aNode.children, &newNode) } } func (n *node) traverse(components []string, params url.Values) (*node, string) { component := components[0] if len(n.children) > 0 { for _, child := range n.children { if component == child.component || child.isNamedParam { if child.isNamedParam && params != nil { params.Add(child.component[1:], component) } next := components[1:] if len(next) > 0 { return child.traverse(next, params) } else { return child, component } } } } return n, component }
package main import ( log "github.com/sirupsen/logrus" "github.com/vloek/realm/data" "github.com/vloek/realm/server" ) func main() { c := data.Character{} c.Pos = data.Point{X: 1.0, Y: 0.0} server := server.Server{} server.Run() log.Info(c) }
/* * SMA WebBox RPC over HTTP REST API * * The data loggers Sunny WebBox and Sunny WebBox with Bluetooth continuously record all the data of a PV plant. This is then averaged over a configurable interval and cached. The data can be transmitted at regular intervals to the Sunny Portal for analysis and visualization. Via the Sunny WebBox and Sunny WebBox with Bluetooth RPC interface, selected data from the PV plant can be transmitted to a remote terminal by means of an RPC protocol (Remote Procedure Call protocol). Related documents: * [SUNNY WEBBOX RPC User Manual v1.4](http://files.sma.de/dl/2585/SWebBoxRPC-BA-en-14.pdf) * [SUNNY WEBBOX RPC User Manual v1.3](http://files.sma.de/dl/4253/SWebBoxRPC-eng-BUS112713.pdf) * * API version: 1.4.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package smawebboxgo type DeviceDataChannels struct { Result map[string][]string `json:"result,omitempty"` // Format string `json:"format"` // Proc string `json:"proc"` // Version string `json:"version"` // Id string `json:"id"` // Error_ string `json:"error,omitempty"` }