text
stringlengths
11
4.05M
package particion import ( "strings" ) // Particion modelo de la estructura type Particion struct { Estado byte Tipo byte Fit byte Inicio int64 Tamanio int64 Nombre [16]byte } // Inicializar Recibe un puntero Particion para ser modificado. func (p *Particion) Inicializar(estado byte, tipo byte, fit byte, inicio int64, tamanio int64, nombre string) { p.Estado = estado p.Tipo = tipo p.Fit = fit p.Inicio = inicio p.Tamanio = tamanio copy(p.Nombre[:], nombre) for i := len(nombre); i < 16; i++ { p.Nombre[i] = byte(" "[0]) } } // GetEstado recibe una copia de Particion ya que no necesita modificarlo. func (p Particion) GetEstado() byte { return p.Estado } // SetEstado recibe un puntero Particion para ser modificado. func (p *Particion) SetEstado(estado byte) { p.Estado = estado } // GetTipo retorna el valor de tipo func (p Particion) GetTipo() byte { return p.Tipo } // SetTipo asigna el tipo func (p *Particion) SetTipo(tipo byte) { p.Tipo = tipo } // GetFit retorna el fit de la particion func (p Particion) GetFit() byte { return p.Fit } // SetFit asigna el fit func (p *Particion) SetFit(fit byte) { p.Fit = fit } // GetInicio retorna la posicion inicial de la particion func (p Particion) GetInicio() int64 { return p.Inicio } // SetInicio asigna la posicion inicial de la particion func (p *Particion) SetInicio(inicio int64) { p.Inicio = inicio } // GetTamanio obtiene el tamaño de la particion func (p Particion) GetTamanio() int64 { return p.Tamanio } // SetTamanio asigna el tamaño a la particion func (p *Particion) SetTamanio(tamanio int64) { p.Tamanio = tamanio } // GetNombre retorna el nombre de la particion func (p Particion) GetNombre() string { var nombre strings.Builder for i := 0; i < len(p.Nombre); i++ { if p.Nombre[i] != 0 { nombre.WriteString(string(p.Nombre[i])) } } return strings.TrimSpace(nombre.String()) } // SetNombre asigna el nombre a la particion func (p *Particion) SetNombre(nombre string) { copy(p.Nombre[:], nombre) } // ReiniciarValores formatea para mostrar en la tabla func (p *Particion) ReiniciarValores(finPartANT int64, inicioPartPost int64) { p.Estado = 0 p.Tipo = 0 p.Fit = 0 p.Inicio = finPartANT p.Tamanio = inicioPartPost copy(p.Nombre[:], " ") for i := len(" "); i < 16; i++ { p.Nombre[i] = byte(" "[0]) } }
package config import ( "bytes" "encoding/json" "io/ioutil" "os" "reflect" "strconv" "strings" logUtils "github.com/bossjones/go-chatbot-lab/shared/log-utils" ) // Config - type Config struct { ConfigFile string `json:"configFile"` // "name": "chatbot", Name string `json:"name"` // "commands": ["how are you:fine","where are you:here"], Commands []string `json:"commands"` // "db-path": "./chatbot.db", DBPath string `json:"db-path"` // "adaptor-path": "/opt/adaptors/", AdaptorPath string `json:"adaptor-path"` // "brain-type": "in-memory", BrainType string `json:"brain-type"` // "alias": "bot", Alias string `json:"alias"` // "log-level": "info", LogLevel string `json:"log-level"` // "log-location": "stdout", LogLocation string `json:"log-location"` // "log-app-name": "chatbot", LogAppName string `json:"log-app-name"` // "host": "127.0.0.1", Host string `json:"host"` // "port": "2001", Port string `json:"port"` // "kvStoreUsername": "user", KVUsername string `json:"kvStoreUsername"` // "kvStorePassword": "pass", KVPassword string `json:"kvStorePassword"` // "kvStoreServerAddress": "localhost:4001", KVServer string `json:"kvStoreServerAddress"` // "kv-ttl": "10", KVttl string `json:"kv-ttl"` // "isContainer": false, IsContainer bool `json:"isContainer"` // "ssl-cert-location": "/etc/chatbot", SSLCertLocation string `json:"ssl-cert-location"` // "log-level": "debugging level" Debug bool `json:"logLevel"` } var chatLog = logUtils.NewLogger() // NewConfig - func NewConfig(file string) (Config, error) { c := Config{} if file != "" { err := c.LoadFromConfigFile(file) return c, err } c.LoadFromEnv() return c, nil } // LoadFromEnv - func (c *Config) LoadFromEnv() { setValueFromEnv(&c.Name, "CHATBOT_NAME") setSliceValueFromEnv(&c.Commands, "CHATBOT_COMMANDS") setValueFromEnv(&c.DBPath, "CHATBOT_DB_PATH") setValueFromEnv(&c.AdaptorPath, "CHATBOT_ADAPTOR_PATH") setValueFromEnv(&c.BrainType, "CHATBOT_BRAIN_TYPE") setValueFromEnv(&c.Alias, "CHATBOT_ALIAS") setValueFromEnv(&c.LogLevel, "CHATBOT_LOG_LEVEL") setValueFromEnv(&c.LogLocation, "CHATBOT_LOG_LOCATION") setValueFromEnv(&c.LogAppName, "CHATBOT_LOG_APP_NAME") setValueFromEnv(&c.Host, "CHATBOT_HOST") setValueFromEnv(&c.Port, "CHATBOT_PORT") setValueFromEnv(&c.KVUsername, "CHATBOT_KV_STORE_USERNAME") setValueFromEnv(&c.KVPassword, "CHATBOT_KV_STORE_PASSWORD") setValueFromEnv(&c.KVServer, "CHATBOT_KV_STORE_SERVER_ADDRESS") setValueFromEnv(&c.KVttl, "CHATBOT_KV_TTL") setBoolValueFromEnv(&c.IsContainer, "CHATBOT_IS_CONTAINER") setValueFromEnv(&c.SSLCertLocation, "CHATBOT_SSL_CERT_LOCATION") setBoolValueFromEnv(&c.Debug, "CHATBOT_DEBUG") } // LoadFromConfigFile - func (c *Config) LoadFromConfigFile(configFile string) error { c.ConfigFile = configFile jsonSrc, err := ioutil.ReadFile(c.ConfigFile) if err != nil { chatLog.Warn("Error reading config.", "error", err) return err } err = json.Unmarshal(jsonSrc, &c) if err != nil { chatLog.Warn("Error parsing config.", "error", err) return err } return nil } // String() is a custom method that returns the Config without DockerPassword func (c *Config) String() string { var buffer bytes.Buffer v := reflect.ValueOf(c).Elem() for i := 0; i < v.NumField(); i++ { key := v.Type().Field(i).Name val := v.Field(i).String() buffer.WriteString(key + ": ") if strings.Contains(strings.ToLower(key), "password") { buffer.WriteString("******" + "\n") } else if strings.ToLower(key) == "commands" { for _, i := range c.Commands { buffer.WriteString(i + " ") } buffer.WriteString("\n") } else { buffer.WriteString(val + "\n") } } return buffer.String() } //CommandListIsManuallySet returns true if a lidt f commands was passed in to config // this is used to tell Capcom not to check for dynamic command list from Flight Director. func (c *Config) CommandListIsManuallySet() bool { tempConfig, _ := NewConfig(c.ConfigFile) return (len(tempConfig.Commands) > 0) } func setValueFromEnv(field *string, envVar string) { env := os.Getenv(envVar) if len(env) > 0 { *field = env } } func setSliceValueFromEnv(field *[]string, envVar string) { env := os.Getenv(envVar) if len(env) > 0 { apps := make([]string, 0) err := json.Unmarshal([]byte(env), &apps) if err != nil { chatLog.Error("Error parsing slice in config.", "variable", envVar, "value", env) } *field = apps } } // func setIntValueFromEnv(field *int, envVar string) { // env := os.Getenv(envVar) // if len(env) > 0 { // var err error // *field, err = strconv.Atoi(env) // if err != nil { // chatLog.Error("Invalid environment variable", "var", envVar, "value", env) // } // } // } // //Validate checks config values for obvious problems. // func (c *Config) Validate() error { // var e error // if _, err := strconv.Atoi(c.APIServerPort); err != nil { // e = errors.New(APIServerPortErr + c.APIServerPort) // } // if !strings.Contains("sqlite3,mysql", c.DBEngine) { // e = errors.New(DBEngineErr + c.DBEngine) // } // if c.DBPath == "" { // e = errors.New(DBPathErr + c.DBPath) // } // //mysql needs usernmae password and database // if c.DBEngine != "sqlite3" && c.DBUsername == "" { // e = errors.New(DBUsernameErr + c.DBUsername) // } // if c.DBEngine != "sqlite3" && c.DBPassword == "" { // e = errors.New(DBPasswordErr + c.DBPassword) // } // if c.DBEngine != "sqlite3" && c.DBDatabase == "" { // e = errors.New(DBDatabaseErr + c.DBDatabase) // } // if c.MarathonMaster == "" { // e = errors.New(MarathonMasterErr + c.MarathonMaster) // } // if c.MesosMaster == "" { // e = errors.New(MesosMasterErr + c.MesosMaster) // } // if c.MesosAuthenticationPrincipal != "" && c.MesosAuthenticationSecretFile == "" { // e = errors.New("Cannot have empty Mesos authentication file if principal is specified") // } // if c.MarathonAuthenticationPrincipal != "" && c.MarathonAuthenticationSecretFile == "" { // e = errors.New("Cannot have empty Marathon authentication file if principal is specified") // } // if c.MarathonAuthenticationPrincipal != "" && c.MarathonUser != "" { // e = errors.New("Cannot specify both MarathonUser and MarathonPrincipal") // } // if c.KVServer == "" { // e = errors.New(KVServerErr + c.KVServer) // } // rangeVals := strings.Split(c.ProxyPortRange, ":") // if len(rangeVals) != 2 { // e = errors.New(ProxyPortRangeFormatErr + c.ProxyPortRange) // } else { // if _, err := strconv.Atoi(rangeVals[0]); err != nil { // e = errors.New(ProxyPortRangeMinErr + c.ProxyPortRange) // } // if _, err := strconv.Atoi(rangeVals[1]); err != nil { // e = errors.New(ProxyPortRangeMaxErr + c.ProxyPortRange) // } // } // if !strings.Contains("json-file journald", c.AppLogDriver) { // e = errors.New(LogErr + c.AppLogDriver) // } // if c.AquaEnabled && c.AquaEndpoint == "" { // e = errors.New(AquaErr) // } // for _, param := range c.AllowedDockerRunParams { // if strings.ContainsAny(param, "[]\"") { // e = errors.New( // "FD_ALLOWED_DOCKER_RUN_PARAMS should be a comma-separated list of param names; no brackets or quotes. E.g.:\n" + // " label,l,read-only,work-dir,w,network,net\n") // } // } // return e // } func setBoolValueFromEnv(field *bool, envVar string) { env := os.Getenv(envVar) if len(env) > 0 { var err error *field, err = strconv.ParseBool(env) if err != nil { chatLog.Error("Invalid environment variable", "var", envVar, "value", env) } } }
package test import "testing" func TestGitPush(t *testing.T) { }
package engine import ( "github.com/stretchr/testify/assert" "github.com/zhenghaoz/gorse/base" "github.com/zhenghaoz/gorse/core" "github.com/zhenghaoz/gorse/model" "path" "reflect" "testing" ) func TestLoadConfig(t *testing.T) { config, _ := LoadConfig("../example/file_config/config_test.toml") /* Check configuration */ // server configuration assert.Equal(t, "127.0.0.1", config.Server.Host) assert.Equal(t, 8080, config.Server.Port) // database configuration assert.Equal(t, "~/.gorse/temp/database.db", config.Database.File) // recommend configuration assert.Equal(t, "svd", config.Recommend.Model) assert.Equal(t, "pearson", config.Recommend.Similarity) assert.Equal(t, 100, config.Recommend.CacheSize) assert.Equal(t, 10, config.Recommend.UpdateThreshold) assert.Equal(t, 1, config.Recommend.CheckPeriod) // params configuration assert.Equal(t, 0.05, config.Params.Lr) assert.Equal(t, 0.01, config.Params.Reg) assert.Equal(t, 100, config.Params.NEpochs) assert.Equal(t, 10, config.Params.NFactors) assert.Equal(t, 21, config.Params.RandomState) assert.Equal(t, false, config.Params.UseBias) assert.Equal(t, 0.0, config.Params.InitMean) assert.Equal(t, 0.001, config.Params.InitStdDev) assert.Equal(t, 10, config.Params.NUserClusters) assert.Equal(t, 10, config.Params.NItemClusters) assert.Equal(t, "baseline", config.Params.Type) assert.Equal(t, true, config.Params.UserBased) assert.Equal(t, "pearson", config.Params.Similarity) assert.Equal(t, 100, config.Params.K) assert.Equal(t, 5, config.Params.MinK) assert.Equal(t, "bpr", config.Params.Optimizer) assert.Equal(t, 1.0, config.Params.Alpha) } func TestParamsConfig_ToParams(t *testing.T) { // test on full configuration config, meta := LoadConfig("../example/file_config/config_test.toml") params := config.Params.ToParams(meta) assert.Equal(t, 20, len(params)) // test on empty configuration config, meta = LoadConfig("../example/file_config/config_empty.toml") params = config.Params.ToParams(meta) assert.Equal(t, 0, len(params)) } func TestTomlConfig_FillDefault(t *testing.T) { config, _ := LoadConfig("../example/file_config/config_empty.toml") /* Check configuration */ // server configuration assert.Equal(t, "127.0.0.1", config.Server.Host) assert.Equal(t, 8080, config.Server.Port) // database configuration assert.Equal(t, path.Join(core.GorseDir, "gorse.db"), config.Database.File) // recommend configuration assert.Equal(t, "svd", config.Recommend.Model) assert.Equal(t, "pearson", config.Recommend.Similarity) assert.Equal(t, 100, config.Recommend.CacheSize) assert.Equal(t, 10, config.Recommend.UpdateThreshold) assert.Equal(t, 1, config.Recommend.CheckPeriod) config, _ = LoadConfig("../example/file_config/config_not_exist.toml") /* Check configuration */ // server configuration assert.Equal(t, "127.0.0.1", config.Server.Host) assert.Equal(t, 8080, config.Server.Port) // database configuration assert.Equal(t, path.Join(core.GorseDir, "gorse.db"), config.Database.File) // recommend configuration assert.Equal(t, "svd", config.Recommend.Model) assert.Equal(t, "pearson", config.Recommend.Similarity) assert.Equal(t, 100, config.Recommend.CacheSize) assert.Equal(t, 10, config.Recommend.UpdateThreshold) assert.Equal(t, 1, config.Recommend.CheckPeriod) } func TestLoadSimilarity(t *testing.T) { assert.Equal(t, reflect.ValueOf(base.PearsonSimilarity).Pointer(), reflect.ValueOf(LoadSimilarity("pearson")).Pointer()) assert.Equal(t, reflect.ValueOf(base.CosineSimilarity).Pointer(), reflect.ValueOf(LoadSimilarity("cosine")).Pointer()) assert.Equal(t, reflect.ValueOf(base.MSDSimilarity).Pointer(), reflect.ValueOf(LoadSimilarity("msd")).Pointer()) // Test similarity not existed assert.Equal(t, uintptr(0), reflect.ValueOf(LoadSimilarity("none")).Pointer()) } func TestLoadModel(t *testing.T) { type Model struct { name string typeOf reflect.Type } models := []Model{ {"svd", reflect.TypeOf(model.NewSVD(nil))}, {"knn", reflect.TypeOf(model.NewKNN(nil))}, {"slope_one", reflect.TypeOf(model.NewSlopOne(nil))}, {"co_clustering", reflect.TypeOf(model.NewCoClustering(nil))}, {"nmf", reflect.TypeOf(model.NewNMF(nil))}, {"wrmf", reflect.TypeOf(model.NewWRMF(nil))}, {"svd++", reflect.TypeOf(model.NewSVDpp(nil))}, } for _, m := range models { assert.Equal(t, m.typeOf, reflect.TypeOf(LoadModel(m.name, nil))) } // Test model not existed assert.Equal(t, nil, LoadModel("none", nil)) }
package osbuild1 import ( "testing" "github.com/stretchr/testify/assert" ) func TestNewSELinuxStageOptions(t *testing.T) { expectedOptions := &SELinuxStageOptions{ FileContexts: "etc/selinux/targeted/contexts/files/file_contexts", } actualOptions := NewSELinuxStageOptions("etc/selinux/targeted/contexts/files/file_contexts") assert.Equal(t, expectedOptions, actualOptions) } func TestNewSELinuxStage(t *testing.T) { expectedStage := &Stage{ Name: "org.osbuild.selinux", Options: &SELinuxStageOptions{}, } actualStage := NewSELinuxStage(&SELinuxStageOptions{}) assert.Equal(t, expectedStage, actualStage) }
package config import ( "github.com/bemobi/envconfig" ) // Data contains parameters that controls the execution of the server. // The struct is filled from environment variables. var Data struct { Server struct { Addr string `envconfig:"default=0.0.0.0:8080"` } Redis struct { Addr string `envconfig:"optional"` Password string `envconfig:"optional"` DB int `envconfig:"default=0"` } } func init() { if err := envconfig.Init(&Data); err != nil { panic(err) } }
package service import ( "errors" "fmt" "strconv" "strings" "time" "github.com/rs/zerolog/log" "github.com/shantanuchalla/awesomeProject/pkg/client" "github.com/shantanuchalla/awesomeProject/pkg/contracts" ) var poll = make(chan contracts.SlotRequest) type CowinSlotChecker struct { Locations []*contracts.Location CowinClient *client.CowinClinet PollInterval time.Duration } func (checker CowinSlotChecker) InitSlotPoller(fetchDistrictId bool) { log.Info().Msgf("Initializing Poller with interval -- %+v", checker.PollInterval) checker.initializeSlotCheck(fetchDistrictId) ticker := time.NewTicker(checker.PollInterval) tickChannel := ticker.C for tick := range tickChannel { log.Info().Msgf("received tick <- +%v", tick) checker.initializeSlotCheck(fetchDistrictId) } } func (checker CowinSlotChecker) initializeSlotCheck(fetchDistrictId bool) { for _, loc := range checker.Locations { req, err := checker.getSlotRequest(loc, fetchDistrictId) if err != nil { continue } poll <- *req } } func (checker CowinSlotChecker) InitPollListener() { for slotRequest := range poll { log.Info().Msgf("Results for state -- %s | region -- %s", slotRequest.Location.State, slotRequest.Location.City) err := checker.processSlots(slotRequest) if err != nil { log.Error().Err(err) } } } func (checker CowinSlotChecker) getSlotRequest(loc *contracts.Location, fetchDistrictId bool) (*contracts.SlotRequest, error) { currentTime := time.Now() year, month, day := currentTime.Date() if fetchDistrictId { stateId, err := checker.getStateId(loc) if err != nil { return nil, err } districtId, err := checker.getDistrictId(loc, stateId) if err != nil { return nil, err } loc.DistrictId = strconv.Itoa(districtId) } return &contracts.SlotRequest{ Location: *loc, Date: fmt.Sprintf("%02d", day) + "-" + fmt.Sprintf("%02d", int(month)) + "-" + fmt.Sprintf("%04d", year), }, nil } func (checker CowinSlotChecker) getDistrictId(loc *contracts.Location, stateId int) (int, error) { districts, err := checker.CowinClient.GetDistricts(stateId) if err != nil { return -1, err } districtId := -1 for _, district := range districts.Districts { if strings.ToLower(loc.City) == strings.ToLower(district.DistrictName) { districtId = district.DistrictId } } if districtId < 0 { return -1, errors.New("city not found") } return districtId, nil } func (checker CowinSlotChecker) getStateId(loc *contracts.Location) (int, error) { states, err := checker.CowinClient.GetStates() if err != nil { return -1, err } stateId := -1 for _, state := range states.States { if strings.ToLower(loc.State) == strings.ToLower(state.StateName) { stateId = state.StateId } } if stateId < 0 { return -1, errors.New("state not found") } return stateId, nil }
package controllers //type VideoController struct { // beego.Controller; //} //// @router /list [get] //func (this *VideoController) List(){ // //qb, _ := com.NewOrm(); // query :=make(map[string]string) // query["type.isnull"]="false"; // //fields :=[]string{"Id","Name","Type","Actors","description","ImagePath","IsRelease","IsFrcc","Price","IsLock","Category","Language","LastUpdate","CompletionDate","Director","Region","LogoHighlight"}; // fields :=[]string{} // sortby :=[]string{"LastUpdate"} // order :=[]string{"desc"} // offset :=1; // limit :=30; // list,err:=models.GetAllProgramProgram(query , fields, sortby, order, int64(offset), int64(limit)) // if(nil!=err){ // logs.Debug(err); // } // m:=make(map[string][]interface{}); // m["list"]=list; // this.Data["json"]=m // this.ServeJSON(); // this.StopRun(); //} // //// @router /getQuery [get] //func (this *VideoController) QueryRows(){ // type Program struct { // Id int // Name string // Actors string // InsertTime string // } // var o orm.Ormer; // o=orm.NewOrm(); // var program []Program // num, err := o.Raw("SELECT id, name,actors,insert_time FROM program_program WHERE type = ? and is_lock=?", 1,1).QueryRows(&program) // if err == nil { // fmt.Println("user nums: ", num) // } // this.Data["json"]=program; // this.ServeJSON(); // this.StopRun(); //}
package main import "fmt" func writeMessageToChannel(message chan string) { message <- "Hello Gopher!" } func main() { fmt.Println("Channel Demo") message := make(chan string) go writeMessageToChannel(message) fmt.Println("Greeting from the message channel: ", <-message) close(message) }
package usecase import ( "TechnoParkDBProject/internal/app/thread" threadModels "TechnoParkDBProject/internal/app/thread/models" "TechnoParkDBProject/internal/app/vote" "TechnoParkDBProject/internal/app/vote/models" "github.com/jackc/pgconn" "strconv" ) type VoteUsecase struct { voteRep vote.Repository threadRep thread.Repository } func NewVoteUsecase(voteRep vote.Repository, threadRep thread.Repository) *VoteUsecase { return &VoteUsecase{ voteRep: voteRep, threadRep: threadRep, } } func (voteUsecase *VoteUsecase) CreateNewVote(vote *models.Vote, slugOrID string) (*threadModels.Thread, error) { threadID, err := strconv.Atoi(slugOrID) var th *threadModels.Thread if err != nil { th, err = voteUsecase.threadRep.FindThreadBySlug(slugOrID) if err != nil { return nil, err } } else { th, err = voteUsecase.threadRep.FindThreadByID(threadID) if err != nil { return nil, err } } vote.ThreadID = th.ID err = voteUsecase.voteRep.CreateNewVote(vote) if err != nil { if err.(*pgconn.PgError).Code == "23503" { return nil, err } linesUpdated, err := voteUsecase.voteRep.UpdateVote(vote) if err != nil { return nil, err } if linesUpdated != 0 { th.Votes += 2 * vote.Voice } return th, err } th.Votes += vote.Voice return th, err }
package sso import ( "context" "fmt" "net/http" "github.com/argoproj/argo/server/auth/jws" ) var NullSSO Interface = nullService{} type nullService struct{} func (n nullService) Authorize(context.Context, string) (*jws.ClaimSet, error) { return nil, fmt.Errorf("not implemented") } func (n nullService) HandleRedirect(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotImplemented) } func (n nullService) HandleCallback(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNotImplemented) }
package mt type MinimapType uint16 const ( NoMinimap MinimapType = iota // none SurfaceMinimap // surface RadarMinimap // radar TextureMinimap // texture ) //go:generate stringer -linecomment -type MinimapType type MinimapMode struct { Type MinimapType Label string Size uint16 Texture Scale uint16 } // DefaultMinimap is the initial set of MinimapModes used by the client. var DefaultMinimap = []MinimapMode{ {Type: NoMinimap}, {Type: SurfaceMinimap, Size: 256}, {Type: SurfaceMinimap, Size: 128}, {Type: SurfaceMinimap, Size: 64}, {Type: RadarMinimap, Size: 512}, {Type: RadarMinimap, Size: 256}, {Type: RadarMinimap, Size: 128}, }
package models import ( "github.com/astaxie/beego/orm" "github.com/astaxie/beego" _ "github.com/go-sql-driver/mysql" "database/sql" "github.com/go-redis/redis" ) func init() { orm.RegisterDriver("mysql", orm.DRMySQL) user := beego.AppConfig.String("sqluser") password := beego.AppConfig.String("sqlpass") dbName := beego.AppConfig.String("sqldb") orm.RegisterDataBase("default", "mysql", user+":"+password+"@/"+dbName+"?charset=utf8") orm.RegisterModel(new(Candy), new(Record), new(Game), new(Token), new(User), new(GameCandy)) } func DB() *sql.DB { user := beego.AppConfig.String("sqluser") password := beego.AppConfig.String("sqlpass") host := beego.AppConfig.String("host") dbName := beego.AppConfig.String("sqldb") db, _ := sql.Open("mysql", user+":"+password+"@tcp("+host+":3306)/"+dbName) err := db.Ping() if err != nil { panic(err) } return db } func Redis() *redis.Client { client := redis.NewClient(&redis.Options{ Addr: beego.AppConfig.String("redis_addr"), Password: "", // no password set DB: 0, // use default DB }) _, err := client.Ping().Result() if err != nil { panic(err) } return client }
package controller import ( "gonum.org/v1/gonum/mat" "../basic" "math" ) type square struct { particles [][]*particle verticalSprings [][]*spring horizontalSprings [][]*spring tilt1Springs [][]*spring tilt2Springs [][]*spring } type particle struct { pos *mat.VecDense prev *mat.VecDense force *mat.VecDense } type spring struct { p1 *particle p2 *particle l float64 } //const Level = 5 //const Length = 0.25 //const k = 700 //const b = 20000 const Level = 5 const Length = 0.25 const k = 700 const b = 25000 func newSquare(x, y float64) *square { cx := x cy := y idx := Length*math.Cos(math.Pi/6)/(Level-1) idy := Length*math.Sin(math.Pi/6)/(Level-1) jdx := Length*math.Cos(math.Pi/6 + math.Pi/2)/(Level-1) jdy := Length*math.Sin(math.Pi/6 + math.Pi/2)/(Level-1) particles := make([][]*particle, Level) for i := 0; i < Level; i++ { particles[i] = make([]*particle, Level) for j := 0; j < Level; j++ { tmpPos := mat.NewVecDense(2, []float64{cx+idx*float64(i)+jdx*float64(j),cy+idy*float64(i)+jdy*float64(j)}) particles[i][j] = &particle{pos: tmpPos, prev: tmpPos, force: basic.ZeroVec()} } } verticalSprings := make([][]*spring, Level) for i := 0; i < Level; i++ { verticalSprings[i] = make([]*spring, Level-1) for j := 0; j < Level-1; j++ { verticalSprings[i][j] = &spring{p1: particles[i][j], p2: particles[i][j+1], l: Length/(Level-1)} } } horizontalSprings := make([][]*spring, Level-1) for i := 0; i < Level-1; i++ { horizontalSprings[i] = make([]*spring, Level) for j := 0; j < Level; j++ { horizontalSprings[i][j] = &spring{p1: particles[i][j], p2: particles[i+1][j], l: Length/(Level-1)} } } tilt1Springs := make([][]*spring, Level-1) for i := 0; i < Level-1; i++ { tilt1Springs[i] = make([]*spring, Level-1) for j := 0; j < Level-1; j++ { tilt1Springs[i][j] = &spring{p1: particles[i][j], p2: particles[i+1][j+1], l: Length/(Level-1)*math.Sqrt2} } } tilt2Springs := make([][]*spring, Level-1) for i := 0; i < Level-1; i++ { tilt2Springs[i] = make([]*spring, Level-1) for j := 0; j < Level-1; j++ { tilt2Springs[i][j] = &spring{p1: particles[i+1][j], p2: particles[i][j+1], l: Length/(Level-1)*math.Sqrt2} } } return &square{particles: particles, verticalSprings:verticalSprings, horizontalSprings:horizontalSprings, tilt1Springs:tilt1Springs, tilt2Springs:tilt2Springs} } func (s *spring) update(dt float64) { p1, p2 := s.p1, s.p2 v1, v2, d := &mat.VecDense{}, &mat.VecDense{}, &mat.VecDense{} v1.SubVec(p1.pos, p1.prev) v1.ScaleVec(dt, v1) v2.SubVec(p2.pos, p2.prev) v2.ScaleVec(dt, v2) d.SubVec(p2.pos, p1.pos) mag := math.Sqrt(d.At(0,0)*d.At(0,0)+d.At(1,0)*d.At(1,0)) d.ScaleVec(1/mag, d) springForce := &mat.VecDense{} springForce.ScaleVec(k*(mag-s.l), d) damperForce := &mat.VecDense{} factor := b*((v2.At(0,0)*d.At(0,0)+v2.At(1,0)*d.At(1,0)) - (v1.At(0,0)*d.At(0,0)+v1.At(1,0)*d.At(1,0))) damperForce.ScaleVec(factor, d) p1.force.AddVec(p1.force, springForce) p1.force.AddVec(p1.force, damperForce) p2.force.SubVec(p2.force, springForce) p2.force.SubVec(p2.force, damperForce) } func (s *square) update(dt float64) { oldPos := make([][]*mat.VecDense, Level) for i := 0; i < Level; i++ { oldPos[i] = make([]*mat.VecDense, Level) for j := 0; j < Level; j++ { oldPos[i][j] = s.particles[i][j].pos } } for _, particles := range s.particles { for _, p := range particles { p.force = basic.NewVec(0, -4) } } for _, springs := range s.verticalSprings { for _ , spring := range springs { spring.update(dt) } } for _, springs := range s.horizontalSprings { for _ , spring := range springs { spring.update(dt) } } for _, springs := range s.tilt1Springs { for _ , spring := range springs { spring.update(dt) } } for _, springs := range s.tilt2Springs { for _ , spring := range springs { spring.update(dt) } } for _, particles := range s.particles { for _, p := range particles { if p.pos.At(1, 0) < -1.0 { posY := p.pos.At(1, 0) prevY := p.prev.At(1, 0) p.pos.SetVec(1, -1.0) p.prev.SetVec(1, -1.0 - (prevY+(-1.0-posY) + 1.0)) //p.prev.SetVec(1, -1.0) } } } for _, particles := range s.particles { for _, p := range particles { p.accelerate(dt) } } newPos := make([][]*mat.VecDense, Level) for i := 0; i < Level; i++ { newPos[i] = make([]*mat.VecDense, Level) for j := 0; j < Level; j++ { newPos[i][j] = s.particles[i][j].pos } } //s.shapeMatch(oldPos, newPos) } func (s *square) shapeMatch(oldPos, newPos [][]*mat.VecDense) { c := basic.ZeroVec() for _, ps := range oldPos { for _, p := range ps { c.AddVec(c, p) } } c.ScaleVec(1.0/float64(Level*Level), c) t := basic.ZeroVec() for _, ps := range newPos { for _, p := range ps { t.AddVec(t, p) } } t.ScaleVec(1.0/float64(Level*Level), t) qs := make([][]*mat.Dense, Level) for i := 0; i < Level; i++ { qs[i] = make([]*mat.Dense, Level) for j := 0; j < Level; j++ { qs[i][j] = &mat.Dense{} qs[i][j].Sub(oldPos[i][j], c) } } ps := make([][]*mat.Dense, Level) for i := 0; i < Level; i++ { ps[i] = make([]*mat.Dense, Level) for j := 0; j < Level; j++ { ps[i][j] = &mat.Dense{} ps[i][j].Sub(newPos[i][j], t) } } Apq := basic.ZeroMat() for i := 0; i < Level; i++ { for j := 0; j < Level; j++ { factor := &mat.Dense{} factor.Mul(ps[i][j], qs[i][j].T()) Apq.Add(Apq, factor) } } Aqq := basic.ZeroMat() for i := 0; i < Level; i++ { for j := 0; j < Level; j++ { factor := &mat.Dense{} factor.Mul(qs[i][j], qs[i][j].T()) Aqq.Add(Aqq, factor) } } Aqq.Inverse(Aqq) Apq2 := &mat.Dense{} Apq2.Mul(Apq.T(), Apq) svd := mat.SVD{} svd.Factorize(Apq2, mat.SVDFull) u := svd.UTo(nil) values := svd.Values(nil) vt := svd.VTo(nil) l := basic.ZeroMat() for i := 0; i < len(values); i++ { l.Set(i, i, 1.0/math.Sqrt(values[i])) } rootApq := &mat.Dense{} rootApq.Mul(u, l) rootApq.Mul(rootApq, vt) R := &mat.Dense{} R.Mul(Apq, rootApq) L := &mat.Dense{} L.Mul(Apq, Aqq) alpha := 0.75 R.Scale(1-alpha, R) L.Scale(alpha, L) Shape := &mat.Dense{} Shape.Add(R, L) for i := 0; i < Level; i++ { for j := 0; j < Level; j++ { s.particles[i][j].pos.MulVec(Shape, qs[i][j].ColView(0)) s.particles[i][j].pos.AddVec(s.particles[i][j].pos, t) } } } func (p *particle) dx() (*mat.VecDense){ v := &mat.VecDense{} v.SubVec(p.pos, p.prev) return v } func (p *particle) accelerate(dt float64) { next := &mat.VecDense{} next.AddVec(p.pos, p.dx()) next.AddScaledVec(next, dt*dt/1.0, p.force) p.prev = p.pos p.pos = next p.force = basic.ZeroVec() } func (p *particle) elements() (x,y float32) { x = float32(p.pos.At(0, 0)) y = float32(p.pos.At(1, 0)) return }
package sonarqube import ( "fmt" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" sonargo "github.com/labd/sonargo/sonar" ) func dataSourceUser() *schema.Resource { return &schema.Resource{ Read: dataSourceUserRead, Schema: map[string]*schema.Schema{ "email": { Type: schema.TypeString, Required: true, }, // Computed values. "login": { Type: schema.TypeString, Computed: true, }, }, } } func dataSourceUserRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*sonargo.Client) result, _, err := client.Users.Search(&sonargo.UsersSearchOption{ Q: d.Get("email").(string), }) if err != nil { return err } if len(result.Users) < 1 { return fmt.Errorf("No user found with email address %s", d.Get("email").(string)) } d.SetId(result.Users[0].Login) d.Set("login", result.Users[0].Login) return nil }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-08-10 20:46 # @File : server.go # @Description : # @Attention : */ package server
// DO NOT EDIT. This file was generated by "github.com/frk/gosql". package testdata import ( "github.com/frk/gosql" "github.com/frk/gosql/internal/testdata/common" ) func (q *SelectWithWhereBlockInPredicate2Query) Exec(c gosql.Conn) error { var ( nstatic = 3 // number of static parameters len1 = len(q.Where.Or.IDs) // length of slice #1 to be unnested pos1 = nstatic // starting position of slice #1 parameters ) var queryString = `SELECT u."id" , u."email" , u."full_name" , u."created_at" FROM "test_user" AS u WHERE u."created_at" BETWEEN $1 AND $2 OR (u."id" IN (` + gosql.InValueList(len1, pos1) + `) AND u."created_at" < $3)` // ` params := make([]interface{}, nstatic+len1) params[0] = q.Where.CreatedAt.After params[1] = q.Where.CreatedAt.Before params[2] = q.Where.Or.CreatedBefore for i := 0; i < len1; i++ { params[pos1+i] = q.Where.Or.IDs[i] } rows, err := c.Query(queryString, params...) if err != nil { return err } defer rows.Close() for rows.Next() { v := new(common.User) err := rows.Scan( &v.Id, &v.Email, &v.FullName, &v.CreatedAt, ) if err != nil { return err } q.Users = append(q.Users, v) } return rows.Err() }
package logic import ( "fmt" ) const ( ERROR_UNKNOWN = 400 ERROR_INPUT = 401 ) type Error struct { Errno int Errmsg string } func (E *Error) Error() string { return fmt.Sprintf("[%d] %s", E.Errno, E.Errmsg) } func NewError(errno int, errmsg string) *Error { return &Error{errno, errmsg} } func GetError(err error) (int, string) { e, ok := err.(*Error) if ok { return e.Errno, e.Errmsg } return ERROR_UNKNOWN, err.Error() } func GetErrorObject(err error) interface{} { n, m := GetError(err) return map[string]interface{}{"errno": n, "errmsg": m} }
package launcher type AlertSender interface { Send(msg string) }
/* Copyright (C) 2016 Red Hat, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package registration import ( "fmt" "github.com/docker/machine/libmachine/host" "github.com/docker/machine/libmachine/log" "github.com/docker/machine/libmachine/provision" "github.com/pkg/errors" ) type RegistrationParameters struct { Username string Password string } // Register host VM func RegisterHostVM(host *host.Host, param *RegistrationParameters) error { commander := provision.GenericSSHCommander{Driver: host.Driver} registrator, supportRegistration, err := DetectRegistrator(commander) if !supportRegistration { log.Debug("Distribution doesn't support registration") } if err != nil && err != ErrDetectionFailed { return err } if registrator != nil { fmt.Println("Registering machine using subscription-manager") if param.Username == "" || param.Password == "" { return errors.New("This virtual machine requires registration. " + "Credentials must either be passed via the environment variables " + "MINISHIFT_USERNAME and MINISHIFT_PASSWORD " + " or the --username and --password flags\n") } if err := registrator.Register(param); err != nil { return err } } return nil } // Unregister host VM func UnregisterHostVM(host *host.Host, param *RegistrationParameters) error { commander := provision.GenericSSHCommander{Driver: host.Driver} registrator, supportUnregistration, err := DetectRegistrator(commander) if !supportUnregistration { log.Debug("Distribution doesn't support unregistration") } if err != nil && err != ErrDetectionFailed { return err } if registrator != nil { fmt.Println("Unregistering machine") if err := registrator.Unregister(param); err != nil { return err } } return nil }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-08-16 14:07 # @File : shell_sort.go # @Description : # @Attention : */ package sort import ( "fmt" "testing" ) func TestShellSort(t *testing.T) { ShellSort(array) fmt.Println(array) }
// Copyright 2015-2018 trivago N.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 consumer import ( "bytes" "encoding/json" "fmt" "io/ioutil" "strconv" "strings" "sync" "time" "gollum/core" "gollum/core/components" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/kinesis" ) const ( kinesisOffsetNewest = "newest" kinesisOffsetOldest = "oldest" ) // AwsKinesis consumer // // This consumer reads a message from an AWS Kinesis router. // // Parameters // // - KinesisStream: This value defines the stream to read from. // By default this parameter is set to "default". // // - OffsetFile: This value defines a file to store the current offset per shard. // To disable this parameter, set it to "". If the parameter is set and the file // is found, consuming will start after the offset stored in the file. // By default this parameter is set to "". // // - RecordsPerQuery: This value defines the number of records to pull per query. // By default this parameter is set to "100". // // - RecordMessageDelimiter: This value defines the string to delimit messages // within a record. To disable this parameter, set it to "". // By default this parameter is set to "". // // - QuerySleepTimeMs: This value defines the number of milliseconds to sleep // before trying to pull new records from a shard that did not return any records. // By default this parameter is set to "1000". // // - RetrySleepTimeSec: This value defines the number of seconds to wait after // trying to reconnect to a shard. // By default this parameter is set to "4". // // - CheckNewShardsSec: This value sets a timer to update shards in Kinesis. // You can set this parameter to "0" for disabling. // By default this parameter is set to "0". // // - DefaultOffset: This value defines the message index to start reading from. // Valid values are either "newest", "oldest", or a number. // By default this parameter is set to "newest". // // Examples // // This example consumes a kinesis stream "myStream" and create messages: // // KinesisIn: // Type: consumer.AwsKinesis // Credential: // Type: shared // File: /Users/<USERNAME>/.aws/credentials // Profile: default // Region: "eu-west-1" // KinesisStream: myStream type AwsKinesis struct { core.SimpleConsumer `gollumdoc:"embed_type"` // AwsMultiClient is public to make AwsMultiClient.Configure() callable AwsMultiClient components.AwsMultiClient `gollumdoc:"embed_type"` stream string `config:"KinesisStream" default:"default"` offsetFile string `config:"OffsetFile"` recordsPerQuery int64 `config:"RecordsPerQuery" default:"100"` delimiter []byte `config:"RecordMessageDelimiter"` sleepTime time.Duration `config:"QuerySleepTimeMs" default:"1000" metric:"ms"` //retryTime time.Duration `config:"RetrySleepTimeSec" default:"4" metric:"sec"` shardTime time.Duration `config:"CheckNewShardsSec" default:"0" metric:"sec"` client *kinesis.Kinesis offsets map[string]string offsetType string defaultOffset string running bool offsetsGuard *sync.RWMutex } func init() { core.TypeRegistry.Register(AwsKinesis{}) } // Configure initializes this consumer with values from a plugin config. func (cons *AwsKinesis) Configure(conf core.PluginConfigReader) { cons.offsets = make(map[string]string) cons.offsetsGuard = new(sync.RWMutex) // Offset offsetValue := strings.ToLower(conf.GetString("DefaultOffset", kinesisOffsetNewest)) switch offsetValue { case kinesisOffsetNewest: cons.offsetType = kinesis.ShardIteratorTypeLatest cons.defaultOffset = "" case kinesisOffsetOldest: cons.offsetType = kinesis.ShardIteratorTypeTrimHorizon cons.defaultOffset = "" default: cons.offsetType = kinesis.ShardIteratorTypeAtSequenceNumber _, err := strconv.ParseUint(offsetValue, 10, 64) if err != nil { cons.Logger.Errorf("Default offset must be \"%s\", \"%s\" or a number. %s given", kinesisOffsetNewest, kinesisOffsetOldest, offsetValue) offsetValue = "0" } cons.defaultOffset = offsetValue } if cons.offsetFile != "" { fileContents, err := ioutil.ReadFile(cons.offsetFile) if err != nil { cons.Logger.Errorf("Failed to open kinesis offset file: %s", err.Error()) } else { cons.offsetType = kinesis.ShardIteratorTypeAfterSequenceNumber conf.Errors.Push(json.Unmarshal(fileContents, &cons.offsets)) } } } func (cons *AwsKinesis) marshalOffsets() ([]byte, error) { cons.offsetsGuard.RLock() defer cons.offsetsGuard.RUnlock() return json.Marshal(cons.offsets) } func (cons *AwsKinesis) storeOffsets() { if cons.offsetFile != "" { fileContents, err := cons.marshalOffsets() if err != nil { cons.Logger.Errorf("Failed to marshal kinesis offsets: %s", err.Error()) return } if err := ioutil.WriteFile(cons.offsetFile, fileContents, 0644); err != nil { cons.Logger.Errorf("Failed to write kinesis offsets: %s", err.Error()) } } } func (cons *AwsKinesis) createShardIteratorConfig(shardID string) *kinesis.GetRecordsInput { for cons.running { cons.offsetsGuard.RLock() offset := cons.offsets[shardID] cons.offsetsGuard.RUnlock() iteratorConfig := kinesis.GetShardIteratorInput{ ShardId: aws.String(shardID), ShardIteratorType: aws.String(cons.offsetType), StreamName: aws.String(cons.stream), StartingSequenceNumber: aws.String(offset), } if *iteratorConfig.StartingSequenceNumber == "" { iteratorConfig.StartingSequenceNumber = nil } else { // starting sequence number requires ShardIteratorTypeAfterSequenceNumber iteratorConfig.ShardIteratorType = aws.String(kinesis.ShardIteratorTypeAfterSequenceNumber) } iterator, err := cons.client.GetShardIterator(&iteratorConfig) if err == nil && iterator.ShardIterator != nil { return &kinesis.GetRecordsInput{ ShardIterator: iterator.ShardIterator, Limit: aws.Int64(cons.recordsPerQuery), } } cons.Logger.Errorf("Failed to iterate shard %s:%s - %s", *iteratorConfig.StreamName, *iteratorConfig.ShardId, err.Error()) time.Sleep(3 * time.Second) } return nil } func (cons *AwsKinesis) processShard(shardID string) { cons.AddWorker() defer cons.WorkerDone() recordConfig := (*kinesis.GetRecordsInput)(nil) for cons.running { if recordConfig == nil { recordConfig = cons.createShardIteratorConfig(shardID) } result, err := cons.client.GetRecords(recordConfig) if err != nil { cons.Logger.Errorf("Failed to get records from shard %s:%s - %s", cons.stream, shardID, err.Error()) if AWSerr, isAWSerr := err.(awserr.Error); isAWSerr { switch AWSerr.Code() { case "ProvisionedThroughputExceededException": // We reached thethroughput limit time.Sleep(5 * time.Second) case "ExpiredIteratorException": // We need to create a new iterator recordConfig = nil } } continue // ### continue ### } if result.NextShardIterator == nil { cons.Logger.Warningf("Shard %s:%s has been closed", cons.stream, shardID) return // ### return, closed ### } for _, record := range result.Records { if record == nil { continue // ### continue ### } if len(cons.delimiter) > 0 { messages := bytes.Split(record.Data, cons.delimiter) for _, msg := range messages { cons.Enqueue(msg) } } else { cons.Enqueue(record.Data) } // Why not an exclusive lock here? // - the map already has an entry for the shardID at this point. // - we are the only one writing to this field // - reading an offset is always a race as it can change at any time // - performance is crucial here // If we could be sure this actually IS a number, we could use atomic.Store here cons.offsetsGuard.RLock() cons.offsets[shardID] = *record.SequenceNumber cons.offsetsGuard.RUnlock() } cons.storeOffsets() recordConfig.ShardIterator = result.NextShardIterator time.Sleep(cons.sleepTime) } } func (cons *AwsKinesis) initKinesisClient() { sess, err := cons.AwsMultiClient.NewSessionWithOptions() if err != nil { cons.Logger.WithError(err).Error("Can't get proper aws config") } awsConfig := cons.AwsMultiClient.GetConfig() // set auto endpoint to s3 if setting is empty if awsConfig.Endpoint == nil || *awsConfig.Endpoint == "" { awsConfig.WithEndpoint(fmt.Sprintf("kinesis.%s.amazonaws.com", *awsConfig.Region)) } cons.client = kinesis.New(sess, awsConfig) } func (cons *AwsKinesis) connect() error { cons.initKinesisClient() // Get shard ids for stream streamQuery := &kinesis.DescribeStreamInput{ StreamName: aws.String(cons.stream), } streamInfo, err := cons.client.DescribeStream(streamQuery) if err != nil { return err } if streamInfo.StreamDescription == nil { return fmt.Errorf("streamDescription could not be retrieved") } cons.running = true for _, shard := range streamInfo.StreamDescription.Shards { if shard.ShardId == nil { return fmt.Errorf("shardId could not be retrieved") } // No locks required here as connect is called only once on start if _, offsetStored := cons.offsets[*shard.ShardId]; !offsetStored { cons.offsets[*shard.ShardId] = cons.defaultOffset } } // No locks required here updateShards is not yet running and processShard // does not change the offsets structure. for shardID := range cons.offsets { cons.Logger.Debugf("Starting consumer for %s:%s", cons.stream, shardID) go cons.processShard(shardID) } if cons.shardTime > 0 { cons.AddWorker() time.AfterFunc(cons.shardTime, cons.updateShards) } return nil } func (cons *AwsKinesis) updateShards() { defer cons.WorkerDone() streamQuery := &kinesis.DescribeStreamInput{ StreamName: aws.String(cons.stream), } for cons.running { streamInfo, err := cons.client.DescribeStream(streamQuery) if err != nil { cons.Logger.Warningf("StreamInfo could not be retrieved.") } if streamInfo.StreamDescription == nil { cons.Logger.Warningf("StreamDescription could not be retrieved.") continue } cons.running = true for _, shard := range streamInfo.StreamDescription.Shards { if shard.ShardId == nil { cons.Logger.Warningf("ShardId could not be retrieved.") continue } cons.offsetsGuard.Lock() if _, offsetStored := cons.offsets[*shard.ShardId]; !offsetStored { cons.offsets[*shard.ShardId] = cons.defaultOffset cons.Logger.Debugf("Starting kinesis consumer for %s:%s", cons.stream, *shard.ShardId) go cons.processShard(*shard.ShardId) } cons.offsetsGuard.Unlock() } time.Sleep(cons.shardTime) } } func (cons *AwsKinesis) close() { cons.running = false cons.WorkerDone() } // Consume listens to stdin. func (cons *AwsKinesis) Consume(workers *sync.WaitGroup) { cons.AddMainWorker(workers) defer cons.close() if err := cons.connect(); err != nil { cons.Logger.Error("Connection error: ", err) } else { cons.ControlLoop() } }
package cockroachdb import ( "context" "database/sql" "errors" "github.com/go-kit/kit/log" "github.com/shijuvar/gokit-examples/services/account" ) var ( ErrRepository = errors.New("unable to handle request") ) type repository struct { db *sql.DB logger log.Logger } // New returns a concrete repository backed by CockroachDB func New(db *sql.DB, logger log.Logger) (account.Repository, error) { // return repository return &repository{ db: db, logger: log.With(logger, "rep", "cockroachdb"), }, nil } // CreateOrder inserts a new order and its order items into db func (repo *repository) CreateCustomer(ctx context.Context, customer account.Customer) error { // Insert order into the "orders" table. sql := ` INSERT INTO customers (id, email, password, phone) VALUES ($1,$2,$3,$4)` _, err := repo.db.ExecContext(ctx, sql, customer.ID, customer.Email, customer.Password, customer.Phone) if err != nil { return err } return nil }
package main import ( "fmt" "html/template" "log" "net/http" "strconv" "time" "github.com/gorilla/mux" ) type SinBlog struct { ID int `db:"id"` UserID int `db:"userid"` Title string `db:"title"` Message string `db:"message"` Category_id int `db:"category_id"` CreateTime time.Time `db:"created_at"` UpdatedTime time.Time `db:"updated_at"` } type StoreSingleBlog struct{ ID int `db:"id"` Message string `db:"message"` } type SinBlogTemplate struct{ SinBlog SinBloglist SinBlog Errors map[string]error } func blogEdit(res http.ResponseWriter,req *http.Request) { parsedTemplate, err := template.ParseFiles( "templates/user/singleblogedit.html", ) if err != nil { log.Println("error while parsing template: ", err.Error()) return } vars := mux.Vars(req) blogid, err := strconv.Atoi(vars["id"]) if err!=nil{ fmt.Println("error occurs when convert string to int",err.Error()) } /*session, err := SessionStore.Get(req, "first_app-session") if err != nil { log.Println("error while getting session: ", err.Error()) } userID := session.Values["user_id"]*/ var sinBlog SinBlog query := ` SELECT * FROM blogss WHERE id = $1 ` if err := DB.Get(&sinBlog, query, blogid); err != nil { log.Println("error while getting blog from db: ", err.Error()) } if err := parsedTemplate.Execute(res, SinBlogTemplate{ SinBloglist: sinBlog, }); err != nil { log.Println("error while executing template: ", err.Error()) } } func blogUpdate(res http.ResponseWriter,req *http.Request){ err := req.ParseForm() if err != nil { log.Println("error while parsing form: ", err.Error()) } var storeSingleBlog StoreSingleBlog err = decoder.Decode(&storeSingleBlog,req.PostForm) if err != nil { log.Println("error while decoding form to struct: ", err.Error()) } vars := mux.Vars(req) blogid, err := strconv.Atoi(vars["id"]) if err!=nil{ fmt.Println("error occurs when convert string to int",err.Error()) } storeSingleBlog.ID = blogid //log.Println("storeSingleBlog.ID is = ",storeSingleBlog.ID) //log.Println("Message is = ",storeSingleBlog.Message) query := ` UPDATE blogss SET message = :message WHERE blogss.id = :id ` stmt, err := DB.PrepareNamed(query) if err != nil { log.Println("db error: failed prepare ", err.Error()) return } if _, err := stmt.Exec(&storeSingleBlog); err != nil { log.Println("db error: failed to update data ", err.Error()) return } http.Redirect(res, req, fmt.Sprintf("/blogs/%d", blogid), http.StatusSeeOther) } func blogDelete(res http.ResponseWriter, req *http.Request){ vars := mux.Vars(req) blogId := vars["id"] var sinBlog SinBlog blogID, err := strconv.Atoi(blogId) if err != nil { log.Println("error while convert string to int : ", err.Error()) } sinBlog.ID = blogID log.Println("blog id",blogID) query := ` DELETE FROM blogss WHERE id = :id ` stmt, err := DB.PrepareNamed(query) if err != nil { log.Println("db error: failed prepare ", err.Error()) return } if _, err := stmt.Exec(&sinBlog); err != nil { log.Println("db error: failed to update data ", err.Error()) return } http.Redirect(res, req, "/blogsdetails/1", http.StatusSeeOther) }
package main import ( "fmt" "sort" ) func main() { a := []Interval{Interval{1, 3}, Interval{2, 6}, Interval{8, 10}, Interval{9, 18}} // fmt.Println(merge(a)) a = []Interval{Interval{1, 4}, Interval{0, 2}, Interval{3, 5}} fmt.Println(merge(a)) } // Interval Definition for an interval. type Interval struct { Start int End int } type sortInterval []Interval func (s sortInterval) Less(i, j int) bool { return s[i].Start < s[j].Start } func (s sortInterval) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s sortInterval) Len() int { return len(s) } func merge(intervals []Interval) []Interval { if len(intervals) == 0 || len(intervals) == 1 { return intervals } sort.Sort(sortInterval(intervals)) // fmt.Println(intervals) res := []Interval{} start := 0 end := 0 for i := 1; i < len(intervals); i++ { if intervals[i].Start <= intervals[end].End { if intervals[i].End > intervals[end].End { end = i } } else { res = append(res, Interval{intervals[start].Start, intervals[end].End}) start = i end = i } // fmt.Println(i, start, end, res) } res = append(res, Interval{intervals[start].Start, intervals[end].End}) return res }
/** * Created by GoLand. * User: link1st * Date: 2019-08-01 * Time: 10:40 */ package models import "gowebsocket/common" const ( MessageTypeText = "text" MessageTypeImage = "image" MessageTypeVoice = "voice" MessageCmdMsg = "msg" MessageCmdEnter = "enter" MessageCmdExit = "exit" SystemNoticeType = "00" ChatNoticeType = "01" PraiseNoticeType = "02" DissNoticeType = "02" CommentNoticeType = "03" ) // 消息的定义 type Message struct { Target string `json:"target"` // 目标 Type string `json:"type"` // 消息类型 text/image/ Msg string `json:"msg"` // 消息内容 From string `json:"from"` // 发送者 To string `json:"to"` // 接收者 SendTime uint64 `json:"sendTime"` // 发送时间(UNIX() 时间) } func NewTestMsg(from string, to string, Msg string) (message *Message) { message = &Message{ Type: MessageTypeText, From: from, To: to, Msg: Msg, } return } func NewTestMsgWithSendTime(from string, to string, Msg string, sendTime uint64) (message *Message) { message = &Message{ Type: MessageTypeText, From: from, To: to, Msg: Msg, SendTime: sendTime, } return } /* seq: 消息的唯一id cmd: 消息的动作:enter(login)、msg、exit(logout) response:返回前端的数据 from: 消息发送者id to: 消息接收者id { "seq":"1577033806984-838426", "cmd":"msg", "response":{ "code":200, "codeMsg":"Ok", "data":{ "target":"", "type":"text", "msg":"213123213213", "from":"29868", "to":"29868" "sendTime":1582804913 } } } */ func getTextMsgData(cmd, fromId, toId, msgId, message string) string { textMsg := NewTestMsg(fromId, toId, message) head := NewResponseHead(msgId, cmd, common.OK, "Ok", textMsg) return head.String() } func getTextMsgDataWithSendTime(cmd, fromId, toId, msgId, message string, sendTime uint64) string { textMsg := NewTestMsgWithSendTime(fromId, toId, message, sendTime) head := NewResponseHead(msgId, cmd, common.OK, "Ok", textMsg) return head.String() } // 封装 Data // 给 All 用户发送消息 func GetMsgData(userId, msgId, cmd, message string, sendTime uint64) string { return getTextMsgDataWithSendTime(cmd, userId, "All", msgId, message, sendTime) } // 封装 Data // 给指定用户发送消息 func GetTextMsgData(fromId, toId, msgId, message string, sendTime uint64) string { return getTextMsgDataWithSendTime("msg", fromId, toId, msgId, message, sendTime) } // 用户进入消息 func GetTextMsgDataEnter(fromId, toId, msgId, message string) string { return getTextMsgData("enter", fromId, toId, msgId, message) } // 用户退出消息 func GetTextMsgDataExit(fromId, toId, msgId, message string) string { return getTextMsgData("exit", fromId, toId, msgId, message) }
package main import ( "encoding/json" "fmt" ) func main() { // Arrays var arr = [5]int{1, 2, 3} println(arr[2]) var arr1 = []string{"Hola", "mundo"} println(arr1[1]) var arr3 = []bool{true, false, false} println(arr3[2]) // Slices var mySlice = make([]int, 20) println(mySlice[1]) mySlice = append(mySlice, 5) // Append an element to a slice println(mySlice[20]) // Remove the first element of a slice mySlice = mySlice[1:] // Remove the first element of a slice mySlice = append(mySlice[:1], mySlice[2:]...) // Remove the last element of a slice mySlice = mySlice[:len(mySlice)-1] // Maps var myMap = make(map[string]int) myMap["one"] = 1 myMap["two"] = 2 println(myMap["two"]) // Json map var myJsonMap = make(map[string]interface{}) var jsonData = []byte(`{"hello":"world"}`) var err = json.Unmarshal(jsonData, &myJsonMap) if err != nil { panic(err) } fmt.Printf("%s", myJsonMap["hello"]) }
package AdminControllers import ( "strings" "github.com/astaxie/beego/orm" "lazybug.me/conv" "github.com/TruthHun/DocHub/models" ) type CrawlController struct { BaseController } //采集管理 func (this *CrawlController) Get() { Type := this.GetString("type", "gitbook") //默认是gitbook p, _ := this.GetInt("p", 1) //页码 listRows := 20 //每页显示记录数 //分类 var cates []models.Category models.O.QueryTable(models.TableCategory).OrderBy("Sort", "Title").All(&cates) //标题关键字 Title := this.GetString("title") Topic := this.GetString("topic") var ( TotalRows int64 = 0 //默认总记录数 data []orm.Params ) switch Type { case "gitbook": cond := orm.NewCondition().And("Id__gt", 0) if len(Title) > 0 { cond = cond.And("Title__contains", Title) } if len(Topic) > 0 { cond = cond.And("Topics__icontains", Topic) } data, _, _ = models.GetList("gitbook", p, listRows, cond, "PublishPdf", "PublishEpub", "PublishMobi", "-Stars") TotalRows = models.Count(models.TableGitbook, cond) } this.Data["IsCrawl"] = true this.Data["CatesJson"], _ = conv.InterfaceToJson(cates) this.Data["Cates"] = cates this.Data["Data"] = data this.Data["Type"] = Type this.Data["topic"] = Topic this.Data["title"] = Title this.Data["TotalRows"] = TotalRows this.TplName = "index.html" } //Gitbook发布 func (this *CrawlController) PublishGitbook() { if models.GlobalGitbookPublishing { this.ResponseJson(0, "存在正在发布的GitBook") } Chanel, _ := this.GetInt("Chanel") //频道 Parent, _ := this.GetInt("Parent") //父类 Children, _ := this.GetInt("Children") //子类 Uid, _ := this.GetInt("Uid") //发布人id Ids := this.GetString("Ids") //文档id if Chanel*Parent*Children*Uid == 0 || len(Ids) == 0 { this.ResponseJson(0, "所有选项均为必填项") } //标记为正在发布 models.GlobalGitbookPublishing = true //查询电子书 IdsArr := strings.Split(Ids, ",") //执行发布操作 go models.ModelGitbook.PublishBooks(Chanel, Parent, Children, Uid, IdsArr) this.ResponseJson(1, "GitBook发布操作提交成功,程序自会执行发布操作") }
package builtin import ( "github.com/kumahq/kuma/pkg/core/resources/manager" "github.com/kumahq/kuma/pkg/tokens/builtin/issuer" "github.com/kumahq/kuma/pkg/tokens/builtin/zoneingress" ) func NewDataplaneTokenIssuer(resManager manager.ReadOnlyResourceManager) (issuer.DataplaneTokenIssuer, error) { return issuer.NewDataplaneTokenIssuer(func(meshName string) ([]byte, error) { return issuer.GetSigningKey(resManager, issuer.DataplaneTokenPrefix, meshName) }), nil } func NewZoneIngressTokenIssuer(resManager manager.ReadOnlyResourceManager) (zoneingress.TokenIssuer, error) { return zoneingress.NewTokenIssuer(func() ([]byte, error) { return zoneingress.GetSigningKey(resManager) }), nil }
package main import ( "context" "github.com/hashicorp/vault/sdk/framework" "github.com/hashicorp/vault/sdk/helper/policyutil" "github.com/hashicorp/vault/sdk/logical" ) const REPO_PATH_PREFIX = "repositories" func (b *backend) pathRepositoriesList() *framework.Path { return &framework.Path{ Pattern: REPO_PATH_PREFIX + "/?$", Operations: map[logical.Operation]framework.OperationHandler{ logical.ListOperation: &framework.PathOperation{ Callback: b.pathRepositoryList, }, }, HelpSynopsis: pathRepositoryHelpSyn, HelpDescription: pathRepositoryHelpDesc, } } func (b *backend) pathRepositories() *framework.Path { return &framework.Path{ Pattern: REPO_PATH_PREFIX + `/(?P<name>.+)`, Fields: map[string]*framework.FieldSchema{ "name": { Type: framework.TypeString, Description: "Name of the Github repository.", }, "policies": { Type: framework.TypeCommaStringSlice, Description: "Comma-separated list of policies associated to the repository.", }, }, Operations: map[logical.Operation]framework.OperationHandler{ logical.DeleteOperation: &framework.PathOperation{ Callback: b.pathRepositoryDelete, }, logical.ReadOperation: &framework.PathOperation{ Callback: b.pathRepositoryRead, }, logical.UpdateOperation: &framework.PathOperation{ Callback: b.pathRepositoryWrite, }, }, HelpSynopsis: pathRepositoryHelpSyn, HelpDescription: pathRepositoryHelpDesc, } } func (b *backend) Repository(ctx context.Context, s logical.Storage, n string) (*RepositoryEntry, error) { entry, err := s.Get(ctx, "repository/"+n) if err != nil { return nil, err } if entry == nil { return &RepositoryEntry{}, nil } var result RepositoryEntry if err := entry.DecodeJSON(&result); err != nil { return nil, err } return &result, nil } func (b *backend) pathRepositoryDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { err := req.Storage.Delete(ctx, "repository/"+d.Get("name").(string)) if err != nil { return nil, err } return nil, nil } func (b *backend) pathRepositoryRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { repository, err := b.Repository(ctx, req.Storage, d.Get("name").(string)) if err != nil { return nil, err } if repository == nil { return nil, nil } return &logical.Response{ Data: map[string]interface{}{ "policies": repository.Policies, }, }, nil } func (b *backend) pathRepositoryWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { // Store it entry, err := logical.StorageEntryJSON("repository/"+d.Get("name").(string), &RepositoryEntry{ Policies: policyutil.ParsePolicies(d.Get("policies")), }) if err != nil { return nil, err } if err := req.Storage.Put(ctx, entry); err != nil { return nil, err } return nil, nil } func (b *backend) pathRepositoryList(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) { repositories, err := req.Storage.List(ctx, "repository/") if err != nil { return nil, err } return logical.ListResponse(repositories), nil } type RepositoryEntry struct { Policies []string } const pathRepositoryHelpSyn = ` Manage repositories allowed to authenticate. ` const pathRepositoryHelpDesc = ` This endpoint allows you to create, read, update, and delete configuration for repositories that are allowed to authenticate, and associate policies to them. `
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "context" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto" iampb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/iam/iam_go_proto" "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/iam" ) // WorkforcePoolProviderServer implements the gRPC interface for WorkforcePoolProvider. type WorkforcePoolProviderServer struct{} // ProtoToWorkforcePoolProviderStateEnum converts a WorkforcePoolProviderStateEnum enum from its proto representation. func ProtoToIamWorkforcePoolProviderStateEnum(e iampb.IamWorkforcePoolProviderStateEnum) *iam.WorkforcePoolProviderStateEnum { if e == 0 { return nil } if n, ok := iampb.IamWorkforcePoolProviderStateEnum_name[int32(e)]; ok { e := iam.WorkforcePoolProviderStateEnum(n[len("IamWorkforcePoolProviderStateEnum"):]) return &e } return nil } // ProtoToWorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum converts a WorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum enum from its proto representation. func ProtoToIamWorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum(e iampb.IamWorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum) *iam.WorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum { if e == 0 { return nil } if n, ok := iampb.IamWorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum_name[int32(e)]; ok { e := iam.WorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum(n[len("IamWorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum"):]) return &e } return nil } // ProtoToWorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum converts a WorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum enum from its proto representation. func ProtoToIamWorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum(e iampb.IamWorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum) *iam.WorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum { if e == 0 { return nil } if n, ok := iampb.IamWorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum_name[int32(e)]; ok { e := iam.WorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum(n[len("IamWorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum"):]) return &e } return nil } // ProtoToWorkforcePoolProviderSaml converts a WorkforcePoolProviderSaml object from its proto representation. func ProtoToIamWorkforcePoolProviderSaml(p *iampb.IamWorkforcePoolProviderSaml) *iam.WorkforcePoolProviderSaml { if p == nil { return nil } obj := &iam.WorkforcePoolProviderSaml{ IdpMetadataXml: dcl.StringOrNil(p.GetIdpMetadataXml()), } return obj } // ProtoToWorkforcePoolProviderOidc converts a WorkforcePoolProviderOidc object from its proto representation. func ProtoToIamWorkforcePoolProviderOidc(p *iampb.IamWorkforcePoolProviderOidc) *iam.WorkforcePoolProviderOidc { if p == nil { return nil } obj := &iam.WorkforcePoolProviderOidc{ IssuerUri: dcl.StringOrNil(p.GetIssuerUri()), ClientId: dcl.StringOrNil(p.GetClientId()), JwksJson: dcl.StringOrNil(p.GetJwksJson()), WebSsoConfig: ProtoToIamWorkforcePoolProviderOidcWebSsoConfig(p.GetWebSsoConfig()), ClientSecret: ProtoToIamWorkforcePoolProviderOidcClientSecret(p.GetClientSecret()), } return obj } // ProtoToWorkforcePoolProviderOidcWebSsoConfig converts a WorkforcePoolProviderOidcWebSsoConfig object from its proto representation. func ProtoToIamWorkforcePoolProviderOidcWebSsoConfig(p *iampb.IamWorkforcePoolProviderOidcWebSsoConfig) *iam.WorkforcePoolProviderOidcWebSsoConfig { if p == nil { return nil } obj := &iam.WorkforcePoolProviderOidcWebSsoConfig{ ResponseType: ProtoToIamWorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum(p.GetResponseType()), AssertionClaimsBehavior: ProtoToIamWorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum(p.GetAssertionClaimsBehavior()), } for _, r := range p.GetAdditionalScopes() { obj.AdditionalScopes = append(obj.AdditionalScopes, r) } return obj } // ProtoToWorkforcePoolProviderOidcClientSecret converts a WorkforcePoolProviderOidcClientSecret object from its proto representation. func ProtoToIamWorkforcePoolProviderOidcClientSecret(p *iampb.IamWorkforcePoolProviderOidcClientSecret) *iam.WorkforcePoolProviderOidcClientSecret { if p == nil { return nil } obj := &iam.WorkforcePoolProviderOidcClientSecret{ Value: ProtoToIamWorkforcePoolProviderOidcClientSecretValue(p.GetValue()), } return obj } // ProtoToWorkforcePoolProviderOidcClientSecretValue converts a WorkforcePoolProviderOidcClientSecretValue object from its proto representation. func ProtoToIamWorkforcePoolProviderOidcClientSecretValue(p *iampb.IamWorkforcePoolProviderOidcClientSecretValue) *iam.WorkforcePoolProviderOidcClientSecretValue { if p == nil { return nil } obj := &iam.WorkforcePoolProviderOidcClientSecretValue{ PlainText: dcl.StringOrNil(p.GetPlainText()), Thumbprint: dcl.StringOrNil(p.GetThumbprint()), } return obj } // ProtoToWorkforcePoolProvider converts a WorkforcePoolProvider resource from its proto representation. func ProtoToWorkforcePoolProvider(p *iampb.IamWorkforcePoolProvider) *iam.WorkforcePoolProvider { obj := &iam.WorkforcePoolProvider{ Name: dcl.StringOrNil(p.GetName()), DisplayName: dcl.StringOrNil(p.GetDisplayName()), Description: dcl.StringOrNil(p.GetDescription()), State: ProtoToIamWorkforcePoolProviderStateEnum(p.GetState()), Disabled: dcl.Bool(p.GetDisabled()), AttributeCondition: dcl.StringOrNil(p.GetAttributeCondition()), Saml: ProtoToIamWorkforcePoolProviderSaml(p.GetSaml()), Oidc: ProtoToIamWorkforcePoolProviderOidc(p.GetOidc()), Location: dcl.StringOrNil(p.GetLocation()), WorkforcePool: dcl.StringOrNil(p.GetWorkforcePool()), } return obj } // WorkforcePoolProviderStateEnumToProto converts a WorkforcePoolProviderStateEnum enum to its proto representation. func IamWorkforcePoolProviderStateEnumToProto(e *iam.WorkforcePoolProviderStateEnum) iampb.IamWorkforcePoolProviderStateEnum { if e == nil { return iampb.IamWorkforcePoolProviderStateEnum(0) } if v, ok := iampb.IamWorkforcePoolProviderStateEnum_value["WorkforcePoolProviderStateEnum"+string(*e)]; ok { return iampb.IamWorkforcePoolProviderStateEnum(v) } return iampb.IamWorkforcePoolProviderStateEnum(0) } // WorkforcePoolProviderOidcWebSsoConfigResponseTypeEnumToProto converts a WorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum enum to its proto representation. func IamWorkforcePoolProviderOidcWebSsoConfigResponseTypeEnumToProto(e *iam.WorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum) iampb.IamWorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum { if e == nil { return iampb.IamWorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum(0) } if v, ok := iampb.IamWorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum_value["WorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum"+string(*e)]; ok { return iampb.IamWorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum(v) } return iampb.IamWorkforcePoolProviderOidcWebSsoConfigResponseTypeEnum(0) } // WorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnumToProto converts a WorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum enum to its proto representation. func IamWorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnumToProto(e *iam.WorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum) iampb.IamWorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum { if e == nil { return iampb.IamWorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum(0) } if v, ok := iampb.IamWorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum_value["WorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum"+string(*e)]; ok { return iampb.IamWorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum(v) } return iampb.IamWorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnum(0) } // WorkforcePoolProviderSamlToProto converts a WorkforcePoolProviderSaml object to its proto representation. func IamWorkforcePoolProviderSamlToProto(o *iam.WorkforcePoolProviderSaml) *iampb.IamWorkforcePoolProviderSaml { if o == nil { return nil } p := &iampb.IamWorkforcePoolProviderSaml{} p.SetIdpMetadataXml(dcl.ValueOrEmptyString(o.IdpMetadataXml)) return p } // WorkforcePoolProviderOidcToProto converts a WorkforcePoolProviderOidc object to its proto representation. func IamWorkforcePoolProviderOidcToProto(o *iam.WorkforcePoolProviderOidc) *iampb.IamWorkforcePoolProviderOidc { if o == nil { return nil } p := &iampb.IamWorkforcePoolProviderOidc{} p.SetIssuerUri(dcl.ValueOrEmptyString(o.IssuerUri)) p.SetClientId(dcl.ValueOrEmptyString(o.ClientId)) p.SetJwksJson(dcl.ValueOrEmptyString(o.JwksJson)) p.SetWebSsoConfig(IamWorkforcePoolProviderOidcWebSsoConfigToProto(o.WebSsoConfig)) p.SetClientSecret(IamWorkforcePoolProviderOidcClientSecretToProto(o.ClientSecret)) return p } // WorkforcePoolProviderOidcWebSsoConfigToProto converts a WorkforcePoolProviderOidcWebSsoConfig object to its proto representation. func IamWorkforcePoolProviderOidcWebSsoConfigToProto(o *iam.WorkforcePoolProviderOidcWebSsoConfig) *iampb.IamWorkforcePoolProviderOidcWebSsoConfig { if o == nil { return nil } p := &iampb.IamWorkforcePoolProviderOidcWebSsoConfig{} p.SetResponseType(IamWorkforcePoolProviderOidcWebSsoConfigResponseTypeEnumToProto(o.ResponseType)) p.SetAssertionClaimsBehavior(IamWorkforcePoolProviderOidcWebSsoConfigAssertionClaimsBehaviorEnumToProto(o.AssertionClaimsBehavior)) sAdditionalScopes := make([]string, len(o.AdditionalScopes)) for i, r := range o.AdditionalScopes { sAdditionalScopes[i] = r } p.SetAdditionalScopes(sAdditionalScopes) return p } // WorkforcePoolProviderOidcClientSecretToProto converts a WorkforcePoolProviderOidcClientSecret object to its proto representation. func IamWorkforcePoolProviderOidcClientSecretToProto(o *iam.WorkforcePoolProviderOidcClientSecret) *iampb.IamWorkforcePoolProviderOidcClientSecret { if o == nil { return nil } p := &iampb.IamWorkforcePoolProviderOidcClientSecret{} p.SetValue(IamWorkforcePoolProviderOidcClientSecretValueToProto(o.Value)) return p } // WorkforcePoolProviderOidcClientSecretValueToProto converts a WorkforcePoolProviderOidcClientSecretValue object to its proto representation. func IamWorkforcePoolProviderOidcClientSecretValueToProto(o *iam.WorkforcePoolProviderOidcClientSecretValue) *iampb.IamWorkforcePoolProviderOidcClientSecretValue { if o == nil { return nil } p := &iampb.IamWorkforcePoolProviderOidcClientSecretValue{} p.SetPlainText(dcl.ValueOrEmptyString(o.PlainText)) p.SetThumbprint(dcl.ValueOrEmptyString(o.Thumbprint)) return p } // WorkforcePoolProviderToProto converts a WorkforcePoolProvider resource to its proto representation. func WorkforcePoolProviderToProto(resource *iam.WorkforcePoolProvider) *iampb.IamWorkforcePoolProvider { p := &iampb.IamWorkforcePoolProvider{} p.SetName(dcl.ValueOrEmptyString(resource.Name)) p.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName)) p.SetDescription(dcl.ValueOrEmptyString(resource.Description)) p.SetState(IamWorkforcePoolProviderStateEnumToProto(resource.State)) p.SetDisabled(dcl.ValueOrEmptyBool(resource.Disabled)) p.SetAttributeCondition(dcl.ValueOrEmptyString(resource.AttributeCondition)) p.SetSaml(IamWorkforcePoolProviderSamlToProto(resource.Saml)) p.SetOidc(IamWorkforcePoolProviderOidcToProto(resource.Oidc)) p.SetLocation(dcl.ValueOrEmptyString(resource.Location)) p.SetWorkforcePool(dcl.ValueOrEmptyString(resource.WorkforcePool)) mAttributeMapping := make(map[string]string, len(resource.AttributeMapping)) for k, r := range resource.AttributeMapping { mAttributeMapping[k] = r } p.SetAttributeMapping(mAttributeMapping) return p } // applyWorkforcePoolProvider handles the gRPC request by passing it to the underlying WorkforcePoolProvider Apply() method. func (s *WorkforcePoolProviderServer) applyWorkforcePoolProvider(ctx context.Context, c *iam.Client, request *iampb.ApplyIamWorkforcePoolProviderRequest) (*iampb.IamWorkforcePoolProvider, error) { p := ProtoToWorkforcePoolProvider(request.GetResource()) res, err := c.ApplyWorkforcePoolProvider(ctx, p) if err != nil { return nil, err } r := WorkforcePoolProviderToProto(res) return r, nil } // applyIamWorkforcePoolProvider handles the gRPC request by passing it to the underlying WorkforcePoolProvider Apply() method. func (s *WorkforcePoolProviderServer) ApplyIamWorkforcePoolProvider(ctx context.Context, request *iampb.ApplyIamWorkforcePoolProviderRequest) (*iampb.IamWorkforcePoolProvider, error) { cl, err := createConfigWorkforcePoolProvider(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return s.applyWorkforcePoolProvider(ctx, cl, request) } // DeleteWorkforcePoolProvider handles the gRPC request by passing it to the underlying WorkforcePoolProvider Delete() method. func (s *WorkforcePoolProviderServer) DeleteIamWorkforcePoolProvider(ctx context.Context, request *iampb.DeleteIamWorkforcePoolProviderRequest) (*emptypb.Empty, error) { cl, err := createConfigWorkforcePoolProvider(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return &emptypb.Empty{}, cl.DeleteWorkforcePoolProvider(ctx, ProtoToWorkforcePoolProvider(request.GetResource())) } // ListIamWorkforcePoolProvider handles the gRPC request by passing it to the underlying WorkforcePoolProviderList() method. func (s *WorkforcePoolProviderServer) ListIamWorkforcePoolProvider(ctx context.Context, request *iampb.ListIamWorkforcePoolProviderRequest) (*iampb.ListIamWorkforcePoolProviderResponse, error) { cl, err := createConfigWorkforcePoolProvider(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } resources, err := cl.ListWorkforcePoolProvider(ctx, request.GetLocation(), request.GetWorkforcePool()) if err != nil { return nil, err } var protos []*iampb.IamWorkforcePoolProvider for _, r := range resources.Items { rp := WorkforcePoolProviderToProto(r) protos = append(protos, rp) } p := &iampb.ListIamWorkforcePoolProviderResponse{} p.SetItems(protos) return p, nil } func createConfigWorkforcePoolProvider(ctx context.Context, service_account_file string) (*iam.Client, error) { conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file)) return iam.NewClient(conf), nil }
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ var ret []int func rightSideView(root *TreeNode) []int { ret = make([]int, 0) if root == nil{ return ret } helper(root, 0) return ret } func helper(nd *TreeNode, level int){ if nd == nil{ return } if len(ret) <= level{ ret = append(ret, 0) } ret[level] = nd.Val helper(nd.Left, level+1) helper(nd.Right, level+1) }
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cloudscheduler import ( "context" "crypto/sha256" "encoding/json" "fmt" "time" "google.golang.org/api/googleapi" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" ) type Job struct { Name *string `json:"name"` Description *string `json:"description"` PubsubTarget *JobPubsubTarget `json:"pubsubTarget"` AppEngineHttpTarget *JobAppEngineHttpTarget `json:"appEngineHttpTarget"` HttpTarget *JobHttpTarget `json:"httpTarget"` Schedule *string `json:"schedule"` TimeZone *string `json:"timeZone"` UserUpdateTime *string `json:"userUpdateTime"` State *JobStateEnum `json:"state"` Status *JobStatus `json:"status"` ScheduleTime *string `json:"scheduleTime"` LastAttemptTime *string `json:"lastAttemptTime"` RetryConfig *JobRetryConfig `json:"retryConfig"` AttemptDeadline *string `json:"attemptDeadline"` Project *string `json:"project"` Location *string `json:"location"` } func (r *Job) String() string { return dcl.SprintResource(r) } // The enum JobAppEngineHttpTargetHttpMethodEnum. type JobAppEngineHttpTargetHttpMethodEnum string // JobAppEngineHttpTargetHttpMethodEnumRef returns a *JobAppEngineHttpTargetHttpMethodEnum with the value of string s // If the empty string is provided, nil is returned. func JobAppEngineHttpTargetHttpMethodEnumRef(s string) *JobAppEngineHttpTargetHttpMethodEnum { v := JobAppEngineHttpTargetHttpMethodEnum(s) return &v } func (v JobAppEngineHttpTargetHttpMethodEnum) Validate() error { if string(v) == "" { // Empty enum is okay. return nil } for _, s := range []string{"HTTP_METHOD_UNSPECIFIED", "POST", "GET", "HEAD", "PUT", "DELETE", "PATCH", "OPTIONS"} { if string(v) == s { return nil } } return &dcl.EnumInvalidError{ Enum: "JobAppEngineHttpTargetHttpMethodEnum", Value: string(v), Valid: []string{}, } } // The enum JobHttpTargetHttpMethodEnum. type JobHttpTargetHttpMethodEnum string // JobHttpTargetHttpMethodEnumRef returns a *JobHttpTargetHttpMethodEnum with the value of string s // If the empty string is provided, nil is returned. func JobHttpTargetHttpMethodEnumRef(s string) *JobHttpTargetHttpMethodEnum { v := JobHttpTargetHttpMethodEnum(s) return &v } func (v JobHttpTargetHttpMethodEnum) Validate() error { if string(v) == "" { // Empty enum is okay. return nil } for _, s := range []string{"HTTP_METHOD_UNSPECIFIED", "POST", "GET", "HEAD", "PUT", "DELETE", "PATCH", "OPTIONS"} { if string(v) == s { return nil } } return &dcl.EnumInvalidError{ Enum: "JobHttpTargetHttpMethodEnum", Value: string(v), Valid: []string{}, } } // The enum JobStateEnum. type JobStateEnum string // JobStateEnumRef returns a *JobStateEnum with the value of string s // If the empty string is provided, nil is returned. func JobStateEnumRef(s string) *JobStateEnum { v := JobStateEnum(s) return &v } func (v JobStateEnum) Validate() error { if string(v) == "" { // Empty enum is okay. return nil } for _, s := range []string{"STATE_UNSPECIFIED", "ENABLED", "PAUSED", "DISABLED", "UPDATE_FAILED"} { if string(v) == s { return nil } } return &dcl.EnumInvalidError{ Enum: "JobStateEnum", Value: string(v), Valid: []string{}, } } type JobPubsubTarget struct { empty bool `json:"-"` TopicName *string `json:"topicName"` Data *string `json:"data"` Attributes map[string]string `json:"attributes"` } type jsonJobPubsubTarget JobPubsubTarget func (r *JobPubsubTarget) UnmarshalJSON(data []byte) error { var res jsonJobPubsubTarget if err := json.Unmarshal(data, &res); err != nil { return err } var m map[string]interface{} json.Unmarshal(data, &m) if len(m) == 0 { *r = *EmptyJobPubsubTarget } else { r.TopicName = res.TopicName r.Data = res.Data r.Attributes = res.Attributes } return nil } // This object is used to assert a desired state where this JobPubsubTarget is // empty. Go lacks global const objects, but this object should be treated // as one. Modifying this object will have undesirable results. var EmptyJobPubsubTarget *JobPubsubTarget = &JobPubsubTarget{empty: true} func (r *JobPubsubTarget) Empty() bool { return r.empty } func (r *JobPubsubTarget) String() string { return dcl.SprintResource(r) } func (r *JobPubsubTarget) HashCode() string { // Placeholder for a more complex hash method that handles ordering, etc // Hash resource body for easy comparison later hash := sha256.New().Sum([]byte(r.String())) return fmt.Sprintf("%x", hash) } type JobAppEngineHttpTarget struct { empty bool `json:"-"` HttpMethod *JobAppEngineHttpTargetHttpMethodEnum `json:"httpMethod"` AppEngineRouting *JobAppEngineHttpTargetAppEngineRouting `json:"appEngineRouting"` RelativeUri *string `json:"relativeUri"` Headers map[string]string `json:"headers"` Body *string `json:"body"` } type jsonJobAppEngineHttpTarget JobAppEngineHttpTarget func (r *JobAppEngineHttpTarget) UnmarshalJSON(data []byte) error { var res jsonJobAppEngineHttpTarget if err := json.Unmarshal(data, &res); err != nil { return err } var m map[string]interface{} json.Unmarshal(data, &m) if len(m) == 0 { *r = *EmptyJobAppEngineHttpTarget } else { r.HttpMethod = res.HttpMethod r.AppEngineRouting = res.AppEngineRouting r.RelativeUri = res.RelativeUri r.Headers = res.Headers r.Body = res.Body } return nil } // This object is used to assert a desired state where this JobAppEngineHttpTarget is // empty. Go lacks global const objects, but this object should be treated // as one. Modifying this object will have undesirable results. var EmptyJobAppEngineHttpTarget *JobAppEngineHttpTarget = &JobAppEngineHttpTarget{empty: true} func (r *JobAppEngineHttpTarget) Empty() bool { return r.empty } func (r *JobAppEngineHttpTarget) String() string { return dcl.SprintResource(r) } func (r *JobAppEngineHttpTarget) HashCode() string { // Placeholder for a more complex hash method that handles ordering, etc // Hash resource body for easy comparison later hash := sha256.New().Sum([]byte(r.String())) return fmt.Sprintf("%x", hash) } type JobAppEngineHttpTargetAppEngineRouting struct { empty bool `json:"-"` Service *string `json:"service"` Version *string `json:"version"` Instance *string `json:"instance"` Host *string `json:"host"` } type jsonJobAppEngineHttpTargetAppEngineRouting JobAppEngineHttpTargetAppEngineRouting func (r *JobAppEngineHttpTargetAppEngineRouting) UnmarshalJSON(data []byte) error { var res jsonJobAppEngineHttpTargetAppEngineRouting if err := json.Unmarshal(data, &res); err != nil { return err } var m map[string]interface{} json.Unmarshal(data, &m) if len(m) == 0 { *r = *EmptyJobAppEngineHttpTargetAppEngineRouting } else { r.Service = res.Service r.Version = res.Version r.Instance = res.Instance r.Host = res.Host } return nil } // This object is used to assert a desired state where this JobAppEngineHttpTargetAppEngineRouting is // empty. Go lacks global const objects, but this object should be treated // as one. Modifying this object will have undesirable results. var EmptyJobAppEngineHttpTargetAppEngineRouting *JobAppEngineHttpTargetAppEngineRouting = &JobAppEngineHttpTargetAppEngineRouting{empty: true} func (r *JobAppEngineHttpTargetAppEngineRouting) Empty() bool { return r.empty } func (r *JobAppEngineHttpTargetAppEngineRouting) String() string { return dcl.SprintResource(r) } func (r *JobAppEngineHttpTargetAppEngineRouting) HashCode() string { // Placeholder for a more complex hash method that handles ordering, etc // Hash resource body for easy comparison later hash := sha256.New().Sum([]byte(r.String())) return fmt.Sprintf("%x", hash) } type JobHttpTarget struct { empty bool `json:"-"` Uri *string `json:"uri"` HttpMethod *JobHttpTargetHttpMethodEnum `json:"httpMethod"` Headers map[string]string `json:"headers"` Body *string `json:"body"` OAuthToken *JobHttpTargetOAuthToken `json:"oauthToken"` OidcToken *JobHttpTargetOidcToken `json:"oidcToken"` } type jsonJobHttpTarget JobHttpTarget func (r *JobHttpTarget) UnmarshalJSON(data []byte) error { var res jsonJobHttpTarget if err := json.Unmarshal(data, &res); err != nil { return err } var m map[string]interface{} json.Unmarshal(data, &m) if len(m) == 0 { *r = *EmptyJobHttpTarget } else { r.Uri = res.Uri r.HttpMethod = res.HttpMethod r.Headers = res.Headers r.Body = res.Body r.OAuthToken = res.OAuthToken r.OidcToken = res.OidcToken } return nil } // This object is used to assert a desired state where this JobHttpTarget is // empty. Go lacks global const objects, but this object should be treated // as one. Modifying this object will have undesirable results. var EmptyJobHttpTarget *JobHttpTarget = &JobHttpTarget{empty: true} func (r *JobHttpTarget) Empty() bool { return r.empty } func (r *JobHttpTarget) String() string { return dcl.SprintResource(r) } func (r *JobHttpTarget) HashCode() string { // Placeholder for a more complex hash method that handles ordering, etc // Hash resource body for easy comparison later hash := sha256.New().Sum([]byte(r.String())) return fmt.Sprintf("%x", hash) } type JobHttpTargetOAuthToken struct { empty bool `json:"-"` ServiceAccountEmail *string `json:"serviceAccountEmail"` Scope *string `json:"scope"` } type jsonJobHttpTargetOAuthToken JobHttpTargetOAuthToken func (r *JobHttpTargetOAuthToken) UnmarshalJSON(data []byte) error { var res jsonJobHttpTargetOAuthToken if err := json.Unmarshal(data, &res); err != nil { return err } var m map[string]interface{} json.Unmarshal(data, &m) if len(m) == 0 { *r = *EmptyJobHttpTargetOAuthToken } else { r.ServiceAccountEmail = res.ServiceAccountEmail r.Scope = res.Scope } return nil } // This object is used to assert a desired state where this JobHttpTargetOAuthToken is // empty. Go lacks global const objects, but this object should be treated // as one. Modifying this object will have undesirable results. var EmptyJobHttpTargetOAuthToken *JobHttpTargetOAuthToken = &JobHttpTargetOAuthToken{empty: true} func (r *JobHttpTargetOAuthToken) Empty() bool { return r.empty } func (r *JobHttpTargetOAuthToken) String() string { return dcl.SprintResource(r) } func (r *JobHttpTargetOAuthToken) HashCode() string { // Placeholder for a more complex hash method that handles ordering, etc // Hash resource body for easy comparison later hash := sha256.New().Sum([]byte(r.String())) return fmt.Sprintf("%x", hash) } type JobHttpTargetOidcToken struct { empty bool `json:"-"` ServiceAccountEmail *string `json:"serviceAccountEmail"` Audience *string `json:"audience"` } type jsonJobHttpTargetOidcToken JobHttpTargetOidcToken func (r *JobHttpTargetOidcToken) UnmarshalJSON(data []byte) error { var res jsonJobHttpTargetOidcToken if err := json.Unmarshal(data, &res); err != nil { return err } var m map[string]interface{} json.Unmarshal(data, &m) if len(m) == 0 { *r = *EmptyJobHttpTargetOidcToken } else { r.ServiceAccountEmail = res.ServiceAccountEmail r.Audience = res.Audience } return nil } // This object is used to assert a desired state where this JobHttpTargetOidcToken is // empty. Go lacks global const objects, but this object should be treated // as one. Modifying this object will have undesirable results. var EmptyJobHttpTargetOidcToken *JobHttpTargetOidcToken = &JobHttpTargetOidcToken{empty: true} func (r *JobHttpTargetOidcToken) Empty() bool { return r.empty } func (r *JobHttpTargetOidcToken) String() string { return dcl.SprintResource(r) } func (r *JobHttpTargetOidcToken) HashCode() string { // Placeholder for a more complex hash method that handles ordering, etc // Hash resource body for easy comparison later hash := sha256.New().Sum([]byte(r.String())) return fmt.Sprintf("%x", hash) } type JobStatus struct { empty bool `json:"-"` Code *int64 `json:"code"` Message *string `json:"message"` Details []JobStatusDetails `json:"details"` } type jsonJobStatus JobStatus func (r *JobStatus) UnmarshalJSON(data []byte) error { var res jsonJobStatus if err := json.Unmarshal(data, &res); err != nil { return err } var m map[string]interface{} json.Unmarshal(data, &m) if len(m) == 0 { *r = *EmptyJobStatus } else { r.Code = res.Code r.Message = res.Message r.Details = res.Details } return nil } // This object is used to assert a desired state where this JobStatus is // empty. Go lacks global const objects, but this object should be treated // as one. Modifying this object will have undesirable results. var EmptyJobStatus *JobStatus = &JobStatus{empty: true} func (r *JobStatus) Empty() bool { return r.empty } func (r *JobStatus) String() string { return dcl.SprintResource(r) } func (r *JobStatus) HashCode() string { // Placeholder for a more complex hash method that handles ordering, etc // Hash resource body for easy comparison later hash := sha256.New().Sum([]byte(r.String())) return fmt.Sprintf("%x", hash) } type JobStatusDetails struct { empty bool `json:"-"` TypeUrl *string `json:"typeUrl"` Value *string `json:"value"` } type jsonJobStatusDetails JobStatusDetails func (r *JobStatusDetails) UnmarshalJSON(data []byte) error { var res jsonJobStatusDetails if err := json.Unmarshal(data, &res); err != nil { return err } var m map[string]interface{} json.Unmarshal(data, &m) if len(m) == 0 { *r = *EmptyJobStatusDetails } else { r.TypeUrl = res.TypeUrl r.Value = res.Value } return nil } // This object is used to assert a desired state where this JobStatusDetails is // empty. Go lacks global const objects, but this object should be treated // as one. Modifying this object will have undesirable results. var EmptyJobStatusDetails *JobStatusDetails = &JobStatusDetails{empty: true} func (r *JobStatusDetails) Empty() bool { return r.empty } func (r *JobStatusDetails) String() string { return dcl.SprintResource(r) } func (r *JobStatusDetails) HashCode() string { // Placeholder for a more complex hash method that handles ordering, etc // Hash resource body for easy comparison later hash := sha256.New().Sum([]byte(r.String())) return fmt.Sprintf("%x", hash) } type JobRetryConfig struct { empty bool `json:"-"` RetryCount *int64 `json:"retryCount"` MaxRetryDuration *string `json:"maxRetryDuration"` MinBackoffDuration *string `json:"minBackoffDuration"` MaxBackoffDuration *string `json:"maxBackoffDuration"` MaxDoublings *int64 `json:"maxDoublings"` } type jsonJobRetryConfig JobRetryConfig func (r *JobRetryConfig) UnmarshalJSON(data []byte) error { var res jsonJobRetryConfig if err := json.Unmarshal(data, &res); err != nil { return err } var m map[string]interface{} json.Unmarshal(data, &m) if len(m) == 0 { *r = *EmptyJobRetryConfig } else { r.RetryCount = res.RetryCount r.MaxRetryDuration = res.MaxRetryDuration r.MinBackoffDuration = res.MinBackoffDuration r.MaxBackoffDuration = res.MaxBackoffDuration r.MaxDoublings = res.MaxDoublings } return nil } // This object is used to assert a desired state where this JobRetryConfig is // empty. Go lacks global const objects, but this object should be treated // as one. Modifying this object will have undesirable results. var EmptyJobRetryConfig *JobRetryConfig = &JobRetryConfig{empty: true} func (r *JobRetryConfig) Empty() bool { return r.empty } func (r *JobRetryConfig) String() string { return dcl.SprintResource(r) } func (r *JobRetryConfig) HashCode() string { // Placeholder for a more complex hash method that handles ordering, etc // Hash resource body for easy comparison later hash := sha256.New().Sum([]byte(r.String())) return fmt.Sprintf("%x", hash) } // Describe returns a simple description of this resource to ensure that automated tools // can identify it. func (r *Job) Describe() dcl.ServiceTypeVersion { return dcl.ServiceTypeVersion{ Service: "cloud_scheduler", Type: "Job", Version: "cloudscheduler", } } func (r *Job) ID() (string, error) { if err := extractJobFields(r); err != nil { return "", err } nr := r.urlNormalized() params := map[string]interface{}{ "name": dcl.ValueOrEmptyString(nr.Name), "description": dcl.ValueOrEmptyString(nr.Description), "pubsub_target": dcl.ValueOrEmptyString(nr.PubsubTarget), "app_engine_http_target": dcl.ValueOrEmptyString(nr.AppEngineHttpTarget), "http_target": dcl.ValueOrEmptyString(nr.HttpTarget), "schedule": dcl.ValueOrEmptyString(nr.Schedule), "time_zone": dcl.ValueOrEmptyString(nr.TimeZone), "user_update_time": dcl.ValueOrEmptyString(nr.UserUpdateTime), "state": dcl.ValueOrEmptyString(nr.State), "status": dcl.ValueOrEmptyString(nr.Status), "schedule_time": dcl.ValueOrEmptyString(nr.ScheduleTime), "last_attempt_time": dcl.ValueOrEmptyString(nr.LastAttemptTime), "retry_config": dcl.ValueOrEmptyString(nr.RetryConfig), "attempt_deadline": dcl.ValueOrEmptyString(nr.AttemptDeadline), "project": dcl.ValueOrEmptyString(nr.Project), "location": dcl.ValueOrEmptyString(nr.Location), } return dcl.Nprintf("projects/{{project}}/locations/{{location}}/jobs/{{name}}", params), nil } const JobMaxPage = -1 type JobList struct { Items []*Job nextToken string pageSize int32 resource *Job } func (l *JobList) HasNext() bool { return l.nextToken != "" } func (l *JobList) Next(ctx context.Context, c *Client) error { ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) defer cancel() if !l.HasNext() { return fmt.Errorf("no next page") } items, token, err := c.listJob(ctx, l.resource, l.nextToken, l.pageSize) if err != nil { return err } l.Items = items l.nextToken = token return err } func (c *Client) ListJob(ctx context.Context, project, location string) (*JobList, error) { ctx = dcl.ContextWithRequestID(ctx) ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) defer cancel() return c.ListJobWithMaxResults(ctx, project, location, JobMaxPage) } func (c *Client) ListJobWithMaxResults(ctx context.Context, project, location string, pageSize int32) (*JobList, error) { ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) defer cancel() // Create a resource object so that we can use proper url normalization methods. r := &Job{ Project: &project, Location: &location, } items, token, err := c.listJob(ctx, r, "", pageSize) if err != nil { return nil, err } return &JobList{ Items: items, nextToken: token, pageSize: pageSize, resource: r, }, nil } func (c *Client) GetJob(ctx context.Context, r *Job) (*Job, error) { ctx = dcl.ContextWithRequestID(ctx) ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) defer cancel() // This is *purposefully* supressing errors. // This function is used with url-normalized values + not URL normalized values. // URL Normalized values will throw unintentional errors, since those values are not of the proper parent form. extractJobFields(r) b, err := c.getJobRaw(ctx, r) if err != nil { if dcl.IsNotFound(err) { return nil, &googleapi.Error{ Code: 404, Message: err.Error(), } } return nil, err } result, err := unmarshalJob(b, c, r) if err != nil { return nil, err } result.Project = r.Project result.Location = r.Location result.Name = r.Name c.Config.Logger.InfoWithContextf(ctx, "Retrieved raw result state: %v", result) c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with specified state: %v", r) result, err = canonicalizeJobNewState(c, result, r) if err != nil { return nil, err } if err := postReadExtractJobFields(result); err != nil { return result, err } c.Config.Logger.InfoWithContextf(ctx, "Created result state: %v", result) return result, nil } func (c *Client) DeleteJob(ctx context.Context, r *Job) error { ctx = dcl.ContextWithRequestID(ctx) ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) defer cancel() if r == nil { return fmt.Errorf("Job resource is nil") } c.Config.Logger.InfoWithContext(ctx, "Deleting Job...") deleteOp := deleteJobOperation{} return deleteOp.do(ctx, r, c) } // DeleteAllJob deletes all resources that the filter functions returns true on. func (c *Client) DeleteAllJob(ctx context.Context, project, location string, filter func(*Job) bool) error { listObj, err := c.ListJob(ctx, project, location) if err != nil { return err } err = c.deleteAllJob(ctx, filter, listObj.Items) if err != nil { return err } for listObj.HasNext() { err = listObj.Next(ctx, c) if err != nil { return nil } err = c.deleteAllJob(ctx, filter, listObj.Items) if err != nil { return err } } return nil } func (c *Client) ApplyJob(ctx context.Context, rawDesired *Job, opts ...dcl.ApplyOption) (*Job, error) { ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second)) defer cancel() ctx = dcl.ContextWithRequestID(ctx) var resultNewState *Job err := dcl.Do(ctx, func(ctx context.Context) (*dcl.RetryDetails, error) { newState, err := applyJobHelper(c, ctx, rawDesired, opts...) resultNewState = newState if err != nil { // If the error is 409, there is conflict in resource update. // Here we want to apply changes based on latest state. if dcl.IsConflictError(err) { return &dcl.RetryDetails{}, dcl.OperationNotDone{Err: err} } return nil, err } return nil, nil }, c.Config.RetryProvider) return resultNewState, err } func applyJobHelper(c *Client, ctx context.Context, rawDesired *Job, opts ...dcl.ApplyOption) (*Job, error) { c.Config.Logger.InfoWithContext(ctx, "Beginning ApplyJob...") c.Config.Logger.InfoWithContextf(ctx, "User specified desired state: %v", rawDesired) // 1.1: Validation of user-specified fields in desired state. if err := rawDesired.validate(); err != nil { return nil, err } if err := extractJobFields(rawDesired); err != nil { return nil, err } initial, desired, fieldDiffs, err := c.jobDiffsForRawDesired(ctx, rawDesired, opts...) if err != nil { return nil, fmt.Errorf("failed to create a diff: %w", err) } diffs, err := convertFieldDiffsToJobDiffs(c.Config, fieldDiffs, opts) if err != nil { return nil, err } // TODO(magic-modules-eng): 2.2 Feasibility check (all updates are feasible so far). // 2.3: Lifecycle Directive Check var create bool lp := dcl.FetchLifecycleParams(opts) if initial == nil { if dcl.HasLifecycleParam(lp, dcl.BlockCreation) { return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Creation blocked by lifecycle params: %#v.", desired)} } create = true } else if dcl.HasLifecycleParam(lp, dcl.BlockAcquire) { return nil, dcl.ApplyInfeasibleError{ Message: fmt.Sprintf("Resource already exists - apply blocked by lifecycle params: %#v.", initial), } } else { for _, d := range diffs { if d.RequiresRecreate { return nil, dcl.ApplyInfeasibleError{ Message: fmt.Sprintf("infeasible update: (%v) would require recreation", d), } } if dcl.HasLifecycleParam(lp, dcl.BlockModification) { return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Modification blocked, diff (%v) unresolvable.", d)} } } } // 2.4 Imperative Request Planning var ops []jobApiOperation if create { ops = append(ops, &createJobOperation{}) } else { for _, d := range diffs { ops = append(ops, d.UpdateOp) } } c.Config.Logger.InfoWithContextf(ctx, "Created plan: %#v", ops) // 2.5 Request Actuation for _, op := range ops { c.Config.Logger.InfoWithContextf(ctx, "Performing operation %T %+v", op, op) if err := op.do(ctx, desired, c); err != nil { c.Config.Logger.InfoWithContextf(ctx, "Failed operation %T %+v: %v", op, op, err) return nil, err } c.Config.Logger.InfoWithContextf(ctx, "Finished operation %T %+v", op, op) } return applyJobDiff(c, ctx, desired, rawDesired, ops, opts...) } func applyJobDiff(c *Client, ctx context.Context, desired *Job, rawDesired *Job, ops []jobApiOperation, opts ...dcl.ApplyOption) (*Job, error) { // 3.1, 3.2a Retrieval of raw new state & canonicalization with desired state c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state...") rawNew, err := c.GetJob(ctx, desired) if err != nil { return nil, err } // Get additional values from the first response. // These values should be merged into the newState above. if len(ops) > 0 { lastOp := ops[len(ops)-1] if o, ok := lastOp.(*createJobOperation); ok { if r, hasR := o.FirstResponse(); hasR { c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state from operation...") fullResp, err := unmarshalMapJob(r, c, rawDesired) if err != nil { return nil, err } rawNew, err = canonicalizeJobNewState(c, rawNew, fullResp) if err != nil { return nil, err } } } } c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with raw desired state: %v", rawDesired) // 3.2b Canonicalization of raw new state using raw desired state newState, err := canonicalizeJobNewState(c, rawNew, rawDesired) if err != nil { return rawNew, err } c.Config.Logger.InfoWithContextf(ctx, "Created canonical new state: %v", newState) // 3.3 Comparison of the new state and raw desired state. // TODO(magic-modules-eng): EVENTUALLY_CONSISTENT_UPDATE newDesired, err := canonicalizeJobDesiredState(rawDesired, newState) if err != nil { return newState, err } if err := postReadExtractJobFields(newState); err != nil { return newState, err } // Need to ensure any transformations made here match acceptably in differ. if err := postReadExtractJobFields(newDesired); err != nil { return newState, err } c.Config.Logger.InfoWithContextf(ctx, "Diffing using canonicalized desired state: %v", newDesired) newDiffs, err := diffJob(c, newDesired, newState) if err != nil { return newState, err } if len(newDiffs) == 0 { c.Config.Logger.InfoWithContext(ctx, "No diffs found. Apply was successful.") } else { c.Config.Logger.InfoWithContextf(ctx, "Found diffs: %v", newDiffs) diffMessages := make([]string, len(newDiffs)) for i, d := range newDiffs { diffMessages[i] = fmt.Sprintf("%v", d) } return newState, dcl.DiffAfterApplyError{Diffs: diffMessages} } c.Config.Logger.InfoWithContext(ctx, "Done Apply.") return newState, nil }
package domain const ( MaterialTypeSeedCode = "SEED" MaterialTypePlantCode = "PLANT" MaterialTypeGrowingMediumCode = "GROWING_MEDIUM" MaterialTypeAgrochemicalCode = "AGROCHEMICAL" MaterialTypeLabelAndCropSupportCode = "LABEL_AND_CROP_SUPPORT" MaterialTypeSeedingContainerCode = "SEEDING_CONTAINER" MaterialTypePostHarvestSupplyCode = "POST_HARVEST_SUPPLY" MaterialTypeOtherCode = "OTHER" ) type MaterialType interface { Code() string } type MaterialTypeSeed struct { PlantType PlantType } func (mt MaterialTypeSeed) Code() string { return MaterialTypeSeedCode } func CreateMaterialTypeSeed(plantType string) (MaterialTypeSeed, error) { pt := GetPlantType(plantType) if pt == (PlantType{}) { return MaterialTypeSeed{}, InventoryMaterialError{InventoryMaterialErrorWrongType} } return MaterialTypeSeed{pt}, nil } type PlantType struct { Code string `json:"code"` Label string `json:"label"` } const ( PlantTypeVegetable = "VEGETABLE" PlantTypeFruit = "FRUIT" PlantTypeHerb = "HERB" PlantTypeFlower = "FLOWER" PlantTypeTree = "TREE" ) func PlantTypes() []PlantType { return []PlantType{ {Code: PlantTypeVegetable, Label: "Vegetable"}, {Code: PlantTypeFruit, Label: "Fruit"}, {Code: PlantTypeHerb, Label: "Herb"}, {Code: PlantTypeFlower, Label: "Flower"}, {Code: PlantTypeTree, Label: "Tree"}, } } func GetPlantType(code string) PlantType { for _, v := range PlantTypes() { if v.Code == code { return v } } return PlantType{} } type MaterialTypeAgrochemical struct { ChemicalType ChemicalType } func (mt MaterialTypeAgrochemical) Code() string { return MaterialTypeAgrochemicalCode } const ( ChemicalTypeDisinfectant = "DISINFECTANT" ChemicalTypeFertilizer = "FERTILIZER" ChemicalTypeHormone = "HORMONE" ChemicalTypeManure = "MANURE" ChemicalTypePesticide = "PESTICIDE" ) type ChemicalType struct { Code string `json:"code"` Label string `json:"label"` } func ChemicalTypes() []ChemicalType { return []ChemicalType{ {Code: ChemicalTypeDisinfectant, Label: "Disinfectant and Sanitizer"}, {Code: ChemicalTypeFertilizer, Label: "Fertilizer"}, {Code: ChemicalTypeHormone, Label: "Hormone and Growth Agent"}, {Code: ChemicalTypeManure, Label: "Manure"}, {Code: ChemicalTypePesticide, Label: "Pesticide"}, } } func GetChemicalType(code string) ChemicalType { for _, v := range ChemicalTypes() { if v.Code == code { return v } } return ChemicalType{} } func CreateMaterialTypeAgrochemical(chemicalType string) (MaterialTypeAgrochemical, error) { ct := GetChemicalType(chemicalType) if ct == (ChemicalType{}) { return MaterialTypeAgrochemical{}, InventoryMaterialError{InventoryMaterialErrorWrongType} } return MaterialTypeAgrochemical{ct}, nil } type MaterialTypeGrowingMedium struct { } func (mt MaterialTypeGrowingMedium) Code() string { return MaterialTypeGrowingMediumCode } type MaterialTypeLabelAndCropSupport struct { } func (mt MaterialTypeLabelAndCropSupport) Code() string { return MaterialTypeLabelAndCropSupportCode } type MaterialTypeSeedingContainer struct { ContainerType ContainerType } func (mt MaterialTypeSeedingContainer) Code() string { return MaterialTypeSeedingContainerCode } const ( ContainerTypeTray = "TRAY" ContainerTypePot = "POT" ) type ContainerType struct { Code string `json:"code"` Label string `json:"label"` } func ContainerTypes() []ContainerType { return []ContainerType{ {Code: ContainerTypeTray, Label: "Tray"}, {Code: ContainerTypePot, Label: "Pot"}, } } func GetContainerType(code string) ContainerType { for _, v := range ContainerTypes() { if v.Code == code { return v } } return ContainerType{} } func CreateMaterialTypeSeedingContainer(containerType string) (MaterialTypeSeedingContainer, error) { ct := GetContainerType(containerType) if ct == (ContainerType{}) { return MaterialTypeSeedingContainer{}, InventoryMaterialError{InventoryMaterialErrorWrongType} } return MaterialTypeSeedingContainer{ContainerType: ct}, nil } type MaterialTypePostHarvestSupply struct { } func (mt MaterialTypePostHarvestSupply) Code() string { return MaterialTypePostHarvestSupplyCode } type MaterialTypeOther struct { } func (mt MaterialTypeOther) Code() string { return MaterialTypeOtherCode } type MaterialTypePlant struct { PlantType PlantType } func (mt MaterialTypePlant) Code() string { return MaterialTypePlantCode } func CreateMaterialTypePlant(plantType string) (MaterialTypePlant, error) { pt := GetPlantType(plantType) if pt == (PlantType{}) { return MaterialTypePlant{}, InventoryMaterialError{InventoryMaterialErrorWrongType} } return MaterialTypePlant{pt}, nil }
package main import ( "github.com/adamveld12/goadventure/game" "github.com/adamveld12/goadventure/persistence" "github.com/adamveld12/goadventure/routes" "github.com/adamveld12/sessionauth" "github.com/go-martini/martini" "github.com/martini-contrib/render" "github.com/martini-contrib/sessions" "net/http" "os" ) func main() { app := martini.Classic() store := sessions.NewCookieStore([]byte(os.Getenv("SECRET"))) app.Use(sessions.Sessions("mud_session", store)) app.Use(render.Renderer(render.Options{ Directory: "templates", Layout: "layout", Extensions: []string{".tmpl", ".html"}, IndentJSON: true, })) static := martini.Static("public", martini.StaticOptions{Fallback: "/access", Exclude: "/api/v1"}) app.NotFound(static, http.NotFound) initServices(app) routes.RegisterRoutes(app) app.Run() } func initServices(app *martini.ClassicMartini) { persistence.InitializeDatabase() playerService := persistence.GetPlayerService() sessionauth.RedirectUrl = "" sessionauth.RedirectParam = "main" app.Use(sessionauth.SessionUser(playerService, func() sessionauth.User { return &game.Player{} })) app.Map(playerService) }
package configuration import polochon "github.com/odwrtw/polochon/lib" // ModuleFetcher is an interface which allows to get torrenters and detailers ... type ModuleFetcher interface { GetDetailers() []polochon.Detailer GetTorrenters() []polochon.Torrenter GetSearchers() []polochon.Searcher GetExplorers() []polochon.Explorer GetSubtitlers() []polochon.Subtitler } // ModuleStatus represent the status of a module type ModuleStatus struct { Name string `json:"name"` Status polochon.ModuleStatus `json:"status"` Error string `json:"error"` } // ModulesStatuses represent the status of all the modules type ModulesStatuses map[string]map[string][]ModuleStatus // ModulesStatus gives the status of the modules configured func (c *Config) ModulesStatus() ModulesStatuses { type module struct { moduleType string config ModuleFetcher } result := ModulesStatuses{} for _, module := range []module{ { "movie", &c.Movie, }, { "show", &c.Show, }, } { result[module.moduleType] = map[string][]ModuleStatus{} for _, detailer := range module.config.GetDetailers() { status, err := detailer.Status() result[module.moduleType]["detailer"] = append(result[module.moduleType]["detailer"], ModuleStatus{ Name: detailer.Name(), Status: status, Error: errorMsg(err), }) } for _, subtitler := range module.config.GetSubtitlers() { status, err := subtitler.Status() result[module.moduleType]["subtitler"] = append(result[module.moduleType]["subtitler"], ModuleStatus{ Name: subtitler.Name(), Status: status, Error: errorMsg(err), }) } for _, torrenter := range module.config.GetTorrenters() { status, err := torrenter.Status() result[module.moduleType]["torrenter"] = append(result[module.moduleType]["torrenter"], ModuleStatus{ Name: torrenter.Name(), Status: status, Error: errorMsg(err), }) } for _, explorer := range module.config.GetExplorers() { status, err := explorer.Status() result[module.moduleType]["explorer"] = append(result[module.moduleType]["explorer"], ModuleStatus{ Name: explorer.Name(), Status: status, Error: errorMsg(err), }) } for _, searcher := range module.config.GetSearchers() { status, err := searcher.Status() result[module.moduleType]["searcher"] = append(result[module.moduleType]["searcher"], ModuleStatus{ Name: searcher.Name(), Status: status, Error: errorMsg(err), }) } } return result } func errorMsg(err error) string { if err == nil { return "" } return err.Error() }
package main import ( "context" "fmt" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/kinesis" ) // arn:aws:kinesis:eu-central-1:627211582084:stream/productevents var ( stream = "productevents" region = "eu-central-1" sid = "shardId-000000000000" ) var kc *kinesis.Kinesis = nil var streamName = aws.String("") var start = "" func init() { s := session.New(&aws.Config{Region: aws.String(region)}) kc = kinesis.New(s) streamName = aws.String(stream) streams, err := kc.DescribeStream(&kinesis.DescribeStreamInput{StreamName: streamName}) if err != nil { panic(err) } start = string(*(streams.StreamDescription.Shards[0].SequenceNumberRange.StartingSequenceNumber)) } type Event struct { id string } type EventsResponse struct { Events []Event LastSequenceNumber string } func MakeHttp() func(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { return func(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { since := request.QueryStringParameters["since"] if since == "" { since = start } iteratorOutput, err := kc.GetShardIterator(&kinesis.GetShardIteratorInput{ ShardId: &sid, ShardIteratorType: aws.String("AFTER_SEQUENCE_NUMBER"), StartingSequenceNumber: aws.String(since), StreamName: streamName, }) if err != nil { panic(err) } eventsResponse := EventsResponse{ Events: []Event{}, LastSequenceNumber: since, } si := iteratorOutput.ShardIterator b := "" for { // get records use shard iterator for making request records, err := kc.GetRecords(&kinesis.GetRecordsInput{ ShardIterator: si, }) if err != nil { panic(err) } for _, r := range records.Records { ev := Event{} eventsResponse.Events = append(eventsResponse.Events, ev) b += "--MixedBoundaryString\r\n" b += fmt.Sprintf("%s\n", string(r.Data)) } if len(records.Records) > 0 { eventsResponse.LastSequenceNumber = string(*((records.Records[len(records.Records)-1]).SequenceNumber)) } if *records.MillisBehindLatest == 0 { break } si = records.NextShardIterator } b += "--MixedBoundaryString--\r\n" //headers:= map[string]string{"Content-Type": "application/soap...xml"} headers := map[string]string{ "Link": fmt.Sprintf("</proto/http/latest?since=%s>; rel=next", eventsResponse.LastSequenceNumber), "Content-Type": `multipart/mixed; boundary="MixedBoundaryString"`, } return events.APIGatewayProxyResponse{ StatusCode: 200, Headers: headers, Body: b, }, nil } } func main() { lambda.Start(MakeHttp()) }
package main import ( "fmt" "math/rand" ) func main() { piggyBank := 0 for piggyBank < 2000 { switch rand.Intn(3) { case 0: piggyBank += 5 case 1: piggyBank += 10 case 2: piggyBank += 15 } dollar := piggyBank /100 cents := piggyBank % 100 fmt.Printf("$%d.%02d\n",dollar,cents) } }
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package reverse can reverse things, particularly strings. package reverse // String returns its argument string reversed rune-wise left to right. func String(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) }
/* * Copyright 2017 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package store import ( "encoding/json" "errors" "github.com/satori/go.uuid" "github.com/streamsets/datacollector-edge/container/common" "github.com/streamsets/datacollector-edge/container/creation" pipelineStateStore "github.com/streamsets/datacollector-edge/container/execution/store" "io/ioutil" "os" "strings" "time" ) const ( PIPELINE_FILE = "pipeline.json" PIPELINE_INFO_FILE = "info.json" PIPELINES_FOLDER = "/data/pipelines/" PIPELINES_RUN_INFO_FOLDER = "/data/runInfo/" ) type FilePipelineStoreTask struct { runtimeInfo common.RuntimeInfo } func (store *FilePipelineStoreTask) GetPipelines() ([]common.PipelineInfo, error) { var pipelineInfoList []common.PipelineInfo files, err := ioutil.ReadDir(store.runtimeInfo.BaseDir + PIPELINES_FOLDER) if err != nil { return nil, err } for _, f := range files { if f.IsDir() { pipelineInfo := common.PipelineInfo{} file, err := os.Open(store.getPipelineInfoFile(f.Name())) if err != nil { return nil, err } decoder := json.NewDecoder(file) err = decoder.Decode(&pipelineInfo) if err != nil { return nil, err } pipelineInfoList = append(pipelineInfoList, pipelineInfo) } } return pipelineInfoList, nil } func (store *FilePipelineStoreTask) GetInfo(pipelineId string) (common.PipelineInfo, error) { if !store.hasPipeline(pipelineId) { return common.PipelineInfo{}, errors.New("Pipeline '" + pipelineId + " does not exist") } pipelineInfo := common.PipelineInfo{} file, err := os.Open(store.getPipelineInfoFile(pipelineId)) if err != nil { return pipelineInfo, err } decoder := json.NewDecoder(file) err = decoder.Decode(&pipelineInfo) if err != nil { return pipelineInfo, err } if pipelineInfo.PipelineId == "" { err = errors.New("InValid pipeline configuration") } return pipelineInfo, err } func (store *FilePipelineStoreTask) Create( pipelineId string, pipelineTitle string, description string, isRemote bool, ) (common.PipelineConfiguration, error) { if store.hasPipeline(pipelineId) { return common.PipelineConfiguration{}, errors.New("Pipeline '" + pipelineId + " already exists") } currentTime := time.Now().Unix() metadata := map[string]interface{}{ "labels": []string{}, } pipelineUuid := uuid.NewV4().String() pipelineInfo := common.PipelineInfo{ PipelineId: pipelineId, Title: pipelineTitle, Description: description, Created: currentTime, LastModified: currentTime, Creator: "admin", LastModifier: "admin", LastRev: "0", UUID: pipelineUuid, Valid: true, Metadata: metadata, } pipelineConfiguration := common.PipelineConfiguration{ SchemaVersion: common.PipelineConfigSchemaVersion, Version: common.PipelineConfigVersion, PipelineId: pipelineId, Title: pipelineTitle, Description: description, UUID: pipelineUuid, Configuration: creation.GetDefaultPipelineConfigs(), UiInfo: map[string]interface{}{}, Stages: []*common.StageConfiguration{}, ErrorStage: creation.GetTrashErrorStageInstance(), StatsAggregatorStage: creation.GetDefaultStatsAggregatorStageInstance(), Previewable: true, Info: pipelineInfo, Metadata: metadata, } err := os.MkdirAll(store.getPipelineDir(pipelineId), 0777) if err != nil { return pipelineConfiguration, err } pipelineInfoJson, err := json.MarshalIndent(pipelineInfo, "", " ") if err != nil { return pipelineConfiguration, err } err = ioutil.WriteFile(store.getPipelineInfoFile(pipelineId), pipelineInfoJson, 0644) pipelineConfigurationJson, err := json.MarshalIndent(pipelineConfiguration, "", " ") if err != nil { return pipelineConfiguration, err } err = ioutil.WriteFile(store.getPipelineFile(pipelineId), pipelineConfigurationJson, 0644) if err != nil { return pipelineConfiguration, err } err = pipelineStateStore.Edited(pipelineId, isRemote) return pipelineConfiguration, err } func (store *FilePipelineStoreTask) Save( pipelineId string, pipelineConfiguration common.PipelineConfiguration, ) (common.PipelineConfiguration, error) { if !store.hasPipeline(pipelineId) { return common.PipelineConfiguration{}, errors.New("Pipeline '" + pipelineId + " does not exist") } savedInfo, err := store.GetInfo(pipelineId) if err != nil { return pipelineConfiguration, err } if savedInfo.UUID != pipelineConfiguration.UUID { return pipelineConfiguration, errors.New("The pipeline '" + pipelineId + "' has been changed.") } currentTime := time.Now().Unix() pipelineUuid := uuid.NewV4().String() pipelineInfo := pipelineConfiguration.Info pipelineInfo.UUID = pipelineUuid pipelineInfo.PipelineId = pipelineConfiguration.PipelineId pipelineInfo.LastModified = currentTime pipelineInfo.Title = pipelineConfiguration.Title pipelineInfo.Description = pipelineConfiguration.Description pipelineConfiguration.Info = pipelineInfo pipelineConfiguration.UUID = pipelineUuid pipelineInfoJson, err := json.MarshalIndent(pipelineInfo, "", " ") if err != nil { return pipelineConfiguration, err } err = ioutil.WriteFile(store.getPipelineInfoFile(pipelineId), pipelineInfoJson, 0644) pipelineConfigurationJson, err := json.MarshalIndent(pipelineConfiguration, "", " ") if err != nil { return pipelineConfiguration, err } err = ioutil.WriteFile(store.getPipelineFile(pipelineId), pipelineConfigurationJson, 0644) return pipelineConfiguration, nil } func (store *FilePipelineStoreTask) LoadPipelineConfig(pipelineId string) (common.PipelineConfiguration, error) { pipelineConfiguration := common.PipelineConfiguration{} file, err := os.Open(store.getPipelineFile(pipelineId)) if err != nil { return pipelineConfiguration, err } decoder := json.NewDecoder(file) err = decoder.Decode(&pipelineConfiguration) if err != nil { return pipelineConfiguration, err } if pipelineConfiguration.PipelineId == "" { err = errors.New("InValid pipeline configuration") } // Process fragment stages pipelineConfiguration.ProcessFragmentStages() return pipelineConfiguration, err } func (store *FilePipelineStoreTask) Delete(pipelineId string) error { if !store.hasPipeline(pipelineId) { return errors.New("Pipeline '" + pipelineId + " does not exist") } err := os.RemoveAll(store.getPipelineDir(pipelineId)) if err != nil { return err } err = os.RemoveAll(store.getPipelineRunInfoDir(pipelineId)) return err } func (store *FilePipelineStoreTask) hasPipeline(pipelineId string) bool { _, err := os.Stat(store.getPipelineDir(pipelineId)) if err == nil { return true } if os.IsNotExist(err) { return false } return true } func (store *FilePipelineStoreTask) getPipelineFile(pipelineId string) string { return store.getPipelineDir(pipelineId) + PIPELINE_FILE } func (store *FilePipelineStoreTask) getPipelineInfoFile(pipelineId string) string { return store.getPipelineDir(pipelineId) + PIPELINE_INFO_FILE } func (store *FilePipelineStoreTask) getPipelineDir(pipelineId string) string { validPipelineId := strings.Replace(pipelineId, ":", "", -1) return store.runtimeInfo.BaseDir + PIPELINES_FOLDER + validPipelineId + "/" } func (store *FilePipelineStoreTask) getPipelineRunInfoDir(pipelineId string) string { validPipelineId := strings.Replace(pipelineId, ":", "", -1) return store.runtimeInfo.BaseDir + PIPELINES_RUN_INFO_FOLDER + validPipelineId + "/" } func NewFilePipelineStoreTask(runtimeInfo common.RuntimeInfo) PipelineStoreTask { pipelineStateStore.BaseDir = runtimeInfo.BaseDir return &FilePipelineStoreTask{runtimeInfo: runtimeInfo} }
// Package rangeset has set operations on ranges: Union, Intersect and Difference package rangeset import ( "fmt" "github.com/biogo/store/step" ) func max(a, b int) int { if a > b { return a } return b } type _bool bool const ( _true = _bool(true) _false = _bool(false) ) func (b _bool) Equal(e step.Equaler) bool { return b == e.(_bool) } // RangeSet acts like a bitvector where the interval values for true can be extracted. type RangeSet struct { v *step.Vector } // Range is 0-based half-open. type Range struct { Start, End int } func (i Range) String() string { return fmt.Sprintf("Range(%d-%d)", i.Start, i.End) } // Ranges returns the intervals that are set to true in the RangeSet. func (b *RangeSet) Ranges() []Range { var posns []Range var start, end int var val step.Equaler var err error for end < b.v.Len() { start, end, val, err = b.v.StepAt(end) if err == nil { if !val.(_bool) { continue } posns = append(posns, Range{start, end}) } else { } } return posns } // SetRange sets the values between start and end to true. func (b *RangeSet) SetRange(start, end int) { b.v.SetRange(start, end, _true) } // ClearRange sets the values between start and end to false. func (b *RangeSet) ClearRange(start, end int) { b.v.SetRange(start, end, _false) } // New returns a new RangeSet func New(start, end int) (*RangeSet, error) { s, err := step.New(start, end, _false) if err == nil { s.Relaxed = true } return &RangeSet{v: s}, err } type operation int const ( intersectionOp operation = iota unionOp differenceOp ) // Intersection returns a new RangeSet with intersecting regions from a and b. func Intersection(a, b *RangeSet) *RangeSet { return combine(a, b, intersectionOp) } // Union returns a new RangeSet with the union of regions from a and b. func Union(a, b *RangeSet) *RangeSet { return combine(a, b, unionOp) } // Difference returns a new RangeSet with regions in a that are absent from b. func Difference(a, b *RangeSet) *RangeSet { return combine(a, b, differenceOp) } func combine(a, b *RangeSet, op operation) *RangeSet { if a.v.Zero != b.v.Zero { panic("intersection must have same Zero state for a and b") } c, err := New(0, max(a.v.Len(), b.v.Len())) if err != nil { panic(err) } var start, end int var val step.Equaler for end < a.v.Len() { start, end, val, _ = a.v.StepAt(end) if !val.(_bool) { continue } c.SetRange(start, end) } start, end = 0, 0 for end < b.v.Len() { start, end, val, err = b.v.StepAt(end) if op == intersectionOp && !val.(_bool) { c.ClearRange(start, end) continue } if op == differenceOp && val.(_bool) { c.ClearRange(start, end) continue } if op == unionOp { if val.(_bool) { c.SetRange(start, end) } continue } c.v.ApplyRange(start, end, func(e step.Equaler) step.Equaler { if op == intersectionOp && (e.(_bool) && val.(_bool)) { return _bool(true) } else if op == differenceOp && (e.(_bool) && !val.(_bool)) { return _bool(true) } return _bool(false) }) } return c }
// Package mustcheck defines an Analyzer that reports .MustVerb usages package mustcheck import ( "bytes" "go/ast" "go/printer" "go/token" "strings" "github.com/fatih/camelcase" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" ) var Analyzer = &analysis.Analyzer{ Name: "mustcheck", Doc: "reports various .MustVerb() usages", Run: run, Requires: []*analysis.Analyzer{inspect.Analyzer}, } func run(pass *analysis.Pass) (interface{}, error) { inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) nodeFilter := []ast.Node{ (*ast.CallExpr)(nil), } inspect.WithStack(nodeFilter, func(n ast.Node, push bool, stack []ast.Node) bool { // TODO: set via config if f := pass.Fset.File(n.Pos()); f != nil && (strings.HasSuffix(f.Name(), "_test.go") || strings.Contains(f.Name(), "utils/test")) { return false } ce := n.(*ast.CallExpr) if len(ce.Args) != 0 { return false } se, ok := ce.Fun.(*ast.SelectorExpr) if !ok { return false } splitted := camelcase.Split(se.Sel.String()) if splitted[0] != "Must" { return false } // if outermost func decl is init or global decl, ignore var outerFD *ast.FuncDecl var outerGD *ast.GenDecl for _, stackElem := range stack { switch t := stackElem.(type) { case *ast.FuncDecl: outerFD = t case *ast.GenDecl: outerGD = t } } if outerFD != nil && outerFD.Name.String() == "init" { return false } if outerGD != nil && len(stack) == 4 { return false } pass.Reportf(se.Sel.Pos(), "MustVerb() usage found %q", render(pass.Fset, se.Sel)) return false }) return nil, nil } // render returns the pretty-print of the given node func render(fset *token.FileSet, x interface{}) string { var buf bytes.Buffer if err := printer.Fprint(&buf, fset, x); err != nil { panic(err) } return buf.String() }
package contentService import ( "github.com/rossifedericoe/bootcamp/clase2/domain" ) func IsValidContent(content domain.IContent) (bool, string) { if !content.ValidTitle() { return false, "title" } if !content.ValidLanguage() { return false, "lang" } return true, "" }
package main import ( "fmt" "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter10/waitgroup" ) func main() { sites := []string{ "https://golang.org", "https://godoc.org", "https://www.google.com/search?q=golang", } resps, err := waitgroup.Crawl(sites) if err != nil { panic(err) } fmt.Println("Resps received:", resps) }
// Package example is usage example for httpexpect. package example
// feet_to_meter.go // converte pés em metros // arataca89@gmail.com // 20210409 package main import "fmt" func main() { var feet float64 fmt.Print("Entre com a medida em pés:") fmt.Scanf("%f", &feet) meters := feet * 0.3048 fmt.Println("A medida em metros é", meters) }
package controllers import ( "net/http" "part2/lib/databases" "part2/models" "strconv" "github.com/labstack/echo" ) func GetBooksControllers(c echo.Context) error { books, err := databases.GetBooks() if err != nil { return echo.NewHTTPError(http.StatusBadRequest, err.Error()) } return c.JSON(http.StatusOK, map[string]interface{}{ "status": "success", "users": books, }) } func GetBookController(c echo.Context) error { id, err := strconv.Atoi(c.Param("id")) if err != nil { return c.JSON(http.StatusBadRequest, map[string]interface{}{ "message": "id invalid", }) } book, err := databases.GetBook(id) if err != nil { return echo.NewHTTPError(http.StatusBadRequest, err.Error()) } return c.JSON(http.StatusOK, map[string]interface{}{ "message": "alhamdulillah", "user": book, }) } func DeleteBookController(c echo.Context) error { id, err := strconv.Atoi(c.Param("id")) if err != nil { return c.JSON(http.StatusBadRequest, map[string]interface{}{ "message": "Id invalid", }) } bookId, err := databases.DeleteBook(id) if err != nil { return echo.NewHTTPError(http.StatusBadRequest, err.Error()) } return c.JSON(http.StatusOK, map[string]interface{}{ "message": "Data has been DELETED", "user": bookId, }) } func CreateBookController(c echo.Context) error { book, err := databases.CreateBook(c) if err != nil { return echo.NewHTTPError(http.StatusBadRequest, err.Error()) } return c.JSON(http.StatusOK, map[string]interface{}{ "status": "success", "users": book, }) } func UpdateBookController(c echo.Context) error { var book models.Book id, err := strconv.Atoi(c.Param("id")) if err != nil { return c.JSON(http.StatusBadRequest, map[string]interface{}{ "message": "invalid id", }) } c.Bind(&book) update_book, err := databases.UpdateUser(id, book) if err != nil { return echo.NewHTTPError(http.StatusBadRequest, err.Error()) } return c.JSON(http.StatusOK, map[string]interface{}{ "message": "success", "data": update_book, }) }
package caaa import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01400104 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.014.001.04 Document"` Message *AcceptorDiagnosticResponseV04 `xml:"AccptrDgnstcRspn"` } func (d *Document01400104) AddMessage() *AcceptorDiagnosticResponseV04 { d.Message = new(AcceptorDiagnosticResponseV04) return d.Message } // The AcceptorDiagnosticResponse message is sent by the acquirer (or its agent) to provide to the acceptor the result of the diagnostic request. type AcceptorDiagnosticResponseV04 struct { // Diagnostic response message management information. Header *iso20022.Header10 `xml:"Hdr"` // Information related to the diagnostic response. DiagnosticResponse *iso20022.AcceptorDiagnosticResponse4 `xml:"DgnstcRspn"` // Trailer of the message containing a MAC. SecurityTrailer *iso20022.ContentInformationType11 `xml:"SctyTrlr"` } func (a *AcceptorDiagnosticResponseV04) AddHeader() *iso20022.Header10 { a.Header = new(iso20022.Header10) return a.Header } func (a *AcceptorDiagnosticResponseV04) AddDiagnosticResponse() *iso20022.AcceptorDiagnosticResponse4 { a.DiagnosticResponse = new(iso20022.AcceptorDiagnosticResponse4) return a.DiagnosticResponse } func (a *AcceptorDiagnosticResponseV04) AddSecurityTrailer() *iso20022.ContentInformationType11 { a.SecurityTrailer = new(iso20022.ContentInformationType11) return a.SecurityTrailer }
package main func main() { //Please go through readME }
package main import ( "gopkg.in/yaml.v2" "io/ioutil" "os" "fmt" ) type Config struct { FileName string } //全局变量怎么表示 var config Config func SetConfig(filePath string) string{ configFile := "conf.yaml" //os.Args[1] source, err := ioutil.ReadFile(configFile) if err != nil { panic(err) } err = yaml.Unmarshal(source, &config) if err != nil { panic(err) } if len(filePath)!=0 { setAttr(filePath) } fmt.Println(config.FileName) out, err := yaml.Marshal(&config) if err != nil { panic(err) } err =ioutil.WriteFile(configFile,out,os.ModeAppend) if err != nil { panic(err) } return config.FileName } func setAttr(fileName string) { config.FileName=fileName }
package ch05 // Give a list of 1's and 0's, write a program to separate 0's and 1's. // Hint: QuickSelect, counting func Separate_0_1(in []int) (zeros, ones int) { for _, val := range in { if val == 0 { zeros++ } else { ones++ } } return zeros, ones }
package main import "errors" func div(x, y int) (int, error) { if y == 0 { return 0, errors.New("division by zero") } return x / y, nil } func main() { r, e := div(100, 0) if e != nil { println("error!") } else { println(r) } }
// Copyright 2020-2021 Buf Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package bufwork defines the primitives used to enable workspaces. // // If a buf.work file exists in a parent directory (up to the root of // the filesystem), the directory containing the file is used as the root of // one or more modules. With this, modules can import from one another, and a // variety of commands work on multiple modules rather than one. For example, if // `buf lint` is run for an input that contains a buf.work, each of // the modules contained within the workspace will be linted. Other commands, such // as `buf build`, will merge workspace modules into one (i.e. a "supermodule") // so that all of the files contained are consolidated into a single image. // // In the following example, the workspace consists of two modules: the module // defined in the petapis directory can import definitions from the paymentapis // module without vendoring the definitions under a common root. To be clear, // `import "acme/payment/v2/payment.proto";` from the acme/pet/v1/pet.proto file // will suffice as long as the buf.work file exists. // // // buf.work // version: v1beta1 // directories: // - paymentapis // - petapis // // $ tree // . // ├── buf.work // ├── paymentapis // │   ├── acme // │   │   └── payment // │   │   └── v2 // │   │   └── payment.proto // │   └── buf.yaml // └── petapis // ├── acme // │   └── pet // │ └── v1 // │   └── pet.proto // └── buf.yaml // // Note that inputs MUST NOT overlap with any of the directories defined in the buf.work // file. For example, it's not possible to build input "paymentapis/acme" since the image // would otherwise include the content defined in paymentapis/acme/payment/v2/payment.proto as // acme/payment/v2/payment.proto and payment/v2/payment.proto. package bufwork import ( "context" "github.com/powerman/buf/internal/buf/bufconfig" "github.com/powerman/buf/internal/buf/bufcore/bufmodule" "github.com/powerman/buf/internal/pkg/storage" "go.uber.org/zap" ) // ExternalConfigV1Beta1FilePath is the default configuration file path for v1beta1. const ExternalConfigV1Beta1FilePath = "buf.work" // NewWorkspace returns a new workspace. func NewWorkspace( ctx context.Context, config *Config, readBucket storage.ReadBucket, configProvider bufconfig.Provider, relativeRootPath string, targetSubDirPath string, ) (bufmodule.Workspace, error) { return newWorkspace(ctx, config, readBucket, configProvider, relativeRootPath, targetSubDirPath) } // Config is the workspace config. type Config struct { // Directories are normalized and validated. Directories []string } // Provider provides workspace configurations. type Provider interface { // GetConfig gets the Config for the YAML data at ConfigFilePath. // // If the data is of length 0, returns the default config. GetConfig(ctx context.Context, readBucket storage.ReadBucket, relativeRootPath string) (*Config, error) // GetConfig gets the Config for the given JSON or YAML data. // // If the data is of length 0, returns the default config. GetConfigForData(ctx context.Context, data []byte) (*Config, error) } // NewProvider returns a new Provider. func NewProvider(logger *zap.Logger) Provider { return newProvider(logger) } type externalConfigV1Beta1 struct { Version string `json:"version,omitempty" yaml:"version,omitempty"` Directories []string `json:"directories,omitempty" yaml:"directories,omitempty"` } type externalConfigVersion struct { Version string `json:"version,omitempty" yaml:"version,omitempty"` }
package test import ( "fmt" "pencil/api/bind" "pencil/api/query" "testing" "time" ) /* any请求方式,支持如下几种:GET \ POST \ PUT \ PATCH \ HEAD \ OPTIONS \ DELETE \ CONNECT \ TRACE xml格式数据和json格式数据传递的时候,可以通过 Content-Type 检查,xml格式的时候,结构体必须有xml标识,json必须有form标识 */ /** * @desc 绑定json \ xml 测试 验证器测试 * @author Ipencil * @create 2019/3/16 */ func TestBand(t *testing.T) { //t.SkipNow() t.Run("band_json", band_json) //json解析的接口,get和post使用同一个,都支持,使用Any请求方式 t.Run("band_json_post", band_json_post) //支持get和post方式 t.Run("band_xml", band_xml) //支持get和post方式 t.Run("books", books) //自定义验证器 t.Run("query", queryJson) //支持json和xml两种格式 t.Run("query", queryXML) //支持json和xml两种格式 t.Run("forms", forms) //支持json和xml两种格式 t.Run("someJSON", someJSON) //支持json和xml两种格式 } //安全json传输 func someJSON(t *testing.T) { t.SkipNow() /*get 请求*/ url := "http://localhost:8000/someJSON" //填空没有默认值 result := queryGet(t, url) fmt.Println(result) } //json客户端发送数据 数组发送,一般复选框能够用上 func forms(t *testing.T) { t.SkipNow() url := "http://localhost:8000/forms" params := map[string][]string{ "colors[]": { "wo", "ai", "ni", }, } send := postSendList(url, params) fmt.Println(send) } //json客户端发送数据 func queryJson(t *testing.T) { t.SkipNow() url := "http://localhost:8000/query" params := map[string]string{ "name": "李长全", "address": "123", "birthday": "1992-08-25 12:12:12", } send := postSend(url, params) fmt.Println(send) } //json客户端发送数据 func queryXML(t *testing.T) { t.SkipNow() url := "http://localhost:8000/query" per := query.Person{} per.Name = "lcq" per.Address = "123" per.Birthday = time.Now() send := postSendCopy(url, per) fmt.Println(send) } //json客户端发送数据 func band_json(t *testing.T) { t.SkipNow() /*get 请求*/ url := "http://localhost:8000/bind_json?name=李长全&password=123" //填空没有默认值 result := queryGet(t, url) fmt.Println(result) } /*post 请求*/ func band_json_post(t *testing.T) { t.SkipNow() url := "http://localhost:8000/bind_json" params := map[string]string{ "name": "李长全", "password": "123", //这种形式也算有值,不会填充默认值 } send := postSend(url, params) fmt.Println(send) } //xml 客户端发送数据 func band_xml(t *testing.T) { t.SkipNow() url := "http://localhost:8000/bind_xml" user := bind.User{} user.Name = "lcq" user.Password = "123" send := postSendCopy(url, user) fmt.Println(send) } //自定义验证器 func books(t *testing.T) { t.SkipNow() url := "http://localhost:8000/bookable?check_in=2019-04-16&check_out=2019-04-17" //填空没有默认值 result := queryGet(t, url) fmt.Println(result) }
package leetcode func minStartValue(nums []int) int { startValue := 0 sum := 0 for i, l := 0, len(nums); i < l; i++ { sum += nums[i] if sum <= 0 { startValue += 1 - sum sum = 1 } } if startValue == 0 { return 1 } return startValue }
package utils import ( "Golang-Echo-MVC-Pattern/constant" "Golang-Echo-MVC-Pattern/entity" "github.com/dgrijalva/jwt-go" "github.com/labstack/echo" "net/http" "os" ) func GetDataToken(c echo.Context) *entity.MyCustomClaims { tokenID := getAuthorizationToken(c) tokenKey := os.Getenv(constant.JWTKey) token, _ := getParseWithClaimsJWT(tokenKey, tokenID) claims, _ := token.Claims.(*entity.MyCustomClaims) return claims } func IsTokenValid(c echo.Context) bool { tokenID := getAuthorizationToken(c) tokenKey := os.Getenv(constant.JWTKey) token, err := getParseWithClaimsJWT(tokenKey, tokenID) if err != nil { return false } _, ok := token.Claims.(*entity.MyCustomClaims) if !ok { return false } return true } func getAuthorizationToken(c echo.Context) string { tokenID := c.Request().Header.Get(constant.Authorization) tokenID = TrimString(tokenID, constant.Bearer) tokenID = TrimString(tokenID, " ") return tokenID } func getParseWithClaimsJWT(tokenKey string, tokenID string) (*jwt.Token, error) { return jwt.ParseWithClaims(tokenID, &entity.MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) { return []byte(tokenKey), nil }) } func Middleware(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if !IsTokenValid(c) { return c.JSON(http.StatusUnauthorized, GetResNoData(constant.StatusError, constant.MessageFailedJWT)) } return next(c) } }
package 链表 // sortList 排序链表。 // 空间复杂度: O(1)。 // 时间复杂度: O(nlogn) func sortList(head *ListNode) *ListNode { // 1. 初始化。 dummyHead := &ListNode{ Next: head, } // 2. 获取链表长度。 length := getLength(head) // 3. 由下到上归并排序。 for size := 1; size <= length; size <<= 1 { tail := dummyHead cur := tail.Next for cur != nil { // 3.1 切分为3段链表。 list1 := cur // 第一段。 list2 := cut(cur, size) // 第二段。 cur = cut(list2, size) // 第三段。 // 3.2 合并。 tail.Next = merge(list1, list2) // 3.3 维护,保证 tail 指向合并后链表的尾部。 tail = getTailNode(tail) } } // 4. 返回。 return dummyHead.Next } // getLength 获取链表长度。 func getLength(head *ListNode) int { cur := head length := 0 for cur != nil { length++ cur = cur.Next } return length } // cut 切分链表为 head[ :min(size, len(head))],返回下一段链表的表头。 func cut(head *ListNode, size int) *ListNode { // 1. 让 cur 指向下一端链表的前一个节点。 cur := head for i := 1; i <= size-1 && cur != nil; i++ { cur = cur.Next } // 2. 断开第一段、第二段链表的连接,返回第二段链表的表头。 if cur != nil { nextListHead := cur.Next cur.Next = nil return nextListHead } // 3. 空返回。 return nil } // merge 两个链表合并。 func merge(list1, list2 *ListNode) *ListNode { // 1. 初始化。 dummyHead := &ListNode{} // 2. 合并。 tail := dummyHead for list1 != nil && list2 != nil { if list1.Val < list2.Val { tail.Next = list1 list1 = list1.Next } else { tail.Next = list2 list2 = list2.Next } tail = tail.Next } if list1 == nil { tail.Next = list2 } if list2 == nil { tail.Next = list1 } // 3. 返回。 return dummyHead.Next } // getTailNode 获取尾节点。 func getTailNode(head *ListNode) *ListNode { if head == nil { return nil } cur := head for cur.Next != nil { cur = cur.Next } return cur }
/* Copyright 2020 SUSE 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 main import ( "context" "fmt" "log" "net/http" "os" "github.com/cloudfoundry-community/go-cfenv" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readpref" ) func main() { serviceName := os.Getenv("SERVICE_NAME") if serviceName == "" { log.Fatal("SERVICE_NAME not set") } appEnv, err := cfenv.Current() if err != nil { log.Fatal(err) } mongodbService, err := appEnv.Services.WithName(serviceName) if err != nil { log.Fatal(err) } uriStr := mongodbService.Credentials["uri"].(string) fmt.Printf("Connecting to %q\n", uriStr) ctx := context.Background() client, err := mongo.Connect(ctx, options.Client().ApplyURI(uriStr)) if err != nil { log.Fatal(err) } defer client.Disconnect(ctx) if err := client.Ping(ctx, readpref.Primary()); err != nil { log.Fatal(err) } databaseStr := mongodbService.Credentials["database"].(string) collection := client.Database(databaseStr).Collection("mits") expectedValue := Mits{"12345"} if _, err := collection.InsertOne(ctx, expectedValue); err != nil { log.Fatal(err) } cursor, err := collection.Find(ctx, bson.D{}) if err != nil { log.Fatal(err) } var results []Mits if err := cursor.All(ctx, &results); err != nil { log.Fatal(err) } if len(results) != 1 { log.Fatal(fmt.Errorf("Invalid result length: %d, expected 1", len(results))) } value := results[0] if value.MitsID != expectedValue.MitsID { log.Fatal(fmt.Errorf("Value %q is not the expected %q", value, expectedValue)) } port, exists := os.LookupEnv("PORT") if !exists { port = "8080" } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "ok") }) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil)) } // Mits represents an instance to be inserted in the mits collection. type Mits struct { MitsID string `json:"mits_id"` }
package mt import ( "fmt" "io" ) type PointedThing interface { pt() } func (*PointedNode) pt() {} func (*PointedAO) pt() {} type PointedNode struct { Under, Above [3]int16 } func PointedSameNode(pos [3]int16) PointedThing { return &PointedNode{pos, pos} } type PointedAO struct { ID AOID } func writePointedThing(w io.Writer, pt PointedThing) error { buf := make([]byte, 2) buf[0] = 0 switch pt.(type) { case nil: buf[1] = 0 case *PointedNode: buf[1] = 1 case *PointedAO: buf[1] = 2 default: panic(pt) } if _, err := w.Write(buf); err != nil { return err } if pt == nil { return nil } return serialize(w, pt) } func readPointedThing(r io.Reader) (PointedThing, error) { buf := make([]byte, 2) if _, err := io.ReadFull(r, buf); err != nil { return nil, err } if buf[0] != 0 { return nil, fmt.Errorf("unsupported PointedThing version: %d", buf[0]) } var pt PointedThing switch buf[1] { case 0: return nil, nil case 1: pt = new(PointedNode) case 2: pt = new(PointedAO) case 3: return nil, fmt.Errorf("invalid PointedThing type: %d", buf[1]) } return pt, deserialize(r, pt) }
package main /** * 文件名: logcenter.go * 创建时间: 2018年3月9日-下午4:47:10 * 简介: * 详情: 游戏日志服 */ import ( "base/common" l4g "base/log4go" "flag" "fmt" "math/rand" "net/http" _ "net/http/pprof" "runtime" "time" ) var ( g_config = new(XmlConfig) g_handler_chan = make(chan *HttpRequestInfo, 102400) g_kafka_addr string g_logM = new(LogM) ) var configFile = flag.String("config", "config/logcenter.config.xml", "") func init() { InitHttpCommand() } func main() { defer time.Sleep(time.Second * 3) rand.Seed(time.Now().Unix()) runtime.GOMAXPROCS(runtime.NumCPU()) flag.Parse() if err := common.LoadConfig(*configFile, g_config); err != nil { panic(fmt.Sprintf("load config %v fail: %v", *configFile, err)) } l4g.LoadConfiguration(g_config.Log.Config) defer l4g.Close() g_kafka_addr = g_config.RemoteServerAddr("kafka") if g_kafka_addr == "" { l4g.Error("kafka config error") return } if g_config.Amount.HandlePool <= 0 || g_config.Amount.KafkaConsumer <= 0 || g_config.Amount.KafkaProducer <= 0 { l4g.Error("Amount config error") return } if g_config.Pprof.State == "true" { go func() { l4g.Error(http.ListenAndServe(g_config.Pprof.Port, nil)) }() } //http pools for i := uint32(0); i < g_config.Amount.HandlePool; i++ { pool := NewHttpHandlerPool(int(i)) go pool.Process() } //Kafka client g_log_kafka = NewLogKafka() if g_log_kafka == nil { l4g.Error("NewLogKafka error") return } else { l4g.Info("NewLogKafka success") } httpRouter() err := http.ListenAndServe(g_config.Server.Port, nil) //设置监听的端口 if err != nil { l4g.Error("ListenAndServe: %v", err) } }
package repository import ( "context" "fmt" "github.com/TodoApp2021/gorestreact/pkg/models" "github.com/jackc/pgx/v4/pgxpool" ) type AuthPostgres struct { pool *pgxpool.Pool } func NewAuthPostgres(pool *pgxpool.Pool) *AuthPostgres { return &AuthPostgres{pool: pool} } func (ap *AuthPostgres) CreateUser(user models.User) (int, error) { ctx := context.Background() var id int query := fmt.Sprintf("INSERT INTO %s (name, username, password_hash) VALUES ($1, $2, $3) RETURNING id", usersTable) conn, err := ap.pool.Acquire(ctx) if err != nil { return 0, err } defer conn.Release() tx, err := conn.Begin(ctx) if err != nil { return 0, err } row := tx.QueryRow(ctx, query, user.Name, user.Username, user.Password) if err := row.Scan(&id); err != nil { return 0, err } return id, tx.Commit(ctx) } func (ap *AuthPostgres) GetUser(username, password string) (models.User, error) { ctx := context.Background() var user models.User query := fmt.Sprintf("SELECT id, name, username, password_hash FROM %s WHERE username=$1 AND password_hash=$2", usersTable) conn, err := ap.pool.Acquire(ctx) if err != nil { return user, err } defer conn.Release() tx, err := conn.Begin(ctx) if err != nil { return user, err } row := tx.QueryRow(ctx, query, username, password) if err := row.Scan(&user.Id, &user.Name, &user.Username, &user.Password); err != nil { return user, err } return user, tx.Commit(ctx) }
package main import ( "flag" "fmt" "os" "os/user" "text/tabwriter" ) const ( cliName = "conair" cliDescription = "conair is a command-line interface to systemd-nspawn containers. much like docker." bridge = "nspawn0" destination = "192.168.13.0/24" home = "/var/lib/machines" hub = "http://conair.teemow.com/images" ) var ( out *tabwriter.Writer globalFlagset = flag.NewFlagSet(cliName, flag.ExitOnError) // top level commands commands []*Command // flags used by all commands globalFlags = struct { Debug bool Version bool }{} projectVersion string ) type stringSlice []string func (s *stringSlice) String() string { return fmt.Sprintf("%v", *s) } func (s *stringSlice) Set(value string) error { *s = append(*s, value) return nil } func init() { user, err := user.Current() if err != nil { fmt.Fprintln(os.Stderr, "Can't find current user. Need to be root.") os.Exit(1) } if user.Uid != "0" { fmt.Fprintln(os.Stderr, "Please run conair as root.") os.Exit(1) } globalFlagset.BoolVar(&globalFlags.Debug, "debug", false, "Print out more debug information to stderr") globalFlagset.BoolVar(&globalFlags.Version, "version", false, "Print the version and exit") } type Command struct { Name string // Name of the Command and the string to use to invoke it Summary string // One-sentence summary of what the Command does Usage string // Usage options/arguments Description string // Detailed description of command Flags flag.FlagSet // Set of flags associated with this command Run func(args []string) int // Run a command with the given arguments, return exit status } func init() { out = new(tabwriter.Writer) out.Init(os.Stdout, 0, 8, 1, '\t', 0) commands = []*Command{ cmdAttach, cmdInit, cmdDestroy, cmdPs, cmdImages, cmdRun, cmdStop, cmdStart, cmdRm, cmdRmi, cmdCommit, cmdStatus, cmdBuild, cmdPull, cmdBootstrap, cmdInspect, cmdIp, cmdSnapshot, cmdHelp, cmdVersion, } } func getAllFlags() (flags []*flag.Flag) { return getFlags(globalFlagset) } func getFlags(flagset *flag.FlagSet) (flags []*flag.Flag) { flags = make([]*flag.Flag, 0) flagset.VisitAll(func(f *flag.Flag) { flags = append(flags, f) }) return } func main() { globalFlagset.Parse(os.Args[1:]) var args = globalFlagset.Args() if len(args) < 1 { args = append(args, "help") } // deal specially with --version if globalFlags.Version { args[0] = "version" } var cmd *Command // determine which Command should be run for _, c := range commands { if c.Name == args[0] { cmd = c if err := c.Flags.Parse(args[1:]); err != nil { fmt.Println(err.Error()) os.Exit(2) } break } } if cmd == nil { fmt.Printf("%v: unknown subcommand: %q\n", cliName, args[0]) fmt.Printf("Run '%v help' for usage.\n", cliName) os.Exit(2) } os.Exit(cmd.Run(cmd.Flags.Args())) }
package sqls // SelResult is SQL. const SelResult = ` SELECT r.file_path FROM results r WHERE r.competition_id = ? AND r.user_id = ? ORDER BY r.created_at DESC LIMIT 1 `
package main import "fmt" func setRoute() { fmt.Printf("Hello, World!!") }
package feed import ( "encoding/xml" "strings" "github.com/azzzak/fakecast/fs" "github.com/azzzak/fakecast/store" ) // RSS entity type RSS struct { XMLName xml.Name `xml:"rss"` Version string `xml:"version,attr"` Itunes string `xml:"xmlns:itunes,attr"` Content string `xml:"xmlns:content,attr"` Channel Channel `xml:"channel"` } // Channel entity type Channel struct { Title string `xml:"title"` Link string `xml:"link,omitempty"` Copyright string `xml:"copyright,omitempty"` Author string `xml:"itunes:author,omitempty"` Description string `xml:"description,omitempty"` Type string `xml:"itunes:type,omitempty"` Image struct { Href string `xml:"href,attr,omitempty"` } `xml:"itunes:image"` Items []Item `xml:"item"` } // Item entity type Item struct { Title string `xml:"title"` Enclosure Enclosure `xml:"enclosure"` GUID string `xml:"guid,omitempty"` PubDate string `xml:"pubDate"` Description string `xml:"description,omitempty"` Duration int `xml:"itunes:duration"` Link string `xml:"link,omitempty"` Explicit bool `xml:"itunes:explicit,omitempty"` Season int `xml:"itunes:season,omitempty"` Episode int `xml:"itunes:episode,omitempty"` } // Enclosure entity type Enclosure struct { URL string `xml:"url,attr"` Length int `xml:"length,attr,omitempty"` Type string `xml:"type,attr,omitempty"` } // GenerateFeed with content of channel func GenerateFeed(channel *store.Channel, podcasts []store.Podcast, host string) RSS { feed := RSS{ Version: "2.0", Itunes: "http://www.itunes.com/dtds/podcast-1.0.dtd", Content: "http://purl.org/rss/1.0/modules/content/", } feed.Channel = Channel{ Title: channel.Title, Description: channel.Description, Author: channel.Author, } feed.Channel.Image.Href = channel.Cover var items []Item for _, p := range podcasts { var explicit bool if p.Explicit == 1 { explicit = true } // Types // mp3 (*.mp3): audio/mpeg // aac (*.m4a): audio/x-m4a cType := "audio/mpeg" if _, ext := fs.NameAndExtFrom(p.Filename); ext == "m4a" { cType = "audio/x-m4a" } items = append(items, Item{ Title: p.Title, Enclosure: Enclosure{ URL: strings.Join([]string{host, "files", channel.Alias, p.Filename}, "/"), Length: p.Length, Type: cType, }, GUID: p.GUID, PubDate: p.PubDate, Description: p.Description, Duration: p.Duration, Explicit: explicit, Season: p.Season, Episode: p.Episode, }) } feed.Channel.Items = items return feed }
package http_metric import ( "time" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "github.com/SDkie/metric_collector/db" "github.com/SDkie/metric_collector/logger" "github.com/gin-gonic/gin" ) //go:generate easytags http_metric.go bson type HttpMetric struct { Id string `bson:"_id"` Count int `bson:"count"` TotalResponseTime time.Duration `bson:"total_response_time"` } var metric HttpMetric const HTTP_METRIC = "HTTP_METRIC" func Init() { hmetric := new(HttpMetric) err := db.MgFindOne(HTTP_METRIC, &bson.M{"_id": HTTP_METRIC}, hmetric) if err != nil { hmetric.Id = HTTP_METRIC hmetric.Count = 0 hmetric.TotalResponseTime = 0 db.MgCreate(HTTP_METRIC, hmetric) } } func HttpMetricMiddleware() gin.HandlerFunc { return func(c *gin.Context) { startTime := time.Now() c.Next() processingTime := time.Now().Sub(startTime) hmetric := new(HttpMetric) change := mgo.Change{ Update: bson.M{"$inc": bson.M{"count": 1, "total_response_time": processingTime}}, ReturnNew: true, } /* MgFindAndModify does findAndModify atomically. So even if multiple instances of this is executed its data will always be consistent */ err := db.MgFindAndModify(HTTP_METRIC, &bson.M{"_id": HTTP_METRIC}, change, hmetric) if err != nil { logger.Errf("Error while running MgFindAndModify %s", err) return } avg := time.Duration(int(hmetric.TotalResponseTime) / hmetric.Count) logger.Debugf("HTTP Metrics:\n No of Requests Handled: %d\n Current processing Time: %s\n Avg Processing Time: %s", hmetric.Count, processingTime, avg) } }
package internal import ( "bytes" "github.com/stretchr/testify/assert" "testing" ) func TestVersion(t *testing.T) { buf := new(bytes.Buffer) WriteVersionInfo("foobar", buf) s := buf.String() assert.Contains(t, s, "foobar version") }
package main import ( "sort" "fmt" ) func main() { // 就地排序,改变原有序列,无返回值 strs := []string{"e", "a", "g", "k"} sort.Strings(strs) fmt.Println(strs) ints := []int{98, 1, 33, 5, 76} sort.Ints(ints) fmt.Println(ints) }
package models type Node_lookup struct { RemoteAddress string `json:"remote_address"` Hostname string `json:"hostname"` BroadcastAddress string `json:"broadcast_address"` TCPPort int `json:"tcp_port"` HTTPPort int `json:"http_port"` Version string `json:"version"` Tombstones []bool `json:"tombstones"` Topics []string `json:"topics"` } type NodeInfoObj_lookup struct { Producers []Node_lookup `json:"producers"` } type NodeInfo_lookup struct { Status_code int `json:"status_code"` Status_txt string `json:"status_txt"` Data NodeInfoObj_lookup `json:"data"` } type NodeInfo_nsqd struct { Status_code int `json:"status_code"` Status_txt string `json:"status_txt"` Data StatsInfo_nsqd `json:"data"` } type StatsInfo_nsqd struct { Version string `json:"version"` Health string `json:"health"` StartTime int64 `json:"start_time"` Topics []TopicStats `json:"topics"` } type TopicStats struct { TopicName string `json:"topic_name"` Channels []ChannelStats `json:"channels"` Depth int64 `json:"depth"` BackendDepth int64 `json:"backend_depth"` MessageCount uint64 `json:"message_count"` Paused bool `json:"paused"` //E2eProcessingLatency *quantile.Result `json:"e2e_processing_latency"` } type ChannelStats struct { ChannelName string `json:"channel_name"` Depth int64 `json:"depth"` BackendDepth int64 `json:"backend_depth"` InFlightCount int `json:"in_flight_count"` DeferredCount int `json:"deferred_count"` MessageCount uint64 `json:"message_count"` RequeueCount uint64 `json:"requeue_count"` TimeoutCount uint64 `json:"timeout_count"` //Clients []ClientStats `json:"clients"` Paused bool `json:"paused"` // E2eProcessingLatency *quantile.Result `json:"e2e_processing_latency"` }
package tpl const ModelTpl = `package {{model}} ` type A struct { Test string `json:"test"` }
package utils import ( "log" ) const ( Error = iota + 31 Debug Warn Info Fatal ) func LogPrint(msg interface{}, level int) { log.Printf("%c[%d;%d;%dm%s%c[0m\n", 0x1B, 0, 0, level, msg, 0x1B) }
package main import ( "io/ioutil" "strconv" ) func check(e error) { if e != nil { panic(e) } } func readContentFile(contentPath string) string { data, err := ioutil.ReadFile(contentPath) check(err) return BytesToStr(data) } func prependContentHeaders(contentType string, content string) string { header := contentType + " " + strconv.Itoa(len(content)) + "\000" newContent := header + content return newContent }
package hw05_parallel_execution //nolint:golint,stylecheck import ( "fmt" "math/rand" "sync/atomic" "testing" "time" "github.com/stretchr/testify/require" ) func TestRun(t *testing.T) { t.Run("if were errors in first M tasks, than finished not more N+M tasks", func(t *testing.T) { tasksCount := 50 tasks := make([]Task, 0, tasksCount) var runTasksCount int32 for i := 0; i < tasksCount; i++ { tasks = append(tasks, func() error { time.Sleep(time.Millisecond * time.Duration(rand.Intn(100))) atomic.AddInt32(&runTasksCount, 1) return fmt.Errorf("error from task %d", i) }) } workersCount := 10 maxErrorsCount := 23 result := Run(tasks, workersCount, maxErrorsCount) require.Equal(t, ErrErrorsLimitExceeded, result) require.LessOrEqual(t, int32(workersCount+maxErrorsCount), runTasksCount, "extra tasks were started") }) t.Run("tasks without errors", func(t *testing.T) { tasksCount := 50 tasks := make([]Task, 0, tasksCount) var runTasksCount int32 var sumTime time.Duration for i := 0; i < tasksCount; i++ { taskSleep := time.Millisecond * time.Duration(rand.Intn(100)) sumTime += taskSleep tasks = append(tasks, func() error { time.Sleep(taskSleep) atomic.AddInt32(&runTasksCount, 1) return nil }) } workersCount := 5 maxErrorsCount := 1 start := time.Now() result := Run(tasks, workersCount, maxErrorsCount) elapsedTime := time.Since(start) require.Nil(t, result) require.Equal(t, int32(tasksCount), runTasksCount, "not all tasks were completed") require.LessOrEqual(t, int64(elapsedTime), int64(sumTime/2), "tasks were run sequentially?") }) t.Run("Every third task produces error: successed", func(t *testing.T) { tasksCount := 30 tasks := make([]Task, 0, tasksCount) var runTasksCount int32 for i := 0; i < tasksCount; i++ { if i%3 == 0 { tasks = append(tasks, func() error { atomic.AddInt32(&runTasksCount, 1) return fmt.Errorf("Some kind of error") }) } else { tasks = append(tasks, func() error { atomic.AddInt32(&runTasksCount, 1) return nil }) } } result := Run(tasks, 10, 11) require.Nil(t, result) require.Equal(t, int32(tasksCount), runTasksCount, "not all tasks were completed") }) t.Run("Every third task produces error: failed", func(t *testing.T) { tasksCount := 30 tasks := make([]Task, 0, tasksCount) var runTasksCount int32 for i := 0; i < tasksCount; i++ { if i%3 == 0 { tasks = append(tasks, func() error { atomic.AddInt32(&runTasksCount, 1) return fmt.Errorf("Some kind of error") }) } else { tasks = append(tasks, func() error { atomic.AddInt32(&runTasksCount, 1) return nil }) } } result := Run(tasks, 10, 8) require.Error(t, ErrErrorsLimitExceeded, result) }) }
/* * @lc app=leetcode.cn id=235 lang=golang * * [235] 二叉搜索树的最近公共祖先 */ package main type TreeNode struct { Val int Left *TreeNode Right *TreeNode } /* func lowestCommonAncestorCore(root, p, q *TreeNode, ancestor **TreeNode) { if root == nil { return } if p.Val < root.Val && q.Val < root.Val { lowestCommonAncestorCore(root.Left, p, q, ancestor) } else if p.Val > root.Val && q.Val > root.Val { lowestCommonAncestorCore(root.Right, p, q, ancestor) } else { *ancestor = root } } func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { ancestor := &TreeNode{} lowestCommonAncestorCore(root, p, q, &ancestor) return ancestor } */ // @lc code=start func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { ancestor := root for { if p.Val < ancestor.Val && q.Val < ancestor.Val { ancestor = ancestor.Left } else if p.Val > ancestor.Val && q.Val > ancestor.Val { ancestor = ancestor.Right } else { break } } return ancestor } // @lc code=end func main() { lowestCommonAncestor(nil, nil, nil) }
package issue // NotFoundError represents account not found error type NotFoundError struct{} func (inf NotFoundError) Error() string { return "Issue Not Found" }
package action import ( "github.com/guilhermesteves/aclow" ) type UpdateTodo struct { app *aclow.App } func (n *UpdateTodo) Address() []string { return []string{"update_todo"} } func (n *UpdateTodo) Start(app *aclow.App) { n.app = app } func (n *UpdateTodo) Execute(msg aclow.Message, call aclow.Caller) (aclow.Message, error) { return aclow.Message{}, nil }
package ora2uml import ( "testing" ) func TestModelTableFullName(t *testing.T) { var table = ModelTable{TableName: "tableName"} if table.FullName() != "tableName" { t.Errorf("table.FullName() should be 'tableName', but was '%v'", table.FullName()) } table.Owner = "sys" if table.FullName() != "sys.tableName" { t.Errorf("table.FullName() should be 'sys.tableName', but was '%v'", table.FullName()) } }
package commit import ( "github.com/scjalliance/drivestream/collection" "github.com/scjalliance/drivestream/page" ) // Source identifies the source of a commit within a collection. type Source struct { Collection collection.SeqNum `json:"collection"` Page page.SeqNum `json:"page,omitempty"` Index int `json:"index,omitempty"` }
package main import ( "fmt" "go.uber.org/zap" ) func main() { fmt.Printf("*** Using the Example logger\n\n") logger := zap.NewExample() logger.Debug("This is a DEBUG message") logger.Info("This is an INFO message") logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2)) logger.Warn("This is a WARN message") logger.Error("This is an ERROR message") // logger.Fatal("This is a FATAL message") // would exit if uncommented logger.DPanic("This is a DPANIC message") //logger.Panic("This is a PANIC message") // would exit if uncommented fmt.Println() fmt.Printf("*** Using the Development logger\n\n") logger, _ = zap.NewDevelopment() logger.Debug("This is a DEBUG message") logger.Info("This is an INFO message") logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2)) logger.Warn("This is a WARN message") logger.Error("This is an ERROR message") // logger.Fatal("This is a FATAL message") // would exit if uncommented // logger.DPanic("This is a DPANIC message") // would exit if uncommented //logger.Panic("This is a PANIC message") // would exit if uncommented fmt.Println() fmt.Printf("*** Using the Production logger\n\n") logger, _ = zap.NewProduction() logger.Debug("This is a DEBUG message") logger.Info("This is an INFO message") logger.Info("This is an INFO message with fields", zap.String("region", "us-west"), zap.Int("id", 2)) logger.Warn("This is a WARN message") logger.Error("This is an ERROR message") // logger.Fatal("This is a FATAL message") // would exit if uncommented logger.DPanic("This is a DPANIC message") // logger.Panic("This is a PANIC message") // would exit if uncommented fmt.Println() fmt.Printf("*** Using the Sugar logger\n\n") logger, _ = zap.NewDevelopment() slogger := logger.Sugar() slogger.Info("Info() uses sprint") slogger.Infof("Infof() uses %s", "sprintf") slogger.Infow("Infow() allows tags", "name", "Legolas", "type", 1) }
//合约的部署工具 //author:caige package deploy import ( "context" "fmt" "io/ioutil" "os" "strings" "comment/token" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/rpc" ) func main() { host := "http://localhost:8545" conn := connectGethRpc(host) keystoreFile := "/Users/caige/geth/init/data/keystore/UTC--2018-06-23T05-02-34.518642288Z--256916bba6f3c2b6519226d083b7b2fbc9eef646" auth := createGethAuth(keystoreFile, "caige") address, ts, _, err := deployContract(conn, auth) if err != nil { logger("部署失败:" + err.Error()) os.Exit(1) } logger("部署完成!") logger("合约地址:" + address.Hex()) logger("交易Hash:" + ts.Hash().Hex()) } //连接geth func connectGethRpc(rpcHost string) *ethclient.Client { logger("连接geth host:" + rpcHost) client, dialErr := rpc.Dial(rpcHost) if dialErr != nil { panic(dialErr) logger("连接失败:" + dialErr.Error()) os.Exit(1) } conn := ethclient.NewClient(client) network, getNetworkIdErr := conn.NetworkID(context.TODO()) if getNetworkIdErr != nil { logger("获取network id 失败:" + getNetworkIdErr.Error()) os.Exit(1) } else { logger("获取network id:" + network.String()) } return conn } //生成geth认证账户 func createGethAuth(keystoreFile, pass string) *bind.TransactOpts { keyStoreContent, readErr := ioutil.ReadFile(keystoreFile) if readErr != nil { logger("读取keystore 文件失败:" + readErr.Error()) os.Exit(1) } key := string(keyStoreContent) auth, err := bind.NewTransactor(strings.NewReader(key), pass) if err != nil { logger("创建transactor失败:" + err.Error()) os.Exit(1) } return auth } //部署合约 func deployContract(conn *ethclient.Client, auth *bind.TransactOpts) (common.Address, *types.Transaction, *token.Comment, error) { return token.DeployComment(auth, conn) } //日志 func logger(v interface{}) { fmt.Println(v) }
package hashmap_shards type sliceInterfaceData struct { data []interface{} err error } func (impl implementation) HMGet(key string, fields ...string) ([]interface{}, error) { var response = make([]interface{}, 0) var err error = nil var keys = impl.constructMapKey(key, fields...) var dataChannel = make(chan sliceInterfaceData, len(keys)) for k, v := range keys { go impl.hmGet(k, dataChannel, v...) } for i := 0; i < len(keys); i++ { select { case x := <-dataChannel: if x.err == nil { response = append(response, x.data...) } else { err = x.err } break } } close(dataChannel) return response, err } func (impl implementation) hmGet(key string, data chan sliceInterfaceData, fields ...string) { response, err := impl.redis.HMGet(key, fields...) data <- sliceInterfaceData{ data: response, err: err, } }
package NFA type NFADesign struct { CurrentStates []int32 AcceptStates []int32 Rulebook DFARulebook } func (n NFADesign) Accepts(sequence string) bool { nfa := n.ToNFA(n.CurrentStates, n.AcceptStates, n.Rulebook) nfa.ReadString(sequence) return nfa.Accepting() } func (n NFADesign) ToNFA(currentStates []int32, acceptState []int32, rulebook DFARulebook) NFA { return NFA{ currentStates: currentStates, acceptStates: acceptState, rulebook: rulebook, } }
// Contains the model of the application data package models import ( "glsamaker/pkg/config" "glsamaker/pkg/database/connection" "time" ) type ApplicationSetting struct { Key string `pg:",pk"` Value string LastUpdate time.Time //LastBugUpdate time.Time //LastCVEUpdate time.Time } type GlobalSettings struct { LastBugUpdate time.Time LastCVEUpdate time.Time Version string Force2FALogin bool Force2FAGLSARelease bool } func GetApplicationKey(key string) *ApplicationSetting { applicationData := &ApplicationSetting{Key: key} connection.DB.Model(applicationData).WherePK().Select() return applicationData } func SetApplicationValue(key string, value string) { applicationData := &ApplicationSetting{ Key: key, Value: value, LastUpdate: time.Now(), } connection.DB.Model(applicationData).WherePK().OnConflict("(key) DO Update").Insert() } func SeedApplicationValue(key string, value string) { applicationData := &ApplicationSetting{ Key: key, Value: value, LastUpdate: time.Now(), } connection.DB.Model(applicationData).WherePK().OnConflict("(key) DO Nothing").Insert() } func GetDefaultGlobalSettings() *GlobalSettings { return &GlobalSettings{ LastBugUpdate: GetApplicationKey("LastBugUpdate").LastUpdate, LastCVEUpdate: GetApplicationKey("LastCVEUpdate").LastUpdate, Version: GetApplicationKey("Version").Value, Force2FALogin: GetApplicationKey("Force2FALogin").Value == "1", Force2FAGLSARelease: GetApplicationKey("Force2FAGLSARelease").Value == "1", } } func SeedInitialApplicationData() { SeedApplicationValue("LastBugUpdate", "") SeedApplicationValue("LastCVEUpdate", "") SeedApplicationValue("Version", config.Version()) SeedApplicationValue("Force2FALogin", "0") SeedApplicationValue("Force2FAGLSARelease", "0") }
package sms import ( "crypto/subtle" "encoding/json" "fmt" "log" "net/http" "net/url" "strings" "github.com/pkg/errors" ) // Twilio represents an account with the communications provider // Twilio. type Twilio struct { accountSid string keySid string keySecret string // where to listen for incoming HTTP requests httpHost string httpPort int // credentials for HTTP auth httpUsername string httpPassword string publicUrl *url.URL client *http.Client } // make sure we implement the right interfaces var _ SmsProvider = &Twilio{} // represents a response from Twilio's API type twilioApiResponse struct { Status string `json:"status"` Message string `json:"message"` Sid string `json:"sid"` Flags []string `json:"flags"` } // represents the HTTP server used for receiving incoming SMS from Twilio type twilioHttpServer struct { username string password string rxSmsCh chan<- RxSms } func (t *Twilio) httpClient() *http.Client { if t.client == nil { return http.DefaultClient } return t.client } // do runs a single API request against Twilio func (t *Twilio) do(service string, form url.Values) (*twilioApiResponse, error) { url := "https://api.twilio.com/2010-04-01/Accounts/" + t.accountSid + "/" + service + ".json" req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode())) if err != nil { return nil, errors.Wrap(err, "building HTTP request") } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.SetBasicAuth(t.keySid, t.keySecret) res, err := t.httpClient().Do(req) if err != nil { return nil, errors.Wrap(err, "running HTTP request") } if res.StatusCode < 200 || res.StatusCode > 299 { return nil, fmt.Errorf("unexpected status: %s", res.Status) } // parse response tRes := new(twilioApiResponse) defer res.Body.Close() err = json.NewDecoder(res.Body).Decode(tRes) if err != nil { return nil, errors.Wrap(err, "parsing Twilio response") } // was the message queued for delivery? if tRes.Status != "queued" { return nil, fmt.Errorf("unexpected status from Twilio API (%s): %s", tRes.Status, tRes.Message) } return tRes, nil } func (t *Twilio) SendSms(sms *Sms) (string, error) { form := make(url.Values) form.Set("To", sms.To) form.Set("From", sms.From) form.Set("Body", sms.Body) if t.publicUrl != nil { form.Set("StatusCallback", t.publicUrl.String()) } res, err := t.do("Messages", form) if err != nil { return "", err } return res.Sid, nil } func (t *Twilio) RunPstnProcess(rxSmsCh chan<- RxSms) <-chan struct{} { s := &twilioHttpServer{ username: t.httpUsername, password: t.httpPassword, rxSmsCh: rxSmsCh, } addr := fmt.Sprintf("%s:%d", t.httpHost, t.httpPort) healthCh := make(chan struct{}) go func() { defer func() { close(healthCh) }() err := http.ListenAndServe(addr, s) log.Printf("HTTP server error: %s", err) }() return healthCh } func (s *twilioHttpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { msgSid := r.FormValue("MessageSid") log.Printf("%s %s (%s)", r.Method, r.URL.Path, msgSid) // verify HTTP authentication if !s.isHttpAuthenticated(r) { w.Header().Set("WWW-Authenticate", "Basic realm=\"sms-over-xmpp\"") w.WriteHeader(http.StatusUnauthorized) fmt.Fprintln(w, "Not authorized") return } // what kind of notice did we receive? errCh := make(chan error) rx, err := s.recognizeNotice(r, errCh) if err == nil && rx != nil { s.rxSmsCh <- rx err = <-errCh } if err != nil { msg := fmt.Sprintf("ERROR: %s", err) w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, msg) log.Println(msg) return } // send blank payload for Twilio to stop complaining w.Header().Set("Content-Type", "text/xml") w.Write([]byte("<Response></Response>")) } func (s *twilioHttpServer) recognizeNotice(r *http.Request, errCh chan<- error) (RxSms, error) { id := r.FormValue("MessageSid") status := r.FormValue("MessageStatus") if id != "" && status != "" { if status == "delivered" { rx := &rxSmsStatus{ id: id, status: smsDelivered, errCh: errCh, } return rx, nil } return nil, nil } from := r.FormValue("From") to := r.FormValue("To") body := r.FormValue("Body") sms := &Sms{ From: from, To: to, Body: body, } rx := &rxSmsMessage{ sms: sms, errCh: errCh, } return rx, nil } func (s *twilioHttpServer) isHttpAuthenticated(r *http.Request) bool { wantUser := s.username wantPass := s.password if wantUser == "" && wantPass == "" { return true } // now we know that HTTP authentication is mandatory gotUser, gotPass, ok := r.BasicAuth() if !ok { return false } if subtle.ConstantTimeCompare([]byte(gotUser), []byte(wantUser)) != 1 { return false } if subtle.ConstantTimeCompare([]byte(gotPass), []byte(wantPass)) != 1 { return false } return true }
package models import ( "github.com/astaxie/beego/orm" "time" "tokensky_bg_admin/utils" ) //理财分类表 /* CREATE TABLE `financial_category` ( `id` int(11) NOT NULL, `avatar` varchar(255) NOT NULL, `symbol` varchar(255) NOT NULL, `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='理财分类' */ //查询的类 type FinancialCategoryQueryParam struct { BaseQueryParam Name string `json:"name"` StartTime int64 `json:"startTime"` //开始时间 EndTime int64 `json:"endTime"` //截止时间 Status string `json:"status"` //状态 Id int `json:"id"` } // TableName 设置表名 func (a *FinancialCategory) TableName() string { return FinancialCategoryTBName() } type FinancialCategory struct { Id int `orm:"pk;column(id)"json:"id"form:"id"` //头像 Avatar string `orm:"column(avatar)"json:"avatar"form:"avatar"` //路径 AvatarUrl string `orm:"-"json:"avatarUrl"form:"avatarUrl"` //货币类型 Symbol string `orm:"column(symbol)"json:"symbol"form:"symbol"` //创建时间 CreateTime time.Time `orm:"auto_now_add;type(datetime);column(create_time)"json:"createTime"form:"createTime"` //更新时间 //UpdateTime time.Time `orm:"auto_now;type(datetime);column(update_time)"json:"updateTime"form:"updateTime"` AdminId int `orm:"column(admin_id)"json:"adminId"form:"adminId"` // FinancialBaseConfigs []*FinancialProduct `orm:"reverse(many)"json:"-"form:"-"` } //获取分页数据 func FinancialCategoryPageList(params *FinancialCategoryQueryParam) ([]*FinancialCategory, int64) { o := orm.NewOrm() query := o.QueryTable(FinancialCategoryTBName()) data := make([]*FinancialCategory, 0) //默认排序 sortorder := "id" switch params.Sort { case "id": sortorder = "id" } if params.Order == "desc" { sortorder = "-" + sortorder } if params.Id != 0 { query = query.Filter("id__exact", params.Id) } total, _ := query.Count() query.OrderBy(sortorder).Limit(params.Limit, (params.Offset-1)*params.Limit).All(&data) //图片下载凭证 deadline := time.Now().Add(time.Second * 3600).Unix() //1小时有效期 for _, obj := range data { obj.AvatarUrl = utils.QiNiuDownload(obj.Avatar, deadline) } return data, total } func FinancialCategoryDelete(id int) (bool, string) { o := orm.NewOrm() query := o.QueryTable(FinancialProductTBName()) query.Filter("financial_category_id__exact", id) count, _ := query.Count() if count > 0 { return false, "关联中不可删除" } _,err := o.QueryTable(FinancialCategoryTBName()).Filter("id__exact",id).Delete() if err != nil { return false, err.Error() } return false, "" }
package main /* * @lc app=leetcode id=113 lang=golang * * [113] Path Sum II */ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func pathSum(root *TreeNode, sum int) [][]int { var res [][]int traverse(root, sum, []int{}, &res) return res } func traverse(root *TreeNode, sum int, path []int, res *[][]int) { if root == nil { return } sum -= root.Val path = append(path, root.Val) if root.Left == nil && root.Right == nil { if sum == 0 { *res = append(*res, copySlice(path)) } return } traverse(root.Left, sum, path, res) traverse(root.Right, sum, path, res) } func copySlice(s []int) []int { t := make([]int, len(s)) copy(t, s) return t }
package router import ( "github.com/astaxie/beego" "github.com/astaxie/beego/context" "github.com/astaxie/beego/logs" "github.com/initlove/ocihub/controllers" ) const ( ociV1Prefix = "/oci/v1" ) func init() { if err := RegisterRouter(ociV1Prefix, OCIV1NameSpace()); err != nil { logs.Error("Failed to register router: '%s'.", ociV1Prefix) } else { logs.Debug("Register router '%s' registered.", ociV1Prefix) } } // OCIV1NameSpace defines the oci v1 router func OCIV1NameSpace() *beego.Namespace { ns := beego.NewNamespace(ociV1Prefix, beego.NSCond(func(ctx *context.Context) bool { logs.Debug("We get ociv1") return true }), beego.NSGet("/", func(ctx *context.Context) { ctx.Output.Body([]byte("ok")) }), beego.NSGet("/_catalog", func(ctx *context.Context) { ctx.Output.Body([]byte("ok")) }), beego.NSRouter("/*/tags/list", &controllers.OCIV1Tag{}, "get:GetTagsList"), beego.NSRouter("/*/blobs/uploads/?:uuid", &controllers.OCIV1Blob{}, "post:PostBlob;patch:PatchBlob;put:PutBlob"), beego.NSRouter("/*/blobs/:digest", &controllers.OCIV1Blob{}, "head:HeadBlob;get:GetBlob;delete:DeleteBlob"), beego.NSRouter("/*/manifest/:tags", &controllers.OCIV1Manifest{}, "get:GetManifest;put:PutManifest;delete:DeleteManifest"), ) return ns }
package tsmt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document01700103 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:tsmt.017.001.03 Document"` Message *ForwardDataSetSubmissionReportV03 `xml:"FwdDataSetSubmissnRpt"` } func (d *Document01700103) AddMessage() *ForwardDataSetSubmissionReportV03 { d.Message = new(ForwardDataSetSubmissionReportV03) return d.Message } // Scope // The ForwardDataSetSubmissionReport message is sent by the matching application to the counterparty(ies) of the submitter of data sets. // This message is used to pass on information related to the purchasing agreement(s) covered by the transaction(s) referred to in the message. // Usage // The ForwardDataSetSubmission message can be sent by the matching application to forward the details of a DataSetSubmission message that it has obtained. type ForwardDataSetSubmissionReportV03 struct { // Identifies the report. ReportIdentification *iso20022.MessageIdentification1 `xml:"RptId"` // Identifies the transactions that this submission relates to and provides associated information. RelatedTransactionReferences []*iso20022.DataSetSubmissionReferences4 `xml:"RltdTxRefs"` // This reference must be used for all data sets belonging to the same submission group. CommonSubmissionReference *iso20022.SimpleIdentificationInformation `xml:"CmonSubmissnRef"` // The financial institution that has submitted the data sets to the matching engine. Submitter *iso20022.BICIdentification1 `xml:"Submitr"` // The financial institution of the buyer, uniquely identified by its BIC. BuyerBank *iso20022.BICIdentification1 `xml:"BuyrBk"` // The financial institution of the seller, uniquely identified by its BIC. SellerBank *iso20022.BICIdentification1 `xml:"SellrBk"` // Commercial information that has been submitted to the matching application by the other party. CommercialDataSet *iso20022.CommercialDataSet3 `xml:"ComrclDataSet,omitempty"` // Transport information that has been submitted to the matching application by the other party. TransportDataSet *iso20022.TransportDataSet3 `xml:"TrnsprtDataSet,omitempty"` // Insurance information that has been submitted to the matching application by the other party. InsuranceDataSet *iso20022.InsuranceDataSet1 `xml:"InsrncDataSet,omitempty"` // Certificate information that has been submitted to the matching application by the other party. CertificateDataSet []*iso20022.CertificateDataSet1 `xml:"CertDataSet,omitempty"` // Other certificate information that has been submitted to the matching application by the other party. OtherCertificateDataSet []*iso20022.OtherCertificateDataSet1 `xml:"OthrCertDataSet,omitempty"` // Next processing step required. RequestForAction *iso20022.PendingActivity2 `xml:"ReqForActn,omitempty"` } func (f *ForwardDataSetSubmissionReportV03) AddReportIdentification() *iso20022.MessageIdentification1 { f.ReportIdentification = new(iso20022.MessageIdentification1) return f.ReportIdentification } func (f *ForwardDataSetSubmissionReportV03) AddRelatedTransactionReferences() *iso20022.DataSetSubmissionReferences4 { newValue := new(iso20022.DataSetSubmissionReferences4) f.RelatedTransactionReferences = append(f.RelatedTransactionReferences, newValue) return newValue } func (f *ForwardDataSetSubmissionReportV03) AddCommonSubmissionReference() *iso20022.SimpleIdentificationInformation { f.CommonSubmissionReference = new(iso20022.SimpleIdentificationInformation) return f.CommonSubmissionReference } func (f *ForwardDataSetSubmissionReportV03) AddSubmitter() *iso20022.BICIdentification1 { f.Submitter = new(iso20022.BICIdentification1) return f.Submitter } func (f *ForwardDataSetSubmissionReportV03) AddBuyerBank() *iso20022.BICIdentification1 { f.BuyerBank = new(iso20022.BICIdentification1) return f.BuyerBank } func (f *ForwardDataSetSubmissionReportV03) AddSellerBank() *iso20022.BICIdentification1 { f.SellerBank = new(iso20022.BICIdentification1) return f.SellerBank } func (f *ForwardDataSetSubmissionReportV03) AddCommercialDataSet() *iso20022.CommercialDataSet3 { f.CommercialDataSet = new(iso20022.CommercialDataSet3) return f.CommercialDataSet } func (f *ForwardDataSetSubmissionReportV03) AddTransportDataSet() *iso20022.TransportDataSet3 { f.TransportDataSet = new(iso20022.TransportDataSet3) return f.TransportDataSet } func (f *ForwardDataSetSubmissionReportV03) AddInsuranceDataSet() *iso20022.InsuranceDataSet1 { f.InsuranceDataSet = new(iso20022.InsuranceDataSet1) return f.InsuranceDataSet } func (f *ForwardDataSetSubmissionReportV03) AddCertificateDataSet() *iso20022.CertificateDataSet1 { newValue := new(iso20022.CertificateDataSet1) f.CertificateDataSet = append(f.CertificateDataSet, newValue) return newValue } func (f *ForwardDataSetSubmissionReportV03) AddOtherCertificateDataSet() *iso20022.OtherCertificateDataSet1 { newValue := new(iso20022.OtherCertificateDataSet1) f.OtherCertificateDataSet = append(f.OtherCertificateDataSet, newValue) return newValue } func (f *ForwardDataSetSubmissionReportV03) AddRequestForAction() *iso20022.PendingActivity2 { f.RequestForAction = new(iso20022.PendingActivity2) return f.RequestForAction }
package models import ( "github.com/libvirt/libvirt-go" ) var libvirtConn *libvirt.Connect func InitLibvirt(uri string) (*libvirt.Connect, error) { conn, err := libvirt.NewConnect(uri) if err != nil { return nil, err } libvirtConn = conn return conn, nil }
package main import ( "flag" "fmt" "log" "net/http" "gophercises/url_shortener/urlshort" "github.com/boltdb/bolt" ) func defaultMux() *http.ServeMux { mux := http.NewServeMux() mux.HandleFunc("/", hello) return mux } func hello(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, world!") } func main() { var flagReadFromFormat string flag.StringVar(&flagReadFromFormat, "redirect-rules", "db", "Where to read redirect rules from (json / yaml / db).") flag.Parse() mux := defaultMux() // Build the MapHandler using the mux as the fallback pathsToUrls := make(map[string]string) mapHandler := urlshort.MapHandler(pathsToUrls, mux) switch flagReadFromFormat { case "json": jsonHandler, err := urlshort.JSONHandler(mapHandler) if err != nil { panic(err) } fmt.Println("Starting the server on :8080") log.Fatal(http.ListenAndServe(":8080", jsonHandler)) case "yaml": yamlHandler, err := urlshort.YAMLHandler(mapHandler) if err != nil { panic(err) } fmt.Println("Starting the server on :8080") log.Fatal(http.ListenAndServe(":8080", yamlHandler)) case "db": db, err := bolt.Open("./redirect_rules/redirect.db", 0600, nil) if err != nil { log.Fatal(err) } defer func() { if err := db.Close(); err != nil { panic(err) } }() boltHandler, err := urlshort.BoltHandler(db, mapHandler) if err != nil { panic(err) } fmt.Println("Starting the server on :8080") log.Fatal(http.ListenAndServe(":8080", boltHandler)) default: fmt.Println("Starting the server on :8080") log.Fatal(http.ListenAndServe(":8080", mapHandler)) } }
package jarvisbot_test import "testing" func TestParseArgs(t *testing.T) { // TODO: Need to figure out how to mock the bot object //j := &jarvisbot.JarvisBot{keys: map[string]string{"open_exchange_api_key": ""}} //res, err := j.RetrieveExchangeRates() //ok(t, err) //assert(t, res.UnixTimestamp != 0, "Exchange rate timestamp should not be empty.") //assert(t, res.Base != "", "Exchange rate base should not be empty.") //assert(t, res.Rates != nil, "Exchange rates should not be empty.") }
package presenters import ( "fmt" "net/url" "time" "github.com/messagedb/messagedb/meta/schema" ) // Organization is a presenter for the schema.Organization model type Organization struct { ID string `json:"id"` Name string `json:"name"` Description string `json:"description"` URL string `json:"url"` Location string `json:"location"` Email string `json:"email"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` Namespace struct { ID string `json:"id,omitempty"` Path string `json:"path,omitempty"` OwnerType string `json:"owner_type"` } `json:"namespace,omitempty"` } // GetLocation returns the API location for the organization resource func (o *Organization) GetLocation() *url.URL { uri, err := url.Parse(fmt.Sprintf("/orgs/%s", o.ID)) if err != nil { return nil } return uri } // OrganizationPresenter creates a new instance of the presenter for the Organization model func OrganizationPresenter(o *schema.Organization) *Organization { org := &Organization{} org.ID = o.ID.Hex() org.Name = o.Name org.Description = o.Description org.URL = o.URL org.Location = o.Location org.Email = o.Email org.CreatedAt = o.CreatedAt org.UpdatedAt = o.UpdatedAt org.Namespace.ID = o.Namespace.ID.Hex() org.Namespace.Path = o.Namespace.Path return org } // OrganizationCollectionPresenter creates an array of presenters for the Organization model func OrganizationCollectionPresenter(items []*schema.Organization) []*Organization { var collection []*Organization for _, item := range items { collection = append(collection, OrganizationPresenter(item)) } return collection }
// Copyright 2020 Torben Schinke // // 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 // // https://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 modal import ( "github.com/golangee/dom" "strconv" . "github.com/golangee/gotrino" . "github.com/golangee/gotrino-html" ) // An Overlay should be added to the body element and takes over the entire screen. It is fully transparent // and allows to place multiple Renderable at arbitrary absolute positions. I know Popper // (https://github.com/popperjs/popper-core#why-popper) but it is really hard to integrate into our lifecycle // and I was not able to get it working in a reasonable time, so we drive our own implementation. type Overlay struct { View items []*overlayLayoutParams clickListeners []func() } func NewOverlay() *Overlay { c := &Overlay{} c.Observe(func() { c.alignOverlay() }) return c } func (c *Overlay) AddClickListener(f func()) *Overlay { c.clickListeners = append(c.clickListeners, f) return c } func (c *Overlay) Put(id string, content Renderable) *Overlay { c.items = append(c.items, &overlayLayoutParams{ domId: id, content: content, }) c.Invalidate() return c } func (c *Overlay) alignOverlay() { for _, item := range c.items { target := dom.GetDocument().GetElementById(item.domId) if !target.IsNull() && item.overlayElem != nil { overlayRect := item.overlayElem.GetBoundingClientRect() targetRect := target.GetBoundingClientRect() wndWidth := dom.GetWindow().InnerWidth() scrollbars := 4 wantedLeft := targetRect.GetLeft() if overlayRect.GetWidth()+wantedLeft > wndWidth { wantedLeft = wndWidth - overlayRect.GetWidth() - scrollbars } if overlayRect.GetWidth() > wndWidth { overlayRect.SetWidth(wndWidth - scrollbars) } item.overlayElem.Style().SetProperty("left", strconv.Itoa(wantedLeft)+"px") item.overlayElem.Style().SetProperty("top", strconv.Itoa(targetRect.GetBottom())+"px") } } } func (c *Overlay) Render() Node { return Div(Class("absolute inset-0"), AddClickListener(func() { for _, listener := range c.clickListeners { listener() } }), ForEach(len(c.items), func(i int) Renderable { lp := c.items[i] return With(lp.content, Style("position", "absolute"), InsideDom(func(e dom.Element) { lp.overlayElem = &e c.alignOverlay() })) }), ) } type overlayLayoutParams struct { domId string content Renderable overlayElem *dom.Element } // ShowOverlay displays the overlay in the body element and removes it when clicked. func ShowOverlay(overlay *Overlay) { body := dom.GetWindow().Document().Body() // ease-in-out transition-all opacity-0 duration-200? resizeListener := dom.GetWindow().AddEventListener("resize", overlay.alignOverlay) WithElement(body, overlay).Element() overlayElem := body.LastChild() overlay.AddClickListener(func() { overlayElem.Remove() resizeListener.Release() }) dom.Post(overlay.alignOverlay) // wait a dom render cycle, don't know if this is a good idea. }
package data type SMSResult struct { Result uint `json:"result"` Errmsg string `json:"errmsg"` Ext string `json:"ext"` Sid string `json:"sid,omitempty"` Fee uint `json:"fee,omitempty"` }
/* * Go Library (C) 2017 Inc. * * @project Project Globo / avaliacao.com * @author @jeffotoni * @size 01/03/2018 */ package handler var ( CTYPE_ACCEPT = "application/json" msgJson string )
package chart type ChartDataOutput struct { Title string Items []*ChartDataOutputItem } type ChartDataOutputItem struct { Name string Data [][2]float64 } type ChartDataOutputItemsSorter [][2]float64 func (c ChartDataOutputItemsSorter) Len() int { return len(c) } func (c ChartDataOutputItemsSorter) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c ChartDataOutputItemsSorter) Less(i, j int) bool { return c[i][0] < c[j][0] }
package main import ( "fmt" "log" "github.com/saylorsolutions/passlock" ) // GenericDataStructure is an example data structure that holds an encrypted payload with a string identifier to allow // application code to reference the encrypted data. // The data structure can be safely transferred over an insecure network after construction with NewDataStructure. type GenericDataStructure struct { Identifier string // Identifier is a string used to relate to the encrypted data. secret []byte // secret holds the encrypted data for later decryption. } // NewDataStructure creates a new GenericDataStructure with the identifier. func NewDataStructure(identifier string) *GenericDataStructure { return &GenericDataStructure{ Identifier: identifier, } } // SetSecret uses the provided password and secret data to encrypt and set the internal value of the structure. If the // password or data is invalid, or if an error occurs during encryption, then err will be non-nil. func (ds *GenericDataStructure) SetSecret(password, secret []byte) error { encryptedData, err := passlock.EncryptBytes(password, secret) if err != nil { return err } ds.secret = encryptedData return nil } // GetSecret uses the provided password to decrypt the internal value of the structure and return the decrypted value. // If the data can not be verified due to an incorrect password or if the data has been tampered with then a non-nil // error will be returned. func (ds *GenericDataStructure) GetSecret(password []byte) (decryptedData []byte, err error) { if ds.secret == nil || len(ds.secret) == 0 { return []byte{}, nil } decryptedData, err = passlock.DecryptBytes(password, ds.secret) return decryptedData, err } func main() { password := []byte("Pa$$w0rd") data := NewDataStructure("ID 1234") fmt.Println("Encrypting secret data...") err := data.SetSecret(password, []byte("Encrypt this")) if err != nil { log.Fatalf("Failed to encrypt data: %v\n", err) } fmt.Println("Data structure secret set with encrypted data") /* ... Some logic to pass the data structure around ... */ fmt.Println("Decrypting data...") secret, err := data.GetSecret(password) if err != nil { log.Fatalf("Failed to decrypt data: %v\n", err) } fmt.Printf("The decrypted secret is '%s'\n", string(secret)) }
package types import "github.com/babyboy/common" type HashArray struct { Hashes []common.Hash } func NewHashArray() HashArray { return HashArray{} }
package util import ( "context" "database/sql" "fmt" "strings" "github.com/elgris/sqrl" "github.com/alewgbl/fdwctl/internal/database" "github.com/alewgbl/fdwctl/internal/logger" "github.com/alewgbl/fdwctl/internal/model" ) const ( // usermapSQLPrefix is the WITH clause used as a prefix on the SQL statement to retrieve usermaps from the DB usermapSQLPrefix = `WITH remoteuser AS (SELECT authorization_identifier, foreign_server_name, option_value AS remoteuser FROM information_schema.user_mapping_options WHERE option_name = 'user'), remotepassword AS (SELECT authorization_identifier, foreign_server_name, option_value AS remotepassword FROM information_schema.user_mapping_options WHERE option_name = 'password')` ) func FindUserMap(usermaps []model.UserMap, localuser string) *model.UserMap { for _, usermap := range usermaps { if usermap.LocalUser == localuser { return &usermap } } return nil } func GetUserMapsForServer(ctx context.Context, dbConnection *sql.DB, foreignServer string) ([]model.UserMap, error) { log := logger.Log(ctx). WithField("function", "GetUserMapsForServer") qbuilder := sqrl. Select("ru.authorization_identifier", "ru.remoteuser", "rp.remotepassword", "ru.foreign_server_name"). From("remoteuser ru"). Join("remotepassword rp ON ru.authorization_identifier = rp.authorization_identifier AND ru.foreign_server_name = rp.foreign_server_name") qbuilder.Prefix(usermapSQLPrefix) if foreignServer != "" { qbuilder = qbuilder.Where(sqrl.Eq{"ru.foreign_server_name": foreignServer}) } query, qArgs, err := qbuilder. PlaceholderFormat(sqrl.Dollar). ToSql() if err != nil { log.Errorf("error creating query: %s", err) return nil, err } log.Tracef("query: %s, args: %#v", query, qArgs) userRows, err := dbConnection.Query(query, qArgs...) if err != nil { log.Errorf("error getting users for server: %s", err) return nil, err } defer database.CloseRows(ctx, userRows) users := make([]model.UserMap, 0) for userRows.Next() { user := new(model.UserMap) user.RemoteSecret = model.Secret{} err = userRows.Scan(&user.LocalUser, &user.RemoteUser, &user.RemoteSecret.Value, &user.ServerName) if err != nil { log.Errorf("error scanning result row: %s", err) continue } users = append(users, *user) } if userRows.Err() != nil { log.Errorf("error iterating result rows: %s", userRows.Err()) return nil, userRows.Err() } return users, nil } func DiffUserMaps(dStateUserMaps []model.UserMap, dbUserMaps []model.UserMap) (umRemove []model.UserMap, umAdd []model.UserMap, umModify []model.UserMap) { // Init return variables umRemove = make([]model.UserMap, 0) umAdd = make([]model.UserMap, 0) umModify = make([]model.UserMap, 0) // umRemove for _, dbUserMap := range dbUserMaps { if FindUserMap(dStateUserMaps, dbUserMap.LocalUser) == nil { umRemove = append(umRemove, dbUserMap) } } // umAdd + umModify for _, dStateUserMap := range dStateUserMaps { if FindUserMap(dbUserMaps, dStateUserMap.LocalUser) == nil { umAdd = append(umAdd, dStateUserMap) } else { umModify = append(umModify, dStateUserMap) } } return } func DropUserMap(ctx context.Context, dbConnection *sql.DB, usermap model.UserMap, dropLocalUser bool) error { log := logger.Log(ctx). WithField("function", "DropUserMap") if usermap.ServerName == "" { return logger.ErrorfAsError(log, "server name is required") } query := fmt.Sprintf("DROP USER MAPPING IF EXISTS FOR %s SERVER %s", usermap.LocalUser, usermap.ServerName) log.Tracef("query: %s", query) _, err := dbConnection.Exec(query) if err != nil { log.Errorf("error dropping user mapping: %s", err) return err } if dropLocalUser { err = DropUser(ctx, dbConnection, usermap.LocalUser) if err != nil { log.Errorf("error dropping local user %s: %s", usermap.LocalUser, err) return err } log.Infof("user %s dropped", usermap.LocalUser) } return nil } func CreateUserMap(ctx context.Context, dbConnection *sql.DB, usermap model.UserMap) error { var secretValue string var err error log := logger.Log(ctx). WithField("function", "CreateUserMap") if usermap.ServerName == "" { return logger.ErrorfAsError(log, "server name is required") } // Check if the secret is defined before resolving it if SecretIsDefined(usermap.RemoteSecret) { secretValue, err = GetSecret(ctx, usermap.RemoteSecret) if err != nil { return logger.ErrorfAsError(log, "error getting secret value: %s", err) } } else { secretValue = "" } // FIXME: There could be no password at all; check for a password before using it in the SQL statement query := fmt.Sprintf("CREATE USER MAPPING FOR %s SERVER %s OPTIONS (user '%s', password '%s')", usermap.LocalUser, usermap.ServerName, usermap.RemoteUser, secretValue) log.Tracef("query: %s", query) _, err = dbConnection.Exec(query) if err != nil { log.Errorf("error creating user mapping: %s", err) return err } return nil } func UpdateUserMap(ctx context.Context, dbConnection *sql.DB, usermap model.UserMap) error { log := logger.Log(ctx). WithField("function", "UpdateUserMap") if usermap.ServerName == "" { return logger.ErrorfAsError(log, "server name is required") } optArgs := make([]string, 0) query := fmt.Sprintf("ALTER USER MAPPING FOR %s SERVER %s OPTIONS (", usermap.LocalUser, usermap.ServerName) if usermap.RemoteUser != "" { optArgs = append(optArgs, fmt.Sprintf("SET user '%s'", usermap.RemoteUser)) } if SecretIsDefined(usermap.RemoteSecret) { secretValue, err := GetSecret(ctx, usermap.RemoteSecret) if err != nil { return logger.ErrorfAsError(log, "error getting secret value: %s", err) } optArgs = append(optArgs, fmt.Sprintf("SET password '%s'", secretValue)) } query = fmt.Sprintf("%s %s )", query, strings.Join(optArgs, ", ")) log.Tracef("query: %s", query) _, err := dbConnection.Exec(query) if err != nil { log.Errorf("error editing user mapping: %s", err) return err } return nil }
package config import ( "database/sql" "fmt" "log" "os" "github.com/joho/godotenv" _ "github.com/lib/pq" ) func CreateConnection() *sql.DB { //load .env file err := godotenv.Load(".env") if err != nil { log.Fatalf("Error loading .env file") } // buka koneksi ke db db, err := sql.Open("postgres", os.Getenv("POSTGRES_URL")) if err != nil { panic(err) } // cek koneksi err = db.Ping() if err != nil { panic(err) } fmt.Println("Sukes connect ke db!") // return connection return db }