content
stringlengths
44
6.13M
membership
stringclasses
2 values
package systems import ( "image" "sync" "golang.org/x/image/colornames" "github.com/brunoga/robomaster/sdk" "github.com/EngoEngine/ecs" "github.com/EngoEngine/engo" "github.com/EngoEngine/engo/common" ) type systemVideoEntity struct { ecs.BasicEntity *common.SpaceComponent *common.RenderComponent } type Video struct { entity *systemVideoEntity client *sdk.Client frameCh chan *image.NRGBA } func NewVideo(client *sdk.Client) *Video { return &Video{ nil, client, make(chan *image.NRGBA, 1), } } func (v *Video) Add() { // We initialize everything we need internally. } func (v *Video) New(w *ecs.World) { spaceComponent := &common.SpaceComponent{ Position: engo.Point{X: 0, Y: 0}, Width: 1280, Height: 720, } rect := image.Rect(0, 0, 1280, 720) img := image.NewNRGBA(rect) obj := common.NewImageObject(img) renderComponent := &common.RenderComponent{ Drawable: common.NewTextureSingle(obj), } v.entity = &systemVideoEntity{ ecs.NewBasic(), spaceComponent, renderComponent, } for _, system := range w.Systems() { switch sys := system.(type) { case *common.RenderSystem: sys.Add(&v.entity.BasicEntity, v.entity.RenderComponent, v.entity.SpaceComponent) } } videoModule := v.client.VideoModule() videoModule.StartStream(v.videoHandler) } func (v *Video) Update(dt float32) { select { case img := <-v.frameCh: obj := common.NewImageObject(img) tex := common.NewTextureSingle(obj) v.entity.Drawable.Close() v.entity.Drawable = tex default: //do nothing } } func (v *Video) Remove(e ecs.BasicEntity) { if e.ID() == v.entity.ID() { v.entity = nil } } func (v *Video) Priority() int { // Makes sure video updates after other systems. return -10 } func horizontalLine(img *image.NRGBA, y, x1, x2 int) { for ; x1 <= x2; x1++ { img.Set(x1, y, colornames.Greenyellow) } } func verticalLine(img *image.NRGBA, x, y1, y2 int) { for ; y1 <= y2; y1++ { img.Set(x, y1, colornames.Greenyellow) } } func (v *Video) videoHandler(frame *image.RGBA, wg *sync.WaitGroup) { frameCopy := *(*image.NRGBA)(frame) // Draw a simple crosshair. horizontalLine(&frameCopy, sdk.CameraVerticalResolutionPoints/2, (sdk.CameraHorizontalResolutionPoints/2)-50, (sdk.CameraHorizontalResolutionPoints/2)+50) verticalLine(&frameCopy, sdk.CameraHorizontalResolutionPoints/2, (sdk.CameraVerticalResolutionPoints/2)-50, (sdk.CameraVerticalResolutionPoints/2)+50) v.frameCh <- &frameCopy wg.Done() }
member
package main import ( "bufio" "encoding/binary" "flag" influxdb2 "github.com/influxdata/influxdb-client-go/v2" "github.com/influxdata/influxdb-client-go/v2/api" "log" "math" "net" "os" "strings" "time" ) const hostname = "0.0.0.0" // Address to listen on (0.0.0.0 = all interfaces) const port = "43110" // UDP Port number to listen on const service = hostname + ":" + port // Combined hostname+port // Telemetry struct represents a piece of telemetry as defined in the Forza data format (see the .dat files) type Telemetry struct { position int name string dataType string startOffset int endOffset int } func main() { // Parse flags horizonMode := flag.Bool("z", false, "Enables Forza Horizon 4 support (Will default to Forza Motorsport if unset)") debugModePTR := flag.Bool("d", false, "Enables extra debug information if set") flag.Parse() if *debugModePTR { log.Println("Debug mode enabled") } // Create InfluxDB Client client := influxdb2.NewClient("http://localhost:8086", "zPD41f0LWTUzW6A9DxN0AzJqCffKtlKaH5KTeAQD02tK07o84dkTz5qeGoCNdc2uybsdT_9kCqy180coOhADfg==") writeAPI := client.WriteAPI("forza", "telemetry") defer client.Close() // Switch to Horizon format if needed var formatFile = "FM7_packetformat.dat" // Path to file containing Forzas data format if *horizonMode { formatFile = "FH4_packetformat.dat" log.Println("Forza Horizon mode selected") } else { log.Println("Forza Motorsport mode selected") } // Load lines from packet format file lines, err := readLines(formatFile) if err != nil { log.Fatalf("Error reading format file: %s", err) } // Process format file into array of Telemetry structs startOffset := 0 endOffset := 0 dataLength := 0 var telemArray []Telemetry log.Printf("Processing %s...", formatFile) for i, line := range lines { dataClean := strings.Split(line, ";") // remove comments after ; from data format file dataFormat := strings.Split(dataClean[0], " ") // array containing data type and name dataType := dataFormat[0] dataName := dataFormat[1] switch dataType { case "s32": // Signed 32bit int dataLength = 4 // Number of bytes endOffset = endOffset + dataLength startOffset = endOffset - dataLength telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset} // Create new Telemetry item / data point telemArray = append(telemArray, telemItem) // Add Telemetry item to main telemetry array case "u32": // Unsigned 32bit int dataLength = 4 endOffset = endOffset + dataLength startOffset = endOffset - dataLength telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset} telemArray = append(telemArray, telemItem) case "f32": // Floating point 32bit dataLength = 4 endOffset = endOffset + dataLength startOffset = endOffset - dataLength telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset} telemArray = append(telemArray, telemItem) case "u16": // Unsigned 16bit int dataLength = 2 endOffset = endOffset + dataLength startOffset = endOffset - dataLength telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset} telemArray = append(telemArray, telemItem) case "u8": // Unsigned 8bit int dataLength = 1 endOffset = endOffset + dataLength startOffset = endOffset - dataLength telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset} telemArray = append(telemArray, telemItem) case "s8": // Signed 8bit int dataLength = 1 endOffset = endOffset + dataLength startOffset = endOffset - dataLength telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset} telemArray = append(telemArray, telemItem) case "hzn": // Forza Horizon 4 unknown values (12 bytes of.. something) dataLength = 12 endOffset = endOffset + dataLength startOffset = endOffset - dataLength telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset} telemArray = append(telemArray, telemItem) default: log.Fatalf("Error: Unknown data type in %s \n", formatFile) } //Debug format file processing: if *debugModePTR { log.Printf("Processed %s line %d: %s (%s), Byte offset: %d:%d \n", formatFile, i, dataName, dataType, startOffset, endOffset) } } if *debugModePTR { // Print completed telemetry array log.Printf("Logging entire telemArray: \n%v", telemArray) } log.Printf("Proccessed %d Telemetry types OK!", len(telemArray)) // Setup UDP listener udpAddr, err := net.ResolveUDPAddr("udp4", service) if err != nil { log.Fatal(err) } listener, err := net.ListenUDP("udp", udpAddr) check(err) defer listener.Close() // close after main ends - probably not really needed // log.Printf("Forza data out server listening on %s, waiting for Forza data...\n", service) log.Printf("Forza data out server listening on %s:%s, waiting for Forza data...\n", GetOutboundIP(), port) for { // main loop readForzaData(listener, writeAPI, telemArray) } } // readForzaData processes recieved UDP packets func readForzaData(conn *net.UDPConn, writeAPI api.WriteAPI, telemArray []Telemetry) { buffer := make([]byte, 1500) n, addr, err := conn.ReadFromUDP(buffer) if err != nil { log.Fatal("Error reading UDP data:", err, addr) } if isFlagPassed("d") == true { // Print extra connection info if debugMode set log.Println("UDP client connected:", addr) // fmt.Printf("Raw Data from UDP client:\n%s", string(buffer[:n])) // Debug: Dump entire received buffer } currentEngineRpm := float32(0) p := influxdb2.NewPointWithMeasurement("stat") // Use Telemetry array to map raw data against Forza's data format for i, T := range telemArray { data := buffer[:n][T.startOffset:T.endOffset] // Process received data in chunks based on byte offsets if isFlagPassed("d") == true { // if debugMode, print received data in each chunk log.Printf("Data chunk %d: %v (%s) (%s)", i, data, T.name, T.dataType) } if T.name == "TimestampMS" { timestamp := binary.LittleEndian.Uint32(data) p = p.SetTime(time.Unix(0, int64(timestamp) * int64(time.Millisecond))) } else if T.name == "CurrentEngineRpm" { currentEngineRpm = Float32frombytes(data) } switch T.dataType { // each data type needs to be converted / displayed differently case "s32": case "u32": // fmt.Println("Name:", T.name, "Type:", T.dataType, "value:", binary.LittleEndian.Uint32(data)) p = p.AddField(T.name, binary.LittleEndian.Uint32(data)) case "f32": // fmt.Println("Name:", T.name, "Type:", T.dataType, "value:", (dataFloated * 1)) p = p.AddField(T.name, Float32frombytes(data)) case "u16": // fmt.Println("Name:", T.name, "Type:", T.dataType, "value:", binary.LittleEndian.Uint16(data)) p = p.AddField(T.name, binary.LittleEndian.Uint16(data)) case "u8": p = p.AddField(T.name, data[0]) case "s8": p = p.AddField(T.name, int8(data[0])) } } // Dont print / log / do anything if RPM is zero // This happens if the game is paused or you rewind // There is a bug with FH4 where it will continue to send data when in certain menus if currentEngineRpm == 0 { return } writeAPI.WritePoint(p.SetTime(time.Now())) } func init() { log.SetFlags(log.Lmicroseconds) log.Println("Started Forza Data Tools") } // Helper functions // Quick error check helper func check(e error) { if e != nil { log.Fatalln(e) } } // Check if flag was passed func isFlagPassed(name string) bool { found := false flag.Visit(func(f *flag.Flag) { if f.Name == name { found = true } }) return found } // Float32frombytes converts bytes into a float32 func Float32frombytes(bytes []byte) float32 { bits := binary.LittleEndian.Uint32(bytes) float := math.Float32frombits(bits) return float } // readLines reads a whole file into memory and returns a slice of its lines func readLines(path string) ([]string, error) { file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() var lines []string scanner := bufio.NewScanner(file) for scanner.Scan() { lines = append(lines, scanner.Text()) } return lines, scanner.Err() } // GetOutboundIP finds preferred outbound ip of this machine func GetOutboundIP() net.IP { conn, err := net.Dial("udp", "1.2.3.4:4321") // Destination does not need to exist, using this to see which is the primary network interface if err != nil { log.Fatal(err) } defer conn.Close() localAddr := conn.LocalAddr().(*net.UDPAddr) return localAddr.IP }
non-member
package transformer import ( "regexp" "strings" "unicode" "unicode/utf8" ) type capitalization int const ( noCapitalization capitalization = iota firstCapitzlized allCapitalized ) // Regexes for handling how to split messages into usable components. var wordSplitRegex = regexp.MustCompile(`(\w+\b-+|\S+)[\n]*`) var punctuationRegex = regexp.MustCompile(`^(\W+)|(\W+)$`) var capitalRegex = regexp.MustCompile(`\b[A-Z]+`) // WordMetadata is individual word metadata information. type WordMetadata struct { Capitalization capitalization PrePunc string PostPunc string } // This method might look a little contrived with the number of "if" statements // checking if `meta` is nil. This is intentional. The point of this is to // reduce heap allocations as much as possible by only creating meta as needed. func createWordMetadata(word string) (*WordMetadata, string) { var meta *WordMetadata if idxs := punctuationRegex.FindAllStringIndex(word, 2); len(idxs) > 0 { var pre, post string if len(idxs) == 1 { if idxs[0][0] == 0 { pre = word[0:idxs[0][1]] } else { post = word[idxs[0][0]:idxs[0][1]] } } else { pre = word[0:idxs[0][1]] post = word[idxs[1][0]:idxs[1][1]] } meta = &WordMetadata{ PrePunc: pre, PostPunc: post, } word = punctuationRegex.ReplaceAllLiteralString(word, "") } switch len(capitalRegex.FindString(word)) { case 0: if meta != nil { meta.Capitalization = noCapitalization } case 1: if meta == nil { meta = &WordMetadata{} } meta.Capitalization = firstCapitzlized word = strings.ToLower(word) default: if meta == nil { meta = &WordMetadata{} } meta.Capitalization = allCapitalized word = strings.ToLower(word) } return meta, word } // MessageMetadata contains a list of words and their associated metadata. type MessageMetadata struct { Words []string Metadata []*WordMetadata size uint32 } // New initializes message metadata struct from a string. func (m *MessageMetadata) New(message string) { wordList := wordSplitRegex.FindAllString(message, -1) m.size = uint32(len(message)) m.Words = make([]string, len(wordList)) m.Metadata = make([]*WordMetadata, len(wordList)) for idx, word := range wordList { meta, normalizedWord := createWordMetadata(word) m.Words[idx] = normalizedWord m.Metadata[idx] = meta } } func (m MessageMetadata) capitalize(word string, idx int) string { if m.Metadata[idx] == nil { return word } switch m.Metadata[idx].Capitalization { case firstCapitzlized: return capitalizeFirst(word) case allCapitalized: return strings.ToUpper(word) default: return word } } func (m MessageMetadata) String() string { builder := ReversibleStringBuilder{} builder.Init() // Grow the buffer so that we have some headroom over the original string. builder.Grow(int(1.2 * float32(m.size))) for idx, word := range m.Words { if meta := m.Metadata[idx]; meta != nil { builder.WriteString(meta.PrePunc) builder.WriteString(m.capitalize(word, idx)) builder.WriteString(meta.PostPunc) if !strings.HasSuffix(meta.PostPunc, "\n") { builder.WriteString(" ") } } else { builder.WriteString(word) builder.WriteString(" ") } if builder.Len() >= 1997 { builder.Reverse(-1) builder.WriteString("....") break } builder.Flush() } return builder.String()[:builder.Len()-1] } func capitalizeFirst(s string) string { if len(s) > 0 { r, sz := utf8.DecodeRuneInString(s) if r != utf8.RuneError || sz > 1 { upper := unicode.ToUpper(r) if upper != r { s = string(upper) + s[sz:] } } } return s }
non-member
package main import ( "testing" ) func TestActivityNotifications(t *testing.T) { cases := []struct { result int expected int }{ { countInversions([]int{1, 1, 1, 2, 2}), 0, }, { countInversions([]int{2, 1, 3, 1, 2}), 4, }, } for _, c := range cases { if c.result != c.expected { t.Errorf("Error got: %v, want: %v.", c.result, c.expected) } } }
non-member
package mysqlparse import ( "bytes" "fmt" "io" "strings" "github.com/xwb1989/sqlparser" ) // Parse blabla func Parse(sql string) { tokens := sqlparser.NewTokenizer(strings.NewReader(sql)) for { stmt, err := sqlparser.ParseNext(tokens) if err == io.EOF { // t.Error(err) break } fmt.Println(parseStmt(stmt)) } } func parseStmt(stmt sqlparser.Statement) string { switch stmt := (stmt).(type) { case *sqlparser.Select: return parseSelect(stmt) case *sqlparser.Insert: default: return "" } return "" } func parseSelect(stmt *sqlparser.Select) string { ret := " select " ret += getStr(stmt.SelectExprs) ret += " from " + getStr(stmt.From) if stmt.Where != nil { ret += " where " ret += parseExpr(stmt.Where.Expr) } if stmt.GroupBy != nil { } return ret } func visit(node sqlparser.SQLNode) (kontinue bool, err error) { return false, nil } func parseExpr(expr sqlparser.Expr) string { expr.WalkSubtree(visit) switch expr := expr.(type) { case *sqlparser.AndExpr: return parseExpr(expr.Left) + " and " + parseExpr(expr.Right) case *sqlparser.OrExpr: fmt.Println("OrExpr") return parseExpr(expr.Left) + " or " + parseExpr(expr.Right) case *sqlparser.NotExpr: fmt.Println("NotExpr") case *sqlparser.ParenExpr: fmt.Println("ParenExpr") case *sqlparser.ComparisonExpr: fmt.Println("ComparisonExpr") return parseExpr(expr.Left) + expr.Operator + parseExpr(expr.Right) case *sqlparser.RangeCond: fmt.Println("RangeCond") case *sqlparser.IsExpr: fmt.Println("IsExpr") return getStr(expr) case *sqlparser.ExistsExpr: fmt.Println("ExistsExpr") case *sqlparser.SQLVal: fmt.Println("SQLVal") return "?" case *sqlparser.NullVal: fmt.Println("NullVal") case sqlparser.BoolVal: fmt.Println("BoolVal") case *sqlparser.ColName: fmt.Println("ColName") return expr.Name.String() case sqlparser.ValTuple: fmt.Println("ValTuple") case *sqlparser.Subquery: fmt.Println("Subquery") case sqlparser.ListArg: fmt.Println("ListArg") case *sqlparser.BinaryExpr: fmt.Println("BinaryExpr") case *sqlparser.UnaryExpr: fmt.Println("UnaryExpr") case *sqlparser.IntervalExpr: fmt.Println("IntervalExpr") case *sqlparser.CollateExpr: fmt.Println("CollateExpr") case *sqlparser.FuncExpr: fmt.Println("FuncExpr") case *sqlparser.CaseExpr: fmt.Println("CaseExpr") case *sqlparser.ValuesFuncExpr: fmt.Println("ValuesFuncExpr") case *sqlparser.ConvertExpr: fmt.Println("ConvertExpr") case *sqlparser.ConvertUsingExpr: fmt.Println("ConvertUsingExpr") case *sqlparser.MatchExpr: fmt.Println("MatchExpr") case *sqlparser.GroupConcatExpr: fmt.Println("GroupConcatExpr") case *sqlparser.Default: fmt.Println("Default") default: } return "" } func getStr(node sqlparser.SQLNode) string { buff := sqlparser.TrackedBuffer{} buff.Buffer = new(bytes.Buffer) node.Format(&buff) return buff.String() }
non-member
// user.go package main import ( "crypto/x509" "database/sql" "errors" "fmt" "strings" "sync" "github.com/golang/glog" ) // ----------------------------------------------- type TUserProfil int const ( ProfilNone = iota ProfilAdmin ProfilUser ) // ----------------------------------------------- var userListLock sync.Mutex var userList []HomeObject // ----------------------------------------------- // getEmailFromCert : read received peer X509 certificates and return found email or err func getEmailFromCert(peerCrt []*x509.Certificate) (email string, err error) { if len(peerCrt) <= 0 { err = errors.New("No certificat received") glog.Error(err) return } // With the certificats I build email is the 5th Attribut - this may chage given the CA settings (TODO : check, not sure) if len(peerCrt[0].Subject.Names) < 5 { err = errors.New(fmt.Sprintf("Did not locate email in (%s)", peerCrt[0].Subject.Names)) glog.Error(err) return } email = peerCrt[0].Subject.Names[4].Value.(string) return } // loadUsers : load all users from DB into global userList // If force == false then only load if userList is empty func loadUsers(db *sql.DB, force bool) (nbUser int, err error) { if db == nil { if db, err = openDB(); err != nil { return } defer db.Close() } userListLock.Lock() defer userListLock.Unlock() nbUser = len(userList) if nbUser > 0 && !force { return } // read all users userList, err = getHomeObjects(db, ItemUser, -1) nbUser = len(userList) return } // getUserFromCert : return user HomeObject or error if not found func getUserFromCert(peerCrt []*x509.Certificate) (userObj HomeObject, err error) { email, err := getEmailFromCert(peerCrt) if err != nil { return } if glog.V(2) { glog.Infof("User email from cert = '%s'", email) } userObj, err = getUserFromEmail(email) return } // getUserFromCode : return user HomeObject or error if not found func getUserFromCode(db *sql.DB, userCode string) (userObj HomeObject, err error) { if db == nil { if db, err = openDB(); err != nil { return } defer db.Close() } if userCode == "" { err = errors.New(fmt.Sprintf("getUserFromCode returning (empty user code) : '%s'", userCode)) return } if glog.V(2) { glog.Infof("User code = '%s'", userCode) } query, err := getGlobalParam(db, "Global", "UserOTP") if err != nil { glog.Errorf("getUserFromCode fail to get userOTP : %s", err) return } rows, err := db.Query(query, userCode) if err != nil { glog.Errorf("getUserFromCode query fail (query=%s,userCode=%s) : %s ", query, userCode, err) return } defer rows.Close() var email string if rows.Next() { err = rows.Scan(&email) if err != nil { glog.Errorf("getUserFromCode scan fail (query=%s,userCode=%s) : %s ", query, userCode, err) return } if err = rows.Err(); err != nil { glog.Errorf("getUserFromCode rows.Err (query=%s,userCode=%s) : %s ", query, userCode, err) return } } else { if glog.V(2) { glog.Infof("getUserFromCode cant validate user code : '%s'", userCode) } } userObj, err = getUserFromEmail(email) return } // getUserFromEmail : return user HomeObject or error if not found func getUserFromEmail(email string) (userObj HomeObject, err error) { _, err = loadUsers(nil, false) if err != nil { return } if email == "" { err = errors.New(fmt.Sprintf("No user found (empty email) '%s'", email)) return } // Search a user with the email found in the certificat userListLock.Lock() defer userListLock.Unlock() for _, obj := range userList { if glog.V(3) { glog.Info("User : ", obj) } val, err1 := obj.getStrVal("Email") if err1 != nil || strings.ToUpper(val) != strings.ToUpper(email) { continue } iProfil, err1 := obj.getIntVal("IdProfil") if err1 != nil { continue // ignore if no IdProfile field } iActive, err1 := obj.getIntVal("IsActive") if err1 != nil { continue // ignore if no IsActive field } if glog.V(2) { glog.Infof("Found active(%d) user for '%s' : id=%d profil=%d)", iActive, email, obj.getId(), iProfil) } userObj = obj return } err = errors.New(fmt.Sprintf("No user found for '%s'", email)) if glog.V(2) { glog.Error("getUserFromEmail Error : ", err) } return } // checkApiUser : check if userObj has acces to level 'profil' func checkApiUser(userObj HomeObject) (profil TUserProfil, err error) { i, err := userObj.getIntVal("IdProfil") if err != nil { return } profil = TUserProfil(i) if profil <= ProfilNone { err = errors.New("insufficient privileges") return } iActive, err := userObj.getIntVal("IsActive") if err != nil { return } if iActive <= 0 { err = errors.New("Not an active user") } return } // profilFilteredItems : return an []Item with only Item matching user profil func profilFilteredItems(profil TUserProfil, items []Item) (filteredItems []Item) { for _, item := range items { if item.IdProfil < profil { continue } filteredItems = append(filteredItems, item) } return } // profilFilteredObjects : return an []HomeObject with only Item matching user profil func profilFilteredObjects(profil TUserProfil, objs []HomeObject) (filteredObjs []HomeObject) { for _, obj := range objs { if checkAccessToObject(profil, obj) != nil { continue } filteredObjs = append(filteredObjs, obj) } return } func checkAccess(profilObject TUserProfil, profilAccess TUserProfil) error { if (profilAccess == ProfilNone && profilObject > ProfilNone) || profilObject < profilAccess { return errors.New("insufficient privileges") } return nil } // checkAccessToObject : check if 'profil' has acces to object func checkAccessToObject(profil TUserProfil, obj HomeObject) error { if !obj.hasField("IdProfil") { // HomeObject without IdProfil have no access restriction return nil } iProfil, err := obj.getIntVal("IdProfil") if err != nil { return err } if profil == ProfilNone || TUserProfil(iProfil) < profil { return errors.New("insufficient privileges") } return checkAccess(TUserProfil(iProfil), profil) } // checkAccessToObjectId : check if 'profil' has acces to object (obj read from DB using objectid) func checkAccessToObjectId(profil TUserProfil, objectid int) error { objs, err := getHomeObjects(nil, ItemIdNone, objectid) if err != nil { return err } if len(objs) <= 0 { return errors.New(fmt.Sprintf("Object with Id=%d not found", objectid)) } return checkAccessToObject(profil, objs[0]) }
non-member
//go:build !windows // +build !windows package ledgerbackend import ( "os" "github.com/pkg/errors" ) // Posix-specific methods for the StellarCoreRunner type. func (c *stellarCoreRunner) getPipeName() string { // The exec.Cmd.ExtraFiles field carries *io.File values that are assigned // to child process fds counting from 3, and we'll be passing exactly one // fd: the write end of the anonymous pipe below. return "fd:3" } func (c *stellarCoreRunner) start(cmd cmdI) (pipe, error) { // First make an anonymous pipe. // Note io.File objects close-on-finalization. readFile, writeFile, err := os.Pipe() if err != nil { return pipe{}, errors.Wrap(err, "error making a pipe") } p := pipe{Reader: readFile, File: writeFile} // Add the write-end to the set of inherited file handles. This is defined // to be fd 3 on posix platforms. cmd.setExtraFiles([]*os.File{writeFile}) err = cmd.Start() if err != nil { writeFile.Close() readFile.Close() return pipe{}, errors.Wrap(err, "error starting stellar-core") } return p, nil }
member
package main // #cgo CPPFLAGS: -I/usr/local/modsecurity/include // #cgo LDFLAGS: /usr/local/modsecurity/lib/libmodsecurity.so // #include "modsec.c" import "C" import ( "encoding/json" "fmt" "github.com/gorilla/mux" "log" "net/http" "net/http/httputil" "net/url" "time" "unsafe" ) func HomeFunc(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) data := "Home ModSec!!!!" err := json.NewEncoder(w).Encode(data) if err != nil { _, err := fmt.Fprintf(w, "%s", err.Error()) if err != nil { log.Fatal(err) return } } } func TestFunc(w http.ResponseWriter, r *http.Request) { log.Print("Processing request") urlx, err := url.Parse("https://www.lightbase.io/freeforlife") if err != nil { log.Println(err) } proxy := httputil.NewSingleHostReverseProxy(urlx) director := proxy.Director proxy.Director = func(req *http.Request) { director(req) req.Header.Set("X-Forwarded-Host", req.Header.Get("Host")) req.Host = req.URL.Host req.URL.Path = urlx.Path } log.Print("Serving request") proxy.ServeHTTP(w, r) } func InitModSec() { //log.Println("initModSec start") C.MyCInit() //log.Println("initModSec -end-") } func modsec(url, httpMethod, httpProtocol, httpVersion string, clientLink string, clientPort int, serverLink string, serverPort int) int { log.Println("modsec start ", url) Curi := C.CString(url) ChttpMethod := C.CString(httpMethod) ChttpProtocol := C.CString(httpProtocol) ChttpVersion := C.CString(httpVersion) CclientLink := C.CString(clientLink) CclientPort := C.int(clientPort) CserverLink := C.CString(serverLink) CserverPort := C.int(serverPort) defer C.free(unsafe.Pointer(Curi)) defer C.free(unsafe.Pointer(ChttpMethod)) defer C.free(unsafe.Pointer(ChttpProtocol)) defer C.free(unsafe.Pointer(ChttpVersion)) defer C.free(unsafe.Pointer(CclientLink)) defer C.free(unsafe.Pointer(CserverLink)) start := time.Now() inter := int(C.MyCProcess(Curi, ChttpMethod, ChttpProtocol, ChttpVersion, CclientLink, CclientPort, CserverLink, CserverPort)) elapsed := time.Since(start) log.Printf("modsec()=%d, elapsed: %s", inter, elapsed) log.Println("modsec -end-") return inter } func LimitMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf("req.URL : \"%s\"", r.URL) log.Printf("Methods : \"%s\"", r.Method) uri := r.URL.String() httpMethod := "GET" //protocol := "HTTP/1.1" httpProtocol := "HTTP" httpVersion := "1.1" //clientSocket := "127.0.0.1:80" clientLink := "127.0.0.1" clientPort := 80 //serverSocket := "127.0.0.1:80" serverLink := "127.0.0.1" serverPort := 80 inter := modsec(uri, httpMethod, httpProtocol, httpVersion, clientLink, clientPort, serverLink, serverPort) if inter > 0 { log.Printf("==== Mod Security Blocked! ====") http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) return } next.ServeHTTP(w, r) }) } func main() { log.Println("testing") bind := ":3080" gmux := mux.NewRouter() gmux.HandleFunc("/", HomeFunc).Methods("GET") gmux.HandleFunc("/test/artists.php", TestFunc).Methods("GET") log.Printf("starting smart reverse proxy on [%s]", bind) log.Printf("initialize mod sec") InitModSec() log.Printf("listening [deny]...") if err := http.ListenAndServe(bind, LimitMiddleware(gmux)); err != nil { log.Fatalf("unable to start web server: %s", err.Error()) } }
non-member
package msg import ( "bufio" "encoding/gob" "fmt" "io" "sync" ) // Reader : simple bufio.Reader safe for goroutines... type Reader struct { b *bufio.Reader m sync.Mutex } // NewReader : constructor func NewReader(rd io.Reader) *Reader { s := new(Reader) s.b = bufio.NewReader(rd) return s } // ReadString : safe version for goroutines func (r *Reader) ReadString() (string, error) { r.m.Lock() defer r.m.Unlock() return r.b.ReadString('\n') } // ReadMessage : decode a message in a safe way for goroutines func (r *Reader) ReadMessage(data interface{}) error { r.m.Lock() defer r.m.Unlock() enc := gob.NewDecoder(r.b) err := enc.Decode(data) if err != nil { fmt.Printf("error in ReadMessage : %s\n", err) } return err }
non-member
package panda import ( "net/http" "github.com/LeeEirc/httpsig" ) const ( signHeaderRequestTarget = "(request-target)" signHeaderDate = "date" signAlgorithm = "hmac-sha256" ) type ProfileAuth struct { KeyID string SecretID string } func (auth *ProfileAuth) Sign(r *http.Request) error { profileReq, err := http.NewRequest(http.MethodGet, UserProfileURL, nil) if err != nil { return err } headers := []string{signHeaderRequestTarget, signHeaderDate} signer, err := httpsig.NewRequestSigner(auth.KeyID, auth.SecretID, signAlgorithm) if err != nil { return err } err = signer.SignRequest(profileReq, headers, nil) if err != nil { return err } for k, v := range profileReq.Header { r.Header[k] = v } return nil } const UserProfileURL = "/api/v1/users/profile/"
non-member
package linux import ( "net" ) func LocalIp() (string, error) { localIp := "N/A" adders, err := net.InterfaceAddrs() if err != nil { return localIp, err } for _, addr := range adders { if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLinkLocalUnicast() && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil { localIp = ipNet.IP.String() } } return localIp, nil }
non-member
package main import ( "flag" "fmt" "os" "os/exec" "runtime" "stashbox/pkg/archive" "stashbox/pkg/crawler" ) func usage() { fmt.Println("Usage: stashbox <command> <options>") fmt.Println("") fmt.Println(" Where command is one of:") fmt.Println(" add -- add a url to the archive") fmt.Println(" list -- list all archives") fmt.Println(" open -- open an archive") fmt.Println("") fmt.Println(" To see help text, you can run:") fmt.Println(" stashbox <command> -h") os.Exit(1) } func main() { // add subcommand addCmd := flag.NewFlagSet("add", flag.ExitOnError) addBase := addCmd.String("b", "./stashDb", "stashbox archive directory (defaults to ./stashDb)") url := addCmd.String("u", "", "url to download") //list subcommand listCmd := flag.NewFlagSet("list", flag.ExitOnError) listBase := listCmd.String("b", "./stashDb", "stashbox archive directory (defaults to ./stashDb)") //open subcommand openCmd := flag.NewFlagSet("open", flag.ExitOnError) openBase := openCmd.String("b", "./stashDb", "stashbox archive directory (defaults to ./stashDb)") n := openCmd.Int("n", 0, "archive number to open (from list command)") if len(os.Args) < 2 { usage() } if os.Args[1] == "-h" { usage() } switch os.Args[1] { case "add": if addCmd.Parse(os.Args[2:]) != nil { addCmd.Usage() os.Exit(2) } if *url == "" { fmt.Println("ERROR: -url is required") addCmd.Usage() os.Exit(1) } c, err := crawler.NewCrawler(*addBase) if err != nil { panic(err) } err = c.AddURL(*url) if err != nil { panic(err) } err = c.Crawl() if err != nil { panic(err) } err = c.Save() if err != nil { panic(err) } case "list": if listCmd.Parse(os.Args[2:]) != nil { listCmd.Usage() os.Exit(2) } archives, err := archive.GetArchives(*listBase) if err != nil { fmt.Println("Error listing archives", err) os.Exit(1) } fmt.Println("Archive listing...") for i, n := range archives { fmt.Printf("%d. %s [%d image(s)]\n", i+1, n.URL, len(n.Dates)) } case "open": if openCmd.Parse(os.Args[2:]) != nil { openCmd.Usage() os.Exit(2) } archives, err := archive.GetArchives(*openBase) if err != nil { panic(err) } if *n < 1 { fmt.Println("Choose an archive to open:") for i, n := range archives { fmt.Printf("%d. %s [%d image(s)]\n", i+1, n.URL, len(n.Dates)) } fmt.Print("\n> ") _, err := fmt.Scanf("%d", n) if err != nil { fmt.Printf("ERROR: reading input: %v", err) os.Exit(1) } } a := archives[*n-1] file := fmt.Sprintf("%s/%s/%s.pdf", *openBase, a.URL, a.Dates[len(a.Dates)-1]) fmt.Printf("Opening: %s\n", file) var cmd *exec.Cmd switch runtime.GOOS { case "windows": cmd = exec.Command(file) // #nosec G204 case "darwin": cmd = exec.Command("open", file) // #nosec G204 default: cmd = exec.Command("xdg-open", file) // #nosec G204 } err = cmd.Run() if err != nil { panic(err) } default: fmt.Printf("ERROR: unknown command (%s) specified\n", os.Args[1]) usage() } }
non-member
package valuechangevalidationfuncinfo import ( "testing" "golang.org/x/tools/go/analysis" ) func TestValidateAnalyzer(t *testing.T) { err := analysis.Validate([]*analysis.Analyzer{Analyzer}) if err != nil { t.Fatal(err) } }
non-member
package main import ( "flag" "log" "net" "strconv" ) func main() { port := flag.Int("port", 8080, "Port to accept connections on.") host := flag.String("host", "0.0.0.0", "Host or IP to bind to") flag.Parse() l, err := net.Listen("tcp", *host+":"+strconv.Itoa(*port)) if err != nil { log.Panicln(err) } log.Println("Listening to connections at '"+*host+"' on port", strconv.Itoa(*port)) defer l.Close() for { conn, err := l.Accept() if err != nil { log.Panicln(err) } go handleRequest(conn) } } func handleRequest(conn net.Conn) { log.Println("Accepted new connection.") defer conn.Close() defer log.Println("Closed connection.") for { buf := make([]byte, 1024) size, err := conn.Read(buf) if err != nil { return } data := buf[:size] log.Println("Received:", string(data)) conn.Write(data) } }
non-member
package lib import ( "errors" "fmt" "runtime" "strings" "testing" ) func TestF테스트_중(t *testing.T) { t.Parallel() F테스트_모드_종료() F테스트_거짓임(t, F테스트_모드_실행_중()) F테스트_모드_시작() F테스트_참임(t, F테스트_모드_실행_중()) } func TestF테스트_참임(t *testing.T) { //t.Parallel() // 화면 출력 중지 로 인하여 병렬 실행 불가. F테스트_참임(t, true) 모의_테스트 := new(S모의_테스트) 원래_출력장치 := F화면_출력_중지() F테스트_참임(모의_테스트, false) F화면_출력_재개(원래_출력장치) F테스트_참임(t, 모의_테스트.Failed()) } func TestF테스트_거짓임(t *testing.T) { //t.Parallel() // 화면 출력 중지 로 인하여 병렬 실행 불가. F테스트_거짓임(t, false) 모의_테스트 := new(S모의_테스트) 원래_출력장치 := F화면_출력_중지() F테스트_거짓임(모의_테스트, true) F화면_출력_재개(원래_출력장치) F테스트_참임(t, 모의_테스트.Failed()) } func TestF에러_없음(t *testing.T) { //t.Parallel() // 화면 출력 중지 로 인하여 병렬 실행 불가. F테스트_에러없음(t, nil) 모의_테스트 := new(S모의_테스트) 원래_출력장치 := F화면_출력_중지() F테스트_에러없음(모의_테스트, fmt.Errorf("")) F화면_출력_재개(원래_출력장치) F테스트_참임(t, 모의_테스트.Failed()) } func TestF테스트_에러발생(t *testing.T) { //t.Parallel() // 화면 출력 중지 로 인하여 병렬 실행 불가. F테스트_에러발생(t, errors.New("")) 모의_테스트 := new(S모의_테스트) 원래_출력장치 := F화면_출력_중지() F테스트_에러발생(모의_테스트, nil) F화면_출력_재개(원래_출력장치) F테스트_참임(t, 모의_테스트.Failed()) } func TestF테스트_같음(t *testing.T) { //t.Parallel() // 화면 출력 중지 로 인하여 병렬 실행 불가. F테스트_같음(t, 1, 1) 모의_테스트 := new(S모의_테스트) 원래_출력장치 := F화면_출력_중지() F테스트_같음(모의_테스트, 1, 2) F화면_출력_재개(원래_출력장치) F테스트_참임(t, 모의_테스트.Failed()) } func TestF테스트_다름(t *testing.T) { //t.Parallel() // 화면 출력 중지 로 인하여 병렬 실행 불가. F테스트_다름(t, 1, 2) 모의_테스트 := new(S모의_테스트) 원래_출력장치 := F화면_출력_중지() F테스트_다름(모의_테스트, 1, 1) F화면_출력_재개(원래_출력장치) F테스트_참임(t, 모의_테스트.Failed()) } func TestF임의_문자열(t *testing.T) { t.Parallel() 맵 := make(map[string]S비어있음) const 테스트_반복횟수 = 100 비어있는_구조체 := S비어있음{} for i := 0; i < 테스트_반복횟수; i++ { 맵[F임의_문자열(10, 20)] = 비어있는_구조체 } F테스트_참임(t, len(맵) > 테스트_반복횟수*0.7) } func TestF문자열_호출경로_출력(t *testing.T) { //t.Parallel() // 문자열 출력 확보로 인해 병렬 실행 불가. 문자열, 에러 := F출력_문자열_확보(func() { F문자열_호출경로_출력("%v, %v", "테스트_문자열", 1) }) F테스트_에러없음(t, 에러) F테스트_참임(t, strings.Count(문자열, "테스트_문자열, 1") == 1, 문자열) F테스트_참임(t, F호출경로_포함(문자열), 문자열) pc, _, _, _ := runtime.Caller(0) 함수명 := runtime.FuncForPC(pc).Name() if strings.LastIndex(함수명, ".") > 0 { 함수명 = 함수명[strings.LastIndex(함수명, ".")+1:] } F테스트_참임(t, strings.Contains(문자열, 함수명), 문자열, 함수명) } func TestNew에러(t *testing.T) { //t.Parallel() // 문자열 출력 확보로 인해 병렬 실행 불가. 에러 := New에러("테스트용 에러. %v", 100) _, ok := 에러.(error) F테스트_참임(t, ok) F테스트_같음(t, strings.Count(에러.Error(), "테스트용 에러. 100"), 1) } func TestF변수값_자료형_문자열(t *testing.T) { //t.Parallel() // 문자열 출력 확보로 인해 병렬 실행 불가. 문자열 := F변수값_자료형_문자열("테스트_문자열", 1) F테스트_참임(t, strings.Contains(문자열, "테스트_문자열")) F테스트_참임(t, strings.Contains(문자열, "string")) F테스트_참임(t, strings.Contains(문자열, "1")) F테스트_참임(t, strings.Contains(문자열, "int")) } func TestF소스코드_위치_포함(t *testing.T) { t.Parallel() 문자열 := "github.com/ghts/sample.go.go:65:f샘플()\n\nFAIL github.com/ghts/ 23.231s" F테스트_참임(t, F호출경로_포함(문자열)) }
non-member
package main import ( "fmt" "sync" ) func greeter(wg *sync.WaitGroup, name string) { fmt.Printf("Hallo %s\n", name) wg.Done() } func main() { wg := &sync.WaitGroup{} wg.Add(1) go greeter(wg, "Alice") wg.Wait() }
non-member
package hexaring import ( "hash" "math/big" ) // CalculateRingVertexes returns the requested number of vertexes around the ring // equi-distant from each other except for potentially the last one which may be larger func CalculateRingVertexes(hash []byte, count int64) []*big.Int { var circum big.Int //circum.SetBytes(maxHash(len(hash))) circum.Exp(big.NewInt(2), big.NewInt(int64(len(hash))*8), nil) // Number of sections arcs := big.NewInt(count) // Size of each section arcWidth := new(big.Int).Div(&circum, arcs) // Starting offset offset := new(big.Int).SetBytes(hash) locs := make([]*big.Int, count) locs[0] = offset for i := int64(1); i < count; i++ { // Index bigI := big.NewInt(i) // Index times the width of the section piece := new(big.Int).Mul(bigI, arcWidth) // Add to offset po := new(big.Int).Add(piece, offset) locs[i] = new(big.Int).Mod(po, &circum) } return locs } // CalculateRingVertexBytes returns the a slice of bytes one for each vertex func CalculateRingVertexBytes(hash []byte, count int64) [][]byte { // Hash size used when produces hashes are smaller. lh := len(hash) // Big int values of hashes vertexes := CalculateRingVertexes(hash, count) // Binary representation out := make([][]byte, len(vertexes)) for i, v := range vertexes { b := v.Bytes() lb := len(b) // Account for modulo. Padd required zeros if lb < lh { p := make([]byte, lh-lb) b = append(p, b...) } out[i] = b } return out } // BuildReplicaHashes hashes the given key and build the required additional hashes // returning the requested count of hashes. func BuildReplicaHashes(key []byte, count int64, h hash.Hash) [][]byte { h.Write(key) sh := h.Sum(nil) return CalculateRingVertexBytes(sh[:], count) } // replicasWithFault returns the number of replicas required in order to tolerate the // given number of faulty nodes. func replicasWithFault(faulty int) int { return (3 * faulty) + 1 } // votesWithFault returns the number of votes required for propose in order to tolerate // the given number of faulty nodes. func votesWithFault(faulty int) int { return (2 * faulty) + 1 } // commitsWithFault returns the number of commits required in order to tolerate the given // number of faulty nodes. func commitsWithFault(faulty int) int { return faulty + 1 } func maxHash(s int) []byte { out := make([]byte, s) for i := range out { out[i] = 0xff } return out }
non-member
package main import ( "fmt" "github.com/formicidae-tracker/zeus/internal/zeus" flags "github.com/jessevdk/go-flags" ) type VersionCommand struct { Args struct { Config flags.Filename } `positional-args:"yes"` } func (c *VersionCommand) Execute(args []string) error { fmt.Printf("%s\n", zeus.ZEUS_VERSION) return nil } func init() { _, err := parser.AddCommand("version", "print zeus version", "prints zeus version on stdout and exit", &VersionCommand{}) if err != nil { panic(err.Error()) } }
non-member
package build import ( "io" "text/template" "github.com/benpate/html" ) // StepInlineSaveButton represents an action-step that can build a Stream into HTML type StepInlineSaveButton struct { ID *template.Template Class string Label *template.Template } // Get builds the Stream HTML to the context func (step StepInlineSaveButton) Get(builder Builder, buffer io.Writer) PipelineBehavior { return nil } func (step StepInlineSaveButton) Post(builder Builder, buffer io.Writer) PipelineBehavior { h := html.New() id := executeTemplate(step.ID, builder) label := executeTemplate(step.Label, builder) h.Button().ID(id).Script("install SaveButton").Class(step.Class + " success").InnerHTML(label) if _, err := buffer.Write(h.Bytes()); err != nil { return Halt().WithError(err) } return Halt().WithHeader("HX-Reswap", "outerHTML").WithHeader("HX-Retarget", "#"+id) }
non-member
/* * @Description: 前置重贴标签算法中图的节点类型 FrontFlowVertex * @Author: wangchengdg@gmail.com * @Date: 2020-02-18 10:31:22 * @LastEditTime: 2020-03-13 22:27:34 * @LastEditors: */ package GraphVertex /*! * * FrontFlowVertex 继承自 FlowVertex,它比FlowVertex顶点多了一个`N_List`数据成员,表示邻接链表 * * relabel_to_front 算法中,每一个FrontFlowVertex顶点位于两个级别的链表中: * * - L 链表:最顶层的链表,L包含了所有的非源、非汇顶点 * - u.N 链表:某个顶点u的邻接链表 * */ type FrontFlowVertex struct { FlowVertex N_List *List //存储和本节点相邻的所有节点 } func NewFrontFlowVertex(k int, ids ...int) *FrontFlowVertex { id := -1 if len(ids) > 0 { id = ids[0] } newList := &List{Head: nil, Current: nil} return &FrontFlowVertex{FlowVertex: FlowVertex{Vertex: Vertex{_ID: id, _Key: k}}, N_List: newList} }
non-member
package main import ( "log" ) func main() { log.SetFlags(log.Ldate | log.Lmicroseconds | log.Llongfile) name := "q0phi80" log.Println("Demo app") log.Printf("%s is here!", name) log.Print("Run") }
non-member
package main import ( "flag" "fmt" "log" "net/http" "os" "github.com/eniehack/persona-server/config" "github.com/eniehack/persona-server/handler" "github.com/go-chi/cors" "github.com/go-chi/chi" "github.com/go-chi/chi/middleware" "github.com/jmoiron/sqlx" _ "github.com/lib/pq" migrate "github.com/rubenv/sql-migrate" "gopkg.in/go-playground/validator.v9" ) func SetUpDataBase(Config *config.DatabaseConfig) (*sqlx.DB, error) { databaseURL := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s", Config.User, Config.Password, Config.Host, Config.Database, Config.SSL) db, err := sqlx.Open("postgres", databaseURL) if err != nil { return nil, fmt.Errorf("failed to connect Database: %s", err) } return db, nil } func main() { var configFilePath string flag.StringVar(&configFilePath, "config", "./configs/config.toml", "config file's path.") flag.Parse() config, err := config.LoadConfig(configFilePath) if err != nil { log.Fatalf("Failed to load config file: %s", err) } corsSettings := cors.New(cors.Options{ AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodOptions, http.MethodDelete}, AllowedHeaders: []string{"Authorization", "Content-Type"}, MaxAge: 3600, ExposedHeaders: []string{"Authorization"}, }) r := chi.NewRouter() r.Use(middleware.Logger) r.Use(middleware.Recoverer) r.Use(corsSettings.Handler) log.Println("Persona v0.1.0-alpha.1 starting......") db, err := SetUpDataBase(config) if err != nil { log.Fatalf(err) } db.SetConnMaxLifetime(1) defer db.Close() log.Println("finiched set up database") validator := validator.New() h := &handler.Handler{ DB: db, Validate: validator, } r.Mount("/api/v1", Router(h)) log.Println("Finished to mount router.") if os.Getenv("PORT") == "" { log.Fatal(http.ListenAndServe(":3000", r)) } else { log.Fatal( http.ListenAndServe( fmt.Sprintf(":%s", os.Getenv("PORT")), r, ), ) } }
non-member
package models type NoSuchObjectError struct { Info string } func (e NoSuchObjectError) Error() string { return e.Info } func NewNoSuchObjectError(s string) NoSuchObjectError { return NoSuchObjectError{Info: s} }
member
package main import ( "encoding/json" "fmt" "log" "net/http" "strings" "github.com/pkg/errors" ) func repoNameToRegistryImageTuple(repo string) (string, string, error) { s := strings.Split(repo, "/") var registryURL, image string switch len(s) { case 2: registryURL = "registry.hub.docker.com" image = s[0] + "/" + s[1] case 3: registryURL = s[0] image = s[1] + "/" + s[2] default: return "", "", fmt.Errorf("couldn't get repo name correctly: %s", repo) } return registryURL, image, nil } func getManifest(t tokenGetter, repo, tag string) (*ManifestResponse, error) { registryURL, image, err := repoNameToRegistryImageTuple(repo) if err != nil { return nil, err } token, err := t.get(registryURL, image) if err != nil { log.Fatalf("Couldn't get auth token: %v", err) } if err := checkIfImageExists(token, registryURL, image, tag); err != nil { return nil, errors.Wrapf(err, "Image %s doesn't exist in %s", image, registryURL) } fmt.Printf("Image %s:%s exists at registry %s\n", image, tag, registryURL) URL := fmt.Sprintf(DockerAPIManifestf, registryURL, image, tag) req, _ := http.NewRequest(http.MethodGet, URL, nil) if len(token) > 0 { req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) } res, err := http.DefaultClient.Do(req) if err != nil { return nil, fmt.Errorf("Fail during HTTP GET %s: %v", URL, err) } defer res.Body.Close() //b, _ := ioutil.ReadAll(res.Body) //fmt.Printf("%s\n", b) contentType := res.Header.Get("Content-Type") if !strings.Contains(contentType, "application/vnd.docker.distribution.manifest.v1+json") && !strings.Contains(contentType, "application/vnd.docker.distribution.manifest.v1+prettyjws") { return nil, fmt.Errorf("Content-Type (schema version) %s not supported", contentType) } // V1 jsonManResp := &ManifestResponse{} if err = json.NewDecoder(res.Body).Decode(jsonManResp); err != nil { return nil, fmt.Errorf("Couldn't decode JSON manifest: %v", err) } return jsonManResp, nil } type FsLayers []struct { BlobSum string `json:"blobSum"` } // ManifestResponse is the json response from manifests API v2 type ManifestResponse struct { Name string `json:"name"` Tag string `json:"tag"` Architecture string `json:"architecture"` SchemaVersion int `json:"schemaVersion"` FsLayers `json:"fsLayers"` History []struct { V1CompatibilityRaw string `json:"v1Compatibility"` V1Compatibility v1Compatibility } `json:"history"` } type v1Compatibility struct { Architecture string `json:"architecture,omitempty"` OS string `json:"os,omitempty"` ID string `json:"id,omitempty"` Parent string `json:"parent,omitempty"` Created string `json:"created,omitempty"` DockerVersion string `json:"docker_version,omitempty"` Throwaway bool `json:"throwaway,omitempty"` //Tty bool `json:"Tty"` //OpenStdin bool `json:"OpenStdin"` //StdinOnce bool `json:"StdinOnce"` //Env []string `json:"Env"` ContainerConfig struct { CmdRaw []string `json:"Cmd"` Cmd string } `json:"container_config"` } type manifestResponse ManifestResponse // UnmarshalJSON implement json.Unmarshaller interface func (m *ManifestResponse) UnmarshalJSON(b []byte) error { var jsonManResp manifestResponse if err := json.Unmarshal(b, &jsonManResp); err != nil { return err } for i := range jsonManResp.History { var comp v1Compatibility if err := json.Unmarshal([]byte(jsonManResp.History[i].V1CompatibilityRaw), &comp); err != nil { continue } jsonManResp.History[i].V1Compatibility = comp jsonManResp.History[i].V1Compatibility.ContainerConfig.Cmd = strings.Join(jsonManResp.History[i].V1Compatibility.ContainerConfig.CmdRaw, " ") } *m = ManifestResponse(jsonManResp) return nil }
non-member
package cpu /* will be useful for debugging func getMode(mode uint8) string { switch mode { case ModeInvalid: return "ModeInvalid" case ModeZeroPage: return "ModeZeroPage" case ModeIndexedZeroPageX: return "ModeIndexedZeroPageX" case ModeIndexedZeroPageY: return "ModeIndexedZeroPageY" case ModeAbsolute: return "ModeAbsolute" case ModeIndexedAbsoluteX: return "ModeIndexedAbsoluteX" case ModeIndexedAbsoluteY: return "ModeIndexedAbsoluteY" case ModeIndirect: return "ModeIndirect" case ModeImplied: return "ModeImplied" case ModeAccumulator: return "ModeAccumulator" case ModeImmediate: return "ModeImmediate" case ModeRelative: return "ModeRelative" case ModeIndexedIndirectX: return "ModeIndexedIndirectX" case ModeIndirectIndexedY: return "ModeIndirectIndexedY" } return "ModeInvalid" } */ func (c *Cpu) setupIns() { // illegal operations have a len of 0 for now // created using table form http://www.oxyron.de/html/opcodes02.html c.addIns2("BRK", 0x00, 1, 7, 0, ModeImplied, c.brk) c.addIns2("ORA", 0x01, 2, 6, 0, ModeIndexedIndirectX, c.ora) c.addIns("KIL", 0x02, 0, 2, 0, ModeImplied) c.addIns("SLO", 0x03, 0, 8, 0, ModeIndexedIndirectX) c.addIns2("NOP", 0x04, 2, 3, 0, ModeZeroPage, c.nop) c.addIns2("ORA", 0x05, 2, 3, 0, ModeZeroPage, c.ora) c.addIns2("ASL", 0x06, 2, 5, 0, ModeZeroPage, c.asl) c.addIns("SLO", 0x07, 0, 5, 0, ModeZeroPage) c.addIns2("PHP", 0x08, 1, 3, 0, ModeImplied, c.php) c.addIns2("ORA", 0x09, 2, 2, 0, ModeImmediate, c.ora) c.addIns2("ASL", 0x0a, 1, 2, 0, ModeAccumulator, c.asl) c.addIns("ANC", 0x0b, 0, 2, 0, ModeImmediate) c.addIns2("NOP", 0x0c, 3, 4, 0, ModeAbsolute, c.nop) c.addIns2("ORA", 0x0d, 3, 4, 0, ModeAbsolute, c.ora) c.addIns2("ASL", 0x0e, 3, 6, 0, ModeAbsolute, c.asl) c.addIns("SLO", 0x0f, 0, 6, 0, ModeAbsolute) c.addIns2("BPL", 0x10, 2, 2, 1, ModeRelative, c.bpl) c.addIns2("ORA", 0x11, 2, 5, 1, ModeIndirectIndexedY, c.ora) c.addIns("KIL", 0x12, 0, 2, 0, ModeImplied) c.addIns("SLO", 0x13, 0, 8, 0, ModeIndirectIndexedY) c.addIns2("NOP", 0x14, 2, 4, 0, ModeIndexedZeroPageX, c.nop) c.addIns2("ORA", 0x15, 2, 4, 0, ModeIndexedZeroPageX, c.ora) c.addIns2("ASL", 0x16, 2, 6, 0, ModeIndexedZeroPageX, c.asl) c.addIns("SLO", 0x17, 0, 6, 0, ModeIndexedZeroPageX) c.addIns2("CLC", 0x18, 1, 2, 0, ModeImplied, c.clc) c.addIns2("ORA", 0x19, 3, 4, 1, ModeIndexedAbsoluteY, c.ora) c.addIns2("NOP", 0x1a, 1, 2, 0, ModeImplied, c.nop) c.addIns("SLO", 0x1b, 0, 7, 0, ModeIndexedAbsoluteY) c.addIns2("NOP", 0x1c, 3, 4, 1, ModeIndexedAbsoluteX, c.nop) c.addIns2("ORA", 0x1d, 3, 4, 1, ModeIndexedAbsoluteX, c.ora) c.addIns2("ASL", 0x1e, 3, 7, 0, ModeIndexedAbsoluteX, c.asl) c.addIns("SLO", 0x1f, 0, 7, 0, ModeIndexedAbsoluteX) c.addIns2("JSR", 0x20, 3, 6, 0, ModeAbsolute, c.jsr) c.addIns2("AND", 0x21, 2, 6, 0, ModeIndexedIndirectX, c.and) c.addIns("KIL", 0x22, 0, 2, 0, ModeImplied) c.addIns("RLA", 0x23, 0, 8, 0, ModeIndexedIndirectX) c.addIns2("BIT", 0x24, 2, 3, 0, ModeZeroPage, c.bit) c.addIns2("AND", 0x25, 2, 3, 0, ModeZeroPage, c.and) c.addIns2("ROL", 0x26, 2, 5, 0, ModeZeroPage, c.rol) c.addIns("RLA", 0x27, 0, 5, 0, ModeZeroPage) c.addIns2("PLP", 0x28, 1, 4, 0, ModeImplied, c.plp) c.addIns2("AND", 0x29, 2, 2, 0, ModeImmediate, c.and) c.addIns2("ROL", 0x2a, 1, 2, 0, ModeAccumulator, c.rol) c.addIns("ANC", 0x2b, 0, 2, 0, ModeImmediate) c.addIns2("BIT", 0x2c, 3, 4, 0, ModeAbsolute, c.bit) c.addIns2("AND", 0x2d, 3, 4, 0, ModeAbsolute, c.and) c.addIns2("ROL", 0x2e, 3, 6, 0, ModeAbsolute, c.rol) c.addIns("RLA", 0x2f, 0, 6, 0, ModeAbsolute) c.addIns2("BMI", 0x30, 2, 2, 1, ModeRelative, c.bmi) c.addIns2("AND", 0x31, 2, 5, 1, ModeIndirectIndexedY, c.and) c.addIns("KIL", 0x32, 0, 2, 0, ModeImplied) c.addIns("RLA", 0x33, 0, 8, 0, ModeIndirectIndexedY) c.addIns2("NOP", 0x34, 2, 4, 0, ModeIndexedZeroPageX, c.nop) c.addIns2("AND", 0x35, 2, 4, 0, ModeIndexedZeroPageX, c.and) c.addIns2("ROL", 0x36, 2, 6, 0, ModeIndexedZeroPageX, c.rol) c.addIns("RLA", 0x37, 0, 6, 0, ModeIndexedZeroPageX) c.addIns2("SEC", 0x38, 1, 2, 0, ModeImplied, c.sec) c.addIns2("AND", 0x39, 3, 4, 1, ModeIndexedAbsoluteY, c.and) c.addIns2("NOP", 0x3a, 1, 2, 0, ModeImplied, c.nop) c.addIns("RLA", 0x3b, 0, 7, 0, ModeIndexedAbsoluteY) c.addIns2("NOP", 0x3c, 3, 4, 1, ModeIndexedAbsoluteX, c.nop) c.addIns2("AND", 0x3d, 3, 4, 1, ModeIndexedAbsoluteX, c.and) c.addIns2("ROL", 0x3e, 3, 7, 0, ModeIndexedAbsoluteX, c.rol) c.addIns("RLA", 0x3f, 0, 7, 0, ModeIndexedAbsoluteX) c.addIns2("RTI", 0x40, 1, 6, 0, ModeImplied, c.rti) c.addIns2("EOR", 0x41, 2, 6, 0, ModeIndexedIndirectX, c.eor) c.addIns("KIL", 0x42, 0, 2, 0, ModeImplied) c.addIns("SRE", 0x43, 0, 8, 0, ModeIndexedIndirectX) c.addIns2("NOP", 0x44, 2, 3, 0, ModeZeroPage, c.nop) c.addIns2("EOR", 0x45, 2, 3, 0, ModeZeroPage, c.eor) c.addIns2("LSR", 0x46, 2, 5, 0, ModeZeroPage, c.lsr) c.addIns("SRE", 0x47, 0, 5, 0, ModeZeroPage) c.addIns2("PHA", 0x48, 1, 3, 0, ModeImplied, c.pha) c.addIns2("EOR", 0x49, 2, 2, 0, ModeImmediate, c.eor) c.addIns2("LSR", 0x4a, 1, 2, 0, ModeAccumulator, c.lsr) c.addIns("ALR", 0x4b, 0, 2, 0, ModeImmediate) c.addIns2("JMP", 0x4c, 3, 3, 0, ModeAbsolute, c.jmp) c.addIns2("EOR", 0x4d, 3, 4, 0, ModeAbsolute, c.eor) c.addIns2("LSR", 0x4e, 3, 6, 0, ModeAbsolute, c.lsr) c.addIns("SRE", 0x4f, 0, 6, 0, ModeAbsolute) c.addIns2("BVC", 0x50, 2, 2, 1, ModeRelative, c.bvc) c.addIns2("EOR", 0x51, 2, 5, 1, ModeIndirectIndexedY, c.eor) c.addIns("KIL", 0x52, 0, 2, 0, ModeImplied) c.addIns("SRE", 0x53, 0, 8, 0, ModeIndirectIndexedY) c.addIns2("NOP", 0x54, 2, 4, 0, ModeIndexedZeroPageX, c.nop) c.addIns2("EOR", 0x55, 2, 4, 0, ModeIndexedZeroPageX, c.eor) c.addIns2("LSR", 0x56, 2, 6, 0, ModeIndexedZeroPageX, c.lsr) c.addIns("SRE", 0x57, 0, 6, 0, ModeIndexedZeroPageX) c.addIns2("CLI", 0x58, 1, 2, 0, ModeImplied, c.cli) c.addIns2("EOR", 0x59, 3, 4, 1, ModeIndexedAbsoluteY, c.eor) c.addIns2("NOP", 0x5a, 1, 2, 0, ModeImplied, c.nop) c.addIns("SRE", 0x5b, 0, 7, 0, ModeIndexedAbsoluteY) c.addIns2("NOP", 0x5c, 3, 4, 1, ModeIndexedAbsoluteX, c.nop) c.addIns2("EOR", 0x5d, 3, 4, 1, ModeIndexedAbsoluteX, c.eor) c.addIns2("LSR", 0x5e, 3, 7, 0, ModeIndexedAbsoluteX, c.lsr) c.addIns("SRE", 0x5f, 0, 7, 0, ModeIndexedAbsoluteX) c.addIns2("RTS", 0x60, 1, 6, 0, ModeImplied, c.rts) c.addIns2("ADC", 0x61, 2, 6, 0, ModeIndexedIndirectX, c.adc) c.addIns("KIL", 0x62, 0, 2, 0, ModeImplied) c.addIns("RRA", 0x63, 0, 8, 0, ModeIndexedIndirectX) c.addIns2("NOP", 0x64, 2, 3, 0, ModeZeroPage, c.nop) c.addIns2("ADC", 0x65, 2, 3, 0, ModeZeroPage, c.adc) c.addIns2("ROR", 0x66, 2, 5, 0, ModeZeroPage, c.ror) c.addIns("RRA", 0x67, 0, 5, 0, ModeZeroPage) c.addIns2("PLA", 0x68, 1, 4, 0, ModeImplied, c.pla) c.addIns2("ADC", 0x69, 2, 2, 0, ModeImmediate, c.adc) c.addIns2("ROR", 0x6a, 1, 2, 0, ModeAccumulator, c.ror) c.addIns("ARR", 0x6b, 0, 2, 0, ModeImmediate) c.addIns2("JMP", 0x6c, 3, 5, 0, ModeIndirect, c.jmp) c.addIns2("ADC", 0x6d, 3, 4, 0, ModeAbsolute, c.adc) c.addIns2("ROR", 0x6e, 3, 6, 0, ModeAbsolute, c.ror) c.addIns("RRA", 0x6f, 0, 6, 0, ModeAbsolute) c.addIns2("BVS", 0x70, 2, 2, 1, ModeRelative, c.bvs) c.addIns2("ADC", 0x71, 2, 5, 1, ModeIndirectIndexedY, c.adc) c.addIns("KIL", 0x72, 0, 2, 0, ModeImplied) c.addIns("RRA", 0x73, 0, 8, 0, ModeIndirectIndexedY) c.addIns2("NOP", 0x74, 2, 4, 0, ModeIndexedZeroPageX, c.nop) c.addIns2("ADC", 0x75, 2, 4, 0, ModeIndexedZeroPageX, c.adc) c.addIns2("ROR", 0x76, 2, 6, 0, ModeIndexedZeroPageX, c.ror) c.addIns("RRA", 0x77, 0, 6, 0, ModeIndexedZeroPageX) c.addIns2("SEI", 0x78, 1, 2, 0, ModeImplied, c.sei) c.addIns2("ADC", 0x79, 3, 4, 1, ModeIndexedAbsoluteY, c.adc) c.addIns2("NOP", 0x7a, 1, 2, 0, ModeImplied, c.nop) c.addIns("RRA", 0x7b, 0, 7, 0, ModeIndexedAbsoluteY) c.addIns2("NOP", 0x7c, 3, 4, 1, ModeIndexedAbsoluteX, c.nop) c.addIns2("ADC", 0x7d, 3, 4, 1, ModeIndexedAbsoluteX, c.adc) c.addIns2("ROR", 0x7e, 3, 7, 0, ModeIndexedAbsoluteX, c.ror) c.addIns("RRA", 0x7f, 0, 7, 0, ModeIndexedAbsoluteX) c.addIns2("NOP", 0x80, 2, 2, 0, ModeImmediate, c.nop) c.addIns2("STA", 0x81, 2, 6, 0, ModeIndexedIndirectX, c.sta) c.addIns2("NOP", 0x82, 0, 2, 0, ModeImmediate, c.nop) c.addIns("SAX", 0x83, 0, 6, 0, ModeIndexedIndirectX) c.addIns2("STY", 0x84, 2, 3, 0, ModeZeroPage, c.sty) c.addIns2("STA", 0x85, 2, 3, 0, ModeZeroPage, c.sta) c.addIns2("STX", 0x86, 2, 3, 0, ModeZeroPage, c.stx) c.addIns("SAX", 0x87, 0, 3, 0, ModeZeroPage) c.addIns2("DEY", 0x88, 1, 2, 0, ModeImplied, c.dey) c.addIns2("NOP", 0x89, 0, 2, 0, ModeImmediate, c.nop) c.addIns2("TXA", 0x8a, 1, 2, 0, ModeImplied, c.txa) c.addIns("XAA", 0x8b, 0, 2, 0, ModeImmediate) c.addIns2("STY", 0x8c, 3, 4, 0, ModeAbsolute, c.sty) c.addIns2("STA", 0x8d, 3, 4, 0, ModeAbsolute, c.sta) c.addIns2("STX", 0x8e, 3, 4, 0, ModeAbsolute, c.stx) c.addIns("SAX", 0x8f, 0, 4, 0, ModeAbsolute) c.addIns2("BCC", 0x90, 2, 2, 1, ModeRelative, c.bcc) c.addIns2("STA", 0x91, 2, 6, 0, ModeIndirectIndexedY, c.sta) c.addIns("KIL", 0x92, 0, 2, 0, ModeImplied) c.addIns("AHX", 0x93, 0, 6, 0, ModeIndirectIndexedY) c.addIns2("STY", 0x94, 2, 4, 0, ModeIndexedZeroPageX, c.sty) c.addIns2("STA", 0x95, 2, 4, 0, ModeIndexedZeroPageX, c.sta) c.addIns2("STX", 0x96, 2, 4, 0, ModeIndexedZeroPageY, c.stx) c.addIns("SAX", 0x97, 0, 4, 0, ModeIndexedZeroPageY) c.addIns2("TYA", 0x98, 1, 2, 0, ModeImplied, c.tya) c.addIns2("STA", 0x99, 3, 5, 0, ModeIndexedAbsoluteY, c.sta) c.addIns2("TXS", 0x9a, 1, 2, 0, ModeImplied, c.txs) c.addIns("TAS", 0x9b, 0, 5, 0, ModeIndexedAbsoluteY) c.addIns("SHY", 0x9c, 0, 5, 0, ModeIndexedAbsoluteX) c.addIns2("STA", 0x9d, 3, 5, 0, ModeIndexedAbsoluteX, c.sta) c.addIns("SHX", 0x9e, 0, 5, 0, ModeIndexedAbsoluteY) c.addIns("AHX", 0x9f, 0, 5, 0, ModeIndexedAbsoluteY) c.addIns2("LDY", 0xa0, 2, 2, 0, ModeImmediate, c.ldy) c.addIns2("LDA", 0xa1, 2, 6, 0, ModeIndexedIndirectX, c.lda) c.addIns2("LDX", 0xa2, 2, 2, 0, ModeImmediate, c.ldx) c.addIns("LAX", 0xa3, 0, 6, 0, ModeIndexedIndirectX) c.addIns2("LDY", 0xa4, 2, 3, 0, ModeZeroPage, c.ldy) c.addIns2("LDA", 0xa5, 2, 3, 0, ModeZeroPage, c.lda) c.addIns2("LDX", 0xa6, 2, 3, 0, ModeZeroPage, c.ldx) c.addIns("LAX", 0xa7, 0, 3, 0, ModeZeroPage) c.addIns2("TAY", 0xa8, 1, 2, 0, ModeImplied, c.tay) c.addIns2("LDA", 0xa9, 2, 2, 0, ModeImmediate, c.lda) c.addIns2("TAX", 0xaa, 1, 2, 0, ModeImplied, c.tax) c.addIns("LAX", 0xab, 0, 2, 0, ModeImmediate) c.addIns2("LDY", 0xac, 3, 4, 0, ModeAbsolute, c.ldy) c.addIns2("LDA", 0xad, 3, 4, 0, ModeAbsolute, c.lda) c.addIns2("LDX", 0xae, 3, 4, 0, ModeAbsolute, c.ldx) c.addIns("LAX", 0xaf, 0, 4, 0, ModeAbsolute) c.addIns2("BCS", 0xb0, 2, 2, 1, ModeRelative, c.bcs) c.addIns2("LDA", 0xb1, 2, 5, 1, ModeIndirectIndexedY, c.lda) c.addIns("KIL", 0xb2, 0, 2, 0, ModeImplied) c.addIns("LAX", 0xb3, 0, 5, 1, ModeIndirectIndexedY) c.addIns2("LDY", 0xb4, 2, 4, 0, ModeIndexedZeroPageX, c.ldy) c.addIns2("LDA", 0xb5, 2, 4, 0, ModeIndexedZeroPageX, c.lda) c.addIns2("LDX", 0xb6, 2, 4, 0, ModeIndexedZeroPageY, c.ldx) c.addIns("LAX", 0xb7, 0, 4, 0, ModeIndexedZeroPageY) c.addIns2("CLV", 0xb8, 1, 2, 0, ModeImplied, c.clv) c.addIns2("LDA", 0xb9, 3, 4, 1, ModeIndexedAbsoluteY, c.lda) c.addIns2("TSX", 0xba, 1, 2, 0, ModeImplied, c.tsx) c.addIns("LAS", 0xbb, 0, 4, 1, ModeIndexedAbsoluteY) c.addIns2("LDY", 0xbc, 3, 4, 1, ModeIndexedAbsoluteX, c.ldy) c.addIns2("LDA", 0xbd, 3, 4, 1, ModeIndexedAbsoluteX, c.lda) c.addIns2("LDX", 0xbe, 3, 4, 1, ModeIndexedAbsoluteY, c.ldx) c.addIns("LAX", 0xbf, 0, 4, 1, ModeIndexedAbsoluteY) c.addIns2("CPY", 0xc0, 2, 2, 0, ModeImmediate, c.cpy) c.addIns2("CMP", 0xc1, 2, 6, 0, ModeIndexedIndirectX, c.cmp) c.addIns2("NOP", 0xc2, 0, 2, 0, ModeImmediate, c.nop) c.addIns("DCP", 0xc3, 0, 8, 0, ModeIndexedIndirectX) c.addIns2("CPY", 0xc4, 2, 3, 0, ModeZeroPage, c.cpy) c.addIns2("CMP", 0xc5, 2, 3, 0, ModeZeroPage, c.cmp) c.addIns2("DEC", 0xc6, 2, 5, 0, ModeZeroPage, c.dec) c.addIns("DCP", 0xc7, 0, 5, 0, ModeZeroPage) c.addIns2("INY", 0xc8, 1, 2, 0, ModeImplied, c.iny) c.addIns2("CMP", 0xc9, 2, 2, 0, ModeImmediate, c.cmp) c.addIns2("DEX", 0xca, 1, 2, 0, ModeImplied, c.dex) c.addIns("AXS", 0xcb, 0, 2, 0, ModeImmediate) c.addIns2("CPY", 0xcc, 3, 4, 0, ModeAbsolute, c.cpy) c.addIns2("CMP", 0xcd, 3, 4, 0, ModeAbsolute, c.cmp) c.addIns2("DEC", 0xce, 3, 6, 0, ModeAbsolute, c.dec) c.addIns("DCP", 0xcf, 0, 6, 0, ModeAbsolute) c.addIns2("BNE", 0xd0, 2, 2, 1, ModeRelative, c.bne) c.addIns2("CMP", 0xd1, 2, 5, 1, ModeIndirectIndexedY, c.cmp) c.addIns("KIL", 0xd2, 0, 2, 0, ModeImplied) c.addIns("DCP", 0xd3, 0, 8, 0, ModeIndirectIndexedY) c.addIns2("NOP", 0xd4, 2, 4, 0, ModeIndexedZeroPageX, c.nop) c.addIns2("CMP", 0xd5, 2, 4, 0, ModeIndexedZeroPageX, c.cmp) c.addIns2("DEC", 0xd6, 2, 6, 0, ModeIndexedZeroPageX, c.dec) c.addIns("DCP", 0xd7, 0, 6, 0, ModeIndexedZeroPageX) c.addIns2("CLD", 0xd8, 1, 2, 0, ModeImplied, c.cld) c.addIns2("CMP", 0xd9, 3, 4, 1, ModeIndexedAbsoluteY, c.cmp) c.addIns2("NOP", 0xda, 1, 2, 0, ModeImplied, c.nop) c.addIns("DCP", 0xdb, 0, 7, 0, ModeIndexedAbsoluteY) c.addIns2("NOP", 0xdc, 3, 4, 1, ModeIndexedAbsoluteX, c.nop) c.addIns2("CMP", 0xdd, 3, 4, 1, ModeIndexedAbsoluteX, c.cmp) c.addIns2("DEC", 0xde, 3, 7, 0, ModeIndexedAbsoluteX, c.dec) c.addIns("DCP", 0xdf, 0, 7, 0, ModeIndexedAbsoluteX) c.addIns2("CPX", 0xe0, 2, 2, 0, ModeImmediate, c.cpx) c.addIns2("SBC", 0xe1, 2, 6, 0, ModeIndexedIndirectX, c.sbc) c.addIns2("NOP", 0xe2, 0, 2, 0, ModeImmediate, c.nop) c.addIns("ISB", 0xe3, 0, 8, 0, ModeIndexedIndirectX) c.addIns2("CPX", 0xe4, 2, 3, 0, ModeZeroPage, c.cpx) c.addIns2("SBC", 0xe5, 2, 3, 0, ModeZeroPage, c.sbc) c.addIns2("INC", 0xe6, 2, 5, 0, ModeZeroPage, c.inc) c.addIns("ISB", 0xe7, 0, 5, 0, ModeZeroPage) c.addIns2("INX", 0xe8, 1, 2, 0, ModeImplied, c.inx) c.addIns2("SBC", 0xe9, 2, 2, 0, ModeImmediate, c.sbc) c.addIns2("NOP", 0xea, 1, 2, 0, ModeImplied, c.nop) c.addIns2("SBC", 0xeb, 0, 2, 0, ModeImmediate, c.sbc) c.addIns2("CPX", 0xec, 3, 4, 0, ModeAbsolute, c.cpx) c.addIns2("SBC", 0xed, 3, 4, 0, ModeAbsolute, c.sbc) c.addIns2("INC", 0xee, 3, 6, 0, ModeAbsolute, c.inc) c.addIns("ISB", 0xef, 0, 6, 0, ModeAbsolute) c.addIns2("BEQ", 0xf0, 2, 2, 1, ModeRelative, c.beq) c.addIns2("SBC", 0xf1, 2, 5, 1, ModeIndirectIndexedY, c.sbc) c.addIns("KIL", 0xf2, 0, 2, 0, ModeImplied) c.addIns("ISB", 0xf3, 0, 8, 0, ModeIndirectIndexedY) c.addIns2("NOP", 0xf4, 2, 4, 0, ModeIndexedZeroPageX, c.nop) c.addIns2("SBC", 0xf5, 2, 4, 0, ModeIndexedZeroPageX, c.sbc) c.addIns2("INC", 0xf6, 2, 6, 0, ModeIndexedZeroPageX, c.inc) c.addIns("ISB", 0xf7, 0, 6, 0, ModeIndexedZeroPageX) c.addIns2("SED", 0xf8, 1, 2, 0, ModeImplied, c.sed) c.addIns2("SBC", 0xf9, 3, 4, 1, ModeIndexedAbsoluteY, c.sbc) c.addIns2("NOP", 0xfa, 1, 2, 0, ModeImplied, c.nop) c.addIns("ISB", 0xfb, 0, 7, 0, ModeIndexedAbsoluteY) c.addIns2("NOP", 0xfc, 3, 4, 1, ModeIndexedAbsoluteX, c.nop) c.addIns2("SBC", 0xfd, 3, 4, 1, ModeIndexedAbsoluteX, c.sbc) c.addIns2("INC", 0xfe, 3, 7, 0, ModeIndexedAbsoluteX, c.inc) c.addIns("ISB", 0xff, 0, 7, 0, ModeIndexedAbsoluteX) } func (c *Cpu) unhandled() { message := "oops... unhandled instruction!\n" c.Logf(message) panic(message) } func (c *Cpu) addIns(opName string, opCode uint8, opLength uint8, opCycles uint8, opPageCycles uint8, addrMode uint8) { c.ins[opCode] = Instruction{opLength, opCycles, opPageCycles, addrMode, opCode, opName, c.unhandled, false} } func (c *Cpu) addIns2(opName string, opCode uint8, opLength uint8, opCycles uint8, opPageCycles uint8, addrMode uint8, f func()) { c.ins[opCode] = Instruction{opLength, opCycles, opPageCycles, addrMode, opCode, opName, f, true} }
member
package cluster import ( "testing" "github.com/ditrit/gandalf/core/cluster" ) func TestNewClusterMember(t *testing.T) { const ( logicalName string = "test" databasePath string = "test" logPath string = "test" shosetType string = "cl" ) connectorMember := cluster.NewClusterMember(logicalName, databasePath, logPath) if connectorMember == nil { t.Errorf("Should not be nil") } if connectorMember.GetChaussette().GetName() != logicalName { t.Errorf("Should be equal") } if connectorMember.GetChaussette().GetShosetType() != shosetType { t.Errorf("Should be equal") } if connectorMember.MapDatabaseClient == nil { t.Errorf("Should not be nil") } if connectorMember.GetChaussette().Handle["cfgjoin"] == nil { t.Errorf("Should not be nil") } if connectorMember.GetChaussette().Handle["cmd"] == nil { t.Errorf("Should not be nil") } if connectorMember.GetChaussette().Handle["evt"] == nil { t.Errorf("Should not be nil") } } func TestClusterMemberInit(t *testing.T) { const ( logicalName string = "test" databasePath string = "test" logPath string = "test" shosetType string = "cls" bindAddress string = "127.0.0.1:8001" ) clusterMember := cluster.ClusterMemberInit(logicalName, bindAddress, databasePath, logPath) if clusterMember == nil { t.Errorf("Should not be nil") } if clusterMember.GetChaussette().GetBindAddr() != bindAddress { t.Errorf("Should be equal") } }
non-member
package main import ( "flag" "log" "net/http" "os" "github.com/nsmith5/vgraas/pkg/middleware" "github.com/nsmith5/vgraas/pkg/vgraas" ) func main() { var ( addr = flag.String("api", ":8080", "API listen address") ) flag.Parse() var api http.Handler { repo := vgraas.NewRAMRepo() api = vgraas.NewAPI(repo) // Limit request size to 500 KiB api = middleware.LimitBody(api, 1<<19) // Rate limit requests to 5Hz per remote address with bursts of 2 api = middleware.RateLimit(api, 5, 2, middleware.XForwardedFor) // Logging api = middleware.Logging(api, os.Stdout) } log.Println(http.ListenAndServe(*addr, api)) }
non-member
package util import ( "fmt" "testing" ) func TestGenerateRandomString(t *testing.T) { for _, length := range []int{0, 10, 25} { t.Run(fmt.Sprintf("length_%d", length), func(t *testing.T) { rnd := GenerateRandomString(length) if len(rnd) != length { t.Errorf("GenerateRandomString() = %v, want %v", len(rnd), length) } }) } } func TestIsNameValid(t *testing.T) { tests := []struct { name string username string want bool }{ {"empty", "", false}, {"too long", "12345678901234567", false}, {"16", "1234567890123456", true}, {"spaces", "hello world", false}, {"no spaces", "helloworld", true}, {"special chars", "helloworld!", false}, {"only special chars", "!ยง$%&", false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := IsNameValid(tt.username); got != tt.want { t.Errorf("IsNameValid() = %v, want %v", got, tt.want) } }) } }
non-member
package web import "testing" func TestIndexHandler(t *testing.T) { rr := testHandler(createRouter(), "GET", "/", nil) if rr.Code != 200 { t.Fatalf("Expected index to respond with 200, got %d instead", rr.Code) } }
non-member
package uix import ( "git.kirsle.net/SketchyMaze/doodle/pkg/shmem" "git.kirsle.net/go/render" "git.kirsle.net/go/ui" ) /* Functions for the Crosshair feature of the game. NOT dependent on Canvas! */ type Crosshair struct { LengthPct float64 // between 0 and 1 Widget ui.Widget } func NewCrosshair(child ui.Widget, length float64) *Crosshair { return &Crosshair{ LengthPct: length, Widget: child, } } // DrawCrosshair renders a crosshair on the screen. It appears while the mouse cursor is // over the child widget and draws within the bounds of the child widget. // // The lengthPct is an integer ranged 0 to 100 to be a percentage length of the crosshair. // A value of zero will not draw anything and just return. func DrawCrosshair(e render.Engine, child ui.Widget, color render.Color, lengthPct int) { // Get our window boundaries based on our widget. var ( Position = ui.AbsolutePosition(child) Size = child.Size() Cursor = shmem.Cursor VertLine = []render.Point{ {X: Cursor.X, Y: Position.Y}, {X: Cursor.X, Y: Position.Y + Size.H}, } HozLine = []render.Point{ {X: Position.X, Y: Cursor.Y}, {X: Position.X + Size.W, Y: Cursor.Y}, } ) if lengthPct > 100 { lengthPct = 100 } else if lengthPct <= 0 { return } // Mouse outside our box. if Cursor.X < Position.X || Cursor.X > Position.X+Size.W || Cursor.Y < Position.Y || Cursor.Y > Position.Y+Size.H { return } e.DrawLine( color, VertLine[0], VertLine[1], ) e.DrawLine( color, HozLine[0], HozLine[1], ) }
non-member
package polyglot var zobristHashes = [781]uint64{ 0x9D39247E33776D41, 0x2AF7398005AAA5C7, 0x44DB015024623547, 0x9C15F73E62A76AE2, 0x75834465489C0C89, 0x3290AC3A203001BF, 0x0FBBAD1F61042279, 0xE83A908FF2FB60CA, 0x0D7E765D58755C10, 0x1A083822CEAFE02D, 0x9605D5F0E25EC3B0, 0xD021FF5CD13A2ED5, 0x40BDF15D4A672E32, 0x011355146FD56395, 0x5DB4832046F3D9E5, 0x239F8B2D7FF719CC, 0x05D1A1AE85B49AA1, 0x679F848F6E8FC971, 0x7449BBFF801FED0B, 0x7D11CDB1C3B7ADF0, 0x82C7709E781EB7CC, 0xF3218F1C9510786C, 0x331478F3AF51BBE6, 0x4BB38DE5E7219443, 0xAA649C6EBCFD50FC, 0x8DBD98A352AFD40B, 0x87D2074B81D79217, 0x19F3C751D3E92AE1, 0xB4AB30F062B19ABF, 0x7B0500AC42047AC4, 0xC9452CA81A09D85D, 0x24AA6C514DA27500, 0x4C9F34427501B447, 0x14A68FD73C910841, 0xA71B9B83461CBD93, 0x03488B95B0F1850F, 0x637B2B34FF93C040, 0x09D1BC9A3DD90A94, 0x3575668334A1DD3B, 0x735E2B97A4C45A23, 0x18727070F1BD400B, 0x1FCBACD259BF02E7, 0xD310A7C2CE9B6555, 0xBF983FE0FE5D8244, 0x9F74D14F7454A824, 0x51EBDC4AB9BA3035, 0x5C82C505DB9AB0FA, 0xFCF7FE8A3430B241, 0x3253A729B9BA3DDE, 0x8C74C368081B3075, 0xB9BC6C87167C33E7, 0x7EF48F2B83024E20, 0x11D505D4C351BD7F, 0x6568FCA92C76A243, 0x4DE0B0F40F32A7B8, 0x96D693460CC37E5D, 0x42E240CB63689F2F, 0x6D2BDCDAE2919661, 0x42880B0236E4D951, 0x5F0F4A5898171BB6, 0x39F890F579F92F88, 0x93C5B5F47356388B, 0x63DC359D8D231B78, 0xEC16CA8AEA98AD76, 0x5355F900C2A82DC7, 0x07FB9F855A997142, 0x5093417AA8A7ED5E, 0x7BCBC38DA25A7F3C, 0x19FC8A768CF4B6D4, 0x637A7780DECFC0D9, 0x8249A47AEE0E41F7, 0x79AD695501E7D1E8, 0x14ACBAF4777D5776, 0xF145B6BECCDEA195, 0xDABF2AC8201752FC, 0x24C3C94DF9C8D3F6, 0xBB6E2924F03912EA, 0x0CE26C0B95C980D9, 0xA49CD132BFBF7CC4, 0xE99D662AF4243939, 0x27E6AD7891165C3F, 0x8535F040B9744FF1, 0x54B3F4FA5F40D873, 0x72B12C32127FED2B, 0xEE954D3C7B411F47, 0x9A85AC909A24EAA1, 0x70AC4CD9F04F21F5, 0xF9B89D3E99A075C2, 0x87B3E2B2B5C907B1, 0xA366E5B8C54F48B8, 0xAE4A9346CC3F7CF2, 0x1920C04D47267BBD, 0x87BF02C6B49E2AE9, 0x092237AC237F3859, 0xFF07F64EF8ED14D0, 0x8DE8DCA9F03CC54E, 0x9C1633264DB49C89, 0xB3F22C3D0B0B38ED, 0x390E5FB44D01144B, 0x5BFEA5B4712768E9, 0x1E1032911FA78984, 0x9A74ACB964E78CB3, 0x4F80F7A035DAFB04, 0x6304D09A0B3738C4, 0x2171E64683023A08, 0x5B9B63EB9CEFF80C, 0x506AACF489889342, 0x1881AFC9A3A701D6, 0x6503080440750644, 0xDFD395339CDBF4A7, 0xEF927DBCF00C20F2, 0x7B32F7D1E03680EC, 0xB9FD7620E7316243, 0x05A7E8A57DB91B77, 0xB5889C6E15630A75, 0x4A750A09CE9573F7, 0xCF464CEC899A2F8A, 0xF538639CE705B824, 0x3C79A0FF5580EF7F, 0xEDE6C87F8477609D, 0x799E81F05BC93F31, 0x86536B8CF3428A8C, 0x97D7374C60087B73, 0xA246637CFF328532, 0x043FCAE60CC0EBA0, 0x920E449535DD359E, 0x70EB093B15B290CC, 0x73A1921916591CBD, 0x56436C9FE1A1AA8D, 0xEFAC4B70633B8F81, 0xBB215798D45DF7AF, 0x45F20042F24F1768, 0x930F80F4E8EB7462, 0xFF6712FFCFD75EA1, 0xAE623FD67468AA70, 0xDD2C5BC84BC8D8FC, 0x7EED120D54CF2DD9, 0x22FE545401165F1C, 0xC91800E98FB99929, 0x808BD68E6AC10365, 0xDEC468145B7605F6, 0x1BEDE3A3AEF53302, 0x43539603D6C55602, 0xAA969B5C691CCB7A, 0xA87832D392EFEE56, 0x65942C7B3C7E11AE, 0xDED2D633CAD004F6, 0x21F08570F420E565, 0xB415938D7DA94E3C, 0x91B859E59ECB6350, 0x10CFF333E0ED804A, 0x28AED140BE0BB7DD, 0xC5CC1D89724FA456, 0x5648F680F11A2741, 0x2D255069F0B7DAB3, 0x9BC5A38EF729ABD4, 0xEF2F054308F6A2BC, 0xAF2042F5CC5C2858, 0x480412BAB7F5BE2A, 0xAEF3AF4A563DFE43, 0x19AFE59AE451497F, 0x52593803DFF1E840, 0xF4F076E65F2CE6F0, 0x11379625747D5AF3, 0xBCE5D2248682C115, 0x9DA4243DE836994F, 0x066F70B33FE09017, 0x4DC4DE189B671A1C, 0x51039AB7712457C3, 0xC07A3F80C31FB4B4, 0xB46EE9C5E64A6E7C, 0xB3819A42ABE61C87, 0x21A007933A522A20, 0x2DF16F761598AA4F, 0x763C4A1371B368FD, 0xF793C46702E086A0, 0xD7288E012AEB8D31, 0xDE336A2A4BC1C44B, 0x0BF692B38D079F23, 0x2C604A7A177326B3, 0x4850E73E03EB6064, 0xCFC447F1E53C8E1B, 0xB05CA3F564268D99, 0x9AE182C8BC9474E8, 0xA4FC4BD4FC5558CA, 0xE755178D58FC4E76, 0x69B97DB1A4C03DFE, 0xF9B5B7C4ACC67C96, 0xFC6A82D64B8655FB, 0x9C684CB6C4D24417, 0x8EC97D2917456ED0, 0x6703DF9D2924E97E, 0xC547F57E42A7444E, 0x78E37644E7CAD29E, 0xFE9A44E9362F05FA, 0x08BD35CC38336615, 0x9315E5EB3A129ACE, 0x94061B871E04DF75, 0xDF1D9F9D784BA010, 0x3BBA57B68871B59D, 0xD2B7ADEEDED1F73F, 0xF7A255D83BC373F8, 0xD7F4F2448C0CEB81, 0xD95BE88CD210FFA7, 0x336F52F8FF4728E7, 0xA74049DAC312AC71, 0xA2F61BB6E437FDB5, 0x4F2A5CB07F6A35B3, 0x87D380BDA5BF7859, 0x16B9F7E06C453A21, 0x7BA2484C8A0FD54E, 0xF3A678CAD9A2E38C, 0x39B0BF7DDE437BA2, 0xFCAF55C1BF8A4424, 0x18FCF680573FA594, 0x4C0563B89F495AC3, 0x40E087931A00930D, 0x8CFFA9412EB642C1, 0x68CA39053261169F, 0x7A1EE967D27579E2, 0x9D1D60E5076F5B6F, 0x3810E399B6F65BA2, 0x32095B6D4AB5F9B1, 0x35CAB62109DD038A, 0xA90B24499FCFAFB1, 0x77A225A07CC2C6BD, 0x513E5E634C70E331, 0x4361C0CA3F692F12, 0xD941ACA44B20A45B, 0x528F7C8602C5807B, 0x52AB92BEB9613989, 0x9D1DFA2EFC557F73, 0x722FF175F572C348, 0x1D1260A51107FE97, 0x7A249A57EC0C9BA2, 0x04208FE9E8F7F2D6, 0x5A110C6058B920A0, 0x0CD9A497658A5698, 0x56FD23C8F9715A4C, 0x284C847B9D887AAE, 0x04FEABFBBDB619CB, 0x742E1E651C60BA83, 0x9A9632E65904AD3C, 0x881B82A13B51B9E2, 0x506E6744CD974924, 0xB0183DB56FFC6A79, 0x0ED9B915C66ED37E, 0x5E11E86D5873D484, 0xF678647E3519AC6E, 0x1B85D488D0F20CC5, 0xDAB9FE6525D89021, 0x0D151D86ADB73615, 0xA865A54EDCC0F019, 0x93C42566AEF98FFB, 0x99E7AFEABE000731, 0x48CBFF086DDF285A, 0x7F9B6AF1EBF78BAF, 0x58627E1A149BBA21, 0x2CD16E2ABD791E33, 0xD363EFF5F0977996, 0x0CE2A38C344A6EED, 0x1A804AADB9CFA741, 0x907F30421D78C5DE, 0x501F65EDB3034D07, 0x37624AE5A48FA6E9, 0x957BAF61700CFF4E, 0x3A6C27934E31188A, 0xD49503536ABCA345, 0x088E049589C432E0, 0xF943AEE7FEBF21B8, 0x6C3B8E3E336139D3, 0x364F6FFA464EE52E, 0xD60F6DCEDC314222, 0x56963B0DCA418FC0, 0x16F50EDF91E513AF, 0xEF1955914B609F93, 0x565601C0364E3228, 0xECB53939887E8175, 0xBAC7A9A18531294B, 0xB344C470397BBA52, 0x65D34954DAF3CEBD, 0xB4B81B3FA97511E2, 0xB422061193D6F6A7, 0x071582401C38434D, 0x7A13F18BBEDC4FF5, 0xBC4097B116C524D2, 0x59B97885E2F2EA28, 0x99170A5DC3115544, 0x6F423357E7C6A9F9, 0x325928EE6E6F8794, 0xD0E4366228B03343, 0x565C31F7DE89EA27, 0x30F5611484119414, 0xD873DB391292ED4F, 0x7BD94E1D8E17DEBC, 0xC7D9F16864A76E94, 0x947AE053EE56E63C, 0xC8C93882F9475F5F, 0x3A9BF55BA91F81CA, 0xD9A11FBB3D9808E4, 0x0FD22063EDC29FCA, 0xB3F256D8ACA0B0B9, 0xB03031A8B4516E84, 0x35DD37D5871448AF, 0xE9F6082B05542E4E, 0xEBFAFA33D7254B59, 0x9255ABB50D532280, 0xB9AB4CE57F2D34F3, 0x693501D628297551, 0xC62C58F97DD949BF, 0xCD454F8F19C5126A, 0xBBE83F4ECC2BDECB, 0xDC842B7E2819E230, 0xBA89142E007503B8, 0xA3BC941D0A5061CB, 0xE9F6760E32CD8021, 0x09C7E552BC76492F, 0x852F54934DA55CC9, 0x8107FCCF064FCF56, 0x098954D51FFF6580, 0x23B70EDB1955C4BF, 0xC330DE426430F69D, 0x4715ED43E8A45C0A, 0xA8D7E4DAB780A08D, 0x0572B974F03CE0BB, 0xB57D2E985E1419C7, 0xE8D9ECBE2CF3D73F, 0x2FE4B17170E59750, 0x11317BA87905E790, 0x7FBF21EC8A1F45EC, 0x1725CABFCB045B00, 0x964E915CD5E2B207, 0x3E2B8BCBF016D66D, 0xBE7444E39328A0AC, 0xF85B2B4FBCDE44B7, 0x49353FEA39BA63B1, 0x1DD01AAFCD53486A, 0x1FCA8A92FD719F85, 0xFC7C95D827357AFA, 0x18A6A990C8B35EBD, 0xCCCB7005C6B9C28D, 0x3BDBB92C43B17F26, 0xAA70B5B4F89695A2, 0xE94C39A54A98307F, 0xB7A0B174CFF6F36E, 0xD4DBA84729AF48AD, 0x2E18BC1AD9704A68, 0x2DE0966DAF2F8B1C, 0xB9C11D5B1E43A07E, 0x64972D68DEE33360, 0x94628D38D0C20584, 0xDBC0D2B6AB90A559, 0xD2733C4335C6A72F, 0x7E75D99D94A70F4D, 0x6CED1983376FA72B, 0x97FCAACBF030BC24, 0x7B77497B32503B12, 0x8547EDDFB81CCB94, 0x79999CDFF70902CB, 0xCFFE1939438E9B24, 0x829626E3892D95D7, 0x92FAE24291F2B3F1, 0x63E22C147B9C3403, 0xC678B6D860284A1C, 0x5873888850659AE7, 0x0981DCD296A8736D, 0x9F65789A6509A440, 0x9FF38FED72E9052F, 0xE479EE5B9930578C, 0xE7F28ECD2D49EECD, 0x56C074A581EA17FE, 0x5544F7D774B14AEF, 0x7B3F0195FC6F290F, 0x12153635B2C0CF57, 0x7F5126DBBA5E0CA7, 0x7A76956C3EAFB413, 0x3D5774A11D31AB39, 0x8A1B083821F40CB4, 0x7B4A38E32537DF62, 0x950113646D1D6E03, 0x4DA8979A0041E8A9, 0x3BC36E078F7515D7, 0x5D0A12F27AD310D1, 0x7F9D1A2E1EBE1327, 0xDA3A361B1C5157B1, 0xDCDD7D20903D0C25, 0x36833336D068F707, 0xCE68341F79893389, 0xAB9090168DD05F34, 0x43954B3252DC25E5, 0xB438C2B67F98E5E9, 0x10DCD78E3851A492, 0xDBC27AB5447822BF, 0x9B3CDB65F82CA382, 0xB67B7896167B4C84, 0xBFCED1B0048EAC50, 0xA9119B60369FFEBD, 0x1FFF7AC80904BF45, 0xAC12FB171817EEE7, 0xAF08DA9177DDA93D, 0x1B0CAB936E65C744, 0xB559EB1D04E5E932, 0xC37B45B3F8D6F2BA, 0xC3A9DC228CAAC9E9, 0xF3B8B6675A6507FF, 0x9FC477DE4ED681DA, 0x67378D8ECCEF96CB, 0x6DD856D94D259236, 0xA319CE15B0B4DB31, 0x073973751F12DD5E, 0x8A8E849EB32781A5, 0xE1925C71285279F5, 0x74C04BF1790C0EFE, 0x4DDA48153C94938A, 0x9D266D6A1CC0542C, 0x7440FB816508C4FE, 0x13328503DF48229F, 0xD6BF7BAEE43CAC40, 0x4838D65F6EF6748F, 0x1E152328F3318DEA, 0x8F8419A348F296BF, 0x72C8834A5957B511, 0xD7A023A73260B45C, 0x94EBC8ABCFB56DAE, 0x9FC10D0F989993E0, 0xDE68A2355B93CAE6, 0xA44CFE79AE538BBE, 0x9D1D84FCCE371425, 0x51D2B1AB2DDFB636, 0x2FD7E4B9E72CD38C, 0x65CA5B96B7552210, 0xDD69A0D8AB3B546D, 0x604D51B25FBF70E2, 0x73AA8A564FB7AC9E, 0x1A8C1E992B941148, 0xAAC40A2703D9BEA0, 0x764DBEAE7FA4F3A6, 0x1E99B96E70A9BE8B, 0x2C5E9DEB57EF4743, 0x3A938FEE32D29981, 0x26E6DB8FFDF5ADFE, 0x469356C504EC9F9D, 0xC8763C5B08D1908C, 0x3F6C6AF859D80055, 0x7F7CC39420A3A545, 0x9BFB227EBDF4C5CE, 0x89039D79D6FC5C5C, 0x8FE88B57305E2AB6, 0xA09E8C8C35AB96DE, 0xFA7E393983325753, 0xD6B6D0ECC617C699, 0xDFEA21EA9E7557E3, 0xB67C1FA481680AF8, 0xCA1E3785A9E724E5, 0x1CFC8BED0D681639, 0xD18D8549D140CAEA, 0x4ED0FE7E9DC91335, 0xE4DBF0634473F5D2, 0x1761F93A44D5AEFE, 0x53898E4C3910DA55, 0x734DE8181F6EC39A, 0x2680B122BAA28D97, 0x298AF231C85BAFAB, 0x7983EED3740847D5, 0x66C1A2A1A60CD889, 0x9E17E49642A3E4C1, 0xEDB454E7BADC0805, 0x50B704CAB602C329, 0x4CC317FB9CDDD023, 0x66B4835D9EAFEA22, 0x219B97E26FFC81BD, 0x261E4E4C0A333A9D, 0x1FE2CCA76517DB90, 0xD7504DFA8816EDBB, 0xB9571FA04DC089C8, 0x1DDC0325259B27DE, 0xCF3F4688801EB9AA, 0xF4F5D05C10CAB243, 0x38B6525C21A42B0E, 0x36F60E2BA4FA6800, 0xEB3593803173E0CE, 0x9C4CD6257C5A3603, 0xAF0C317D32ADAA8A, 0x258E5A80C7204C4B, 0x8B889D624D44885D, 0xF4D14597E660F855, 0xD4347F66EC8941C3, 0xE699ED85B0DFB40D, 0x2472F6207C2D0484, 0xC2A1E7B5B459AEB5, 0xAB4F6451CC1D45EC, 0x63767572AE3D6174, 0xA59E0BD101731A28, 0x116D0016CB948F09, 0x2CF9C8CA052F6E9F, 0x0B090A7560A968E3, 0xABEEDDB2DDE06FF1, 0x58EFC10B06A2068D, 0xC6E57A78FBD986E0, 0x2EAB8CA63CE802D7, 0x14A195640116F336, 0x7C0828DD624EC390, 0xD74BBE77E6116AC7, 0x804456AF10F5FB53, 0xEBE9EA2ADF4321C7, 0x03219A39EE587A30, 0x49787FEF17AF9924, 0xA1E9300CD8520548, 0x5B45E522E4B1B4EF, 0xB49C3B3995091A36, 0xD4490AD526F14431, 0x12A8F216AF9418C2, 0x001F837CC7350524, 0x1877B51E57A764D5, 0xA2853B80F17F58EE, 0x993E1DE72D36D310, 0xB3598080CE64A656, 0x252F59CF0D9F04BB, 0xD23C8E176D113600, 0x1BDA0492E7E4586E, 0x21E0BD5026C619BF, 0x3B097ADAF088F94E, 0x8D14DEDB30BE846E, 0xF95CFFA23AF5F6F4, 0x3871700761B3F743, 0xCA672B91E9E4FA16, 0x64C8E531BFF53B55, 0x241260ED4AD1E87D, 0x106C09B972D2E822, 0x7FBA195410E5CA30, 0x7884D9BC6CB569D8, 0x0647DFEDCD894A29, 0x63573FF03E224774, 0x4FC8E9560F91B123, 0x1DB956E450275779, 0xB8D91274B9E9D4FB, 0xA2EBEE47E2FBFCE1, 0xD9F1F30CCD97FB09, 0xEFED53D75FD64E6B, 0x2E6D02C36017F67F, 0xA9AA4D20DB084E9B, 0xB64BE8D8B25396C1, 0x70CB6AF7C2D5BCF0, 0x98F076A4F7A2322E, 0xBF84470805E69B5F, 0x94C3251F06F90CF3, 0x3E003E616A6591E9, 0xB925A6CD0421AFF3, 0x61BDD1307C66E300, 0xBF8D5108E27E0D48, 0x240AB57A8B888B20, 0xFC87614BAF287E07, 0xEF02CDD06FFDB432, 0xA1082C0466DF6C0A, 0x8215E577001332C8, 0xD39BB9C3A48DB6CF, 0x2738259634305C14, 0x61CF4F94C97DF93D, 0x1B6BACA2AE4E125B, 0x758F450C88572E0B, 0x959F587D507A8359, 0xB063E962E045F54D, 0x60E8ED72C0DFF5D1, 0x7B64978555326F9F, 0xFD080D236DA814BA, 0x8C90FD9B083F4558, 0x106F72FE81E2C590, 0x7976033A39F7D952, 0xA4EC0132764CA04B, 0x733EA705FAE4FA77, 0xB4D8F77BC3E56167, 0x9E21F4F903B33FD9, 0x9D765E419FB69F6D, 0xD30C088BA61EA5EF, 0x5D94337FBFAF7F5B, 0x1A4E4822EB4D7A59, 0x6FFE73E81B637FB3, 0xDDF957BC36D8B9CA, 0x64D0E29EEA8838B3, 0x08DD9BDFD96B9F63, 0x087E79E5A57D1D13, 0xE328E230E3E2B3FB, 0x1C2559E30F0946BE, 0x720BF5F26F4D2EAA, 0xB0774D261CC609DB, 0x443F64EC5A371195, 0x4112CF68649A260E, 0xD813F2FAB7F5C5CA, 0x660D3257380841EE, 0x59AC2C7873F910A3, 0xE846963877671A17, 0x93B633ABFA3469F8, 0xC0C0F5A60EF4CDCF, 0xCAF21ECD4377B28C, 0x57277707199B8175, 0x506C11B9D90E8B1D, 0xD83CC2687A19255F, 0x4A29C6465A314CD1, 0xED2DF21216235097, 0xB5635C95FF7296E2, 0x22AF003AB672E811, 0x52E762596BF68235, 0x9AEBA33AC6ECC6B0, 0x944F6DE09134DFB6, 0x6C47BEC883A7DE39, 0x6AD047C430A12104, 0xA5B1CFDBA0AB4067, 0x7C45D833AFF07862, 0x5092EF950A16DA0B, 0x9338E69C052B8E7B, 0x455A4B4CFE30E3F5, 0x6B02E63195AD0CF8, 0x6B17B224BAD6BF27, 0xD1E0CCD25BB9C169, 0xDE0C89A556B9AE70, 0x50065E535A213CF6, 0x9C1169FA2777B874, 0x78EDEFD694AF1EED, 0x6DC93D9526A50E68, 0xEE97F453F06791ED, 0x32AB0EDB696703D3, 0x3A6853C7E70757A7, 0x31865CED6120F37D, 0x67FEF95D92607890, 0x1F2B1D1F15F6DC9C, 0xB69E38A8965C6B65, 0xAA9119FF184CCCF4, 0xF43C732873F24C13, 0xFB4A3D794A9A80D2, 0x3550C2321FD6109C, 0x371F77E76BB8417E, 0x6BFA9AAE5EC05779, 0xCD04F3FF001A4778, 0xE3273522064480CA, 0x9F91508BFFCFC14A, 0x049A7F41061A9E60, 0xFCB6BE43A9F2FE9B, 0x08DE8A1C7797DA9B, 0x8F9887E6078735A1, 0xB5B4071DBFC73A66, 0x230E343DFBA08D33, 0x43ED7F5A0FAE657D, 0x3A88A0FBBCB05C63, 0x21874B8B4D2DBC4F, 0x1BDEA12E35F6A8C9, 0x53C065C6C8E63528, 0xE34A1D250E7A8D6B, 0xD6B04D3B7651DD7E, 0x5E90277E7CB39E2D, 0x2C046F22062DC67D, 0xB10BB459132D0A26, 0x3FA9DDFB67E2F199, 0x0E09B88E1914F7AF, 0x10E8B35AF3EEAB37, 0x9EEDECA8E272B933, 0xD4C718BC4AE8AE5F, 0x81536D601170FC20, 0x91B534F885818A06, 0xEC8177F83F900978, 0x190E714FADA5156E, 0xB592BF39B0364963, 0x89C350C893AE7DC1, 0xAC042E70F8B383F2, 0xB49B52E587A1EE60, 0xFB152FE3FF26DA89, 0x3E666E6F69AE2C15, 0x3B544EBE544C19F9, 0xE805A1E290CF2456, 0x24B33C9D7ED25117, 0xE74733427B72F0C1, 0x0A804D18B7097475, 0x57E3306D881EDB4F, 0x4AE7D6A36EB5DBCB, 0x2D8D5432157064C8, 0xD1E649DE1E7F268B, 0x8A328A1CEDFE552C, 0x07A3AEC79624C7DA, 0x84547DDC3E203C94, 0x990A98FD5071D263, 0x1A4FF12616EEFC89, 0xF6F7FD1431714200, 0x30C05B1BA332F41C, 0x8D2636B81555A786, 0x46C9FEB55D120902, 0xCCEC0A73B49C9921, 0x4E9D2827355FC492, 0x19EBB029435DCB0F, 0x4659D2B743848A2C, 0x963EF2C96B33BE31, 0x74F85198B05A2E7D, 0x5A0F544DD2B1FB18, 0x03727073C2E134B1, 0xC7F6AA2DE59AEA61, 0x352787BAA0D7C22F, 0x9853EAB63B5E0B35, 0xABBDCDD7ED5C0860, 0xCF05DAF5AC8D77B0, 0x49CAD48CEBF4A71E, 0x7A4C10EC2158C4A6, 0xD9E92AA246BF719E, 0x13AE978D09FE5557, 0x730499AF921549FF, 0x4E4B705B92903BA4, 0xFF577222C14F0A3A, 0x55B6344CF97AAFAE, 0xB862225B055B6960, 0xCAC09AFBDDD2CDB4, 0xDAF8E9829FE96B5F, 0xB5FDFC5D3132C498, 0x310CB380DB6F7503, 0xE87FBB46217A360E, 0x2102AE466EBB1148, 0xF8549E1A3AA5E00D, 0x07A69AFDCC42261A, 0xC4C118BFE78FEAAE, 0xF9F4892ED96BD438, 0x1AF3DBE25D8F45DA, 0xF5B4B0B0D2DEEEB4, 0x962ACEEFA82E1C84, 0x046E3ECAAF453CE9, 0xF05D129681949A4C, 0x964781CE734B3C84, 0x9C2ED44081CE5FBD, 0x522E23F3925E319E, 0x177E00F9FC32F791, 0x2BC60A63A6F3B3F2, 0x222BBFAE61725606, 0x486289DDCC3D6780, 0x7DC7785B8EFDFC80, 0x8AF38731C02BA980, 0x1FAB64EA29A2DDF7, 0xE4D9429322CD065A, 0x9DA058C67844F20C, 0x24C0E332B70019B0, 0x233003B5A6CFE6AD, 0xD586BD01C5C217F6, 0x5E5637885F29BC2B, 0x7EBA726D8C94094B, 0x0A56A5F0BFE39272, 0xD79476A84EE20D06, 0x9E4C1269BAA4BF37, 0x17EFEE45B0DEE640, 0x1D95B0A5FCF90BC6, 0x93CBE0B699C2585D, 0x65FA4F227A2B6D79, 0xD5F9E858292504D5, 0xC2B5A03F71471A6F, 0x59300222B4561E00, 0xCE2F8642CA0712DC, 0x7CA9723FBB2E8988, 0x2785338347F2BA08, 0xC61BB3A141E50E8C, 0x150F361DAB9DEC26, 0x9F6A419D382595F4, 0x64A53DC924FE7AC9, 0x142DE49FFF7A7C3D, 0x0C335248857FA9E7, 0x0A9C32D5EAE45305, 0xE6C42178C4BBB92E, 0x71F1CE2490D20B07, 0xF1BCC3D275AFE51A, 0xE728E8C83C334074, 0x96FBF83A12884624, 0x81A1549FD6573DA5, 0x5FA7867CAF35E149, 0x56986E2EF3ED091B, 0x917F1DD5F8886C61, 0xD20D8C88C8FFE65F, 0x31D71DCE64B2C310, 0xF165B587DF898190, 0xA57E6339DD2CF3A0, 0x1EF6E6DBB1961EC9, 0x70CC73D90BC26E24, 0xE21A6B35DF0C3AD7, 0x003A93D8B2806962, 0x1C99DED33CB890A1, 0xCF3145DE0ADD4289, 0xD0E4427A5514FB72, 0x77C621CC9FB3A483, 0x67A34DAC4356550B, 0xF8D626AAAF278509, }
non-member
package stencil import ( "fmt" "strings" "github.com/harrowio/harrow/domain" ) // CapistranoRails sets up default tasks and environments for working // with a RubyOnRails application using capistrano. type CapistranoRails struct { conf *Configuration } func NewCapistranoRails(configuration *Configuration) *CapistranoRails { return &CapistranoRails{ conf: configuration, } } // Create creates the following objects for this stencil: // // Environments: test, staging, production // // Tasks (in test): "bundle outdated", "rake notes", "rake test" // // Tasks (in staging, production): "cap $env deploy" func (self *CapistranoRails) Create() error { errors := NewError() project, err := self.conf.Projects.FindProject(self.conf.ProjectUuid) if err != nil { return errors.Add("FindProject", project, err) } testEnvironment := project.NewEnvironment("Test") if err := self.conf.Environments.CreateEnvironment(testEnvironment); err != nil { errors.Add("CreateEnvironment", testEnvironment, err) } stagingEnvironment := project.NewEnvironment("Staging"). Set("CAPISTRANO_ENV", "staging") if err := self.conf.Environments.CreateEnvironment(stagingEnvironment); err != nil { errors.Add("CreateEnvironment", stagingEnvironment, err) } productionEnvironment := project.NewEnvironment("Production"). Set("CAPISTRANO_ENV", "production") if err := self.conf.Environments.CreateEnvironment(productionEnvironment); err != nil { errors.Add("CreateEnvironment", productionEnvironment, err) } deployTask := project.NewTask("Deploy", self.DeployTaskBody()) if err := self.conf.Tasks.CreateTask(deployTask); err != nil { errors.Add("CreateTask", deployTask, err) } notesTask := project.NewTask("Notes", self.NotesTaskBody()) if err := self.conf.Tasks.CreateTask(notesTask); err != nil { errors.Add("CreateTask", notesTask, err) } checkDependenciesTask := project.NewTask("Check dependencies", self.CheckDependenciesTaskBody()) if err := self.conf.Tasks.CreateTask(checkDependenciesTask); err != nil { errors.Add("CreateTask", checkDependenciesTask, err) } runTestsTask := project.NewTask("Run tests", self.RunTestsTaskBody()) if err := self.conf.Tasks.CreateTask(runTestsTask); err != nil { errors.Add("CreateTask", runTestsTask, err) } notesJob := &domain.Job{} runTestsJob := &domain.Job{} deployToStagingJob := &domain.Job{} jobsToCreate := []struct { Task *domain.Task Environment *domain.Environment SaveAs **domain.Job }{ {runTestsTask, testEnvironment, &runTestsJob}, {notesTask, testEnvironment, &notesJob}, {checkDependenciesTask, testEnvironment, nil}, {deployTask, stagingEnvironment, &deployToStagingJob}, {deployTask, productionEnvironment, nil}, } for _, jobToCreate := range jobsToCreate { jobName := fmt.Sprintf("%s - %s", jobToCreate.Environment.Name, jobToCreate.Task.Name) job := project.NewJob(jobName, jobToCreate.Task.Uuid, jobToCreate.Environment.Uuid) if err := self.conf.Jobs.CreateJob(job); err != nil { errors.Add("CreateJob", job, err) } if jobToCreate.SaveAs != nil { *jobToCreate.SaveAs = job } } if strings.Contains(self.conf.NotifyViaEmail, "@") { emailNotifier := project.NewEmailNotifier(self.conf.NotifyViaEmail, self.conf.UrlHost) if err := self.conf.EmailNotifiers.CreateEmailNotifier(emailNotifier); err != nil { errors.Add("CreateEmailNotifier", emailNotifier, err) } notifyAboutNotes := project.NewNotificationRule( "email_notifiers", emailNotifier.Uuid, notesJob.Uuid, "operation.succeeded", ) notifyAboutNotes.CreatorUuid = self.conf.UserUuid if err := self.conf.NotificationRules.CreateNotificationRule(notifyAboutNotes); err != nil { errors.Add("CreateNotificationRule", notifyAboutNotes, err) } } runNotesWeekly := notesJob.NewRecurringSchedule(self.conf.UserUuid, "@weekly") if err := self.conf.Schedules.CreateSchedule(runNotesWeekly); err != nil { errors.Add("CreateSchedule", runNotesWeekly, err) } triggerTestsOnNewCommits := project.NewGitTrigger( "run tests", self.conf.UserUuid, runTestsJob.Uuid, ) if err := self.conf.GitTriggers.CreateGitTrigger(triggerTestsOnNewCommits); err != nil { errors.Add("CreateGitTrigger", triggerTestsOnNewCommits, err) } stagingDeployKey := stagingEnvironment.NewSecret("Deploy key", domain.SecretSsh) if err := self.conf.Secrets.CreateSecret(stagingDeployKey); err != nil { errors.Add("CreateSecret", stagingDeployKey, err) } productionDeployKey := productionEnvironment.NewSecret("Deploy key", domain.SecretSsh) if err := self.conf.Secrets.CreateSecret(productionDeployKey); err != nil { errors.Add("CreateSecret", productionDeployKey, err) } currentUser, err := self.conf.Users.FindUser(self.conf.UserUuid) if err != nil && !domain.IsNotFound(err) { errors.Add("FindUser", self.conf.UserUuid, err) } if currentUser != nil { self.setUpJobNotifierForDeployingToStaging(errors, currentUser, project, runTestsJob, deployToStagingJob) } return errors.ToError() } func (self *CapistranoRails) setUpJobNotifierForDeployingToStaging(errors *Error, currentUser *domain.User, project *domain.Project, triggeringJob *domain.Job, jobToTrigger *domain.Job) { deployToStagingAfterTestsRan := jobToTrigger.NewJobNotifier() deployToStagingAfterTestsRan.ProjectUuid = project.Uuid webhook := domain.NewWebhook( self.conf.ProjectUuid, currentUser.Uuid, jobToTrigger.Uuid, fmt.Sprintf("urn:harrow:job-notifier:%s", deployToStagingAfterTestsRan.Uuid), ) if err := self.conf.Webhooks.CreateWebhook(webhook); err != nil { errors.Add("CreateWebhook", webhook, err) return } deployToStagingAfterTestsRan.WebhookURL = webhook.Links(map[string]map[string]string{}, "https", currentUser.UrlHost+"/api")["deliver"]["href"] if err := self.conf.JobNotifiers.CreateJobNotifier(deployToStagingAfterTestsRan); err != nil { errors.Add("CreateJobNotifier", deployToStagingAfterTestsRan, err) } notificationRule := project.NewNotificationRule( "job_notifiers", deployToStagingAfterTestsRan.Uuid, triggeringJob.Uuid, "operation.succeeded", ) notificationRule.CreatorUuid = currentUser.Uuid if err := notificationRule.Validate(); err != nil { errors.Add("notificationRule.Validate", notificationRule, err) } if err := self.conf.NotificationRules.CreateNotificationRule(notificationRule); err != nil { errors.Add("CreateNotificationRule", notificationRule, err) } } // DeployTaskBody returns the body of the "deploy" task. func (self *CapistranoRails) DeployTaskBody() string { return `#!/bin/bash -e find ~/repositories -type f -name 'Capfile' -print0 | xargs -L 1 -0 -I% /bin/bash -c ' cd $(dirname $1) hfold bundling bundle install bundle exec cap $CAPISTRANO_ENV deploy ' _ % ` } // CheckDependenciesTaskBody returns the body of the "check // dependencies" task. func (self *CapistranoRails) CheckDependenciesTaskBody() string { return `#!/bin/bash -e find ~/repositories -type f -name 'Gemfile' -print0 | xargs -L 1 -0 -I% /bin/bash -c ' cd $(dirname $1) hfold bundling bundle install bundle outdated ' _ % ` } // NotesTaskBody returns the body of the task for displaying project // notes. func (self *CapistranoRails) NotesTaskBody() string { return `#!/bin/bash -e find ~/repositories -type f -name 'Rakefile' -print0 | xargs -L 1 -0 -I% /bin/bash -c ' cd $(dirname $1) hfold bundling bundle install bundle exec rake notes ' _ % ` } // RunTestsTaskBody returns the body of the task for running the // project's unit tests. func (self *CapistranoRails) RunTestsTaskBody() string { return `#!/bin/bash -e find ~/repositories -type f -name 'Rakefile' -print0 | xargs -L 1 -0 -I% /bin/bash -c ' cd $(dirname $1) hfold bundling bundle install bundle exec rake test ' _ % ` }
non-member
package parser // https://github.com/SatisfactoryModdingUE/UnrealEngine/blob/4.22-CSS/Engine/Source/Runtime/Core/Public/Misc/FrameNumber.h#L16 type FFrameNumber struct { Value int32 `json:"value"` } func (parser *PakParser) ReadFFrameNumber() *FFrameNumber { return &FFrameNumber{ Value: parser.ReadInt32(), } }
non-member
package events type ( Event struct { stopped bool } ) // StopPropagation Stops the propagation of the event to further event listeners func (e *Event) StopPropagation() { e.stopped = true } // IsPropagationStopped returns whether further event listeners should be triggered func (e *Event) IsPropagationStopped() bool { return e.stopped }
non-member
package mysqlutil import ( "database/sql/driver" "fmt" "log" "net/url" "strings" "github.com/leizongmin/go/sqlutil" ) type ConnectionOptions struct { Host string Port int User string Password string Database string Charset string Timezone string // +8:00 ParseTime bool AutoCommit bool Params map[string]string } func (opts ConnectionOptions) BuildDataSourceString() string { if opts.Host == "" { opts.Host = "127.0.0.1" } if opts.Port == 0 { opts.Port = 3306 } if opts.User == "" { opts.User = "root" } str := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?", opts.User, opts.Password, opts.Host, opts.Port, opts.Database, ) appendQueryString := func(s string) { if str[len(str)-1:] == "?" { str += s } else { str += "&" + s } } if opts.ParseTime { appendQueryString("parseTime=true&loc=Local") } if opts.Charset != "" { appendQueryString("charset=" + opts.Charset) } if opts.Timezone != "" { appendQueryString("time_zone=" + url.QueryEscape("'"+opts.Timezone+"'")) } if opts.AutoCommit { appendQueryString("autocommit=true") } for k, v := range opts.Params { appendQueryString(k + "=" + url.QueryEscape(v)) } return str } func Table(tableName string) *sqlutil.QueryBuilder { return sqlutil.NewEmptyQuery().Init(quoteIdentifier, quoteLiteral).Table(tableName) } func Custom(query string, args ...driver.Value) string { if len(args) < 1 { return strings.Trim(query, " ") } ret, err := sqlutil.InterpolateParams(query, args, sqlutil.GetDefaultLocation(), quoteLiteral) if err != nil { log.Println(err) return query } return strings.Trim(ret, " ") } func quoteLiteral(buf []byte, v string) []byte { buf = append(buf, '\'') buf = escapeStringQuotes(buf, v) buf = append(buf, '\'') return buf } func quoteIdentifier(id string) string { return "`" + strings.Replace(strings.Replace(id, "`", "``", -1), ".", "`.`", -1) + "`" }
non-member
package types import ( "regexp" "whapp-irc/ircconnection" "whapp-irc/whapp" ) const messageIDListSize = 750 var ( numberRegex = regexp.MustCompile(`^\+[\d ]+$`) nonNumberRegex = regexp.MustCompile(`[^\d]`) ) // A Participant is an user on WhatsApp. type Participant whapp.Participant // FullName returns the full/formatted name for the current Participant. func (p *Participant) FullName() string { return p.Contact.FormattedName } // SafeName returns the irc-safe name for the current Participant. func (p *Participant) SafeName() string { str := p.FullName() if numberRegex.MatchString(str) { if res := ircconnection.SafeString(p.Contact.PushName); res != "" { return res } } return ircconnection.SafeString(str) } // Chat represents a chat on the bridge. // It can be private or public, and is always accompanied by a WhatsApp chat. type Chat struct { ID whapp.ID Name string IsGroupChat bool Participants []Participant Joined bool MessageIDs []string RawChat whapp.Chat } // SafeName returns the IRC-safe name for the current chat. func (c *Chat) SafeName() string { return ircconnection.SafeString(c.Name) } // Identifier returns the safe IRC identifier for the current chat. func (c *Chat) Identifier() string { prefix := "" if c.IsGroupChat { prefix = "#" } name := c.SafeName() if !c.IsGroupChat && len(name) > 0 && name[0] == '+' { name = name[1:] } return prefix + name } // AddMessageID adds the given id to the chat, so that it's known as // received/sent. func (c *Chat) AddMessageID(id string) { if len(c.MessageIDs) >= messageIDListSize { c.MessageIDs = c.MessageIDs[1:] } c.MessageIDs = append(c.MessageIDs, id) } // HasMessageID returns whether or not a message with the given id has been // received/sent in the current chat. func (c *Chat) HasMessageID(id string) bool { for _, x := range c.MessageIDs { if x == id { return true } } return false } // User represents the on-disk format of an user of the bridge. type User struct { Password string `json:"password"` LocalStorage map[string]string `json:"localStorage"` LastReceivedReceipts map[string]int64 `json:"lastReceivedReceipts"` Chats []ChatListItem `json:"chats"` }
non-member
package subsonic import ( "errors" "net/http" "time" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/server/subsonic/responses" "github.com/navidrome/navidrome/utils/req" "github.com/navidrome/navidrome/utils/slice" ) func (api *Router) GetBookmarks(r *http.Request) (*responses.Subsonic, error) { user, _ := request.UserFrom(r.Context()) repo := api.ds.MediaFile(r.Context()) bookmarks, err := repo.GetBookmarks() if err != nil { return nil, err } response := newResponse() response.Bookmarks = &responses.Bookmarks{} response.Bookmarks.Bookmark = slice.Map(bookmarks, func(bmk model.Bookmark) responses.Bookmark { return responses.Bookmark{ Entry: childFromMediaFile(r.Context(), bmk.Item), Position: bmk.Position, Username: user.UserName, Comment: bmk.Comment, Created: bmk.CreatedAt, Changed: bmk.UpdatedAt, } }) return response, nil } func (api *Router) CreateBookmark(r *http.Request) (*responses.Subsonic, error) { p := req.Params(r) id, err := p.String("id") if err != nil { return nil, err } comment, _ := p.String("comment") position := p.Int64Or("position", 0) repo := api.ds.MediaFile(r.Context()) err = repo.AddBookmark(id, comment, position) if err != nil { return nil, err } return newResponse(), nil } func (api *Router) DeleteBookmark(r *http.Request) (*responses.Subsonic, error) { p := req.Params(r) id, err := p.String("id") if err != nil { return nil, err } repo := api.ds.MediaFile(r.Context()) err = repo.DeleteBookmark(id) if err != nil { return nil, err } return newResponse(), nil } func (api *Router) GetPlayQueue(r *http.Request) (*responses.Subsonic, error) { user, _ := request.UserFrom(r.Context()) repo := api.ds.PlayQueue(r.Context()) pq, err := repo.Retrieve(user.ID) if err != nil && !errors.Is(err, model.ErrNotFound) { return nil, err } if pq == nil || len(pq.Items) == 0 { return newResponse(), nil } response := newResponse() response.PlayQueue = &responses.PlayQueue{ Entry: slice.MapWithArg(pq.Items, r.Context(), childFromMediaFile), Current: pq.Current, Position: pq.Position, Username: user.UserName, Changed: &pq.UpdatedAt, ChangedBy: pq.ChangedBy, } return response, nil } func (api *Router) SavePlayQueue(r *http.Request) (*responses.Subsonic, error) { p := req.Params(r) ids, _ := p.Strings("id") current, _ := p.String("current") position := p.Int64Or("position", 0) user, _ := request.UserFrom(r.Context()) client, _ := request.ClientFrom(r.Context()) var items model.MediaFiles for _, id := range ids { items = append(items, model.MediaFile{ID: id}) } pq := &model.PlayQueue{ UserID: user.ID, Current: current, Position: position, ChangedBy: client, Items: items, CreatedAt: time.Time{}, UpdatedAt: time.Time{}, } repo := api.ds.PlayQueue(r.Context()) err := repo.Store(pq) if err != nil { return nil, err } return newResponse(), nil }
non-member
package iterables import ( "container/heap" "fmt" ) func (i Iterable[T]) Sort(cmp func(T, T) int) Iterable[T] { gen := sort[T]{tHeap[T]{cmpFunc: cmp}} for true { item, err := i.Next() if (err == IterationStop{}) { break } else if err != nil { invalid := invalidIterable[T]{InvalidSort{err}} return Iterable[T]{&invalid} } heap.Push(&gen.sorter, item) } return Iterable[T]{&gen} } type sort[T any] struct { sorter tHeap[T] } func (s *sort[T]) Next() (T, error) { if s.sorter.Len() <= 0 { return *new(T), IterationStop{} } popped := heap.Pop(&s.sorter).(T) return popped, nil } type tHeap[T any] struct { cmpFunc func(T, T) int data []T } func (h *tHeap[T]) Push(x any) { item := x.(T) h.data = append(h.data, item) } func (h *tHeap[T]) Pop() any { lastIndex := len(h.data) - 1 result := h.data[lastIndex] h.data = h.data[:lastIndex] return result } func (h *tHeap[T]) Len() int { return len(h.data) } func (h *tHeap[T]) Less(i int, j int) bool { itemI := h.data[i] itemJ := h.data[j] return h.cmpFunc(itemI, itemJ) < 0 } func (h *tHeap[T]) Swap(i int, j int) { save := h.data[i] h.data[i] = h.data[j] h.data[j] = save } type InvalidSort struct { Cause error } func (i InvalidSort) Error() string { return fmt.Sprintf( "invalid sort because underlying iterable failed: %v", i.Cause) }
non-member
package main import "fmt" func filter(in, out chan int) { go func() { for n := range in { if n%2 == 0 { out <- n } } close(out) }() } func main() { done := make(chan struct{}) ch := gen(done) f := make(chan int) filter(ch, f) quadratChannel := sq(f) fmt.Println(<-quadratChannel) fmt.Println(<-quadratChannel) fmt.Println(<-quadratChannel) close(done) } func sq(in <-chan int) <-chan int { out := make(chan int) go func() { for n := range in { out <- n * n } close(out) }() return out } func gen(done chan struct{}) chan int { ch := make(chan int) go func() { i := 0 for { select { case ch <- i: i++ case <-done: close(ch) return } } }() return ch }
non-member
package k8sutil import ( "context" "time" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" ) // UpdatePodCondition updates the given condition type of the given pod with the new status and reason func UpdatePodCondition(pod *corev1.Pod, condType corev1.PodConditionType, condStatus corev1.ConditionStatus, reason string, kubeclient client.Client) error { now := metav1.NewTime(time.Now()) found := false for i, condition := range pod.Status.Conditions { if condition.Type == condType { found = true condition.LastProbeTime = now if condition.Status != condStatus { condition.Status = condStatus condition.LastTransitionTime = now } pod.Status.Conditions[i] = condition break } } if !found { pod.Status.Conditions = append(pod.Status.Conditions, corev1.PodCondition{ Type: condType, Status: condStatus, Reason: reason, LastProbeTime: now, LastTransitionTime: now, }) } return kubeclient.Status().Update(context.TODO(), pod) } // UpdatePodConditionWithBool updates the given condition type of the given pod with the new status and reason. // It accepts bool conditional status and internally calls UpdatePodCondition with correct status value func UpdatePodConditionWithBool(pod *corev1.Pod, condType corev1.PodConditionType, condStatus *bool, reason string, kubeclient client.Client) error { actualStatus := corev1.ConditionUnknown if condStatus != nil { if *condStatus { actualStatus = corev1.ConditionTrue } else { actualStatus = corev1.ConditionFalse } } return UpdatePodCondition(pod, condType, actualStatus, reason, kubeclient) }
non-member
// Pictures fetcher package pictures import ( "fmt" "io/ioutil" "log" "math/rand" "github.com/PeterCxy/gotelegram" "github.com/PeterCxy/gotgbot/support/types" ) type Pictures struct { tg *telegram.Telegram pic string debug bool } func Setup(t *telegram.Telegram, config map[string]interface{}, modules map[string]bool, cmds *types.CommandMap) types.Command { if val, ok := modules["pictures"]; !ok || val { pictures := &Pictures{tg: t, pic: config["gallery"].(string)} if debug, ok := config["debug"]; ok { pictures.debug = debug.(bool) } // Meizhi (gank.io girls) (*cmds)["meizhi"] = types.Command{ Name: "meizhi", ArgNum: 0, Desc: "Random picture of girls from gank.io", Processor: pictures, } // Local collection (*cmds)["pic"] = types.Command{ Name: "pic", ArgNum: 0, Desc: "Fetch a picture randomly from Peter's personal collection (WARNING: Might be NSFW)", Processor: pictures, } } return types.Command{} } func (this *Pictures) Command(name string, msg telegram.TObject, args []string) { switch name { case "meizhi": this.Meizhi(msg) case "pic": this.Pic(msg) } } func (this *Pictures) Default(name string, msg telegram.TObject, state *map[string]interface{}) { } func (this *Pictures) Pic(msg telegram.TObject) { this.tg.SendChatAction("upload_photo", msg.ChatId()) files, _ := ioutil.ReadDir(this.pic) f := files[rand.Intn(len(files))] name := fmt.Sprintf("%s/%s", this.pic, f.Name()) if this.debug { log.Println(name) } this.tg.SendPhoto(name, msg.ChatId()) }
non-member
package telegram import ( "main/pkg/constants" tele "gopkg.in/telebot.v3" ) func (reporter *Reporter) GetHelpCommand() Command { return Command{ Name: "help", Query: constants.ReporterQueryHelp, Execute: reporter.HandleHelp, } } func (reporter *Reporter) HandleHelp(c tele.Context) (string, error) { return reporter.Render("Help", reporter.Version) }
non-member
package jsonrpc import ( "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/yellomoon/web3tool" "github.com/yellomoon/web3tool/testutil" ) func TestSubscribeNewHead(t *testing.T) { testutil.MultiAddr(t, func(s *testutil.TestServer, addr string) { if strings.HasPrefix(addr, "http") { return } c, _ := NewClient(addr) defer c.Close() data := make(chan []byte) cancel, err := c.Subscribe("newHeads", func(b []byte) { data <- b }) if err != nil { t.Fatal(err) } var lastBlock *web3tool.Block recv := func(ok bool) { select { case buf := <-data: if !ok { t.Fatal("unexpected value") } var block web3tool.Block if err := block.UnmarshalJSON(buf); err != nil { t.Fatal(err) } if lastBlock != nil { if lastBlock.Number+1 != block.Number { t.Fatalf("bad sequence %d %d", lastBlock.Number, block.Number) } } lastBlock = &block case <-time.After(1 * time.Second): if ok { t.Fatal("timeout for new head") } } } s.ProcessBlock() recv(true) s.ProcessBlock() recv(true) assert.NoError(t, cancel()) s.ProcessBlock() recv(false) // subscription already closed assert.Error(t, cancel()) }) }
non-member
package admin_controller import ( "net/http" "github.com/gin-gonic/gin" "github.com/y-transport-server/pkg/app" "github.com/y-transport-server/pkg/e" "github.com/y-transport-server/service/admin_service" ) type login struct { User string `json:"user" valid:"Required; MaxSize(20);"` // 用户名 也是登录账号 Password string `json:"password" valid:"Required; MaxSize(20);MinSize(6);"` // 密码被加密过的 } //AdminCheck 后台的身份验证 func AdminCheck(c *gin.Context) { appG := app.Gin{C: c} appG.Response(http.StatusOK, e.SUCCESS, nil) } //Login 后台登录 func Login(c *gin.Context) { var ( appG = app.Gin{C: c} form login ) httpCode, errCode := app.BindAndValid(c, &form) if errCode != e.SUCCESS { appG.Response(httpCode, errCode, nil) return } adminService := admin_service.Admin{User: form.User, Password: form.Password} token, err := adminService.Login() if err != nil { appG.Response(http.StatusOK, e.ERROR_ADMIN_USER, err) } else { c.SetCookie("token", token, 86400, "/", "", false, false) appG.Response(http.StatusOK, e.SUCCESS, nil) } } //Logout 退出登录 func Logout(c *gin.Context) { appG := app.Gin{C: c} c.SetCookie("token", "token", -1, "/", "", false, false) appG.Response(http.StatusOK, e.SUCCESS, nil) }
member
package users import ( "Office-Booking/app/config" mid "Office-Booking/delivery/http/middleware" domain "Office-Booking/domain/users" "Office-Booking/domain/users/request" "Office-Booking/domain/users/response" "net/http" "strconv" "github.com/labstack/echo/v4" ) type UserController struct { UserUsecase domain.UserUsecase } func NewUserController(e *echo.Echo, Usecase domain.UserUsecase) { UserController := &UserController{ UserUsecase: Usecase, } authMiddleware := mid.NewGoMiddleware().AuthMiddleware() // Auth e.POST("/login", UserController.Login) e.POST("/Login", UserController.Login) e.POST("/register", UserController.RegisterUser) e.POST("/Register", UserController.RegisterUser) // customer e.POST("/customer", UserController.CreateUser) e.GET("/customer/profile/:id", UserController.GetUserByID, authMiddleware) e.PUT("/customer/profile/:id", UserController.UpdateUsers) // admin e.POST("/admin/booking/user", UserController.CreateBooking) e.GET("/admin/users", UserController.GetUsers) e.GET("/admin/user/:id", UserController.GetUserByID) e.DELETE("/admin/User/:id", UserController.DeleteUsers) e.DELETE("/admin/user/:id", UserController.DeleteUsers) e.PUT("/admin/user/:id", UserController.UpdateUsers) e.PUT("/admin/profile/:id", UserController.UpdatesAdmin) } func (u *UserController) Login(c echo.Context) error { var req request.LoginRequest if err := c.Bind(&req); err != nil { return c.JSON(http.StatusBadRequest, err.Error()) } res, err := u.UserUsecase.Login(req) if err != nil { return c.JSON(http.StatusUnauthorized, map[string]interface{}{ "code": 401, "status": false, "message": err.Error(), }) } return c.JSON(http.StatusOK, map[string]interface{}{ "code": 200, "status": true, "id_user": res.ID, "email": res.Email, "token": res.Token, }) } func (u *UserController) RegisterUser(c echo.Context) error { var req request.RegisterRequest if err := c.Bind(&req); err != nil { return c.JSON(http.StatusBadRequest, err.Error()) } res, err := u.UserUsecase.RegisterUser(req) if err != nil { return c.JSON(http.StatusUnauthorized, map[string]interface{}{ "code": 401, "status": false, "message": err.Error(), }) } return c.JSON(http.StatusOK, map[string]interface{}{ "code": 200, "status": true, "id_user": res.ID, "email": res.Email, "name": res.Name, "fullname": res.Fullname, "alamat": res.Alamat, "phone": res.Phone, }) } func (u *UserController) CreateBooking(c echo.Context) error { var req request.UserBookingReq if err := c.Bind(&req); err != nil { return c.JSON(http.StatusBadRequest, err.Error()) } res, err := u.UserUsecase.CreateBooking(req) if err != nil { return c.JSON(http.StatusUnauthorized, map[string]interface{}{ "code": 401, "status": false, "message": err.Error(), }) } return c.JSON(http.StatusOK, map[string]interface{}{ "code": 200, "status": true, "ID": res.ID, "Name": res.Name, "Description": res.Email, "IDBooking": res.IDBooking, }) } func (u *UserController) CreateUser(c echo.Context) error { var req request.UserCreateRequest if err := c.Bind(&req); err != nil { return c.JSON(http.StatusBadRequest, err.Error()) } createdUser, err := u.UserUsecase.Create(req) if err != nil { return c.JSON(http.StatusBadRequest, map[string]interface{}{ "code": 400, "status": false, "message": err.Error(), }) } res := response.UserCreateResponse{ ID: int(createdUser.ID), Email: createdUser.Email, } return c.JSON(http.StatusCreated, map[string]interface{}{ "code": 201, "status": true, "data": res, }) } func (u *UserController) GetUserByID(c echo.Context) error { id, err := strconv.Atoi((c.Param("id"))) if err != nil { return c.JSON(http.StatusBadRequest, err.Error()) } foundUser, err := u.UserUsecase.ReadByID(id) if err != nil { return c.JSON(http.StatusNotFound, map[string]interface{}{ "code": 404, "status": false, "message": err.Error(), }) } res := response.UserResponse{ ID: int(foundUser.ID), Email: foundUser.Email, Password: foundUser.Password, Name: foundUser.Name, Fullname: foundUser.Fullname, Alamat: foundUser.Alamat, Phone: foundUser.Phone, CreatedAt: foundUser.CreatedAt, } return c.JSON(http.StatusOK, map[string]interface{}{ "code": 200, "status": true, "data": res, }) } func (u *UserController) GetUserByName(c echo.Context) error { name := c.Param("name") foundUser, err := u.UserUsecase.ReadByName(name) if err != nil { return c.JSON(http.StatusNotFound, map[string]interface{}{ "code": 404, "status": false, "message": err.Error(), }) } res := response.UserResponse{ ID: foundUser.ID, Name: foundUser.Name, Fullname: foundUser.Fullname, Email: foundUser.Email, Alamat: foundUser.Alamat, Phone: foundUser.Phone, Password: foundUser.Password, } return c.JSON(http.StatusOK, map[string]interface{}{ "code": 200, "status": true, "data": res, }) } func (u *UserController) GetUsers(c echo.Context) error { foundUsers, err := u.UserUsecase.ReadAll() if err != nil { return c.JSON(http.StatusBadRequest, err.Error()) } var res []response.UsersResponse for _, foundUser := range *foundUsers { res = append(res, response.UsersResponse{ ID: int(foundUser.ID), Email: foundUser.Email, Name: foundUser.Name, Fullname: foundUser.Fullname, Alamat: foundUser.Alamat, Phone: foundUser.Phone, CreatedAt: foundUser.CreatedAt, }) } return c.JSON(http.StatusOK, map[string]interface{}{ "code": 200, "status": true, "data": res, }) } func (u *UserController) DeleteUsers(c echo.Context) error { id, err := strconv.Atoi(c.Param("id")) if err != nil { return c.JSON(http.StatusBadRequest, err.Error()) } _, e := u.UserUsecase.Delete(id) if e != nil { return c.JSON(http.StatusNotFound, map[string]interface{}{ "messages": "not found", "code": 404, }) } config.DB.Unscoped().Delete(&domain.User{}, id) return c.JSON(http.StatusOK, map[string]interface{}{ "messages": "success delete user with id " + strconv.Itoa(id), "code": 200, }) } func (u *UserController) UpdateUsers(c echo.Context) error { id, err := strconv.Atoi(c.Param("id")) if err != nil { return c.JSON(http.StatusBadRequest, err.Error()) } updateUser := domain.User{} err = c.Bind(&updateUser) if err != nil { return err } if err := config.DB.Model(&domain.User{}).Where("id = ?", id).Updates(domain.User{ Name: updateUser.Name, Fullname: updateUser.Fullname, Email: updateUser.Email, Password: updateUser.Password, Alamat: updateUser.Alamat, Phone: updateUser.Phone, IDBooking: updateUser.IDBooking, }).Error; err != nil { return c.JSON(http.StatusBadRequest, map[string]interface{}{ "messages": err.Error(), "code": 400, }) } foundUser, _ := u.UserUsecase.ReadByID(id) return c.JSON(http.StatusOK, map[string]interface{}{ "messages": "success update user with id " + strconv.Itoa(id), "code": 200, "data": foundUser, }) } func (u *UserController) UpdatesAdmin(c echo.Context) error { id, err := strconv.Atoi(c.Param("id")) if err != nil { return c.JSON(http.StatusBadRequest, err.Error()) } updateUser := domain.User{} err = c.Bind(&updateUser) if err != nil { return err } if err := config.DB.Model(&domain.User{}).Where("id = ?", id).Updates(domain.User{ Password: updateUser.Password, NewPassword: updateUser.NewPassword, ConfirmPassword: updateUser.ConfirmPassword, }).Error; err != nil { return c.JSON(http.StatusBadRequest, map[string]interface{}{ "messages": err.Error(), "code": 400, }) } foundUser, _ := u.UserUsecase.ReadByID(id) return c.JSON(http.StatusOK, map[string]interface{}{ "messages": "success update user with id " + strconv.Itoa(id), "code": 200, "data": foundUser, }) }
non-member
package dtclient import ( "encoding/json" "github.com/pkg/errors" ) type ConnectionInfo struct { TenantUUID string TenantToken string Endpoints string } type ActiveGateConnectionInfo struct { ConnectionInfo } type OneAgentConnectionInfo struct { ConnectionInfo CommunicationHosts []CommunicationHost } // CommunicationHost => struct of connection endpoint type CommunicationHost struct { Protocol string // nolint:unused Host string // nolint:unused Port uint32 // nolint:unused } func (dtc *dynatraceClient) GetActiveGateConnectionInfo() (*ActiveGateConnectionInfo, error) { response, err := dtc.makeRequest( dtc.getActiveGateConnectionInfoUrl(), dynatracePaaSToken, ) if err != nil { return nil, errors.WithStack(err) } defer CloseBodyAfterRequest(response) data, err := dtc.getServerResponseData(response) if err != nil { return nil, dtc.handleErrorResponseFromAPI(data, response.StatusCode) } tenantInfo, err := dtc.readResponseForActiveGateTenantInfo(data) if err != nil { return nil, err } if len(tenantInfo.Endpoints) == 0 { log.Info("tenant has no endpoints") } return tenantInfo, nil } type activeGateConnectionInfoJsonResponse struct { TenantUUID string `json:"tenantUUID"` TenantToken string `json:"tenantToken"` CommunicationEndpoints string `json:"communicationEndpoints"` } func (dtc *dynatraceClient) readResponseForActiveGateTenantInfo(response []byte) (*ActiveGateConnectionInfo, error) { resp := activeGateConnectionInfoJsonResponse{} err := json.Unmarshal(response, &resp) if err != nil { log.Error(err, "error unmarshalling activegate tenant info", "response", string(response)) return nil, err } agTenantInfo := &ActiveGateConnectionInfo{ ConnectionInfo: ConnectionInfo{ TenantUUID: resp.TenantUUID, TenantToken: resp.TenantToken, Endpoints: resp.CommunicationEndpoints, }, } return agTenantInfo, nil } func (dtc *dynatraceClient) GetOneAgentConnectionInfo() (OneAgentConnectionInfo, error) { resp, err := dtc.makeRequest(dtc.getOneAgentConnectionInfoUrl(), dynatracePaaSToken) if err != nil { return OneAgentConnectionInfo{}, err } defer CloseBodyAfterRequest(resp) responseData, err := dtc.getServerResponseData(resp) if err != nil { return OneAgentConnectionInfo{}, err } return dtc.readResponseForOneAgentConnectionInfo(responseData) } func (dtc *dynatraceClient) readResponseForOneAgentConnectionInfo(response []byte) (OneAgentConnectionInfo, error) { type jsonResponse struct { TenantUUID string `json:"tenantUUID"` TenantToken string `json:"tenantToken"` CommunicationEndpoints []string `json:"communicationEndpoints"` FormattedCommunicationEndpoints string `json:"formattedCommunicationEndpoints"` } resp := jsonResponse{} err := json.Unmarshal(response, &resp) if err != nil { log.Error(err, "error unmarshalling connection info response", "response", string(response)) return OneAgentConnectionInfo{}, err } tenantUUID := resp.TenantUUID tenantToken := resp.TenantToken communicationHosts := make([]CommunicationHost, 0, len(resp.CommunicationEndpoints)) formattedCommunicationEndpoints := resp.FormattedCommunicationEndpoints for _, s := range resp.CommunicationEndpoints { e, err := ParseEndpoint(s) if err != nil { log.Info("failed to parse communication endpoint", "url", s) continue } communicationHosts = append(communicationHosts, e) } if len(communicationHosts) == 0 { return OneAgentConnectionInfo{}, errors.New("no communication hosts available") } ci := OneAgentConnectionInfo{ CommunicationHosts: communicationHosts, ConnectionInfo: ConnectionInfo{ TenantUUID: tenantUUID, TenantToken: tenantToken, Endpoints: formattedCommunicationEndpoints, }, } return ci, nil }
member
package aomx import ( "net/url" ) // MustUrl enables parsing and dereferencing a URL in one line. // It returns a panic if err is not nil. // Call it for example when you want to dereference the pointer to a parsed URL // and assign the value to a variable in one line of code. // This can be useful when initializing structs for example. // var urlPtr *url.Url // var urlVal url.Url // // Assigning to a pointer is possible in one line // urlPtr, _ = url.Parse(urlString) // // But two lines are needed for the value // tempPtr, _ := url.Parse(urlString) // urlVal = *tempPtr // // // With this method though: // urlVal = *aomx.MustUrl(url.Parse(urlString)) func MustUrl(url *url.URL, err error) *url.URL { if err != nil { panic(err) } return url }
non-member
package main import "testing" var TestCases = []struct { Str string WordExpected string SentenceExpected string }{ {"a", "a", "a"}, {"word", "drow", "word"}, {"word1 word2", "2drow 1drow", "word2 word1"}, {"sentence, with. punctuation;", ";noitautcnup .htiw ,ecnetnes", "punctuation; with. sentence,"}, } func TestReverseString(t *testing.T) { for _, v := range TestCases { t.Run(v.Str, func(t *testing.T) { get := ReverseString(v.Str) if get != v.WordExpected { t.Errorf("Expected: %v, got: %v", v.WordExpected, get) } }) } } func TestReverseSentence(t *testing.T) { for _, v := range TestCases { t.Run(v.Str, func(t *testing.T) { get := ReverseSentence(v.Str, ReverseString) if get != v.SentenceExpected { t.Errorf("Expected: %v, got: %v", v.SentenceExpected, get) } }) } }
non-member
package db import ( "database/sql" "errors" "github.com/google/uuid" "strconv" "tide/common" "tide/pkg/custype" ) type Item struct { StationId uuid.UUID `json:"station_id" binding:"required"` Name string `json:"name" binding:"max=20"` Type string `json:"type"` DeviceName string `json:"device_name"` Status common.Status `json:"status"` StatusChangedAt custype.TimeMillisecond `json:"status_changed_at"` Available bool `json:"available"` } func GetItems(stationId uuid.UUID) ([]Item, error) { var ( rows *sql.Rows err error ) if stationId == uuid.Nil { rows, err = TideDB.Query(`select station_id, name, type ,device_name, status, status_changed_at, available!='' from items`) } else { rows, err = TideDB.Query(`select station_id, name, type ,device_name, status, status_changed_at, available!='' from items where station_id=$1`, stationId) } if err != nil { return nil, err } var ( i Item items []Item ) for rows.Next() { err = rows.Scan(&i.StationId, &i.Name, &i.Type, &i.DeviceName, &i.Status, &i.StatusChangedAt, &i.Available) if err != nil { return nil, err } items = append(items, i) } if err = rows.Err(); err != nil { return nil, err } return items, err } func MakeSureTableExist(name string) (err error) { if common.ContainsIllegalCharacter(name) { return errors.New("Table name contains illegal characters: " + name) } var n int err = TideDB.QueryRow("select count(to_regclass($1))", name).Scan(&n) if err != nil { return err } if n == 0 { _, err = TideDB.Exec(`create table ` + name + ` ( station_id uuid not null, value double precision not null, timestamp timestamptz not null ); create unique index on ` + name + ` (station_id, timestamp);`) return err } return nil } func EditItem(i Item) (err error) { if err = MakeSureTableExist(i.Name); err != nil { return err } tx, err := TideDB.Begin() if err != nil { return err } defer func() { _ = tx.Rollback() }() _, err = tx.Exec(`with latestStatus as ((select status, changed_at from item_status_log where station_id = $1 and item_name = $2 order by row_id desc limit 1) union (select '', 'epoch'::timestamptz) order by changed_at desc limit 1) insert into items(station_id, name, type, device_name, available, status, status_changed_at) values ($1,$2,$3,$4,hstore('0', NULL),(select latestStatus.status from latestStatus), (select latestStatus.changed_at from latestStatus)) on conflict (station_id,name) do update set type = excluded.type, device_name = excluded.device_name`, i.StationId, i.Name, i.Type, i.DeviceName) if err != nil { return err } return tx.Commit() } func SyncItem(i Item) (int64, error) { res, err := TideDB.Exec(`with latestStatus as ((select status, changed_at from item_status_log where station_id = $1 and item_name = $2 order by row_id desc limit 1) union (select '', 'epoch'::timestamptz) order by changed_at desc limit 1) insert into items(station_id, name, type, device_name, status, status_changed_at) values ($1,$2,$3,$4,(select latestStatus.status from latestStatus), (select latestStatus.changed_at from latestStatus)) on conflict (station_id,name) do update set type = excluded.type, device_name = excluded.device_name where items.type != $3 or items.device_name != $4`, i.StationId, i.Name, i.Type, i.DeviceName) return checkResult(res, err) } func DelItem(stationId uuid.UUID, name string) (int64, error) { res, err := TideDB.Exec(`delete from items where station_id=$1 and name=$2`, stationId, name) return checkResult(res, err) } func GetAvailableItems() ([]common.StationItemStruct, error) { rows, err := TideDB.Query(`select station_id, name from items where available != ''`) if err != nil { return nil, err } ss, err := scanStationItem(rows) if err != nil { return nil, err } return ss, err } func scanStationItem(rows *sql.Rows) ([]common.StationItemStruct, error) { var ( err error s common.StationItemStruct ss []common.StationItemStruct ) for rows.Next() { err = rows.Scan(&s.StationId, &s.ItemName) if err != nil { return ss, err } ss = append(ss, s) } return ss, rows.Err() } func UpdateAvailableItems(upstreamId int, newAvail common.UUIDStringsMap) (int64, error) { var n int64 var err error tx, err := TideDB.Begin() if err != nil { return n, err } defer func() { _ = tx.Rollback() }() rows, err := tx.Query(`select station_id, name from items where available ? $1 and station_id in (select station_id from upstream_stations where upstream_id=$2)`, strconv.Itoa(upstreamId), upstreamId) if err != nil { return n, err } var ( s common.StationItemStruct old = make(map[common.StationItemStruct]struct{}) ) for rows.Next() { err = rows.Scan(&s.StationId, &s.ItemName) if err != nil { return n, err } old[s] = struct{}{} } if err = rows.Err(); err != nil { return n, err } for stationId, items := range newAvail { for _, itemName := range items { key := common.StationItemStruct{StationId: stationId, ItemName: itemName} if _, ok := old[key]; ok { delete(old, key) } else { if err = addAvailableTx(tx, stationId, itemName, upstreamId); err != nil { return n, err } n++ } } } for s := range old { if err = removeAvailableTx(tx, s.StationId, s.ItemName, upstreamId); err != nil { return n, err } n++ } return n, tx.Commit() } func addAvailableTx(tx *sql.Tx, stationId uuid.UUID, itemName string, upstreamId int) error { _, err := tx.Exec(`update items set available = items.available||hstore($3, NULL) where station_id=$1 and name=$2`, stationId, itemName, strconv.Itoa(upstreamId)) return err } func removeAvailableTx(tx *sql.Tx, stationId uuid.UUID, itemName string, upstreamId int) error { _, err := tx.Exec(`update items set available = delete(available,$3) where station_id=$1 and name=$2`, stationId, itemName, strconv.Itoa(upstreamId)) return err } func RemoveAvailableByUpstreamId(upstreamId int) error { tx, err := TideDB.Begin() if err != nil { return err } defer func() { _ = tx.Rollback() }() _, err = tx.Exec(`update items set available = delete(available,$1::text) where station_id in (select station_id from upstream_stations where upstream_id=$1)`, upstreamId) if err != nil { return err } return tx.Commit() } //func AddAvailable(upstreamId int, stationId uuid.UUID, itemName string) error { // tx, err := TideDB.Begin() // if err != nil { // return err // } // defer func() { // _ = tx.Rollback() // }() // _, err = tx.Exec(`insert into items(station_id,name,available) values ($1, $2, hstore($3, NULL)) //on conflict(station_id,name) do update set available = items.available||hstore($3, NULL)`, // stationId, itemName, strconv.Itoa(upstreamId)) // if err != nil { // return err // } // return tx.Commit() //}
non-member
package verification type Type int const ( Registration Type = 0 Recovery Type = 1 )
non-member
package database import ( "testing" "os" "flag" "database/sql" ) var databaseFlag = flag.Bool("database", false, "run database integration tests") var messageQueue = flag.Bool("messageQueue", false, "run message queue integration tests") var integration = flag.Bool("integration", false, "run all integration tests") var db *sql.DB func TestMain(m *testing.M) { flag.Parse() if *databaseFlag || *integration { setupDatabase() } if *messageQueue || *integration { setupDatabase() } //if !testing.Short() { //} result := m.Run() //if *databaseFlag || *integration { // teardownDatabase() //} // //if *messageQueue || *integration { // teardownDatabase() //} //if !testing.Short() { // teardownDatabase() //} os.Exit(result) } func TestDatabaseGet(t *testing.T) { if !*databaseFlag && !*integration { t.Skip() } res := ShowBooks2(db) if res[0].Title != "Meep" { t.Error("Expected Span") } if res[0].Author != "Jihaad" { t.Error("Expected Jihaad") } } func setupDatabase() { db = NewDB() }
member
package model import ( "fmt" "gorm.io/gorm" ) type ArticleView struct { gorm.Model Title string `gorm:"type:varchar(50) not null;commit:标题"` Content string `gorm:"type:text not null;commit:内容"` CategoryID uint8 `gorm:"type:smallint not null;commit:分类ID"` CategoryName string `gorm:"type:varchar(20) not null;commit:分类名称"` TagID uint8 `gorm:"type:smallint not null;commit:标签ID"` TagName string `gorm:"type:varchar(20) not null;commit:标签名称"` CommentCount uint `gorm:"type:int(10) not null;commit:评论总数"` } func (av ArticleView) Create(db *gorm.DB) error { err := db.AutoMigrate(av) if err != nil { fmt.Println(err) return err } return db.Create(&av).Error } func (av ArticleView) Read(db *gorm.DB) (ArticleView, error) { var articleView ArticleView tx := db.First(&articleView, av.ID) if err := tx.Error; err != nil { return articleView, err } return articleView, nil }
member
package wally import ( "errors" "fmt" "github.com/google/gousb" "io/ioutil" "time" ) type status struct { bStatus string bwPollTimeout int bState string iString string } func dfuCommand(dev *gousb.Device, addr int, command int, status *status) (err error) { var buf []byte if command == setAddress { buf = make([]byte, 5) buf[0] = 0x21 buf[1] = byte(addr & 0xff) buf[2] = byte((addr >> 8) & 0xff) buf[3] = byte((addr >> 16) & 0xff) buf[4] = byte((addr >> 24) & 0xff) } if command == eraseAddress { buf = make([]byte, 5) buf[0] = 0x41 buf[1] = byte(addr & 0xff) buf[2] = byte((addr >> 8) & 0xff) buf[3] = byte((addr >> 16) & 0xff) buf[4] = byte((addr >> 24) & 0xff) } if command == eraseFlash { buf = make([]byte, 1) buf[0] = 0x41 } _, err = dev.Control(33, 1, 0, 0, buf) err = dfuPollTimeout(dev, status) if err != nil { return err } return nil } func dfuPollTimeout(dev *gousb.Device, status *status) (err error) { for i := 0; i < 3; i++ { err = dfuGetStatus(dev, status) time.Sleep(time.Duration(status.bwPollTimeout) * time.Millisecond) } return err } func dfuGetStatus(dev *gousb.Device, status *status) (err error) { buf := make([]byte, 6) stat, err := dev.Control(161, 3, 0, 0, buf) if err != nil { return err } if stat == 6 { status.bStatus = string(buf[0]) status.bwPollTimeout = int((0xff & buf[3] << 16) | (0xff & buf[2]) | 0xff&buf[1]) status.bState = string(buf[4]) status.iString = string(buf[5]) } return err } func dfuClearStatus(dev *gousb.Device) (err error) { _, err = dev.Control(33, 4, 2, 0, nil) return err } func dfuReboot(dev *gousb.Device, status *status) (err error) { err = dfuPollTimeout(dev, status) _, err = dev.Control(33, 1, 2, 0, nil) time.Sleep(1000 * time.Millisecond) err = dfuGetStatus(dev, status) return err } func extractSuffix(fileData []byte) (hasSuffix bool, data []byte, err error) { fileSize := len(fileData) suffix := fileData[fileSize-dfuSuffixLength : fileSize] d := string(suffix[10]) f := string(suffix[9]) u := string(suffix[8]) if d == "D" && f == "F" && u == "U" { vid := int((suffix[5] << 8) + suffix[4]) pid := int((suffix[3] << 8) + suffix[2]) if vid != dfuSuffixVendorID || pid != dfuSuffixProductID { message := fmt.Sprintf("Invalid vendor or product id, expected %#x:%#x got %#x:%#x", dfuSuffixVendorID, dfuSuffixProductID, vid, pid) err = errors.New(message) return true, fileData, err } return true, fileData[0 : fileSize-dfuSuffixLength], nil } return false, fileData, nil } func DFUFlash(s *State) { dfuStatus := status{} fileData, err := ioutil.ReadFile(s.FirmwarePath) if err != nil { message := fmt.Sprintf("Error while opening firmware: %s", err) s.Log("error", message) return } hasSuffix, firmwareData, err := extractSuffix(fileData) if err != nil { message := fmt.Sprintf("Error while extracting DFU Suffix: %s", err) s.Log("error", message) return } if hasSuffix { s.Log("info", "Found a valid DFU Suffix") } else { s.Log("info", "No DFU Suffix found") } ctx := gousb.NewContext() defer ctx.Close() var dev *gousb.Device // Get the list of device that match TMK's vendor id for { // if the app is reset stop this goroutine and close the usb context if s.Step != 3 { s.Log("info", "App reset, interrupting the flashing process.") return } s.Log("info", "Waiting for a DFU capable device") devs, err := ctx.OpenDevices(func(desc *gousb.DeviceDesc) bool { if desc.Vendor == gousb.ID(dfuVendorID) && desc.Product == gousb.ID(dfuProductID) { return true } return false }) defer func() { for _, d := range devs { d.Close() } }() if err != nil { message := fmt.Sprintf("OpenDevices: %s", err) s.Log("warning", message) } if len(devs) > 0 { dev = devs[0] break } time.Sleep(1 * time.Second) } dev.SetAutoDetach(true) dev.ControlTimeout = 5 * time.Second cfg, err := dev.Config(1) if err != nil { message := fmt.Sprintf("Error while claiming the usb interface: %s", err) s.Log("error", message) return } defer cfg.Close() fileSize := len(firmwareData) s.FlashProgress.Sent = 0 s.FlashProgress.Total = fileSize err = dfuClearStatus(dev) if err != nil { message := fmt.Sprintf("Error while clearing the device status: %s", err) s.Log("error", message) return } s.Step = 4 s.emitUpdate() err = dfuCommand(dev, 0, eraseFlash, &dfuStatus) if err != nil { message := fmt.Sprintf("Error while erasing flash:", err) s.Log("error", message) return } for page := 0; page < fileSize; page += planckBlockSize { addr := planckStartAddress + page chunckSize := planckBlockSize if page+chunckSize > fileSize { chunckSize = fileSize - page } err = dfuCommand(dev, addr, eraseAddress, &dfuStatus) if err != nil { message := fmt.Sprintf("Error while sending the erase address command: %s", err) s.Log("error", message) return } err = dfuCommand(dev, addr, setAddress, &dfuStatus) if err != nil { message := fmt.Sprintf("Error while sending the set address command: %s", err) s.Log("error", message) return } buf := firmwareData[page : page+chunckSize] bytes, err := dev.Control(33, 1, 2, 0, buf) if err != nil { message := fmt.Sprintf("Error while sending firmware bytes: %s", err) s.Log("error", message) return } message := fmt.Sprintf("Sent %d bytes out of %d", page+bytes, fileSize) s.Log("info", message) s.FlashProgress.Sent += bytes s.emitUpdate() } time.Sleep(1 * time.Second) s.Log("info", "Sending the reboot command") err = dfuReboot(dev, &dfuStatus) if err != nil { message := fmt.Sprintf("Error while rebooting device: %s", err) s.Log("error", message) return } s.Step = 5 s.Log("info", "Flash complete") }
member
package utils import ( "github.com/dgrijalva/jwt-go" "pledge-bridge-backend/config" "time" ) func CreateToken(username string) (string, error) { at := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "username": username, "exp": time.Now().Add(time.Hour * 24 * 30).Unix(), }) token, err := at.SignedString([]byte(config.Config.Jwt.SecretKey)) if err != nil { return "", err } return token, nil } func ParseToken(token string, secret string) (string, error) { claim, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) { return []byte(secret), nil }) if err != nil { return "", err } return claim.Claims.(jwt.MapClaims)["username"].(string), nil }
non-member
package main import ( "github.com/kataras/iris" "github.com/kataras/iris/context" ) func main() { app := iris.New() none := app.None("/invisible/{username}", func(ctx context.Context) { ctx.Writef("Hello %s with method: %s", ctx.Values().GetString("username"), ctx.Method()) if from := ctx.Values().GetString("from"); from != "" { ctx.Writef("\nI see that you're coming from %s", from) } }) app.Get("/change", func(ctx context.Context) { if none.IsOnline() { none.Method = iris.MethodNone } else { none.Method = iris.MethodGet } // refresh re-builds the router at serve-time in order to be notified for its new routes. app.RefreshRouter() }) app.Get("/execute", func(ctx context.Context) { // same as navigating to "http://localhost:8080/invisible/iris" when /change has being invoked and route state changed // from "offline" to "online" ctx.Values().Set("from", "/execute") // values and session can be shared when calling Exec from a "foreign" context. ctx.Exec("GET", "/invisible/iris") }) app.Run(iris.Addr(":8080")) }
non-member
package workflow_error import ( "time" "go.temporal.io/sdk/temporal" "go.temporal.io/sdk/workflow" ) type BusinessError struct{} func (be BusinessError) Error() string { return "business error" } func ExperimentalWorkflow(ctx workflow.Context) error { ctx = defineActivityOptions(ctx, "some") err := workflow.ExecuteActivity(ctx, "Activity1").Get(ctx, nil) if err != nil { return err } err = workflow.ExecuteActivity(ctx, "Activity2").Get(ctx, nil) if err != nil { return err } return nil } func defineActivityOptions(ctx workflow.Context, queue string) workflow.Context { ao := workflow.ActivityOptions{ TaskQueue: queue, ScheduleToStartTimeout: time.Second, StartToCloseTimeout: 24 * time.Hour, HeartbeatTimeout: time.Second * 2, RetryPolicy: &temporal.RetryPolicy{ InitialInterval: time.Second, BackoffCoefficient: 2.0, MaximumInterval: time.Minute * 5, NonRetryableErrorTypes: []string{"BusinessError"}, }, } ctxOut := workflow.WithActivityOptions(ctx, ao) return ctxOut }
non-member
package psql_test import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/dobermanndotdev/dobermann/internal/app/query" "github.com/dobermanndotdev/dobermann/internal/domain" "github.com/dobermanndotdev/dobermann/internal/domain/monitor" "github.com/dobermanndotdev/dobermann/tests" ) func TestIncidentRepository_Lifecycle(t *testing.T) { account00 := tests.FixtureAndInsertAccount(t, db, true) monitor00 := tests.FixtureMonitor(t, account00) incident00 := tests.FixtureIncident(t, monitor00.ID().String()) require.NoError(t, monitorRepository.Insert(ctx, monitor00)) assert.NoError(t, incidentRepository.Create(ctx, incident00)) t.Run("find_incident_by_id", func(t *testing.T) { t.Parallel() found00, err := incidentRepository.FindByID(ctx, incident00.ID()) require.NoError(t, err) assertIncident(t, incident00, found00) }) t.Run("incident_not_found", func(t *testing.T) { t.Parallel() _, err := incidentRepository.FindByID(ctx, domain.NewID()) assert.ErrorIs(t, err, monitor.ErrIncidentNotFound) }) t.Run("all_incidents", func(t *testing.T) { t.Parallel() result, err := incidentRepository.FindAll(ctx, account00.ID(), query.PaginationParams{ Page: 1, Limit: 100, }) require.NoError(t, err) for _, foundIncident := range result.Data { require.Equal(t, monitor00.ID(), foundIncident.MonitorID()) } }) } func assertIncident(t *testing.T, expected, found *monitor.Incident) { t.Helper() assert.Equal(t, expected.ID(), found.ID()) assert.Equal(t, expected.CheckedURL(), found.CheckedURL()) assert.Equal(t, expected.Cause(), found.Cause()) //POST_IDEA?: comparing dates in tests assert.Equal(t, expected.CreatedAt().Truncate(time.Second), found.CreatedAt().Truncate(time.Second)) }
non-member
package finder import ( "testing" ) func TestFunction_elemInSlice(t *testing.T) { var elem string = "elem" var slice = []string{"elem", "foo", "bar"} if !elemInSlice(slice, elem) { t.Errorf("Failure: Expected to find element 'elem' in slice!") } elem = "elem" slice = []string{"foo", "bar"} if elemInSlice(slice, elem) { t.Errorf("Failure: Expected to not find element 'elem' in slice!") } } func TestFunction_ToString(t *testing.T) { var function = Function{ name: "testFunction", line: 1337, file: "just/some/random/test/file.ext", } var shouldBe = "Function | Name: testFunction, Line: 1337, File: just/some/random/test/file.ext" if function.ToString() != shouldBe { t.Errorf("Failure: Expected \"%s\", got: : \"%s\"", shouldBe, function.ToString()) } } func TestCleanLine(t *testing.T) { var idx = 1 auxTest := func(line, exp string) { ret := CleanLine(line) if ret != exp { t.Errorf("%v: Expected line '%s' to have answer: '%v', got: '%v'", idx, line, exp, ret) } idx++ } auxTest("// This is a inline comment", "") auxTest(" // Same inline comment", "") auxTest(" \t // Same inline comment with tab", "") auxTest("int a = 12; // Random comment", "int a = 12;") auxTest("bool func(type param) // Comment", "bool func(type param)") auxTest("bool func(type param) /* Comment */", "bool func(type param)") auxTest(" bool func(type param) /* Comment */", "bool func(type param)") auxTest(" \tbool func(type param) /* Comment */", "bool func(type param)") auxTest("// func(type param)", "") auxTest(" * This is a multiline comment", "") auxTest(" /* This is the startline of a multiline comment", "") auxTest(" * This is a multiline comment with additional steps", "") auxTest(" \t * This is a multiline comment with tab", "") auxTest(" int a = 12; /* Comment */ int b = 24;", "int a = 12; int b = 24;") } func TestHasFuncDec(t *testing.T) { var idx = 1 auxTest := func(line string, exp bool) { ret := HasFuncDec(line) if ret != exp { t.Errorf("%v: Expected line '%s' to have answer: %v, got: %v", idx, line, exp, ret) } idx++ } auxTest("", false) auxTest("bool (func(type param)", false) auxTest("bool func(type param", false) auxTest("bool func(type param,", true) auxTest("bool func(type param)", true) auxTest("bool func(type param){", true) auxTest("bool func(type param", false) auxTest("bool func(void){", true) auxTest("bool func(void)", true) auxTest("bool func(uint8 param_1, void)", true) // not really okay, but to tidious if i wanted to fix that auxTest("bool func(void, ", false) auxTest("bool func(void, \t", false) auxTest("bool func(uint8 param_1, void)", true) // not really okay, but to tidious if i wanted to fix that auxTest("bool func(uint8 param_1)", true) auxTest("bool func()", true) auxTest("bool func( )", true) auxTest("bool func(void)", true) auxTest("bool func(void,", true) // not really okay, but to tidious if i wanted to fix that auxTest("bool func(uint8 param_1,", true) auxTest("// bool func(void,", false) auxTest("// bool func(type param,", false) auxTest(" * bool func(type param,", false) auxTest("bool func(type param,", true) auxTest("extern bool func(type param,", true) auxTest("static bool func(type param,", true) auxTest("extern static bool func(type param,", false) auxTest("external bool func(type param,", false) auxTest("static \t bool func(type param,", true) auxTest("extern \t bool func(type param,", true) auxTest("extern \t\t bool funcincation(type param,", true) auxTest("extern bool funcincation{type param,", false) auxTest("bool funcincation{type param,", false) auxTest("bool bool funcincation(type param,", false) auxTest("bool funcincation(type param, type param,type param){", true) auxTest("\tbool funcincation(type param,", true) auxTest(" bool funcincation(type param,", true) auxTest("\t bool funcincation(type param,", true) auxTest("\t \tbool funcincation(type param,", true) } func TestHasOptimize(t *testing.T) { var idx = 1 testFunc := func(line string, exp bool) { ret := HasOptimize(line, PossibleOptimizations) if ret != exp { t.Errorf("%v: Expected line '%s' to have answer: %v, got: %v", idx, line, exp, ret) } idx++ } testFunc("", false) testFunc("// commment __attribute__((optimize(\"-Os\")))", false) testFunc("__attribute__((optimize(\"-Os\")))", true) testFunc("__attribute__((optimize(\"-Ost\")))", false) testFunc("__attribute__((optimize(\"-O5\")))", false) testFunc("__attribute__((optimize(\"-0s\")))", false) testFunc("__attribute__((optimize(\"-\")))", false) testFunc("__attribute__((optimize(\"-O\")))", true) testFunc(" * __attribute__((optimize(\"-Os\")))", false) testFunc("#__attribute__((optimize(\"-Os\")))", false) testFunc(" \t \t__attribute__((optimize(\"-Os\")))", true) testFunc("_attribute__((optimize(\"-Os\")))", false) testFunc("__attribute_((optimize(\"-Os\")))", false) testFunc("__attribute__(optimize(\"-Os\"))", false) testFunc("__attribute__((optimize(\"-Os\"))))", false) testFunc("__attribute__((optimize\"-Os\")))", false) testFunc("__attribute__ ((optimize-Os\")))", false) testFunc("__attribute__ ((optimize-Os)))", false) testFunc("__attribute__((optimize-Oss)))\t", false) testFunc("__attribute__ ((optimize-Oss)))", false) } func TestExtractFuncName(t *testing.T) { testFunc := func(line string, exp string) { ret := ExtractFuncName(line) if ret != exp { t.Errorf("Expected line '%s' to have answer: %v, got: %v", line, exp, ret) } } testFunc("bool func(type param", "func") testFunc("bool func(type param,", "func") testFunc("bool func(type param)", "func") testFunc("bool func(type param){", "func") testFunc("bool func(type param", "func") testFunc("bool func(void){", "func") testFunc("bool func(void)", "func") testFunc("bool func(type param,", "func") testFunc("extern bool func(type param,", "func") testFunc("static bool func(type param,", "func") testFunc("extern \t bool func(type param,", "func") testFunc("extern \t\t bool funcincation(type param,", "funcincation") testFunc("bool funcincation(type param, type param,type param){", "funcincation") testFunc("\tbool funcincation(type param,", "funcincation") testFunc(" bool funcincation(type param,", "funcincation") testFunc("\t bool funcincation(type param,", "funcincation") testFunc("\t \tbool funcincation(type param,", "funcincation") }
non-member
package transfer_test import ( "testing" ) func TestAccTransfer_serial(t *testing.T) { testCases := map[string]map[string]func(t *testing.T){ "Access": { "disappears": testAccAccess_disappears, "EFSBasic": testAccAccess_efs_basic, "S3Basic": testAccAccess_s3_basic, "S3Policy": testAccAccess_s3_policy, }, "Server": { "basic": testAccServer_basic, "disappears": testAccServer_disappears, "APIGateway": testAccServer_apiGateway, "APIGatewayForceDestroy": testAccServer_apiGateway_forceDestroy, "DirectoryService": testAccServer_directoryService, "Domain": testAccServer_domain, "ForceDestroy": testAccServer_forceDestroy, "HostKey": testAccServer_hostKey, "Protocols": testAccServer_protocols, "SecurityPolicy": testAccServer_securityPolicy, "UpdateEndpointTypePublicToVPC": testAccServer_updateEndpointType_publicToVPC, "UpdateEndpointTypePublicToVPCAddressAllocationIDs": testAccServer_updateEndpointType_publicToVPC_addressAllocationIDs, "UpdateEndpointTypeVPCEndpointToVPC": testAccServer_updateEndpointType_vpcEndpointToVPC, "UpdateEndpointTypeVPCEndpointToVPCAddressAllocationIDs": testAccServer_updateEndpointType_vpcEndpointToVPC_addressAllocationIDs, "UpdateEndpointTypeVPCEndpointToVPCSecurityGroupIDs": testAccServer_updateEndpointType_vpcEndpointToVPC_securityGroupIDs, "UpdateEndpointTypeVPCToPublic": testAccServer_updateEndpointType_vpcToPublic, "VPC": testAccServer_vpc, "VPCAddressAllocationIDs": testAccServer_vpcAddressAllocationIDs, "VPCAddressAllocationIDsSecurityGroupIDs": testAccServer_vpcAddressAllocationIds_securityGroupIDs, "VPCEndpointID": testAccServer_vpcEndpointID, "VPCSecurityGroupIDs": testAccServer_vpcSecurityGroupIDs, }, "SSHKey": { "basic": testAccSSHKey_basic, }, "User": { "basic": testAccUser_basic, "disappears": testAccUser_disappears, "HomeDirectoryMappings": testAccUser_homeDirectoryMappings, "ModifyWithOptions": testAccUser_modifyWithOptions, "Posix": testAccUser_posix, "UserNameValidation": testAccUser_UserName_Validation, }, } for group, m := range testCases { m := m t.Run(group, func(t *testing.T) { for name, tc := range m { tc := tc t.Run(name, func(t *testing.T) { tc(t) }) } }) } }
non-member
package utils import ( "encoding/json" "fmt" "io/ioutil" "log" "minirpc/Model" "net/http" "net/url" "regexp" "strconv" "strings" "time" "unsafe" ) type StackInfo struct { Name string `json:"name"` Code string `json:"code"` Ocode string `json:"ocode"` Gcode string `json:"gcode"` Val string `json:"val"` Per string `json:"per"` //位置 Ptype string `json:"ptype"` Daystr string `json:"daystr"` } type StockHistory struct { Code string `json:"code"` Todaye string `json:"todaye"` Ydaye string `json:"ydaye"` List []StockHistoryItem `json:"list"` } type StockHistoryItem struct { Date string `json:"date"` Sprice float64 `json:"sprice"` Eprice float64 `json:"eprice"` Cval float64 `json:"cval"` Cper float64 `json:"cper"` Cnum float64 `json:"cnum"` Ctval float64 `json:"ctval"` Chand float64 `json:"chand"` } var Ofile string var Gdreg *regexp.Regexp var Gdreg2 *regexp.Regexp var otherinfoarr []string func StockAnaly(code string) string { var retstr string dayNum := 7 end :=time.Now().Format("20060102") start :=time.Now().AddDate(0,0,-dayNum).Format("20060102") dayarr := make(map[int]string,dayNum) for { week := time.Now().AddDate(0,0,-dayNum).Weekday() if week ==0 || week==6 { dayarr[dayNum] ="" }else{ dayarr[dayNum] = time.Now().AddDate(0,0,-dayNum).Format("2006-01-02") } dayNum-- if dayNum<0 { break } } list := gethistory(code,start,end) retstr +="昨到今:" +list.Ydaye +"~"+list.Todaye if checkRaise(list,dayarr) { retstr += " 连涨3天!!" } if checkDec(list,dayarr) { retstr += " 连跌3天!!" } return retstr } func checkRaise(list StockHistory,dayarr map[int]string) bool { flag := true raseCunt :=0 startval := 0.0 for n:=0 ; n<len(dayarr); n++ { if dayarr[n]!="" { for _,v :=range list.List{ if v.Date == dayarr[n]{ if startval ==0 { startval = v.Eprice }else if startval>v.Eprice{ startval = v.Eprice raseCunt++ }else{ //未涨 flag = false } break } } } if !flag{ break } } if raseCunt>=3{ //连涨3天 fmt.Println("连涨"+strconv.Itoa(raseCunt)+"天") return true } return false } func checkDec(list StockHistory,dayarr map[int]string) bool { flag := true raseCunt :=0 startval := 0.0 for n:=0 ; n<len(dayarr); n++ { if dayarr[n]!="" { for _,v :=range list.List{ if v.Date == dayarr[n]{ if startval ==0 { startval = v.Eprice }else if startval<v.Eprice{ startval = v.Eprice raseCunt++ }else{ //fmt.Println(startval,v.Eprice) flag = false } break } } } if !flag{ break } } if raseCunt>=3{ //连跌3天 fmt.Println("连跌"+strconv.Itoa(raseCunt)+"天") return true } return false } func gethistory(code string,start string,end string ) StockHistory { var list StockHistory list.List = make([]StockHistoryItem,0) //https://q.stock.sohu.com/hisHq?code=cn_002960&start=20210301&end=20210309&stat=1&order=D&period=d&callback=historySearchHandler&rt=json data := make(map[string]string) data["code"] ="cn_"+code data["start"] =start data["end"] =end data["stat"] ="1" data["order"] = "D" data["period"] = "d" data["callback"] = "historySearchHandler" data["rt"] = "json" header := make(map[string]string) header["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36" res,err:=curltest("https://q.stock.sohu.com/hisHq",data,header,"GET") //["2018-05-10","3.02","3.05","0.04","1.33%","3.02","3.06","118307","3601.96","0.52%"] //[日期,开盘价,收盘价,涨跌额,涨跌幅,最低,最高,成交量,成交额,换手率] nowdaystr := time.Now().Format("2006-01-02") nowweek := time.Now().Weekday() lastdaystr :="" if nowweek==1 { lastdaystr = time.Now().AddDate(0,0,-3).Format("2006-01-02") }else{ lastdaystr = time.Now().AddDate(0,0,-1).Format("2006-01-02") } if err !=nil { fmt.Println(err) return list }else{ var m []interface{} err = json.Unmarshal([]byte(res), &m) if err != nil { fmt.Println(data["code"]," gethistory json fail") fmt.Println(res) fmt.Println(err) return list } tcode := m[0].(map[string]interface{})["code"].(string) if tcode!="cn_"+code{ return list } dlst := m[0].(map[string]interface{})["hq"].([]interface{}) for _,item := range dlst{ var titem StockHistoryItem titem.Date = item.([]interface{})[0].(string) v, err := strtof64(item.([]interface{})[1].(string)) if err != nil{ fmt.Println(err) return list } titem.Sprice = v v, err = strtof64(item.([]interface{})[2].(string)) if err != nil{ fmt.Println(err) } titem.Eprice = v if nowdaystr == titem.Date{ list.Todaye = item.([]interface{})[2].(string) } if lastdaystr ==titem.Date{ list.Ydaye = item.([]interface{})[2].(string) } v, err = strtof64(item.([]interface{})[3].(string)) if err != nil{ fmt.Println(err) } titem.Cval = v v, err = strtof64(strings.Trim(item.([]interface{})[4].(string),"%")) if err != nil{ fmt.Println(err) } titem.Cper = v v, err = strtof64(item.([]interface{})[7].(string)) if err != nil{ fmt.Println(err) } titem.Cnum = v v, err = strtof64(item.([]interface{})[8].(string)) if err != nil{ fmt.Println(err) } titem.Ctval = v v, err = strtof64(strings.Trim(item.([]interface{})[9].(string),"%")) if err != nil{ fmt.Println(err) } titem.Chand = v list.List = append(list.List,titem) } } list.Code = code return list } func GetStockBaseInfo(gcode string,name string) StackInfo{ //查询数据库 info,err := Model.GetOneStockInfo(gcode) if err!=nil{ fmt.Println(err) } if info.Name !="" { return StackInfo{ Name:info.Name, Code:info.Code, Gcode:info.Gcode, Ptype :info.Type, } }else { //爬取 info2 :=CrawStockBaseInfo(name) if info2.Name !=""{ //入库 Model.AddOneStockInfo(info2.Name,info2.Code,info2.Ptype,gcode,name) return StackInfo{ Name:info2.Name, Code:info2.Code, Gcode:info2.Gcode, Ptype :info2.Ptype, } }else{ return StackInfo{ Name:"", } } } } func CrawStockBaseInfo(name string) StackInfo{ var stockInfo StackInfo //https://quotes.money.163.com/stocksearch/json.do?type=HS&count=5&word=%E4%B8%AD%E9%87%91%E5%85%AC%E5%8F%B8&t=0.40060858273627353 data := make(map[string]string) data["word"] =name data["type"] ="HS" data["count"] = "1" header := make(map[string]string) header["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36" res,err:=curltest("https://quotes.money.163.com/stocksearch/json.do",data,header,"GET") //_ntes_stocksearch_callback([{"code":"0601995","type":"SH","symbol":"601995","tag":"HS MYHS","spell":"zjgs","name":"\u4e2d\u91d1\u516c\u53f8"}]) if err!= nil { fmt.Println(err) return stockInfo } if len(res)<27 { fmt.Println("get stockInfo fail") return stockInfo } res = res[27:len(res)-1] var m []interface{} err = json.Unmarshal([]byte(res), &m) if err != nil { fmt.Println(name) fmt.Println(res) fmt.Println(err) return stockInfo } /* if name != m[0].(map[string]interface{})["name"].(string){ fmt.Println(name) fmt.Println(m[0].(map[string]interface{})["name"].(string)) fmt.Println("get stockInfo no match") return stockInfo } */ stockInfo.Name =m[0].(map[string]interface{})["name"].(string) stockInfo.Code = m[0].(map[string]interface{})["symbol"].(string) stockInfo.Ptype = m[0].(map[string]interface{})["type"].(string) return stockInfo } func strtof64(str string) (float64,error) { v, err := strconv.ParseFloat(str, 64) if err != nil{ return 0,err } return v,nil } func curltest(ourl string,data map[string]string, header map[string]string,dtype string) (string,error) { reader := strings.NewReader("") var mentype string if dtype =="JSON" { mentype = "POST" }else{ mentype = dtype } if data!=nil { if mentype == "POST"{ str, err := json.Marshal(data) if err != nil { fmt.Println("json.Marshal failed:", err) return "",err } reader = strings.NewReader(string(str)) } else if mentype== "GET"{ params := url.Values{} parseURL, err := url.Parse(ourl) if err != nil { log.Println("err") } for key,val := range data { params.Set(key, val) } //如果参数中有中文参数,这个方法会进行URLEncode parseURL.RawQuery = params.Encode() ourl = parseURL.String() } } //fmt.Println(ourl) // request, err := http.Get(ourl) //fmt.Println(reader) request, err := http.NewRequest(mentype, ourl, reader) if err != nil { return "",err } if dtype =="JSON" { request.Header.Set("Content-Type", "application/json;charset=utf-8") } for key,item := range header{ request.Header.Set(key,item) } client := http.Client{} resp, err := client.Do(request) if err != nil { return "",err } //utf8Reader := transform.NewReader(resp.Body,simplifiedchinese.GBK.NewDecoder()) respBytes, err := ioutil.ReadAll(resp.Body) //respBytes, err := ioutil.ReadAll(utf8Reader) if err != nil { return "",err } //byte数组直接转成string,优化内存 //utf8 := mahonia.NewDecoder("utf8").ConvertString(string(respBytes)) //ioutil.WriteFile("./output2.txt", respBytes, 0666) //写入文件(字节数组) res := (*string)(unsafe.Pointer(&respBytes)) return *res,nil }
non-member
package files import ( "fmt" "github.com/alexcoder04/iserv2go/iserv/types" "github.com/studio-b12/gowebdav" ) type FilesClient struct { config *types.ClientConfig davClient *gowebdav.Client } func (c *FilesClient) Login(config *types.ClientConfig) error { c.config = config c.davClient = gowebdav.NewClient(fmt.Sprintf("https://webdav.%s", c.config.IServHost), c.config.Username, c.config.Password) return c.davClient.Connect() } func (c *FilesClient) Logout() error { return nil }
non-member
package currency import ( "github.com/pkg/errors" "go.mongodb.org/mongo-driver/bson/bsontype" "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) func (a Big) MarshalBSONValue() (bsontype.Type, []byte, error) { return bsontype.String, bsoncore.AppendString(nil, a.String()), nil } func (a *Big) UnmarshalBSONValue(t bsontype.Type, b []byte) error { if t != bsontype.String { return errors.Errorf("invalid marshaled type for Big, %v", t) } s, _, ok := bsoncore.ReadString(b) if !ok { return errors.Errorf("can not read string") } ua, err := NewBigFromString(s) if err != nil { return err } *a = ua return nil }
non-member
package main import ( glog "github.com/Sirupsen/logrus" "k8s.io/apimachinery/pkg/api/resource" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/pkg/api/v1" ) // Load nodes func LoadNodes() []v1.Node { nodes, err := GetKubeCli().CoreV1().Nodes().List(meta_v1.ListOptions{}) if err != nil { panic(err.Error()) } glog.Infof("There are %d nodes in the cluster\n", len(nodes.Items)) for _, node := range nodes.Items { glog.Infof("node info: %v\n", node) } return nodes.Items } // node strategies type NodeStrategy struct { Nodes []v1.Node Strategies []*Strategy } func NewNodeStrategy(nodes ...v1.Node) *NodeStrategy { ns := &NodeStrategy{ Nodes: make([]v1.Node, 0), Strategies: make([]*Strategy, 0), } nodeLen := len(nodes) if nodeLen == 0 { return ns } else if nodeLen > 1 { ns.Nodes = append(ns.Nodes, nodes...) ns.Strategies = append(ns.Strategies, ClusterStrategies...) } else { ns.Nodes = append(ns.Nodes, nodes[0]) if ss, ok := NodesStrategies["general"]; ok { ns.Strategies = append(ns.Strategies, ss...) } if ss, ok := NodesStrategies[ns.Nodes[0].Name]; ok { ns.Strategies = append(ns.Strategies, ss...) } } return ns } func (ns *NodeStrategy) Check() { if len(ns.Nodes) == 0 || len(ns.Strategies) == 0 { return } STRATEGIES: for _, s := range ns.Strategies { switch s.StrategyType { case ResourceStrategy: for resourceName, resourceThreshold := range s.ResourceRules { threshold, err := resource.ParseQuantity(resourceThreshold) if err != nil { glog.Errorf("invalid resource threshold format: %v\n", err) continue STRATEGIES } leftResource := ns.LeftResource(resourceName) if leftResource.Cmp(threshold) > 1 { glog.Infof("left %s is greater than threshold, %s >= %s\n", resourceName, leftResource, threshold) continue STRATEGIES } } // current strategy has been captured. for _, op := range s.Operations { if err := op.Execute(); err != nil { glog.Warningf("exec operation return err: %v\n", err) } } if !s.Fallthrough { break STRATEGIES } case NodePhaseStrategy: case NodeConditionStrategy: } } } // LeftResource func (ns *NodeStrategy) LeftResource(resourceName v1.ResourceName) *resource.Quantity { leftResource := resource.NewQuantity(0, resource.DecimalSI) for _, node := range ns.Nodes { leftResource.Add(node.Status.Allocatable[resourceName]) } glog.Debugf("%s leftResource: %v", resourceName, leftResource) return leftResource }
member
package types import ( log "github.com/33cn/chain33/common/log/log15" "github.com/33cn/chain33/types" ) /* * 交易相关类型定义 * 交易action通常有对应的log结构,用于交易回执日志记录 * 每一种action和log需要用id数值和name名称加以区分 */ // action类型id和name,这些常量可以自定义修改 const ( TyUnknowAction = iota + 100 TyAddAction TySubAction TyMulAction TyDivAction NameAddAction = "Add" NameSubAction = "Sub" NameMulAction = "Mul" NameDivAction = "Div" ) // log类型id值 const ( TyUnknownLog = iota + 100 TyAddLog TySubLog TyMulLog TyDivLog ) var ( //HelloX 执行器名称定义 HelloX = "hello" //定义actionMap actionMap = map[string]int32{ NameAddAction: TyAddAction, NameSubAction: TySubAction, NameMulAction: TyMulAction, NameDivAction: TyDivAction, } //定义log的id和具体log类型及名称,填入具体自定义log类型 logMap = map[int64]*types.LogInfo{ //LogID: {Ty: reflect.TypeOf(LogStruct), Name: LogName}, } tlog = log.New("module", "hello.types") ) // init defines a register function func init() { types.AllowUserExec = append(types.AllowUserExec, []byte(HelloX)) //注册合约启用高度 types.RegFork(HelloX, InitFork) types.RegExec(HelloX, InitExecutor) } // InitFork defines register fork func InitFork(cfg *types.Chain33Config) { cfg.RegisterDappFork(HelloX, "Enable", 0) } // InitExecutor defines register executor func InitExecutor(cfg *types.Chain33Config) { types.RegistorExecutor(HelloX, NewType(cfg)) } type helloType struct { types.ExecTypeBase } func NewType(cfg *types.Chain33Config) *helloType { c := &helloType{} c.SetChild(c) c.SetConfig(cfg) return c } // GetPayload 获取合约action结构 func (h *helloType) GetPayload() types.Message { return &HelloAction{} } // GeTypeMap 获取合约action的id和name信息 func (h *helloType) GetTypeMap() map[string]int32 { return actionMap } // GetLogMap 获取合约log相关信息 func (h *helloType) GetLogMap() map[int64]*types.LogInfo { return logMap }
member
package runner import ( "errors" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "strconv" "strings" "syscall" "testing" "time" ) func TestIsDirRootPath(t *testing.T) { result := isDir(".") if result != true { t.Errorf("expected '%t' but got '%t'", true, result) } } func TestIsDirMainFile(t *testing.T) { result := isDir("main.go") if result != false { t.Errorf("expected '%t' but got '%t'", true, result) } } func TestIsDirFileNot(t *testing.T) { result := isDir("main.go") if result != false { t.Errorf("expected '%t' but got '%t'", true, result) } } func TestExpandPathWithDot(t *testing.T) { path, _ := expandPath(".") wd, _ := os.Getwd() if path != wd { t.Errorf("expected '%s' but got '%s'", wd, path) } } func TestExpandPathWithHomePath(t *testing.T) { path := "~/.conf" result, _ := expandPath(path) home := os.Getenv("HOME") want := home + path[1:] if result != want { t.Errorf("expected '%s' but got '%s'", want, result) } } func TestFileChecksum(t *testing.T) { tests := []struct { name string fileContents []byte expectedChecksum string expectedChecksumError string }{ { name: "empty", fileContents: []byte(``), expectedChecksum: "", expectedChecksumError: "empty file, forcing rebuild without updating checksum", }, { name: "simple", fileContents: []byte(`foo`), expectedChecksum: "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae", expectedChecksumError: "", }, { name: "binary", fileContents: []byte{0xF}, // invalid UTF-8 codepoint expectedChecksum: "dc0e9c3658a1a3ed1ec94274d8b19925c93e1abb7ddba294923ad9bde30f8cb8", expectedChecksumError: "", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { f, err := os.CreateTemp("", "") if err != nil { t.Fatalf("couldn't create temp file for test: %v", err) } defer func() { if err := f.Close(); err != nil { t.Errorf("error closing temp file: %v", err) } if err := os.Remove(f.Name()); err != nil { t.Errorf("error removing temp file: %v", err) } }() _, err = f.Write(test.fileContents) if err != nil { t.Fatalf("couldn't write to temp file for test: %v", err) } checksum, err := fileChecksum(f.Name()) if err != nil && err.Error() != test.expectedChecksumError { t.Errorf("expected '%s' but got '%s'", test.expectedChecksumError, err.Error()) } if checksum != test.expectedChecksum { t.Errorf("expected '%s' but got '%s'", test.expectedChecksum, checksum) } }) } } func TestChecksumMap(t *testing.T) { m := &checksumMap{m: make(map[string]string, 3)} if !m.updateFileChecksum("foo.txt", "abcxyz") { t.Errorf("expected no entry for foo.txt, but had one") } if m.updateFileChecksum("foo.txt", "abcxyz") { t.Errorf("expected matching entry for foo.txt") } if !m.updateFileChecksum("foo.txt", "123456") { t.Errorf("expected matching entry for foo.txt") } if !m.updateFileChecksum("bar.txt", "123456") { t.Errorf("expected no entry for bar.txt, but had one") } } func TestAdaptToVariousPlatforms(t *testing.T) { config := &config{ Build: cfgBuild{ Bin: "tmp\\main.exe -dev", }, } adaptToVariousPlatforms(config) if config.Build.Bin != "tmp\\main.exe -dev" { t.Errorf("expected '%s' but got '%s'", "tmp\\main.exe -dev", config.Build.Bin) } } func Test_killCmd_no_process(t *testing.T) { e := Engine{ config: &config{ Build: cfgBuild{ SendInterrupt: false, }, }, } _, err := e.killCmd(&exec.Cmd{ Process: &os.Process{ Pid: 9999, }, }) if err == nil { t.Errorf("expected error but got none") } if !errors.Is(err, syscall.ESRCH) { t.Errorf("expected '%s' but got '%s'", syscall.ESRCH, errors.Unwrap(err)) } } func Test_killCmd_SendInterrupt_false(t *testing.T) { _, b, _, _ := runtime.Caller(0) // Root folder of this project dir := filepath.Dir(b) err := os.Chdir(dir) if err != nil { t.Fatalf("couldn't change directory: %v", err) } // clean file before test os.Remove("pid") defer os.Remove("pid") e := Engine{ config: &config{ Build: cfgBuild{ SendInterrupt: false, }, }, } startChan := make(chan struct { pid int cmd *exec.Cmd }) go func() { cmd, _, _, _, err := e.startCmd("sh _testdata/run-many-processes.sh") if err != nil { t.Errorf("failed to start command: %v", err) return } pid := cmd.Process.Pid t.Logf("process pid is %v", pid) startChan <- struct { pid int cmd *exec.Cmd }{pid: pid, cmd: cmd} _ = cmd.Wait() }() resp := <-startChan t.Logf("process started. checking pid %v", resp.pid) time.Sleep(5 * time.Second) pid, err := e.killCmd(resp.cmd) if err != nil { t.Fatalf("failed to kill command: %v", err) } t.Logf("%v was been killed", pid) // check processes were being killed // read pids from file bytesRead, _ := ioutil.ReadFile("pid") lines := strings.Split(string(bytesRead), "\n") for _, line := range lines { _, err := strconv.Atoi(line) if err != nil { t.Logf("failed to covert str to int %v", err) continue } _, err = exec.Command("ps", "-p", line, "-o", "comm= ").Output() if err == nil { t.Fatalf("process should be killed %v", line) } } }
non-member
package main import ( "encoding/json" "fmt" "log" "net/http" ) type Numverify struct { Valid bool `json:"valid"` Number string `json:"number"` LocalFormat string `json:"local_format"` InternationalFormat string `json:"international_format"` CountryPrefix string `json:"country_prefix"` CountryCode string `json:"country_code"` CountryName string `json:"country_name"` Location string `json:"location"` Carrier string `json:"carrier"` LineType string `json:"line_type"` } func entries(word string) { //phone := "14158586273" // QueryEscape escapes the phone string so // it can be safely placed inside a URL query //safePhone := url.QueryEscape(phone) //url := fmt.Sprintf("http://apilayer.net/api/validate?access_key=YOUR_ACCESS_KEY&number=%s", safePhone) //word := "ace" url := fmt.Sprintf("https://od-api.oxforddictionaries.com:443/api/v1/entries/en/",word) // Build the request req, err := http.NewRequest("GET", url, nil) if err != nil { log.Fatal("NewRequest: ", err) return } // For control over HTTP client headers, // redirect policy, and other settings, // create a Client // A Client is an HTTP client client := &http.Client{} // headers req.Header.Set("Accept", "application/json") req.Header.Set("app_id", "c305db46") req.Header.Set("app_key", "539ae75d43042248f92ce6f6a07a8d8d") //"Accept": "application/json", //"app_id": "c305db46", //"app_key": "539ae75d43042248f92ce6f6a07a8d8d" // Send the request via a client // Do sends an HTTP request and // returns an HTTP response resp, err := client.Do(req) if err != nil { log.Fatal("Do: ", err) return } // Callers should close resp.Body // when done reading from it // Defer the closing of the body defer resp.Body.Close() // Fill the record with the data from the JSON var record DictionarySchema // Use json.Decode for reading streams of JSON data if err := json.NewDecoder(resp.Body).Decode(&record); err != nil { log.Println(err) } fmt.Println("Word = ", record.Results[0].Word) fmt.Println("Type = ", record.Results[0].Type) } type DictionarySchema struct { Metadata struct { } `json:"metadata"` Results []struct { ID string `json:"id"` Language string `json:"language"` LexicalEntries []struct { Entries []struct { Etymologies []string `json:"etymologies"` GrammaticalFeatures []struct { Text string `json:"text"` Type string `json:"type"` } `json:"grammaticalFeatures"` HomographNumber string `json:"homographNumber"` Pronunciations []struct { AudioFile string `json:"audioFile"` Dialects []string `json:"dialects"` PhoneticNotation string `json:"phoneticNotation"` PhoneticSpelling string `json:"phoneticSpelling"` Regions []string `json:"regions"` } `json:"pronunciations"` Senses []struct { CrossReferenceMarkers []string `json:"crossReferenceMarkers"` CrossReferences []struct { ID string `json:"id"` Text string `json:"text"` Type string `json:"type"` } `json:"crossReferences"` Definitions []string `json:"definitions"` Domains []string `json:"domains"` Examples []struct { Definitions []string `json:"definitions"` Domains []string `json:"domains"` Regions []string `json:"regions"` Registers []string `json:"registers"` SenseIds []string `json:"senseIds"` Text string `json:"text"` Translations []struct { Domains []string `json:"domains"` GrammaticalFeatures []struct { Text string `json:"text"` Type string `json:"type"` } `json:"grammaticalFeatures"` Language string `json:"language"` Regions []string `json:"regions"` Registers []string `json:"registers"` Text string `json:"text"` } `json:"translations"` } `json:"examples"` ID string `json:"id"` Pronunciations []struct { AudioFile string `json:"audioFile"` Dialects []string `json:"dialects"` PhoneticNotation string `json:"phoneticNotation"` PhoneticSpelling string `json:"phoneticSpelling"` Regions []string `json:"regions"` } `json:"pronunciations"` Regions []string `json:"regions"` Registers []string `json:"registers"` Subsenses []struct { } `json:"subsenses"` Translations []struct { Domains []string `json:"domains"` GrammaticalFeatures []struct { Text string `json:"text"` Type string `json:"type"` } `json:"grammaticalFeatures"` Language string `json:"language"` Regions []string `json:"regions"` Registers []string `json:"registers"` Text string `json:"text"` } `json:"translations"` VariantForms []struct { Regions []string `json:"regions"` Text string `json:"text"` } `json:"variantForms"` } `json:"senses"` VariantForms []struct { Regions []string `json:"regions"` Text string `json:"text"` } `json:"variantForms"` } `json:"entries"` GrammaticalFeatures []struct { Text string `json:"text"` Type string `json:"type"` } `json:"grammaticalFeatures"` Language string `json:"language"` LexicalCategory string `json:"lexicalCategory"` Pronunciations []struct { AudioFile string `json:"audioFile"` Dialects []string `json:"dialects"` PhoneticNotation string `json:"phoneticNotation"` PhoneticSpelling string `json:"phoneticSpelling"` Regions []string `json:"regions"` } `json:"pronunciations"` Text string `json:"text"` VariantForms []struct { Regions []string `json:"regions"` Text string `json:"text"` } `json:"variantForms"` } `json:"lexicalEntries"` Pronunciations []struct { AudioFile string `json:"audioFile"` Dialects []string `json:"dialects"` PhoneticNotation string `json:"phoneticNotation"` PhoneticSpelling string `json:"phoneticSpelling"` Regions []string `json:"regions"` } `json:"pronunciations"` Type string `json:"type"` Word string `json:"word"` } `json:"results"` }
member
package neurons import ( "fmt" "strings" "sync" ) type Client struct { Mu sync.Mutex Uid string Hostname string Username string Response chan []byte Jobs chan string Transfer chan string Pulse chan struct{} } type ClientList struct { Mu sync.Mutex List map[string]*Client // string key will be the uid sha256 hash Current string } var Clients = ClientList{ List: make(map[string]*Client), } const padLength = 66 const numberOfFields = 3 var frame string func init() { var tmpFrame strings.Builder padding := strings.Repeat("-", padLength) for i := 0; i < numberOfFields; i++ { tmpFrame.WriteString("+") tmpFrame.WriteString(padding) } tmpFrame.WriteString("+") frame = tmpFrame.String() } func leftPad(s string, padStr string, pLen int) string { return strings.Repeat(padStr, pLen) + s } func rightPad(s string, padStr string, pLen int) string { return s + strings.Repeat(padStr, pLen) } // ref: https://stackoverflow.com/a/47823574 func center(s string, w int) string { return fmt.Sprintf("%*s", -w, fmt.Sprintf("%*s", (w+len(s))/2, s)) } func (c *ClientList) Display() { fmt.Println(frame) if len(c.List) == 0 { fmt.Println("|", center("No clients connected.", (padLength*numberOfFields)+2), "|") } else { for uid, client := range c.List { fmt.Println("|", center(uid, padLength), "|", center(client.Hostname, padLength), "|", center(client.Username, padLength), "|") } } fmt.Println(frame) } func (c *ClientList) Size() int { return len(c.List) } func (c *ClientList) DisplayCurrent() { if c.HasCurrent() { fmt.Println(c.Current) } else { fmt.Println("No current client selected.") } } func (c *ClientList) GetCurrent() *Client { return c.List[c.Current] } func (c *ClientList) HasCurrent() bool { return c.Current != "" } func (c *ClientList) Cleanup(uid string) { fmt.Printf("\nClient dead: %s\n", uid) c.Mu.Lock() if c.Current == uid { c.Current = "" } delete(c.List, uid) c.Mu.Unlock() } func (c *ClientList) Add(uid string, name string) { fmt.Printf("\nClient connected: %s\n", uid) c.Mu.Lock() c.List[uid] = &Client{ Uid: uid, Hostname: strings.Split(name, ":")[0], Username: strings.Split(name, ":")[1], Response: make(chan []byte), Jobs: make(chan string, 1), Transfer: make(chan string, 1), Pulse: make(chan struct{}, 1), } c.Mu.Unlock() }
non-member
package strat import "github.com/curusarn/resh/pkg/records" // RecentBash prediction/recommendation strategy type RecentBash struct { histfile []string histfileSnapshot map[string][]string history map[string][]string } // Init see name func (s *RecentBash) Init() { s.histfileSnapshot = map[string][]string{} s.history = map[string][]string{} } // GetTitleAndDescription see name func (s *RecentBash) GetTitleAndDescription() (string, string) { return "recent (bash-like)", "Behave like bash" } // GetCandidates see name func (s *RecentBash) GetCandidates(strippedRecord records.EnrichedRecord) []string { // populate the local history from histfile if s.histfileSnapshot[strippedRecord.SessionID] == nil { s.histfileSnapshot[strippedRecord.SessionID] = s.histfile } return append(s.history[strippedRecord.SessionID], s.histfileSnapshot[strippedRecord.SessionID]...) } // AddHistoryRecord see name func (s *RecentBash) AddHistoryRecord(record *records.EnrichedRecord) error { // remove previous occurance of record for i, cmd := range s.history[record.SessionID] { if cmd == record.CmdLine { s.history[record.SessionID] = append(s.history[record.SessionID][:i], s.history[record.SessionID][i+1:]...) } } // append new record s.history[record.SessionID] = append([]string{record.CmdLine}, s.history[record.SessionID]...) if record.LastRecordOfSession { // append history of the session to histfile and clear session history s.histfile = append(s.history[record.SessionID], s.histfile...) s.histfileSnapshot[record.SessionID] = nil s.history[record.SessionID] = nil } return nil } // ResetHistory see name func (s *RecentBash) ResetHistory() error { s.Init() return nil }
member
package redactr import ( "encoding/base64" "fmt" "os" "regexp" "github.com/dhoelle/redactr/aes" "github.com/dhoelle/redactr/exec" "github.com/dhoelle/redactr/vault" "github.com/hashicorp/vault/api" ) // A Tool can be used to redact and unredact secrets. // If you want to use redactr as a library, you probably // want to create and use a Tool. type Tool struct { SecretUnredacter TokenUnredacter VaultUnredacter TokenUnredacter SecretRedacter TokenRedacter VaultRedacter TokenRedacter } // New creates a new Tool func New(opts ...NewToolOption) (*Tool, error) { c := &NewToolConfig{} for _, o := range opts { o(c) } t := &Tool{} // // AES redacter // if c.aesKey != "" { key, err := keyFromString(c.aesKey) if err != nil { return nil, fmt.Errorf("failed to parse AES key: %v", err) } t.SecretRedacter = &CompositeTokenRedacter{ Locator: &RegexTokenLocator{RE: regexp.MustCompile(`(?U)~~redact:(.+)~~`)}, Redacter: &aes.Redacter{Key: key}, Wrapper: &StringWrapper{Before: "~~redacted-aes:", After: "~~"}, } t.SecretUnredacter = &CompositeTokenUnredacter{ Locator: &RegexTokenLocator{RE: regexp.MustCompile(`(?U)~~redacted-aes:(.+)~~`)}, Unredacter: &aes.Redacter{Key: key}, Wrapper: &StringWrapper{Before: "~~redact:", After: "~~"}, } } // // Vault redacter // vaultClient, err := api.NewClient(api.DefaultConfig()) if err != nil { return nil, fmt.Errorf("failed to create Vault client: %v", err) } vaultWrapper := &vault.StandardClientWrapper{Client: vaultClient} vaultRedacter := vault.NewRedacter(vaultWrapper) t.VaultUnredacter = &CompositeTokenUnredacter{ Locator: &RegexTokenLocator{RE: vault.RedactedRE}, Unredacter: vaultRedacter, Wrapper: &vault.TokenWrapper{Before: "~~redact-vault:", After: "~~"}, } t.VaultRedacter = &CompositeTokenRedacter{ Locator: &RegexTokenLocator{RE: vault.UnredactedRE}, Redacter: vaultRedacter, Wrapper: &StringWrapper{Before: "~~redacted-vault:", After: "~~"}, } return t, nil } // NewToolConfig is used to configure a Tool created by New() type NewToolConfig struct { aesKey string } // NewToolOption configures a Tool on a call to New() type NewToolOption func(*NewToolConfig) // AESKey sets the key used for AES encryption and decryption func AESKey(key string) NewToolOption { return func(c *NewToolConfig) { c.aesKey = key } } // RedactTokens redacts all tokens in a string func (t *Tool) RedactTokens(s string) (string, error) { var err error if t.SecretRedacter != nil { s, err = t.SecretRedacter.RedactTokens(s) if err != nil { return "", fmt.Errorf("secret redacter failed: %v", err) } } if t.VaultRedacter != nil { s, err = t.VaultRedacter.RedactTokens(s) if err != nil { return "", fmt.Errorf("vault redacter failed: %v", err) } } return s, nil } // UnredactTokens unredacts all tokens in a string func (t *Tool) UnredactTokens(s string, opts ...UnredactTokensOption) (string, error) { var err error if t.SecretUnredacter != nil { sc := s s, err = t.SecretUnredacter.UnredactTokens(sc, opts...) if err != nil { return "", fmt.Errorf("failed to unredact secret token %v: %v", sc, err) } } if t.VaultUnredacter != nil { sc := s s, err = t.VaultUnredacter.UnredactTokens(sc, opts...) if err != nil { return "", fmt.Errorf("failed to unredact vault token %v: %v", sc, err) } } return s, nil } // Exec executes a command. It acts like os.Exec, // but with a couple of features that are helpful // when working with redacted secrets: // // 1. Before running the command, redacted secrets // in the environment will be unredacted. // // 2. When called with the RestartIfEnvChanges or // StopIfEnvChanges option, Exec will periodically // re-evaluate the environment. If the environment // has changed, Exec will restart or stop the command // as requested. func (t *Tool) Exec(name string, args []string, opts ...ExecOption) error { runner := exec.NewRunner( os.Stdin, os.Stdout, os.Environ(), toolUnredactReplacer(*t), name, args...) return Exec(runner, opts...) } // A toolUnredactReplacer uses a Tool to replace // redacted tokens with unredacted values type toolUnredactReplacer Tool // Replace will replace any redacted tokens // in the given string with unredacted values func (r toolUnredactReplacer) Replace(s string) (string, error) { t := Tool(r) return t.UnredactTokens(s) } func keyFromString(s string) (*[32]byte, error) { // keys should be base64 redacted d, err := base64.StdEncoding.DecodeString(s) if err != nil { return nil, fmt.Errorf("could not base64-unredact key: %v", err) } if len(d) != 32 { return nil, fmt.Errorf("key must be exactly 32 bytes (got %v)", len(d)) } b := &[32]byte{} copy(b[:], d) return b, nil }
member
package katana import ( "testing" ) func TestMarkup( t *testing.T ){ data := []struct { in, out string errors int } { { "", "", 0 }, { "texto", "texto", 0 }, { "texto @e(emph) @b(bold)", "texto emph bold", 0 }, { "@e(algo<>emph) @b(bold)", "emph bold", 0 }, { "n", "n", 0 }, { "b", "b", 0 }, { "@@", "@", 0 }, { "@{", "{", 0 }, { "@}", "}", 0 }, { "@((", "((", 0 }, { "@e[", "", 1 }, { "@e{", "", 1 }, { "@e}", "@e}", 1 }, { "@ [", "@ [", 1 }, { "@e}h", "@e}h", 1 }, { "@e>h", "@e>h", 1 }, { "hey @e[", "hey ", 1 }, { "aloha bye@e{", "aloha bye", 1 }, { "@\t>h", "@\t>h", 1 }, { "@b{h", "h", 1 }, { "@e{h", "h", 1 }, { "@\"{h", "h", 1 }, { "@\"{cite @e(emph)}", "cite emph", 0 }, { "@q<quote @e<emph @i[italic]>>", "quote emph italic", 0 }, { "@b<something <@> something-more>", "something <> something-more", 0 }, { "@b<something <>b>", "b", 0 }, { "@be(hola @l<link<>@c[main()]>)", "hola main()", 0 }, { "hela @aei {hey", "hela @aei {hey", 1 }, { "hela @{aei @({hey", "hela {aei ({hey", 0 }, { "hela @{aei @\n{hey", "hela {aei @\n{hey", 1 }, { "hela @i} @x}@{aei @e{hey", "hela @i} @x}{aei hey", 3 }, { "hela @i}@x}@{aei @e{hey", "hela @i}@x}{aei hey", 3 }, } for _, d := range data { x := NewScanner( d.in ).Init() eCount := 0 x.CustomError = func( s *Scanner, msg string ){ eCount++ } m := x.GetMarkup() result := m.String() if result != d.out || d.errors != eCount { t.Errorf( "Markup.String( %q )\nresult %q [%d errors]\nexpected %q [%d errors]", d.in, result, d.errors, d.out, eCount ) } } } func TestRebuild( t *testing.T ){ data := [...]string { "", "hola", "@b(hola)", "@b<hola>", "@b[hola]", "@b{hola}", "text @b(left<>right)", "text @b<right> b[left<>right]", "text @b<left<>right> b[left<>right]", "@b(left @i(it @e(ith<>oth)<>oth) ot <> et)", "@q[left @i(ith-left @i{ith-left2<>oth 2} ith left-1.2 <> ith right) left 1.2 <> right @c(right left @i{&¤}<>right)]", "@b(hola @e(emph @i(it) ot) ul)", "@@{", "@e", "@a(hola)", "@ab(hola)", "@abcd(hola)", "@l(#Mi Enlace<>un Enlace)", "hola @abcd(hola)", "hola @abcd(hola) bye", "hola @abcd(hey) [byte 0<>byte 1<>byte 2]", "@be(hola @l<link<>@c[main()]>)", } for i, d := range data { x := NewScanner( d ).Init() x.CustomError = quietSplash m := x.GetMarkup() result := m.Rebuild() if result != d { t.Errorf( "[%d] Markup.Rebuild( %q )\nresult %q\nexpected %q\n%v", i, d, result, d, m ) } } } func TestMultiMarkupRebuild( t *testing.T ){ data := [...]struct { in, out string } { { "@\"(@c(func))", "@\"c(func)" }, { "hola @\"(@c(func))", "hola @\"c(func)" }, { "hola @\"(@e(@c(func)))", "hola @\"ec(func)" }, { "hola @\"(@e(@c(func <>toMark)))", "hola @\"ec(func <>toMark)" }, { "hola @i(@e(hey<>@c(func <>toMark)))", "hola @ie(hey<>@c(func <>toMark))" }, { "hola @i(@q[@e(hey<>@c[func <>toMark()])])", "hola @iqe(hey<>@c[func <>toMark()])" }, } for i, d := range data { x := NewScanner( d.in ).Init() x.CustomError = quietSplash m := x.GetMarkup() result := m.Rebuild() if result != d.out { t.Errorf( "[%d] Markup.Rebuild( %q )\nresult %q\nexpected %q", i, d.in, result, d.out ) } } }
non-member
package db import ( pb "github.com/shuza/packet-service/proto" "github.com/stretchr/testify/mock" "sync" ) /** * := create date: 31-May-2019 * := (C) CopyRight Shuza * := shuza.ninja * := shuza.sa@gmail.com * := Code : Coffee : Fun **/ type MockDb struct { mu sync.RWMutex packets []*pb.Packet mock.Mock } // Create new packet func (repo *MockDb) Create(packet *pb.Packet) (*pb.Packet, error) { args := repo.Mock.Called(packet) if args.Get(1) != nil { return args.Get(0).(*pb.Packet), args.Get(1).(error) } repo.mu.Lock() updated := append(repo.packets, packet) repo.packets = updated repo.mu.Unlock() return args.Get(0).(*pb.Packet), nil } // Get all packets func (repo *MockDb) GetAll() []*pb.Packet { return repo.packets }
member
package globals import ( "io/ioutil" ) const ( // ConnAddr is a string constant specifying where the job creator connects to. ConnAddr = "localhost" // ConnPort is a string constant specifying the port the job creator runs on ConnPort = 7777 // ConnType specifies the connection type for the job creator (usually just TCP) ConnType = "tcp" ) // GetJobNames is an array of job names for the C&C to use func GetJobNames() []string { return []string{ "EQN", "HOSTUP", "TCPFLOOD", "UDPFLOOD", "NEIGHBOURS", } } // GetTCPPorts port is an array of TCP ports to be used in the TCP flood func GetTCPPorts() []int { return []int{ 25, 80, 443, 20, 21, 23, 143, 3389, 22, 53, 110, } } // GetUDPPorts is an array of UDP ports to be used in the UDP flood func GetUDPPorts() []int { return []int{ 53, 67, 68, 69, 123, 137, 138, 139, 161, 162, 389, 636, } } // MACString gets the default gateway mac address because I couldn't get ARP to work on time func MACString() (string, error) { s, err := ioutil.ReadFile("../Globals/secret.txt") if err != nil { return "", err } return string(s), nil }
non-member
package cluster import ( "fmt" "github.com/guillaumemichel/ipfs-local/config" ) func main() { instances := config.LoadInstances("save0") fmt.Println(instances) }
non-member
package driver import ( "github.com/graphql-go/graphql" ) //Deprecate //CreateVolActionHandler : Only Create volume action, func CreateVolActionHandler(params graphql.ResolveParams) (interface{}, error) { // logger.Logger.Println("Resolving: create_volume") // if params.Args["use_type"] == "" || params.Args["server_uuid"] == "" { // strerr := "Param args missing => (" + ")" // return nil, errors.New("[Cello]Can't Create Volume : " + strerr) // } // err := handler.ReloadPoolObject() // if err != nil { // strerr := "Can't reload Zpool => (" + fmt.Sprintln(err) + ")" // return nil, errors.New("[Cello]Can't Create Volume : " + strerr) // } // out, err := gouuid.NewV4() // if err != nil { // logger.Logger.Println("[volumeDao]Can't Create Volume UUID : ", err) // return nil, err // } // uuid := out.String() // params.Args["uuid"] = uuid // tempStruct, err := handler.ActionHandle(params.Args) // tempvolume := tempStruct.(model.Volume) // if err != nil { // logger.Logger.Println(err) // return nil, err // } // params.Args["lun_num"] = tempvolume.LunNum // volume, err := dao.CreateVolume(params.Args) // if err != nil { // strerr := "create_volume action status => (" + fmt.Sprintln(err) + ")" // logger.Logger.Println(strerr) // return nil, errors.New("[Cello]Can't Create Volume : " + strerr) // } // logger.Logger.Println("[Create Volume] Success : ", volume) return nil, nil } //UpdateVolActionHandler : Update Volume func UpdateVolActionHandler(params graphql.ResolveParams) (interface{}, error) { return nil, nil } //DeleteVolActionHandler : Delete Volume func DeleteVolActionHandler(params graphql.ResolveParams) (interface{}, error) { return nil, nil }
non-member
package odoo_api_wrapper import ( "fmt" ) // ProjectTask represents project.task model. type ProjectTask struct { Id *Int `xmlrpc:"id,omptempty"` Name *String `xmlrpc:"name,omptempty"` ProjectId *Many2One `xmlrpc:"project_id,omptempty"` ParentId *Many2One `xmlrpc:"parent_id,omptempty"` } // ProjectTasks represents array of project.task model. type ProjectTasks []ProjectTask // ProjectTaskModel is the odoo_api_wrapper model name. const ProjectTaskModel = "project.task" // Many2One convert ProjectTask to *Many2One. func (pt *ProjectTask) Many2One() *Many2One { return NewMany2One(pt.Id.Get(), "") } // CreateProjectTask creates a new project.task model and returns its id. func (c *Client) CreateProjectTask(pt *ProjectTask) (int64, error) { return c.Create(ProjectTaskModel, pt) } // UpdateProjectTask updates an existing project.task record. func (c *Client) UpdateProjectTask(pt *ProjectTask) error { return c.UpdateProjectTasks([]int64{pt.Id.Get()}, pt) } // UpdateProjectTasks updates existing project.task records. // All records (represented by ids) will be updated by pt values. func (c *Client) UpdateProjectTasks(ids []int64, pt *ProjectTask) error { return c.Update(ProjectTaskModel, ids, pt) } // DeleteProjectTask deletes an existing project.task record. func (c *Client) DeleteProjectTask(id int64) error { return c.DeleteProjectTasks([]int64{id}) } // DeleteProjectTasks deletes existing project.task records. func (c *Client) DeleteProjectTasks(ids []int64) error { return c.Delete(ProjectTaskModel, ids) } // GetProjectTask gets project.task existing record. func (c *Client) GetProjectTask(id int64) (*ProjectTask, error) { pts, err := c.GetProjectTasks([]int64{id}) if err != nil { return nil, err } if pts != nil && len(*pts) > 0 { return &((*pts)[0]), nil } return nil, fmt.Errorf("id %v of project.task not found", id) } // GetProjectTasks gets project.task existing records. func (c *Client) GetProjectTasks(ids []int64) (*ProjectTasks, error) { pts := &ProjectTasks{} if err := c.Read(ProjectTaskModel, ids, nil, pts); err != nil { return nil, err } return pts, nil } // FindProjectTask finds project.task record by querying it with criteria. func (c *Client) FindProjectTask(criteria *Criteria) (*ProjectTask, error) { pts := &ProjectTasks{} if err := c.SearchRead(ProjectTaskModel, criteria, NewOptions().Limit(1), pts); err != nil { return nil, err } if pts != nil && len(*pts) > 0 { return &((*pts)[0]), nil } return nil, fmt.Errorf("project.task was not found") } // FindProjectTasks finds project.task records by querying it // and filtering it with criteria and options. func (c *Client) FindProjectTasks(criteria *Criteria, options *Options) (*ProjectTasks, error) { pts := &ProjectTasks{} if err := c.SearchRead(ProjectTaskModel, criteria, options, pts); err != nil { return nil, err } return pts, nil } // FindProjectTaskIds finds records ids by querying it // and filtering it with criteria and options. func (c *Client) FindProjectTaskIds(criteria *Criteria, options *Options) ([]int64, error) { ids, err := c.Search(ProjectTaskModel, criteria, options) if err != nil { return []int64{}, err } return ids, nil } // FindProjectTaskId finds record id by querying it with criteria. func (c *Client) FindProjectTaskId(criteria *Criteria, options *Options) (int64, error) { ids, err := c.Search(ProjectTaskModel, criteria, options) if err != nil { return -1, err } if len(ids) > 0 { return ids[0], nil } return -1, fmt.Errorf("project.task was not found") }
non-member
package main import "fmt" const UNITED_STATE_STATES = 50 func main() { statesNeeded := []string{"mt", "wa", "or", "id", "nv", "ut", "ca", "az"} stations := make(map[string][]string) stations["kone"] = []string{"id", "nv", "ut"} stations["ktwo"] = []string{"wa", "id", "mt"} stations["kthree"] = []string{"or", "nv", "ca"} stations["kfour"] = []string{"nv", "ut"} stations["kfive"] = []string{"az", "ca"} fmt.Println(findStationsGreedy(statesNeeded, stations)) fmt.Println(findStationsExact(statesNeeded, stations)) } func findStationsExact(needed []string, stations map[string][]string) []string { stationNames := []string{} for sname := range stations { stationNames = append(stationNames, sname) } subsets := subsetList(stationNames) bestSubset := []string{} bestSubsetCount := UNITED_STATE_STATES for _, subset := range subsets { subsetStations := []string{} for _, station := range subset { subsetStations = append(subsetStations, stations[station]...) } if doesItCovers(subsetStations, &needed) { if len(subset) < bestSubsetCount { bestSubsetCount = len(subset) bestSubset = subset } } } return bestSubset } func doesItCovers(s []string, needed *[]string) bool { length := 0 for _, i := range *needed { for _, j := range s { if i == j { length++ break } } } return length >= len(*needed) } func subsetList(s []string) [][]string { subsets := [][]string{} for i := range s { subsets = append(subsets, []string{s[i]}) } subsetListRecursive(s, &subsets) return subsets } func subsetListRecursive(s []string, subsets *[][]string) { if len(s) == 1 { return } fullElements := []string{} // for _, element := range s { // fullElements = append(fullElements, element) // } fullElements = append(fullElements, s...) // fmt.Println(stringExist(subsets, fullElements)) if !stringExist(subsets, fullElements) { *subsets = append(*subsets, fullElements) } tempslice := make([]string, len(s)) for e := range s { copy(tempslice[:e], s[:e]) t := append(tempslice[:e], s[e+1:]...) subsetListRecursive(t, subsets) } } func stringExist(s *[][]string, e []string) bool { flag := true for _, slice := range *s { if len(slice) == len(e) { flag = true for i := range e { if slice[i] != e[i] { flag = false break } } if flag { return true } } } return false } func findStationsGreedy(needed []string, stations map[string][]string) []string { tempneeded := make([]string, len(needed)) copy(tempneeded, needed) // TODO: it doesn't kill if we check if all the needed states are offered by the stations finalStations := []string{} // go until we find all the needed states for len(tempneeded) != 0 { // loop through every station to find the one that covers the most states in needed var bestStation string stateCovered := []string{} for station, states := range stations { covered, n := slicesIntersection(states, tempneeded) if n > len(stateCovered) { bestStation = station stateCovered = covered } } // remove added states from needed for _, i := range stateCovered { for index, j := range tempneeded { if i == j { tempneeded = append(tempneeded[:index], tempneeded[index+1:]...) } } } // add the best station that we found in this iteration finalStations = append(finalStations, bestStation) } return finalStations } func slicesIntersection(s1 []string, s2 []string) ([]string, int) { inboth := []string{} count := 0 for _, i := range s1 { for _, j := range s2 { if i == j { inboth = append(inboth, i) count++ } } } return inboth, count }
non-member
// Copyright 2020 Delving B.V. // // 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 domain import ( "context" "fmt" "net/http" "unicode" ) type orgIDKey struct{} var ( // MaxLengthID the maximum length of an identifier MaxLengthID = 12 // protected organization names protected = []OrganizationID{ OrganizationID("public"), OrganizationID("all"), } ) type OrganizationFilter struct { // OffSet is the start of the results returned OffSet int // Limit is the number of items returned from the filter Limit int // Org can be used to filter the results based on the filled in value. // This is mostly useful if you want to filter by attributes.. Org Organization } // OrganizationID represents a short identifier for an Organization. // // The maximum length is MaxLengthID. // // In JSON the OrganizationID is represented as 'orgID'. type OrganizationID string // Organization is a basic building block for storing information. // Everything that is stored by ikuzo must have an organization.ID as part of its metadata. type Organization struct { ID OrganizationID `json:"orgID"` Config OrganizationConfig `json:"config"` } // NewOrganizationID returns an OrganizationID and an error if the supplied input is invalid. func NewOrganizationID(input string) (OrganizationID, error) { id := OrganizationID(input) if err := id.Valid(); err != nil { return OrganizationID(""), err } return id, nil } // Valid validates the identifier. // // - ErrIDTooLong is returned when ID is too long // // - ErrIDInvalidCharacter is returned when ID contains non-letters // func (id OrganizationID) Valid() error { if id == "" { return ErrIDCannotBeEmpty } if len(id) > MaxLengthID { return ErrIDTooLong } for _, p := range protected { if id == p { return ErrIDExists } } for _, r := range id { if r == '-' { continue } // allow letters and numbers if unicode.IsLetter(r) || unicode.IsNumber(r) { continue } return ErrIDInvalidCharacter } return nil } // String returns the OrganizationID as a string func (id OrganizationID) String() string { return string(id) } // RawID returns the raw direct identifier string for an Organization func (o *Organization) RawID() string { return o.ID.String() } func (o *Organization) NewDatasetURI(spec string) string { return fmt.Sprintf(o.Config.RDF.MintDatasetURL, o.Config.RDF.RDFBaseURL, spec) } // GetOrganizationID retrieves an OrganizationID from a *http.Request. // // This orgID is set by middleware and available for each request func GetOrganizationID(r *http.Request) OrganizationID { org, ok := GetOrganization(r) if ok { return org.ID } return "" } // GetOrganization retrieves an Organization from a *http.Request. // // This Organization is set by middleware and available for each request func GetOrganization(r *http.Request) (Organization, bool) { rawOrg := r.Context().Value(orgIDKey{}) if rawOrg != nil { organization, ok := rawOrg.(Organization) if ok { return organization, true } } return Organization{}, false } // SetOrganizationID sets the orgID in the context of a *http.Request // // This function is called by the middleware func SetOrganizationID(r *http.Request, orgID string) *http.Request { return r.WithContext(context.WithValue(r.Context(), orgIDKey{}, orgID)) } // SetOrganization sets the orgID in the context of a *http.Request // // This function is called by the middleware func SetOrganization(r *http.Request, org *Organization) *http.Request { return r.WithContext(context.WithValue(r.Context(), orgIDKey{}, *org)) }
member
package leetcode import ( "testing" "github.com/stretchr/testify/assert" "github.com/lijinglin3/algorithm-go/leetcode" ) func TestLevelOrder(t *testing.T) { cases := []*leetcode.Node{ leetcode.NodeExample1, {}, nil, } results := [][][]int{ {{0}, {1, 2, 3}, {4, 5, 6}}, {{0}}, nil, } for i := range cases { assert.Equal(t, results[i], levelOrder(cases[i])) } }
non-member
package usercommands import ( "fmt" "github.com/volte6/gomud/mobs" "github.com/volte6/gomud/rooms" "github.com/volte6/gomud/users" ) func Zap(rest string, user *users.UserRecord, room *rooms.Room) (bool, error) { if rest != `` { playerId, mobId := room.FindByName(rest) if mobId > 0 { mob := mobs.GetInstance(mobId) if mob == nil { user.SendText("Zap Mob not found.") return true, nil } user.SendText(fmt.Sprintf(`You zap <ansi fg="mobname">%s</ansi> with a bolt of lightning!`, mob.Character.Name)) room.SendText(fmt.Sprintf(`<ansi fg="username">%s</ansi> zaps <ansi fg="mobname">%s</ansi> with a bolt of lightning!`, user.Character.Name, mob.Character.Name), user.UserId) mob.Character.Health = 1 return true, nil } if playerId > 0 { if u := users.GetByUserId(playerId); u != nil { user.SendText(fmt.Sprintf(`You zap <ansi fg="username">%s</ansi> with a bolt of lightning!`, u.Character.Name)) room.SendText(fmt.Sprintf(`<ansi fg="username">%s</ansi> zaps <ansi fg="username">%s</ansi> with a bolt of lightning!`, user.Character.Name, u.Character.Name), user.UserId, u.UserId) u.SendText(fmt.Sprintf(`<ansi fg="username">%s</ansi> zaps you with a bolt of lightning!`, user.Character.Name)) u.Character.Health = 1 return true, nil } } } if user.Character.Aggro == nil || user.Character.Aggro.MobInstanceId == 0 { user.SendText("You are not in combat.") return true, nil } mob := mobs.GetInstance(user.Character.Aggro.MobInstanceId) if mob == nil { user.SendText("Zap Mob not found.") return true, nil } user.SendText(fmt.Sprintf(`You zap <ansi fg="mobname">%s</ansi> with a bolt of lightning!`, mob.Character.Name)) room.SendText(fmt.Sprintf(`<ansi fg="username">%s</ansi> zaps <ansi fg="mobname">%s</ansi> with a bolt of lightning!`, user.Character.Name, mob.Character.Name), user.UserId) mob.Character.Health = 1 return true, nil }
non-member
package api import ( "encoding/json" "net/http" "testing" "github.com/photoprism/photoprism/internal/i18n" "github.com/stretchr/testify/assert" ) func TestCancelImport(t *testing.T) { t.Run("successful request", func(t *testing.T) { app, router, _ := NewApiTest() CancelImport(router) r := PerformRequest(app, "DELETE", "/api/v1/import") var resp i18n.Response if err := json.Unmarshal(r.Body.Bytes(), &resp); err != nil { t.Fatal(err) } assert.True(t, resp.Success()) assert.Equal(t, i18n.Msg(i18n.MsgImportCanceled), resp.Msg) assert.Equal(t, i18n.Msg(i18n.MsgImportCanceled), resp.String()) assert.Equal(t, http.StatusOK, r.Code) assert.Equal(t, http.StatusOK, resp.Code) }) }
non-member
package configuration /* 实现common.Configuration接口 应用端通过System获取接口对象 */ import ( "github.com/muidea/magicCenter/common" "github.com/muidea/magicCenter/common/configuration/bll" ) func init() { localConfigurationMap = make(map[string]common.Configuration) } // GetConfiguration 获取指定的Configuration func GetConfiguration(id string) common.Configuration { cfg, found := localConfigurationMap[id] if !found { cfg = createConfiguration(id) localConfigurationMap[id] = cfg } return cfg } var localConfigurationMap map[string]common.Configuration // CreateConfiguration 创建Configuration func createConfiguration(id string) common.Configuration { s := &impl{id: id} s.configProperityMap = map[string]string{} return s } type impl struct { id string configProperityMap map[string]string } func (instance *impl) ID() string { return instance.id } func (instance *impl) LoadConfig(items []string) { instance.configProperityMap = bll.GetConfigurations(instance.id, items) } // GetOption 获取指定的配置项 func (instance *impl) GetOption(name string) (string, bool) { value, found := instance.configProperityMap[name] if !found { return bll.GetConfiguration(instance.id, name) } return value, found } // SetOption 设置指定配置项 func (instance *impl) SetOption(name, value string) bool { // 如果值没有变化则直接返回成功 oldValue, found := instance.configProperityMap[name] if found && oldValue == value { return true } if bll.UpdateConfiguration(instance.id, name, value) { if found { // 如果之前已经在内存中Load过了,这里也需要把内存中得信息更新一下 instance.configProperityMap[name] = value } return true } return false } func (instance *impl) UpdateOptions(opts map[string]string) bool { ret := bll.UpdateConfigurations(instance.id, opts) if ret { for k, v := range opts { instance.configProperityMap[k] = v } } return ret }
member
package model import ( "strings" ) func MarketConverter(market, typ string) (string, string) { var x, y string if strings.Index(strings.ToUpper(market), "/") >= 0 { arr := strings.Split(strings.ToUpper(market), "/") x = arr[0] y = arr[1] } else if strings.Index(strings.ToUpper(market), "-") >= 0 { arr := strings.Split(strings.ToUpper(market), "-") x = arr[1] y = arr[0] } else { if strings.ToUpper(market)[len(market)-1] == 'T' { x = strings.ToUpper(market)[:len(market)-4] y = strings.ToUpper(market)[len(market)-4:] } else { x = strings.ToUpper(market)[:len(market)-3] y = strings.ToUpper(market)[len(market)-3:] } } if strings.ToUpper(typ) == "BUY" { return y, x } else { return x, y } } func InvMarketConverter(market, typ string) (string, string) { var x, y string if strings.Index(strings.ToUpper(market), "-") >= 0 { arr := strings.Split(strings.ToUpper(market), "-") x = arr[0] y = arr[1] } else { if strings.ToUpper(market)[len(market)-1] == 'T' { x = strings.ToUpper(market)[:len(market)-4] y = strings.ToUpper(market)[len(market)-4:] } else { x = strings.ToUpper(market)[:len(market)-3] y = strings.ToUpper(market)[len(market)-3:] } } if strings.ToUpper(typ) == "BUY" { return y, x } else { return x, y } } //First Returned is the Base Currency, Second is Quote Currency //out.BaseCurrency, out.QuoteCurrency = model.MarketConverter(txn.Market, txn.Type) //var name = []string{ //"ETHBTC", //"ETHBTC", //"LTCBTC", //"BNBBTC", //"NEOBTC", //"QTUMETH", //"EOSETH", //"SNTETH", //"BNTETH", //"BCHBTC", //"GASBTC", //"BNBETH", //"BTCUSDT", //"ETHUSDT", //"OAXETH", //"DNTETH", //"MCOETH", //"MCOBTC", //"WTCBTC", //"WTCETH", //"LRCBTC", //"LRCETH", //"QTUMBTC", //"YOYOWBTC", //"OMGBTC", //"OMGETH", //"ZRXBTC", //"ZRXETH", //"STRATBTC", //"STRATETH", //"SNGLSBTC", //"SNGLSETH", //"ETHOSBTC", //"ETHOSETH", //"KNCBTC", //"KNCETH", //"FUNBTC", //"FUNETH", //"SNMBTC", //"SNMETH", //"NEOETH", //"MIOTABTC", //"MIOTAETH", //"LINKBTC", //"LINKETH", //"XVGBTC", //"XVGETH", //"SALTBTC", //"SALTETH", //"MDABTC", //"MDAETH", //"MTLBTC", //"MTLETH", //"SUBBTC", //"SUBETH", //"EOSBTC", //"SNTBTC", //"ETCETH", //"ETCBTC", //"MTHBTC", //"MTHETH", //"ENGBTC", //"ENGETH", //"DNTBTC", //"ZECBTC", //"ZECETH", //"BNTBTC", //"ASTBTC", //"ASTETH", //"DASHBTC", //"DASHETH", //"OAXBTC", //"BTGBTC", //"BTGETH", //"EVXBTC", //"EVXETH", //"REQBTC", //"REQETH", //"VIBBTC", //"VIBETH", //"TRXBTC", //"TRXETH", //"POWRBTC", //"POWRETH", //"ARKBTC", //"ARKETH", //"YOYOWETH", //"XRPBTC", //"XRPETH", //"MODBTC", //"MODETH", //"ENJBTC", //"ENJETH", //"STORJBTC", //"STORJETH", //"BNBUSDT", //"YOYOWBNB", //"POWRBNB", //"KMDBTC", //"KMDETH", //"NULSBNB", //"RCNBTC", //"RCNETH", //"RCNBNB", //"NULSBTC", //"NULSETH", //"RDNBTC", //"RDNETH", //"RDNBNB", //"XMRBTC", //"XMRETH", //"DLTBNB", //"WTCBNB", //"DLTBTC", //"DLTETH", //"AMBBTC", //"AMBETH", //"AMBBNB", //"BCHETH", //"BCHUSDT", //"BCHBNB", //"BATBTC", //"BATETH", //"BATBNB", //"BCPTBTC", //"BCPTETH", //"BCPTBNB", //"ARNBTC", //"ARNETH", //"GVTBTC", //"GVTETH", //"CDTBTC", //"CDTETH", //"GXSBTC", //"GXSETH", //"NEOUSDT", //"NEOBNB", //"POEBTC", //"POEETH", //"QSPBTC", //"QSPETH", //"QSPBNB", //"BTSBTC", //"BTSETH", //"BTSBNB", //"XZCBTC", //"XZCETH", //"XZCBNB", //"LSKBTC", //"LSKETH", //"LSKBNB", //"TNTBTC", //"TNTETH", //"FUELBTC", //"FUELETH", //"MANABTC", //"MANAETH", //"BCDBTC", //"BCDETH", //"DGDBTC", //"DGDETH", //"MIOTABNB", //"ADXBTC", //"ADXETH", //"ADXBNB", //"ADABTC", //"ADAETH", //"PPTBTC", //"PPTETH", //"CMTBTC", //"CMTETH", //"CMTBNB", //"XLMBTC", //"XLMETH", //"XLMBNB", //"CNDBTC", //"CNDETH", //"CNDBNB", //"LENDBTC", //"LENDETH", //"WABIBTC", //"WABIETH", //"WABIBNB", //"LTCETH", //"LTCUSDT", //"LTCBNB", //"TNBBTC", //"TNBETH", //"WAVESBTC", //"WAVESETH", //"WAVESBNB", //"GTOBTC", //"GTOETH", //"GTOBNB", //"ICXBTC", //"ICXETH", //"ICXBNB", //"OSTBTC", //"OSTETH", //"OSTBNB", //"ELFBTC", //"ELFETH", //"AIONBTC", //"AIONETH", //"AIONBNB", //"NEBLBTC", //"NEBLETH", //"NEBLBNB", //"BRDBTC", //"BRDETH", //"BRDBNB", //"MCOBNB", //"EDOBTC", //"EDOETH", //"WINGSBTC", //"WINGSETH", //"NAVBTC", //"NAVETH", //"NAVBNB", //"LUNBTC", //"LUNETH", //"APPCBTC", //"APPCETH", //"APPCBNB", //"VIBEBTC", //"VIBEETH", //"RLCBTC", //"RLCETH", //"RLCBNB", //"INSBTC", //"INSETH", //"PIVXBTC", //"PIVXETH", //"PIVXBNB", //"IOSTBTC", //"IOSTETH", //"STEEMBTC", //"STEEMETH", //"STEEMBNB", //"NANOBTC", //"NANOETH", //"NANOBNB", //"VIABTC", //"VIAETH", //"VIABNB", //"BLZBTC", //"BLZETH", //"BLZBNB", //"AEBTC", //"AEETH", //"AEBNB", //"NCASHBTC", //"NCASHETH", //"NCASHBNB", //"POABTC", //"POAETH", //"POABNB", //"ZILBTC", //"ZILETH", //"ZILBNB", //"ONTBTC", //"ONTETH", //"ONTBNB", //"STORMBTC", //"STORMETH", //"STORMBNB", //"QTUMBNB", //"QTUMUSDT", //"XEMBTC", //"XEMETH", //"XEMBNB", //"WANBTC", //"WANETH", //"WANBNB", //"WPRBTC", //"WPRETH", //"QLCBTC", //"QLCETH", //"SYSBTC", //"SYSETH", //"SYSBNB", //"QLCBNB", //"GRSBTC", //"GRSETH", //"ADAUSDT", //"ADABNB", //"CLOAKBTC", //"CLOAKETH", //"GNTBTC", //"GNTETH", //"GNTBNB", //"LOOMBTC", //"LOOMETH", //"LOOMBNB", //"XRPUSDT", //"REPBTC", //"REPETH", //"REPBNB", //"TUSDBTC", //"TUSDETH", //"TUSDBNB", //"ZENBTC", //"ZENETH", //"ZENBNB", //"SKYBTC", //"SKYETH", //"SKYBNB", //"EOSUSDT", //"EOSBNB", //"CVCBTC", //"CVCETH", //"CVCBNB", //"THETABTC", //"THETAETH", //"THETABNB", //"XRPBNB", //"TUSDUSDT", //"MIOTAUSDT", //"XLMUSDT", //"IOTXBTC", //"IOTXETH", //"QKCBTC", //"QKCETH", //"AGIBTC", //"AGIETH", //"AGIBNB", //"NXSBTC", //"NXSETH", //"NXSBNB", //"ENJBNB", //"DATABTC", //"DATAETH", //"ONTUSDT", //"TRXBNB", //"TRXUSDT", //"ETCUSDT", //"ETCBNB", //"ICXUSDT", //"SCBTC", //"SCETH", //"SCBNB", //"NPXSBTC", //"NPXSETH", //"KEYBTC", //"KEYETH", //"NASBTC", //"NASETH", //"NASBNB", //"MFTBTC", //"MFTETH", //"MFTBNB", //"DENTBTC", //"DENTETH", //"ARDRBTC", //"ARDRETH", //"ARDRBNB", //"NULSUSDT", //"HOTBTC", //"HOTETH", //"VETBTC", //"VETETH", //"VETUSDT", //"VETBNB", //"DOCKBTC", //"DOCKETH", //"POLYBTC", //"POLYBNB", //"PHXBTC", //"PHXETH", //"PHXBNB", //"HCBTC", //"HCETH", //"GOBTC", //"GOBNB", //"PAXBTC", //"PAXBNB", //"PAXUSDT", //"PAXETH", //"RVNBTC", //"RVNBNB", //}
non-member
package newtype import "errors" var ( ErrTypeMissmatch = errors.New("type missmatch") ErrUnknownType = errors.New("unknown type") )
non-member
package teaconfigs import ( "github.com/go-yaml/yaml" "github.com/iwind/TeaGo/Tea" "github.com/iwind/TeaGo/lists" "github.com/iwind/TeaGo/logs" "github.com/iwind/TeaGo/types" "io/ioutil" "path/filepath" "strings" ) // 本地监听服务配置 type ListenerConfig struct { Key string // 区分用的Key Address string Http bool SSL *SSLConfig Servers []*ServerConfig } // 从配置文件中分析配置 func ParseConfigs() ([]*ListenerConfig, error) { listenerConfigMap := map[string]*ListenerConfig{} configsDir := Tea.ConfigDir() files, err := filepath.Glob(configsDir + Tea.DS + "*.proxy.conf") if err != nil { return nil, err } for _, configFile := range files { configData, err := ioutil.ReadFile(configFile) if err != nil { logs.Error(err) continue } serverConfig := &ServerConfig{} err = yaml.Unmarshal(configData, serverConfig) if err != nil { logs.Error(err) continue } err = serverConfig.Validate() if err != nil { logs.Error(err) continue } if !serverConfig.On { continue } // HTTP if serverConfig.Http { for _, address := range serverConfig.Listen { // 是否有端口 if strings.Index(address, ":") < 0 { address += ":80" } key := "http://" + address listenerConfig, found := listenerConfigMap[key] if !found { listenerConfig = &ListenerConfig{ Key: key, Address: address, Servers: []*ServerConfig{serverConfig}, } listenerConfigMap[key] = listenerConfig } else { listenerConfig.Servers = append(listenerConfig.Servers, serverConfig) } listenerConfig.Http = true } } // HTTPS if serverConfig.SSL != nil && serverConfig.SSL.On { serverConfig.SSL.Validate() for _, address := range serverConfig.SSL.Listen { // 是否有端口 if strings.Index(address, ":") < 0 { address += ":443" } key := "https://" + address listenerConfig, found := listenerConfigMap[key] if !found { listenerConfig = &ListenerConfig{ Key: key, Address: address, Servers: []*ServerConfig{serverConfig}, } listenerConfigMap[key] = listenerConfig } else { listenerConfig.Servers = append(listenerConfig.Servers, serverConfig) } listenerConfig.Http = false listenerConfig.SSL = serverConfig.SSL } } } listenerConfigArray := []*ListenerConfig{} for _, listenerConfig := range listenerConfigMap { listenerConfigArray = append(listenerConfigArray, listenerConfig) } return listenerConfigArray, nil } // 获取当前监听服务的端口 func (this *ListenerConfig) Port() int { index := strings.LastIndex(this.Address, ":") if index < 0 { return 0 } return types.Int(this.Address[index+1:]) } // 添加服务 func (this *ListenerConfig) AddServer(serverConfig *ServerConfig) { this.Servers = append(this.Servers, serverConfig) } // 根据域名来查找匹配的域名 // @TODO 把查找的结果加入缓存 func (this *ListenerConfig) FindNamedServer(name string) (serverConfig *ServerConfig, serverName string) { countServers := len(this.Servers) if countServers == 0 { return nil, "" } // 如果只有一个server,则默认为这个 if countServers == 1 { server := this.Servers[0] matchedName, matched := server.MatchName(name) if matched { if len(matchedName) > 0 { return server, matchedName } else { return server, name } } // 匹配第一个域名 firstName := server.FirstName() if len(firstName) > 0 { return server, firstName } return server, name } // 精确查找 for _, server := range this.Servers { if lists.Contains(server.Name, name) { return server, name } } // 模糊查找 for _, server := range this.Servers { if _, matched := server.MatchName(name); matched { return server, name } } // 如果没有找到,则匹配到第一个 server := this.Servers[0] firstName := server.FirstName() if len(firstName) > 0 { return server, firstName } return server, name }
member
package xhttp import ( "github.com/gin-gonic/gin" "net/http" ) type Response struct { Msg string `json:"msg"` Data interface{} `json:"data"` } func SuccessResponse(ctx *gin.Context, data interface{}) { ctx.JSON(http.StatusOK, Response{ Msg: "OK", Data: data, }) } func BadRequestResponse(ctx *gin.Context, err error) { ctx.JSON(http.StatusBadRequest, Response{ Msg: err.Error(), }) } func UnauthorizedResponse(ctx *gin.Context, err error) { ctx.JSON(http.StatusUnauthorized, Response{ Msg: err.Error(), }) } func ForbiddenResponse(ctx *gin.Context, err error) { ctx.JSON(http.StatusForbidden, Response{ Msg: err.Error(), }) } func NotFoundResponse(ctx *gin.Context, err error) { ctx.JSON(http.StatusNotFound, Response{ Msg: err.Error(), }) } func InternalServerErrorResponse(ctx *gin.Context, err error) { ctx.JSON(http.StatusInternalServerError, Response{ Msg: err.Error(), }) } func NotImplementedResponse(ctx *gin.Context, err error) { ctx.JSON(http.StatusNotImplemented, Response{ Msg: err.Error(), }) } func ServiceUnavailableResponse(ctx *gin.Context, err error) { ctx.JSON(http.StatusServiceUnavailable, Response{ Msg: err.Error(), }) } func GatewayTimeoutResponse(ctx *gin.Context, err error) { ctx.JSON(http.StatusGatewayTimeout, Response{ Msg: err.Error(), }) }
non-member
package main import ( "fmt" "os" "github.com/sonm-io/core/insonmnia/worker/gpu" ) var appVersion string func main() { fmt.Printf("sonm lspgu %s\r\n", appVersion) cards, err := gpu.CollectDRICardDevices() if err != nil { fmt.Printf("cannot collect card devces: %v\r\n", err) os.Exit(1) } for _, card := range cards { fmt.Printf("Card: %s\r\n", card.Path) if m, err := card.Metrics(); err == nil { fmt.Printf(" t = %.1f (fan = %.1f%%)\r\n", m.Temperature, m.Fan) fmt.Printf(" power = %.1fW\r\n", m.Power) } else { fmt.Printf(" metrics is not available\r\n") } fmt.Printf(" vid=%d did=%d\r\n", card.VendorID, card.DeviceID) fmt.Printf(" maj=%d min=%d\r\n", card.Major, card.Minor) fmt.Printf(" PCI=%s\r\n", card.PCIBusID) for _, rel := range card.Devices { fmt.Printf(" %s\r\n", rel) } } }
non-member
package myzap import ( "os" "go.uber.org/zap" "go.uber.org/zap/zapcore" "github.com/natefinch/lumberjack" ) type ZapLogger struct { Logger *zap.Logger } func NewLogger() *ZapLogger { return NewLoggerWithEncoder(zapcore.ISO8601TimeEncoder, GrpcCallerEncoder) } func NewLoggerWithEncoder(timeEncoder zapcore.TimeEncoder, callerEncoder zapcore.CallerEncoder) *ZapLogger { level := zap.InfoLevel var syncers []zapcore.WriteSyncer logger := &lumberjack.Logger{ Filename: "/tmp/playground/log.log", MaxSize: 100, MaxBackups: 500, MaxAge: 10000000, Compress: false, } syncers = append(syncers, zapcore.AddSync(logger)) syncers = append(syncers, zapcore.AddSync(os.Stdout)) ws := zapcore.NewMultiWriteSyncer(syncers...) encoderConf := zap.NewProductionEncoderConfig() encoderConf.EncodeTime = timeEncoder encoderConf.EncodeCaller = callerEncoder encoder := zapcore.NewConsoleEncoder(encoderConf) return &ZapLogger{ Logger: zap.New( zapcore.NewCore(encoder, ws, zap.NewAtomicLevelAt(level)), zap.AddCaller(), zap.AddCallerSkip(2), ), } }
non-member
package transxchange import "errors" type RouteSection struct { ID string `xml:"id,attr"` RouteLinks []RouteLink `xml:"RouteLink"` } func (r *RouteSection) GetRouteLink(ID string) (*RouteLink, error) { for _, routeLink := range r.RouteLinks { if routeLink.ID == ID { return &routeLink, nil } } return nil, errors.New("could not find route link") } type RouteLink struct { ID string `xml:"id,attr"` CreationDateTime string `xml:",attr"` ModificationDateTime string `xml:",attr"` FromStop string `xml:"From>StopPointRef"` ToStop string `xml:"To>StopPointRef"` Distance int Track []Location `xml:"Track>Mapping>Location"` }
non-member
package integration import ( "github.com/hellgate75/k8s-deploy/log" "github.com/hellgate75/k8s-deploy/model" ) type kubernetesFilesRepositoryManager struct { repository model.Repository dataFolder string logger log.Logger files []model.KubernetesFileInfo } const ( repositoryKubernetesFilesIndexTemplate = "%s%crepositories%c%s%ckubefiles%cindex.%v" repositoryKubernetesFilesFolderTemplate = "%s%crepositories%c%s%ckubefiles" repositoryKubernetesFileDetailsIndexTemplate = "%s%crepositories%c%s%ckubefiles%c%s%cindex.%v" repositoryKubernetesFileDetailsFolderTemplate = "%s%crepositories%c%s%ckubefiles%c%s" repositoryKubernetesFileVersionsDetailsFolderTemplate = "%s%crepositories%c%s%ckubefiles%c%s%c%s" ) func (k *kubernetesFilesRepositoryManager) VerifyKubernetesFile(name string, version string) error { panic("implement me") } func (k *kubernetesFilesRepositoryManager) InstallKubernetesFile(name string, version string, file string) error { panic("implement me") } func (k *kubernetesFilesRepositoryManager) DeleteKubernetesFileVersion(name string, version string) error { panic("implement me") } func (k *kubernetesFilesRepositoryManager) DeleteEntireKubernetesFile(name string, version string) error { panic("implement me") } func (k *kubernetesFilesRepositoryManager) GetKubernetesFileVersionTemplate(name string, version string) (string, error) { panic("implement me") } func (k *kubernetesFilesRepositoryManager) UpdateExistingKubernetesFile(name string, version string, file string) error { panic("implement me") } func (k *kubernetesFilesRepositoryManager) GetKubernetesFileVersions(name string) ([]model.Version, error) { panic("implement me") } func (k *kubernetesFilesRepositoryManager) GetKubernetesFileProjectVersions(name string) ([]model.ProjectKubeFile, error) { panic("implement me") } func (k *kubernetesFilesRepositoryManager) DeployInstallKubernetesFile(name string, version string) (string, error) { panic("implement me") } func (k *kubernetesFilesRepositoryManager) DeployUpgradeKubernetesFile(name string, version string, force bool) (string, error) { panic("implement me") } func (k *kubernetesFilesRepositoryManager) GetInstalledKubernetesFileVersion(name string) (model.Version, error) { panic("implement me") } func (k *kubernetesFilesRepositoryManager) GetInstalledKubernetesFileVersionDetails(name string, version string) (model.Version, error) { panic("implement me") } func (k *kubernetesFilesRepositoryManager) UnDeployInstalledKubernetesFile(name string) (model.Version, error) { panic("implement me") } func (k *kubernetesFilesRepositoryManager) init() (model.RepositoryKubernetesFilesManager, error) { files, err := loadKubernetesFiles(k.dataFolder, k.logger, k.repository.Name) if err != nil { return k, err } k.files = files return k, nil } func NewRepositoryKubernetesFilesManager(repository model.Repository, dataFolder string, logger log.Logger) (model.RepositoryKubernetesFilesManager, error) { return (&kubernetesFilesRepositoryManager{ repository: repository, dataFolder: dataFolder, logger: logger, files: make([]model.KubernetesFileInfo, 0), }).init() }
non-member
package sdk import ( "context" "encoding/json" "strings" ) const ( CampaignMinimumBudget = 1 CampaignMaximumBudget = 300 CampaignMaximumImpBudget = 100000 ) // Campaign is a QoL alias for campaigns.Campaign type Campaign struct { ID string `json:"id"` OwnerID string `json:"ownerID"` Active bool `json:"active"` Archived bool `json:"archived,omitempty"` Name string `json:"name"` Notes string `json:"notes,omitempty"` Budget float64 `json:"budget"` ImpBudget uint32 `json:"impBudget"` Created int64 `json:"created"` Scheduled bool `json:"scheduled"` Start int64 `json:"start"` End int64 `json:"end"` Segments []string `json:"segments,omitempty"` Adgroups []string `json:"adGroups,omitempty"` Apps map[string]*json.RawMessage `json:"apps,omitempty"` Searches []string `json:"searches,omitempty"` } // can't specify methods on aliased types func (c *Campaign) validateCampaign() (err error) { if c == nil { return ErrCampaignIsNil } if len(c.Name) == 0 { return ErrInvalidName } if c.Budget < CampaignMinimumBudget && c.ImpBudget == 0 { return ErrInvalidBudget } if c.ImpBudget > CampaignMaximumImpBudget { return ErrInvalidImpBudget } if c.Scheduled && c.Start >= c.End { return ErrInvalidSchedule } return nil } // CreateCampaign will create a campaign for a given user ID func (c *Client) CreateCampaign(ctx context.Context, uid string, cmp *Campaign) (string, error) { return c.createCampaign(ctx, uid, cmp, false) } // CreateDraftCampaign will create a draft campaign for a given user ID func (c *Client) CreateDraftCampaign(ctx context.Context, uid string, cmp *Campaign) (string, error) { return c.createCampaign(ctx, uid, cmp, true) } func (c *Client) createCampaign(ctx context.Context, uid string, cmp *Campaign, drafts bool) (cid string, err error) { if uid == "" { err = ErrMissingUID return } var ( resp idOrDataResp ep = "campaigns/byAdv/" ) if drafts { ep = "campaignDrafts/" } for _, app := range DefaultApps { if _, ok := cmp.Apps[app.Name()]; !ok { SetApp(cmp, app) } } if err = c.rawPost(ctx, ep+uid, cmp, &resp); err != nil { return } cid = resp.String() return } // GetCampaign will get a campaign by campaign id func (c *Client) GetCampaign(ctx context.Context, cid string) (*Campaign, error) { return c.getCampaign(ctx, cid, false) } // GetDraftCampaign will get a campaign by campaign id func (c *Client) GetDraftCampaign(ctx context.Context, cid string) (*Campaign, error) { return c.getCampaign(ctx, cid, true) } func (c *Client) getCampaign(ctx context.Context, cid string, drafts bool) (cmp *Campaign, err error) { if cid == "" { err = ErrMissingCID return } var ( resp struct { Data *Campaign `json:"data"` } ep = "campaigns/byCID/" ) if drafts { ep = "campaignDraft/" } if err = c.rawGet(ctx, ep+cid, &resp); err != nil { return } cmp = resp.Data return } // UpdateCampaign will update a campaign func (c *Client) UpdateCampaign(ctx context.Context, cmp *Campaign) error { return c.updateCampaign(ctx, cmp, false) } // UpdateDraftCampaign will update a draft campaign func (c *Client) UpdateDraftCampaign(ctx context.Context, cmp *Campaign) error { return c.updateCampaign(ctx, cmp, true) } // updateCampaign will update a campaign func (c *Client) updateCampaign(ctx context.Context, cmp *Campaign, drafts bool) (err error) { var ( ep = "campaigns/byCID/" ) if drafts { ep = "campaignDraft/" } return c.rawPut(ctx, ep+cmp.ID, cmp, nil) } // DeleteCampaign will delete a campaign by it's ID func (c *Client) DeleteCampaign(ctx context.Context, cid string) error { return c.deleteCampaign(ctx, cid, false) } // DeleteDraftCampaign will delete a draft campaign by it's ID func (c *Client) DeleteDraftCampaign(ctx context.Context, cid string) error { return c.deleteCampaign(ctx, cid, true) } // deleteCampaign will delete a campaign by it's ID func (c *Client) deleteCampaign(ctx context.Context, cid string, drafts bool) (err error) { if cid == "" { err = ErrMissingCID return } ep := "campaigns/byCID/" if drafts { ep = "campaignDraft/" } return c.rawDelete(ctx, ep+cid, nil) } // ListCampaigns will list all the campaigns for a given user id func (c *Client) ListCampaigns(ctx context.Context, uid string) (map[string]*Campaign, error) { return c.listCampaigns(ctx, uid, false) } // ListDraftCampaigns will list all the draft campaigns for a given user id func (c *Client) ListDraftCampaigns(ctx context.Context, uid string) (map[string]*Campaign, error) { return c.listCampaigns(ctx, uid, true) } func (c *Client) listCampaigns(ctx context.Context, uid string, drafts bool) (cmps map[string]*Campaign, err error) { if uid == "" { err = ErrMissingUID return } var ( resp []*Campaign ep = "campaignsList/" ) if drafts { ep = "campaignDrafts/" } if err = c.rawGet(ctx, ep+uid, &resp); err != nil || len(resp) == 0 { return } cmps = make(map[string]*Campaign, len(resp)) for _, cmp := range resp { cmp.OwnerID = uid cmps[cmp.ID] = cmp } return } type CreateFullCampaignRequest struct { Campaign *Campaign `json:"campaign,omitempty"` // required Ads []*CreateAdRequest `json:"ads,omitempty"` // required CampaignApps []App `json:"campaignApps,omitempty"` Segments []*Segment `json:"segments,omitempty"` // optional ProximitySegment []*ProximitySegment `json:"proximitySegment,omitempty"` // optional IsDraft bool `json:"isDraft"` // this is only used for rollback adIDs []string } func (req *CreateFullCampaignRequest) validate() (err error) { if req == nil { return ErrRequestIsNil } if err = req.Campaign.validateCampaign(); err != nil { return } if len(req.Ads) == 0 { return ErrMissingAds } for _, ad := range req.Ads { if err = ad.validate(); err != nil { return } } for _, seg := range req.Segments { if seg.Name == "" { return ErrMissingSegName } } for _, seg := range req.ProximitySegment { if seg.Name == "" { return ErrMissingProxSegName } if len(seg.Locations) == 0 { return ErrMissingLocations } } return } // deletes any partially created resources func (req *CreateFullCampaignRequest) Rollback(c *Client) { cmp := req.Campaign ctx := context.Background() if cmp.ID != "" { c.deleteCampaign(ctx, cmp.ID, req.IsDraft) } for _, segID := range cmp.Segments { if strings.HasPrefix(segID, "px_") { c.DeleteProximitySegment(ctx, segID) } else { c.DeleteSegment(ctx, segID) } } for _, adID := range req.adIDs { c.DeleteAd(ctx, adID) } for _, agID := range cmp.Adgroups { c.DeleteAdGroup(ctx, agID) } } // CreateFullCampaign takes full control of the passed request, reusing it can cause races and/or crashes. // A new ADGroup will be created for this request and filled in with the ads, and appended to cmp.Adgroups. func (c *Client) CreateFullCampaign(ctx context.Context, uid string, req *CreateFullCampaignRequest) (cmp *Campaign, err error) { if uid == "" { return nil, err } if err = req.validate(); err != nil { return } defer func() { if err != nil { cmp = nil // should this be ran in a goroutine? req.Rollback(c) } }() cmp = req.Campaign cmp.OwnerID = uid for _, app := range req.CampaignApps { SetApp(cmp, app) } var agID string if agID, err = c.CreateAdGroup(ctx, uid, cmp.Name); err != nil { return } cmp.Adgroups = append(cmp.Adgroups, agID) var newAd *Ad for _, ad := range req.Ads { ad.GroupID = agID if newAd, err = c.CreateAd(ctx, uid, ad); err != nil { return } req.adIDs = append(req.adIDs, newAd.ID) } var segID string for _, seg := range req.Segments { if segID, err = c.CreateSegment(ctx, uid, seg); err != nil { return } cmp.Segments = append(cmp.Segments, segID) } for _, seg := range req.ProximitySegment { if segID, err = c.CreateProximitySegment(ctx, uid, seg); err != nil { return } cmp.Segments = append(cmp.Segments, segID) } if cmp.ID, err = c.createCampaign(ctx, uid, cmp, req.IsDraft); err != nil { return } return cmp, nil } // UpgradeCampaign will attempt to upgrade a draft campaign to a full campaign and returning new campaign id. // note that it may return an error and a campaign id if deleting the draft campaign fails after creating the full campaign. func (c *Client) UpgradeCampaign(ctx context.Context, uid, draftCampaignID string) (cid string, err error) { var cmp *Campaign if cmp, err = c.GetDraftCampaign(ctx, draftCampaignID); err != nil { return } if cid, err = c.CreateCampaign(ctx, uid, cmp); err == nil { err = c.DeleteDraftCampaign(ctx, draftCampaignID) } return }
member
package logg import "github.com/zerodha/logf" type LoggOpts struct { Debug bool Caller bool Color bool } func NewLogg(o LoggOpts) logf.Logger { loggConfig := logf.Opts{ EnableColor: o.Color, EnableCaller: o.Caller, } if o.Debug { loggConfig.Level = logf.DebugLevel } else { loggConfig.Level = logf.InfoLevel } return logf.New(loggConfig) }
non-member
package payreq import ( "fmt" "strings" "unicode" "github.com/btcsuite/btcd/chaincfg" ) // Currency is a type representing a cryptocurrency. It has a name and // parameters defining the chain of the cryptocurrency. type Currency struct { Name string Chaincfg *chaincfg.Params } var ( // liteCoinParams contains the custom parameters defined for the Litecoin chain. liteCoinParams = &chaincfg.Params{ Name: "mainnet", // Human-readable part for Bech32 encoded segwit addresses, as defined in // BIP 173. Bech32HRPSegwit: "ltc", // always ltc for main net // Address encoding magics (version bytes) PubKeyHashAddrID: 0x30, // starts with L ScriptHashAddrID: 0x32, // starts with M PrivateKeyID: 0xB0, // starts with 6 (uncompressed) or T (compressed) WitnessPubKeyHashAddrID: 0x06, // starts with p2 WitnessScriptHashAddrID: 0x0A, // starts with 7Xh } // liteCoinParamsTestnet contains the custom parameters defined for the Litecoin chain. liteCoinParamsTestnet = &chaincfg.Params{ Name: "testnet3", // Human-readable part for Bech32 encoded segwit addresses, as defined in // BIP 173. Bech32HRPSegwit: "tltc", // always tltc for test net // Address encoding magics PubKeyHashAddrID: 0x6f, // starts with m or n ScriptHashAddrID: 0x3a, // starts with Q WitnessPubKeyHashAddrID: 0x52, // starts with QW WitnessScriptHashAddrID: 0x31, // starts with T7n PrivateKeyID: 0xef, // starts with 9 (uncompressed) or c (compressed) } // liteCoinParamsSimnet contains the custom parameters defined for the Litecoin chain. liteCoinParamsSimnet = &chaincfg.Params{ Name: "simnet", // Human-readable part for Bech32 encoded segwit addresses, as defined in // BIP 173. Bech32HRPSegwit: "sltc", // always lsb for sim net // Address encoding magics PubKeyHashAddrID: 0x3f, // starts with S ScriptHashAddrID: 0x7b, // starts with s PrivateKeyID: 0x64, // starts with 4 (uncompressed) or F (compressed) WitnessPubKeyHashAddrID: 0x19, // starts with Gg WitnessScriptHashAddrID: 0x28, // starts with ? } // Btc represents the Bitcoin currency. Btc = Currency{ Name: "Bitcoin", Chaincfg: &chaincfg.MainNetParams, } // BtcTestnet represents the Bitcoin testnet currency. BtcTestnet = Currency{ Name: "Bitcoin Testnet", Chaincfg: &chaincfg.TestNet3Params, } // BtcSimnet represents the Bitcoin testnet currency. BtcSimnet = Currency{ Name: "Bitcoin Simnet", Chaincfg: &chaincfg.SimNetParams, } // Ltc represents the Litecoin currency. Ltc = Currency{ Name: "Litecoin", Chaincfg: liteCoinParams, } // LtcTestnet represents the Litecoin currency. LtcTestnet = Currency{ Name: "Litecoin Testnet", Chaincfg: liteCoinParamsTestnet, } // LtcSimnet represents the Litecoin currency. LtcSimnet = Currency{ Name: "Litecoin Simnet", Chaincfg: liteCoinParamsSimnet, } ) // bech32ToCurrency is a map of Bech32 HRPs back to their Currency. var bech32ToCurrency = map[string]Currency{ Btc.Chaincfg.Bech32HRPSegwit: Btc, BtcTestnet.Chaincfg.Bech32HRPSegwit: BtcTestnet, BtcSimnet.Chaincfg.Bech32HRPSegwit: BtcSimnet, Ltc.Chaincfg.Bech32HRPSegwit: Ltc, LtcTestnet.Chaincfg.Bech32HRPSegwit: LtcTestnet, LtcSimnet.Chaincfg.Bech32HRPSegwit: LtcSimnet, } // RateMap contains exchange rates between Currencies. var RateMap = map[Currency]map[Currency]float64{ Btc: map[Currency]float64{ Ltc: 10, }, BtcTestnet: map[Currency]float64{ LtcTestnet: 10, }, BtcSimnet: map[Currency]float64{ LtcSimnet: 10, }, Ltc: map[Currency]float64{ Btc: 0.1, }, LtcTestnet: map[Currency]float64{ BtcTestnet: 0.1, }, LtcSimnet: map[Currency]float64{ BtcSimnet: 0.1, }, } // GetCurrency returns the Currency for a Bech32 HRP. func GetCurrency(hrp string) (Currency, error) { // Check if Currency HRP is inside supported currencies. c, ok := bech32ToCurrency[hrp] if !ok { return Currency{}, fmt.Errorf("Invoice currency is not supported") } return c, nil } // GetCurrencyFromInvoice returns the Currency of a Lightning network Bolt11 // invoice without validating the checksum of the invoice. func GetCurrencyFromInvoice(bolt11 string) (Currency, error) { if strings.TrimSpace(bolt11) == "" { return Currency{}, fmt.Errorf("Lightning invoice is required") } // The Bech32 human-readable part for the currency is everything after the // first 'ln' until the first '1'. one := strings.IndexByte(bolt11, '1') if one < 3 || one+7 > len(bolt11) { return Currency{}, fmt.Errorf("Invalid index of 1") } hrp := bolt11[2:one] // Treat anything inside the HRP up to a digit as the currency prefix. amntIdx := strings.IndexFunc(hrp+"0", func(c rune) bool { return unicode.IsDigit(c) }) curHrp := hrp[:amntIdx] // Check if Currency HRP is inside supported currencies. return GetCurrency(curHrp) }
member
// +build linux package redir import ( "encoding/binary" "errors" "net" "syscall" ) const ( IPV6_TRANSPARENT = 0x4b IPV6_RECVORIGDSTADDR = 0x4a ) func setsockopt(c *net.UDPConn, addr string) error { isIPv6 := true host, _, err := net.SplitHostPort(addr) if err != nil { return err } ip := net.ParseIP(host) if ip != nil && ip.To4() != nil { isIPv6 = false } rc, err := c.SyscallConn() if err != nil { return err } rc.Control(func(fd uintptr) { err = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1) if err == nil { err = syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1) } if err == nil && isIPv6 { err = syscall.SetsockoptInt(int(fd), syscall.SOL_IPV6, IPV6_TRANSPARENT, 1) } if err == nil { err = syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_RECVORIGDSTADDR, 1) } if err == nil && isIPv6 { err = syscall.SetsockoptInt(int(fd), syscall.SOL_IPV6, IPV6_RECVORIGDSTADDR, 1) } }) return err } func getOrigDst(oob []byte, oobn int) (*net.UDPAddr, error) { msgs, err := syscall.ParseSocketControlMessage(oob[:oobn]) if err != nil { return nil, err } for _, msg := range msgs { if msg.Header.Level == syscall.SOL_IP && msg.Header.Type == syscall.IP_RECVORIGDSTADDR { ip := net.IP(msg.Data[4:8]) port := binary.BigEndian.Uint16(msg.Data[2:4]) return &net.UDPAddr{IP: ip, Port: int(port)}, nil } else if msg.Header.Level == syscall.SOL_IPV6 && msg.Header.Type == IPV6_RECVORIGDSTADDR { ip := net.IP(msg.Data[8:24]) port := binary.BigEndian.Uint16(msg.Data[2:4]) return &net.UDPAddr{IP: ip, Port: int(port)}, nil } } return nil, errors.New("cannot find origDst") }
non-member
package client import ( "context" "fmt" "strconv" "testing" "time" "github.com/ory/dockertest/v3" "github.com/stretchr/testify/require" "github.com/rudderlabs/rudder-go-kit/kafkaclient/testutil" "github.com/rudderlabs/rudder-go-kit/tcpproxy" "github.com/rudderlabs/rudder-go-kit/testhelper" "github.com/rudderlabs/rudder-go-kit/testhelper/docker/resource/kafka" "github.com/rudderlabs/rudder-go-kit/testhelper/rand" ) func BenchmarkCompression(b *testing.B) { proxyPort, err := testhelper.GetFreePort() require.NoError(b, err) var ( ctx = context.Background() topic = "foo_bar_topic" proxyHost = "localhost:" + strconv.Itoa(proxyPort) ) setupKafka := func(b *testing.B) string { pool, err := dockertest.NewPool("") require.NoError(b, err) kafkaContainer, err := kafka.Setup(pool, b, kafka.WithCustomAdvertisedListener(proxyHost)) require.NoError(b, err) return kafkaContainer.Brokers[0] } setupProxy := func(b *testing.B, kafkaAddr string, c Compression, bs int, bt time.Duration) ( *tcpproxy.Proxy, *Producer, ) { proxy := &tcpproxy.Proxy{ LocalAddr: proxyHost, RemoteAddr: kafkaAddr, } go proxy.Start(b) client, err := New("tcp", []string{proxy.LocalAddr}, Config{}) require.NoError(b, err) require.Eventuallyf(b, func() bool { err = client.Ping(ctx) return err == nil }, 30*time.Second, 100*time.Millisecond, "failed to connect to kafka: %v", err) producer, err := client.NewProducer(ProducerConfig{ Compression: c, BatchSize: bs, BatchTimeout: bt, }) require.NoError(b, err) return proxy, producer } run := func(addr string, comp Compression, value string, batchSize int, batchTimeout time.Duration) func(*testing.B) { return func(b *testing.B) { proxy, producer := setupProxy(b, addr, comp, batchSize, batchTimeout) kafkaCtx, kafkaCtxCancel := context.WithTimeout(context.Background(), 3*time.Minute) err = waitForKafka(kafkaCtx, topic, addr) kafkaCtxCancel() require.NoError(b, err) var ( noOfErrors int messages = make([]Message, 0, batchSize) ) for i := 0; i < batchSize; i++ { messages = append(messages, Message{ Key: []byte("my-key"), Value: []byte(value), Topic: topic, }) } b.ResetTimer() for i := 0; i < b.N; i++ { if err := producer.Publish(ctx, messages...); err != nil { noOfErrors++ } } b.StopTimer() _ = producer.Close(ctx) proxy.Stop() // stopping the proxy here to properly gather the metrics b.SetBytes(proxy.BytesReceived.Load()) b.ReportMetric(float64(proxy.BytesReceived.Load())/float64(b.N)/1024, "kb/op") b.ReportMetric(float64(noOfErrors), "errors") } } var ( compressionTypes = []Compression{CompressionNone, CompressionGzip, CompressionSnappy, CompressionLz4, CompressionZstd} compressionTypesMap = map[Compression]string{ CompressionNone: "none", CompressionGzip: "gzip", CompressionSnappy: "snappy", CompressionLz4: "lz4", CompressionZstd: "zstd", } batchSizes = []int{1, 100, 1000} batchTimeouts = []time.Duration{time.Nanosecond, time.Millisecond} values = []string{rand.String(1 << 10), rand.String(10 << 10), rand.String(100 << 10)} ) for _, comp := range compressionTypes { b.Run(compressionTypesMap[comp], func(b *testing.B) { kafkaAddr := setupKafka(b) // setup kafka only once per compression combination for _, value := range values { for _, batchSize := range batchSizes { for _, batchTimeout := range batchTimeouts { b.Run( fmt.Sprintf("%s-%d-%s", byteCount(len(value)), batchSize, batchTimeout), run(kafkaAddr, comp, value, batchSize, batchTimeout), ) } } } }) } } func byteCount(b int) string { const unit = 1000 if b < unit { return fmt.Sprintf("%dB", b) } div, exp := int64(unit), 0 for n := b / unit; n >= unit; n /= unit { div *= unit exp++ } return fmt.Sprintf("%.1f%cB", float64(b)/float64(div), "kMGTPE"[exp]) } func waitForKafka(ctx context.Context, topic, addr string) (err error) { tc := testutil.New("tcp", addr) for { select { case <-ctx.Done(): return fmt.Errorf("kafka not ready within context (%v): %v", ctx.Err(), err) case <-time.After(50 * time.Millisecond): var topics []testutil.TopicPartition topics, err = tc.ListTopics(ctx) if err != nil { continue } var found bool for _, top := range topics { if top.Topic == topic { found = true break } } if found { return nil } if err = tc.CreateTopic(ctx, topic, 1, 1); err != nil { continue } } } }
non-member
package main import ( "database/sql" "errors" "fmt" _ "github.com/go-sql-driver/mysql" ) type Storehouse struct { StoreCode string Capacity int } type ClothingInfo struct { ClothingCode string Size string Price int ClothingType string } type Supplier struct { SupplierCode string SupplierName string } type SupplySituation struct { ClothingCode string SupplierCode string Quality string } //数据库配置 const ( driverName = "mysql" userName = "root" password = "123456" ip = "127.0.0.1" port = "3306" databaseName = "third_week" ) var DB *sql.DB // DB数据库连接池 func ConnectToDatabase() error { var err error // 连接数据库 dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", userName, password, ip, port, databaseName) //打开数据库 DB, err = sql.Open(driverName, dataSourceName) if err != nil { return errors.New(fmt.Sprintf("连接数据库失败:%v", err)) } //设置数据库最大连接数 DB.SetConnMaxLifetime(10) //设置数据库最大闲置连接数 DB.SetMaxIdleConns(5) //验证连接 if err = DB.Ping(); err != nil { return errors.New(fmt.Sprintf("连接失败:%v", err)) } return nil } func InsertData(sqlStr string) error { //向数据表中插入数据 if DB == nil { return errors.New("数据库未连接") } tx, err := DB.Begin() //开启事务 if err != nil { tx.Rollback() // 回滚 return errors.New(fmt.Sprintf("开启事务失败%v", err)) } _, err = tx.Exec(sqlStr) if err != nil { tx.Rollback() // 回滚 return errors.New(fmt.Sprintf("插入失败:%v", err)) } tx.Commit() //提交事务 return nil } func readRows(rows *sql.Rows, tableName string) { // 读取数据 defer rows.Close() switch tableName { case "storehouse": info := Storehouse{} for rows.Next() { err := rows.Scan(&info.StoreCode, &info.Capacity) if err != nil { fmt.Println("读取失败!", err) } fmt.Println(info) } case "clothing_info": info := ClothingInfo{} for rows.Next() { err := rows.Scan(&info.ClothingCode, &info.Size, &info.Price, &info.ClothingType) if err != nil { fmt.Println("读取失败!", err) } fmt.Println(info) } case "supplier": info := Supplier{} for rows.Next() { err := rows.Scan(&info.SupplierCode, &info.SupplierName) if err != nil { fmt.Println("读取失败!", err) } fmt.Println(info) } case "supply_situation": info := SupplySituation{} for rows.Next() { err := rows.Scan(&info.ClothingCode, &info.SupplierCode, &info.Quality) if err != nil { fmt.Println("读取失败!", err) } fmt.Println(info) } } } func SelectData(tableName string, sqlStr string) error { //查询 if DB == nil { return errors.New("数据库未连接") } rows, err := DB.Query(sqlStr) if err != nil { return errors.New(fmt.Sprintf("查询失败:%v", err)) } readRows(rows, tableName) return nil } func UpdateData(sqlStr string) error { // 更新 if DB == nil { return errors.New("数据库未连接") } tx, err := DB.Begin() //开启事务 if err != nil { tx.Rollback() // 回滚 return errors.New(fmt.Sprintf("开启事务失败%v", err)) } _, err = tx.Exec(sqlStr) if err != nil { tx.Rollback() // 回滚 return errors.New(fmt.Sprintf("更新失败:%v", err)) } tx.Commit() //提交事务 return nil } func DeleteData(sqlStr string) error { // 删除 if DB == nil { return errors.New("数据库未连接") } tx, err := DB.Begin() //开启事务 if err != nil { tx.Rollback() // 回滚 return errors.New(fmt.Sprintf("开启事务失败%v", err)) } _, err = tx.Exec(sqlStr) if err != nil { tx.Rollback() // 回滚 return errors.New(fmt.Sprintf("更新失败:%v", err)) } tx.Commit() //提交事务 return nil } func main() { // 连接数据库 err := ConnectToDatabase() if err != nil { fmt.Println(err) } defer func() { if DB != nil { DB.Close() } }() //// 查询服装尺码为'S'且销售价格在100以下的服装信息 //err = SelectData("clothing_info", "SELECT * FROM clothing_info WHERE size='S' and price<100") //if err != nil { // fmt.Println(err) //} // //// 查询仓库容量最大的仓库信息。 //err = SelectData("storehouse", "SELECT * FROM storehouse WHERE capacity = (SELECT MAX(capacity) FROM storehouse)") //if err != nil { // fmt.Println(err) //} // //// 查询服装编码以‘A’开始开头的服装 //err = SelectData("clothing_info", "SELECT * FROM clothing_info WHERE clothing_code LIKE 'A%'") //if err != nil { // fmt.Println(err) //} // //// 查询服装质量等级有不合格的供应商信息。 //err = SelectData("supplier", "SELECT * FROM supplier WHERE supplier_code IN (SELECT supplier_code FROM supply_situation WHERE quality = '不合格')") //if err != nil { // fmt.Println(err) //} // //// 把服装尺寸为'S'的服装的销售价格均在原来基础上提高10%。 //err = UpdateData("UPDATE clothing_info SET price=price*(1+0.1) WHERE size='S'") //if err != nil { // fmt.Println(err) //} //// 删除所有服装质量等级不合格的供应情况。 //err = DeleteData("DELETE FROM supply_situation WHERE quality='不合格'") //if err != nil { // fmt.Println(err) //} // 向每张表插入一条记录。 // # 向storehouse表中插入一条数据 //err = InsertData("INSERT INTO storehouse (store_code,capacity) VALUES ('CK1006',6000)") //if err != nil { // fmt.Println(err) //} // # 向clothing_info表中插入一条数据 //err = InsertData("INSERT INTO clothing_info (clothing_code,size,price,clothing_type) VALUES ('CFZ00007','M',90,'C')") //if err != nil { // fmt.Println(err) //} //// # 向supplier表中插入一条数据 //err = InsertData("INSERT INTO supplier (supplier_code,supplier_name) VALUES ('GYS1006','供应商F')") //if err != nil { // fmt.Println(err) //} //// # 向supply_situation表中插入一条数据 //err = InsertData("INSERT INTO supply_situation (clothing_code,supplier_code,quality) VALUES ('CFZ00006','GYS1006','不合格')") //if err != nil { // fmt.Println(err) //} }
non-member
package cmd import ( "fmt" "github.com/cloudfauj/cloudfauj/api" "github.com/cloudfauj/cloudfauj/environment" "github.com/spf13/cobra" "github.com/spf13/viper" ) var envCreateCmd = &cobra.Command{ Use: "create --config PATH", Short: "Create a new Environment", Long: ` This command lets you create a new environment. You must provide a configuration to create the environment from. The config defines the underlying infrastructure to provision to manage different types of resources such as container orchestrator. At least 1 env must exist for an application to be deployed.`, RunE: runEnvCreateCmd, Example: "cloudfauj env create --config ./cloudfauj-env.yml", } func init() { envCreateCmd.Flags().String("config", "", "Configuration file to create an environment from") _ = envCreateCmd.MarkFlagRequired("config") } func runEnvCreateCmd(cmd *cobra.Command, args []string) error { apiClient, err := api.NewClient(serverAddr) if err != nil { return err } configFile, _ := cmd.Flags().GetString("config") initConfig(configFile) var env environment.Environment _ = viper.Unmarshal(&env) fmt.Printf("Requesting creation of %s\n\n", env.Name) eventsCh, err := apiClient.CreateEnvironment(&env) if err != nil { return err } for e := range eventsCh { if e.Err != nil { return e.Err } fmt.Println(e.Msg) } return nil }
non-member
package server import ( "fmt" "net/http" "github.com/labstack/echo/v4" "github.com/faroukelkholy/bank/internal/service/customer" "github.com/faroukelkholy/bank/internal/service/models" "github.com/faroukelkholy/bank/internal/storage/postgres" ) func CCAHandler(srv customer.Service) echo.HandlerFunc { return func(c echo.Context) (err error) { var a models.Account if err = c.Bind(&a); err != nil { fmt.Println("err bind account ", err) return c.JSON(http.StatusBadRequest, HTTPResponse{ Data: nil, Err: HTTPError{ Title: "account data is not valid", Description: "", }, }) } if err = srv.CreateCustomerAccount(c.Param("id"), &a); err != nil { fmt.Println("err execute service ", err) if err.Error() == postgres.NoCustomerID { return c.JSON(http.StatusNotFound, HTTPResponse{ Data: nil, Err: HTTPError{ Title: postgres.NoCustomerID, Description: "", }, }) } return c.JSON(http.StatusInternalServerError, HTTPResponse{ Data: nil, Err: HTTPError{ Title: "internal error", Description: "", }, }) } return c.JSON(http.StatusCreated, HTTPResponse{ Data: "created", Err: HTTPError{}, }) } }
member
package login import ( "RainbowRunner/internal/message" "RainbowRunner/internal/serverconfig" "fmt" log "github.com/sirupsen/logrus" "net" ) func StartLoginServer() { listen, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", serverconfig.Config.Network.LoginServerPort)) if err != nil { panic(err) } defer func() { err := listen.Close() if err != nil { panic(err) } }() for { conn, err := listen.Accept() if err != nil { panic(err) } go handleConnection(conn) } } func handleConnection(conn net.Conn) { parser := message.NewAuthMessageParser(conn) buf := make([]byte, 1024*10) fmt.Println("Client connected") _, err := conn.Write([]byte{ 3, 0, // Length 0, // Message Type }) if err != nil { panic(err) } for { read, err := conn.Read(buf) if err != nil { log.Info(fmt.Sprintf("failed to read from connection: %e\n", err)) break } parser.Parse(buf, read) } err = conn.Close() if err != nil { return } }
non-member
package storage func IsCloud(path string) bool { return IsS3(path) || IsGCS(path) } func IsCloudDir(path string) bool { return IsS3Dir(path) || IsGCSDir(path) }
non-member
package mocks import ( "github.com/makerdao/vdb-mcd-transformers/backfill/repository" ) type EventsRepository struct { GetForksError error GetForksForksToReturn []repository.Fork GetForksPassedStartingBlock int GetFrobsError error GetFrobsFrobsToReturn []repository.Frob GetFrobsPassedStartingBlock int GetGrabsError error GetGrabsGrabsToReturn []repository.Grab GetGrabsPassedStartingBlock int } func (mock *EventsRepository) GetForks(startingBlock int) ([]repository.Fork, error) { mock.GetForksPassedStartingBlock = startingBlock return mock.GetForksForksToReturn, mock.GetForksError } func (mock *EventsRepository) GetFrobs(startingBlock int) ([]repository.Frob, error) { mock.GetFrobsPassedStartingBlock = startingBlock return mock.GetFrobsFrobsToReturn, mock.GetFrobsError } func (mock *EventsRepository) GetGrabs(startingBlock int) ([]repository.Grab, error) { mock.GetGrabsPassedStartingBlock = startingBlock return mock.GetGrabsGrabsToReturn, mock.GetGrabsError }
non-member