text
stringlengths
11
4.05M
//go:build !go1.21 // +build !go1.21 package log import ( "bufio" "io" stdlog "log" "os" "strings" ) var ( stdLogWriter *io.PipeWriter redirectComplete chan struct{} ) // RedirectGoStdLog is used to redirect Go's internal std log output to this logger AND registers a handler for slog // that redirects slog output to this logger. func RedirectGoStdLog(redirect bool) { if (redirect && stdLogWriter != nil) || (!redirect && stdLogWriter == nil) { // already redirected or already not redirected return } if !redirect { stdlog.SetOutput(os.Stderr) // will stop scanner reading PipeReader _ = stdLogWriter.Close() stdLogWriter = nil <-redirectComplete return } ready := make(chan struct{}) redirectComplete = make(chan struct{}) // last option is to redirect go func() { var r *io.PipeReader r, stdLogWriter = io.Pipe() defer func() { _ = r.Close() }() stdlog.SetOutput(stdLogWriter) defer func() { close(redirectComplete) redirectComplete = nil }() scanner := bufio.NewScanner(r) close(ready) for scanner.Scan() { txt := scanner.Text() if strings.Contains(txt, "error") { WithField("stdlog", true).Error(txt) } else if strings.Contains(txt, "warning") { WithField("stdlog", true).Warn(txt) } else { WithField("stdlog", true).Notice(txt) } } }() <-ready }
package ssvgc import ( "encoding/xml" "image" "image/draw" "io/ioutil" "log" "strconv" "github.com/golang/freetype" "github.com/golang/freetype/truetype" "golang.org/x/image/math/fixed" ) type Text struct { textContext chunks []*textChunk buf []byte } func NewText() *Text { t := &Text{} t.fillColor = image.Black t.strokeColor = image.Transparent t.fontSize = 12 t.textAnchor = "small" return t } func (t *Text) SetAttribute(name, value string) { switch name { case "font-size": t.fontSize, _ = strconv.ParseFloat(value, 64) case "ttf-font": t.ttfFont = value t.font = nil case "text-anchor": switch value { case "middle", "end": t.textAnchor = value } default: t.commonElement.SetAttribute(name, value) } t.upToDate = false } func (t *Text) ParseAttributes(start *xml.StartElement) { for _, attr := range start.Attr { t.SetAttribute(attr.Name.Local, attr.Value) } } func (t *Text) Draw() image.Image { if len(t.chunks) == 0 { return image.Transparent } if t.canvas != nil && t.upToDate { return t.canvas } width, height, maxFont := fixed.I(0), 0, 0.0 for _, chunk := range t.chunks { t.textContext = chunk.textContext t.font = t.loadFont(t.ttfFont) s := string(t.buf[chunk.startPos:chunk.endPos]) cWidth, _ := t.GetStringSize(s) width += cWidth cHeight := t.getMaxHeight() if cHeight > height { height = cHeight } if t.fontSize > maxFont { maxFont = t.fontSize } } t.textContext = t.chunks[0].textContext imgWidth := int(width >> 6) t.setDimensions(imgWidth, height) startX := 0 switch t.textAnchor { case "middle": startX -= imgWidth >> 1 case "end": startX -= imgWidth } bounds := image.Rect(startX, -int(maxFont), imgWidth, height-int(maxFont)) log.Println(t.Bounds(), imgWidth, startX, bounds) img := image.NewRGBA(bounds) draw.Draw(img, bounds, image.Transparent, image.ZP, draw.Src) ctx := freetype.NewContext() ctx.SetDst(img) ctx.SetClip(bounds) pt := freetype.Pt(startX, 0) t.font = t.loadFont(t.ttfFont) for _, chunk := range t.chunks { ctx.SetFont(t.font) ctx.SetFontSize(chunk.fontSize) ctx.SetSrc(&image.Uniform{chunk.fillColor}) pt, _ = ctx.DrawString(string(t.buf[chunk.startPos:chunk.endPos]), pt) } return img } func (t *Text) GetStringSize(s string) (fixed.Int26_6, fixed.Int26_6) { // Assumes 72 DPI fupe := fixed.Int26_6(t.fontSize * 64.0) width := fixed.I(0) prev, hasPrev := t.font.Index(0), false for _, r := range s { idx := t.font.Index(r) if hasPrev { width += t.font.Kerning(fupe, prev, idx) } width += t.font.HMetric(fupe, idx).AdvanceWidth prev, hasPrev = idx, true } fontBounds := t.font.Bounds(fupe) return width, (fontBounds.YMax - fontBounds.YMin) } func (t *Text) loadFont(path string) *truetype.Font { if t.font != nil { return t.font } ttfBytes, err := ioutil.ReadFile(t.ttfFont) if err != nil { log.Fatal(err) } font, err := freetype.ParseFont(ttfBytes) if err != nil { log.Fatal(err) } return font } func (t *Text) getMaxHeight() int { w, h := t.GetStringSize("|") bounds := image.Rect(0, 0, int(w>>6), int(h>>6)) img := image.NewRGBA(bounds) ctx := freetype.NewContext() ctx.SetFont(t.font) ctx.SetFontSize(t.fontSize) ctx.SetSrc(&image.Uniform{t.fillColor}) ctx.SetDst(img) ctx.SetClip(bounds) ctx.DrawString("|", freetype.Pt(0, int(t.fontSize))) var i = len(img.Pix) - 1 for ; img.Pix[i] == 0; i-- { } return (i / img.Stride) + 1 } type textContext struct { commonElement fontSize float64 ttfFont string textAnchor string font *truetype.Font } type textChunk struct { textContext startPos int endPos int }
// Copyright (c) 2015-2017 Marcus Rohrmoser, http://purl.mro.name/recorder // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES // OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // MIT License http://opensource.org/licenses/MIT package main import ( "fmt" // "log" // log.Fatal "os" "path/filepath" "regexp" ) func main() { if 1 >= len(os.Args) || "-?" == os.Args[1] || "--help" == os.Args[1] { commandHelp() return } for _, mp3FileName := range os.Args[1:] { fmt.Fprintf(os.Stderr, "tagging %s\n", mp3FileName) ap, err := filepath.Abs(mp3FileName) if nil != err { fmt.Fprintf(os.Stderr, "error %s\n", err) continue } bc, err := broadcastFromXmlFileName(xmlBroadcastFileNameForMp3EnclosureFileName(ap)) if nil != err { fmt.Fprintf(os.Stderr, "error %s\n", err) continue } err = tagMp3File(ap, bc) if nil != err { fmt.Fprintf(os.Stderr, "error %s\n", err) continue } } } func commandHelp() { program := os.Args[0] fmt.Printf("Usage: %s enclosure0.mp3 enclosure1.mp3 enclosure2.mp3\n", program) fmt.Printf("\n") fmt.Printf("tags the given enclosures with meta data from it's broadcast file (xml).\n") } func identifierForMp3EnclosureFileName(mp3FileName string) string { rx := regexp.MustCompile("[^/]+/\\d{4}/\\d{2}/\\d{2}/\\d{4}(?: .+)?\\.mp3$") return rx.FindString(mp3FileName) } func xmlBroadcastFileNameForMp3EnclosureFileName(mp3FileName string) string { rx := regexp.MustCompile("^(.*)/enclosures/([^/]+/\\d{4}/\\d{2}/\\d{2}/\\d{4}(?: .+)?)\\.mp3$") ret := rx.ReplaceAllString(mp3FileName, "$1/stations/$2.xml") if ret == mp3FileName { return "" } return ret }
package silverfish import ( "errors" "strconv" "time" entity "silverfish/silverfish/entity" "gopkg.in/mgo.v2/bson" ) // User export type User struct { userInf *entity.MongoInf } // NewUser export func NewUser(userInf *entity.MongoInf) *User { u := new(User) u.userInf = userInf return u } // GetUser export func (u *User) GetUser(account *string) (*entity.User, error) { result, err := u.userInf.FindOne(bson.M{"account": *account}, &entity.User{}) if err != nil { if err.Error() == "not found" { return nil, errors.New("Account not exists") } return nil, err } return result.(*entity.User), nil } // GetUserBookmark export func (u *User) GetUserBookmark(account *string) (*entity.Bookmark, error) { result, err := u.userInf.FindOne(bson.M{"account": account}, &entity.User{}) if err != nil { return nil, errors.New("Account not exists") } return result.(*entity.User).Bookmark, nil } // UpdateBookmark export func (u *User) UpdateBookmark(bookType string, bookID, account, indexStr *string) { index, err := strconv.Atoi(*indexStr) if err != nil { return } result, err2 := u.userInf.FindOne(bson.M{"account": *account}, &entity.User{}) if err2 == nil { user := result.(*entity.User) if bookType == "Novel" { if val, ok := user.Bookmark.Novel[*bookID]; ok { val.LastReadIndex = index val.LastReadDatetime = time.Now() user.Bookmark.Novel[*bookID] = val } else { user.Bookmark.Novel[*bookID] = &entity.BookmarkEntry{ Type: bookType, ID: *bookID, LastReadIndex: index, LastReadDatetime: time.Now(), } } } else { if val, ok := user.Bookmark.Comic[*bookID]; ok { val.LastReadIndex = index val.LastReadDatetime = time.Now() user.Bookmark.Comic[*bookID] = val } else { user.Bookmark.Comic[*bookID] = &entity.BookmarkEntry{ Type: bookType, ID: *bookID, LastReadIndex: index, LastReadDatetime: time.Now(), } } } u.userInf.Upsert(bson.M{"account": *account}, user) } }
package io import ( "consumer-importer/io/util" "consumer-importer/model" "errors" "strconv" "strings" "time" ) //IsHeader checks if the line is a header type func IsHeader(line string) bool { return len(line) == util.HeaderSize } //Format format a string line of the imported file to a Consumer object func Format(line string) model.Consumer { row := formatFile(line) return toConsumer(row) } func formatFile(row string) util.FileRow { return util.FileRow{ CPF: row[:util.CPFEnd], Private: row[util.CPFEnd:util.PrivateEnd], Incompleto: row[util.PrivateEnd:util.IncompletoEnd], DataUltimaCompra: row[util.IncompletoEnd:util.DataUltimaCompraEnd], TicketMedio: row[util.DataUltimaCompraEnd:util.TicketMedioEnd], TicketUltimaCompra: row[util.TicketMedioEnd:util.TicketUltimaCompraEnd], LojaMaisFrequente: row[util.TicketUltimaCompraEnd:util.LojaMaisFrequenteEnd], LojaUltimaCompra: row[util.LojaMaisFrequenteEnd:], } } func toConsumer(row util.FileRow) model.Consumer { private, err := parseBoolean(row.Private) if err != nil { panic(err) } incompleto, err := parseBoolean(row.Incompleto) if err != nil { panic(err) } return model.Consumer{ CPF: parseString(row.CPF), Private: private, Incompleto: incompleto, DataUltimaCompra: parseDate(row.DataUltimaCompra), TicketMedio: parseFloat(row.TicketMedio), TicketUltimaCompra: parseFloat(row.TicketUltimaCompra), LojaMaisFrequente: parseString(row.LojaMaisFrequente), LojaUltimaCompra: parseString(row.LojaUltimaCompra), } } func parseString(str string) *string { cleanedStr := util.CleanUpString(str) if strings.ToLower(cleanedStr) == "null" { return nil } removedDots := strings.ReplaceAll(cleanedStr, ".", "") removedDashes := strings.ReplaceAll(removedDots, "-", "") finalStr := strings.ReplaceAll(removedDashes, "/", "") return &finalStr } func parseBoolean(str string) (bool, error) { cleanedStr := util.CleanUpString(str) if cleanedStr == "1" { return true, nil } else if cleanedStr == "0" { return false, nil } return false, errors.New("invalid boolean type") } func parseDate(str string) *time.Time { cleanedStr := util.CleanUpString(str) if strings.ToLower(cleanedStr) == "null" { return nil } time, _ := time.Parse("2006-01-02", cleanedStr) return &time } func parseFloat(str string) *float64 { floatStr := strings.ReplaceAll(util.CleanUpString(str), ",", ".") if strings.ToLower(floatStr) == "null" { return nil } converted, _ := strconv.ParseFloat(floatStr, 64) return &converted }
package dict import ( "context" "fmt" "testing" ) func TestBing_Search(t *testing.T) { bing := Bing{} word, err := bing.Search(context.Background(), "hello") if err != nil { t.Fatal(err) } fmt.Println(word) }
package models import ( "github.com/astaxie/beego/orm" "time" ) //查询的类 type RoleBlackListQueryParam struct { BaseQueryParam Phone string `json:"phone"` //手机号 模糊查询 //发布时间 StartTime int64 `json:"startTime"` //开始时间 EndTime int64 `json:"endTime"` //截止时间 } func (a *RoleBlackList) TableName() string { return RoleBlackListTBName() } //角色黑名单 type RoleBlackList struct { Id int `orm:"pk;column(id)"json:"id"form:"id"` //手机号 Phone string `orm:"column(phone)"json:"phone"form:"phone"` //黑名单类型 BalckType int `orm:"column(balck_type)"json:"balckType"form:"balckType"` //开始时间 StartTime time.Time `orm:"auto_now_add;type(datetime);column(start_time)"json:"startTime"form:"startTime"` //结束时间 EndTime time.Time `orm:"type(datetime);column(end_time)"json:"endTime"form:"endTime"` //持续时间 PeriodTime int64 `orm:"column(period_time)"json:"periodTime"form:"periodTime"` //用户Uid 连表用户 一对多关系 User *TokenskyUser `orm:"rel(fk)"json:"-"form:"-"` //用户uid UserId int `orm:"-"json:"userId"form:"-"` //昵称 NickName string `orm:"-"json:"nickName"form:"-"` } // OtcEntrustOrderPageList 获取分页数据 func RoleBlackListPageList(params *RoleBlackListQueryParam) ([]*RoleBlackList, int64) { o := orm.NewOrm() query := o.QueryTable(RoleBlackListTBName()) data := make([]*RoleBlackList, 0) //默认排序 sortorder := "id" switch params.Sort { case "id": sortorder = "id" } if params.Order == "desc" { sortorder = "-" + sortorder } //手机号模糊查询 起始位置开始 if params.Phone != "" { query = query.Filter("phone__istartswith", params.Phone) } total, _ := query.Count() query.OrderBy(sortorder).Limit(params.Limit, (params.Offset-1)*params.Limit).RelatedSel().All(&data) //数据处理 for _, obj := range data { //if obj.User != nil{ obj.UserId = obj.User.UserId obj.NickName = obj.User.NickName //} } return data, total } // RoleBlackListOneById 根据id获取单条 func RoleBlackListOneById(id int) (*RoleBlackList, error) { o := orm.NewOrm() m := RoleBlackList{Id: id} err := o.Read(&m) if err != nil { return nil, err } return &m, nil } // RoleBlackListDelete 批量删除 func RoleBlackListDelete(ids []int) (int64, error) { query :=orm.NewOrm().QueryTable(RoleBlackListTBName()) num, err := query.Filter("id__in", ids).Delete() return num, err }
package main // import "github.com/kidoda/quikalarm" import ( _ "errors" "time" _ "github.com/faiface/beep" _ "github.com/faiface/beep/speaker" _ "github.com/faiface/beep/wav" ) var ( now = time.Now() // A global now just for reference alarmSound = loadBuzzer() // TODO: Git rid of this global and call locally in an alarm field. mainClock = NewClock() ) // clock is the time keeping part of an alarm. type clock struct { startTime time.Time currentTimeChan func() <-chan string { ch := make(chan string, 1) } currentTime time.Time } func (a *alarm) SetWakeTime(newWakeTime time.Time) { if after := a.currentTime } func (a alarm) GetWakeTime() string { return a.wakeTime.String() } // alarm is the complete object with time, buzzer, and wake time. type alarm struct { clock *clock wakeTime time.Time alarmSound buzzer } // TODO: Need to rethink this approach, combine creations? func NewAlarm() *alarm { anAlarm := &alarm{ clock: NewClock(), alarmSound: loadBuzzer(), } return anAlarm } // NewClock instantiates a new clock with current time values and returns a pointer func NewClock() *clock { clock := &clock{ startTime: time.Now(), ticker: time.NewTicker(time.Second * 1), } go func() { for t := range clock.ticker.C { clock.currentTimeString = t.String() } }() return clock }
package client import ( "io/ioutil" "path/filepath" "strings" "github.com/herb-go/herbgo/util/config/tomlconfig" "github.com/herb-go/herbgo/util" ) //ModuleName module name const ModuleName = "900services.client" var WorldsPath string func MustLoadWorlds() { files, err := ioutil.ReadDir(WorldsPath) if err != nil { panic(err) } for _, f := range files { filename := f.Name() if strings.HasSuffix(filename, ".toml") { id := filename[:len(filename)-5] world := NewWorld() tomlconfig.MustLoad(filepath.Join(WorldsPath, filename), world) client := DefaultManager.NewClient(id, world) client.Script.Triggers.LoadWorldTrigger(world.Triggers) } } } func init() { util.RegisterModule(ModuleName, func() { //Init registered initator which registered by RegisterInitiator //util.RegisterInitiator(ModuleName, "func", func()error{}) util.InitOrderByName(ModuleName) WorldsPath = util.RegisterDataFolder("worlds") MustLoadWorlds() }) }
package cors import ( "github.com/Highway-Project/highway/pkg/middlewares" "net/http" "strconv" "strings" ) type CORSMiddleware struct { // AllowOrigin defines a list of origins that may access the resource. // Optional. Default value []string{"*"}. AllowOrigins []string // AllowMethods defines a list methods allowed when accessing the resource. // This is used in response to a preflight request. // Optional. Default value DefaultCORSConfig.AllowMethods. AllowMethods []string // AllowHeaders defines a list of request headers that can be used when // making the actual request. This is in response to a preflight request. // Optional. Default value []string{}. AllowHeaders []string // AllowCredentials indicates whether or not the response to the request // can be exposed when the credentials flag is true. When used as part of // a response to a preflight request, this indicates whether or not the // actual request can be made using credentials. // Optional. Default value false. AllowCredentials bool // ExposeHeaders defines a whitelist headers that clients are allowed to // access. // Optional. Default value []string{}. ExposeHeaders []string // MaxAge indicates how long (in seconds) the results of a preflight request // can be cached. // Optional. Default value 0. MaxAge int } const ( HeaderVary = "Vary" HeaderOrigin = "Origin" HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" ) const ( AllowOrigins = "allowOrigins" AllowMethods = "allowMethods" AllowHeaders = "allowHeaders" AllowCredentials = "allowCredentials" ExposeHeaders = "exposeHeaders" MaxAge = "maxAge" ) var ( // DefaultCORSConfig is the default CORS middleware config. DefaultCORSParams = map[string][]string{ AllowOrigins: {"*"}, AllowMethods: {http.MethodGet, http.MethodHead, http.MethodPut, http.MethodPatch, http.MethodPost, http.MethodDelete}, } ) func New(params middlewares.MiddlewareParams) (middlewares.Middleware, error) { allowOrigins, exists, err := params.GetStringList(AllowOrigins) if err != nil { return CORSMiddleware{}, err } if !exists { allowOrigins = DefaultCORSParams[AllowOrigins] } allowMethods, exists, err := params.GetStringList(AllowMethods) if err != nil { return CORSMiddleware{}, err } if !exists { allowMethods = DefaultCORSParams[AllowMethods] } allowHeaders, _, err := params.GetStringList(AllowHeaders) if err != nil { return CORSMiddleware{}, err } allowCredentials, _, err := params.GetBool(AllowCredentials) if err != nil { return CORSMiddleware{}, err } exposeHeaders, _, err := params.GetStringList(ExposeHeaders) if err != nil { return CORSMiddleware{}, err } maxAge, _, err := params.GetInt(MaxAge) if err != nil { return CORSMiddleware{}, err } mw := CORSMiddleware{ AllowOrigins: allowOrigins, AllowMethods: allowMethods, AllowHeaders: allowHeaders, AllowCredentials: allowCredentials, ExposeHeaders: exposeHeaders, MaxAge: maxAge, } return mw, nil } func (c CORSMiddleware) Process(handler http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { origin := r.Header.Get(HeaderOrigin) allowOrigin := "" allowMethods := strings.Join(c.AllowMethods, ",") allowHeaders := strings.Join(c.AllowHeaders, ",") exposeHeaders := strings.Join(c.ExposeHeaders, ",") maxAge := strconv.Itoa(c.MaxAge) for _, o := range c.AllowOrigins { if o == "*" && c.AllowCredentials { allowOrigin = origin break } if o == "*" || o == origin { allowOrigin = o break } if c.matchSubdomain(origin, o) { allowOrigin = origin break } } // Simple request if r.Method != http.MethodOptions { w.Header().Add(HeaderVary, HeaderOrigin) w.Header().Set(HeaderAccessControlAllowOrigin, allowOrigin) if c.AllowCredentials { w.Header().Set(HeaderAccessControlAllowCredentials, "true") } if len(c.ExposeHeaders) > 0 { w.Header().Set(HeaderAccessControlExposeHeaders, exposeHeaders) } handler(w, r) return } // Preflight request w.Header().Add(HeaderVary, HeaderOrigin) w.Header().Add(HeaderVary, HeaderAccessControlRequestMethod) w.Header().Add(HeaderVary, HeaderAccessControlRequestHeaders) w.Header().Set(HeaderAccessControlAllowOrigin, allowOrigin) w.Header().Set(HeaderAccessControlAllowMethods, allowMethods) if c.AllowCredentials { w.Header().Set(HeaderAccessControlAllowCredentials, "true") } if len(c.AllowHeaders) > 0 { w.Header().Set(HeaderAccessControlAllowHeaders, allowHeaders) } else { h := r.Header.Get(HeaderAccessControlRequestHeaders) if h != "" { w.Header().Set(HeaderAccessControlAllowHeaders, h) } } if c.MaxAge > 0 { w.Header().Set(HeaderAccessControlMaxAge, maxAge) } handler(w, r) } } func (c CORSMiddleware) matchScheme(domain, pattern string) bool { didx := strings.Index(domain, ":") pidx := strings.Index(pattern, ":") return didx != -1 && pidx != -1 && domain[:didx] == pattern[:pidx] } // matchSubdomain compares authority with wildcard func (c CORSMiddleware) matchSubdomain(domain, pattern string) bool { if !c.matchScheme(domain, pattern) { return false } didx := strings.Index(domain, "://") pidx := strings.Index(pattern, "://") if didx == -1 || pidx == -1 { return false } domAuth := domain[didx+3:] // to avoid long loop by invalid long domain if len(domAuth) > 253 { return false } patAuth := pattern[pidx+3:] domComp := strings.Split(domAuth, ".") patComp := strings.Split(patAuth, ".") for i := len(domComp)/2 - 1; i >= 0; i-- { opp := len(domComp) - 1 - i domComp[i], domComp[opp] = domComp[opp], domComp[i] } for i := len(patComp)/2 - 1; i >= 0; i-- { opp := len(patComp) - 1 - i patComp[i], patComp[opp] = patComp[opp], patComp[i] } for i, v := range domComp { if len(patComp) <= i { return false } p := patComp[i] if p == "*" { return true } if p != v { return false } } return false }
package test_helpers import ( "fmt" "github.com/go-martini/martini" . "github.com/onsi/gomega" "net/http" "net/url" ) var ( GLOBAL_SERVER_URL *url.URL Router *martini.ClassicMartini ) func CloneHeaders(headers http.Header) http.Header { header_cloned := make(http.Header) for k, v := range headers { header_cloned[k] = v } return header_cloned } func MakeUrl( server_url *url.URL, urlName string, url_params []string, query_params map[string]string, ) ( *url.URL, error, ) { // Get url from routing params := make([]interface{}, 0) for _, url_param := range url_params { params = append(params, url_param) } url := Router.URLFor(urlName, params...) // Get currently serving httptest url_I := *server_url // Join it's address and path of a specific url url_I.Path = url q := url_I.Query() for k, v := range query_params { q.Set(k, v) } url_I.RawQuery = q.Encode() // End of url work return &url_I, nil } func GetHandler( session_id string, headers http.Header, project_id, handler string, ) ( request *Request, ) { header_cloned := CloneHeaders(headers) header_cloned.Set("Authorization", fmt.Sprintf("SessionId %s", session_id)) header_cloned.Set("X-Project", project_id) url, err := MakeUrl( GLOBAL_SERVER_URL, handler, []string{}, map[string]string{}, ) Expect(err).NotTo(HaveOccurred()) request = &Request{} err = request.Get( url.String(), header_cloned, ) Expect(err).NotTo(HaveOccurred()) return request }
package backends import ( "log" "github.com/liut/staffio/pkg/backends/ldap" "github.com/liut/staffio/pkg/common" "github.com/liut/staffio/pkg/models" "github.com/liut/staffio/pkg/models/cas" "github.com/liut/staffio/pkg/models/weekly" "github.com/liut/staffio/pkg/settings" ) type Servicer interface { models.Authenticator models.StaffStore models.PasswordStore models.GroupStore cas.TicketStore OSIN() OSINStore Ready() error CloseAll() SaveStaff(staff *models.Staff) error InGroup(gn, uid string) bool ProfileModify(uid, password string, staff *models.Staff) error PasswordForgot(at common.AliasType, target, uid string) error PasswordResetTokenVerify(token string) (uid string, err error) PasswordResetWithToken(login, token, passwd string) (err error) Team() weekly.TeamStore Weekly() weekly.WeeklyStore } type serviceImpl struct { *ldap.LDAPStore osinStore *DbStorage teamStore *teamStore weeklyStore *weeklyStore } var _ Servicer = (*serviceImpl)(nil) func NewService() Servicer { ldap.Base = settings.LDAP.Base ldap.Domain = settings.EmailDomain cfg := &ldap.Config{ Addr: settings.LDAP.Hosts, Base: settings.LDAP.Base, Bind: settings.LDAP.BindDN, Passwd: settings.LDAP.Password, } store, err := ldap.NewStore(cfg) if err != nil { log.Fatalf("new service ERR %s", err) } // LDAP is a special store return &serviceImpl{ LDAPStore: store, osinStore: NewStorage(), teamStore: &teamStore{}, weeklyStore: &weeklyStore{}, } } func (s *serviceImpl) Ready() error { return s.LDAPStore.Ready() } func (s *serviceImpl) OSIN() OSINStore { return s.osinStore } func (s *serviceImpl) CloseAll() { s.LDAPStore.Close() s.osinStore.Close() } func (s *serviceImpl) Team() weekly.TeamStore { return s.teamStore } func (s *serviceImpl) Weekly() weekly.WeeklyStore { return s.weeklyStore }
/* * 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 dev_random import ( "bytes" log "github.com/sirupsen/logrus" "github.com/streamsets/datacollector-edge/api" "github.com/streamsets/datacollector-edge/api/validation" "github.com/streamsets/datacollector-edge/container/common" "github.com/streamsets/datacollector-edge/stages/lib/dataparser" "github.com/streamsets/datacollector-edge/stages/stagelibrary" ) const ( LIBRARY = "streamsets-datacollector-dev-lib" STAGE_NAME = "com_streamsets_pipeline_stage_devtest_rawdata_RawDataDSource" ) var randomOffset string = "random" type DevRawDataDSource struct { *common.BaseStage RawData string `ConfigDef:"type=STRING,required=true"` StopAfterFirstBatch bool `ConfigDef:"type=BOOLEAN,required=true"` DataFormat string `ConfigDef:"type=STRING,required=true"` DataFormatConfig dataparser.DataParserFormatConfig `ConfigDefBean:"dataFormatConfig"` } func init() { stagelibrary.SetCreator(LIBRARY, STAGE_NAME, func() api.Stage { return &DevRawDataDSource{BaseStage: &common.BaseStage{}} }) } func (d *DevRawDataDSource) Init(stageContext api.StageContext) []validation.Issue { issues := d.BaseStage.Init(stageContext) log.Debug("DevRawDataDSource Init method") d.DataFormatConfig.Init(d.DataFormat, stageContext, issues) return issues } func (d *DevRawDataDSource) Produce( lastSourceOffset string, maxBatchSize int, batchMaker api.BatchMaker, ) (*string, error) { var err error recordReaderFactory := d.DataFormatConfig.RecordReaderFactory recordBuffer := bytes.NewBufferString(d.RawData) recordReader, err := recordReaderFactory.CreateReader(d.GetStageContext(), recordBuffer) if err != nil { log.WithError(err).Error("Failed to create record reader") return nil, err } defer recordReader.Close() for { record, err := recordReader.ReadRecord() if err != nil { log.WithError(err).Error("Failed to parse raw data") return nil, err } if record == nil { break } batchMaker.AddRecord(record) } if d.StopAfterFirstBatch { return nil, err } return &randomOffset, err }
/* Copyright 2022 The KubeVela Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package component import ( "testing" "time" "github.com/stretchr/testify/assert" "k8s.io/utils/pointer" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/envtest" "github.com/oam-dev/kubevela/pkg/utils/common" ) func TestInfo(t *testing.T) { testEnv := &envtest.Environment{ ControlPlaneStartTimeout: time.Minute * 3, ControlPlaneStopTimeout: time.Minute, UseExistingCluster: pointer.Bool(false), } cfg, err := testEnv.Start() assert.NoError(t, err) k8sClient, err := client.New(cfg, client.Options{Scheme: common.Scheme}) assert.NoError(t, err) info := NewInfo(&themeConfig) info.Init(k8sClient, cfg) assert.Equal(t, info.GetColumnCount(), 7) assert.Equal(t, info.GetRowCount(), 6) assert.Equal(t, info.GetCell(0, 0).Text, "Context:") assert.Equal(t, info.GetCell(1, 0).Text, "K8S Version:") assert.Equal(t, info.GetCell(2, 0).Text, "VelaCLI Version:") assert.Equal(t, info.GetCell(3, 0).Text, "VelaCore Version:") assert.Equal(t, info.GetCell(0, 0).Color, themeConfig.Info.Title.Color()) assert.NoError(t, testEnv.Stop()) }
package main import ( "github.com/funkygao/gobench/util" "testing" ) func main() { b := testing.Benchmark(benchmarkStackAllocation) util.ShowBenchResult("stack alloc:", b) b = testing.Benchmark(benchmarkHeapAllocation) util.ShowBenchResult("heap alloc:", b) } func stackalloc() [128]int64 { return [128]int64{} } func heapalloc() *[128]int64 { return &[128]int64{} } func benchmarkStackAllocation(b *testing.B) { for i := 0; i < b.N; i++ { stackalloc() } } func benchmarkHeapAllocation(b *testing.B) { for i := 0; i < b.N; i++ { heapalloc() } }
package redis import ( "context" "errors" "fmt" goredis "github.com/go-redis/redis/v8" "time" ) const ( PIPELINES_KEY = "pipelines" LEASE_DURATION = time.Minute ) var ( LeaseExpired = errors.New("lease expired") LeaseNotFound = errors.New("lease not found") LeaseExists = errors.New("lease already exists") ) type RedisClient interface { TxPipeline() goredis.Pipeliner LRange(ctx context.Context, key string, start, stop int64) *goredis.StringSliceCmd Get(ctx context.Context, key string) *goredis.StringCmd Set(ctx context.Context, key string, value interface{}, expiration time.Duration) *goredis.StatusCmd LPush(ctx context.Context, key string, values ...interface{}) *goredis.IntCmd Expire(ctx context.Context, key string, expiration time.Duration) *goredis.BoolCmd Del(ctx context.Context, keys ...string) *goredis.IntCmd HSet(ctx context.Context, key string, values ...interface{}) *goredis.IntCmd HGet(ctx context.Context, key, field string) *goredis.StringCmd HKeys(ctx context.Context, key string) *goredis.StringSliceCmd } type client struct { rc RedisClient } type PipelineLease struct { PipelineUid string `json:"pipelineUid"` Owner string `json:"owner"` Acquired time.Time `json:"acquired"` Expires time.Time `json:"expires"` } type RedisError struct { nested error } func (e *RedisError) Error() string { return fmt.Sprintf("persistance error: %s", e.nested.Error()) }
package main import ( "fmt" "net/http" "log" "html/template" "github.com/meditate/miniature-garbanzo-blog/models" "database/sql" _ "github.com/lib/pq" ) var posts map[string]*models.Post func writeHandler(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles( "templates/write.html", "templates/header.html", "templates/footer.html") if err != nil { fmt.Println(w, err.Error()) } t.ExecuteTemplate(w, "write", nil) } func editHandler(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles( "templates/write.html", "templates/header.html", "templates/footer.html") if err != nil { fmt.Println(w, err.Error()) } id := r.FormValue("id") fmt.Println(id) post, found := posts[id] if !found { http.NotFound(w, r) } t.ExecuteTemplate(w, "write", post) } func indexHandler(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles( "templates/index.html", "templates/header.html", "templates/footer.html") if err != nil { fmt.Println(w, err.Error()) } fmt.Println(posts) t.ExecuteTemplate(w, "index", posts) } func savePostHandler(w http.ResponseWriter, r *http.Request) { id := r.FormValue("id") title := r.FormValue("title") article := r.FormValue("article") var post *models.Post if id != "" { post = posts[id] post.Title = title post.Article = article } else { id = GenerateId() post := models.NewPost(id, title, article) posts[post.Id] = post } http.Redirect(w, r, "/", 302) } func destroyPostHandler(w http.ResponseWriter, r *http.Request) { id := r.FormValue("id") if id != "" { delete(posts, id) } http.Redirect(w, r, "/", 302) } func newSessionHandler(w http.ResponseWriter, r *http.Request) { t, err := template.ParseFiles( "templates/sessions/new.html", "templates/header.html", "templates/footer.html") if err != nil { fmt.Println(w, err.Error()) } t.ExecuteTemplate(w, "sessions/new", nil) } func main() { fmt.Println("Listen on port :3000") db, db_err := sql.Open("postgres", "user=pqgotest dbname=pqgotest sslmode=verify-full") if db_err != nil { log.Fatal(db_err) } rows, _ := db.Query("SELECT * FROM articles") if rows != nil { log.Fatal(rows) } posts = make(map[string]*models.Post, 0) http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("./assets/")))) http.HandleFunc("/", indexHandler) http.HandleFunc("/write", writeHandler) http.HandleFunc("/edit", editHandler) http.HandleFunc("/destroy", destroyPostHandler) http.HandleFunc("/SavePost", savePostHandler) http.HandleFunc("/sessions/new", newSessionHandler) err := http.ListenAndServe(":3000", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
package Service import ( "Work_5/DAO" "Work_5/object" ) //获取点赞前十的文章 func SelectTopArticle(articles *[]object.Article) object.ErrMessage { //获得数据库连接 db, err := DAO.DataBaseInit() if err.IsErr { return err } //调用DAO层函数 if err = DAO.SelectTopArticle(articles, db); err.IsErr { return err } return object.ErrMessage{} }
package net import ( "context" "errors" "strings" "sync" "time" "github.com/drand/drand/protobuf/drand" "github.com/nikkolasg/slog" "google.golang.org/grpc" "google.golang.org/grpc/credentials" ) var _ Client = (*grpcClient)(nil) //var defaultJSONMarshaller = &runtime.JSONBuiltin{} var defaultJSONMarshaller = &HexJSON{} // grpcClient implements both InternalClient and ExternalClient functionalities // using gRPC as its underlying mechanism type grpcClient struct { sync.Mutex conns map[string]*grpc.ClientConn opts []grpc.DialOption timeout time.Duration manager *CertManager failFast grpc.CallOption } var defaultTimeout = 1 * time.Minute // NewGrpcClient returns an implementation of an InternalClient and // ExternalClient using gRPC connections func NewGrpcClient(opts ...grpc.DialOption) Client { return &grpcClient{ opts: opts, conns: make(map[string]*grpc.ClientConn), timeout: defaultTimeout, } } // NewGrpcClientFromCertManager returns a Client using gRPC with the given trust // store of certificates. func NewGrpcClientFromCertManager(c *CertManager, opts ...grpc.DialOption) Client { client := NewGrpcClient(opts...).(*grpcClient) client.manager = c return client } // NewGrpcClientWithTimeout returns a Client using gRPC using fixed timeout for // method calls. func NewGrpcClientWithTimeout(timeout time.Duration, opts ...grpc.DialOption) Client { c := NewGrpcClient(opts...).(*grpcClient) c.timeout = timeout return c } func getTimeoutContext(timeout time.Duration) (context.Context, context.CancelFunc) { clientDeadline := time.Now().Add(timeout) return context.WithDeadline(context.Background(), clientDeadline) } func (g *grpcClient) SetTimeout(p time.Duration) { g.Lock() defer g.Unlock() g.timeout = p } func (g *grpcClient) PublicRand(p Peer, in *drand.PublicRandRequest) (*drand.PublicRandResponse, error) { var resp *drand.PublicRandResponse fn := func() error { c, err := g.conn(p) if err != nil { return err } client := drand.NewPublicClient(c) ctx, _ := getTimeoutContext(g.timeout) resp, err = client.PublicRand(ctx, in) return err } return resp, g.retryTLS(p, fn) } func (g *grpcClient) PrivateRand(p Peer, in *drand.PrivateRandRequest) (*drand.PrivateRandResponse, error) { var resp *drand.PrivateRandResponse fn := func() error { c, err := g.conn(p) if err != nil { return err } client := drand.NewPublicClient(c) ctx, _ := getTimeoutContext(g.timeout) resp, err = client.PrivateRand(ctx, in) return err } return resp, g.retryTLS(p, fn) } func (g *grpcClient) Group(p Peer, in *drand.GroupRequest) (*drand.GroupResponse, error) { var resp *drand.GroupResponse fn := func() error { c, err := g.conn(p) if err != nil { return err } client := drand.NewPublicClient(c) ctx, _ := getTimeoutContext(g.timeout) resp, err = client.Group(ctx, in) return err } return resp, g.retryTLS(p, fn) } func (g *grpcClient) DistKey(p Peer, in *drand.DistKeyRequest) (*drand.DistKeyResponse, error) { var resp *drand.DistKeyResponse fn := func() error { c, err := g.conn(p) if err != nil { return err } client := drand.NewPublicClient(c) resp, err = client.DistKey(context.Background(), in) return err } return resp, g.retryTLS(p, fn) } func (g *grpcClient) Setup(p Peer, in *drand.SetupPacket, opts ...CallOption) (*drand.Empty, error) { var resp *drand.Empty fn := func() error { c, err := g.conn(p) if err != nil { return err } client := drand.NewProtocolClient(c) // give more time for DKG we are not in a hurry ctx, _ := getTimeoutContext(g.timeout * time.Duration(2)) resp, err = client.Setup(ctx, in, opts...) return err } return resp, g.retryTLS(p, fn) } func (g *grpcClient) Reshare(p Peer, in *drand.ResharePacket, opts ...CallOption) (*drand.Empty, error) { var resp *drand.Empty fn := func() error { c, err := g.conn(p) if err != nil { return err } client := drand.NewProtocolClient(c) // give more time for DKG we are not in a hurry ctx, _ := getTimeoutContext(g.timeout * time.Duration(2)) resp, err = client.Reshare(ctx, in, opts...) return err } return resp, g.retryTLS(p, fn) } func (g *grpcClient) NewBeacon(p Peer, in *drand.BeaconRequest, opts ...CallOption) (*drand.BeaconResponse, error) { var resp *drand.BeaconResponse fn := func() error { c, err := g.conn(p) if err != nil { return err } client := drand.NewProtocolClient(c) ctx, _ := getTimeoutContext(g.timeout) resp, err = client.NewBeacon(ctx, in, opts...) return err } return resp, g.retryTLS(p, fn) } func (g *grpcClient) Home(p Peer, in *drand.HomeRequest) (*drand.HomeResponse, error) { var resp *drand.HomeResponse fn := func() error { c, err := g.conn(p) if err != nil { return err } client := drand.NewPublicClient(c) ctx, _ := getTimeoutContext(g.timeout) resp, err = client.Home(ctx, in) return err } return resp, g.retryTLS(p, fn) } // retryTLS performs a manual reconnection in case there is an error with TLS // certificates. It's a hack for issue // https://github.com/grpc/grpc-go/issues/2394 func (g *grpcClient) retryTLS(p Peer, fn func() error) error { total := 1 for retry := 0; retry < total; retry++ { err := fn() if err == nil { return nil } isTLS := strings.Contains(err.Error(), "tls:") isX509 := strings.Contains(err.Error(), "x509:") if isTLS || isX509 { slog.Infof("drand: forced client reconnection due to TLS error to %s", p.Address()) g.deleteConn(p) g.conn(p) } else { // not an TLS error return err } } return errors.New("grpc: can't connect to " + p.Address()) } func (g *grpcClient) deleteConn(p Peer) { g.Lock() defer g.Unlock() delete(g.conns, p.Address()) } // conn retrieve an already existing conn to the given peer or create a new one func (g *grpcClient) conn(p Peer) (*grpc.ClientConn, error) { g.Lock() defer g.Unlock() var err error c, ok := g.conns[p.Address()] if !ok { slog.Debugf("grpc-client: attempting connection to %s (TLS %v)", p.Address(), p.IsTLS()) if !p.IsTLS() { c, err = grpc.Dial(p.Address(), append(g.opts, grpc.WithInsecure())...) } else { opts := g.opts if g.manager != nil { pool := g.manager.Pool() creds := credentials.NewClientTLSFromCert(pool, "") opts = append(g.opts, grpc.WithTransportCredentials(creds)) } c, err = grpc.Dial(p.Address(), opts...) } g.conns[p.Address()] = c } return c, err } // proxyClient is used by the gRPC json gateway to dispatch calls to the // underlying gRPC server. It needs only to implement the public facing API type proxyClient struct { s Service } func newProxyClient(s Service) *proxyClient { return &proxyClient{s} } func (p *proxyClient) Public(c context.Context, in *drand.PublicRandRequest, opts ...grpc.CallOption) (*drand.PublicRandResponse, error) { return p.s.PublicRand(c, in) } func (p *proxyClient) Private(c context.Context, in *drand.PrivateRandRequest, opts ...grpc.CallOption) (*drand.PrivateRandResponse, error) { return p.s.PrivateRand(c, in) } func (p *proxyClient) DistKey(c context.Context, in *drand.DistKeyRequest, opts ...grpc.CallOption) (*drand.DistKeyResponse, error) { return p.s.DistKey(c, in) } func (p *proxyClient) Home(c context.Context, in *drand.HomeRequest, opts ...grpc.CallOption) (*drand.HomeResponse, error) { return p.s.Home(c, in) }
package c46_rsa_parity import ( "errors" "math/big" "github.com/vodafon/cryptopals/set5/c39_rsa" ) type System struct { *c39_rsa.RSA } func NewSystem(bs int) System { rsa, err := c39_rsa.Generate(bs) if err != nil { panic(err) } return System{rsa} } func (obj System) IsEven(ciphertext []byte) bool { plaintext := obj.Decrypt(ciphertext) if len(plaintext) == 0 { panic("Invalid ciphertext") } return plaintext[len(plaintext)-1]%2 == 0 } func Exploit(ciphertext []byte, s System) (*big.Int, error) { pubK := s.PublicKey() startN := big.NewInt(0) finN := new(big.Int).Set(pubK.N) c := new(big.Int).SetBytes(ciphertext) double := new(big.Int).Exp(big.NewInt(2), pubK.E, pubK.N) for startN.Cmp(new(big.Int).Sub(finN, big.NewInt(10))) <= 0 { c.Mul(c, double).Mod(c, pubK.N) sub := new(big.Int).Sub(finN, startN) sub.Div(sub, big.NewInt(2)) if s.IsEven(c.Bytes()) { finN.Sub(finN, sub) } else { startN.Add(startN, sub) } } return bruteInterval(startN, finN, ciphertext, s) } func bruteInterval(startN, finN *big.Int, ciphertext []byte, s System) (*big.Int, error) { finN.Add(finN, big.NewInt(10)) startN.Sub(startN, big.NewInt(10)) pubK := s.PublicKey() c := new(big.Int).SetBytes(ciphertext) isEven := s.IsEven(c.Bytes()) for finN.Cmp(startN) != 0 { if isEven != bigIsEven(startN) { startN.Add(startN, big.NewInt(1)) continue } ciphertext1 := c39_rsa.Encrypt(startN.Bytes(), pubK) c1 := new(big.Int).SetBytes(ciphertext1) if c1.Cmp(c) == 0 { return startN, nil } startN.Add(startN, big.NewInt(1)) } return nil, errors.New("not found") } func bigIsEven(b *big.Int) bool { bts := b.Bytes() return bts[len(bts)-1]%2 == 0 }
package main import ( "log" "time" ) func main() { for range time.Tick(0) { log.Printf("hello, time now: %v", time.Now().Unix()) } }
package svc11 import ( "fmt" "github.com/feng/future/go-kit/agfun/trace/middleware" "github.com/gin-gonic/gin" opentracing "github.com/opentracing/opentracing-go" "net/http" ) type httpService struct { service Service } func (s *httpService) concatHandler(c *gin.Context) { v := c.Request.URL.Query() result, err := s.service.Concat(c.Request.Context(), v.Get("a"), v.Get("b")) if err != nil { fmt.Printf("%+v", err) c.JSON(http.StatusOK, err) return } c.JSON(http.StatusOK, result) } func (s *httpService) sumHandler(c *gin.Context) { panic("todo") } func RouterInit(hostPort string, tracer opentracing.Tracer, service Service) { svc := &httpService{service: service} concatHandler := gin.HandlerFunc(svc.concatHandler) concatHandler = middleware.FromHTTPRequest(tracer, "Concat")(concatHandler) sumHandler := gin.HandlerFunc(svc.sumHandler) sumHandler = middleware.FromHTTPRequest(tracer, "Sum")(sumHandler) router := gin.New() router.GET("/concat/", concatHandler) router.POST("/sum/", sumHandler) router.Run(hostPort) }
package document import ( "github.com/spf13/cobra" "opendev.org/airship/airshipctl/cmd/document/secret" "opendev.org/airship/airshipctl/pkg/environment" ) // NewDocumentCommand creates a new command for managing airshipctl documents func NewDocumentCommand(rootSettings *environment.AirshipCTLSettings) *cobra.Command { documentRootCmd := &cobra.Command{ Use: "document", Short: "manages deployment documents", } documentRootCmd.AddCommand(secret.NewSecretCommand(rootSettings)) return documentRootCmd }
package api_test import ( "bytes" "context" "errors" "fmt" "io" "mime/multipart" "net/http" "net/http/httptest" "os" "strconv" "testing" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/odpf/stencil/models" stencilv1 "github.com/odpf/stencil/server/odpf/stencil/v1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "google.golang.org/grpc/status" ) var ( formError = models.ErrMissingFormData.Message() uploadError = models.ErrUploadFailed.Message() success = "success" ) func createMultipartBody(name string, version string, dryrun bool) (*bytes.Buffer, *multipart.Writer, error) { buf := new(bytes.Buffer) writer := multipart.NewWriter(buf) defer writer.Close() if err := writer.WriteField("name", name); err != nil { return nil, writer, err } if err := writer.WriteField("version", version); err != nil { return nil, writer, err } if err := writer.WriteField("dryrun", strconv.FormatBool(dryrun)); err != nil { return nil, writer, err } fileWriter, err := writer.CreateFormFile("file", "test.desc") if err != nil { return nil, writer, err } file, err := os.Open("./testdata/test.desc") if err != nil { return nil, writer, err } defer file.Close() _, err = io.Copy(fileWriter, file) return buf, writer, err } func TestUpload(t *testing.T) { for _, test := range []struct { desc string name string version string exists bool validateErr error insertErr error expectedCode int responseMsg string }{ {"should return 400 if name is missing", "", "1.0.1", false, nil, nil, 400, formError}, {"should return 400 if version is missing", "name1", "", false, nil, nil, 400, formError}, {"should return 400 if version is invalid semantic version", "name1", "invalid", false, nil, nil, 400, formError}, {"should return 400 if backward check fails", "name1", "1.0.1", false, errors.New("validation"), nil, 400, "validation"}, {"should return 409 if resource already exists", "name1", "1.0.1", true, nil, nil, 409, "Resource already exists"}, {"should return 500 if insert fails", "name1", "1.0.1", false, nil, errors.New("insert fail"), 500, "Internal error"}, {"should return 200 if upload succeeded", "name1", "1.0.1", false, nil, nil, 200, success}, } { t.Run(test.desc, func(t *testing.T) { router, mockService, metadata, _ := setup() metadata.On("Exists", mock.Anything, mock.Anything).Return(test.exists) mockService.On("Validate", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(test.validateErr) mockService.On("Insert", mock.Anything, mock.Anything, mock.Anything).Return(test.insertErr) w := httptest.NewRecorder() body, writer, _ := createMultipartBody(test.name, test.version, false) req, _ := http.NewRequest("POST", "/v1/namespaces/namespace/descriptors", body) req.Header.Set("Content-Type", writer.FormDataContentType()) router.ServeHTTP(w, req) assert.Equal(t, test.expectedCode, w.Code) if w.Code == 200 { assert.JSONEq(t, fmt.Sprintf(`{"message": "%s", "dryrun": false}`, test.responseMsg), w.Body.String()) } else { assert.JSONEq(t, fmt.Sprintf(`{"message": "%s"}`, test.responseMsg), w.Body.String()) } }) t.Run(fmt.Sprintf("gRPC: %s", test.desc), func(t *testing.T) { _, mockService, metadata, api := setup() metadata.On("Exists", mock.Anything, mock.Anything).Return(test.exists) mockService.On("Validate", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(test.validateErr) mockService.On("Insert", mock.Anything, mock.Anything, mock.Anything).Return(test.insertErr) data, err := os.ReadFile("./testdata/test.desc") assert.Nil(t, err) req := &stencilv1.UploadDescriptorRequest{ Namespace: "namespace", Name: test.name, Version: test.version, Data: data, } res, err := api.UploadDescriptor(context.Background(), req) if test.expectedCode != 200 { e := status.Convert(err) assert.Equal(t, test.expectedCode, runtime.HTTPStatusFromCode(e.Code())) } else { assert.Equal(t, res.Dryrun, false) assert.Equal(t, res.Success, true) assert.Equal(t, res.Errors, "") } }) } t.Run("should not insert if dry run flag is enabled", func(t *testing.T) { name := "name1" version := "1.0.1" router, mockService, metadata, _ := setup() metadata.On("Exists", mock.Anything, mock.Anything).Return(false) mockService.On("Validate", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) mockService.On("Insert", mock.Anything, mock.Anything, mock.Anything).Return(nil) w := httptest.NewRecorder() body, writer, _ := createMultipartBody(name, version, true) req, _ := http.NewRequest("POST", "/v1/namespaces/namespace/descriptors", body) req.Header.Set("Content-Type", writer.FormDataContentType()) router.ServeHTTP(w, req) assert.Equal(t, 200, w.Code) assert.JSONEq(t, `{"message": "success", "dryrun": true}`, w.Body.String()) mockService.AssertNotCalled(t, "Insert", mock.Anything, mock.Anything, mock.Anything) }) }
// Copyright 2020 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "net/http" ) func main() { http.HandleFunc("/oauth/token", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`{"access_token": "ok", "token_type":"service_account", "expires_in":3600}`)) }) _ = http.ListenAndServe(":5000", nil) }
// Copyright 2016 Google Inc. 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 grumpy import ( "fmt" "math/big" "reflect" "runtime" "testing" ) func TestNewStr(t *testing.T) { expected := &Str{Object: Object{typ: StrType}, value: "foo"} s := NewStr("foo") if !reflect.DeepEqual(s, expected) { t.Errorf(`NewStr("foo") = %+v, expected %+v`, *s, *expected) } } func BenchmarkNewStr(b *testing.B) { var ret *Str for i := 0; i < b.N; i++ { ret = NewStr("foo") } runtime.KeepAlive(ret) } // # On a 64bit system: // >>> hash("foo") // -4177197833195190597 // >>> hash("bar") // 327024216814240868 // >>> hash("baz") // 327024216814240876 func TestHashString(t *testing.T) { truncateInt := func(i int64) int { return int(i) } // Support for 32bit platforms cases := []struct { value string hash int }{ {"foo", truncateInt(-4177197833195190597)}, {"bar", truncateInt(327024216814240868)}, {"baz", truncateInt(327024216814240876)}, } for _, cas := range cases { if h := hashString(cas.value); h != cas.hash { t.Errorf("hashString(%q) = %d, expected %d", cas.value, h, cas.hash) } } } func TestStrBinaryOps(t *testing.T) { fun := wrapFuncForTest(func(f *Frame, fn binaryOpFunc, v *Object, w *Object) (*Object, *BaseException) { return fn(f, v, w) }) cases := []invokeTestCase{ {args: wrapArgs(Add, "foo", "bar"), want: NewStr("foobar").ToObject()}, {args: wrapArgs(Add, "foo", NewUnicode("bar")), want: NewUnicode("foobar").ToObject()}, {args: wrapArgs(Add, "baz", ""), want: NewStr("baz").ToObject()}, {args: wrapArgs(Add, "", newObject(ObjectType)), wantExc: mustCreateException(TypeErrorType, "unsupported operand type(s) for +: 'str' and 'object'")}, {args: wrapArgs(Add, None, ""), wantExc: mustCreateException(TypeErrorType, "unsupported operand type(s) for +: 'NoneType' and 'str'")}, {args: wrapArgs(Mod, "%s", 42), want: NewStr("42").ToObject()}, {args: wrapArgs(Mod, "%3s", 42), want: NewStr(" 42").ToObject()}, {args: wrapArgs(Mod, "%03s", 42), want: NewStr(" 42").ToObject()}, {args: wrapArgs(Mod, "%f", 3.14), want: NewStr("3.140000").ToObject()}, {args: wrapArgs(Mod, "%10f", 3.14), want: NewStr(" 3.140000").ToObject()}, {args: wrapArgs(Mod, "%010f", 3.14), want: NewStr("003.140000").ToObject()}, {args: wrapArgs(Mod, "abc %d", NewLong(big.NewInt(123))), want: NewStr("abc 123").ToObject()}, {args: wrapArgs(Mod, "%d", 3.14), want: NewStr("3").ToObject()}, {args: wrapArgs(Mod, "%%", NewTuple()), want: NewStr("%").ToObject()}, {args: wrapArgs(Mod, "%3%", NewTuple()), want: NewStr(" %").ToObject()}, {args: wrapArgs(Mod, "%03%", NewTuple()), want: NewStr(" %").ToObject()}, {args: wrapArgs(Mod, "%r", "abc"), want: NewStr("'abc'").ToObject()}, {args: wrapArgs(Mod, "%6r", "abc"), want: NewStr(" 'abc'").ToObject()}, {args: wrapArgs(Mod, "%06r", "abc"), want: NewStr(" 'abc'").ToObject()}, {args: wrapArgs(Mod, "%s %s", true), wantExc: mustCreateException(TypeErrorType, "not enough arguments for format string")}, {args: wrapArgs(Mod, "%Z", None), wantExc: mustCreateException(ValueErrorType, "invalid format spec")}, {args: wrapArgs(Mod, "%s", NewDict()), want: NewStr("{}").ToObject()}, {args: wrapArgs(Mod, "% d", 23), wantExc: mustCreateException(NotImplementedErrorType, "conversion flags not yet supported")}, {args: wrapArgs(Mod, "%.3f", 102.1), wantExc: mustCreateException(NotImplementedErrorType, "field width not yet supported")}, {args: wrapArgs(Mod, "%x", 0x1f), want: NewStr("1f").ToObject()}, {args: wrapArgs(Mod, "%X", 0xffff), want: NewStr("FFFF").ToObject()}, {args: wrapArgs(Mod, "%x", 1.2), want: NewStr("1").ToObject()}, {args: wrapArgs(Mod, "abc %x", NewLong(big.NewInt(123))), want: NewStr("abc 7b").ToObject()}, {args: wrapArgs(Mod, "%x", None), wantExc: mustCreateException(TypeErrorType, "an integer is required")}, {args: wrapArgs(Mod, "%f", None), wantExc: mustCreateException(TypeErrorType, "float argument required, not NoneType")}, {args: wrapArgs(Mod, "%s", newTestTuple(123, None)), wantExc: mustCreateException(TypeErrorType, "not all arguments converted during string formatting")}, {args: wrapArgs(Mod, "%d", newTestTuple("123")), wantExc: mustCreateException(TypeErrorType, "an integer is required")}, {args: wrapArgs(Mod, "%o", newTestTuple(123)), want: NewStr("173").ToObject()}, {args: wrapArgs(Mod, "%o", 8), want: NewStr("10").ToObject()}, {args: wrapArgs(Mod, "%o", -8), want: NewStr("-10").ToObject()}, {args: wrapArgs(Mod, "%03o", newTestTuple(123)), want: NewStr("173").ToObject()}, {args: wrapArgs(Mod, "%04o", newTestTuple(123)), want: NewStr("0173").ToObject()}, {args: wrapArgs(Mod, "%o", newTestTuple("123")), wantExc: mustCreateException(TypeErrorType, "an integer is required")}, {args: wrapArgs(Mod, "%o", None), wantExc: mustCreateException(TypeErrorType, "an integer is required")}, {args: wrapArgs(Mod, "%(foo)s", "bar"), wantExc: mustCreateException(TypeErrorType, "format requires a mapping")}, {args: wrapArgs(Mod, "%(foo)s %(bar)d", newTestDict("foo", "baz", "bar", 123)), want: NewStr("baz 123").ToObject()}, {args: wrapArgs(Mod, "%(foo)s", newTestDict()), wantExc: mustCreateException(KeyErrorType, "'foo'")}, {args: wrapArgs(Mod, "%(foo)s %s", newTestDict("foo", "bar")), wantExc: mustCreateException(TypeErrorType, "not enough arguments for format string")}, {args: wrapArgs(Mod, "%s %(foo)s", newTestDict("foo", "bar")), want: NewStr("{'foo': 'bar'} bar").ToObject()}, {args: wrapArgs(Mul, "", 10), want: NewStr("").ToObject()}, {args: wrapArgs(Mul, "foo", -2), want: NewStr("").ToObject()}, {args: wrapArgs(Mul, "foobar", 0), want: NewStr("").ToObject()}, {args: wrapArgs(Mul, "aloha", 2), want: NewStr("alohaaloha").ToObject()}, {args: wrapArgs(Mul, 1, "baz"), want: NewStr("baz").ToObject()}, {args: wrapArgs(Mul, newObject(ObjectType), "qux"), wantExc: mustCreateException(TypeErrorType, "unsupported operand type(s) for *: 'object' and 'str'")}, {args: wrapArgs(Mul, "foo", ""), wantExc: mustCreateException(TypeErrorType, "unsupported operand type(s) for *: 'str' and 'str'")}, {args: wrapArgs(Mul, "bar", MaxInt), wantExc: mustCreateException(OverflowErrorType, "result too large")}, } for _, cas := range cases { if err := runInvokeTestCase(fun, &cas); err != "" { t.Error(err) } } } func TestStrCompare(t *testing.T) { cases := []invokeTestCase{ {args: wrapArgs("", ""), want: compareAllResultEq}, {args: wrapArgs("foo", "foo"), want: compareAllResultEq}, {args: wrapArgs("", "foo"), want: compareAllResultLT}, {args: wrapArgs("foo", ""), want: compareAllResultGT}, {args: wrapArgs("bar", "baz"), want: compareAllResultLT}, } for _, cas := range cases { if err := runInvokeTestCase(compareAll, &cas); err != "" { t.Error(err) } } } func TestStrContains(t *testing.T) { cases := []invokeTestCase{ {args: wrapArgs("foobar", "foo"), want: True.ToObject()}, {args: wrapArgs("abcdef", "bar"), want: False.ToObject()}, {args: wrapArgs("", ""), want: True.ToObject()}, {args: wrapArgs("foobar", NewUnicode("bar")), want: True.ToObject()}, {args: wrapArgs("", 102.1), wantExc: mustCreateException(TypeErrorType, "'in <string>' requires string as left operand, not float")}, } for _, cas := range cases { if err := runInvokeMethodTestCase(StrType, "__contains__", &cas); err != "" { t.Error(err) } } } func TestStrDecode(t *testing.T) { cases := []invokeTestCase{ {args: wrapArgs("foo"), want: NewUnicode("foo").ToObject()}, {args: wrapArgs("foo\xffbar", "utf8", "replace"), want: NewUnicode("foo\ufffdbar").ToObject()}, {args: wrapArgs("foo\xffbar", "utf8", "ignore"), want: NewUnicode("foobar").ToObject()}, // Bad error handler name only triggers LookupError when an // error is encountered. {args: wrapArgs("foobar", "utf8", "noexist"), want: NewUnicode("foobar").ToObject()}, {args: wrapArgs("foo\xffbar", "utf8", "noexist"), wantExc: mustCreateException(LookupErrorType, "unknown error handler name 'noexist'")}, {args: wrapArgs("foobar", "noexist"), wantExc: mustCreateException(LookupErrorType, "unknown encoding: noexist")}, {args: wrapArgs("foo\xffbar"), wantExc: mustCreateException(UnicodeDecodeErrorType, "'utf8' codec can't decode byte 0xff in position 3")}, // Surrogates are not valid UTF-8 and should raise, unlike // CPython 2.x. {args: wrapArgs("foo\xef\xbf\xbdbar", "utf8", "strict"), wantExc: mustCreateException(UnicodeDecodeErrorType, "'utf8' codec can't decode byte 0xef in position 3")}, } for _, cas := range cases { if err := runInvokeMethodTestCase(StrType, "decode", &cas); err != "" { t.Error(err) } } } func TestStrGetItem(t *testing.T) { intIndexType := newTestClass("IntIndex", []*Type{ObjectType}, newStringDict(map[string]*Object{ "__index__": newBuiltinFunction("__index__", func(f *Frame, _ Args, _ KWArgs) (*Object, *BaseException) { return NewInt(2).ToObject(), nil }).ToObject(), })) longIndexType := newTestClass("LongIndex", []*Type{ObjectType}, newStringDict(map[string]*Object{ "__index__": newBuiltinFunction("__index__", func(f *Frame, _ Args, _ KWArgs) (*Object, *BaseException) { return NewLong(big.NewInt(2)).ToObject(), nil }).ToObject(), })) cases := []invokeTestCase{ {args: wrapArgs("bar", 1), want: NewStr("a").ToObject()}, {args: wrapArgs("foo", 3.14), wantExc: mustCreateException(TypeErrorType, "string indices must be integers or slice, not float")}, {args: wrapArgs("bar", big.NewInt(1)), want: NewStr("a").ToObject()}, {args: wrapArgs("baz", -1), want: NewStr("z").ToObject()}, {args: wrapArgs("baz", newObject(intIndexType)), want: NewStr("z").ToObject()}, {args: wrapArgs("baz", newObject(longIndexType)), want: NewStr("z").ToObject()}, {args: wrapArgs("baz", -4), wantExc: mustCreateException(IndexErrorType, "index out of range")}, {args: wrapArgs("", 0), wantExc: mustCreateException(IndexErrorType, "index out of range")}, {args: wrapArgs("foo", 3), wantExc: mustCreateException(IndexErrorType, "index out of range")}, {args: wrapArgs("bar", newTestSlice(None, 2)), want: NewStr("ba").ToObject()}, {args: wrapArgs("bar", newTestSlice(1, 3)), want: NewStr("ar").ToObject()}, {args: wrapArgs("bar", newTestSlice(1, None)), want: NewStr("ar").ToObject()}, {args: wrapArgs("foobarbaz", newTestSlice(1, 8, 2)), want: NewStr("obra").ToObject()}, {args: wrapArgs("abc", newTestSlice(None, None, -1)), want: NewStr("cba").ToObject()}, {args: wrapArgs("bar", newTestSlice(1, 2, 0)), wantExc: mustCreateException(ValueErrorType, "slice step cannot be zero")}, } for _, cas := range cases { if err := runInvokeMethodTestCase(StrType, "__getitem__", &cas); err != "" { t.Error(err) } } } func TestStrNew(t *testing.T) { dummy := newObject(ObjectType) dummyStr := NewStr(fmt.Sprintf("<object object at %p>", dummy)) fooType := newTestClass("Foo", []*Type{ObjectType}, newStringDict(map[string]*Object{ "__str__": newBuiltinFunction("__str__", func(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) { return NewInt(123).ToObject(), nil }).ToObject(), })) foo := newObject(fooType) strictEqType := newTestClassStrictEq("StrictEq", StrType) subType := newTestClass("SubType", []*Type{StrType}, newStringDict(map[string]*Object{})) subTypeObject := (&Str{Object: Object{typ: subType}, value: "abc"}).ToObject() goodSlotType := newTestClass("GoodSlot", []*Type{ObjectType}, newStringDict(map[string]*Object{ "__str__": newBuiltinFunction("__str__", func(_ *Frame, _ Args, _ KWArgs) (*Object, *BaseException) { return NewStr("abc").ToObject(), nil }).ToObject(), })) badSlotType := newTestClass("BadSlot", []*Type{ObjectType}, newStringDict(map[string]*Object{ "__str__": newBuiltinFunction("__str__", func(_ *Frame, _ Args, _ KWArgs) (*Object, *BaseException) { return newObject(ObjectType), nil }).ToObject(), })) slotSubTypeType := newTestClass("SlotSubType", []*Type{ObjectType}, newStringDict(map[string]*Object{ "__str__": newBuiltinFunction("__str__", func(_ *Frame, _ Args, _ KWArgs) (*Object, *BaseException) { return subTypeObject, nil }).ToObject(), })) cases := []invokeTestCase{ {wantExc: mustCreateException(TypeErrorType, "'__new__' requires 1 arguments")}, {args: wrapArgs(IntType.ToObject()), wantExc: mustCreateException(TypeErrorType, "str.__new__(int): int is not a subtype of str")}, {args: wrapArgs(StrType.ToObject(), NewInt(1).ToObject(), NewInt(2).ToObject()), wantExc: mustCreateException(TypeErrorType, "str() takes at most 1 argument (2 given)")}, {args: wrapArgs(StrType.ToObject(), foo), wantExc: mustCreateException(TypeErrorType, "__str__ returned non-string (type int)")}, {args: wrapArgs(StrType.ToObject()), want: NewStr("").ToObject()}, {args: wrapArgs(StrType.ToObject(), NewDict().ToObject()), want: NewStr("{}").ToObject()}, {args: wrapArgs(StrType.ToObject(), dummy), want: dummyStr.ToObject()}, {args: wrapArgs(strictEqType, "foo"), want: (&Str{Object: Object{typ: strictEqType}, value: "foo"}).ToObject()}, {args: wrapArgs(StrType, newObject(goodSlotType)), want: NewStr("abc").ToObject()}, {args: wrapArgs(StrType, newObject(badSlotType)), wantExc: mustCreateException(TypeErrorType, "__str__ returned non-string (type object)")}, {args: wrapArgs(StrType, newObject(slotSubTypeType)), want: subTypeObject}, {args: wrapArgs(strictEqType, newObject(goodSlotType)), want: (&Str{Object: Object{typ: strictEqType}, value: "abc"}).ToObject()}, {args: wrapArgs(strictEqType, newObject(badSlotType)), wantExc: mustCreateException(TypeErrorType, "__str__ returned non-string (type object)")}, } for _, cas := range cases { if err := runInvokeMethodTestCase(StrType, "__new__", &cas); err != "" { t.Error(err) } } } func TestStrRepr(t *testing.T) { cases := []invokeTestCase{ {args: wrapArgs("foo"), want: NewStr(`'foo'`).ToObject()}, {args: wrapArgs("on\nmultiple\nlines"), want: NewStr(`'on\nmultiple\nlines'`).ToObject()}, {args: wrapArgs("\x00\x00"), want: NewStr(`'\x00\x00'`).ToObject()}, } for _, cas := range cases { if err := runInvokeMethodTestCase(StrType, "__repr__", &cas); err != "" { t.Error(err) } } } func TestStrMethods(t *testing.T) { fooType := newTestClass("Foo", []*Type{ObjectType}, newStringDict(map[string]*Object{"bar": None})) intIndexType := newTestClass("IntIndex", []*Type{ObjectType}, newStringDict(map[string]*Object{ "__index__": newBuiltinFunction("__index__", func(f *Frame, _ Args, _ KWArgs) (*Object, *BaseException) { return NewInt(2).ToObject(), nil }).ToObject(), })) longIndexType := newTestClass("LongIndex", []*Type{ObjectType}, newStringDict(map[string]*Object{ "__index__": newBuiltinFunction("__index__", func(f *Frame, _ Args, _ KWArgs) (*Object, *BaseException) { return NewLong(big.NewInt(2)).ToObject(), nil }).ToObject(), })) intIntType := newTestClass("IntInt", []*Type{ObjectType}, newStringDict(map[string]*Object{ "__int__": newBuiltinFunction("__int__", func(f *Frame, _ Args, _ KWArgs) (*Object, *BaseException) { return NewInt(2).ToObject(), nil }).ToObject(), })) longIntType := newTestClass("LongInt", []*Type{ObjectType}, newStringDict(map[string]*Object{ "__int__": newBuiltinFunction("__int__", func(f *Frame, _ Args, _ KWArgs) (*Object, *BaseException) { return NewLong(big.NewInt(2)).ToObject(), nil }).ToObject(), })) cases := []struct { methodName string args Args want *Object wantExc *BaseException }{ {"capitalize", wrapArgs(""), NewStr("").ToObject(), nil}, {"capitalize", wrapArgs("foobar"), NewStr("Foobar").ToObject(), nil}, {"capitalize", wrapArgs("FOOBAR"), NewStr("Foobar").ToObject(), nil}, {"capitalize", wrapArgs("ùBAR"), NewStr("ùbar").ToObject(), nil}, {"capitalize", wrapArgs("вол"), NewStr("вол").ToObject(), nil}, {"capitalize", wrapArgs("foobar", 123), nil, mustCreateException(TypeErrorType, "'capitalize' of 'str' requires 1 arguments")}, {"capitalize", wrapArgs("ВОЛ"), NewStr("ВОЛ").ToObject(), nil}, {"center", wrapArgs("foobar", 9, "#"), NewStr("##foobar#").ToObject(), nil}, {"center", wrapArgs("foobar", 10, "#"), NewStr("##foobar##").ToObject(), nil}, {"center", wrapArgs("foobar", 3, "#"), NewStr("foobar").ToObject(), nil}, {"center", wrapArgs("foobar", -1, "#"), NewStr("foobar").ToObject(), nil}, {"center", wrapArgs("foobar", 10, "##"), nil, mustCreateException(TypeErrorType, "center() argument 2 must be char, not str")}, {"center", wrapArgs("foobar", 10, ""), nil, mustCreateException(TypeErrorType, "center() argument 2 must be char, not str")}, {"count", wrapArgs("", "a"), NewInt(0).ToObject(), nil}, {"count", wrapArgs("five", ""), NewInt(5).ToObject(), nil}, {"count", wrapArgs("abba", "bb"), NewInt(1).ToObject(), nil}, {"count", wrapArgs("abbba", "bb"), NewInt(1).ToObject(), nil}, {"count", wrapArgs("abbbba", "bb"), NewInt(2).ToObject(), nil}, {"count", wrapArgs("abcdeffdeabcb", "b"), NewInt(3).ToObject(), nil}, {"count", wrapArgs(""), nil, mustCreateException(TypeErrorType, "'count' of 'str' requires 2 arguments")}, {"endswith", wrapArgs("", ""), True.ToObject(), nil}, {"endswith", wrapArgs("", "", 1), False.ToObject(), nil}, {"endswith", wrapArgs("foobar", "bar"), True.ToObject(), nil}, {"endswith", wrapArgs("foobar", "bar", 0, -2), False.ToObject(), nil}, {"endswith", wrapArgs("foobar", "foo", 0, 3), True.ToObject(), nil}, {"endswith", wrapArgs("foobar", "bar", 3, 5), False.ToObject(), nil}, {"endswith", wrapArgs("foobar", "bar", 5, 3), False.ToObject(), nil}, {"endswith", wrapArgs("bar", "foobar"), False.ToObject(), nil}, {"endswith", wrapArgs("foo", newTestTuple("barfoo", "oo").ToObject()), True.ToObject(), nil}, {"endswith", wrapArgs("foo", 123), nil, mustCreateException(TypeErrorType, "endswith first arg must be str, unicode, or tuple, not int")}, {"endswith", wrapArgs("foo", newTestTuple(123).ToObject()), nil, mustCreateException(TypeErrorType, "expected a str")}, {"find", wrapArgs("", ""), NewInt(0).ToObject(), nil}, {"find", wrapArgs("", "", 1), NewInt(-1).ToObject(), nil}, {"find", wrapArgs("", "", -1), NewInt(0).ToObject(), nil}, {"find", wrapArgs("", "", None, -1), NewInt(0).ToObject(), nil}, {"find", wrapArgs("foobar", "bar"), NewInt(3).ToObject(), nil}, {"find", wrapArgs("foobar", "bar", fooType), nil, mustCreateException(TypeErrorType, "slice indices must be integers or None or have an __index__ method")}, {"find", wrapArgs("foobar", "bar", NewInt(MaxInt)), NewInt(-1).ToObject(), nil}, {"find", wrapArgs("foobar", "bar", None, NewInt(MaxInt)), NewInt(3).ToObject(), nil}, {"find", wrapArgs("foobar", "bar", newObject(intIndexType)), NewInt(3).ToObject(), nil}, {"find", wrapArgs("foobar", "bar", None, newObject(intIndexType)), NewInt(-1).ToObject(), nil}, {"find", wrapArgs("foobar", "bar", newObject(longIndexType)), NewInt(3).ToObject(), nil}, {"find", wrapArgs("foobar", "bar", None, newObject(longIndexType)), NewInt(-1).ToObject(), nil}, // TODO: Support unicode substring. {"find", wrapArgs("foobar", NewUnicode("bar")), nil, mustCreateException(TypeErrorType, "'find/index' requires a 'str' object but received a 'unicode'")}, {"find", wrapArgs("foobar", "bar", "baz"), nil, mustCreateException(TypeErrorType, "slice indices must be integers or None or have an __index__ method")}, {"find", wrapArgs("foobar", "bar", 0, "baz"), nil, mustCreateException(TypeErrorType, "slice indices must be integers or None or have an __index__ method")}, {"find", wrapArgs("foobar", "bar", None), NewInt(3).ToObject(), nil}, {"find", wrapArgs("foobar", "bar", 0, None), NewInt(3).ToObject(), nil}, {"find", wrapArgs("foobar", "bar", 0, -2), NewInt(-1).ToObject(), nil}, {"find", wrapArgs("foobar", "foo", 0, 3), NewInt(0).ToObject(), nil}, {"find", wrapArgs("foobar", "foo", 10), NewInt(-1).ToObject(), nil}, {"find", wrapArgs("foobar", "foo", 3, 3), NewInt(-1).ToObject(), nil}, {"find", wrapArgs("foobar", "bar", 3, 5), NewInt(-1).ToObject(), nil}, {"find", wrapArgs("foobar", "bar", 5, 3), NewInt(-1).ToObject(), nil}, {"find", wrapArgs("bar", "foobar"), NewInt(-1).ToObject(), nil}, {"find", wrapArgs("bar", "a", 1, 10), NewInt(1).ToObject(), nil}, {"find", wrapArgs("bar", "a", NewLong(big.NewInt(1)), 10), NewInt(1).ToObject(), nil}, {"find", wrapArgs("bar", "a", 0, NewLong(big.NewInt(2))), NewInt(1).ToObject(), nil}, {"find", wrapArgs("bar", "a", 1, 3), NewInt(1).ToObject(), nil}, {"find", wrapArgs("bar", "a", 0, -1), NewInt(1).ToObject(), nil}, {"find", wrapArgs("foo", newTestTuple("barfoo", "oo").ToObject()), nil, mustCreateException(TypeErrorType, "'find/index' requires a 'str' object but received a 'tuple'")}, {"find", wrapArgs("foo", 123), nil, mustCreateException(TypeErrorType, "'find/index' requires a 'str' object but received a 'int'")}, {"index", wrapArgs("", ""), NewInt(0).ToObject(), nil}, {"index", wrapArgs("", "", 1), nil, mustCreateException(ValueErrorType, "substring not found")}, {"index", wrapArgs("", "", -1), NewInt(0).ToObject(), nil}, {"index", wrapArgs("", "", None, -1), NewInt(0).ToObject(), nil}, {"index", wrapArgs("foobar", "bar"), NewInt(3).ToObject(), nil}, {"index", wrapArgs("foobar", "bar", fooType), nil, mustCreateException(TypeErrorType, "slice indices must be integers or None or have an __index__ method")}, {"index", wrapArgs("foobar", "bar", NewInt(MaxInt)), nil, mustCreateException(ValueErrorType, "substring not found")}, {"index", wrapArgs("foobar", "bar", None, NewInt(MaxInt)), NewInt(3).ToObject(), nil}, {"index", wrapArgs("foobar", "bar", newObject(intIndexType)), NewInt(3).ToObject(), nil}, {"index", wrapArgs("foobar", "bar", None, newObject(intIndexType)), nil, mustCreateException(ValueErrorType, "substring not found")}, {"index", wrapArgs("foobar", "bar", newObject(longIndexType)), NewInt(3).ToObject(), nil}, {"index", wrapArgs("foobar", "bar", None, newObject(longIndexType)), nil, mustCreateException(ValueErrorType, "substring not found")}, //TODO: Support unicode substring. {"index", wrapArgs("foobar", NewUnicode("bar")), nil, mustCreateException(TypeErrorType, "'find/index' requires a 'str' object but received a 'unicode'")}, {"index", wrapArgs("foobar", "bar", "baz"), nil, mustCreateException(TypeErrorType, "slice indices must be integers or None or have an __index__ method")}, {"index", wrapArgs("foobar", "bar", 0, "baz"), nil, mustCreateException(TypeErrorType, "slice indices must be integers or None or have an __index__ method")}, {"index", wrapArgs("foobar", "bar", None), NewInt(3).ToObject(), nil}, {"index", wrapArgs("foobar", "bar", 0, None), NewInt(3).ToObject(), nil}, {"index", wrapArgs("foobar", "bar", 0, -2), nil, mustCreateException(ValueErrorType, "substring not found")}, {"index", wrapArgs("foobar", "foo", 0, 3), NewInt(0).ToObject(), nil}, {"index", wrapArgs("foobar", "foo", 10), nil, mustCreateException(ValueErrorType, "substring not found")}, {"index", wrapArgs("foobar", "foo", 3, 3), nil, mustCreateException(ValueErrorType, "substring not found")}, {"index", wrapArgs("foobar", "bar", 3, 5), nil, mustCreateException(ValueErrorType, "substring not found")}, {"index", wrapArgs("foobar", "bar", 5, 3), nil, mustCreateException(ValueErrorType, "substring not found")}, {"index", wrapArgs("bar", "foobar"), nil, mustCreateException(ValueErrorType, "substring not found")}, {"index", wrapArgs("bar", "a", 1, 10), NewInt(1).ToObject(), nil}, {"index", wrapArgs("bar", "a", NewLong(big.NewInt(1)), 10), NewInt(1).ToObject(), nil}, {"index", wrapArgs("bar", "a", 0, NewLong(big.NewInt(2))), NewInt(1).ToObject(), nil}, {"index", wrapArgs("bar", "a", 1, 3), NewInt(1).ToObject(), nil}, {"index", wrapArgs("bar", "a", 0, -1), NewInt(1).ToObject(), nil}, {"index", wrapArgs("foo", newTestTuple("barfoo", "oo").ToObject()), nil, mustCreateException(TypeErrorType, "'find/index' requires a 'str' object but received a 'tuple'")}, {"index", wrapArgs("foo", 123), nil, mustCreateException(TypeErrorType, "'find/index' requires a 'str' object but received a 'int'")}, {"index", wrapArgs("barbaz", "ba"), NewInt(0).ToObject(), nil}, {"index", wrapArgs("barbaz", "ba", 1), NewInt(3).ToObject(), nil}, {"isalnum", wrapArgs("123abc"), True.ToObject(), nil}, {"isalnum", wrapArgs(""), False.ToObject(), nil}, {"isalnum", wrapArgs("#$%"), False.ToObject(), nil}, {"isalnum", wrapArgs("abc#123"), False.ToObject(), nil}, {"isalnum", wrapArgs("123abc", "efg"), nil, mustCreateException(TypeErrorType, "'isalnum' of 'str' requires 1 arguments")}, {"isalpha", wrapArgs("xyz"), True.ToObject(), nil}, {"isalpha", wrapArgs(""), False.ToObject(), nil}, {"isalpha", wrapArgs("#$%"), False.ToObject(), nil}, {"isalpha", wrapArgs("abc#123"), False.ToObject(), nil}, {"isalpha", wrapArgs("absd", "efg"), nil, mustCreateException(TypeErrorType, "'isalpha' of 'str' requires 1 arguments")}, {"isdigit", wrapArgs("abc"), False.ToObject(), nil}, {"isdigit", wrapArgs("123"), True.ToObject(), nil}, {"isdigit", wrapArgs(""), False.ToObject(), nil}, {"isdigit", wrapArgs("abc#123"), False.ToObject(), nil}, {"isdigit", wrapArgs("123", "456"), nil, mustCreateException(TypeErrorType, "'isdigit' of 'str' requires 1 arguments")}, {"islower", wrapArgs("abc"), True.ToObject(), nil}, {"islower", wrapArgs("ABC"), False.ToObject(), nil}, {"islower", wrapArgs(""), False.ToObject(), nil}, {"islower", wrapArgs("abc#123"), False.ToObject(), nil}, {"islower", wrapArgs("123", "456"), nil, mustCreateException(TypeErrorType, "'islower' of 'str' requires 1 arguments")}, {"isupper", wrapArgs("abc"), False.ToObject(), nil}, {"isupper", wrapArgs("ABC"), True.ToObject(), nil}, {"isupper", wrapArgs(""), False.ToObject(), nil}, {"isupper", wrapArgs("abc#123"), False.ToObject(), nil}, {"isupper", wrapArgs("123", "456"), nil, mustCreateException(TypeErrorType, "'isupper' of 'str' requires 1 arguments")}, {"isspace", wrapArgs(""), False.ToObject(), nil}, {"isspace", wrapArgs(" "), True.ToObject(), nil}, {"isspace", wrapArgs("\n\t\v\f\r "), True.ToObject(), nil}, {"isspace", wrapArgs(""), False.ToObject(), nil}, {"isspace", wrapArgs("asdad"), False.ToObject(), nil}, {"isspace", wrapArgs(" "), True.ToObject(), nil}, {"isspace", wrapArgs(" ", "456"), nil, mustCreateException(TypeErrorType, "'isspace' of 'str' requires 1 arguments")}, {"istitle", wrapArgs("abc"), False.ToObject(), nil}, {"istitle", wrapArgs("Abc&D"), True.ToObject(), nil}, {"istitle", wrapArgs("ABc&D"), False.ToObject(), nil}, {"istitle", wrapArgs(""), False.ToObject(), nil}, {"istitle", wrapArgs("abc#123"), False.ToObject(), nil}, {"istitle", wrapArgs("ABc&D", "456"), nil, mustCreateException(TypeErrorType, "'istitle' of 'str' requires 1 arguments")}, {"join", wrapArgs(",", newTestList("foo", "bar")), NewStr("foo,bar").ToObject(), nil}, {"join", wrapArgs(":", newTestList("foo", "bar", NewUnicode("baz"))), NewUnicode("foo:bar:baz").ToObject(), nil}, {"join", wrapArgs("nope", NewTuple()), NewStr("").ToObject(), nil}, {"join", wrapArgs("nope", newTestTuple("foo")), NewStr("foo").ToObject(), nil}, {"join", wrapArgs(",", newTestList("foo", "bar", 3.14)), nil, mustCreateException(TypeErrorType, "sequence item 2: expected string, float found")}, {"join", wrapArgs("\xff", newTestList(NewUnicode("foo"), NewUnicode("bar"))), nil, mustCreateException(UnicodeDecodeErrorType, "'utf8' codec can't decode byte 0xff in position 0")}, {"ljust", wrapArgs("foobar", 10, "#"), NewStr("foobar####").ToObject(), nil}, {"ljust", wrapArgs("foobar", 3, "#"), NewStr("foobar").ToObject(), nil}, {"ljust", wrapArgs("foobar", -1, "#"), NewStr("foobar").ToObject(), nil}, {"ljust", wrapArgs("foobar", 10, "##"), nil, mustCreateException(TypeErrorType, "ljust() argument 2 must be char, not str")}, {"ljust", wrapArgs("foobar", 10, ""), nil, mustCreateException(TypeErrorType, "ljust() argument 2 must be char, not str")}, {"lower", wrapArgs(""), NewStr("").ToObject(), nil}, {"lower", wrapArgs("a"), NewStr("a").ToObject(), nil}, {"lower", wrapArgs("A"), NewStr("a").ToObject(), nil}, {"lower", wrapArgs(" A"), NewStr(" a").ToObject(), nil}, {"lower", wrapArgs("abc"), NewStr("abc").ToObject(), nil}, {"lower", wrapArgs("ABC"), NewStr("abc").ToObject(), nil}, {"lower", wrapArgs("aBC"), NewStr("abc").ToObject(), nil}, {"lower", wrapArgs("abc def", 123), nil, mustCreateException(TypeErrorType, "'lower' of 'str' requires 1 arguments")}, {"lower", wrapArgs(123), nil, mustCreateException(TypeErrorType, "unbound method lower() must be called with str instance as first argument (got int instance instead)")}, {"lower", wrapArgs("вол"), NewStr("вол").ToObject(), nil}, {"lower", wrapArgs("ВОЛ"), NewStr("ВОЛ").ToObject(), nil}, {"lstrip", wrapArgs("foo "), NewStr("foo ").ToObject(), nil}, {"lstrip", wrapArgs(" foo bar "), NewStr("foo bar ").ToObject(), nil}, {"lstrip", wrapArgs("foo foo", "o"), NewStr("foo foo").ToObject(), nil}, {"lstrip", wrapArgs("foo foo", "f"), NewStr("oo foo").ToObject(), nil}, {"lstrip", wrapArgs("foo bar", "abr"), NewStr("foo bar").ToObject(), nil}, {"lstrip", wrapArgs("foo bar", "fo"), NewStr(" bar").ToObject(), nil}, {"lstrip", wrapArgs("foo", NewUnicode("f")), NewUnicode("oo").ToObject(), nil}, {"lstrip", wrapArgs("123", 3), nil, mustCreateException(TypeErrorType, "strip arg must be None, str or unicode")}, {"lstrip", wrapArgs("foo", "bar", "baz"), nil, mustCreateException(TypeErrorType, "'strip' of 'str' requires 2 arguments")}, {"lstrip", wrapArgs("\xfboo", NewUnicode("o")), nil, mustCreateException(UnicodeDecodeErrorType, "'utf8' codec can't decode byte 0xfb in position 0")}, {"lstrip", wrapArgs("foo", NewUnicode("o")), NewUnicode("f").ToObject(), nil}, {"rfind", wrapArgs("", ""), NewInt(0).ToObject(), nil}, {"rfind", wrapArgs("", "", 1), NewInt(-1).ToObject(), nil}, {"rfind", wrapArgs("", "", -1), NewInt(0).ToObject(), nil}, {"rfind", wrapArgs("", "", None, -1), NewInt(0).ToObject(), nil}, {"rfind", wrapArgs("foobar", "bar"), NewInt(3).ToObject(), nil}, {"rfind", wrapArgs("foobar", "bar", fooType), nil, mustCreateException(TypeErrorType, "slice indices must be integers or None or have an __index__ method")}, {"rfind", wrapArgs("foobar", "bar", NewInt(MaxInt)), NewInt(-1).ToObject(), nil}, {"rfind", wrapArgs("foobar", "bar", None, NewInt(MaxInt)), NewInt(3).ToObject(), nil}, {"rfind", wrapArgs("foobar", "bar", newObject(intIndexType)), NewInt(3).ToObject(), nil}, {"rfind", wrapArgs("foobar", "bar", None, newObject(intIndexType)), NewInt(-1).ToObject(), nil}, {"rfind", wrapArgs("foobar", "bar", newObject(longIndexType)), NewInt(3).ToObject(), nil}, {"rfind", wrapArgs("foobar", "bar", None, newObject(longIndexType)), NewInt(-1).ToObject(), nil}, //r TODO: Support unicode substring. {"rfind", wrapArgs("foobar", NewUnicode("bar")), nil, mustCreateException(TypeErrorType, "'find/index' requires a 'str' object but received a 'unicode'")}, {"rfind", wrapArgs("foobar", "bar", "baz"), nil, mustCreateException(TypeErrorType, "slice indices must be integers or None or have an __index__ method")}, {"rfind", wrapArgs("foobar", "bar", 0, "baz"), nil, mustCreateException(TypeErrorType, "slice indices must be integers or None or have an __index__ method")}, {"rfind", wrapArgs("foobar", "bar", None), NewInt(3).ToObject(), nil}, {"rfind", wrapArgs("foobar", "bar", 0, None), NewInt(3).ToObject(), nil}, {"rfind", wrapArgs("foobar", "bar", 0, -2), NewInt(-1).ToObject(), nil}, {"rfind", wrapArgs("foobar", "foo", 0, 3), NewInt(0).ToObject(), nil}, {"rfind", wrapArgs("foobar", "foo", 10), NewInt(-1).ToObject(), nil}, {"rfind", wrapArgs("foobar", "foo", 3, 3), NewInt(-1).ToObject(), nil}, {"rfind", wrapArgs("foobar", "bar", 3, 5), NewInt(-1).ToObject(), nil}, {"rfind", wrapArgs("foobar", "bar", 5, 3), NewInt(-1).ToObject(), nil}, {"rfind", wrapArgs("bar", "foobar"), NewInt(-1).ToObject(), nil}, {"rfind", wrapArgs("bar", "a", 1, 10), NewInt(1).ToObject(), nil}, {"rfind", wrapArgs("bar", "a", NewLong(big.NewInt(1)), 10), NewInt(1).ToObject(), nil}, {"rfind", wrapArgs("bar", "a", 0, NewLong(big.NewInt(2))), NewInt(1).ToObject(), nil}, {"rfind", wrapArgs("bar", "a", 1, 3), NewInt(1).ToObject(), nil}, {"rfind", wrapArgs("bar", "a", 0, -1), NewInt(1).ToObject(), nil}, {"rfind", wrapArgs("foo", newTestTuple("barfoo", "oo").ToObject()), nil, mustCreateException(TypeErrorType, "'find/index' requires a 'str' object but received a 'tuple'")}, {"rfind", wrapArgs("foo", 123), nil, mustCreateException(TypeErrorType, "'find/index' requires a 'str' object but received a 'int'")}, {"rfind", wrapArgs("barbaz", "ba"), NewInt(3).ToObject(), nil}, {"rfind", wrapArgs("barbaz", "ba", None, 4), NewInt(0).ToObject(), nil}, {"rindex", wrapArgs("", ""), NewInt(0).ToObject(), nil}, {"rindex", wrapArgs("", "", 1), nil, mustCreateException(ValueErrorType, "substring not found")}, {"rindex", wrapArgs("", "", -1), NewInt(0).ToObject(), nil}, {"rindex", wrapArgs("", "", None, -1), NewInt(0).ToObject(), nil}, {"rindex", wrapArgs("foobar", "bar"), NewInt(3).ToObject(), nil}, {"rindex", wrapArgs("foobar", "bar", fooType), nil, mustCreateException(TypeErrorType, "slice indices must be integers or None or have an __index__ method")}, {"rindex", wrapArgs("foobar", "bar", NewInt(MaxInt)), nil, mustCreateException(ValueErrorType, "substring not found")}, {"rindex", wrapArgs("foobar", "bar", None, NewInt(MaxInt)), NewInt(3).ToObject(), nil}, {"rindex", wrapArgs("foobar", "bar", newObject(intIndexType)), NewInt(3).ToObject(), nil}, {"rindex", wrapArgs("foobar", "bar", None, newObject(intIndexType)), nil, mustCreateException(ValueErrorType, "substring not found")}, {"rindex", wrapArgs("foobar", "bar", newObject(longIndexType)), NewInt(3).ToObject(), nil}, {"rindex", wrapArgs("foobar", "bar", None, newObject(longIndexType)), nil, mustCreateException(ValueErrorType, "substring not found")}, // TODO: Support unicode substring. {"rindex", wrapArgs("foobar", NewUnicode("bar")), nil, mustCreateException(TypeErrorType, "'find/index' requires a 'str' object but received a 'unicode'")}, {"rindex", wrapArgs("foobar", "bar", "baz"), nil, mustCreateException(TypeErrorType, "slice indices must be integers or None or have an __index__ method")}, {"rindex", wrapArgs("foobar", "bar", 0, "baz"), nil, mustCreateException(TypeErrorType, "slice indices must be integers or None or have an __index__ method")}, {"rindex", wrapArgs("foobar", "bar", None), NewInt(3).ToObject(), nil}, {"rindex", wrapArgs("foobar", "bar", 0, None), NewInt(3).ToObject(), nil}, {"rindex", wrapArgs("foobar", "bar", 0, -2), nil, mustCreateException(ValueErrorType, "substring not found")}, {"rindex", wrapArgs("foobar", "foo", 0, 3), NewInt(0).ToObject(), nil}, {"rindex", wrapArgs("foobar", "foo", 10), nil, mustCreateException(ValueErrorType, "substring not found")}, {"rindex", wrapArgs("foobar", "foo", 3, 3), nil, mustCreateException(ValueErrorType, "substring not found")}, {"rindex", wrapArgs("foobar", "bar", 3, 5), nil, mustCreateException(ValueErrorType, "substring not found")}, {"rindex", wrapArgs("foobar", "bar", 5, 3), nil, mustCreateException(ValueErrorType, "substring not found")}, {"rindex", wrapArgs("bar", "foobar"), nil, mustCreateException(ValueErrorType, "substring not found")}, {"rindex", wrapArgs("bar", "a", 1, 10), NewInt(1).ToObject(), nil}, {"rindex", wrapArgs("bar", "a", NewLong(big.NewInt(1)), 10), NewInt(1).ToObject(), nil}, {"rindex", wrapArgs("bar", "a", 0, NewLong(big.NewInt(2))), NewInt(1).ToObject(), nil}, {"rindex", wrapArgs("bar", "a", 1, 3), NewInt(1).ToObject(), nil}, {"rindex", wrapArgs("bar", "a", 0, -1), NewInt(1).ToObject(), nil}, {"rindex", wrapArgs("foo", newTestTuple("barfoo", "oo").ToObject()), nil, mustCreateException(TypeErrorType, "'find/index' requires a 'str' object but received a 'tuple'")}, {"rindex", wrapArgs("foo", 123), nil, mustCreateException(TypeErrorType, "'find/index' requires a 'str' object but received a 'int'")}, {"rindex", wrapArgs("barbaz", "ba"), NewInt(3).ToObject(), nil}, {"rindex", wrapArgs("barbaz", "ba", None, 4), NewInt(0).ToObject(), nil}, {"rjust", wrapArgs("foobar", 10, "#"), NewStr("####foobar").ToObject(), nil}, {"rjust", wrapArgs("foobar", 3, "#"), NewStr("foobar").ToObject(), nil}, {"rjust", wrapArgs("foobar", -1, "#"), NewStr("foobar").ToObject(), nil}, {"rjust", wrapArgs("foobar", 10, "##"), nil, mustCreateException(TypeErrorType, "rjust() argument 2 must be char, not str")}, {"rjust", wrapArgs("foobar", 10, ""), nil, mustCreateException(TypeErrorType, "rjust() argument 2 must be char, not str")}, {"split", wrapArgs("foo,bar", ","), newTestList("foo", "bar").ToObject(), nil}, {"split", wrapArgs("1,2,3", ",", 1), newTestList("1", "2,3").ToObject(), nil}, {"split", wrapArgs("a \tb\nc"), newTestList("a", "b", "c").ToObject(), nil}, {"split", wrapArgs("a \tb\nc", None), newTestList("a", "b", "c").ToObject(), nil}, {"split", wrapArgs("a \tb\nc", None, -1), newTestList("a", "b", "c").ToObject(), nil}, {"split", wrapArgs("a \tb\nc", None, 1), newTestList("a", "b\nc").ToObject(), nil}, {"split", wrapArgs("foo", 1), nil, mustCreateException(TypeErrorType, "expected a str separator")}, {"split", wrapArgs("foo", ""), nil, mustCreateException(ValueErrorType, "empty separator")}, {"split", wrapArgs(""), newTestList().ToObject(), nil}, {"split", wrapArgs(" "), newTestList().ToObject(), nil}, {"split", wrapArgs("", "x"), newTestList("").ToObject(), nil}, {"split", wrapArgs(" ", " ", 1), newTestList("", "").ToObject(), nil}, {"split", wrapArgs("aa", "a", 2), newTestList("", "", "").ToObject(), nil}, {"split", wrapArgs(" a ", "a"), newTestList(" ", " ").ToObject(), nil}, {"split", wrapArgs("a b c d", None, 1), newTestList("a", "b c d").ToObject(), nil}, {"split", wrapArgs("a b c d "), newTestList("a", "b", "c", "d").ToObject(), nil}, {"split", wrapArgs(" a b c d ", None, 1), newTestList("a", "b c d ").ToObject(), nil}, {"split", wrapArgs(" a b c d ", None, 0), newTestList("a b c d ").ToObject(), nil}, {"splitlines", wrapArgs(""), NewList().ToObject(), nil}, {"splitlines", wrapArgs("\n"), newTestList("").ToObject(), nil}, {"splitlines", wrapArgs("foo"), newTestList("foo").ToObject(), nil}, {"splitlines", wrapArgs("foo\r"), newTestList("foo").ToObject(), nil}, {"splitlines", wrapArgs("foo\r", true), newTestList("foo\r").ToObject(), nil}, {"splitlines", wrapArgs("foo\r\nbar\n", big.NewInt(12)), newTestList("foo\r\n", "bar\n").ToObject(), nil}, {"splitlines", wrapArgs("foo\n\r\nbar\n\n"), newTestList("foo", "", "bar", "").ToObject(), nil}, {"splitlines", wrapArgs("foo", newObject(ObjectType)), nil, mustCreateException(TypeErrorType, "an integer is required")}, {"splitlines", wrapArgs("foo", "bar", "baz"), nil, mustCreateException(TypeErrorType, "'splitlines' of 'str' requires 2 arguments")}, {"splitlines", wrapArgs("foo", overflowLong), nil, mustCreateException(OverflowErrorType, "Python int too large to convert to a Go int")}, {"startswith", wrapArgs("", ""), True.ToObject(), nil}, {"startswith", wrapArgs("", "", 1), False.ToObject(), nil}, {"startswith", wrapArgs("foobar", "foo"), True.ToObject(), nil}, {"startswith", wrapArgs("foobar", "foo", 2), False.ToObject(), nil}, {"startswith", wrapArgs("foobar", "bar", 3), True.ToObject(), nil}, {"startswith", wrapArgs("foobar", "bar", 3, 5), False.ToObject(), nil}, {"startswith", wrapArgs("foobar", "bar", 5, 3), False.ToObject(), nil}, {"startswith", wrapArgs("foo", "foobar"), False.ToObject(), nil}, {"startswith", wrapArgs("foo", newTestTuple("foobar", "fo").ToObject()), True.ToObject(), nil}, {"startswith", wrapArgs("foo", 123), nil, mustCreateException(TypeErrorType, "startswith first arg must be str, unicode, or tuple, not int")}, {"startswith", wrapArgs("foo", "f", "123"), nil, mustCreateException(TypeErrorType, "'startswith' requires a 'int' object but received a 'str'")}, {"startswith", wrapArgs("foo", newTestTuple(123).ToObject()), nil, mustCreateException(TypeErrorType, "expected a str")}, {"strip", wrapArgs("foo "), NewStr("foo").ToObject(), nil}, {"strip", wrapArgs(" foo bar "), NewStr("foo bar").ToObject(), nil}, {"strip", wrapArgs("foo foo", "o"), NewStr("foo f").ToObject(), nil}, {"strip", wrapArgs("foo bar", "abr"), NewStr("foo ").ToObject(), nil}, {"strip", wrapArgs("foo", NewUnicode("o")), NewUnicode("f").ToObject(), nil}, {"strip", wrapArgs("123", 3), nil, mustCreateException(TypeErrorType, "strip arg must be None, str or unicode")}, {"strip", wrapArgs("foo", "bar", "baz"), nil, mustCreateException(TypeErrorType, "'strip' of 'str' requires 2 arguments")}, {"strip", wrapArgs("\xfboo", NewUnicode("o")), nil, mustCreateException(UnicodeDecodeErrorType, "'utf8' codec can't decode byte 0xfb in position 0")}, {"strip", wrapArgs("foo", NewUnicode("o")), NewUnicode("f").ToObject(), nil}, {"partition", wrapArgs("foo", ""), nil, mustCreateException(ValueErrorType, "empty separator")}, {"partition", wrapArgs("foo", ":"), newTestTuple("foo", "", "").ToObject(), nil}, {"partition", wrapArgs(":foo", ":"), newTestTuple("", ":", "foo").ToObject(), nil}, {"partition", wrapArgs("foo:", ":"), newTestTuple("foo", ":", "").ToObject(), nil}, {"partition", wrapArgs("foo:bar", ":"), newTestTuple("foo", ":", "bar").ToObject(), nil}, {"partition", wrapArgs("foo:bar:zor", ":"), newTestTuple("foo", ":", "bar:zor").ToObject(), nil}, {"rpartition", wrapArgs("foo", ""), nil, mustCreateException(ValueErrorType, "empty separator")}, {"rpartition", wrapArgs("foo", ":"), newTestTuple("", "", "foo").ToObject(), nil}, {"rpartition", wrapArgs(":foo", ":"), newTestTuple("", ":", "foo").ToObject(), nil}, {"rpartition", wrapArgs("foo:", ":"), newTestTuple("foo", ":", "").ToObject(), nil}, {"rpartition", wrapArgs("foo:bar", ":"), newTestTuple("foo", ":", "bar").ToObject(), nil}, {"rpartition", wrapArgs("foo:bar:zor", ":"), newTestTuple("foo:bar", ":", "zor").ToObject(), nil}, {"replace", wrapArgs("one!two!three!", "!", "@", 1), NewStr("one@two!three!").ToObject(), nil}, {"replace", wrapArgs("one!two!three!", "!", ""), NewStr("onetwothree").ToObject(), nil}, {"replace", wrapArgs("one!two!three!", "!", "@", 2), NewStr("one@two@three!").ToObject(), nil}, {"replace", wrapArgs("one!two!three!", "!", "@", 3), NewStr("one@two@three@").ToObject(), nil}, {"replace", wrapArgs("one!two!three!", "!", "@", 4), NewStr("one@two@three@").ToObject(), nil}, {"replace", wrapArgs("one!two!three!", "!", "@", 0), NewStr("one!two!three!").ToObject(), nil}, {"replace", wrapArgs("one!two!three!", "!", "@"), NewStr("one@two@three@").ToObject(), nil}, {"replace", wrapArgs("one!two!three!", "x", "@"), NewStr("one!two!three!").ToObject(), nil}, {"replace", wrapArgs("one!two!three!", "x", "@", 2), NewStr("one!two!three!").ToObject(), nil}, {"replace", wrapArgs("\xd0\xb2\xd0\xbe\xd0\xbb", "", "\x00", -1), NewStr("\x00\xd0\x00\xb2\x00\xd0\x00\xbe\x00\xd0\x00\xbb\x00").ToObject(), nil}, {"replace", wrapArgs("\xd0\xb2\xd0\xbe\xd0\xbb", "", "\x01\x02", -1), NewStr("\x01\x02\xd0\x01\x02\xb2\x01\x02\xd0\x01\x02\xbe\x01\x02\xd0\x01\x02\xbb\x01\x02").ToObject(), nil}, {"replace", wrapArgs("abc", "", "-"), NewStr("-a-b-c-").ToObject(), nil}, {"replace", wrapArgs("abc", "", "-", 3), NewStr("-a-b-c").ToObject(), nil}, {"replace", wrapArgs("abc", "", "-", 0), NewStr("abc").ToObject(), nil}, {"replace", wrapArgs("", "", ""), NewStr("").ToObject(), nil}, {"replace", wrapArgs("", "", "a"), NewStr("a").ToObject(), nil}, {"replace", wrapArgs("abc", "a", "--", 0), NewStr("abc").ToObject(), nil}, {"replace", wrapArgs("abc", "xy", "--"), NewStr("abc").ToObject(), nil}, {"replace", wrapArgs("123", "123", ""), NewStr("").ToObject(), nil}, {"replace", wrapArgs("123123", "123", ""), NewStr("").ToObject(), nil}, {"replace", wrapArgs("123x123", "123", ""), NewStr("x").ToObject(), nil}, {"replace", wrapArgs("one!two!three!", "!", "@", NewLong(big.NewInt(1))), NewStr("one@two!three!").ToObject(), nil}, {"replace", wrapArgs("foobar", "bar", "baz", newObject(intIntType)), NewStr("foobaz").ToObject(), nil}, {"replace", wrapArgs("foobar", "bar", "baz", newObject(longIntType)), NewStr("foobaz").ToObject(), nil}, {"replace", wrapArgs("", "", "x"), NewStr("x").ToObject(), nil}, {"replace", wrapArgs("", "", "x", -1), NewStr("x").ToObject(), nil}, {"replace", wrapArgs("", "", "x", 0), NewStr("").ToObject(), nil}, {"replace", wrapArgs("", "", "x", 1), NewStr("").ToObject(), nil}, {"replace", wrapArgs("", "", "x", 1000), NewStr("").ToObject(), nil}, // TODO: Support unicode substring. {"replace", wrapArgs("foobar", "", NewUnicode("bar")), nil, mustCreateException(TypeErrorType, "'replace' requires a 'str' object but received a 'unicode'")}, {"replace", wrapArgs("foobar", NewUnicode("bar"), ""), nil, mustCreateException(TypeErrorType, "'replace' requires a 'str' object but received a 'unicode'")}, {"replace", wrapArgs("foobar", "bar", "baz", None), nil, mustCreateException(TypeErrorType, "an integer is required")}, {"replace", wrapArgs("foobar", "bar", "baz", newObject(intIndexType)), nil, mustCreateException(TypeErrorType, "an integer is required")}, {"replace", wrapArgs("foobar", "bar", "baz", newObject(longIndexType)), nil, mustCreateException(TypeErrorType, "an integer is required")}, {"rstrip", wrapArgs("foo "), NewStr("foo").ToObject(), nil}, {"rstrip", wrapArgs(" foo bar "), NewStr(" foo bar").ToObject(), nil}, {"rstrip", wrapArgs("foo foo", "o"), NewStr("foo f").ToObject(), nil}, {"rstrip", wrapArgs("foo bar", "abr"), NewStr("foo ").ToObject(), nil}, {"rstrip", wrapArgs("foo", NewUnicode("o")), NewUnicode("f").ToObject(), nil}, {"rstrip", wrapArgs("123", 3), nil, mustCreateException(TypeErrorType, "strip arg must be None, str or unicode")}, {"rstrip", wrapArgs("foo", "bar", "baz"), nil, mustCreateException(TypeErrorType, "'strip' of 'str' requires 2 arguments")}, {"rstrip", wrapArgs("\xfboo", NewUnicode("o")), nil, mustCreateException(UnicodeDecodeErrorType, "'utf8' codec can't decode byte 0xfb in position 0")}, {"rstrip", wrapArgs("foo", NewUnicode("o")), NewUnicode("f").ToObject(), nil}, {"title", wrapArgs(""), NewStr("").ToObject(), nil}, {"title", wrapArgs("a"), NewStr("A").ToObject(), nil}, {"title", wrapArgs("A"), NewStr("A").ToObject(), nil}, {"title", wrapArgs(" a"), NewStr(" A").ToObject(), nil}, {"title", wrapArgs("abc def"), NewStr("Abc Def").ToObject(), nil}, {"title", wrapArgs("ABC DEF"), NewStr("Abc Def").ToObject(), nil}, {"title", wrapArgs("aBC dEF"), NewStr("Abc Def").ToObject(), nil}, {"title", wrapArgs("abc def", 123), nil, mustCreateException(TypeErrorType, "'title' of 'str' requires 1 arguments")}, {"title", wrapArgs(123), nil, mustCreateException(TypeErrorType, "unbound method title() must be called with str instance as first argument (got int instance instead)")}, {"title", wrapArgs("вол"), NewStr("вол").ToObject(), nil}, {"title", wrapArgs("ВОЛ"), NewStr("ВОЛ").ToObject(), nil}, {"upper", wrapArgs(""), NewStr("").ToObject(), nil}, {"upper", wrapArgs("a"), NewStr("A").ToObject(), nil}, {"upper", wrapArgs("A"), NewStr("A").ToObject(), nil}, {"upper", wrapArgs(" a"), NewStr(" A").ToObject(), nil}, {"upper", wrapArgs("abc"), NewStr("ABC").ToObject(), nil}, {"upper", wrapArgs("ABC"), NewStr("ABC").ToObject(), nil}, {"upper", wrapArgs("aBC"), NewStr("ABC").ToObject(), nil}, {"upper", wrapArgs("abc def", 123), nil, mustCreateException(TypeErrorType, "'upper' of 'str' requires 1 arguments")}, {"upper", wrapArgs(123), nil, mustCreateException(TypeErrorType, "unbound method upper() must be called with str instance as first argument (got int instance instead)")}, {"upper", wrapArgs("вол"), NewStr("вол").ToObject(), nil}, {"upper", wrapArgs("ВОЛ"), NewStr("ВОЛ").ToObject(), nil}, {"zfill", wrapArgs("123", 2), NewStr("123").ToObject(), nil}, {"zfill", wrapArgs("123", 3), NewStr("123").ToObject(), nil}, {"zfill", wrapArgs("123", 4), NewStr("0123").ToObject(), nil}, {"zfill", wrapArgs("+123", 3), NewStr("+123").ToObject(), nil}, {"zfill", wrapArgs("+123", 4), NewStr("+123").ToObject(), nil}, {"zfill", wrapArgs("+123", 5), NewStr("+0123").ToObject(), nil}, {"zfill", wrapArgs("-123", 3), NewStr("-123").ToObject(), nil}, {"zfill", wrapArgs("-123", 4), NewStr("-123").ToObject(), nil}, {"zfill", wrapArgs("-123", 5), NewStr("-0123").ToObject(), nil}, {"zfill", wrapArgs("123", NewLong(big.NewInt(3))), NewStr("123").ToObject(), nil}, {"zfill", wrapArgs("123", NewLong(big.NewInt(5))), NewStr("00123").ToObject(), nil}, {"zfill", wrapArgs("", 0), NewStr("").ToObject(), nil}, {"zfill", wrapArgs("", 1), NewStr("0").ToObject(), nil}, {"zfill", wrapArgs("", 3), NewStr("000").ToObject(), nil}, {"zfill", wrapArgs("", -1), NewStr("").ToObject(), nil}, {"zfill", wrapArgs("34", 1), NewStr("34").ToObject(), nil}, {"zfill", wrapArgs("34", 4), NewStr("0034").ToObject(), nil}, {"zfill", wrapArgs("34", None), nil, mustCreateException(TypeErrorType, "an integer is required")}, {"zfill", wrapArgs("", True), NewStr("0").ToObject(), nil}, {"zfill", wrapArgs("", False), NewStr("").ToObject(), nil}, {"zfill", wrapArgs("34", NewStr("test")), nil, mustCreateException(TypeErrorType, "an integer is required")}, {"zfill", wrapArgs("34"), nil, mustCreateException(TypeErrorType, "'zfill' of 'str' requires 2 arguments")}, {"swapcase", wrapArgs(""), NewStr("").ToObject(), nil}, {"swapcase", wrapArgs("a"), NewStr("A").ToObject(), nil}, {"swapcase", wrapArgs("A"), NewStr("a").ToObject(), nil}, {"swapcase", wrapArgs(" A"), NewStr(" a").ToObject(), nil}, {"swapcase", wrapArgs("abc"), NewStr("ABC").ToObject(), nil}, {"swapcase", wrapArgs("ABC"), NewStr("abc").ToObject(), nil}, {"swapcase", wrapArgs("aBC"), NewStr("Abc").ToObject(), nil}, {"swapcase", wrapArgs("abc def", 123), nil, mustCreateException(TypeErrorType, "'swapcase' of 'str' requires 1 arguments")}, {"swapcase", wrapArgs(123), nil, mustCreateException(TypeErrorType, "unbound method swapcase() must be called with str instance as first argument (got int instance instead)")}, {"swapcase", wrapArgs("вол"), NewStr("вол").ToObject(), nil}, {"swapcase", wrapArgs("ВОЛ"), NewStr("ВОЛ").ToObject(), nil}, } for _, cas := range cases { testCase := invokeTestCase{args: cas.args, want: cas.want, wantExc: cas.wantExc} if err := runInvokeMethodTestCase(StrType, cas.methodName, &testCase); err != "" { t.Error(err) } } } func TestStrStr(t *testing.T) { cases := []invokeTestCase{ {args: wrapArgs("foo"), want: NewStr("foo").ToObject()}, {args: wrapArgs("on\nmultiple\nlines"), want: NewStr("on\nmultiple\nlines").ToObject()}, {args: wrapArgs("\x00\x00"), want: NewStr("\x00\x00").ToObject()}, } for _, cas := range cases { if err := runInvokeMethodTestCase(StrType, "__str__", &cas); err != "" { t.Error(err) } } }
package adapter import ( "github.com/giantswarm/aws-operator/service/controller/clusterapi/v30/key" ) type GuestIAMPoliciesAdapter struct { ClusterID string EC2ServiceDomain string KMSKeyARN string MasterRoleName string MasterPolicyName string MasterProfileName string RegionARN string S3Bucket string } func (i *GuestIAMPoliciesAdapter) Adapt(cfg Config) error { clusterID := key.ClusterID(&cfg.CustomObject) i.ClusterID = clusterID i.EC2ServiceDomain = key.EC2ServiceDomain(cfg.AWSRegion) i.MasterPolicyName = key.PolicyNameMaster(cfg.CustomObject) i.MasterProfileName = key.ProfileNameMaster(cfg.CustomObject) i.MasterRoleName = key.RoleNameMaster(cfg.CustomObject) i.RegionARN = key.RegionARN(cfg.AWSRegion) i.KMSKeyARN = cfg.TenantClusterKMSKeyARN i.S3Bucket = key.BucketName(&cfg.CustomObject, cfg.TenantClusterAccountID) return nil }
package model // Номенклатура type Nomenclature struct { Id int MeasureId int Name string }
package mongo import ( "config" "errors" "fmt" "lebangproto" "logger" "strconv" "strings" "sync" "time" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type MongoManager struct { session []*mgo.Session index int lockGuard sync.Mutex } func (this *MongoManager) updateErrandsMainClassification() { logger.LOGLINE("update errands main classification") if !this.IsCollExist(config.DB().DBName, config.DB().CollMap["errandsclassification"]) { this.Insert(config.DB().DBName, config.DB().CollMap["errandsclassification"], &lebangproto.ErrandsClassification{Classification: "main", Labels: config.DB().ErrandsClassification["labels"], Hint: config.DB().ErrandsClassification["hint"]}) } else { this.Update(config.DB().DBName, config.DB().CollMap["errandsclassification"], bson.M{"Classification": "main"}, &lebangproto.ErrandsClassification{Classification: "main", Labels: config.DB().ErrandsClassification["labels"], Hint: config.DB().ErrandsClassification["hint"]}) } } func (this *MongoManager) updateErrandsSubClassification() { logger.LOGLINE("errands sub classification") errandsLabels := strings.Split(config.DB().ErrandsClassification["labels"], " ") for _, classification := range errandsLabels { if !this.IsExist(config.DB().DBName, config.DB().CollMap["errandssubclassification"], bson.M{"classification": classification}) { this.Insert(config.DB().DBName, config.DB().CollMap["errandssubclassification"], &lebangproto.ErrandsClassification{Classification: classification, Labels: config.DB().ErrandsSubClassification[classification]["labels"], Hint: config.DB().ErrandsSubClassification[classification]["hint"]}) } else { this.Update(config.DB().DBName, config.DB().CollMap["errandssubclassification"], bson.M{"classification": classification}, &lebangproto.ErrandsClassification{Classification: classification, Labels: config.DB().ErrandsSubClassification[classification]["labels"], Hint: config.DB().ErrandsSubClassification[classification]["hint"]}) } } } func (this *MongoManager) updateClassificationView() { logger.LOGLINE("update classificationview") for name, types := range config.DB().ClassificationView { if !this.IsExist(config.DB().DBName, config.DB().CollMap["classificationview"], bson.M{"name": name}) { this.Insert(config.DB().DBName, config.DB().CollMap["classificationview"], &lebangproto.ClassificationView{Name: name, Typeids: types}) } else { this.Update(config.DB().DBName, config.DB().CollMap["classificationview"], bson.M{"name": name}, &lebangproto.ClassificationView{Name: name, Typeids: types}) } } } func (this *MongoManager) updateClassification() { logger.LOGLINE("update classification") for name, typeidstr := range config.DB().Classification { if !this.IsExist(config.DB().DBName, config.DB().CollMap["classification"], bson.M{"name": name}) { typeid, _ := strconv.Atoi(typeidstr) this.Insert(config.DB().DBName, config.DB().CollMap["classification"], &lebangproto.Classification{Name: name, Typeid: int32(typeid)}) } else { typeid, _ := strconv.Atoi(typeidstr) this.Update(config.DB().DBName, config.DB().CollMap["classification"], bson.M{"name": name}, &lebangproto.Classification{Name: name, Typeid: int32(typeid)}) } } } func (this *MongoManager) updateSubClassification() { logger.LOGLINE("update sub classification") for name, subinfostr := range config.DB().SubClassification { if !this.IsExist(config.DB().DBName, config.DB().CollMap["subclassification"], bson.M{"name": name}) { subinfo := strings.Split(subinfostr, " ") parenttypeid, _ := strconv.Atoi(subinfo[0]) typeid, _ := strconv.Atoi(subinfo[1]) this.Insert(config.DB().DBName, config.DB().CollMap["subclassification"], &lebangproto.SubClassification{Name: name, Typeid: int32(typeid), Parenttypeid: int32(parenttypeid), Image: subinfo[2]}) } else { subinfo := strings.Split(subinfostr, " ") parenttypeid, _ := strconv.Atoi(subinfo[0]) typeid, _ := strconv.Atoi(subinfo[1]) this.Update(config.DB().DBName, config.DB().CollMap["subclassification"], bson.M{"name": name}, &lebangproto.SubClassification{Name: name, Typeid: int32(typeid), Parenttypeid: int32(parenttypeid), Image: subinfo[2]}) } } } func (this *MongoManager) Init(addrs string, port string) error { addr := fmt.Sprintf("%s:%s", addrs, port) session, err := mgo.Dial(addr) if err != nil { logger.PRINTLINE("open mongodb error:", err) } else { session.SetSocketTimeout(100 * time.Hour) session.SetMode(mgo.Monotonic, true) this.session = append(this.session, session) logger.LOGLINE("mongodb connect ", addrs, " success!") } // update errands main classification this.updateErrandsMainClassification() // update errands sub classification this.updateErrandsSubClassification() // update classificationview this.updateClassificationView() // update classification this.updateClassification() // update sub classification this.updateSubClassification() if len(this.session) > 0 { return nil } return errors.New("all mysql connect error!") } func (this *MongoManager) Close() { for _, node := range this.session { if node != nil { node.Close() } } } func (this *MongoManager) GetDB(name string) *mgo.Database { this.lockGuard.Lock() defer this.lockGuard.Unlock() return this.session[this.index].DB(name) } func NewMongoManager(addrs string, port string) *MongoManager { instance := MongoManager{ session: nil, index: 0, } if instance.Init(addrs, port) == nil { return &instance } else { return nil } }
package cmd import ( "fmt" "log" "os" "path/filepath" "github.com/lhopki01/dirin/internal/color" "github.com/lhopki01/dirin/internal/config" "github.com/spf13/cobra" "github.com/spf13/viper" ) func registerAddCmd(rootCmd *cobra.Command) { addCmd := &cobra.Command{ Use: "add <space separated list of directories>", Short: "Add a list directories to a collection", Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { runAddCmd(args) }, } rootCmd.AddCommand(addCmd) addCmd.Flags().String("collection", "", "The collection to add directories too") viper.BindPFlag("collectionAdd", addCmd.Flags().Lookup("collection")) } func runAddCmd(args []string) { collection, err := config.GetCollection("collectionAdd") if err != nil { log.Fatal(err) } c, f, err := config.LoadCollection(collection) if err != nil { if os.IsNotExist(err) { fmt.Printf("Collection %s does not exit. Please choose from: %v\n", collection, getCollections()) fmt.Println("Or create the collection using dirin create <collection name>") os.Exit(1) } log.Fatal(err) } usedColors := c.GetUsedColors() dirs := []*config.Dir{} for _, dir := range args { if stat, err := os.Stat(dir); err == nil && stat.IsDir() { absoluteFilePath, err := filepath.Abs(dir) if err != nil { fmt.Printf("Can't find absolute filepath for %s\n", dir) } else { newColor := 15 usedColors, newColor = color.NewColor(usedColors) newDir := &config.Dir{ Path: absoluteFilePath, Color: newColor, Name: filepath.Base(dir), } dirs = append(dirs, newDir) } fmt.Printf("Adding %s\n", dir) } else { fmt.Printf("%s is not a dir\n", dir) } } c.AddDirectoriesToCollection(dirs, f) }
package strategyPattern import ( "design-patterns-go/strategyPattern/duck" "fmt" ) type StrategyPattern interface { Run() } type strategy struct { strategyPattern StrategyPattern } func NewStrategy() strategy { return strategy{} } func (st strategy) Run() { fmt.Println("~~~~~~~~~~ STRATEGY PATTERN ~~~~~~~~~~~~~") mallardDuck := duck.NewMallardDuck() fmt.Println("name : ", mallardDuck.Display()) fmt.Println("swim : ", mallardDuck.Swim()) fmt.Println("fly : ", mallardDuck.Fly()) rubberDuck := duck.NewRubberDuck() fmt.Println("name : ", rubberDuck.Display()) fmt.Println("swim : ", rubberDuck.Swim()) fmt.Println("fly : ", rubberDuck.Fly()) }
package "make-collection"
package router import ( "github.com/kataras/iris" "github.com/kataras/iris/middleware/recover" "github.com/iris-contrib/middleware/cors" "../config" "../controller" controller_admin "../controller/admin" "time" "github.com/kataras/iris/middleware/basicauth" ) func Routes(app *iris.Application) { // use recover(y) middleware, to prevent crash all app on request app.Use(recover.New()) var origins []string = []string{"*"} crs := cors.New(cors.Options{ AllowedOrigins: origins, // allows everything, use that to change the hosts. AllowedHeaders: []string{"*"}, AllowCredentials: true, // Debug: true, }) root := app.Party("/", crs).AllowMethods(iris.MethodOptions) // <- important for the preflight. captchaRoute := root.Party("/captcha") captchaRoute.Get("/id", controller.CaptchaId) captchaRoute.Get("/{captcha}", controller.CaptchaMedia) root.Get("/whitelist/confirm_email", controller.WhitelistConfirmEmail) root.Post("/whitelist/request", iris.LimitRequestBodySize((config.Config.MaxFileUploadSizeMb*3)<<20), controller.WhitelistRequest) // admin section authConfig := basicauth.Config{ Users: map[string]string{config.Config.AdminLogin: config.Config.AdminPassword}, Realm: "Authorization Required", // defaults to "Authorization Required" Expires: time.Duration(1) * time.Minute, } authentication := basicauth.New(authConfig) admin := root.Party("/admin", authentication) { admin.Get("/basic-auth", func(ctx iris.Context) {}) // to check auth admin.Get("/whitelist/list", controller_admin.GetWhitelistList) admin.Post("/whitelist/accept/{id:int min(1)}", controller_admin.WhitelistAccept) admin.Post("/whitelist/decline/{id:int min(1)}", controller_admin.WhitelistDecline) admin.Post("/whitelist/question/{id:int min(1)}", controller_admin.WhitelistQuestion) } }
package backend import ( "encoding/json" "fmt" "html/template" "math" "net/http" "os" "path/filepath" "github.com/TheAndruu/git-leaderboard/models" "golang.org/x/net/context" "google.golang.org/appengine" "google.golang.org/appengine/log" ) var templates = make(map[string]*template.Template) var numCommitsToSave = 10 func init() { initializeTemplates() defineRoutes() } func defineRoutes() { http.HandleFunc("/repostats", saveRepoPost) http.HandleFunc("/recently-submitted", showRecentlySubmitted) http.HandleFunc("/most-commits", showMostCommits) http.HandleFunc("/most-authors", showMostAuthors) http.HandleFunc("/most-single-author", showMostSingleAuthor) http.HandleFunc("/lead-author-highest-percent", showLeadAuthorHighestPercent) http.HandleFunc("/highest-average-commits", showHighestAverageCommits) http.HandleFunc("/lowest-standard-deviation", showLowestStandardDeviation) http.HandleFunc("/least-coefficient-variation", showLeastCoefficientVariation) http.HandleFunc("/", showHome) } // Base template is 'theme.html' Can add any variety of content fillers in /layouts directory func initializeTemplates() { layouts, err := filepath.Glob("static/templates/*.html") if err != nil { fmt.Fprintln(os.Stderr, "Issue setting up templates ", err) } for _, layout := range layouts { templates[filepath.Base(layout)] = template.Must(template.ParseFiles(layout, "static/templates/layouts/theme.html")) } } func saveRepoPost(w http.ResponseWriter, r *http.Request) { ctx := appengine.NewContext(r) log.Infof(ctx, "Saving repo stats") target := models.RepoStats{} json.NewDecoder(r.Body).Decode(&target) defer r.Body.Close() // TODO: Add validation on the fields of the struct - strip out anything not valid computeStats(ctx, &target) // Save the data log.Infof(ctx, fmt.Sprintf("Accepting repo name: %v", target.RepoName)) id, err := SaveStats(ctx, &target) if err != nil { log.Errorf(ctx, "Issue saving stats to datastore %v", err) w.Header().Set("Content-Type", "application/json") w.WriteHeader(420) values := map[string]string{"message": "Issue saving git stats to database"} asBytes, _ := json.Marshal(values) w.Write(asBytes) return } // Write content-type, statuscode, payload log.Infof(ctx, fmt.Sprintf("Created stats with id %v", id)) w.Header().Set("Content-Type", "application/json") w.WriteHeader(201) values := map[string]string{"message": fmt.Sprintf("Successfully stored stats for %s", target.RepoName)} asBytes, _ := json.Marshal(values) w.Write(asBytes) } func computeStats(ctx context.Context, stats *models.RepoStats) { var totalCommits int var authorCount int var leadAuthorTotal int for _, stat := range stats.Commits { // Sum the total number of commits totalCommits += stat.NumCommits // Sum the total number of authors authorCount++ // Ensure we set the max commit value if stat.NumCommits > leadAuthorTotal { leadAuthorTotal = stat.NumCommits } } // calculate mean and percent totalCommitFloat := float64(totalCommits) leadAuthorPercent := float64(leadAuthorTotal) / totalCommitFloat averageAuthorCommits := totalCommitFloat / float64(authorCount) // calculate standard deviation // https://www.mathsisfun.com/data/standard-deviation-formulas.html var sumOfSquaredDifferencesFromMean float64 for _, stat := range stats.Commits { diffFromMean := float64(stat.NumCommits) - averageAuthorCommits sumOfSquaredDifferencesFromMean += math.Pow(diffFromMean, 2) } meanOfSquaredDifferences := sumOfSquaredDifferencesFromMean / float64(authorCount) commitDeviation := math.Sqrt(meanOfSquaredDifferences) // set the values on the struct stats.AuthorCount = authorCount stats.AverageAuthorCommits = averageAuthorCommits stats.LeadAuthorPercent = leadAuthorPercent stats.LeadAuthorTotal = leadAuthorTotal stats.TotalCommits = totalCommits stats.CommitDeviation = commitDeviation stats.CoefficientVariation = commitDeviation / averageAuthorCommits if len(stats.Commits) > numCommitsToSave { stats.Commits = stats.Commits[:numCommitsToSave] } }
/* Given 2 strings, return their concatenation, except omit the first char of each. */ package main import ( "fmt" ) func non_start(a string, b string) string { if len(a) > 0 { a = a[1:] } if len(b) > 0 { b = b[1:] } return a + b } func main(){ var status int = 0 if non_start("Hello", "There") == "ellohere" { status += 1 } if non_start("j", "code") == "ode" { status += 1 } if non_start("TDD", "") == "DD" { status += 1 } if status == 3 { fmt.Println("OK") } else { fmt.Println("NOT OK") } }
package ekshealthtest import ( "context" "database/sql" "fmt" "os" "strings" "time" _ "github.com/lib/pq" // As suggested by lib/pq driver "github.com/olivere/elastic" ) func ESHealth() (string, int) { errs := 0 esProto := os.Getenv("ES_PROTO") esHost := os.Getenv("ES_HOST") esPort := os.Getenv("ES_PORT") connectionString := esProto + "://" + esHost + ":" + esPort connectionStringRedacted := connectionString outStr := "ElasticSearch connection string: " + connectionStringRedacted + "\n" ctx := context.Background() client, err := elastic.NewClient( elastic.SetURL(connectionString), elastic.SetSniff(false), //elastic.SetScheme("https"), ) outStr += fmt.Sprintf("Connection result:\nConnection: '%+v'\n", client) if err != nil { outStr += fmt.Sprintf("Error: '%+v'\n", err) errs++ return outStr, errs } info, code, err := client.Ping(connectionString).Do(ctx) outStr += fmt.Sprintf("Ping:\nInfo: '%+v'\nCode: '%+v'\n", info, code) if err != nil { outStr += fmt.Sprintf("Error: '%+v'\n", err) errs++ return outStr, errs } outStr += fmt.Sprintf("ElasticSearch version %s\n", info.Version.Number) return outStr, errs } func PgHealth() (string, int) { errs := 0 expectedStr := "hello" pgHost := os.Getenv("PG_HOST") pgPort := os.Getenv("PG_PORT") pgDB := os.Getenv("PG_DB") pgUser := os.Getenv("PG_USER") pgPass := os.Getenv("PG_PASS") pgSSL := os.Getenv("PG_SSL") pgPassRedacted := fmt.Sprintf("len=%d", len(pgPass)) connectionString := "client_encoding=UTF8 sslmode='" + pgSSL + "' host='" + pgHost + "' port=" + pgPort + " dbname='" + pgDB + "' user='" + pgUser + "' password='" + pgPass + "'" connectionStringRedacted := strings.Replace(connectionString, "password='"+pgPass+"'", "password='"+pgPassRedacted+"'", -1) outStr := "Postgres connection string: " + connectionStringRedacted + "\n" con, err := sql.Open("postgres", connectionString) conRedacted := strings.Replace(fmt.Sprintf("%+v", con), "password='"+pgPass+"'", "password='"+pgPassRedacted+"'", -1) outStr += fmt.Sprintf("Connection result:\nConnection: '%+v'\n", conRedacted) if err != nil { outStr += fmt.Sprintf("Error: '%+v'\n", err) errs++ } rows, err := con.Query("select now(), $1, usename from pg_user where usename = $2", expectedStr, pgUser) if err == nil { outStr += fmt.Sprintf("Query OK\nRows: '%+v'\n", err) var ( now time.Time str string user string ) for rows.Next() { err = rows.Scan(&now, &str, &user) if err != nil { outStr += fmt.Sprintf("Row scan error: '%+v'\n", err) errs++ } else { outStr += fmt.Sprintf("Scanned: '%+v', %s, %s\n", now, str, user) } } if str != expectedStr { outStr += fmt.Sprintf("Error: expected to scan '%s', scanned '%s'\n", expectedStr, str) errs++ } if user != pgUser { outStr += fmt.Sprintf("Error: expected to scan '%s', scanned '%s'\n", pgUser, user) errs++ } err = rows.Err() if err != nil { outStr += fmt.Sprintf("Rows error: '%+v'\n", err) errs++ } err = rows.Close() if err != nil { outStr += fmt.Sprintf("Rows close error: '%+v'\n", err) errs++ } } else { outStr += fmt.Sprintf("Query error: '%+v'\n", err) errs++ } return outStr, errs }
package reading import ( "encoding/json" "fmt" "log" "github.com/brittonhayes/godb/pkg/types" scribble "github.com/nanobox-io/golang-scribble" ) // One reads an entry from the database func One(db *scribble.Driver, folder string, file string, entry *types.Fish) error { result := entry response := db.Read(folder, file, &result) if response != nil { log.Fatal("Error", response) } fmt.Printf("\nREAD:\n\n") fmt.Printf(" Collection: %v\n", folder) fmt.Printf(" Object: %v\n", file) fmt.Printf(" Data: %+v\n", entry) return response } // All reads all entries from the database, unmarshaling the response. func All(db *scribble.Driver) []types.Fish { records, err := db.ReadAll("fish") if err != nil { log.Fatal("Error", err) } results := []types.Fish{} for _, f := range records { resultFound := types.Fish{} if err := json.Unmarshal([]byte(f), &resultFound); err != nil { fmt.Println("Error", err) } results = append(results, resultFound) fmt.Printf("\nREAD:\n\n") fmt.Printf(" DATA: %v\n", resultFound) } return results }
package handlers import ( "encoding/json" "fmt" "net/http" "test_server/domain" "test_server/storage" ) type TaskHandlers struct{ storage storage.Storage } func NewTaskHandlers(store storage.Storage) TaskHandlers{ return TaskHandlers{ storage: store, } } func (th TaskHandlers) GetAllTasks(w http.ResponseWriter, r *http.Request){ if r.Method != http.MethodGet{ w.WriteHeader(http.StatusBadRequest) return } tasks, err := th.storage.GetAllTasks() if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, "Cannot get tasks due to: ", err.Error()) } data, err := json.Marshal(tasks) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, "Cannot marshal tasks due to: ", err.Error()) } w.WriteHeader(http.StatusOK) fmt.Fprintln(w, string(data)) return } func (th TaskHandlers) CreateTask(w http.ResponseWriter, r *http.Request){ if r.Method != http.MethodPost{ w.WriteHeader(http.StatusBadRequest) return } var task domain.Task decoder := json.NewDecoder(r.Body) err := decoder.Decode(&task) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, "Cannot decode request body due to: ", err.Error()) } task, err = th.storage.CreateTask(task) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, "Cannot create task due to: ", err.Error()) } data, err := json.Marshal(task) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, "Cannot marshal tasks due to: ", err.Error()) } w.WriteHeader(http.StatusOK) fmt.Fprintln(w, string(data)) return }
package main import ( "math" "fmt" ) func main () { fmt.Println(Fib_3(100)) // 没有限定 n 的最大值, 会溢出 } /** * fibonacci 数列满足 f(0) = 0, f(1) = 1, f(n) = f(n-1) + f(n-2) (n>=2, *) * 最小允许计算 f(0), 所以递归出口的判断条件应该是 n < 2 或 n == 0 * 尾递归一般是把这一次的计算结果保存在参数里,递推到下一次调用然后直接使用这个保存值. 但是初始调用时这个参数值就要是明确的。在 fib_1 里需要的初始参数值就是 (n, f(0), f(1)) */ /** * 普通递归 * fn = f(n-1) + f(n-2), 递归出口应该放在当 n < 2 的时候 */ func Fib_0 (n int) int { if (n <= 1) { return n } return Fib_0(n-1) + Fib_0(n-2) } /** * 普通递归的优化 * fib_0 里会有大量重复计算,比如 fib_0(10) 会进行 2 次 fib_0 (8) 的计算, 会进行 3 次 fib_0 (7) 计算 * 可以把计算过的结果存起来 */ var tmp = make(map[int]int) // 注意判断最大值... func Fib_0_enhanced(n int) int { if (n <= 1) { return n } if _, ok := tmp[n]; ok { return tmp[n] } tmp[n] = Fib_0_enhanced(n-1) + Fib_0_enhanced(n-2) return tmp[n] } /** * 尾递归 * n 递减,但是初始调用必须提供 r1 和 r2 (accumulator - 累加器), 所以从 f(0) + (f1) 开始算递增, f(0) + f(1) + ... + f(n-2) + f(n-1) * 初始调用为 fib_1(n, f(0), f(1)) */ func Fib_1 (n int, r1 int, r2 int) int{ if (n == 0) { return r1 } return Fib_1(n-1, r2, r1+r2) } /** * 迭代 */ func Fib_2(n int) int { if (n <= 1) { return n } tmp := map[int]int{0:0, 1:1} for i := 2; i <=n; i++ { tmp[i] = tmp[i-1] + tmp[i-2] } return tmp[n] } /** * 通项公式求解 * 数学比较差.. 就不推导了 */ func Fib_3(n int) int { sq5 := math.Sqrt(5) coeff := 1 / sq5 m := math.Pow(((1 + sq5) / 2), float64(n)) - math.Pow(((1 - sq5) / 2), float64(n)) return int(coeff * m) } /** * 矩阵快速幂优化递推求解 */ func Fib_4(n int) int { return 0 // TODO keep updating }
package main import ( "context" "fmt" "log" "sync" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/push" ) // PrometheusConfig describes the YAML-provided configuration for a Prometheus // pushgateway storage backend type PrometheusConfig struct { Host string `yaml:"host"` Port int `yaml:"port"` Namespace string `yaml:"metric-namespace,omitempty"` } // PrometheusStorage holds the configuration for a Graphite storage backend type PrometheusStorage struct { Namespace string Registry *prometheus.Registry url string } // NewPrometheusStorage sets up a new Prometheus storage backend func NewPrometheusStorage(c *Config) PrometheusStorage { p := PrometheusStorage{} p.Namespace = c.Storage.Prometheus.Namespace p.url = fmt.Sprint(c.Storage.Prometheus.Host, ":", c.Storage.Prometheus.Port) p.Registry = prometheus.NewRegistry() return p } // StartStorageEngine creates a goroutine loop to receive metrics and send // them off to a Prometheus pushgateway func (p PrometheusStorage) StartStorageEngine(ctx context.Context, wg *sync.WaitGroup) (chan<- Metric, chan<- Event) { // We're going to declare eventChan here but not initialize the channel because Prometheus // storage doesn't support Events, only Metrics. We should never receive an Event on this // channel and if something mistakenly sends one, the program will panic. var eventChan chan<- Event // We *do* support Metrics, so we'll initialize this as a buffered channel metricChan := make(chan Metric, 10) // Start processing the metrics we receive go p.processMetrics(ctx, wg, metricChan) return metricChan, eventChan } func (p PrometheusStorage) processMetrics(ctx context.Context, wg *sync.WaitGroup, mchan <-chan Metric) { wg.Add(1) defer wg.Done() for { select { case m := <-mchan: err := p.sendMetric(m) if err != nil { log.Println(err) } case <-ctx.Done(): log.Println("Cancellation request received. Cancelling metrics processor.") return } } } // sendMetric sends a metric value to Prometheus func (p PrometheusStorage) sendMetric(m Metric) error { var metricName string grouping := make(map[string]string) if p.Namespace == "" { metricName = fmt.Sprintf("crabby.%v", m.Name) grouping = push.HostnameGroupingKey() } else { metricName = fmt.Sprintf("%v.%v", p.Namespace, m.Name) grouping["crabby"] = p.Namespace } pm := prometheus.NewGauge(prometheus.GaugeOpts{ Name: metricName, Help: "Crabby timing metric, in milliseconds", }) pm.Set(m.Value) p.Registry.MustRegister(pm) push.AddFromGatherer("crabby", grouping, p.url, p.Registry) return nil } // sendEvent is necessary to implement the StorageEngine interface. func (p PrometheusStorage) sendEvent(e Event) error { var err error return err }
package sqlc import ( "bytes" "database/sql" "errors" "fmt" "github.com/alokmenghrajani/sqlc/meta" "io/ioutil" "log" "os" "regexp" "strings" "text/template" "time" ) var integer = regexp.MustCompile("(?i)INT") var int_64 = regexp.MustCompile("(?i)INTEGER|BIGINT") var varchar = regexp.MustCompile("(?i)VARCHAR|CHARACTER VARYING|TEXT") var ts = regexp.MustCompile("(?i)TIMESTAMP|DATETIME") var dbType = regexp.MustCompile("mysql|postgres|sqlite") type Provenance struct { Version string Timestamp time.Time } type TableMeta struct { Name string Fields []FieldMeta } type FieldMeta struct { Name string Type string } type Options struct { File string `short:"f" long:"file" description:"The path to the sqlite file"` Url string `short:"u" long:"url" description:"The DB URL"` Output string `short:"o" long:"output" description:"The path to save the generated objects to" required:"true"` Package string `short:"p" long:"package" description:"The package to put the generated objects into" required:"true"` Type string `short:"t" long:"type" description:"The type of the DB (mysql,postgres,sqlite)" required:"true"` Schema string `short:"s" long:"schema" description:"The target DB schema (required for MySQL and Postgres)"` Version func() `short:"V" long:"version" description:"Print sqlc version and exit"` Dialect Dialect } func (o *Options) DbType() (Dialect, error) { switch o.Type { case "sqlite": return Sqlite, nil case "mysql": return MySQL, nil case "postgres": return Postgres, nil default: return Sqlite, errors.New("Invalid Db type") } } func (o *Options) Validate() error { if !dbType.MatchString(o.Type) { return errors.New("Invalid DB type") } d, err := o.DbType() if err != nil { return err } switch d { case MySQL, Postgres: if o.Schema == "" { return errors.New("Must specify a target schema") } } if o.File == "" && o.Url == "" { return errors.New("Must specify EITHER file path for sqlite OR url to DB") } if o.File != "" && o.Url != "" { return errors.New("Cannot specify BOTH file path for sqlite AND url to DB") } return nil } func Generate(db *sql.DB, version string, opts *Options) error { tables, err := opts.Dialect.metadata(opts.Schema, db) if err != nil { return err } provenance := Provenance{ Version: version, Timestamp: time.Now(), } params := make(map[string]interface{}) params["Tables"] = tables params["Package"] = opts.Package params["Types"] = meta.Types params["Provenance"] = provenance m := template.FuncMap{ "toLower": strings.ToLower, "toUpper": strings.ToUpper, } schemaBin, _ := sqlc_tmpl_schema_tmpl() t := template.Must(template.New("schema.tmpl").Funcs(m).Parse(string(schemaBin))) var b bytes.Buffer t.Execute(&b, params) if err := ioutil.WriteFile(opts.Output, b.Bytes(), os.ModePerm); err != nil { log.Fatalf("Could not write templated file: %s", err) return err } return nil } func (d Dialect) metadata(schema string, db *sql.DB) ([]TableMeta, error) { switch d { case Sqlite: return sqlite(db) case MySQL: return infoSchema(MySQL, schema, db) case Postgres: return infoSchema(Postgres, schema, db) default: return nil, errors.New("Unsupported dialect") } } func infoSchema(d Dialect, schema string, db *sql.DB) ([]TableMeta, error) { rows, err := db.Query(infoTableSQL(d), schema) if err != nil { return nil, err } tables := make([]TableMeta, 0) for rows.Next() { var t TableMeta rows.Scan(&t.Name) tables = append(tables, t) } for i, table := range tables { rows, err = db.Query(infoColumnsSQL(d), schema, table.Name) if err != nil { return nil, err } fields := make([]FieldMeta, 0) for rows.Next() { var colName, colType sql.NullString err = rows.Scan(&colName, &colType) if err != nil { return nil, err } var fieldType string if int_64.MatchString(colType.String) { fieldType = "Int64" } else if integer.MatchString(colType.String) { fieldType = "Int" } else if varchar.MatchString(colType.String) { fieldType = "String" } else if ts.MatchString(colType.String) { fieldType = "Time" } field := FieldMeta{Name: colName.String, Type: fieldType} fields = append(fields, field) } tables[i].Fields = fields } return tables, nil } func sqlite(db *sql.DB) ([]TableMeta, error) { rows, err := db.Query("SELECT name FROM sqlite_master where type = 'table' and name NOT IN ('sqlite_sequence','schema_versions');") if err != nil { return nil, err } tables := make([]TableMeta, 0) for rows.Next() { var t TableMeta rows.Scan(&t.Name) tables = append(tables, t) } for i, table := range tables { pragma := fmt.Sprintf("PRAGMA table_info(%s);", table.Name) rows, err = db.Query(pragma) if err != nil { return nil, err } fields := make([]FieldMeta, 0) for rows.Next() { var notNull sql.NullBool var id, pk sql.NullInt64 var colName, colType, defaultValue sql.NullString err = rows.Scan(&id, &colName, &colType, &notNull, &defaultValue, &pk) if err != nil { return nil, err } var fieldType string if int_64.MatchString(colType.String) { fieldType = "Int64" } else if integer.MatchString(colType.String) { fieldType = "Int" } else if varchar.MatchString(colType.String) { fieldType = "String" } else if ts.MatchString(colType.String) { fieldType = "Time" } field := FieldMeta{Name: colName.String, Type: fieldType} //fmt.Printf("Field type: %s -> %s\n", fieldType, colType.String) fields = append(fields, field) } tables[i].Fields = fields } return tables, nil } func infoTableSQL(d Dialect) string { return fmt.Sprintf(infoTablesTmpl, d.renderPlaceholder(1)) } func infoColumnsSQL(d Dialect) string { return fmt.Sprintf(infoColumnsTmpl, d.renderPlaceholder(1), d.renderPlaceholder(2)) } const infoTablesTmpl = ` select table_name from information_schema.tables where table_schema = %s AND table_name != 'schema_versions'; ` const infoColumnsTmpl = ` SELECT column_name, UPPER(data_type) FROM information_schema.columns WHERE table_schema = %s and table_name = %s; `
///////////////////////////////////////////////////////////////////// // arataca89@gmail.com // 20210417 // // func Fields(s string) []string // // Separa a string s em tokens e retorna um slice com estes tokens. // Considera que o separador dos tokens é o caracter de espaço // definido por unicode.IsSpace // // Fonte: https://golang.org/pkg/strings/ // package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.Fields(" foo bar baz ")) // [foo bar baz] fmt.Println(strings.Fields(" ")) // [] }
// Copyright 2022 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package bindinfo import ( "strconv" "strings" "testing" "github.com/pingcap/tidb/sessionctx/variable" "github.com/pingcap/tidb/util/hack" "github.com/stretchr/testify/require" ) func TestBindCache(t *testing.T) { variable.MemQuotaBindingCache.Store(200) bindCache := newBindCache() value := make([][]*BindRecord, 3) key := make([]bindCacheKey, 3) var bigKey string for i := 0; i < 3; i++ { cacheKey := strings.Repeat(strconv.Itoa(i), 50) key[i] = bindCacheKey(hack.Slice(cacheKey)) record := &BindRecord{OriginalSQL: cacheKey, Db: ""} value[i] = []*BindRecord{record} bigKey += cacheKey require.Equal(t, int64(100), calcBindCacheKVMem(key[i], value[i])) } ok, err := bindCache.set(key[0], value[0]) require.True(t, ok) require.Nil(t, err) result := bindCache.get(key[0]) require.NotNil(t, result) ok, err = bindCache.set(key[1], value[1]) require.True(t, ok) require.Nil(t, err) result = bindCache.get(key[1]) require.NotNil(t, result) ok, err = bindCache.set(key[2], value[2]) require.True(t, ok) require.NotNil(t, err) result = bindCache.get(key[2]) require.NotNil(t, result) // key[0] is not in the cache result = bindCache.get(key[0]) require.Nil(t, result) // key[1] is still in the cache result = bindCache.get(key[1]) require.NotNil(t, result) bigBindCacheKey := bindCacheKey(hack.Slice(bigKey)) bigRecord := &BindRecord{OriginalSQL: bigKey, Db: ""} bigBindCacheValue := []*BindRecord{bigRecord} require.Equal(t, int64(300), calcBindCacheKVMem(bigBindCacheKey, bigBindCacheValue)) ok, err = bindCache.set(bigBindCacheKey, bigBindCacheValue) require.False(t, ok) require.NotNil(t, err) result = bindCache.get(bigBindCacheKey) require.Nil(t, result) }
package main import ( "encoding/json" "fmt" "net/http" "os" "strconv" "strings" "time" "github.com/Microsoft/ApplicationInsights-Go/appinsights" ) type Response struct { Now time.Time `json:"now"` IsTestStream bool `json:"isTestStream"` StartedAt time.Time `json:"startedAt"` AccessKey string `json:"accessKey"` HlsSrc string `json:"hlsSrc"` FtlSrc string `json:"ftlSrc"` } type ChannelUserRelationship struct { ID int `json:"id"` Status struct { Roles []string `json:"roles"` Follows struct { User int `json:"user"` Channel int `json:"channel"` CreatedAt time.Time `json:"createdAt"` } `json:"follows"` } `json:"status"` } type lsAPI struct { ID int `json:"id"` IsLSEnabled bool `json:"isLSEnabled"` ChannelID int `json:"channelId"` } type ChannelAPI struct { Featured bool `json:"featured"` ID int `json:"id"` UserID int `json:"userId"` Token string `json:"token"` Online bool `json:"online"` FeatureLevel int `json:"featureLevel"` Partnered bool `json:"partnered"` TranscodingProfileID int `json:"transcodingProfileId"` Suspended bool `json:"suspended"` Name string `json:"name"` Audience string `json:"audience"` ViewersTotal int `json:"viewersTotal"` ViewersCurrent int `json:"viewersCurrent"` NumFollowers int `json:"numFollowers"` Description interface{} `json:"description"` TypeID interface{} `json:"typeId"` Interactive bool `json:"interactive"` InteractiveGameID interface{} `json:"interactiveGameId"` Ftl int `json:"ftl"` HasVod bool `json:"hasVod"` LanguageID interface{} `json:"languageId"` CoverID interface{} `json:"coverId"` ThumbnailID interface{} `json:"thumbnailId"` BadgeID interface{} `json:"badgeId"` BannerURL interface{} `json:"bannerUrl"` HosteeID interface{} `json:"hosteeId"` HasTranscodes bool `json:"hasTranscodes"` VodsEnabled bool `json:"vodsEnabled"` CostreamID interface{} `json:"costreamId"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` DeletedAt interface{} `json:"deletedAt"` Thumbnail interface{} `json:"thumbnail"` Cover interface{} `json:"cover"` Badge interface{} `json:"badge"` Type interface{} `json:"type"` Preferences struct { HypezoneAllow bool `json:"hypezone:allow"` HostingAllow bool `json:"hosting:allow"` HostingAllowlive bool `json:"hosting:allowlive"` MixerFeaturedAllow bool `json:"mixer:featured:allow"` CostreamAllow string `json:"costream:allow"` Sharetext string `json:"sharetext"` ChannelBannedwords []interface{} `json:"channel:bannedwords"` ChannelLinksClickable bool `json:"channel:links:clickable"` ChannelLinksAllowed bool `json:"channel:links:allowed"` ChannelSlowchat int `json:"channel:slowchat"` ChannelNotifyDirectPurchaseMessage string `json:"channel:notify:directPurchaseMessage"` ChannelNotifyDirectPurchase bool `json:"channel:notify:directPurchase"` ChannelNotifyFollow bool `json:"channel:notify:follow"` ChannelNotifyFollowmessage string `json:"channel:notify:followmessage"` ChannelNotifyHostedBy string `json:"channel:notify:hostedBy"` ChannelNotifyHosting string `json:"channel:notify:hosting"` ChannelNotifySubscribemessage string `json:"channel:notify:subscribemessage"` ChannelNotifySubscribe bool `json:"channel:notify:subscribe"` ChannelPartnerSubmail string `json:"channel:partner:submail"` ChannelPlayerMuteOwn bool `json:"channel:player:muteOwn"` ChannelTweetEnabled bool `json:"channel:tweet:enabled"` ChannelTweetBody string `json:"channel:tweet:body"` ChannelUsersLevelRestrict int `json:"channel:users:levelRestrict"` ChannelCatbotLevel int `json:"channel:catbot:level"` ChannelOfflineAutoplayVod bool `json:"channel:offline:autoplayVod"` ChannelChatHostswitch bool `json:"channel:chat:hostswitch"` ChannelDirectPurchaseEnabled bool `json:"channel:directPurchase:enabled"` } `json:"preferences"` User struct { Level int `json:"level"` Social struct { Verified []interface{} `json:"verified"` } `json:"social"` ID int `json:"id"` Username string `json:"username"` Verified bool `json:"verified"` Experience int `json:"experience"` Sparks int `json:"sparks"` AvatarURL string `json:"avatarUrl"` Bio interface{} `json:"bio"` PrimaryTeam interface{} `json:"primaryTeam"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` DeletedAt interface{} `json:"deletedAt"` Groups []struct { ID int `json:"id"` Name string `json:"name"` } `json:"groups"` } `json:"user"` } var ( telemetryConfig = appinsights.NewTelemetryConfiguration("1fdaf5f5-63e1-4145-9f0b-c08c46dcbc1e") client appinsights.TelemetryClient input string inputTwo string ) func main() { // Configure how many items can be sent in one call to the data collector: telemetryConfig.MaxBatchSize = 8192 // Configure the maximum delay before sending queued telemetry: telemetryConfig.MaxBatchInterval = 500 * time.Millisecond // Define the client client = appinsights.NewTelemetryClientFromConfig(telemetryConfig) client.Context().Tags.Cloud().SetRole("light-servoid") start := time.Now() // Application Insights single event client.TrackEvent("Light-Servoid: Starting") // Pull the command line Arguments args := os.Args //Check for invalid username by checking the length of the array. Exit the program if there is no valid input. if len(args) < 1 { fmt.Println("Please enter a valid username.") os.Exit(0) //Exit the program } else if len(args) == 2 { //Run getChannelID for singular channel ID entered by the user getChannelID(args[1]) } else if len(args) == 3 { input = args[1] inputTwo = args[2] //Run the method to get the channel relationship info between two channels. channelRelationship(input, inputTwo) } client.TrackEvent("Light-Servoid: Completed") delta := time.Now().Sub(start) //fmt.Println("Completed in " + delta.String()) request := appinsights.NewRequestTelemetry("GET", "https://mixer-servoid/api/v1/foo/bar", delta, "200") request.MarkTime(start, time.Now()) client.Track(request) client.Channel().Flush() time.Sleep(1 * time.Second) } func getChannelID(channel string) { client.TrackEvent("Light-Servoid: Getting channel ID") //fmt.Println("Getting ChannelInfo for", channel) start := time.Now() resp, err := http.Get("https://mixer.com/api/v1/channels/" + channel) delta := time.Now().Sub(start) var dependency *appinsights.RemoteDependencyTelemetry success := true if err != nil { fmt.Println(err) success = false } dependency = appinsights.NewRemoteDependencyTelemetry("api/v1/channels/{id}", "HTTP GET", "Backend", success /* success */) dependency.Duration = delta dependency.Data = "api/v1/channels/" + channel dependency.ResultCode = strconv.Itoa(resp.StatusCode) dependency.Properties["cv"] = "12346" if resp.StatusCode != 200 { trace := appinsights.NewTraceTelemetry("Light-Servoid: Backend Call failed getting channel info", appinsights.Information) client.Track(trace) fmt.Println(channel + " Not found") return } else { trace := appinsights.NewTraceTelemetry("Light-Servoid: Backend Call successful getting channel info", appinsights.Information) client.Track(trace) } var channelObj ChannelAPI err = json.NewDecoder(resp.Body).Decode(&channelObj) if channelObj.Token != "" { fmt.Println("Looking up " + input + " with ID " + strconv.Itoa(channelObj.ID)) getM3u8(strconv.Itoa(channelObj.ID)) fmt.Println("Current Time UTC):", time.Now().UTC()) if channelObj.HosteeID != nil { fmt.Println("Hosting:", strconv.FormatFloat(channelObj.HosteeID.(float64), 'f', -1, 64)) } else { fmt.Println("Hosting: Nobody") } if len(channelObj.User.Groups) == 1 { fmt.Println("Pro User: false") } else if channelObj.User.Groups[1].Name == "Staff" { fmt.Println("Pro: Staff") } else if channelObj.User.Groups[1].Name == "Pro" || channelObj.User.Groups[2].Name == "Pro" { fmt.Println("Pro User: true") } getLS(strconv.Itoa(channelObj.ID)) fmt.Println("VODs Enabled:", channelObj.VodsEnabled) fmt.Println("Users Current Sparks:", channelObj.User.Sparks) vlcURL(channelObj.ID) fmt.Println("Xpert URL: https://xpert.microsoft.com/osg/views/PROBOTv2?overrides=%7B%22Source%22%3A%22Environment%3DPROD%3BModernClient%3DPartners%3BVEFProvider%3DMixer%3BVEFProvider%3DServices%3BVEFProvider%3DChannel%3BVEFTopic%3D" + strconv.Itoa(channelObj.ID) + "%3B%22%7D") fmt.Println("Unstuck URL (Requires v-dash): https://mixer-unstuck-ppe.azurewebsites.net/api/unstick/channel/" + channel) fmt.Println("Refresh URL (Requires v-dash): https://mixer-unstuck-ppe.azurewebsites.net/api/refresh/channel" + channel) } else { fmt.Println("Failed to get ID") return } defer resp.Body.Close() } func getUserID(channel string, userID bool) int { //gets the user ID client.TrackEvent("Light-Servoid: Getting user ID") //start := time.Now() resp, err := http.Get("https://mixer.com/api/v1/channels/" + channel) // success := true if err != nil { fmt.Println(err) //success = false } if resp.StatusCode != 200 { trace := appinsights.NewTraceTelemetry("Light-Servoid: Backend Call failed getting channel info", appinsights.Information) client.Track(trace) fmt.Println(channel + " Not found") return 0 } else { trace := appinsights.NewTraceTelemetry("Light-Servoid: Backend Call successful getting channel info", appinsights.Information) client.Track(trace) } var channelObj ChannelAPI err = json.NewDecoder(resp.Body).Decode(&channelObj) if channelObj.Token != "" { //just proceed if there is no error } else { fmt.Println("Failed to get user ID") return 0 } defer resp.Body.Close() if userID == false { return channelObj.ID } else { return channelObj.UserID } } func getLS(channel string) { client.TrackEvent("Light-Servoid: Getting channel LightStream Status") //fmt.Println("Getting LightStream Status for", channel) start := time.Now() resp, err := http.Get("https://mixer.com/api/v1/channels/" + channel + "/videoSettings") delta := time.Now().Sub(start) var dependency *appinsights.RemoteDependencyTelemetry success := true if err != nil { fmt.Println(err) success = false } dependency = appinsights.NewRemoteDependencyTelemetry("api/v1/channels/{id}/videoSettings", "HTTP GET", "Backend", success /* success */) dependency.Duration = delta dependency.Data = "api/v1/channels/" + channel + "/videoSettings" dependency.ResultCode = strconv.Itoa(resp.StatusCode) dependency.Properties["cv"] = "12346" if resp.StatusCode != 200 { trace := appinsights.NewTraceTelemetry("Light-Servoid: Backend Call failed getting VideoSettings", appinsights.Information) client.Track(trace) fmt.Println(channel + " 404 LS Not found") return } else { trace := appinsights.NewTraceTelemetry("Light-Servoid: Backend Call successful getting VideoSettings", appinsights.Information) client.Track(trace) } var channelObj lsAPI err = json.NewDecoder(resp.Body).Decode(&channelObj) fmt.Println("LightStream Status:", channelObj.IsLSEnabled) defer resp.Body.Close() } func getM3u8(channel string) { //fmt.Println("Getting M3U8 for", channel) client.TrackEvent("Light-Servoid: Getting channel manifest") start := time.Now() resp, err := http.Get("https://mixer.com/api/v1/channels/" + channel + "/manifest.light2") delta := time.Now().Sub(start) var dependency *appinsights.RemoteDependencyTelemetry success := true if err != nil { fmt.Println(err) success = false } dependency = appinsights.NewRemoteDependencyTelemetry("api/v1/channels/{id}/manifest.light2", "HTTP GET", "Falcon", success /* success */) dependency.Duration = delta dependency.Data = "api/v1/channels/" + channel + "/manifest.light2" dependency.ResultCode = strconv.Itoa(resp.StatusCode) dependency.Properties["cv"] = "12346" if resp.StatusCode != 200 { trace := appinsights.NewTraceTelemetry("Light-Servoid: Channel was offline", appinsights.Information) client.Track(trace) fmt.Println("channel was offline") return } else { trace := appinsights.NewTraceTelemetry("Light-Servoid: Channel was online", appinsights.Information) client.Track(trace) } var respObj Response err = json.NewDecoder(resp.Body).Decode(&respObj) // Define the Trace trace := appinsights.NewTraceTelemetry("message", appinsights.Information) trace.Properties["hlsSource"] = respObj.HlsSrc trace.Properties["ftlSource"] = respObj.FtlSrc client.Track(trace) getDist(respObj.AccessKey) fmt.Println("PROCESSED VIDEO (VLC): https://video.mixer.com/hls/" + respObj.AccessKey + "_source/index.m3u8") //fmt.Println("HLSSource: " + respObj.HlsSource) //fmt.Println("FTLSource: " + respObj.FtlSource) client.Track(dependency) defer resp.Body.Close() } func getDist(accessKey string) { client.TrackEvent("Light-Servoid: Getting Dist Server") url := "https://video.mixer.com/hls/" + accessKey + "_source/index.m3u8" start := time.Now() resp, err := http.Get(url) delta := time.Now().Sub(start) var dependency *appinsights.RemoteDependencyTelemetry success := true if err != nil { fmt.Println(err) success = false } dependency = appinsights.NewRemoteDependencyTelemetry("/hls/{accessKey}_source/index.m3u8", "HTTP GET", "Janus", success /* success */) dependency.Duration = delta dependency.Data = url dependency.ResultCode = strconv.Itoa(resp.StatusCode) client.Track(dependency) defer resp.Body.Close() if resp.StatusCode != 200 { fmt.Println(resp.StatusCode) } else { for header, value := range resp.Header { if strings.Contains(header, "Cdn") { client.TrackEvent("Light-Servoid: Reporting Dist Server") // Define the Trace trace := appinsights.NewTraceTelemetry("message", appinsights.Information) trace.Properties["dist"] = value[0] client.Track(trace) fmt.Println("Your Dist: " + value[0]) } } } } func vlcURL(channel int) { //Print the video to watch the streams source video for VLC. var channelString = strconv.Itoa(channel) fmt.Println("SOURCE VIDEO (VLC): rtmp://<ingestname>.mixer.com:1935/beam/" + channelString) } func channelRelationship(channelOne string, channelTwo string) { //Get the user ID or channel ID, pass true if you want the user ID and false for channel ID, returns the ID in an INT userIDNum := getUserID(channelTwo, true) channelIDNum := getUserID(channelOne, false) //Convert channel/user IDs to Strings to concatenate onto the URL userIDString := strconv.Itoa(userIDNum) channelIDString := strconv.Itoa(channelIDNum) //Show the user what we're doing fmt.Println("Looking up the channel user relationship with " + "Channel: " + channelOne + " User: " + channelTwo) //Generate the correct json url with the channel id and user id strings url := "https://mixer.com/api/v1/channels/" + channelIDString + "/relationship?user=" + userIDString fmt.Println("URL: " + url) //Parse the json file into the struct (check for) & print the roles resp, err := http.Get(url) if err != nil { fmt.Println(err) } else { var userObj ChannelUserRelationship err = json.NewDecoder(resp.Body).Decode(&userObj) fmt.Print("User Roles: ") fmt.Println(userObj.Status.Roles) } defer resp.Body.Close() }
package codex import ( "context" "github.com/pathbird/pbauthor/internal/auth" "github.com/pathbird/pbauthor/internal/course" "github.com/pathbird/pbauthor/internal/graphql" "github.com/pkg/errors" "io/ioutil" "os" "path/filepath" ) // Initialize a new codex config file func InitConfig(dirname string) (*Config, error) { // Look for a codex file before initializing files, err := ioutil.ReadDir(dirname) if err != nil { return nil, errors.Wrap(err, "failed to list files") } var codexSourceFile string for _, file := range files { if isCodexSourceFile(file) { codexSourceFile = file.Name() break } } if codexSourceFile == "" { return nil, errors.Errorf("directory (%s) does not contain a codex source file", dirname) } configFile := filepath.Join(dirname, ConfigFileName) conf := &Config{ configFile: configFile, } // TODO: shouldn't create a new client here, but oh well authn, err := auth.GetAuth() if err != nil { return nil, err } g := graphql.NewClient(authn) courses, err := g.QueryCourses(context.Background()) if err != nil { return nil, err } cour, err := course.PromptCourse(courses) if err != nil { return nil, err } cat, err := course.PromptCodexCategory(cour.CodexCategories) if err != nil { return nil, err } conf.Upload.CodexCategory = cat.ID if err := conf.Save(); err != nil { return nil, err } return conf, nil } func isCodexSourceFile(file os.FileInfo) bool { ext := filepath.Ext(file.Name()) return !file.IsDir() && ext == ".ipynb" }
// Copyright 2020 The Reed Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. package p2p import ( "bufio" "bytes" "encoding/json" "fmt" "net" "testing" ) func newMockTCP(recvCh chan<- []byte) error { l, err := net.Listen("tcp", ":7000") if err != nil { return err } go func() { for { conn, err := l.Accept() if err != nil { fmt.Println(err) } input := bufio.NewScanner(conn) for input.Scan() { recvCh <- input.Bytes() } } }() return nil } func TestSpecialMsg(t *testing.T) { recvCh := make(chan []byte) _ = newMockTCP(recvCh) conn, err := net.Dial("tcp", ":7000") if err != nil { t.Fatal(err) } connection := NewConnection("", nil, conn, getOurNodeInfo(), nil) isSpecialMsg := connection.specialMsg([]byte{handshakeCode}) if !isSpecialMsg { t.Fatal("can not recognize handshakeCode") } select { case msg := <-recvCh: if msg[0] != handshakeRespCode { t.Fatal("first byte must handshakeRespCode") } ni := &NodeInfo{} if err := json.Unmarshal(msg[1:], ni); err != nil { t.Fatal(err) } if !bytes.Equal(ourNodeID.Bytes(), ni.ID.Bytes()) { t.Fatal("ourNodeID:send and receive not equal") } if ni.RemoteAddr != ourAddr { t.Fatal("ourRemoteAddr:send and receive not equal") } } }
package main import ( "fmt" "net/http" ) var ( n1 = 1 n2 = 2 n3 = 3 ) func main() { var n4 int n4 = 100 // n1, n2, n3 := 1, 2, 3 // n1 := 1 fmt.Print(n1, n2, n3, n4) http.HandleFunc("/", handler) http.ListenAndServe(":8081", nil) } func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello Golang!") }
package utils import ( "errors" "io" "os" "strings" "testing" "github.com/stretchr/testify/require" ) type testConfig struct { BackendAddr string `json:"backend_addr"` } func (c *testConfig) Read() error { return nil } func (c *testConfig) Write() error { return nil } func (c *testConfig) Init(rd io.Reader) error { return nil } type errorConfig struct { BackendAddr string `json:"backend_addr"` } func (c *errorConfig) Read() error { if c.BackendAddr == "readerror" { return errors.New("read error") } return nil } func (c *errorConfig) Write() error { if c.BackendAddr == "writeerror" { return errors.New("write error") } return nil } func (c *errorConfig) Init(rd io.Reader) error { if c.BackendAddr == "initerror" { return errors.New("init error") } return nil } type errorAllConfig struct { BackendAddr string `json:"backend_addr"` } func (c *errorAllConfig) Read() error { return errors.New("read error") } func (c *errorAllConfig) Write() error { return errors.New("write error") } func (c *errorAllConfig) Init(rd io.Reader) error { return errors.New("init error") } type funcFieldConfig struct { BackendAddr func() `json:"backend_addr"` } func (c *funcFieldConfig) Read() error { return errors.New("read error") } func (c *funcFieldConfig) Write() error { return errors.New("write error") } func (c *funcFieldConfig) Init(rd io.Reader) error { return errors.New("init error") } func TestConfig(t *testing.T) { filename := "ozymandias" addr := ":21" tmpDir := t.TempDir() t.Setenv("HOME", tmpDir) tmpStdout := os.Stdout os.Stdout, _ = os.Open(os.DevNull) t.Run("it should successfully create config flow", func(t *testing.T) { conf := &testConfig{addr} err := InitializeConfig(conf) require.NoError(t, err) require.Equal(t, addr, conf.BackendAddr) err = WriteConfigToFile(conf, filename) require.NoError(t, err) err = ReadConfigFromFile(conf, filename) require.NoError(t, err) err = DeleteConfig(filename) require.NoError(t, err) }) t.Run("it should be failed to initialize config", func(t *testing.T) { conf := &errorAllConfig{addr} err := InitializeConfig(conf) require.Error(t, err) require.Equal(t, addr, conf.BackendAddr) err = WriteConfigToFile(conf, filename) require.NoError(t, err) err = ReadConfigFromFile(conf, filename) require.NoError(t, err) err = DeleteConfig(filename) require.NoError(t, err) }) t.Run("it should create and delete folder", func(t *testing.T) { err := createFolder("banger") require.NoError(t, err) err = os.RemoveAll("banger") require.NoError(t, err) }) t.Run("it should error when writing config", func(t *testing.T) { payload := "writeerror" conf := &errorConfig{payload} err := InitializeConfig(conf) require.Error(t, err) payload = "initerror" conf = &errorConfig{payload} err = InitializeConfig(conf) require.Error(t, err) }) t.Run("it should error when writing config", func(t *testing.T) { t.Setenv("HOME", "/home/somerandomhomethatsnotsupposedtobepresent") conf := &errorAllConfig{addr} err := InitializeConfig(conf) require.Error(t, err) require.Equal(t, addr, conf.BackendAddr) err = WriteConfigToFile(conf, filename) require.Error(t, err) err = ReadConfigFromFile(conf, filename) require.Error(t, err) err = DeleteConfig(filename) require.Error(t, err) }) t.Run("it should error when $HOME env is unset", func(t *testing.T) { os.Unsetenv("HOME") conf := &errorAllConfig{addr} err := InitializeConfig(conf) require.Error(t, err) require.Equal(t, addr, conf.BackendAddr) err = WriteConfigToFile(conf, filename) require.Error(t, err) err = ReadConfigFromFile(conf, filename) require.Error(t, err) err = DeleteConfig(filename) require.Error(t, err) t.Setenv("HOME", tmpDir) }) t.Run("it should error when marshaling a func", func(t *testing.T) { conf := &funcFieldConfig{func() {}} err := WriteConfigToFile(conf, "") require.Error(t, err) }) t.Run("it should prompt correctly", func(t *testing.T) { text, err := Prompt("listen address", ":13120", strings.NewReader("Banger\n")) require.NoError(t, err) require.Equal(t, text, "Banger") }) t.Run("it should prompt and errored", func(t *testing.T) { text, err := Prompt("listen address", ":13120", strings.NewReader("")) require.Error(t, err) require.Equal(t, text, "") }) os.Stdout = tmpStdout }
package main import ( "net/http" "fmt" ) type dog int type cat int func(d dog) ServeHTTP(w http.ResponseWriter,r *http.Request){ //this is the signature of handler interface //switch r.URL.Path { fmt.Fprintln(w,"barks") //case "/cat":fmt.Fprintln(w,"meows") //} } func(c cat) ServeHTTP(w http.ResponseWriter,r *http.Request){ //this is the signature of handler interface fmt.Fprintln(w,"mews") } func main() { var d dog var c cat //Handle need a handler http.Handle("/dog/",d) //no servemux() is created it uses the default serve mux http.Handle("/cat",c) http.ListenAndServe(":8080",nil) }
// macAndIpInfo package DaeseongLib import ( _ "fmt" "net" ) func macAddress() string { ifaces, err := net.Interfaces() if err != nil { return "" } for _, iface := range ifaces { if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { continue } addrs, err := iface.Addrs() if err != nil { return "" } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } if ip == nil || ip.IsLoopback() || ip.To4() == nil { continue } return iface.HardwareAddr.String() } } return "" } func IpAddress() string { ifaces, err := net.Interfaces() if err != nil { return "" } for _, iface := range ifaces { if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { continue } addrs, err := iface.Addrs() if err != nil { return "" } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } if ip == nil || ip.IsLoopback() { continue } ip = ip.To4() if ip == nil { continue } return ip.String() } } return "" } /* func main() { fmt.Println(IpAddress()) fmt.Println() fmt.Println(macAddress()) } */
package converter import ( "errors" "log" "time" ) // 超时错误 var ( ErrConversionTimeout = errors.New("pdf 转换超时") ) // Worker 工作者信息 type Worker struct { id int } // InitWorkers 初始化转换队列 // maxWorkers: 最大并行转换数 // maxQueue: 队列里做多等待数量 // timeout: 转换超时时间 func InitWorkers(maxWorkers, maxQueue, timeout int) chan<- Work { wq := make(chan Work, maxQueue) for i := 0; i < maxWorkers; i++ { w := Worker{i} go func(wq <-chan Work, w Worker, timeout int) { for work := range wq { log.Printf("[工号 #%d] 正在转换 pdf 中... (当前等待的转换数量: %d)\n", w.id, len(wq)) work.Process(timeout) } }(wq, w, timeout) } return wq } // Work 转换器信息 type Work struct { converter Converter source ConversionSource out chan []byte url chan string err chan error uploaded chan struct{} done chan struct{} } // NewWork 添加新的转换工作 func NewWork(wq chan<- Work, c Converter, s ConversionSource) Work { w := Work{} w.converter = c w.source = s w.out = make(chan []byte, 1) w.url = make(chan string, 1) w.err = make(chan error, 1) w.uploaded = make(chan struct{}, 1) w.done = make(chan struct{}, 1) go func(wq chan<- Work, w Work) { wq <- w }(wq, w) return w } // Process 处理超时信息 func (w Work) Process(timeout int) { done := make(chan struct{}, 1) defer close(done) wout := make(chan []byte, 1) werr := make(chan error, 1) wurl := make(chan string, 1) go func(w Work, done <-chan struct{}, wout chan<- []byte, werr chan<- error) { // NOTE: 这里转换只是用到了链接, 对于需要 cookie 和参数的是不合适的, 需要注意 out, err := w.converter.Convert(w.source, done) if err != nil { werr <- err return } // 七牛上传只需要返回给前端 URL 就好了, 不用自动弹出下载框 // uploaded, url, err := w.converter.UploadQiniu(out) // if err != nil { // werr <- err // return // } // if uploaded { // close(w.uploaded) // return // } // log.Println("七牛返回链接: ", url) // 原始返回的是字节数组, 七牛的话, 只返回链接即可 wout <- out // wurl <- url }(w, done, wout, werr) select { case <-w.Cancelled(): case <-w.Uploaded(): case out := <-wout: w.out <- out case url := <-wurl: w.url <- url case err := <-werr: w.err <- err case <-time.After(time.Second * time.Duration(timeout)): w.err <- ErrConversionTimeout } } // AWSS3Success returns a channel that will be used for publishing the output of a // conversion. func (w Work) AWSS3Success() <-chan []byte { return w.out } // QiniuSuccess 七牛上传成功 func (w Work) QiniuSuccess() <-chan string { return w.url } // Error returns a channel that will be used for publishing errors from a // conversion. func (w Work) Error() <-chan error { return w.err } // Uploaded returns a channel that will be closed when a conversion has been // uploaded. func (w Work) Uploaded() <-chan struct{} { return w.uploaded } // Cancel will close the done channel. This will indicate to child Goroutines // that the job has been terminated, and the results are no longer needed. func (w Work) Cancel() { close(w.done) } // Cancelled returns a channel that will indicate when a job has been completed. func (w Work) Cancelled() <-chan struct{} { return w.done }
package readconfig import "testing" func TestReadConfJSON(t *testing.T) { var path string ="../conf.json" res := ReadConfJSON(path) t.Log(res.Enabled,res.Path) }
package constants type TAG_KEY_TYPE string type TAG_VALUE_TYPE string const ( TAG_KEY_JSON TAG_KEY_TYPE = "json" // json标签 TAG_KEY_GORM TAG_KEY_TYPE = "gorm" // gorm标签 TAG_VALUE_keep_ignore TAG_VALUE_TYPE = `"-"` // 忽略 TAG_VALUE_keep_prefix TAG_VALUE_TYPE = `"#` // 标签值前缀 TAG_VALUE_keep_toSnake TAG_VALUE_TYPE = TAG_VALUE_keep_prefix + `toSnake"` // "#toSnake" 转成蛇形-->xx_yy TAG_VALUE_keep_toCamel TAG_VALUE_TYPE = TAG_VALUE_keep_prefix + `toCamel"` // "#toCamel" 转成驼峰-->XxYy TAG_VALUE_keep_toCamel2 TAG_VALUE_TYPE = TAG_VALUE_keep_prefix + `toCamel2"` // "#toCamel2" 转成驼峰,首字符小写-->xxYy )
package bundle import ( "context" "crypto/sha256" "fmt" "strings" "time" "github.com/operator-framework/operator-registry/pkg/api" "github.com/operator-framework/operator-registry/pkg/configmap" "github.com/sirupsen/logrus" batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" k8slabels "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/kubernetes" listersbatchv1 "k8s.io/client-go/listers/batch/v1" listerscorev1 "k8s.io/client-go/listers/core/v1" listersrbacv1 "k8s.io/client-go/listers/rbac/v1" "k8s.io/utils/pointer" "github.com/operator-framework/api/pkg/operators/reference" operatorsv1alpha1 "github.com/operator-framework/api/pkg/operators/v1alpha1" v1listers "github.com/operator-framework/operator-lifecycle-manager/pkg/api/client/listers/operators/v1" listersoperatorsv1alpha1 "github.com/operator-framework/operator-lifecycle-manager/pkg/api/client/listers/operators/v1alpha1" "github.com/operator-framework/operator-lifecycle-manager/pkg/controller/install" "github.com/operator-framework/operator-lifecycle-manager/pkg/controller/registry/resolver/projection" "github.com/operator-framework/operator-lifecycle-manager/pkg/lib/image" ) const ( // TODO: This can be a spec field // BundleUnpackTimeoutAnnotationKey allows setting a bundle unpack timeout per OperatorGroup // and overrides the default specified by the --bundle-unpack-timeout flag // The time duration should be in the same format as accepted by time.ParseDuration() // e.g 1m30s BundleUnpackTimeoutAnnotationKey = "operatorframework.io/bundle-unpack-timeout" BundleUnpackPodLabel = "job-name" ) type BundleUnpackResult struct { *operatorsv1alpha1.BundleLookup bundle *api.Bundle name string } func (b *BundleUnpackResult) Bundle() *api.Bundle { return b.bundle } func (b *BundleUnpackResult) Name() string { return b.name } // SetCondition replaces the existing BundleLookupCondition of the same type, or adds it if it was not found. func (b *BundleUnpackResult) SetCondition(cond operatorsv1alpha1.BundleLookupCondition) operatorsv1alpha1.BundleLookupCondition { for i, existing := range b.Conditions { if existing.Type != cond.Type { continue } if existing.Status == cond.Status && existing.Reason == cond.Reason { cond.LastTransitionTime = existing.LastTransitionTime } b.Conditions[i] = cond return cond } b.Conditions = append(b.Conditions, cond) return cond } var catalogSourceGVK = operatorsv1alpha1.SchemeGroupVersion.WithKind(operatorsv1alpha1.CatalogSourceKind) func newBundleUnpackResult(lookup *operatorsv1alpha1.BundleLookup) *BundleUnpackResult { return &BundleUnpackResult{ BundleLookup: lookup.DeepCopy(), name: hash(lookup.Path), } } func (c *ConfigMapUnpacker) job(cmRef *corev1.ObjectReference, bundlePath string, secrets []corev1.LocalObjectReference, annotationUnpackTimeout time.Duration) *batchv1.Job { job := &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ install.OLMManagedLabelKey: install.OLMManagedLabelValue, }, }, Spec: batchv1.JobSpec{ //ttlSecondsAfterFinished: 0 // can use in the future to not have to clean up job Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Name: cmRef.Name, Labels: map[string]string{ install.OLMManagedLabelKey: install.OLMManagedLabelValue, }, }, Spec: corev1.PodSpec{ // With restartPolicy = "OnFailure" when the spec.backoffLimit is reached, the job controller will delete all // the job's pods to stop them from crashlooping forever. // By setting restartPolicy = "Never" the pods don't get cleaned up since they're not running after a failure. // Keeping the pods around after failures helps in inspecting the logs of a failed bundle unpack job. // See: https://kubernetes.io/docs/concepts/workloads/controllers/job/#pod-backoff-failure-policy RestartPolicy: corev1.RestartPolicyNever, ImagePullSecrets: secrets, SecurityContext: &corev1.PodSecurityContext{ SeccompProfile: &corev1.SeccompProfile{ Type: corev1.SeccompProfileTypeRuntimeDefault, }, }, Containers: []corev1.Container{ { Name: "extract", Image: c.opmImage, Command: []string{"opm", "alpha", "bundle", "extract", "-m", "/bundle/", "-n", cmRef.Namespace, "-c", cmRef.Name, "-z", }, Env: []corev1.EnvVar{ { Name: configmap.EnvContainerImage, Value: bundlePath, }, }, VolumeMounts: []corev1.VolumeMount{ { Name: "bundle", // Expected bundle content mount MountPath: "/bundle", }, }, Resources: corev1.ResourceRequirements{ Requests: corev1.ResourceList{ corev1.ResourceCPU: resource.MustParse("10m"), corev1.ResourceMemory: resource.MustParse("50Mi"), }, }, SecurityContext: &corev1.SecurityContext{ AllowPrivilegeEscalation: pointer.Bool(false), Capabilities: &corev1.Capabilities{ Drop: []corev1.Capability{"ALL"}, }, }, }, }, InitContainers: []corev1.Container{ { Name: "util", Image: c.utilImage, Command: []string{"/bin/cp", "-Rv", "/bin/cpb", "/util/cpb"}, // Copy tooling for the bundle container to use VolumeMounts: []corev1.VolumeMount{ { Name: "util", MountPath: "/util", }, }, Resources: corev1.ResourceRequirements{ Requests: corev1.ResourceList{ corev1.ResourceCPU: resource.MustParse("10m"), corev1.ResourceMemory: resource.MustParse("50Mi"), }, }, SecurityContext: &corev1.SecurityContext{ AllowPrivilegeEscalation: pointer.Bool(false), Capabilities: &corev1.Capabilities{ Drop: []corev1.Capability{"ALL"}, }, }, }, { Name: "pull", Image: bundlePath, ImagePullPolicy: image.InferImagePullPolicy(bundlePath), Command: []string{"/util/cpb", "/bundle"}, // Copy bundle content to its mount VolumeMounts: []corev1.VolumeMount{ { Name: "bundle", MountPath: "/bundle", }, { Name: "util", MountPath: "/util", }, }, Resources: corev1.ResourceRequirements{ Requests: corev1.ResourceList{ corev1.ResourceCPU: resource.MustParse("10m"), corev1.ResourceMemory: resource.MustParse("50Mi"), }, }, SecurityContext: &corev1.SecurityContext{ AllowPrivilegeEscalation: pointer.Bool(false), Capabilities: &corev1.Capabilities{ Drop: []corev1.Capability{"ALL"}, }, }, }, }, Volumes: []corev1.Volume{ { Name: "bundle", // Used to share bundle content VolumeSource: corev1.VolumeSource{ EmptyDir: &corev1.EmptyDirVolumeSource{}, }, }, { Name: "util", // Used to share utils VolumeSource: corev1.VolumeSource{ EmptyDir: &corev1.EmptyDirVolumeSource{}, }, }, }, NodeSelector: map[string]string{ "kubernetes.io/os": "linux", }, Tolerations: []corev1.Toleration{ { Key: "kubernetes.io/arch", Value: "amd64", Operator: "Equal", }, { Key: "kubernetes.io/arch", Value: "arm64", Operator: "Equal", }, { Key: "kubernetes.io/arch", Value: "ppc64le", Operator: "Equal", }, { Key: "kubernetes.io/arch", Value: "s390x", Operator: "Equal", }, }, }, }, }, } job.SetNamespace(cmRef.Namespace) job.SetName(cmRef.Name) job.SetOwnerReferences([]metav1.OwnerReference{ownerRef(cmRef)}) if c.runAsUser > 0 { job.Spec.Template.Spec.SecurityContext.RunAsUser = &c.runAsUser job.Spec.Template.Spec.SecurityContext.RunAsNonRoot = pointer.Bool(true) } // By default the BackoffLimit is set to 6 which with exponential backoff 10s + 20s + 40s ... // translates to ~10m of waiting time. // We want to fail faster than that when we have repeated failures from the bundle unpack pod // so we set it to 3 which is ~1m of waiting time // See: https://kubernetes.io/docs/concepts/workloads/controllers/job/#pod-backoff-failure-policy backOffLimit := int32(3) job.Spec.BackoffLimit = &backOffLimit // Set ActiveDeadlineSeconds as the unpack timeout // Don't set a timeout if it is 0 if c.unpackTimeout != time.Duration(0) { t := int64(c.unpackTimeout.Seconds()) job.Spec.ActiveDeadlineSeconds = &t } // Check annotationUnpackTimeout which is the annotation override for the default unpack timeout // A negative timeout means the annotation was unset or malformed so we ignore it if annotationUnpackTimeout < time.Duration(0) { return job } // // 0 means no timeout so we unset ActiveDeadlineSeconds if annotationUnpackTimeout == time.Duration(0) { job.Spec.ActiveDeadlineSeconds = nil return job } timeoutSeconds := int64(annotationUnpackTimeout.Seconds()) job.Spec.ActiveDeadlineSeconds = &timeoutSeconds return job } //go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . Unpacker type Unpacker interface { UnpackBundle(lookup *operatorsv1alpha1.BundleLookup, timeout time.Duration) (result *BundleUnpackResult, err error) } type ConfigMapUnpacker struct { logger *logrus.Logger opmImage string utilImage string client kubernetes.Interface csLister listersoperatorsv1alpha1.CatalogSourceLister cmLister listerscorev1.ConfigMapLister jobLister listersbatchv1.JobLister podLister listerscorev1.PodLister roleLister listersrbacv1.RoleLister rbLister listersrbacv1.RoleBindingLister loader *configmap.BundleLoader now func() metav1.Time unpackTimeout time.Duration runAsUser int64 } type ConfigMapUnpackerOption func(*ConfigMapUnpacker) func NewConfigmapUnpacker(options ...ConfigMapUnpackerOption) (*ConfigMapUnpacker, error) { unpacker := &ConfigMapUnpacker{ loader: configmap.NewBundleLoader(), } unpacker.apply(options...) if err := unpacker.validate(); err != nil { return nil, err } return unpacker, nil } func WithUnpackTimeout(timeout time.Duration) ConfigMapUnpackerOption { return func(unpacker *ConfigMapUnpacker) { unpacker.unpackTimeout = timeout } } func WithOPMImage(opmImage string) ConfigMapUnpackerOption { return func(unpacker *ConfigMapUnpacker) { unpacker.opmImage = opmImage } } func WithUtilImage(utilImage string) ConfigMapUnpackerOption { return func(unpacker *ConfigMapUnpacker) { unpacker.utilImage = utilImage } } func WithLogger(logger *logrus.Logger) ConfigMapUnpackerOption { return func(unpacker *ConfigMapUnpacker) { unpacker.logger = logger } } func WithClient(client kubernetes.Interface) ConfigMapUnpackerOption { return func(unpacker *ConfigMapUnpacker) { unpacker.client = client } } func WithCatalogSourceLister(csLister listersoperatorsv1alpha1.CatalogSourceLister) ConfigMapUnpackerOption { return func(unpacker *ConfigMapUnpacker) { unpacker.csLister = csLister } } func WithConfigMapLister(cmLister listerscorev1.ConfigMapLister) ConfigMapUnpackerOption { return func(unpacker *ConfigMapUnpacker) { unpacker.cmLister = cmLister } } func WithJobLister(jobLister listersbatchv1.JobLister) ConfigMapUnpackerOption { return func(unpacker *ConfigMapUnpacker) { unpacker.jobLister = jobLister } } func WithPodLister(podLister listerscorev1.PodLister) ConfigMapUnpackerOption { return func(unpacker *ConfigMapUnpacker) { unpacker.podLister = podLister } } func WithRoleLister(roleLister listersrbacv1.RoleLister) ConfigMapUnpackerOption { return func(unpacker *ConfigMapUnpacker) { unpacker.roleLister = roleLister } } func WithRoleBindingLister(rbLister listersrbacv1.RoleBindingLister) ConfigMapUnpackerOption { return func(unpacker *ConfigMapUnpacker) { unpacker.rbLister = rbLister } } func WithNow(now func() metav1.Time) ConfigMapUnpackerOption { return func(unpacker *ConfigMapUnpacker) { unpacker.now = now } } func WithUserID(id int64) ConfigMapUnpackerOption { return func(unpacker *ConfigMapUnpacker) { unpacker.runAsUser = id } } func (c *ConfigMapUnpacker) apply(options ...ConfigMapUnpackerOption) { for _, option := range options { option(c) } } func (c *ConfigMapUnpacker) validate() (err error) { switch { case c.opmImage == "": err = fmt.Errorf("no opm image given") case c.utilImage == "": err = fmt.Errorf("no util image given") case c.client == nil: err = fmt.Errorf("client is nil") case c.csLister == nil: err = fmt.Errorf("catalogsource lister is nil") case c.cmLister == nil: err = fmt.Errorf("configmap lister is nil") case c.jobLister == nil: err = fmt.Errorf("job lister is nil") case c.podLister == nil: err = fmt.Errorf("pod lister is nil") case c.roleLister == nil: err = fmt.Errorf("role lister is nil") case c.rbLister == nil: err = fmt.Errorf("rolebinding lister is nil") case c.loader == nil: err = fmt.Errorf("bundle loader is nil") case c.now == nil: err = fmt.Errorf("now func is nil") } return } const ( CatalogSourceMissingReason = "CatalogSourceMissing" CatalogSourceMissingMessage = "referenced catalogsource not found" JobFailedReason = "JobFailed" JobFailedMessage = "unpack job has failed" JobIncompleteReason = "JobIncomplete" JobIncompleteMessage = "unpack job not completed" JobNotStartedReason = "JobNotStarted" JobNotStartedMessage = "unpack job not yet started" NotUnpackedReason = "BundleNotUnpacked" NotUnpackedMessage = "bundle contents have not yet been persisted to installplan status" ) func (c *ConfigMapUnpacker) UnpackBundle(lookup *operatorsv1alpha1.BundleLookup, timeout time.Duration) (result *BundleUnpackResult, err error) { result = newBundleUnpackResult(lookup) // if bundle lookup failed condition already present, then there is nothing more to do failedCond := result.GetCondition(operatorsv1alpha1.BundleLookupFailed) if failedCond.Status == corev1.ConditionTrue { return result, nil } // if pending condition is not true then bundle has already been unpacked(unknown) pendingCond := result.GetCondition(operatorsv1alpha1.BundleLookupPending) if pendingCond.Status != corev1.ConditionTrue { return result, nil } now := c.now() var cs *operatorsv1alpha1.CatalogSource if cs, err = c.csLister.CatalogSources(result.CatalogSourceRef.Namespace).Get(result.CatalogSourceRef.Name); err != nil { if apierrors.IsNotFound(err) && pendingCond.Reason != CatalogSourceMissingReason { pendingCond.Status = corev1.ConditionTrue pendingCond.Reason = CatalogSourceMissingReason pendingCond.Message = CatalogSourceMissingMessage pendingCond.LastTransitionTime = &now result.SetCondition(pendingCond) err = nil } return } // Add missing info to the object reference csRef := result.CatalogSourceRef.DeepCopy() csRef.SetGroupVersionKind(catalogSourceGVK) csRef.UID = cs.GetUID() cm, err := c.ensureConfigmap(csRef, result.name) if err != nil { return } var cmRef *corev1.ObjectReference cmRef, err = reference.GetReference(cm) if err != nil { return } _, err = c.ensureRole(cmRef) if err != nil { return } _, err = c.ensureRoleBinding(cmRef) if err != nil { return } secrets := make([]corev1.LocalObjectReference, 0) for _, secretName := range cs.Spec.Secrets { secrets = append(secrets, corev1.LocalObjectReference{Name: secretName}) } var job *batchv1.Job job, err = c.ensureJob(cmRef, result.Path, secrets, timeout) if err != nil || job == nil { // ensureJob can return nil if the job present does not match the expected job (spec and ownerefs) // The current job is deleted in that case so UnpackBundle needs to be retried return } // Check if bundle unpack job has failed due a timeout // Return a BundleJobError so we can mark the InstallPlan as Failed if jobCond, isFailed := getCondition(job, batchv1.JobFailed); isFailed { // Add the BundleLookupFailed condition with the message and reason from the job failure failedCond.Status = corev1.ConditionTrue failedCond.Reason = jobCond.Reason failedCond.Message = jobCond.Message failedCond.LastTransitionTime = &now result.SetCondition(failedCond) return } if _, isComplete := getCondition(job, batchv1.JobComplete); !isComplete { // In the case of an image pull failure for a non-existent image the bundle unpack job // can stay pending until the ActiveDeadlineSeconds timeout ~10m // To indicate why it's pending we inspect the container statuses of the // unpack Job pods to surface that information on the bundle lookup conditions pendingMessage := JobIncompleteMessage var pendingContainerStatusMsgs string pendingContainerStatusMsgs, err = c.pendingContainerStatusMessages(job) if err != nil { return } if pendingContainerStatusMsgs != "" { pendingMessage = pendingMessage + ": " + pendingContainerStatusMsgs } // Update BundleLookupPending condition if there are any changes if pendingCond.Status != corev1.ConditionTrue || pendingCond.Reason != JobIncompleteReason || pendingCond.Message != pendingMessage { pendingCond.Status = corev1.ConditionTrue pendingCond.Reason = JobIncompleteReason pendingCond.Message = pendingMessage pendingCond.LastTransitionTime = &now result.SetCondition(pendingCond) } return } result.bundle, err = c.loader.Load(cm) if err != nil { return } if result.Bundle() == nil || len(result.Bundle().GetObject()) == 0 { return } if result.BundleLookup.Properties != "" { props, err := projection.PropertyListFromPropertiesAnnotation(lookup.Properties) if err != nil { return nil, fmt.Errorf("failed to load bundle properties for %q: %w", lookup.Identifier, err) } result.bundle.Properties = props } // A successful load should remove the pending condition result.RemoveCondition(operatorsv1alpha1.BundleLookupPending) return } func (c *ConfigMapUnpacker) pendingContainerStatusMessages(job *batchv1.Job) (string, error) { containerStatusMessages := []string{} // List pods for unpack job podLabel := map[string]string{BundleUnpackPodLabel: job.GetName()} pods, listErr := c.podLister.Pods(job.GetNamespace()).List(k8slabels.SelectorFromValidatedSet(podLabel)) if listErr != nil { c.logger.Errorf("failed to list pods for job(%s): %v", job.GetName(), listErr) return "", fmt.Errorf("failed to list pods for job(%s): %v", job.GetName(), listErr) } // Ideally there should be just 1 pod running but inspect all pods in the pending phase // to see if any are stuck on an ImagePullBackOff or ErrImagePull error for _, pod := range pods { if pod.Status.Phase != corev1.PodPending { // skip status check for non-pending pods continue } for _, ic := range pod.Status.InitContainerStatuses { if ic.Ready { // only check non-ready containers for their waiting reasons continue } msg := fmt.Sprintf("Unpack pod(%s/%s) container(%s) is pending", pod.Namespace, pod.Name, ic.Name) waiting := ic.State.Waiting if waiting != nil { msg = fmt.Sprintf("Unpack pod(%s/%s) container(%s) is pending. Reason: %s, Message: %s", pod.Namespace, pod.Name, ic.Name, waiting.Reason, waiting.Message) } // Aggregate the wait reasons for all pending containers containerStatusMessages = append(containerStatusMessages, msg) } } return strings.Join(containerStatusMessages, " | "), nil } func (c *ConfigMapUnpacker) ensureConfigmap(csRef *corev1.ObjectReference, name string) (cm *corev1.ConfigMap, err error) { fresh := &corev1.ConfigMap{} fresh.SetNamespace(csRef.Namespace) fresh.SetName(name) fresh.SetOwnerReferences([]metav1.OwnerReference{ownerRef(csRef)}) fresh.SetLabels(map[string]string{install.OLMManagedLabelKey: install.OLMManagedLabelValue}) cm, err = c.cmLister.ConfigMaps(fresh.GetNamespace()).Get(fresh.GetName()) if apierrors.IsNotFound(err) { cm, err = c.client.CoreV1().ConfigMaps(fresh.GetNamespace()).Create(context.TODO(), fresh, metav1.CreateOptions{}) // CM already exists in cluster but not in cache, then add the label if err != nil && apierrors.IsAlreadyExists(err) { cm, err = c.client.CoreV1().ConfigMaps(fresh.GetNamespace()).Get(context.TODO(), fresh.GetName(), metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("failed to retrieve configmap %s: %v", fresh.GetName(), err) } cm.SetLabels(map[string]string{ install.OLMManagedLabelKey: install.OLMManagedLabelValue, }) cm, err = c.client.CoreV1().ConfigMaps(cm.GetNamespace()).Update(context.TODO(), cm, metav1.UpdateOptions{}) if err != nil { return nil, fmt.Errorf("failed to update configmap %s: %v", cm.GetName(), err) } } } return } func (c *ConfigMapUnpacker) ensureJob(cmRef *corev1.ObjectReference, bundlePath string, secrets []corev1.LocalObjectReference, timeout time.Duration) (job *batchv1.Job, err error) { fresh := c.job(cmRef, bundlePath, secrets, timeout) job, err = c.jobLister.Jobs(fresh.GetNamespace()).Get(fresh.GetName()) if err != nil { if apierrors.IsNotFound(err) { job, err = c.client.BatchV1().Jobs(fresh.GetNamespace()).Create(context.TODO(), fresh, metav1.CreateOptions{}) } return } if equality.Semantic.DeepDerivative(fresh.GetOwnerReferences(), job.GetOwnerReferences()) && equality.Semantic.DeepDerivative(fresh.Spec, job.Spec) { return } // TODO: Decide when to fail-out instead of deleting the job err = c.client.BatchV1().Jobs(job.GetNamespace()).Delete(context.TODO(), job.GetName(), metav1.DeleteOptions{}) job = nil return } func (c *ConfigMapUnpacker) ensureRole(cmRef *corev1.ObjectReference) (role *rbacv1.Role, err error) { if cmRef == nil { return nil, fmt.Errorf("configmap reference is nil") } rule := rbacv1.PolicyRule{ APIGroups: []string{ "", }, Verbs: []string{ "create", "get", "update", }, Resources: []string{ "configmaps", }, ResourceNames: []string{ cmRef.Name, }, } fresh := &rbacv1.Role{ Rules: []rbacv1.PolicyRule{rule}, } fresh.SetNamespace(cmRef.Namespace) fresh.SetName(cmRef.Name) fresh.SetOwnerReferences([]metav1.OwnerReference{ownerRef(cmRef)}) fresh.SetLabels(map[string]string{install.OLMManagedLabelKey: install.OLMManagedLabelValue}) role, err = c.roleLister.Roles(fresh.GetNamespace()).Get(fresh.GetName()) if err != nil { if apierrors.IsNotFound(err) { role, err = c.client.RbacV1().Roles(fresh.GetNamespace()).Create(context.TODO(), fresh, metav1.CreateOptions{}) } return } // Add the policy rule if necessary for _, existing := range role.Rules { if equality.Semantic.DeepDerivative(rule, existing) { return } } role = role.DeepCopy() role.Rules = append(role.Rules, rule) role, err = c.client.RbacV1().Roles(role.GetNamespace()).Update(context.TODO(), role, metav1.UpdateOptions{}) return } func (c *ConfigMapUnpacker) ensureRoleBinding(cmRef *corev1.ObjectReference) (roleBinding *rbacv1.RoleBinding, err error) { fresh := &rbacv1.RoleBinding{ Subjects: []rbacv1.Subject{ { Kind: "ServiceAccount", APIGroup: "", Name: "default", Namespace: cmRef.Namespace, }, }, RoleRef: rbacv1.RoleRef{ APIGroup: "rbac.authorization.k8s.io", Kind: "Role", Name: cmRef.Name, }, } fresh.SetNamespace(cmRef.Namespace) fresh.SetName(cmRef.Name) fresh.SetOwnerReferences([]metav1.OwnerReference{ownerRef(cmRef)}) fresh.SetLabels(map[string]string{install.OLMManagedLabelKey: install.OLMManagedLabelValue}) roleBinding, err = c.rbLister.RoleBindings(fresh.GetNamespace()).Get(fresh.GetName()) if err != nil { if apierrors.IsNotFound(err) { roleBinding, err = c.client.RbacV1().RoleBindings(fresh.GetNamespace()).Create(context.TODO(), fresh, metav1.CreateOptions{}) } return } if equality.Semantic.DeepDerivative(fresh.Subjects, roleBinding.Subjects) && equality.Semantic.DeepDerivative(fresh.RoleRef, roleBinding.RoleRef) { return } // TODO: Decide when to fail-out instead of deleting the rbac err = c.client.RbacV1().RoleBindings(roleBinding.GetNamespace()).Delete(context.TODO(), roleBinding.GetName(), metav1.DeleteOptions{}) roleBinding = nil return } // hash hashes data with sha256 and returns the hex string. func hash(data string) string { // A SHA256 hash is 64 characters, which is within the 253 character limit for kube resource names h := fmt.Sprintf("%x", sha256.Sum256([]byte(data))) // Make the hash 63 characters instead to comply with the 63 character limit for labels return fmt.Sprintf(h[:len(h)-1]) } var blockOwnerDeletion = false // ownerRef converts an ObjectReference to an OwnerReference. func ownerRef(ref *corev1.ObjectReference) metav1.OwnerReference { return metav1.OwnerReference{ APIVersion: ref.APIVersion, Kind: ref.Kind, Name: ref.Name, UID: ref.UID, Controller: &blockOwnerDeletion, BlockOwnerDeletion: &blockOwnerDeletion, } } // getCondition returns true if the given job has the given condition with the given condition type true, and returns false otherwise. // Also returns the condition if true func getCondition(job *batchv1.Job, conditionType batchv1.JobConditionType) (condition *batchv1.JobCondition, isTrue bool) { if job == nil { return } for _, cond := range job.Status.Conditions { if cond.Type == conditionType && cond.Status == corev1.ConditionTrue { condition = &cond isTrue = true return } } return } // OperatorGroupBundleUnpackTimeout returns bundle timeout from annotation if specified. // If the timeout annotation is not set, return timeout < 0 which is subsequently ignored. // This is to overrides the --bundle-unpack-timeout flag value on per-OperatorGroup basis. func OperatorGroupBundleUnpackTimeout(ogLister v1listers.OperatorGroupNamespaceLister) (time.Duration, error) { ignoreTimeout := -1 * time.Minute ogs, err := ogLister.List(k8slabels.Everything()) if err != nil { return ignoreTimeout, err } if len(ogs) != 1 { return ignoreTimeout, fmt.Errorf("found %d operatorGroups, expected 1", len(ogs)) } timeoutStr, ok := ogs[0].GetAnnotations()[BundleUnpackTimeoutAnnotationKey] if !ok { return ignoreTimeout, nil } d, err := time.ParseDuration(timeoutStr) if err != nil { return ignoreTimeout, fmt.Errorf("failed to parse unpack timeout annotation(%s: %s): %w", BundleUnpackTimeoutAnnotationKey, timeoutStr, err) } return d, nil }
package test import ( "fmt" "gengine/builder" "gengine/context" "gengine/engine" "testing" "time" ) const inverse_rules = ` rule "1000" "most priority" salience 1000 begin cal.Data = 5 end rule "998" "lower priority" salience 998 begin cal.Name = "hello world" end rule "996" "lowest priority" salience 996 begin println("cal.Data-->", cal.Data) println("cal.Name-->", cal.Name) end ` type Calculate struct { Data int Name string } func Test_inverse(t *testing.T) { dataContext := context.NewDataContext() //inject struct calculate := &Calculate{Data: 0} dataContext.Add("cal", calculate) //rename and inject dataContext.Add("println", fmt.Println) //init rule engine ruleBuilder := builder.NewRuleBuilder(dataContext) //读取规则 e1 := ruleBuilder.BuildRuleFromString(inverse_rules) if e1 != nil { panic(e1) } eng := engine.NewGengine() e2 := eng.ExecuteInverseMixModel(ruleBuilder) if e2 != nil { panic(e2) } } func Test_inverse_with_selected(t *testing.T) { dataContext := context.NewDataContext() //inject struct calculate := &Calculate{Data: 0} dataContext.Add("cal", calculate) //rename and inject dataContext.Add("println", fmt.Println) //init rule engine ruleBuilder := builder.NewRuleBuilder(dataContext) //读取规则 e1 := ruleBuilder.BuildRuleFromString(inverse_rules) if e1 != nil { panic(e1) } eng := engine.NewGengine() e2 := eng.ExecuteSelectedRulesInverseMixModel(ruleBuilder, []string{"996", "1000"}) if e2 != nil { panic(e2) } } func Test_inverse_pool(t *testing.T) { t1 := time.Now() apis := make(map[string]interface{}) apis["println"] = fmt.Println pool, e1 := engine.NewGenginePool(1, 2, 4, inverse_rules, apis) if e1 != nil { println(fmt.Sprintf("e1: %+v", e1)) } println("build pool cost time:", time.Since(t1), "ns") calculate := &Calculate{Data: 0} data := make(map[string]interface{}) data["cal"] = calculate e2, _ := pool.ExecuteInverseMixModel(data) if e2 != nil { panic(e2) } } func Test_inverse_select_pool(t *testing.T) { t1 := time.Now() apis := make(map[string]interface{}) apis["println"] = fmt.Println pool, e1 := engine.NewGenginePool(1, 2, 4, inverse_rules, apis) if e1 != nil { println(fmt.Sprintf("e1: %+v", e1)) } println("build pool cost time:", time.Since(t1), "ns") calculate := &Calculate{Data: 0} data := make(map[string]interface{}) data["cal"] = calculate e2, _ := pool.ExecuteSelectedRulesInverseMixModel(data, []string{"996", "1000"}) if e2 != nil { panic(e2) } } func Test_select_pool(t *testing.T) { t1 := time.Now() apis := make(map[string]interface{}) apis["println"] = fmt.Println pool, e1 := engine.NewGenginePool(1, 2, 4, inverse_rules, apis) if e1 != nil { println(fmt.Sprintf("e1: %+v", e1)) } println("build pool cost time:", time.Since(t1), "ns") calculate := &Calculate{Data: 0} data := make(map[string]interface{}) data["cal"] = calculate e2, _ := pool.ExecuteSelectedWithSpecifiedEM(data, []string{"996", "1000"}) if e2 != nil { panic(e2) } } func Test_base_pool(t *testing.T) { t1 := time.Now() apis := make(map[string]interface{}) apis["println"] = fmt.Println pool, e1 := engine.NewGenginePool(1, 2, 4, inverse_rules, apis) if e1 != nil { println(fmt.Sprintf("e1: %+v", e1)) } println("build pool cost time:", time.Since(t1), "ns") calculate := &Calculate{Data: 0} data := make(map[string]interface{}) data["cal"] = calculate //e2 := pool.ExecuteRulesWithMultiInputAndStopTag(data, &engine.Stag{StopTag:false}) e2, _ := pool.ExecuteRulesWithMultiInputWithSpecifiedEM(data) if e2 != nil { panic(e2) } }
package user import ( "backend/user/models" "backend/utils/response" ) // User 用户序列化器 type Serializer struct { ID int `json:"id"` UserName string `json:"name"` Nickname string `json:"nick_name"` Status string `json:"status"` Avatar string `json:"avatar"` Admin bool `json:"admin"` Role string `json:"role"` CreatedAt int `json:"created_at"` } // UserResponse 单个用户序列化 type Response struct { Data models.User `json:"user"` } // BuildUser 序列化用户 func BuildUser(user models.User) Serializer { return Serializer{ ID: user.ID, UserName: user.Username, Nickname: user.Nickname, Status: user.Status, Avatar: user.Avatar, Admin: user.SuperUser, Role: user.Role, //CreatedAt: user.CreatedOn, } } // BuildUserResponse 序列化用户响应 func DefaultUserResponse(user models.User) response.Response { successResponse := response.Response{}.SuccessResponse() successResponse.Data = BuildUser(user) return successResponse }
package main import ( "encoding/json" "flag" "log" "net" "net/http" "os" "os/exec" "runtime" ) type Message struct { Message string `json:"message"` } const ( helloWorldString = "Hello, World!" ) var ( helloWorldBytes = []byte(helloWorldString) ) var prefork = flag.Bool("prefork", false, "use prefork") var child = flag.Bool("child", false, "is child proc") func main() { var listener net.Listener flag.Parse() if !*prefork { runtime.GOMAXPROCS(runtime.NumCPU()) } else { listener = doPrefork() } http.HandleFunc("/json", jsonHandler) http.HandleFunc("/plaintext", plaintextHandler) if !*prefork { http.ListenAndServe(":8080", nil) } else { http.Serve(listener, nil) } } func doPrefork() net.Listener { var listener net.Listener if !*child { addr, err := net.ResolveTCPAddr("tcp", ":8080") if err != nil { log.Fatal(err) } tcplistener, err := net.ListenTCP("tcp", addr) if err != nil { log.Fatal(err) } fl, err := tcplistener.File() if err != nil { log.Fatal(err) } children := make([]*exec.Cmd, runtime.NumCPU()/2) for i := range children { children[i] = exec.Command(os.Args[0], "-prefork", "-child") children[i].Stdout = os.Stdout children[i].Stderr = os.Stderr children[i].ExtraFiles = []*os.File{fl} err = children[i].Start() if err != nil { log.Fatal(err) } } for _, ch := range children { if err := ch.Wait(); err != nil { log.Print(err) } } os.Exit(0) } else { var err error listener, err = net.FileListener(os.NewFile(3, "")) if err != nil { log.Fatal(err) } } return listener } // Test 1: JSON serialization func jsonHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Server", "Go") w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(&Message{helloWorldString}) } // Test 6: Plaintext func plaintextHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Server", "Go") w.Header().Set("Content-Type", "text/plain") w.Write(helloWorldBytes) }
// // Copyright 2020 IBM Corporation // // 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 resources import ( "reflect" "github.com/IBM/ibm-auditlogging-operator/controllers/constant" utils "github.com/IBM/ibm-auditlogging-operator/controllers/util" certmgr "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1alpha1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) const GodIssuer = "audit-god-issuer" const RootIssuer = "audit-root-ca-issuer" // BuildGodIssuer returns an Issuer object func BuildGodIssuer(namespace string) *certmgr.Issuer { metaLabels := utils.LabelsForMetadata(constant.FluentdName) return &certmgr.Issuer{ ObjectMeta: metav1.ObjectMeta{ Name: GodIssuer, Namespace: namespace, Labels: metaLabels, }, Spec: certmgr.IssuerSpec{ IssuerConfig: certmgr.IssuerConfig{ SelfSigned: &certmgr.SelfSignedIssuer{}, }, }, } } // BuildRootCAIssuer returns an Issuer object func BuildRootCAIssuer(namespace string) *certmgr.Issuer { metaLabels := utils.LabelsForMetadata(constant.FluentdName) return &certmgr.Issuer{ ObjectMeta: metav1.ObjectMeta{ Name: RootIssuer, Namespace: namespace, Labels: metaLabels, }, Spec: certmgr.IssuerSpec{ IssuerConfig: certmgr.IssuerConfig{ CA: &certmgr.CAIssuer{ SecretName: RootCert, }, }, }, } } // EqualIssuers returns a boolean func EqualIssuers(expected *certmgr.Issuer, found *certmgr.Issuer) bool { return !reflect.DeepEqual(expected.Spec, found.Spec) }
package server import ( "context" "fmt" "time" "github.com/CyCoreSystems/ari" "github.com/CyCoreSystems/ari-proxy/proxy" "github.com/CyCoreSystems/ari-proxy/server/dialog" "github.com/CyCoreSystems/ari/client/native" "github.com/inconshreveable/log15" "github.com/nats-io/nats" "github.com/pkg/errors" ) // Server describes the asterisk-facing ARI proxy server type Server struct { // Application is the name of the ARI application of this server Application string // AsteriskID is the unique identifier for the Asterisk box // to which this server is connected. AsteriskID string // NATSPrefix is the string which should be prepended to all NATS subjects, sending and receiving. It defaults to "ari.". NATSPrefix string // ari is the native Asterisk ARI client by which this proxy is directly connected ari ari.Client // nats is the JSON-encoded NATS connection nats *nats.EncodedConn // Dialog is the dialog manager Dialog dialog.Manager readyCh chan struct{} // cancel is the context cancel function, by which all subtended subscriptions may be terminated cancel context.CancelFunc // Log is the log15.Logger for the service. You may replace or call SetHandler() on this at any time to change the logging of the service. Log log15.Logger } // New returns a new Server func New() *Server { log := log15.New() log.SetHandler(log15.DiscardHandler()) return &Server{ NATSPrefix: "ari.", readyCh: make(chan struct{}), Dialog: dialog.NewMemManager(), Log: log, } } // Listen runs the given server, listening to ARI and NATS, as specified func (s *Server) Listen(ctx context.Context, ariOpts *native.Options, natsURI string) (err error) { ctx, cancel := context.WithCancel(ctx) s.cancel = cancel // Connect to ARI s.ari, err = native.Connect(ariOpts) if err != nil { return errors.Wrap(err, "failed to connect to ARI") } defer s.ari.Close() // Connect to NATS nc, err := nats.Connect(natsURI) if err != nil { return errors.Wrap(err, "failed to connect to NATS") } s.nats, err = nats.NewEncodedConn(nc, nats.JSON_ENCODER) if err != nil { return errors.Wrap(err, "failed to encode NATS connection") } defer s.nats.Close() return s.listen(ctx) } // ListenOn runs the given server, listening on the provided ARI and NATS connections func (s *Server) ListenOn(ctx context.Context, a ari.Client, n *nats.EncodedConn) error { ctx, cancel := context.WithCancel(ctx) s.cancel = cancel s.ari = a s.nats = n return s.listen(ctx) } // Ready returns a channel which is closed when the Server is ready func (s *Server) Ready() <-chan struct{} { if s.readyCh == nil { s.readyCh = make(chan struct{}) } return s.readyCh } // nolint: gocyclo func (s *Server) listen(ctx context.Context) error { s.Log.Debug("starting listener") var wg closeGroup defer func() { select { case <-wg.Done(): case <-time.After(500 * time.Millisecond): panic("timeout waiting for shutdown of sub components") } }() // First, get the Asterisk ID ret, err := s.ari.Asterisk().Info(nil) if err != nil { return errors.Wrap(err, "failed to get Asterisk ID") } s.AsteriskID = ret.SystemInfo.EntityID if s.AsteriskID == "" { return errors.New("empty Asterisk ID") } // Store the ARI application name for top-level access s.Application = s.ari.ApplicationName() // // Listen on the initial NATS subjects // // ping handler pingSub, err := s.nats.Subscribe(proxy.PingSubject(s.NATSPrefix), s.pingHandler) if err != nil { return errors.Wrap(err, "failed to subscribe to pings") } defer wg.Add(pingSub.Unsubscribe) // get a contextualized request handler requestHandler := s.newRequestHandler(ctx) // get handlers allGet, err := s.nats.Subscribe(proxy.Subject(s.NATSPrefix, "get", "", ""), requestHandler) if err != nil { return errors.Wrap(err, "failed to create get-all subscription") } defer wg.Add(allGet.Unsubscribe)() appGet, err := s.nats.Subscribe(proxy.Subject(s.NATSPrefix, "get", s.Application, ""), requestHandler) if err != nil { return errors.Wrap(err, "failed to create get-app subscription") } defer wg.Add(appGet.Unsubscribe)() idGet, err := s.nats.Subscribe(proxy.Subject(s.NATSPrefix, "get", s.Application, s.AsteriskID), requestHandler) if err != nil { return errors.Wrap(err, "failed to create get-id subscription") } defer wg.Add(idGet.Unsubscribe)() // data handlers allData, err := s.nats.Subscribe(proxy.Subject(s.NATSPrefix, "data", "", ""), requestHandler) if err != nil { return errors.Wrap(err, "failed to create data-all subscription") } defer wg.Add(allData.Unsubscribe)() appData, err := s.nats.Subscribe(proxy.Subject(s.NATSPrefix, "data", s.Application, ""), requestHandler) if err != nil { return errors.Wrap(err, "failed to create data-app subscription") } defer wg.Add(appData.Unsubscribe)() idData, err := s.nats.Subscribe(proxy.Subject(s.NATSPrefix, "data", s.Application, s.AsteriskID), requestHandler) if err != nil { return errors.Wrap(err, "failed to create data-id subscription") } defer wg.Add(idData.Unsubscribe)() // command handlers allCommand, err := s.nats.Subscribe(proxy.Subject(s.NATSPrefix, "command", "", ""), requestHandler) if err != nil { return errors.Wrap(err, "failed to create command-all subscription") } defer wg.Add(allCommand.Unsubscribe)() appCommand, err := s.nats.Subscribe(proxy.Subject(s.NATSPrefix, "command", s.Application, ""), requestHandler) if err != nil { return errors.Wrap(err, "failed to create command-app subscription") } defer wg.Add(appCommand.Unsubscribe)() idCommand, err := s.nats.Subscribe(proxy.Subject(s.NATSPrefix, "command", s.Application, s.AsteriskID), requestHandler) if err != nil { return errors.Wrap(err, "failed to create command-id subscription") } defer wg.Add(idCommand.Unsubscribe)() // create handlers allCreate, err := s.nats.QueueSubscribe(proxy.Subject(s.NATSPrefix, "create", "", ""), "ariproxy", requestHandler) if err != nil { return errors.Wrap(err, "failed to create create-all subscription") } defer wg.Add(allCreate.Unsubscribe)() appCreate, err := s.nats.QueueSubscribe(proxy.Subject(s.NATSPrefix, "create", s.Application, ""), "ariproxy", requestHandler) if err != nil { return errors.Wrap(err, "failed to create create-app subscription") } defer wg.Add(appCreate.Unsubscribe)() idCreate, err := s.nats.QueueSubscribe(proxy.Subject(s.NATSPrefix, "create", s.Application, s.AsteriskID), "ariproxy", requestHandler) if err != nil { return errors.Wrap(err, "failed to create create-id subscription") } defer wg.Add(idCreate.Unsubscribe)() // Run the periodic announcer go s.runAnnouncer(ctx) // Run the event handler go s.runEventHandler(ctx) // TODO: run the dialog cleanup routine (remove bindings for entities which no longer exist) //go s.runDialogCleaner(ctx) // Close the readyChannel to indicate that we are operational if s.readyCh != nil { close(s.readyCh) } // Wait for context closure to exit <-ctx.Done() return ctx.Err() } // runAnnouncer runs the periodic discovery announcer func (s *Server) runAnnouncer(ctx context.Context) { ticker := time.NewTicker(proxy.AnnouncementInterval) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: s.announce() } } } // announce publishes the presence of this server to the cluster func (s *Server) announce() { s.publish(proxy.AnnouncementSubject(s.NATSPrefix), &proxy.Announcement{ Node: s.AsteriskID, Application: s.Application, }) } // runEventHandler processes events which are received from ARI func (s *Server) runEventHandler(ctx context.Context) { sub := s.ari.Bus().Subscribe(nil, ari.Events.All) defer sub.Cancel() for { s.Log.Debug("listening for events", "application", s.Application) select { case <-ctx.Done(): return case e := <-sub.Events(): s.Log.Debug("event received", "kind", e.GetType()) // Publish event to canonical destination s.publish(fmt.Sprintf("%sevent.%s.%s", s.NATSPrefix, s.Application, s.AsteriskID), e) // Publish event to any associated dialogs for _, d := range s.dialogsForEvent(e) { de := e de.SetDialog(d) s.publish(fmt.Sprintf("%sdialogevent.%s", s.NATSPrefix, d), de) } } } } // pingHandler publishes the server's presence func (s *Server) pingHandler(m *nats.Msg) { s.announce() } // publish sends a message out over NATS, logging any error func (s *Server) publish(subject string, msg interface{}) { if err := s.nats.Publish(subject, msg); err != nil { s.Log.Warn("failed to publish NATS message", "subject", subject, "data", msg, "error", err) } } // newRequestHandler returns a context-wrapped nats.Handler to handle requests func (s *Server) newRequestHandler(ctx context.Context) func(subject string, reply string, req *proxy.Request) { return func(subject string, reply string, req *proxy.Request) { go s.dispatchRequest(ctx, reply, req) } } // TODO: see if there is a more programmatic approach to this // nolint: gocyclo func (s *Server) dispatchRequest(ctx context.Context, reply string, req *proxy.Request) { var f func(context.Context, string, *proxy.Request) s.Log.Debug("received request", "kind", req.Kind) switch req.Kind { case "ApplicationData": f = s.applicationData case "ApplicationGet": f = s.applicationGet case "ApplicationList": f = s.applicationList case "ApplicationSubscribe": f = s.applicationSubscribe case "ApplicationUnsubscribe": f = s.applicationUnsubscribe case "AsteriskConfigData": f = s.asteriskConfigData case "AsteriskConfigDelete": f = s.asteriskConfigDelete case "AsteriskConfigUpdate": f = s.asteriskConfigUpdate case "AsteriskLoggingCreate": f = s.asteriskLoggingCreate case "AsteriskLoggingData": f = s.asteriskLoggingData case "AsteriskLoggingDelete": f = s.asteriskLoggingDelete case "AsteriskLoggingGet": f = s.asteriskLoggingGet case "AsteriskLoggingList": f = s.asteriskLoggingList case "AsteriskLoggingRotate": f = s.asteriskLoggingRotate case "AsteriskModuleData": f = s.asteriskModuleData case "AsteriskModuleGet": f = s.asteriskModuleGet case "AsteriskModuleLoad": f = s.asteriskModuleLoad case "AsteriskModuleList": f = s.asteriskModuleList case "AsteriskModuleReload": f = s.asteriskModuleReload case "AsteriskModuleUnload": f = s.asteriskModuleUnload case "AsteriskInfo": f = s.asteriskInfo case "AsteriskVariableGet": f = s.asteriskVariableGet case "AsteriskVariableSet": f = s.asteriskVariableSet case "BridgeAddChannel": f = s.bridgeAddChannel case "BridgeCreate": f = s.bridgeCreate case "BridgeStageCreate": f = s.bridgeStageCreate case "BridgeData": f = s.bridgeData case "BridgeDelete": f = s.bridgeDelete case "BridgeGet": f = s.bridgeGet case "BridgeList": f = s.bridgeList case "BridgeMOH": f = s.bridgeMOH case "BridgeStopMOH": f = s.bridgeStopMOH case "BridgePlay": f = s.bridgePlay case "BridgeStagePlay": f = s.bridgeStagePlay case "BridgeRecord": f = s.bridgeRecord case "BridgeStageRecord": f = s.bridgeStageRecord case "BridgeRemoveChannel": f = s.bridgeRemoveChannel case "BridgeSubscribe": f = s.bridgeSubscribe case "BridgeUnsubscribe": f = s.bridgeUnsubscribe case "ChannelAnswer": f = s.channelAnswer case "ChannelBusy": f = s.channelBusy case "ChannelCongestion": f = s.channelCongestion case "ChannelCreate": f = s.channelCreate case "ChannelContinue": f = s.channelContinue case "ChannelData": f = s.channelData case "ChannelDial": f = s.channelDial case "ChannelGet": f = s.channelGet case "ChannelHangup": f = s.channelHangup case "ChannelHold": f = s.channelHold case "ChannelList": f = s.channelList case "ChannelMOH": f = s.channelMOH case "ChannelMute": f = s.channelMute case "ChannelOriginate": f = s.channelOriginate case "ChannelStageOriginate": f = s.channelStageOriginate case "ChannelPlay": f = s.channelPlay case "ChannelStagePlay": f = s.channelStagePlay case "ChannelRecord": f = s.channelRecord case "ChannelStageRecord": f = s.channelStageRecord case "ChannelRing": f = s.channelRing case "ChannelSendDTMF": f = s.channelSendDTMF case "ChannelSilence": f = s.channelSilence case "ChannelSnoop": f = s.channelSnoop case "ChannelStageSnoop": f = s.channelStageSnoop case "ChannelStopHold": f = s.channelStopHold case "ChannelStopMOH": f = s.channelStopMOH case "ChannelStopRing": f = s.channelStopRing case "ChannelStopSilence": f = s.channelStopSilence case "ChannelSubscribe": f = s.channelSubscribe case "ChannelUnmute": f = s.channelUnmute case "ChannelVariableGet": f = s.channelVariableGet case "ChannelVariableSet": f = s.channelVariableSet case "DeviceStateData": f = s.deviceStateData case "DeviceStateDelete": f = s.deviceStateDelete case "DeviceStateGet": f = s.deviceStateGet case "DeviceStateList": f = s.deviceStateList case "DeviceStateUpdate": f = s.deviceStateUpdate case "EndpointData": f = s.endpointData case "EndpointGet": f = s.endpointGet case "EndpointList": f = s.endpointList case "EndpointListByTech": f = s.endpointListByTech case "MailboxData": f = s.mailboxData case "MailboxDelete": f = s.mailboxDelete case "MailboxGet": f = s.mailboxGet case "MailboxList": f = s.mailboxList case "MailboxUpdate": f = s.mailboxUpdate case "PlaybackControl": f = s.playbackControl case "PlaybackData": f = s.playbackData case "PlaybackGet": f = s.playbackGet case "PlaybackStop": f = s.playbackStop case "PlaybackSubscribe": f = s.playbackSubscribe case "RecordingStoredCopy": f = s.recordingStoredCopy case "RecordingStoredData": f = s.recordingStoredData case "RecordingStoredDelete": f = s.recordingStoredDelete case "RecordingStoredGet": f = s.recordingStoredGet case "RecordingStoredList": f = s.recordingStoredList case "RecordingLiveData": f = s.recordingLiveData case "RecordingLiveGet": f = s.recordingLiveGet case "RecordingLiveMute": f = s.recordingLiveMute case "RecordingLivePause": f = s.recordingLivePause case "RecordingLiveResume": f = s.recordingLiveResume case "RecordingLiveScrap": f = s.recordingLiveScrap case "RecordingLiveSubscribe": f = s.recordingLiveSubscribe case "RecordingLiveStop": f = s.recordingLiveStop case "RecordingLiveUnmute": f = s.recordingLiveUnmute case "SoundData": f = s.soundData case "SoundList": f = s.soundList default: f = func(ctx context.Context, reply string, req *proxy.Request) { s.sendError(reply, errors.New("Not implemented")) } } f(ctx, reply, req) } func (s *Server) sendError(reply string, err error) { s.publish(reply, proxy.NewErrorResponse(err)) } /* // Start runs the server side instance func (i *Instance) Start(ctx context.Context) { i.ctx, i.cancel = context.WithCancel(ctx) i.log.Debug("Starting dialog instance") go func() { i.application() i.asterisk() i.modules() i.channel() i.storedRecording() i.liveRecording() i.bridge() i.device() i.playback() i.mailbox() i.sound() i.logging() i.config() // do commands last, since that is the one that will be dispatching i.commands() close(i.readyCh) <-i.ctx.Done() }() <-i.readyCh } // Stop stops the instance func (i *Instance) Stop() { if i == nil { return } i.cancel() } func (i *Instance) String() string { return fmt.Sprintf("Instance{%s}", i.Dialog.ID) } */
package model // defining player data type type Players struct { Name string Counter int Score int }
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "os" "strconv" ) const usage = ` usage: todo COMMAND Commands: samples Get sample todo tasks all Get all todo tasks add Add new todo task delete Remove a todo task ` func main() { if len(os.Args) < 2 { fmt.Print(usage) return } switch command := os.Args[1]; command { case "samples": get("samples") case "all": get("todo") case "add": add() case "delete": del() default: fmt.Printf("'%s' is not a todo command.", command) } } func get(path string) { res, err := http.Get(fmt.Sprintf("http://localhost:8080/%s", path)) if err != nil { panic(err) } defer res.Body.Close() b, err := ioutil.ReadAll(res.Body) if err != nil { panic(err) } if len(b) == 0 { fmt.Println("The response is empty.") return } fmt.Println(string(b)) } const usage_add = ` usage: todo add TODO_NAME TODO_NOTE DUE_DATE ` func add() { if len(os.Args) < 3 { fmt.Print(usage_add) return } name := os.Args[2] var note string var date string if len(os.Args) > 3 { note = os.Args[3] if len(os.Args) > 4 { date = os.Args[4] } } todo := struct { Title string `json:"title"` Note string `json:"note,omitempty"` DueDate string `json:"due_date,omitempty"` }{ name, note, date, } b, err := json.Marshal(todo) if err != nil { panic(err) } fmt.Println(string(b)) res, err := http.Post("http://localhost:8080/todo", "application/json", bytes.NewReader(b)) if err != nil { panic(err) } defer res.Body.Close() b, err = ioutil.ReadAll(res.Body) if err != nil { panic(err) } fmt.Println(string(b)) } func del() { if len(os.Args) < 3 { fmt.Print("usage: todo delete TASK_ID") return } id, err := strconv.Atoi(os.Args[2]) if err != nil { fmt.Println("TASK_ID should be number") return } b, err := json.Marshal(map[string]int{"id": id}) if err != nil { panic(err) } req, err := http.NewRequest(http.MethodDelete, "http://localhost:8080/todo", bytes.NewReader(b)) if err != nil { panic(err) } client := &http.Client{} res, err := client.Do(req) if err != nil { panic(err) } res.Body.Close() }
package main import ( "fmt" "log" "net/http" "os" "cloud.google.com/go/datastore" "golang.org/x/net/context" ) func main() { ctx := context.Background() log.SetOutput(os.Stderr) // Set this in app.yaml when running in production. projectID := os.Getenv("GCLOUD_DATASET_ID") datastoreClient, err := datastore.NewClient(ctx, projectID) if err != nil { log.Fatal(err) } c := Controller{datastoreClient} http.HandleFunc("/", c.handle) port := os.Getenv("PORT") if port == "" { port = "8080" log.Printf("Defaulting to port %s", port) } log.Printf("Listening on port %s", port) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil)) }
package model // AppSetting a struct to rep app settings account type AppSetting struct { BaseIntModel Name string `json:"name" gorm:"not null;type:varchar(50);"` SKey string `json:"s_key" gorm:"not null;type:varchar(100);unique_index"` Value string `json:"value" gorm:"not null;type:varchar(200)"` Comment string `json:"comment" gorm:"type:varchar(200)"` Status string `json:"status" gorm:"type:enum('active','disabled');default:'active'"` }
package main import ( "flag" "fmt" "net/http" "muto/controllers" "muto/middleware" "muto/models" "muto/rand" "github.com/gorilla/csrf" "github.com/gorilla/mux" ) func main() { // Production flag for ensuring .config file is provided. boolPtr := flag.Bool("prod", false, "Provide this flag "+ "in production. This ensures that a .config file is "+ "provided before the application starts.") flag.Parse() // Configuartion Information. // boolPtr is a pointer to a boolean, so we need to use // *boolPtr to get the boolean value and pass it // into our LoadConfig function. cfg := LoadConfig(*boolPtr) dbCfg := cfg.Database // Create a service, check for errors, // defer close until main func exits, // and call the AutoMigrate function. services, err := models.NewServices( models.WithGorm(dbCfg.Dialect(), dbCfg.ConnectionInfo()), // Only log when not in prod models.WithLogMode(!cfg.IsProd()), models.WithAccount(cfg.Pepper, cfg.HMACKey), models.WithGallery(), models.WithImage(), ) if err != nil { panic(err) } defer services.Close() services.AutoMigrate() // Controllers r := mux.NewRouter() staticC := controllers.NewStatic() accountsC := controllers.NewAccounts(services.Account) galleriesC := controllers.NewGalleries(services.Gallery, services.Image, r) // Middleware - Check Account Logged In AccountMw := middleware.Account{ AccountService: services.Account, } // Middleware - Require Account Logged In requireAccountMw := middleware.RequireAccount{} // Asset Routes assetHandler := http.FileServer(http.Dir("./assets/")) assetHandler = http.StripPrefix("/assets/", assetHandler) r.PathPrefix("/assets/").Handler(assetHandler) // Image Routes imageHandler := http.FileServer(http.Dir("./images/")) r.PathPrefix("/images/").Handler(http.StripPrefix("/images/", imageHandler)) // Static Routes r.Handle("/", staticC.LandingView).Methods("GET") r.Handle("/contact", staticC.ContactView).Methods("GET") r.Handle("/faq", staticC.FaqView).Methods("GET") r.Handle("/faq-question", staticC.FaqQuestionView).Methods("GET") r.Handle("/dashboard", staticC.DashboardView).Methods("GET") // Account Routes r.HandleFunc("/register", accountsC.New).Methods("GET") r.HandleFunc("/register", accountsC.Create).Methods("POST") r.Handle("/enter", accountsC.LoginView).Methods("GET") r.HandleFunc("/enter", accountsC.Login).Methods("POST") r.HandleFunc("/cookietest", accountsC.CookieTest).Methods("GET") // Gallery Routes r.Handle("/galleries/new", requireAccountMw.Apply(galleriesC.New)). Methods("GET") r.Handle("/galleries", requireAccountMw.ApplyFn(galleriesC.Create)). Methods("POST") r.HandleFunc("/galleries/{id:[0-9]+}", galleriesC.Show). Methods("GET"). Name(controllers.ShowGallery) r.HandleFunc("/galleries/{id:[0-9]+}/edit", requireAccountMw.ApplyFn(galleriesC.Edit)). Methods("GET"). Name(controllers.EditGallery) r.HandleFunc("/galleries/{id:[0-9]+}/update", requireAccountMw.ApplyFn(galleriesC.Update)). Methods("POST") r.HandleFunc("/galleries/{id:[0-9]+}/delete", requireAccountMw.ApplyFn(galleriesC.Delete)). Methods("POST") r.HandleFunc("/galleries", requireAccountMw.ApplyFn(galleriesC.Index)). Methods("GET"). Name(controllers.IndexGalleries) r.HandleFunc("/galleries/{id:[0-9]+}/images", requireAccountMw.ApplyFn(galleriesC.ImageUpload)). Methods("POST") r.HandleFunc("/galleries/{id:[0-9]+}/images/{filename}/delete", requireAccountMw.ApplyFn(galleriesC.ImageDelete)). Methods("POST") b, err := rand.Bytes(32) if err != nil { panic(err) } // CSRF Protection csrfMw := csrf.Protect(b, csrf.Secure(cfg.IsProd())) // Server Messages / Listen & Serve fmt.Printf("Starting the server on Port:%d...\n", cfg.Port) fmt.Println("Success! Application Compiled.") fmt.Println("Application Running...") http.ListenAndServe(fmt.Sprintf(":%d", cfg.Port), csrfMw(AccountMw.Apply(r))) }
package wordbreak import ( "fmt" "testing" ) func TestWordBreak(t *testing.T) { var tests = []struct { s string wordDict []string expect bool }{ {"catsanddog", []string{"cat", "cats", "and", "sand", "dog"}, true}, } for _, test := range tests { if got := wordBreak(test.s, test.wordDict); got != test.expect { t.Errorf("wordBreak(%v, %v) = %v (expected %v)", test.s, test.wordDict, got, test.expect) } } } func TestWordBreakII(t *testing.T) { var tests = []struct { s string wordDict []string expect string }{ {"catsanddog", []string{"cat", "cats", "and", "sand", "dog"}, "[\"cat sand dog\" \"cats and dog\"]"}, } for _, test := range tests { if got := fmt.Sprintf("%q", wordBreakII(test.s, test.wordDict)); got != test.expect { t.Errorf("wordBreakII(%v, %v) = %v (expected %v)", test.s, test.wordDict, got, test.expect) } } }
package main import "testing" func TestLargestPrimeFactor(t *testing.T) { tests := []struct { input int64 output int64 }{ {600851475143, 6857}, {13195, 29}, } for _, test := range tests { result := LargestPrimeFactor(test.input) if result != test.output { t.Errorf("%v should return %v, got %v", test.input, test.output, result) } } }
package cipher import ( "strings" "unicode" ) const firstLetterIndex = 'z' - 'a' + 1 type Vigenere struct { key string } func NewCaesar() Cipher { return NewShift(3) } func NewShift(distance int) Cipher { if distance == 0 || distance > 25 || distance < -25 { return nil } return NewVigenere(string(rune('a' + (firstLetterIndex+distance)%firstLetterIndex))) } func NewVigenere(key string) Cipher { isA := false isValid := true for i := 0; i < len(key); i++ { isLower := unicode.IsLower(rune(key[i])) if !isLower && isValid { isValid = false } if !isA && key[i] != 'a' { isA = true } } if !isA || !isValid { return nil } return &Vigenere{key} } func (cipher *Vigenere) Encode(msg string) string { msg = strings.ToLower(msg) var encrypted string var j int for i := 0; i < len(msg); i++ { if !unicode.IsLetter(rune(msg[i])) { continue } qq := cipher.key[j] - 'a' j++ if j == len(cipher.key) { j = 0 } aa := (msg[i] - 'a' + qq) % 26 encrypted += string(rune(aa + 'a')) } return encrypted } func (cipher *Vigenere) Decode(msg string) string { var decrypted string for i := 0; i < len(msg); i++ { if !unicode.IsLetter(rune(msg[i])) { continue } cipherChar := cipher.key[i%len(cipher.key)] decrypted = decrypted + string(rune('a' + ((msg[i]-'a')-(cipherChar-'a')+firstLetterIndex)%firstLetterIndex)) } return decrypted }
// populate scrapes reads command line arguments and searches rosettacode.org // for blocks of code listed under headings (programming language names) that // match those strings. The code blocks are saved under individual files with // extensions matched to the language or ".txt" as a default if the extension // is unknown. package main import ( "bytes" "fmt" "os" "path/filepath" "strings" "github.com/PuerkitoBio/goquery" "github.com/gocolly/colly" log "github.com/sirupsen/logrus" "golang.org/x/net/html" ) func main() { index := "http://rosettacode.org/wiki/Category:Programming_Tasks" langs := os.Args[1:] // normalize language names for i, l := range langs { langs[i] = slugUp(l) folder := filepath.Join("sources", langs[i]) err := os.MkdirAll(folder, os.ModePerm) if err != nil { log.Error(err) } } log.Info("Starting...") // scrapes programming challenges taskCollector := colly.NewCollector( colly.AllowedDomains("rosettacode.org"), colly.MaxDepth(1), ) // scrapes code blocks from a specific challenge codeCollector := colly.NewCollector( colly.AllowedDomains("rosettacode.org"), colly.Async(true), colly.MaxDepth(0), ) // get tasks taskCollector.OnHTML("div.mw-category", func(e *colly.HTMLElement) { task := e.ChildAttrs("a", "href") log.Info("tasks found:", len(task)) for i, t := range task { codeCollector.Visit(e.Request.AbsoluteURL(t)) if i > 0 { break } } }) // get code blocks codeCollector.OnRequest(func(r *colly.Request) { log.Info("Visiting:\t", r.URL.String()) }) codeCollector.OnResponse(func(r *colly.Response) { log.Info("Received response:\t", r.StatusCode) }) codeCollector.OnHTML("h2", func(e *colly.HTMLElement) { i, ok := find(strings.ToUpper(e.ChildAttr("span", "id")), langs) if ok { log.Info("Found a match") // Get all pre.highlighted_source blocks up to the next title block sel := e.DOM.NextUntil("h2") blocks := sel.Filter("pre.highlighted_source") // assign common variables for writing algoURL := strings.Split(e.Request.URL.Path, "/") algo := algoURL[len(algoURL)-1] ext, ok := findExt(langs[i]) if !ok { ext = "txt" } // We need to preserve <br> tags to make newlines. log.Info("Writing to files...") blocks.Each(func(j int, s *goquery.Selection) { fileName := fmt.Sprint(algo, "_", j, ".", ext) path := filepath.Join("sources", langs[i], fileName) f, err := os.Create(path) defer f.Close() if err != nil { log.Error(err) return } _, err = f.WriteString(customText(s)) if err != nil { log.Error(err) } }) // } }) log.Info("visiting: ", index) taskCollector.Visit(index) } // get the index of a matched string within a slice of strings func find(s string, col []string) (n int, ok bool) { for i, c := range col { if s == c { return i, true } } return 0, false } // slugify func slugUp(s string) string { return strings.ToUpper(strings.ReplaceAll(s, " ", "_")) } // container for map to match languages with their extensions func findExt(lang string) (e string, ok bool) { ext := map[string]string{ "PYTHON": "py", "PERL": "pl", "PERL_6": "p6", "RUBY": "rb", "PHP": "php", "C": "c", "C++": "cpp", "JAVA": "java", "SCHEME": "scm", "RUST": "rs", "GO": "go", } e, ok = ext[lang] return e, ok } // We need a customized modification of the Text method from goquery. // This will preserve <br> tags as newline characters to keep our output // code valid. func customText(s *goquery.Selection) string { var buf bytes.Buffer // Slightly optimized vs calling Each: no single selection object created var f func(*html.Node) f = func(n *html.Node) { if n.Type == html.TextNode { // We will get weird characters from the nbsp that we need to get rid // of. We may get additional white space, but that's not such a problem. d := strings.ReplaceAll(n.Data, "\xa0", "\x20") d = strings.ReplaceAll(d, "\xc2", "\x20") buf.WriteString(d) } // insert a newline where there is a <br> tag if n.Data == "br" { buf.WriteString("\n") } if n.FirstChild != nil { for c := n.FirstChild; c != nil; c = c.NextSibling { f(c) } } } for _, n := range s.Nodes { f(n) } return buf.String() }
package main import ( "bytes" // need to convert data into byte in order to be sent on the network, computer understands better the byte(8bits)language "crypto/sha256" //crypto library to hash the data "strconv" // for conversion "time" // use timestamp ) // Generating a hash of the block // We will just concatenate all the data and hash it to obtain the block hash func (block *Block) SetHash() { timestamp := []byte(strconv.FormatInt(block.Timestamp, 10)) // get the time and convert it into a unique series of digits headers := bytes.Join([][]byte{timestamp, block.PreviousBlockHash, block.BlockData}, []byte{}) // concatenate all the block data hash := sha256.Sum256(headers) block.BlockHash = hash[:] } // Block Generation and return that block func NewBlock(data string, prevBlockHash []byte) *Block { block := &Block{time.Now().Unix(), prevBlockHash, []byte{}, []byte(data)} // the block received block.SetHash() // the block is hashed return block // return the block } func NewGenesisBlock() *Block { return NewBlock("Genesis Block", []byte{}) // Creating genesis block with some data }
// +build !hosted package router func extractPath(host, path string) string { return path } func systemPathFromSpace(space string) string { return basePath } func systemPathFromURL(host, path string) string { return basePath }
package kit import ( "fmt" "path/filepath" "runtime" "strings" ) //common resource var MessageMap = map[string]map[int]string{ "en": { 10001: "System error", 10002: "A required parameter is missing or doesn't have the right format:%v", 10003: "%v is required", 10004: "The parameter format should be %v", 10005: "%v not exist", 10006: "%v failure", 10007: "No row is affected", 10008: "%v has a wrong format", 10009: "Routing is missing parameter: %v", 10011: "Please check the parameters contained in Fields:%v", 10012: "There is duplicate data:%v", 10013: "Save failed because:%v", 10015: "Token verifivation failed", 10016: "No data has been found", 10017: "Access to this API requires special permissions", 10018: "Two-dimensional code has expired", }, "zh": { 10001: "系统错误", 10002: "缺少必要的参数,或者参数格式不正确:%v", 10003: "%v 不能为空", 10004: "参数格式应该是 %v", 10005: "%v 不存在", 10006: "%v 失败", 10007: "没有数据被改变", 10008: "%v 有一个错误的格式", 10009: "路由缺少参数:%v", 10011: "请检查Fields所包含的参数:%v", 10012: "存在重复的数据:%v", 10013: "保存失败,原因是:%v", 10015: "Token验证失败", 10016: "没有查询到数据", 10017: "访问此API,需要特殊的权限", 10018: "二维码已过期", }, "ko": { 10001: "시스템 오류입니다.", 10002: "필요되는 파라미터가 없거나 파라미터 포맷이 정확하지 않습니다:%v", 10003: "%v 가 빈값이면 안됩니다.", 10004: "파라미터 포맷은 %v 입니다.", 10005: "%v 존재하지 않습니다.", 10006: "%v 실패하였습니다.", 10007: "변경된 데이터가 없습니다.", 10008: "%v 에 오류 포맷이 존재합니다.", 10009: "루팅에 파라미터가 부족합니다. %v", 10011: "Fields에 포함된 파라미터 %v를 점검하세요.", 10012: "중복된 데이터가 존재합니다. %v", 10013: "저장실패하였습니다. 원인:%v", 10015: "Token인증실패", 10016: "조회된 데이터가 없습니다.", 10017: "Access to this API requires special permissions", 10018: "큐알코드 시간초과하였습니다.", }, } // Parse accept-language in header to convert it as: tw, en, jp ... func ParseAcceptLang(acceptLang string) string { // 1. Chrome: [zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4] // 2. Safari: [zh-tw] // 3. FF: [zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3] // // Ret: zh or en ... tarStrings := strings.Split(acceptLang, ";") if len(strings.Split(tarStrings[0], ",")) > 1 { return strings.Split(tarStrings[0], ",")[1] } return strings.Split(tarStrings[0], "-")[0] } var Lang []string func MessageString(resourceKey int, params ...interface{}) string { langStr := strings.Join(Lang[:], ";") currntLang := ParseAcceptLang(langStr) if len(currntLang) != 2 { currntLang = "en" } var message string if len(params) == 0 { message = MessageMap[currntLang][resourceKey] } else { message = fmt.Sprintf(MessageMap[currntLang][resourceKey], params...) } return message } func SystemMessage(detail string) *Result { return NewApiMessage(10001, detail) } func NewApiError(resourceKey int, details string, params ...interface{}) (apiError Error) { return Error{Code: resourceKey, Message: MessageString(resourceKey, params...), Details: details} } func NewApiStatusMessage(statusCode int, resourceKey int, details string, params ...interface{}) (statusMessage *StatusMessage) { pc, file, line, _ := runtime.Caller(1) fmt.Printf("%s:%d:\n\n\tmethod:%v\n\n\thttpStatusCode: %#v\n\n\tmessage: %#v\n\n\tdetails: %#v\n\n", filepath.Base(file), line, runtime.FuncForPC(pc).Name(), statusCode, MessageString(resourceKey, params...), details) return &StatusMessage{StatusCode: statusCode, Result: Result{Success: false, Error: NewApiError(resourceKey, details, params...)}} } func NewApiMessage(resourceKey int, details string, params ...interface{}) *Result { pc, file, line, _ := runtime.Caller(1) fmt.Printf("%s:%d:\n\n\tmethod:%v\n\n\tmessage: %#v\n\n\tdetails: %#v\n\n", filepath.Base(file), line, runtime.FuncForPC(pc).Name(), MessageString(resourceKey, params...), details) return &Result{Success: false, Error: NewApiError(resourceKey, details, params...)} }
/* * jQuery File Upload Plugin GAE Go Example 3.1.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ package app import ( "appengine" "appengine/blobstore" "appengine/image" "appengine/taskqueue" "bytes" "encoding/json" "fmt" "io" "log" "mime/multipart" "net/http" "net/url" "regexp" "strings" "time" ) const ( WEBSITE = "http://blueimp.github.io/jQuery-File-Upload/" MIN_FILE_SIZE = 1 // bytes MAX_FILE_SIZE = 5000000 // bytes IMAGE_TYPES = "image/(gif|p?jpeg|(x-)?png)" ACCEPT_FILE_TYPES = IMAGE_TYPES EXPIRATION_TIME = 300 // seconds THUMBNAIL_PARAM = "=s80" ) var ( imageTypes = regexp.MustCompile(IMAGE_TYPES) acceptFileTypes = regexp.MustCompile(ACCEPT_FILE_TYPES) ) type FileInfo struct { Key appengine.BlobKey `json:"-"` Url string `json:"url,omitempty"` ThumbnailUrl string `json:"thumbnailUrl,omitempty"` Name string `json:"name"` Type string `json:"type"` Size int64 `json:"size"` Error string `json:"error,omitempty"` DeleteUrl string `json:"deleteUrl,omitempty"` DeleteType string `json:"deleteType,omitempty"` } func (fi *FileInfo) ValidateType() (valid bool) { if acceptFileTypes.MatchString(fi.Type) { return true } fi.Error = "Filetype not allowed" return false } func (fi *FileInfo) ValidateSize() (valid bool) { if fi.Size < MIN_FILE_SIZE { fi.Error = "File is too small" } else if fi.Size > MAX_FILE_SIZE { fi.Error = "File is too big" } else { return true } return false } func (fi *FileInfo) CreateUrls(r *http.Request, c appengine.Context) { u := &url.URL{ Scheme: r.URL.Scheme, Host: appengine.DefaultVersionHostname(c), Path: "/", } uString := u.String() fi.Url = uString + escape(string(fi.Key)) + "/" + escape(string(fi.Name)) fi.DeleteUrl = fi.Url + "?delete=true" fi.DeleteType = "DELETE" if imageTypes.MatchString(fi.Type) { servingUrl, err := image.ServingURL( c, fi.Key, &image.ServingURLOptions{ Secure: strings.HasSuffix(u.Scheme, "s"), Size: 0, Crop: false, }, ) check(err) fi.ThumbnailUrl = servingUrl.String() + THUMBNAIL_PARAM } } func check(err error) { if err != nil { panic(err) } } func escape(s string) string { return strings.Replace(url.QueryEscape(s), "+", "%20", -1) } func delayedDelete(c appengine.Context, fi *FileInfo) { if key := string(fi.Key); key != "" { task := &taskqueue.Task{ Path: "/" + escape(key) + "/-", Method: "DELETE", Delay: time.Duration(EXPIRATION_TIME) * time.Second, } taskqueue.Add(c, task, "") } } func handleUpload(r *http.Request, p *multipart.Part) (fi *FileInfo) { fi = &FileInfo{ Name: p.FileName(), Type: p.Header.Get("Content-Type"), } if !fi.ValidateType() { return } defer func() { if rec := recover(); rec != nil { log.Println(rec) fi.Error = rec.(error).Error() } }() lr := &io.LimitedReader{R: p, N: MAX_FILE_SIZE + 1} context := appengine.NewContext(r) w, err := blobstore.Create(context, fi.Type) defer func() { w.Close() fi.Size = MAX_FILE_SIZE + 1 - lr.N fi.Key, err = w.Key() check(err) if !fi.ValidateSize() { err := blobstore.Delete(context, fi.Key) check(err) return } delayedDelete(context, fi) fi.CreateUrls(r, context) }() check(err) _, err = io.Copy(w, lr) return } func getFormValue(p *multipart.Part) string { var b bytes.Buffer io.CopyN(&b, p, int64(1<<20)) // Copy max: 1 MiB return b.String() } func handleUploads(r *http.Request) (fileInfos []*FileInfo) { fileInfos = make([]*FileInfo, 0) mr, err := r.MultipartReader() check(err) r.Form, err = url.ParseQuery(r.URL.RawQuery) check(err) part, err := mr.NextPart() for err == nil { if name := part.FormName(); name != "" { if part.FileName() != "" { fileInfos = append(fileInfos, handleUpload(r, part)) } else { r.Form[name] = append(r.Form[name], getFormValue(part)) } } part, err = mr.NextPart() } return } func get(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { http.Redirect(w, r, WEBSITE, http.StatusFound) return } parts := strings.Split(r.URL.Path, "/") if len(parts) == 3 { if key := parts[1]; key != "" { blobKey := appengine.BlobKey(key) bi, err := blobstore.Stat(appengine.NewContext(r), blobKey) if err == nil { w.Header().Add("X-Content-Type-Options", "nosniff") if !imageTypes.MatchString(bi.ContentType) { w.Header().Add("Content-Type", "application/octet-stream") w.Header().Add( "Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", parts[2]), ) } w.Header().Add( "Cache-Control", fmt.Sprintf("public,max-age=%d", EXPIRATION_TIME), ) blobstore.Send(w, blobKey) return } } } http.Error(w, "404 Not Found", http.StatusNotFound) } func post(w http.ResponseWriter, r *http.Request) { result := make(map[string][]*FileInfo, 1) result["files"] = handleUploads(r) b, err := json.Marshal(result) check(err) if redirect := r.FormValue("redirect"); redirect != "" { if strings.Contains(redirect, "%s") { redirect = fmt.Sprintf( redirect, escape(string(b)), ) } http.Redirect(w, r, redirect, http.StatusFound) return } w.Header().Set("Cache-Control", "no-cache") jsonType := "application/json" if strings.Index(r.Header.Get("Accept"), jsonType) != -1 { w.Header().Set("Content-Type", jsonType) } fmt.Fprintln(w, string(b)) } func delete(w http.ResponseWriter, r *http.Request) { parts := strings.Split(r.URL.Path, "/") if len(parts) != 3 { return } result := make(map[string]bool, 1) if key := parts[1]; key != "" { c := appengine.NewContext(r) blobKey := appengine.BlobKey(key) err := blobstore.Delete(c, blobKey) check(err) err = image.DeleteServingURL(c, blobKey) check(err) result[key] = true } jsonType := "application/json" if strings.Index(r.Header.Get("Accept"), jsonType) != -1 { w.Header().Set("Content-Type", jsonType) } b, err := json.Marshal(result) check(err) fmt.Fprintln(w, string(b)) } func handle(w http.ResponseWriter, r *http.Request) { params, err := url.ParseQuery(r.URL.RawQuery) check(err) w.Header().Add("Access-Control-Allow-Origin", "*") w.Header().Add( "Access-Control-Allow-Methods", "OPTIONS, HEAD, GET, POST, PUT, DELETE", ) w.Header().Add( "Access-Control-Allow-Headers", "Content-Type, Content-Range, Content-Disposition", ) switch r.Method { case "OPTIONS": case "HEAD": case "GET": get(w, r) case "POST": if len(params["_method"]) > 0 && params["_method"][0] == "DELETE" { delete(w, r) } else { post(w, r) } case "DELETE": delete(w, r) default: http.Error(w, "501 Not Implemented", http.StatusNotImplemented) } } func init() { http.HandleFunc("/", handle) }
package websocket type handler interface { handle() (Message, bool) }
package main import ( "bufio" "context" "encoding/csv" "io" "io/ioutil" "log" "os" "os/exec" "strings" speech "cloud.google.com/go/speech/apiv1" speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1" ) func main() { memories, err := importVocab("vocab.csv") chk(err) words, err := recognizeFile(os.Stdout, os.Args[1]) chk(err) // portaudio.Initialize() // defer portaudio.Terminate() // in := make([]int32, 64) // stream, err := portaudio.OpenDefaultStream(1, 0, 44100, len(in), in) // chk(err) // defer stream.Close() // chk(stream.Start()) // for { // chk(stream.Read()) // chk(binary.Write(f, binary.BigEndian, in)) // nSamples += len(in) // select { // case <-sig: // return // default: // } // } // chk(stream.Stop()) // if err != nil { // log.Fatal(err) // } if words[0] == "device" { device := findDevice(memories, words[1]) cmd := exec.Command("say", device) log.Println(device) if err := cmd.Run(); err != nil { log.Fatal(err) } } } func recognizeFile(w io.Writer, file string) ([]string, error) { ctx := context.Background() client, err := speech.NewClient(ctx) if err != nil { return nil, err } data, err := ioutil.ReadFile(file) if err != nil { return nil, err } // Send the contents of the audio file with the encoding and // and sample rate information to be transcripted. resp, err := client.Recognize(ctx, &speechpb.RecognizeRequest{ Config: &speechpb.RecognitionConfig{ Encoding: speechpb.RecognitionConfig_LINEAR16, SampleRateHertz: 16000, LanguageCode: "en-US", }, Audio: &speechpb.RecognitionAudio{ AudioSource: &speechpb.RecognitionAudio_Content{Content: data}, }, }) var words []string // Print the results. for _, result := range resp.Results { for _, alt := range result.Alternatives { wordSlice := strings.Split(alt.Transcript, " ") for _, word := range wordSlice { words = append(words, word) } } } return words, nil } type memory struct { KhmerWord string EnglishWord string Device string } func importVocab(file string) ([]memory, error) { csvFile, _ := os.Open(file) reader := csv.NewReader(bufio.NewReader(csvFile)) // skip first line (column names) reader.Read() var memories []memory for { line, err := reader.Read() if err == io.EOF { break } else if err != nil { return nil, err } memories = append(memories, memory{ KhmerWord: line[0], EnglishWord: line[1], Device: line[2], }) } return memories, nil } func findDevice(memories []memory, englishWord string) string { for _, memory := range memories { if memory.EnglishWord == englishWord { return memory.Device } } return "No device found for " + englishWord } func chk(err error) { if err != nil { panic(err) } }
package commands import ( "time" "github.com/pkg/errors" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "github.com/michigan-com/brvty-api/brvtyclient" "github.com/michigan-com/brvty-api/mongoqueue" m "github.com/michigan-com/gannett-newsfetch/model" ) type extractor struct { session *mgo.Session client *brvtyclient.Client brvtyTimeout time.Duration } func RunQueuedJobs(session *mgo.Session, client *brvtyclient.Client, queue *mongoqueue.Queue, brvtyTimeout time.Duration) { ex := extractor{session, client, brvtyTimeout} queue.Run(map[string]mongoqueue.Worker{ OpBrvty: mongoqueue.Worker{ Func: mongoqueue.WorkerFunc(ex.extract), }, OpBrvtyPostback: mongoqueue.Worker{ Func: mongoqueue.WorkerFunc(ex.postback), }, }, mongoqueue.RunParams{ PollInterval: 1 * time.Second, Shutdown: nil, }) } func (ex *extractor) extract(op string, args map[string]interface{}) error { aid := args[ParamArticleID].(int) if aid == 0 { return errors.New("Invalid params: missing article ID") } url := args[ParamURL].(string) if url == "" { return errors.New("Invalid params: missing URL") } resources, err := ex.client.Add([]string{url}, ex.brvtyTimeout) if err != nil { return errors.Wrap(err, "brvty.Add failed") } resource := resources[0] articlesC := ex.session.DB("").C("Article") body := resource.OptimalBody() if body == nil { return errors.New("No body yet") } summary := resource.OptimalSummary() if summary == nil { return errors.New("No summary yet") } err = articlesC.Update(bson.M{"article_id": aid}, bson.M{ "$set": bson.M{ "brvty": bson.M{ "headline": body.Headline, "text": body.Text, "summary": summary.Sentences, }, }, }) if err != nil { return errors.Wrap(err, "saving failed") } return nil } func (ex *extractor) postback(op string, args map[string]interface{}) error { aid := args[ParamArticleID].(int) if aid == 0 { return errors.New("Invalid params: missing article ID") } url := args[ParamURL].(string) if url == "" { return errors.New("Invalid params: missing URL") } var article *m.Article articlesC := ex.session.DB("").C("Article") err := articlesC.Find(bson.M{"article_id": aid}).One(&article) if err != nil { return errors.Wrap(err, "failed to load newsfetch article") } if article.Body != "" { err = ex.client.UpdateBody(url, "newsfetch", article.Headline, article.Body) if err != nil { return errors.Wrap(err, "UpdateBody failed") } } if len(article.Summary) > 0 { err = ex.client.UpdateSummary(url, "newsfetch", article.Summary) if err != nil { return errors.Wrap(err, "UpdateSummary failed") } } return nil }
package models import ( "context" "errors" "fmt" "os" "github.com/jackc/pgx/v4" ) var conn *pgx.Conn func init() { var err error pgstr := os.Getenv("PGCONN") if pgstr == "" { panic(errors.New("no pgconn provided, put PGCONN='connect string' in your environment")) } // "postgresql://user:password@localhost:5432/development" conn, err = pgx.Connect(context.Background(), pgstr) if err != nil { panic(err) } if err = conn.Ping(context.Background()); err != nil { panic(err) } fmt.Println("Connected to Database") }
package main import ( "basic-rabbitmq/RabbitMQ" "fmt" "strconv" "time" ) func main() { // work mode publisher rabbitmq := RabbitMQ.NewRabbitMQSimple("goSimple") for i := 0; i <= 100; i++ { rabbitmq.PublishSimple("Learning RabbitMQ with go!" + strconv.Itoa(i)) time.Sleep(1 * time.Second) fmt.Println(i) } }
package bmc import ( "context" "fmt" "log" gf "github.com/stmcginnis/gofish" "github.com/stmcginnis/gofish/redfish" _ "github.com/stmcginnis/gofish/redfish" pb "github.com/stopa323/kimbap/api/bmc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type BMCServer struct { pb.UnimplementedBMCServer } func (s *BMCServer) GetServerPowerStatus( ctx context.Context, bmc *pb.BMCAccess) ( *pb.ServerPowerStatusResponse, error) { log.Printf("get power status: %v", bmc.GetConnectionString()) c, err := gf.ConnectDefault(bmc.GetConnectionString()) if err != nil { return nil, status.Errorf( codes.Internal, fmt.Sprintf("Unable to connect to %v", bmc.GetConnectionString())) } computerSystems, err := c.Service.Systems() if err != nil { return nil, status.Errorf( codes.Internal, "Unable to fetch computer systems") } if 1 != len(computerSystems) { return &pb.ServerPowerStatusResponse{ Status: pb.PowerStatus_UNKNOWN}, nil } return &pb.ServerPowerStatusResponse{ Status: ConvertGofishPowerStateToProto(string( computerSystems[0].PowerState))}, nil } func (s *BMCServer) PowerServerOff( ctx context.Context, bmc *pb.BMCAccess) (*pb.Empty, error) { c, err := gf.ConnectDefault(bmc.GetConnectionString()) if err != nil { return nil, status.Errorf( codes.Internal, fmt.Sprintf("Unable to connect to %v", bmc.GetConnectionString())) } defer c.Logout() // Query the computer systems systems, err := c.Service.Systems() if err != nil { return nil, status.Errorf( codes.Internal, "Unable to fetch computer systems") } // Each computer system that is found is gracefuly shut down for _, system := range systems { err = system.Reset(redfish.ForceOffResetType) if err != nil { return nil, status.Errorf( codes.Internal, fmt.Sprintf("Failed to power off computer: %v", err)) } } // Empty message on success return &pb.Empty{}, nil } func (s *BMCServer) PowerServerOn( ctx context.Context, bmc *pb.BMCAccess) (*pb.Empty, error) { c, err := gf.ConnectDefault(bmc.GetConnectionString()) if err != nil { return nil, status.Errorf( codes.Internal, fmt.Sprintf("Unable to connect to %v", bmc.GetConnectionString())) } defer c.Logout() // Query the computer systems systems, err := c.Service.Systems() if err != nil { return nil, status.Errorf( codes.Internal, "Unable to fetch computer systems") } // Each computer system that is found is gracefuly shut down for _, system := range systems { err = system.Reset(redfish.ForceOnResetType) if err != nil { return nil, status.Errorf( codes.Internal, fmt.Sprintf("Failed to power on computer: %v", err)) } } // Empty message on success return &pb.Empty{}, nil }
package database import ( "errors" "strconv" db "taskweb/database" ) type TbCategory struct { Id int Name string Createtime int64 Remark string } func ExistTbCategory(id int) (bool, error) { rows, err := db.Dtsc.Query("select count(0) Count from tb_category where id=?", id) if err != nil { return false, err } if len(rows) <= 0 { return false, nil } for _, obj := range rows { count, err := strconv.Atoi(string(obj["Count"])) if err != nil { return false, errors.New("parse Count error: " + err.Error()) } return count > 0, nil } return false, nil } func InsertTbCategory(tb_category TbCategory) (int64, error) { result, err := db.Dtsc.Exec("insert into tb_category(name,createtime,remark) values(?,?,?)", tb_category.Name,tb_category.Createtime,tb_category.Remark) if err != nil { return -1, err } return result.LastInsertId() } func UpdateTbCategory(tb_category TbCategory) (bool, error) { result, err := db.Dtsc.Exec("update tb_category set name=?, createtime=?, remark=? where id=?", tb_category.Name, tb_category.Createtime, tb_category.Remark, tb_category.Id) if err != nil { return false, err } affected, err := result.RowsAffected() if err != nil { return false, err } return affected > 0, nil } func GetTbCategory(id int) (tb_category TbCategory, err error) { rows, err := db.Dtsc.Query("select id, name, createtime, remark from tb_category where id=?", id) if err != nil { return tb_category, err } if len(rows) <= 0 { return tb_category, nil } tb_categorys, err := _TbCategoryRowsToArray(rows) if err != nil { return tb_category, err } return tb_categorys[0], nil } func GetTbCategorys() (tb_categorys []TbCategory, err error) { rows, err := db.Dtsc.Query("select id, name, createtime, remark from tb_category ") if err != nil { return tb_categorys, err } if len(rows) <= 0 { return tb_categorys, nil } return _TbCategoryRowsToArray(rows) } func GetTbCategoryRowCount() (count int, err error) { rows, err := db.Dtsc.Query("select count(0) Count from tb_category") if err != nil { return -1, err } if len(rows) <= 0 { return -1, nil } for _, obj := range rows { count, err := strconv.Atoi(string(obj["Count"])) if err != nil { return -1, errors.New("parse Count error: " + err.Error()) } return count, nil } return -1, nil } func _TbCategoryRowsToArray(maps []map[string][]byte) ([]TbCategory, error) { models := make([]TbCategory, len(maps)) var err error for index, obj := range maps { model := TbCategory{} model.Id, err = strconv.Atoi(string(obj["id"])) if err != nil { return nil, errors.New("parse Id error: " + err.Error()) } model.Name = string(obj["name"]) model.Createtime, err = strconv.ParseInt(string(obj["createtime"]), 10, 64) if err != nil { return nil, errors.New("parse Createtime error: " + err.Error()) } model.Remark = string(obj["remark"]) models[index] = model } return models, err } func DelTbCategory(categoryid int) (ra int64, err error) { exist, err := db.Dtsc.Query("select * from tb_job where category_id=? ",categoryid) if len(exist)>0{ return 0,nil } rows, err := db.Dtsc.Exec("delete from tb_category where id=?",categoryid) if err != nil { return 0, err } return rows.RowsAffected() }
package caaa import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00900102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.009.001.02 Document"` Message *AcceptorReconciliationRequestV02 `xml:"AccptrRcncltnReq"` } func (d *Document00900102) AddMessage() *AcceptorReconciliationRequestV02 { d.Message = new(AcceptorReconciliationRequestV02) return d.Message } // The AcceptorReconciliationRequest message is sent by an acceptor (or its agent) to the acquirer (or its agent) , to ensure that the debits and credits performed by the acceptor matches the computed balances of the acquirer for the debits and credits performed during the same reconciliation period. // If the acceptor or the acquirer notices a difference in totals, the discrepancy will be resolved by other means, outside the scope of the protocol. type AcceptorReconciliationRequestV02 struct { // Reconciliation request message management information. Header *iso20022.Header1 `xml:"Hdr"` // Information related to the reconcilliation request. ReconciliationRequest *iso20022.AcceptorReconciliationRequest2 `xml:"RcncltnReq"` // Trailer of the message containing a MAC. SecurityTrailer *iso20022.ContentInformationType6 `xml:"SctyTrlr"` } func (a *AcceptorReconciliationRequestV02) AddHeader() *iso20022.Header1 { a.Header = new(iso20022.Header1) return a.Header } func (a *AcceptorReconciliationRequestV02) AddReconciliationRequest() *iso20022.AcceptorReconciliationRequest2 { a.ReconciliationRequest = new(iso20022.AcceptorReconciliationRequest2) return a.ReconciliationRequest } func (a *AcceptorReconciliationRequestV02) AddSecurityTrailer() *iso20022.ContentInformationType6 { a.SecurityTrailer = new(iso20022.ContentInformationType6) return a.SecurityTrailer }
// Copyright 2019-present Open Networking Foundation. // // 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 config import ( gnmiutils "github.com/onosproject/onos-config/test/utils/gnmi" "github.com/onosproject/onos-config/test/utils/proto" "testing" ) const ( newRootName = "new-root" newRootPath = "/interfaces/interface[name=" + newRootName + "]" newRootConfigNamePath = newRootPath + "/config/name" newRootEnabledPath = newRootPath + "/config/enabled" newRootDescriptionPath = newRootPath + "/config/description" newDescription = "description" ) // TestTreePath tests create/set/delete of a tree of GNMI paths to a single device func (s *TestSuite) TestTreePath(t *testing.T) { // Make a simulated device simulator := gnmiutils.CreateSimulator(t) defer gnmiutils.DeleteSimulator(t, simulator) // Make a GNMI client to use for requests gnmiClient := gnmiutils.GetGNMIClientOrFail(t) getPath := gnmiutils.GetTargetPath(simulator.Name(), newRootEnabledPath) // Set name of new root using gNMI client setNamePath := []proto.TargetPath{ {TargetName: simulator.Name(), Path: newRootConfigNamePath, PathDataValue: newRootName, PathDataType: proto.StringVal}, } gnmiutils.SetGNMIValueOrFail(t, gnmiClient, setNamePath, gnmiutils.NoPaths, gnmiutils.NoExtensions) // Set values using gNMI client setPath := []proto.TargetPath{ {TargetName: simulator.Name(), Path: newRootDescriptionPath, PathDataValue: newDescription, PathDataType: proto.StringVal}, {TargetName: simulator.Name(), Path: newRootEnabledPath, PathDataValue: "false", PathDataType: proto.BoolVal}, } gnmiutils.SetGNMIValueOrFail(t, gnmiClient, setPath, gnmiutils.NoPaths, gnmiutils.SyncExtension(t)) // Check that the name value was set correctly gnmiutils.CheckGNMIValue(t, gnmiClient, setNamePath, newRootName, 0, "Query name after set returned the wrong value") // Check that the enabled value was set correctly gnmiutils.CheckGNMIValue(t, gnmiClient, getPath, "false", 0, "Query enabled after set returned the wrong value") // Remove the root path we added gnmiutils.SetGNMIValueOrFail(t, gnmiClient, gnmiutils.NoPaths, getPath, gnmiutils.SyncExtension(t)) // Make sure child got removed gnmiutils.CheckGNMIValue(t, gnmiClient, setNamePath, newRootName, 0, "New child was not removed") // Make sure new root got removed gnmiutils.CheckGNMIValue(t, gnmiClient, getPath, "", 0, "New root was not removed") }
package routers import ( "github.com/astaxie/beego" "github.com/kingiw/casbin-js-demo/controllers" ) func init() { beego.Router("/", &controllers.MainController{}) beego.Router("/api/get-profiles", &controllers.APIController{}) }
package utils import ( "fmt" "github.com/kelseyhightower/envconfig" "net/url" ) type Env struct { ConsumerKey string ConsumerSecret string Token string TokenSecret string } type DatabaseConfig struct { Username string `envconfig:"DB_USERNAME" required:"true"` Password string `envconfig:"DB_PASSWORD" required:"true"` Host string `envconfig:"DB_HOST" required:"true"` Port string `envconfig:"DB_PORT" required:"true"` Name string `envconfig:"DB_NAME" required:"true"` } func (d *DatabaseConfig) GetDataSourceName() string { return fmt.Sprintf( "%s:%s@tcp(%s:%s)/%s?parseTime=true&charset=utf8mb4&loc=%s", d.Username, d.Password, d.Host, d.Port, d.Name, url.QueryEscape("Asia/Tokyo"), ) } func ReadDBConfig() (*DatabaseConfig, error) { var config DatabaseConfig if err := envconfig.Process("bot", &config); err != nil { return nil, fmt.Errorf("failed to read dsn from env") } return &config, nil }
package count_triplets import ( "fmt" "testing" ) type Result struct { TotalCount int64 FullfilCount int64 PrevCount int64 } func countTriplets(arr []int64, r int64) int64 { length := len(arr) var totalCount int64 if length < 3 { return 0 } singleMap := map[int64]*Result{} for i := 0; i < length; i++ { if i == 0 { res := Result{1, 0, 0} singleMap[arr[i]*r] = &res continue } mulRes := arr[i] * r res, ok := singleMap[mulRes] if !ok { res = &Result{0, 0, 0} } // count all prev fullfil, with the latest Triplets element index = i prev, ok := singleMap[arr[i]] if ok { totalCount += prev.PrevCount res.FullfilCount += prev.PrevCount res.PrevCount += prev.TotalCount } res.TotalCount += 1 singleMap[mulRes] = res } return totalCount } func TestCount(t *testing.T) { c := countTriplets([]int64{1,5,5,25,25,5,25,125}, 5) fmt.Println(c) c2 := countTriplets([]int64{1,100,100,100}, 1) fmt.Println(c2) }
package resolver import ( "fmt" "strings" "github.com/appootb/substratum/discovery" "github.com/appootb/substratum/util/iphelper" "google.golang.org/grpc/resolver" ) type DiscoveryResolver struct { target resolver.Target cc resolver.ClientConn opts resolver.BuildOptions } // ResolveNow will be called by gRPC to try to resolve the target name // again. It's just a hint, resolver can ignore this if it's not necessary. // // It could be called multiple times concurrently. func (r *DiscoveryResolver) ResolveNow(_ resolver.ResolveNowOptions) { ipPrefix := fmt.Sprintf("%v:", iphelper.LocalIP()) nodes := discovery.Implementor().GetNodes(r.target.Endpoint) addrs := make([]resolver.Address, 0, len(nodes)) for addr := range nodes { if strings.HasPrefix(addr, ipPrefix) || strings.HasPrefix(addr, "127.0.0.1:") { addrs = []resolver.Address{ { Addr: addr, }, } break } addrs = append(addrs, resolver.Address{ Addr: addr, }) } r.cc.UpdateState(resolver.State{ Addresses: addrs, }) } // Close closes the resolver. func (r *DiscoveryResolver) Close() { }
package proto import ( "os" ) type File struct { Filename string Content []byte Mode os.FileMode } type FileRequest struct { Filename string } type FileResponse struct { Filename string Checksum [64]byte Overwritten bool }
package prettier import ( "bytes" "fmt" "io/fs" "log" "path/filepath" "strings" "github.com/spf13/afero" "golang.org/x/sys/unix" ) type Chart struct { manifests []Manifest files map[string][]byte } func NewChart() *Chart { c := &Chart{} c.files = make(map[string][]byte) return c } func (c *Chart) LoadChart(appFs afero.Fs, path string) error { addManifests := func(path string, info fs.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() && isManifestFile(info.Name()) { err = c.AddFile(appFs, path) if err != nil { return err } } return nil } err := afero.Walk(appFs, path, addManifests) if err != nil { return err } return nil } func (c *Chart) DeleteFiles(appFs afero.Fs, path string) error { deleteManifests := func(path string, info fs.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() && isManifestFile(info.Name()) { err = appFs.Remove(path) if err != nil { return err } } return nil } err := afero.Walk(appFs, path, deleteManifests) if err != nil { return err } return nil } func isManifestFile(path string) bool { for _, ext := range []string{".yaml", ".yml", ".yaml.tpl", ".yml.tpl"} { if strings.HasSuffix(path, ext) { return true } } return false } func (c *Chart) WriteOut(appFs afero.Fs, path string) error { unique, err := uniqueNames(c.manifests) if err != nil { return err } umask := unix.Umask(0) unix.Umask(umask) for name, manifest := range unique { ext := ".yaml" if strings.Contains(manifest.Yaml, "{{") { ext = ".yaml.tpl" } filename := filepath.Join(path, name+ext) content := manifest.Yaml if !strings.HasSuffix(content, "\n") { content += "\n" } err := afero.WriteFile(appFs, filename, []byte(content), fs.FileMode(0666^umask)) if err != nil { return err } } for filename, content := range c.files { if !bytes.HasSuffix(content, []byte("\n")) { content = append(content, []byte("\n")...) } err := afero.WriteFile(appFs, filename, []byte(content), fs.FileMode(0666^umask)) if err != nil { return err } } return nil } func (c *Chart) AddFile(appFs afero.Fs, path string) error { content, err := afero.ReadFile(appFs, path) if err != nil { return err } err = c.AddManifests(string(content)) if err != nil { log.Printf("add manifests from %s: %v", path, err) c.files[path] = content } return nil } func (c *Chart) AddManifests(yaml string) error { manifests, err := SplitManifests(yaml) if err != nil { return err } c.manifests = append(c.manifests, manifests...) return nil } func uniqueNames(manifests []Manifest) (map[string]Manifest, error) { kindAsName := func(m Manifest) string { return m.Kind } nameInName := func(m Manifest) string { return m.Kind + "-" + m.Metadata.Name } namespaceInName := func(m Manifest) string { return m.Kind + "-" + m.Metadata.Name + "-" + m.Metadata.Namespace } kindNamed, collisions := filterUniqueNames(manifests, kindAsName) nameNamed, collisions := filterUniqueNames(collisions, nameInName) namespaceNamed, collisions := filterUniqueNames(collisions, namespaceInName) if len(collisions) > 0 { return map[string]Manifest{}, fmt.Errorf("not all manifests are unique using kind, name, and namespace as identifier") } all := map[string]Manifest{} for name, manifest := range kindNamed { all[strings.ToLower(name)] = manifest } for name, manifest := range nameNamed { all[strings.ToLower(name)] = manifest } for name, manifest := range namespaceNamed { all[strings.ToLower(name)] = manifest } return all, nil } func filterUniqueNames(manifests []Manifest, name func(Manifest) string) (map[string]Manifest, []Manifest) { uniqueNamed := map[string]Manifest{} named := map[string][]Manifest{} for _, manifest := range manifests { name := name(manifest) named[name] = append(named[name], manifest) } collisions := []Manifest{} for name, manifests := range named { if len(manifests) > 1 { collisions = append(collisions, manifests...) continue } uniqueNamed[name] = manifests[0] } return uniqueNamed, collisions }
package generate import ( "encoding/json" "reflect" "strings" "testing" ) func TestThatCapitalisationOccursCorrectly(t *testing.T) { tests := []struct { input string expected string }{ { input: "ssd", expected: "Ssd", }, { input: "f", expected: "F", }, { input: "fishPaste", expected: "FishPaste", }, { input: "", expected: "", }, { input: "F", expected: "F", }, } for idx, test := range tests { actual := capitaliseFirstLetter(test.input) if actual != test.expected { t.Errorf("Test %d failed: For input \"%s\", expected \"%s\", got \"%s\"", idx, test.input, test.expected, actual) } } } func TestFieldGeneration(t *testing.T) { properties := map[string]*Schema{ "property1": {TypeValue: "string"}, "property2": {Reference: "#/definitions/address"}, // test sub-objects with properties or additionalProperties "property3": {TypeValue: "object", Title: "SubObj1", Properties: map[string]*Schema{"name": {TypeValue: "string"}}}, "property4": {TypeValue: "object", Title: "SubObj2", AdditionalProperties: &AdditionalProperties{TypeValue: "integer"}}, // test sub-objects with properties composed of objects "property5": {TypeValue: "object", Title: "SubObj3", Properties: map[string]*Schema{"SubObj3a": {TypeValue: "object", Properties: map[string]*Schema{"subproperty1": {TypeValue: "integer"}}}}}, // test sub-objects with additionalProperties composed of objects "property6": {TypeValue: "object", Title: "SubObj4", AdditionalProperties: &AdditionalProperties{TypeValue: "object", Title: "SubObj4a", Properties: map[string]*Schema{"subproperty1": {TypeValue: "integer"}}}}, // test sub-objects without titles "property7": {TypeValue: "object"}, // test sub-objects with properties AND additionalProperties "property8": {TypeValue: "object", Title: "SubObj5", Properties: map[string]*Schema{"name": {TypeValue: "string"}}, AdditionalProperties: &AdditionalProperties{TypeValue: "integer"}}, } requiredFields := []string{"property2"} root := Schema{ SchemaType: "http://localhost", Title: "TestFieldGeneration", TypeValue: "object", Properties: properties, Definitions: map[string]*Schema{ "address": {TypeValue: "object"}, }, Required: requiredFields, } root.Init() g := New(&root) err := g.CreateTypes() // Output(os.Stderr, g, "test") if err != nil { t.Error("Failed to get the fields: ", err) } if len(g.Structs) != 8 { t.Errorf("Expected 8 results, but got %d results", len(g.Structs)) } testField(g.Structs["TestFieldGeneration"].Fields["Property1"], "property1", "Property1", "string", false, t) testField(g.Structs["TestFieldGeneration"].Fields["Property2"], "property2", "Property2", "*Address", true, t) testField(g.Structs["TestFieldGeneration"].Fields["Property3"], "property3", "Property3", "*SubObj1", false, t) testField(g.Structs["TestFieldGeneration"].Fields["Property4"], "property4", "Property4", "map[string]int", false, t) testField(g.Structs["TestFieldGeneration"].Fields["Property5"], "property5", "Property5", "*SubObj3", false, t) testField(g.Structs["TestFieldGeneration"].Fields["Property6"], "property6", "Property6", "map[string]*SubObj4a", false, t) testField(g.Structs["TestFieldGeneration"].Fields["Property7"], "property7", "Property7", "*Property7", false, t) testField(g.Structs["TestFieldGeneration"].Fields["Property8"], "property8", "Property8", "*SubObj5", false, t) testField(g.Structs["SubObj1"].Fields["Name"], "name", "Name", "string", false, t) testField(g.Structs["SubObj3"].Fields["SubObj3a"], "SubObj3a", "SubObj3a", "*SubObj3a", false, t) testField(g.Structs["SubObj4a"].Fields["Subproperty1"], "subproperty1", "Subproperty1", "int", false, t) testField(g.Structs["SubObj5"].Fields["Name"], "name", "Name", "string", false, t) testField(g.Structs["SubObj5"].Fields["AdditionalProperties"], "-", "AdditionalProperties", "map[string]int", false, t) if strct, ok := g.Structs["Property7"]; !ok { t.Fatal("Property7 wasn't generated") } else { if len(strct.Fields) != 0 { t.Fatal("Property7 expected 0 fields") } } } func TestFieldGenerationWithArrayReferences(t *testing.T) { properties := map[string]*Schema{ "property1": {TypeValue: "string"}, "property2": { TypeValue: "array", Items: &Schema{ Reference: "#/definitions/address", }, }, "property3": { TypeValue: "array", Items: &Schema{ TypeValue: "object", AdditionalProperties: (*AdditionalProperties)(&Schema{TypeValue: "integer"}), }, }, "property4": { TypeValue: "array", Items: &Schema{ Reference: "#/definitions/outer", }, }, } requiredFields := []string{"property2"} root := Schema{ SchemaType: "http://localhost", Title: "TestFieldGenerationWithArrayReferences", TypeValue: "object", Properties: properties, Definitions: map[string]*Schema{ "address": {TypeValue: "object"}, "outer": {TypeValue: "array", Items: &Schema{Reference: "#/definitions/inner"}}, "inner": {TypeValue: "object"}, }, Required: requiredFields, } root.Init() g := New(&root) err := g.CreateTypes() //Output(os.Stderr, g, "test") if err != nil { t.Error("Failed to get the fields: ", err) } if len(g.Structs) != 3 { t.Errorf("Expected 3 results, but got %d results", len(g.Structs)) } testField(g.Structs["TestFieldGenerationWithArrayReferences"].Fields["Property1"], "property1", "Property1", "string", false, t) testField(g.Structs["TestFieldGenerationWithArrayReferences"].Fields["Property2"], "property2", "Property2", "[]*Address", true, t) testField(g.Structs["TestFieldGenerationWithArrayReferences"].Fields["Property3"], "property3", "Property3", "[]map[string]int", false, t) testField(g.Structs["TestFieldGenerationWithArrayReferences"].Fields["Property4"], "property4", "Property4", "[][]*Inner", false, t) } func testField(actual Field, expectedJSONName string, expectedName string, expectedType string, expectedToBeRequired bool, t *testing.T) { if actual.JSONName != expectedJSONName { t.Errorf("JSONName - expected \"%s\", got \"%s\"", expectedJSONName, actual.JSONName) } if actual.Name != expectedName { t.Errorf("Name - expected \"%s\", got \"%s\"", expectedName, actual.Name) } if actual.Type != expectedType { t.Errorf("Type - expected \"%s\", got \"%s\"", expectedType, actual.Type) } if actual.Required != expectedToBeRequired { t.Errorf("Required - expected \"%v\", got \"%v\"", expectedToBeRequired, actual.Required) } } func TestNestedStructGeneration(t *testing.T) { root := &Schema{} root.Title = "Example" root.Properties = map[string]*Schema{ "property1": { TypeValue: "object", Properties: map[string]*Schema{ "subproperty1": {TypeValue: "string"}, }, }, } root.Init() g := New(root) err := g.CreateTypes() results := g.Structs //Output(os.Stderr, g, "test") if err != nil { t.Error("Failed to create structs: ", err) } if len(results) != 2 { t.Errorf("2 results should have been created, a root type and a type for the object 'property1' but %d structs were made", len(results)) } if _, contains := results["Example"]; !contains { t.Errorf("The Example type should have been made, but only types %s were made.", strings.Join(getStructNamesFromMap(results), ", ")) } if _, contains := results["Property1"]; !contains { t.Errorf("The Property1 type should have been made, but only types %s were made.", strings.Join(getStructNamesFromMap(results), ", ")) } if results["Example"].Fields["Property1"].Type != "*Property1" { t.Errorf("Expected that the nested type property1 is generated as a struct, so the property type should be *Property1, but was %s.", results["Example"].Fields["Property1"].Type) } } func TestEmptyNestedStructGeneration(t *testing.T) { root := &Schema{} root.Title = "Example" root.Properties = map[string]*Schema{ "property1": { TypeValue: "object", Properties: map[string]*Schema{ "nestedproperty1": {TypeValue: "string"}, }, }, } root.Init() g := New(root) err := g.CreateTypes() results := g.Structs // Output(os.Stderr, g, "test") if err != nil { t.Error("Failed to create structs: ", err) } if len(results) != 2 { t.Errorf("2 results should have been created, a root type and a type for the object 'property1' but %d structs were made", len(results)) } if _, contains := results["Example"]; !contains { t.Errorf("The Example type should have been made, but only types %s were made.", strings.Join(getStructNamesFromMap(results), ", ")) } if _, contains := results["Property1"]; !contains { t.Errorf("The Property1 type should have been made, but only types %s were made.", strings.Join(getStructNamesFromMap(results), ", ")) } if results["Example"].Fields["Property1"].Type != "*Property1" { t.Errorf("Expected that the nested type property1 is generated as a struct, so the property type should be *Property1, but was %s.", results["Example"].Fields["Property1"].Type) } } func TestStructNameExtractor(t *testing.T) { m := make(map[string]Struct) m["name1"] = Struct{} m["name2"] = Struct{} names := getStructNamesFromMap(m) if len(names) != 2 { t.Error("Didn't extract all names from the map.") } if !contains(names, "name1") { t.Error("name1 was not extracted") } if !contains(names, "name2") { t.Error("name2 was not extracted") } } func getStructNamesFromMap(m map[string]Struct) []string { sn := make([]string, len(m)) i := 0 for k := range m { sn[i] = k i++ } return sn } func TestStructGeneration(t *testing.T) { root := &Schema{} root.Title = "RootElement" root.Definitions = make(map[string]*Schema) root.Definitions["address"] = &Schema{ Properties: map[string]*Schema{ "address1": {TypeValue: "string"}, "zip": {TypeValue: "number"}, }, } root.Properties = map[string]*Schema{ "property1": {TypeValue: "string"}, "property2": {Reference: "#/definitions/address"}, } root.Init() g := New(root) err := g.CreateTypes() results := g.Structs // Output(os.Stderr, g, "test") if err != nil { t.Error("Failed to create structs: ", err) } if len(results) != 2 { t.Error("2 results should have been created, a root type and an address") } } func TestArrayGeneration(t *testing.T) { root := &Schema{ Title: "Array of Artists Example", TypeValue: "array", Items: &Schema{ Title: "Artist", TypeValue: "object", Properties: map[string]*Schema{ "name": {TypeValue: "string"}, "birthyear": {TypeValue: "number"}, }, }, } root.Init() g := New(root) err := g.CreateTypes() results := g.Structs // Output(os.Stderr, g, "test") if err != nil { t.Fatal("Failed to create structs: ", err) } if len(results) != 1 { t.Errorf("Expected one struct should have been generated, but %d have been generated.", len(results)) } artistStruct, ok := results["Artist"] if !ok { t.Errorf("Expected Name to be Artist, that wasn't found, but the struct contains \"%+v\"", results) } if len(artistStruct.Fields) != 2 { t.Errorf("Expected the fields to be birtyear and name, but %d fields were found.", len(artistStruct.Fields)) } if _, ok := artistStruct.Fields["Name"]; !ok { t.Errorf("Expected to find a Name field, but one was not found.") } if _, ok := artistStruct.Fields["Birthyear"]; !ok { t.Errorf("Expected to find a Birthyear field, but one was not found.") } } func TestNestedArrayGeneration(t *testing.T) { root := &Schema{ Title: "Favourite Bars", TypeValue: "object", Properties: map[string]*Schema{ "barName": {TypeValue: "string"}, "cities": { TypeValue: "array", Items: &Schema{ Title: "City", TypeValue: "object", Properties: map[string]*Schema{ "name": {TypeValue: "string"}, "country": {TypeValue: "string"}, }, }, }, "tags": { TypeValue: "array", Items: &Schema{TypeValue: "string"}, }, }, } root.Init() g := New(root) err := g.CreateTypes() results := g.Structs // Output(os.Stderr, g, "test") if err != nil { t.Error("Failed to create structs: ", err) } if len(results) != 2 { t.Errorf("Expected two structs to be generated - 'Favourite Bars' and 'City', but %d have been generated.", len(results)) } fbStruct, ok := results["FavouriteBars"] if !ok { t.Errorf("FavouriteBars struct was not found. The results were %+v", results) } if _, ok := fbStruct.Fields["BarName"]; !ok { t.Errorf("Expected to find the BarName field, but didn't. The struct is %+v", fbStruct) } f, ok := fbStruct.Fields["Cities"] if !ok { t.Errorf("Expected to find the Cities field on the FavouriteBars, but didn't. The struct is %+v", fbStruct) } if f.Type != "[]*City" { t.Errorf("Expected to find that the Cities array was of type *City, but it was of %s", f.Type) } f, ok = fbStruct.Fields["Tags"] if !ok { t.Errorf("Expected to find the Tags field on the FavouriteBars, but didn't. The struct is %+v", fbStruct) } if f.Type != "[]string" { t.Errorf("Expected to find that the Tags array was of type string, but it was of %s", f.Type) } cityStruct, ok := results["City"] if !ok { t.Error("City struct was not found.") } if _, ok := cityStruct.Fields["Name"]; !ok { t.Errorf("Expected to find the Name field on the City struct, but didn't. The struct is %+v", cityStruct) } if _, ok := cityStruct.Fields["Country"]; !ok { t.Errorf("Expected to find the Country field on the City struct, but didn't. The struct is %+v", cityStruct) } } func TestMultipleSchemaStructGeneration(t *testing.T) { root1 := &Schema{ Title: "Root1Element", ID06: "http://example.com/schema/root1", Properties: map[string]*Schema{ "property1": {Reference: "root2#/definitions/address"}, }, } root2 := &Schema{ Title: "Root2Element", ID06: "http://example.com/schema/root2", Properties: map[string]*Schema{ "property1": {Reference: "#/definitions/address"}, }, Definitions: map[string]*Schema{ "address": { Properties: map[string]*Schema{ "address1": {TypeValue: "string"}, "zip": {TypeValue: "number"}, }, }, }, } root1.Init() root2.Init() g := New(root1, root2) err := g.CreateTypes() results := g.Structs // Output(os.Stderr, g, "test") if err != nil { t.Error("Failed to create structs: ", err) } if len(results) != 3 { t.Errorf("3 results should have been created, 2 root types and an address, but got %v", getStructNamesFromMap(results)) } } func TestThatJavascriptKeyNamesCanBeConvertedToValidGoNames(t *testing.T) { tests := []struct { description string input string expected string }{ { description: "Camel case is converted to pascal case.", input: "camelCase", expected: "CamelCase", }, { description: "Spaces are stripped.", input: "Contains space", expected: "ContainsSpace", }, { description: "Hyphens are stripped.", input: "key-name", expected: "KeyName", }, { description: "Underscores are stripped.", input: "key_name", expected: "KeyName", }, { description: "Periods are stripped.", input: "a.b.c", expected: "ABC", }, { description: "Colons are stripped.", input: "a:b", expected: "AB", }, { description: "GT and LT are stripped.", input: "a<b>", expected: "AB", }, { description: "Not allowed to start with a number.", input: "123ABC", expected: "_123ABC", }, } for _, test := range tests { actual := getGolangName(test.input) if test.expected != actual { t.Errorf("For test '%s', for input '%s' expected '%s' but got '%s'.", test.description, test.input, test.expected, actual) } } } func TestThatArraysWithoutDefinedItemTypesAreGeneratedAsEmptyInterfaces(t *testing.T) { root := &Schema{} root.Title = "Array without defined item" root.Properties = map[string]*Schema{ "name": {TypeValue: "string"}, "repositories": { TypeValue: "array", }, } root.Init() g := New(root) err := g.CreateTypes() results := g.Structs // Output(os.Stderr, g, "test") if err != nil { t.Errorf("Error generating structs: %v", err) } if _, contains := results["ArrayWithoutDefinedItem"]; !contains { t.Errorf("The ArrayWithoutDefinedItem type should have been made, but only types %s were made.", strings.Join(getStructNamesFromMap(results), ", ")) } if o, ok := results["ArrayWithoutDefinedItem"]; ok { if f, ok := o.Fields["Repositories"]; ok { if f.Type != "[]interface{}" { t.Errorf("Since the schema doesn't include a type for the array items, the property type should be []interface{}, but was %s.", f.Type) } } else { t.Errorf("Expected the ArrayWithoutDefinedItem type to have a Repostitories field, but none was found.") } } } func TestThatTypesWithMultipleDefinitionsAreGeneratedAsEmptyInterfaces(t *testing.T) { root := &Schema{} root.Title = "Multiple possible types" root.Properties = map[string]*Schema{ "name": {TypeValue: []interface{}{"string", "integer"}}, } root.Init() g := New(root) err := g.CreateTypes() results := g.Structs // Output(os.Stderr, g, "test") if err != nil { t.Errorf("Error generating structs: %v", err) } if _, contains := results["MultiplePossibleTypes"]; !contains { t.Errorf("The MultiplePossibleTypes type should have been made, but only types %s were made.", strings.Join(getStructNamesFromMap(results), ", ")) } if o, ok := results["MultiplePossibleTypes"]; ok { if f, ok := o.Fields["Name"]; ok { if f.Type != "interface{}" { t.Errorf("Since the schema has multiple types for the item, the property type should be []interface{}, but was %s.", f.Type) } } else { t.Errorf("Expected the MultiplePossibleTypes type to have a Name field, but none was found.") } } } func TestThatUnmarshallingIsPossible(t *testing.T) { // { // "$schema": "http://json-schema.org/draft-04/schema#", // "name": "Example", // "type": "object", // "properties": { // "name": { // "type": ["object", "array", "integer"], // "description": "name" // } // } // } tests := []struct { name string input string expected Root }{ { name: "map", input: `{ "name": { "key": "value" } }`, expected: Root{ Name: map[string]interface{}{ "key": "value", }, }, }, { name: "array", input: `{ "name": [ "a", "b" ] }`, expected: Root{ Name: []interface{}{"a", "b"}, }, }, { name: "integer", input: `{ "name": 1 }`, expected: Root{ Name: 1.0, // can't determine whether it's a float or integer without additional info }, }, } for _, test := range tests { var actual Root err := json.Unmarshal([]byte(test.input), &actual) if err != nil { t.Errorf("%s: error unmarshalling: %v", test.name, err) } expectedType := reflect.TypeOf(test.expected.Name) actualType := reflect.TypeOf(actual.Name) if expectedType != actualType { t.Errorf("expected Name to be of type %v, but got %v", expectedType, actualType) } } } func TestTypeAliases(t *testing.T) { tests := []struct { gotype string input *Schema structs, aliases int }{ { gotype: "string", input: &Schema{TypeValue: "string"}, structs: 0, aliases: 1, }, { gotype: "int", input: &Schema{TypeValue: "integer"}, structs: 0, aliases: 1, }, { gotype: "bool", input: &Schema{TypeValue: "boolean"}, structs: 0, aliases: 1, }, { gotype: "[]*Foo", input: &Schema{TypeValue: "array", Items: &Schema{ TypeValue: "object", Title: "foo", Properties: map[string]*Schema{ "nestedproperty": {TypeValue: "string"}, }, }}, structs: 1, aliases: 1, }, { gotype: "[]interface{}", input: &Schema{TypeValue: "array"}, structs: 0, aliases: 1, }, { gotype: "map[string]string", input: &Schema{ TypeValue: "object", AdditionalProperties: (*AdditionalProperties)(&Schema{TypeValue: "string"}), }, structs: 0, aliases: 1, }, { gotype: "map[string]interface{}", input: &Schema{ TypeValue: "object", AdditionalProperties: (*AdditionalProperties)(&Schema{TypeValue: []interface{}{"string", "integer"}}), }, structs: 0, aliases: 1, }, } for _, test := range tests { test.input.Init() g := New(test.input) err := g.CreateTypes() structs := g.Structs aliases := g.Aliases // Output(os.Stderr, g, "test") if err != nil { t.Fatal(err) } if len(structs) != test.structs { t.Errorf("Expected %d structs, got %d", test.structs, len(structs)) } if len(aliases) != test.aliases { t.Errorf("Expected %d type aliases, got %d", test.aliases, len(aliases)) } if test.gotype != aliases["Root"].Type { t.Errorf("Expected Root type %q, got %q", test.gotype, aliases["Root"].Type) } } } // Root is an example of a generated type. type Root struct { Name interface{} `json:"name,omitempty"` }
package main import ( "fmt" "gober/gbinterface" "gober/gbnet" ) type pingRouter struct { } func (this *pingRouter) PreHandle(request gbinterface.IRequest) { return } func (this *pingRouter) PostHandle(request gbinterface.IRequest) { return } func (this *pingRouter) Handler(request gbinterface.IRequest){ fmt.Println("call handler action \n") request.GetMessageID() fmt.Printf("get id from client msgid :%d msglen:%d msgcontent : %s \n",request.GetMessageID(),request.GetMessageLen(),request.GetData()) content :=[]byte{'c','a','o','b','o','y'} err := request.GetConnection().SendMsg(12,content) if err != nil{ fmt.Println("send msg err!") } } func main(){ s := gbnet.NewServer("caomao") s.AddRouter(&pingRouter{}) s.Server() }
package main import ( "fmt" "euler" ) func main() { f := make([]int,1000002) for x := 1 ; x < 10; x++ { f[x] = x // fmt.Print(x) } p := 10 for x := 10; p < 1000001; x++ { di := euler.GetDigits(x) for y := 0; y < len(di); y++ { if p < 1000001 { f[p] = di[y] } p++ } } tot := 1 fmt.Println() for x := 1; x < 1000001; x = x * 10 { tot = tot * f[x] fmt.Println(f[x]) } fmt.Println(tot) }
// Package soapboxd provides server-side implementation of the // services defined in the proto package for Soapbox application, // deployment, environment, etc. related services. package soapboxd
// +build darwin dragonfly freebsd linux,!appengine netbsd openbsd package jqrepl import "os" // ReopenTTY will open a new filehandle to the controlling terminal. // // Used when stdin has been redirected so that we can still get an interactive // prompt to the user. func ReopenTTY() (*os.File, error) { return os.Open("/dev/tty") }
// Each of these tests just come out of either intuition or from my notes // in cryptography class... don't judge me package modmath_test import ( "testing" "github.com/deanveloper/nikola" . "github.com/deanveloper/modmath" ) func TestLpr(t *testing.T) { nikola.SuggestEqual(t, 0, Lpr(0, 5)) nikola.SuggestEqual(t, 1, Lpr(1, 10)) nikola.SuggestEqual(t, 2, Lpr(202, 10)) nikola.SuggestEqual(t, 3, Lpr(47291873, 4729187)) } func TestSolve(t *testing.T) { var r int var e error r, e = Solve(3, 5, 10) nikola.SuggestEqual(t, 5, r) nikola.SuggestEqual(t, nil, e) r, e = Solve(20, 5, 25) nikola.SuggestEqual(t, 4, r) nikola.SuggestEqual(t, nil, e) r, e = Solve(20, 5, 30) nikola.SuggestEqual(t, 0, r) nikola.SuggestEqual(t, NoSolution, e) } func TestSolveExp(t *testing.T) { nikola.SuggestEqual(t, 4, SolveExp(7, 365, 9)) nikola.SuggestEqual(t, 5, SolveExp(5, 291, 11)) } func TestSolveCrt(t *testing.T) { nikola.SuggestEqual(t, 7, SolveCrt(2, 5, 1, 3)) nikola.SuggestEqual(t, 5871, SolveCrt(12, 93, 29, 127)) nikola.SuggestEqual(t, 1316, SolveCrt(5, 23, 70, 89)) } func TestSolveCrtMany(t *testing.T) { // I only have one example in my notes of this section nikola.SuggestEqual(t, 49, SolveCrtMany([]CrtEntry{{1, 3}, {4, 5}, {0, 7}})) }
package main import ( "fmt" "testing" ) func TestCombine(t *testing.T) { ans := Combine(4, 2) // 预期 [[1 2] [1 3] [1 4] [2 3] [2 4] [3 4]] >>> [[1 2] [1 3] [1 4] [1 3] [1 4] [1 4] [2 3] [2 4] [2 4] [3 4]] fmt.Println("?????????????") fmt.Println(ans) fmt.Println("?????????????") ans1 := Combine(1, 1) // 预期 [[1]] fmt.Println("?????????????") fmt.Println(ans1) fmt.Println("?????????????") ans2 := Combine(2, 1) // 预期 [[1] [2]] fmt.Println("?????????????") fmt.Println(ans2) fmt.Println("?????????????") ans3 := Combine(4, 3) // 预期 [[1,2,3],[1,2,4],[1,3,4],[2,3,4]] fmt.Println("?????????????") fmt.Println(ans3) fmt.Println("?????????????") }
package main import ( "fmt" ) func main() { var num = []int{5,6,89,76,54,3,2,12,34,56,7,8,9,90} var soma int = 0 for x, n := range num { if(n % 2 != 0){ num[x] *= 2 } if(n % 2 == 0){ num[x] /= 2 } soma += num[x] } fmt.Printf("%v\n%d", num, soma) }
package cmd import ( "flag" "fmt" "sort" "strconv" "string" "os" "github.com/openebs/mayaserver/lib/config" //using maya configuration can print the bind addr and nodes name "github.com/mitchellh/cli" //cli imports all required cli-ui commands ) type Ports struct { HTTP int `mapstructure:"http"` } //this structure helps in managing the ports //also supports default ports to server type StatusCommand struct { Meta Ui cli.Ui args []string BindAddr string Region string DataDir string Datacenter string LogLevel string } // status structure which includes the cofig nodes func usage() { fmt.Fprintf(os.Stderr, "usage: test-local-port [5656]\n") flag.PrintDefaults() os.Exit(2) } //this function returns the actual port usage func (f *ports) readMayaConfig() *config.MayaConfig { var configPath []string cmdConfig := &config.MayaConfig{ Ports: &config.Ports{}, flag.Usage == usage flag.Parse(), args := flag.Args() } //check with the port details to know if the port is used or not func (f *ports) check() *Statuscommand { if len(args) < 1 { fmt.Fprintf(os.Stderr, "Input port is missing.") os.Exit(1) }//checks the input port if port := args[0] _, err := strconv.ParseUint(port, 10, 16) //this coverts the string to uint and compares with the actual expected port if err != nil { fmt.Fprintf(os.Stderr, "Invalid port %q: %s\n", port, err) os.Exit(1) } } } //using merge function in configuration to merge actual port and the expected port func (mc *MayaConfig) Merge(b *MayaConfig) *MayaConfig { if result.Ports == nil && b.Ports != nil { ports := *b.Ports result.Ports = &ports } else if b.Ports != nil { result.Ports = result.Ports.Merge(b.Ports) } //merge function func (a *Ports) Merge(b *Ports) *Ports { result := *a if b.HTTP != 0 { result.HTTP = b.HTTP } return &result } //prints the cofiguration of status func (c *StatusCommand) readMayaConfig() *config.MayaConfig { { flags := flag.NewFlagSet("up", flag.ContinueOnError) flags.Usage = func() { c.Ui.Error(c.Help()) } flags.Var((*flaghelper.StringFlag)(&configPath), "config", "config") flags.StringVar(&cmdConfig.BindAddr, "bind", "", "") flags.StringVar(&cmdConfig.NodeName, "name", "m-apiserver", "") flags.StringVar(&cmdConfig.DataDir, "data-dir", "", "") flags.StringVar(&cmdConfig.LogLevel, "log-level", "", "") } //the main status command //here when the vagrant machine is running //then the status runs func (c *StatusCommand) Run(args []string) int { //check for vagrant up //because when vagrant up is not done then the m-apiserver could not be responded if config.vmbox_status == 'running' { //assiging the up variable the value of up command to check up := {func() (cli.Command, error) { return &cmd.UpCommand{ Revision: GitCommit, Version: Version, VersionPrerelease: VersionPrerelease, Ui: meta.Ui, ShutdownCh: make(chan struct{}), }, nil } //CMD UP is mot nil then the status command can be executed //up variable either stores the nil | up terms //when it is not nil the status command can be executed if up != nil { mconfig := c.readMayaConfig() expec_port= check () *Statuscommand //the merged ports can be verfied when merged the ports may be sam as expected port and the port running //by this check the code can be runned //when it is not running on the actual/expected port he status command cannot be executed if expec_port=='5656' { c.Ui.Output(out) out := fmt.Sprintf("Name IP Ports Status \n%-16s%-16s%d\t%-16s", mconfig.NodeName, mconfig.BindAddr, mconfig.Ports, Status) } else fmt.Fprintf("you are running on different port : check with your configuration") } }
package main import ( "fmt" "github.com/lijian777/BitCoin/block" ) //启动 func main() { //var bc=bc.NewBlock(1, []byte("aaa"), []byte("vvvv")) //fmt.Printf("frist bolck: %v\n",bc) //初始化区块链bc bc := block.CreateBlockChainWithGenesisBlock() //上链 bc.AddBlock(bc.Blocks[len(bc.Blocks)-1].Height+1, bc.Blocks[len(bc.Blocks)-1].Hash, []byte("lily send 10 btc to bob")) bc.AddBlock(bc.Blocks[len(bc.Blocks)-1].Height+1, bc.Blocks[len(bc.Blocks)-1].Hash, []byte("mike send 10 btc to bob")) for _, b := range bc.Blocks { fmt.Printf("prev hash: %x,current hash:%x \n", b.PrevBlockHash, b.Hash) } }
// Package search provides a way to index entities and run relatively // complicated search queries, best served outside of data stores, and // by specialized search engines like ElasticSearch or Solr etc. // // This tackles the limitations caused by gocrud in terms of filtering // and sort operations which would otherwise would need to be done at // application level. package search import "github.com/manishrjain/gocrud/x" var log = x.Log("search") // All the search operations are run via this Search interface. // Implement this interface to add support for a search engine. // Note that the term Entity is being used interchangeably with // the term Subject. An Entity has a kind, and has an id. // Query interface provides the search api encapsulator, responsible for // generating the right query for the engine, and then running it. type Query interface { // NewAndFilter would return a filter which would run AND operation // among individual filter queries. NewAndFilter() FilterQuery // NewOrFilter would return a filter which would run OR operation // among individual filter queries. NewOrFilter() FilterQuery // From would set the offset from the first result. Use it along // with Limit(int) to do pagination. From(num int) Query // Limit would limit the number of results to num. Limit(num int) Query // Order would sort the results by field in ascending order. // A "-field" can be provided to sort results in descending order. Order(field string) Query // Run the generated query, providing resulting documents and error, if any. Run() ([]x.Doc, error) // Count the number of results that would be generated. Don't run the query. Count() (int64, error) } type FilterQuery interface { // AddExact would do exact full string, int, etc. filtering. Also called // term filtering by some engines. AddExact(field string, value interface{}) FilterQuery // AddRegex would do regular expression filtering. // Naturally, requires value to be string. AddRegex(field string, value string) FilterQuery } // Engine provides the interface to be implemented to support search engines. type Engine interface { // Init should be used for initializing search engine. The string arguments // can be used differently by different engines. Init(args ...string) // Update doc into index. Note that doc.NanoTs should be utilized to implement // any sort of versioning facility provided by the search engine, to avoid // overwriting a newer doc by an older doc. Update(x.Doc) error // NewQuery creates the query encapsulator, restricting results by given kind. NewQuery(kind string) Query } // Search docs where: // Where("field =", "something") or // Where("field >", "something") or // Where("field <", "something") var dengine Engine func Register(name string, driver Engine) { if driver == nil { log.WithField("search", name).Fatal("nil engine") return } if dengine != nil { log.WithField("search", name).Fatal("Register called twice") return } log.WithField("search", name).Debug("Registering search engine") dengine = driver } func Get() Engine { if dengine == nil { log.Fatal("No engine registered") return nil } return dengine }
package resources import ( "gopkg.in/mgo.v2" ) func NewMongoResource(config *MongoConfig) (ResourceInterface, error) { return &MongoResource{config: config}, nil } type MongoResource struct { config *MongoConfig session *mgo.Session } type MongoConfig struct { URI string } func (this *MongoResource) Get() (interface{}, error) { // creating mongo session var err error this.session, err = mgo.Dial(this.config.URI) if err != nil { return nil, err } this.session.SetMode(mgo.Monotonic, true) return this.session.DB("e_corp_api"), nil } func (this *MongoResource) Close() bool { if this.session != nil { this.session.Close() return true } return false }
package controllers import ( "app-auth/types" "app-auth/utils" "fmt" "net/http" "github.com/dgrijalva/jwt-go" "github.com/labstack/echo/v4" ) func GetTeamMembers(ctx echo.Context) error { user := ctx.Get("user").(*jwt.Token) claims := user.Claims.(jwt.MapClaims) admin := claims["id"].(string) app := claims["app"].(string) id := ctx.Param("id") teamParam := ctx.Param("team") organisationUtil := utils.OrganisationUtil{Id: id, Name: "", UserId: admin, App: app,} organisationUtil.GetOrganisation() teamUtil := utils.TeamUtil{TeamId: teamParam, TeamName: "", UserId: admin, App: app, Organisation: organisationUtil} members := teamUtil.GetMembers(); if members == nil { return ctx.JSON(http.StatusNotFound, types.TeamNotFound { Message: fmt.Sprintf("No Members Found"), Status: 404, Error: true, Type: "GetTeamMembers", }) } return ctx.JSON(http.StatusOK, members) } func GetTeamMember(ctx echo.Context) error { user := ctx.Get("user").(*jwt.Token) claims := user.Claims.(jwt.MapClaims) admin := claims["id"].(string) app := claims["app"].(string) id := ctx.Param("id") teamParam := ctx.Param("team") userParam := ctx.Param("userId") organisationUtil := utils.OrganisationUtil{Id: id, Name: "", UserId: admin, App: app,} organisationUtil.GetOrganisation() teamUtil := utils.TeamUtil{TeamId: teamParam, TeamName: "", UserId: admin, App: app, Organisation: organisationUtil} member := teamUtil.GetMember(userParam); if member == nil { return ctx.JSON(http.StatusNotFound, types.TeamNotFound { Message: fmt.Sprintf("Member %s Not Found", userParam), Status: 404, Error: true, Type: "GetTeamMember", }) } return ctx.JSON(http.StatusOK, member) } func AddTeamMember(ctx echo.Context) error { user := ctx.Get("user").(*jwt.Token) claims := user.Claims.(jwt.MapClaims) admin := claims["id"].(string) app := claims["app"].(string) id := ctx.Param("id") teamParam := ctx.Param("team") memberPostDetails := new(types.TeamMemberInvitePOSTPayload) err := ctx.Bind(memberPostDetails); if err != nil { fmt.Println(err) return err } organisationUtil := utils.OrganisationUtil{Id: id, Name: "", UserId: admin, App: app,} organisationUtil.GetOrganisation() teamUtil := utils.TeamUtil{TeamId: teamParam, TeamName: "", UserId: admin, App: app, Organisation: organisationUtil} member := teamUtil.AddMember(memberPostDetails.Email, memberPostDetails.SignupUrl, memberPostDetails.AppRedirectUrl, app); if member == nil { return ctx.JSON(http.StatusInternalServerError, types.TeamOperation { Message: fmt.Sprintf("Team Member %s Not Created", memberPostDetails.Email), Status: 500, Error: true, Type: "PostTeamMember", State: "Unsuccessful", }) } return ctx.JSON(http.StatusCreated, member) } func RemoveTeamMember(ctx echo.Context) error { user := ctx.Get("user").(*jwt.Token) claims := user.Claims.(jwt.MapClaims) admin := claims["id"].(string) app := claims["app"].(string) id := ctx.Param("id") teamParam := ctx.Param("team") userParam := ctx.Param("userId") organisationUtil := utils.OrganisationUtil{Id: id, Name: "", UserId: admin, App: app,} organisationUtil.GetOrganisation() teamUtil := utils.TeamUtil{TeamId: teamParam, TeamName: "", UserId: admin, App: app, Organisation: organisationUtil} member := teamUtil.RemoveMember(userParam); if member == &utils.AndFalse { return ctx.JSON(http.StatusInternalServerError, types.TeamOperation { Message: fmt.Sprintf("Team Member Not Removed"), Status: 500, Error: true, Type: "RemoveTeamMember", State: "Unsuccessful", }) } return ctx.JSON(http.StatusOK, types.TeamOperation { Message: fmt.Sprintf("Team Member Not Removed"), Status: 200, Error: true, Type: "RemoveTeamMember", State: "Success", }) }