text stringlengths 11 4.05M |
|---|
package serve
import (
"io/ioutil"
"github.com/microcosm-cc/bluemonday"
"github.com/russross/blackfriday"
)
func generateHtml(path string) (html []byte, err error) {
fileBytes, err := ioutil.ReadFile(path)
if err != nil {
return
}
unsafe := blackfriday.MarkdownCommon(fileBytes)
html = bluemonday.UGCPolicy().SanitizeBytes(unsafe)
return
}
|
// Copyright (c) OpenFaaS Author(s) 2018. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// API source - https://haveibeenpwned.com/API/v2#SearchingPwnedPasswordsByRange
// Idea from Matthew Holt (@mholt6)
package function
import (
"crypto/sha1"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
)
// Handle a serverless request
func Handle(payload []byte) string {
if len(payload) == 0 {
return "Enter a number of characters."
}
hashed := fmt.Sprintf("%X", sha1.Sum(payload))
prefix := hashed[:5]
c := http.Client{}
req, _ := http.NewRequest(http.MethodGet,
fmt.Sprintf("https://api.pwnedpasswords.com/range/%s", prefix), nil)
res, err := c.Do(req)
if err != nil {
return err.Error()
}
var bytesOut []byte
if res.Body != nil {
defer res.Body.Close()
bytesOut, _ = ioutil.ReadAll(res.Body)
}
passwords := string(bytesOut)
foundTimes, findErr := findPassword(passwords, prefix, hashed)
if findErr != nil {
return findErr.Error()
}
result := result{Found: foundTimes}
output, _ := json.Marshal(result)
return string(output)
}
type result struct {
Found int `json:"found"`
}
func findPassword(passwords string, prefix string, hashed string) (int, error) {
foundTimes := 0
for _, passwordLine := range strings.Split(passwords, "\r\n") {
if passwordLine != "" {
parts := strings.Split(passwordLine, ":")
if fmt.Sprintf("%s%s", prefix, parts[0]) == hashed {
var convErr error
foundTimes, convErr = strconv.Atoi(parts[1])
if convErr != nil {
return 0, fmt.Errorf(`Cannot convert value: "%s", error: "%s"\n`, parts[1], convErr)
}
break
}
}
}
return foundTimes, nil
}
|
package plan
type Merge struct {
nodeBase
}
func (self *Merge) Children() []Node {
return self.nodeBase.Children
}
func (self *Merge) Accept(v Visitor, f *bool) {
v.OnMerge(self, f)
visitChildrenIfNeed(self, v, f)
}
type Project struct {
nodeBase
Columns []Node
}
func (self *Project) Children() []Node {
return self.nodeBase.Children
}
func (self *Project) Accept(v Visitor, f *bool) {
v.OnProject(self, f)
visitChildrenIfNeed(self, v, f)
}
type Select struct {
nodeBase
}
func (self *Select) Children() []Node {
return self.nodeBase.Children
}
func (self *Select) Accept(v Visitor, f *bool) {
v.OnSelect(self, f)
visitChildrenIfNeed(self, v, f)
}
type Relation struct {
nodeBase `yaml:"Relation"`
// ... metadata
HostName string `yaml:"hostName"`
DBName string `yaml:"dbName"`
SchemaName string `yaml:"schemaName"`
}
func (self *Relation) Children() []Node {
return self.nodeBase.Children
}
func (self *Relation) Accept(v Visitor, f *bool) {
v.OnRelation(self, f)
visitChildrenIfNeed(self, v, f)
}
type Alias struct {
nodeBase `yaml:"Alias"`
Name string
}
func (self *Alias) Children() []Node {
return self.nodeBase.Children
}
func (self *Alias) Accept(v Visitor, f *bool) {
v.OnAlias(self, f)
visitChildrenIfNeed(self, v, f)
}
type nodeBase struct {
Limit *Limit
Filter *Filter
Children []Node
}
type Node interface {
Children() []Node
Accept(v Visitor, f *bool)
}
type Limit struct {
Offset int64
Limit int64
}
type Filter struct {
}
type Visitor interface {
OnMerge(node *Merge, f *bool)
OnProject(node *Project, f *bool)
OnSelect(node *Select, f *bool)
OnRelation(node *Relation, f *bool)
OnAlias(node *Alias, f *bool)
}
func visitChildrenIfNeed(node Node, visitor Visitor, f *bool) {
if *f && node.Children() != nil {
for _, child := range node.Children() {
child.Accept(visitor, f)
if !*f {
return
}
}
}
}
|
package emoji
import (
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"github.com/sairoutine/RenmeriMaker/server/constant"
"github.com/sairoutine/RenmeriMaker/server/model"
"github.com/sairoutine/RenmeriMaker/server/util"
"net/http"
)
func Add(c *gin.Context) {
db := c.MustGet("DB").(*gorm.DB)
novelId := c.Param("id")
emojiType := c.Param("type")
novel := model.Novel{}
recordNotFound := db.Where(&model.Novel{ID: util.String2Uint64(novelId)}).First(&novel).RecordNotFound()
// 存在しないノベルならエラー
if recordNotFound {
util.RenderNotFound(c)
return
}
// 存在しない絵文字ならエラー
if _, ok := constant.EmojiMap[emojiType]; !ok {
util.RenderNotFound(c)
return
}
// +1
db.Exec(`
INSERT INTO emojis
(novel_id,type,count) VALUES (?,?,1)
ON DUPLICATE KEY UPDATE
count=count+1
`, novelId, emojiType)
util.RenderJSON(c, http.StatusOK, gin.H{})
}
|
package game
import (
"errors"
"github.com/golang/glog"
"github.com/noxue/utils/argsUtil"
"github.com/noxue/utils/fsm"
"qipai/dao"
"qipai/game/card"
"qipai/model"
"qipai/utils"
"time"
)
func StateSetScore(action fsm.ActionType, args ...interface{}) (nextState fsm.StateType) {
if action != SetScoreAction {
return
}
var roomId uint
var uid uint
var score int
var auto bool
res := utils.Msg("")
alreadySet := false // 是否已经下注
defer func() {
if alreadySet { // 已经下注就直接退出,不用再次通知
return
}
if res == nil {
res = utils.Msg("").AddData("game", &model.Game{
PlayerId: uid,
Score: score,
RoomId: roomId,
Auto: auto,
})
SendToAllPlayers(res, BroadcastScore, roomId)
return
}
p := GetPlayer(uid)
if p == nil {
glog.V(1).Infoln("玩家:", uid, "不在线,发送下注信息失败")
return
}
res.Send(BroadcastScore, p.Session)
}()
e := argsUtil.NewArgsUtil(args...).To(&roomId, &uid, &score, &auto)
if e != nil {
res = utils.Msg(e.Error()).Code(-1)
glog.Errorln(e)
return
}
room, e := dao.Room.Get(roomId)
if e != nil {
res = utils.Msg(e.Error()).Code(-1)
glog.Errorln(e)
return
}
ret := dao.Db().Model(&model.Game{}).Where("room_id=? and player_id=? and current=? and banker=0 and score=0", roomId, uid, room.Current).Update(map[string]interface{}{"score": score, "auto": auto})
if ret.Error != nil {
res = utils.Msg(ret.Error.Error()).Code(-1)
return
}
if ret.RowsAffected == 0 {
alreadySet = true
}
games, err := dao.Game.GetGames(roomId, room.Current)
if err != nil {
res = utils.Msg(err.Error()).Code(-1)
return
}
all := true // 是否全部都抢庄了
for _, v := range games {
if v.Banker {
continue
}
// 如果还有没下注的,直接返回,通知所有人该用户的抢庄倍数
if v.Score == 0 {
all = false
break
}
}
if all {
nextState = ShowCardState
// 计算牌型
e:=calcCard(roomId)
if e!=nil{
res = utils.Msg(e.Error()).Code(-1)
return
}
g1, e := Games.Get(roomId)
if e!=nil{
res = utils.Msg(e.Error()).Code(-1)
return
}
go func() {
time.Sleep(time.Millisecond*500) // 等待0.5秒后通知看牌
g1.ShowCard()
}()
}
glog.V(3).Infoln(roomId, "房间:", uid, " 下注,", score, "分。是否自动下注:", auto)
res = nil
return
}
func calcCard(roomId uint)(err error){
games, e := dao.Game.GetCurrentGames(roomId)
if e != nil {
err = e
return
}
if len(games) == 0 {
err = errors.New("当前房间没有玩家")
return
}
for _, g := range games {
paixing, cardStr, e := card.GetPaixing(g.Cards)
if e != nil {
err = e
return
}
if dao.Db().Model(&g).Update(map[string]interface{}{"card_type": paixing, "cards": cardStr}).Error != nil {
err = errors.New("更新牌型失败")
return
}
}
return
} |
package epaper
import (
"fmt"
"image"
"time"
"periph.io/x/periph/conn/gpio"
"periph.io/x/periph/conn/gpio/gpioreg"
"periph.io/x/periph/conn/physic"
"periph.io/x/periph/conn/spi"
"periph.io/x/periph/conn/spi/spireg"
"periph.io/x/periph/host"
)
// Epd is basic struc for Waveshare eps2in13bc
type Epd struct {
Width int
Height int
port spi.PortCloser
spiConn spi.Conn
rstPin gpio.PinIO
dcPin gpio.PinIO
csPin gpio.PinIO
busyPin gpio.PinIO
}
// CreateEpd is constructor for Epd
func CreateEpd() Epd {
e := Epd{
Width: 122,
Height: 250,
}
var err error
host.Init()
// SPI
e.port, err = spireg.Open("")
if err != nil {
fmt.Println(err)
}
e.spiConn, err = e.port.Connect(3000000*physic.Hertz, 0b00, 8)
if err != nil {
fmt.Println(err)
}
fmt.Println(e.spiConn)
// GPIO - read
e.rstPin = gpioreg.ByName("GPIO17") // out
e.dcPin = gpioreg.ByName("GPIO25") // out
e.csPin = gpioreg.ByName("GPIO8") // out
e.busyPin = gpioreg.ByName("GPIO24") // in
return e
}
// Close is closing pariph.io port
func (e *Epd) Close() {
e.port.Close()
}
// reset epd
func (e *Epd) reset() {
e.rstPin.Out(true)
time.Sleep(200 * time.Millisecond)
e.rstPin.Out(false)
time.Sleep(5 * time.Millisecond)
e.rstPin.Out(true)
time.Sleep(200 * time.Millisecond)
}
// sendCommand sets DC ping low and sends byte over SPI
func (e *Epd) sendCommand(command byte) {
e.dcPin.Out(false)
e.csPin.Out(false)
c := []byte{command}
r := make([]byte, len(c))
e.spiConn.Tx(c, r)
e.csPin.Out(true)
e.readBusy()
}
// sendData sets DC ping high and sends byte over SPI
func (e *Epd) sendData(data byte) {
e.dcPin.Out(true)
e.csPin.Out(false)
c := []byte{data}
r := make([]byte, len(c))
e.spiConn.Tx(c, r)
e.csPin.Out(true)
e.readBusy()
}
// ReadBusy waits for epd
func (e *Epd) readBusy() {
//
// 0: idle
// 1: busy
for e.busyPin.Read() == gpio.High {
time.Sleep(100 * time.Millisecond)
}
}
// Sleep powers off the epd
func (e *Epd) Sleep() {
e.executeCommandAndLog(0x10, "DEEP_SLEEP", []byte{0x03})
time.Sleep(100 * time.Millisecond)
}
// Display sends an image to epd
func (e *Epd) Display(image []byte) {
lineWidth := e.Width / 8
if e.Width%8 != 0 {
lineWidth++
}
e.sendCommand(0x24)
for j := 0; j < e.Height; j++ {
for i := 0; i < lineWidth; i++ {
e.sendData(image[i+j*lineWidth])
}
}
e.TurnDisplayOn()
}
// TurnDisplayOn turn the epd on
func (e *Epd) TurnDisplayOn() {
e.sendCommand(0x22)
e.sendData(0xC7)
e.sendCommand(0x20)
e.readBusy()
}
var lutFullUpdate = []byte{
0x80, 0x60, 0x40, 0x00, 0x00, 0x00, 0x00,
0x10, 0x60, 0x20, 0x00, 0x00, 0x00, 0x00,
0x80, 0x60, 0x40, 0x00, 0x00, 0x00, 0x00,
0x10, 0x60, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x03, 0x03, 0x00, 0x00, 0x02,
0x09, 0x09, 0x00, 0x00, 0x02,
0x03, 0x03, 0x00, 0x00, 0x02,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x15, 0x41, 0xA8, 0x32, 0x30, 0x0A,
}
// Init starts the epd
func (e *Epd) Init() {
e.reset()
e.readBusy()
e.executeCommandAndLog(0x12, "SOFT_RESET", nil)
e.readBusy()
e.executeCommandAndLog(0x74, "SET_ANALOG_BLOCK_CONTROL", []byte{0x54})
e.executeCommandAndLog(0x7E, "SET_DIGITAL_BLOCK_CONTROL", []byte{0x3B})
e.executeCommandAndLog(0x01, "DRIVER_OUTPUT_CONTROL", []byte{0xF9, 0x0, 0x0})
e.executeCommandAndLog(0x11, "DATA_ENTRY_MODE", []byte{0x01})
e.executeCommandAndLog(0x44, "SET_X-RAM_START_END_POSITION - Second data byte 0x0C-->(15+1)*8=128", []byte{0x0, 0x0F})
e.executeCommandAndLog(0x45, "SET_X-RAM_START_END_POSITION - First data byte 0xF9-->(249+1)=250", []byte{0xF9, 0x0, 0x0, 0x0})
e.executeCommandAndLog(0x3C, "BorderWavefrom", []byte{0x03})
e.executeCommandAndLog(0x2C, "VCOM_VOLTAGE", []byte{0x55})
e.executeCommandAndLog(0x03, "lut_full_update[70]", []byte{lutFullUpdate[70]})
e.executeCommandAndLog(0x04, "lut_full_update[71-72-73]", []byte{lutFullUpdate[71], lutFullUpdate[72], lutFullUpdate[73]})
e.executeCommandAndLog(0x3A, "DUMMY_LINE", []byte{lutFullUpdate[74]})
e.executeCommandAndLog(0x3B, "GATE_TIME", []byte{lutFullUpdate[75]})
e.executeCommandAndLog(0x32, "lut_full_update[0:70]", nil)
for i := 0; i < 70; i++ {
e.sendData(lutFullUpdate[i])
}
e.executeCommandAndLog(0x4E, "SET_X-RAM_ADDRESS_COUNT_TO_ZERO", []byte{0x0})
e.executeCommandAndLog(0x4F, "SET_Y-RAM_ADDRESS_COUNT_TO_0x127", []byte{0xF9, 0x0})
e.readBusy()
fmt.Println("INIT DONE")
time.Sleep(100 * time.Millisecond)
}
func (e *Epd) executeCommandAndLog(command byte, log string, data []byte) {
fmt.Println(log)
e.sendCommand(command)
for i := 0; i < len(data); i++ {
e.sendData(data[i])
}
}
// Clear sets epd display to white (0xFF)
func (e *Epd) Clear() {
lineWidth := e.Width / 8
if e.Width%8 != 0 {
lineWidth++
}
e.sendCommand(0x24)
for i := 0; i < e.Height; i++ {
for j := 0; j < lineWidth; j++ {
e.sendData(0xFF)
}
}
e.TurnDisplayOff()
}
// TurnDisplayOff turn the display off
func (e *Epd) TurnDisplayOff() {
e.sendCommand(0x22)
e.sendData(0xC7)
e.sendCommand(0x20)
}
// GetBuffer return the buffer from a RGBA image, this buffer
// should be pass to Display method.
func (e *Epd) GetBuffer(image *image.RGBA) []byte {
lineWidth := e.Width / 8
if e.Width%8 != 0 {
lineWidth++
}
size := (lineWidth * e.Height)
data := make([]byte, size)
for i := 0; i < len(data); i++ {
data[i] = 0xFF
}
imageWidth := image.Rect.Dx()
imageHeight := image.Rect.Dy()
if imageWidth == e.Width && imageHeight == e.Height {
for y := 0; y < imageHeight; y++ {
for x := 0; x < imageWidth; x++ {
if isBlack(image, x, y) {
pos := imageWidth - x
data[pos/8+y*lineWidth] &= ^(0x80 >> (pos % 8))
}
}
}
return data
}
if imageWidth == e.Height && imageHeight == e.Width {
for y := 0; y < imageHeight; y++ {
for x := 0; x < imageWidth; x++ {
if isBlack(image, x, y) {
posx := y
posy := imageWidth - (e.Height - x - 1) - 1
data[posx/8+posy*lineWidth] &= ^(0x80 >> (y % 8))
}
}
}
return data
}
fmt.Printf("Can't convert image expected %d %d but having %d %d", lineWidth, e.Height, imageWidth, imageHeight)
return data
}
func isBlack(image *image.RGBA, x, y int) bool {
r, g, b, a := getRGBA(image, x, y)
offset := 10
return r < 255-offset && g < 255-offset && b < 255-offset && a > offset
}
func getRGBA(image *image.RGBA, x, y int) (int, int, int, int) {
r, g, b, a := image.At(x, y).RGBA()
r = r / 257
g = g / 257
b = b / 257
a = a / 257
return int(r), int(g), int(b), int(a)
}
|
package main
import "fmt"
func main() {
// รับค่า
fmt.Print("Input Your Number : ")
// ตัวแปร ชื่อ input รับค่าแบบทศนิยม
var input float64
// แสดงผลเป็นทศนิยม
fmt.Scanf("%f", &input)
output := input * 2
fmt.Println(output)
}
|
package main
import (
"database/sql"
"errors"
"fmt"
"log"
"net/http"
"os"
"sort"
"github.com/gorilla/sessions"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/srinathgs/mysqlstore"
"golang.org/x/crypto/bcrypt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
var (
db *sqlx.DB
)
type (
LoginRequestBody struct {
Username string `json:"username,omitempty" form:"username"`
Password string `json:"password,omitempty" form:"password"`
}
User struct {
Username string `json:"username,omitempty" db:"Username"`
HashedPass string `json:"-" db:"HashedPass"`
}
City struct {
ID int `json:"id" db:"ID"`
Name string `json:"name" db:"Name"`
CountryCode string `json:"countryCode" db:"CountryCode"`
District string `json:"district,omitempty" db:"District"`
Population int `json:"population,omitempty" db:"Population"`
}
Country struct {
Code string `db:"Code"`
Name string `db:"Name"`
Continent string `db:"Continent"`
Region string `db:"Region"`
SurfaceArea float64 `db:"SurfaceArea"`
IndepYear sql.NullInt32 `db:"IndepYear"`
Population int `db:"Population"`
LifeExpectancy sql.NullFloat64 `db:"LifeExpectancy"`
GNP sql.NullFloat64 `db:"GNP"`
GNPOld sql.NullFloat64 `db:"GNPOld"`
LocalName string `db:"LocalName"`
GovernmentForm string `db:"GovernmentForm"`
HeadOfState sql.NullString `db:"HeadOfState"`
Capital sql.NullInt32 `db:"Capital"`
Code2 string `db:"Code2"`
}
CountryNamePop struct {
Code string `json:"countryCode,omitempty" db:"Code"`
Name string `json:"name,omitempty" db:"Name"`
Population int `json:"population,omitempty" db:"Population"`
}
CityPopulationResponse struct {
Name string
Population int
Ratio float64
}
WhoAmIResponse struct {
Username string `json:"username,omitempty" db:"username"`
}
CountryNameResponse struct {
Name string
}
CityNameResponse struct {
Name string
}
)
func initDB() *sqlx.DB {
_db, err := sqlx.Connect("mysql", fmt.Sprintf(
"%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
os.Getenv("DB_USERNAME"), os.Getenv("DB_PASSWORD"),
os.Getenv("DB_HOSTNAME"), os.Getenv("DB_PORT"),
os.Getenv("DB_DATABASE")))
if err != nil {
log.Fatalf("Cannot Connect to Database: %s", err)
}
// fmt.Println("Connected!")
return _db
}
func initSession() sessions.Store {
store, err := mysqlstore.NewMySQLStoreFromConnection(
db.DB, "sessions", "/", 60*60*24*14, []byte("secret-token"))
if err != nil {
panic(err)
}
return store
}
func postSignUpHandler(c echo.Context) error {
req := &LoginRequestBody{}
if err := c.Bind(req); err != nil {
return c.String(http.StatusBadRequest, "Bad request")
}
// TODO: バリデーションの内容を考える必要がある
if req.Password == "" || req.Username == "" {
return c.String(http.StatusBadRequest, "項目が空です")
}
hashedPass, hashErr := bcrypt.GenerateFromPassword(
[]byte(req.Password), bcrypt.DefaultCost)
if hashErr != nil {
return c.String(http.StatusInternalServerError,
fmt.Sprintf("bcrypt genetrate error: %v", hashErr))
}
// ユーザーの存在チェック
var count int
countQuery := "select count(*) from users where Username=?"
if queryErr := db.Get(&count, countQuery, req.Username); queryErr != nil {
return c.String(http.StatusInternalServerError,
fmt.Sprintf("db error: %v", queryErr))
}
if count > 0 {
return c.String(http.StatusConflict, "ユーザーが既に存在しています")
}
addUserQuery := "insert into users (Username, HashedPass) values(?, ?)"
if _, queryErr := db.Exec(
addUserQuery, req.Username, hashedPass); queryErr != nil {
return c.String(http.StatusInternalServerError,
fmt.Sprintf("db error: %v", queryErr))
}
return c.NoContent(http.StatusCreated)
}
func postLoginHandler(c echo.Context) error {
req := &LoginRequestBody{}
if err := c.Bind(req); err != nil {
return c.String(http.StatusBadRequest, "Bad request")
}
user := &User{}
userQuery := "select * from users where username=?"
if queryErr := db.Get(user, userQuery, req.Username); queryErr != nil {
return c.String(http.StatusInternalServerError,
fmt.Sprintf("db error: %v", queryErr))
}
if hashErr := bcrypt.CompareHashAndPassword(
[]byte(user.HashedPass), []byte(req.Password)); hashErr != nil {
if errors.Is(hashErr, bcrypt.ErrMismatchedHashAndPassword) {
return c.NoContent(http.StatusForbidden)
} else {
return c.NoContent(http.StatusInternalServerError)
}
}
sess, sessErr := session.Get("sessions", c)
if sessErr != nil {
fmt.Println(sessErr)
return c.String(http.StatusInternalServerError,
"something wrong in getting session")
}
sess.Values["userName"] = req.Username
sess.Save(c.Request(), c.Response())
return c.NoContent(http.StatusOK)
}
func checkLogin(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
sess, err := session.Get("sessions", c)
if err != nil {
fmt.Println(err)
return c.String(http.StatusInternalServerError,
"something wrong in getting session")
}
if sess.Values["userName"] == nil {
return c.String(http.StatusForbidden, "please login")
}
c.Set("userName", sess.Values["userName"].(string))
return next(c)
}
}
func getCity(name string) (*City, error) {
city := &City{}
query := "select * from city where name = ?"
if err := db.Get(city, query, name); errors.Is(err, sql.ErrNoRows) {
log.Printf("no such city Name %s\n", name)
return nil, err
} else if err != nil {
log.Fatalf("DB Error: %s", err)
return nil, err
}
return city, nil
}
func getCountries() (*[]Country, error) {
countries := &[]Country{}
query := "select * from country"
if err := db.Select(countries, query); err != nil {
log.Fatalf("DB Error: %s", err)
return nil, err
}
return countries, nil
}
func getCountryByName(name string) (*Country, error) {
country := &Country{}
query := "select * from country where Name = ?"
if err := db.Get(country, query, name); errors.Is(err, sql.ErrNoRows) {
log.Printf("no country %s found \n", country.Name)
return nil, err
} else if err != nil {
log.Fatalf("DB Error: %s", err)
return nil, err
}
return country, nil
}
func getCountryNamePop(code string) CountryNamePop {
countryNamePop := CountryNamePop{}
query := "select Code, Name, Population from country where code = ?"
if err := db.Get(
&countryNamePop, query, code); errors.Is(err, sql.ErrNoRows) {
log.Printf("no such country Code %s\n", code)
} else if err != nil {
log.Fatalf("DB Error: %s", err)
}
return countryNamePop
}
func getCitiesByCountry(country *Country) (*[]City, error) {
cities := &[]City{}
query := "select * from city where CountryCode = ?"
if err := db.Select(cities, query, country.Code); errors.Is(err, sql.ErrNoRows) {
log.Printf("no city found in country %s\n", country.Name)
return nil, err
} else if err != nil {
log.Fatalf("DB Error: %s", err)
return nil, err
}
return cities, nil
}
func getCityPopulationHandler(c echo.Context) error {
target_city := c.Param("cityName")
city, _ := getCity(target_city)
fmt.Printf("%sの人口は%d人です\n", target_city, city.Population)
countryNamePop := getCountryNamePop(city.CountryCode)
ratio := float64(city.Population) / float64(countryNamePop.Population)
fmt.Printf("%sの人口は%sの人口の%f%%です\n",
target_city, countryNamePop.Name, ratio*100.0)
return c.JSON(http.StatusOK, CityPopulationResponse{
Name: target_city,
Population: city.Population,
Ratio: ratio,
})
}
func getCityInfoHandler(c echo.Context) error {
target_city := c.Param("cityName")
city, err := getCity(target_city)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return c.String(http.StatusBadRequest, "no city found")
} else {
return c.String(http.StatusInternalServerError,
"something went wrong")
}
}
return c.JSON(http.StatusOK, *city)
}
func postCityHandler(c echo.Context) error {
new_city := &City{}
if err := c.Bind(new_city); err != nil {
return c.String(http.StatusBadRequest, "Bad request")
}
query := `
insert into
city (Name, CountryCode, District, Population)
values
(:Name, :CountryCode, :District, :Population)
`
if _, err := db.NamedExec(query, new_city); err != nil {
log.Fatalf("DB Error: %s", err)
}
return c.String(http.StatusOK, "")
}
func getWhoAmIHandler(c echo.Context) error {
username := c.Get("userName").(string)
return c.JSON(http.StatusOK, WhoAmIResponse{
Username: username,
})
}
func getCountriesHandler(c echo.Context) error {
countries, err := getCountries()
if err != nil {
return c.String(http.StatusInternalServerError,
"something went wrong")
}
response := []CountryNameResponse{}
for _, country := range *countries {
response = append(response, CountryNameResponse{
Name: country.Name,
})
}
sort.SliceStable(response,
func(i, j int) bool { return response[i].Name < response[j].Name })
return c.JSON(http.StatusOK, response)
}
func getCountryCitiesHandler(c echo.Context) error {
countryName := c.Param("countryName")
country, err := getCountryByName(countryName)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return c.String(http.StatusBadRequest, "no cities found")
} else {
return c.String(http.StatusInternalServerError,
"something went wrong")
}
}
cities, err := getCitiesByCountry(country)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return c.String(http.StatusBadRequest, "no cities found")
} else {
return c.String(http.StatusInternalServerError,
"something went wrong")
}
}
response := []CityNameResponse{}
for _, city := range *cities {
response = append(response, CityNameResponse{
Name: city.Name,
})
}
sort.SliceStable(response,
func(i, j int) bool { return response[i].Name < response[j].Name })
return c.JSON(http.StatusOK, response)
}
func main() {
db = initDB()
store := initSession()
e := echo.New()
e.Use(middleware.Logger())
e.Use(session.Middleware(store))
e.GET("/ping", func(c echo.Context) error {
return c.String(http.StatusOK, "pong")
})
e.POST("/login", postLoginHandler)
e.POST("/signup", postSignUpHandler)
withLogin := e.Group("")
withLogin.Use(checkLogin)
withLogin.GET("/cities/:cityName", getCityInfoHandler)
withLogin.GET("/whoami", getWhoAmIHandler)
withLogin.GET("/countries", getCountriesHandler)
withLogin.GET("/country/:countryName/cities", getCountryCitiesHandler)
e.Start(":10101")
}
|
package JsonStructure
//******************************************************************************
/*
struct for User Request
*/
type QueryReqS struct {
Mdn string `json:"mdn"`
Dateofdeparture string `json:"dateofdeparture"`
Dateofarrival string `json:"dateofarrival"`
Source string `json:"source"`
Destination string `json:"destination"`
Seatingclass string `json:"seatingclass"`
Adults string `json:"adults"`
Children string `json:"children"`
Infants string `json:"infants"`
Counter string `json:"counter"`
City string `json:"city"`
Rating string `json:"rating"`
La string `json:"la"`
Lo string `json:"lo"`
Country string `json:"country"`
Amenities string `json:"amenities"`
}
//******************************************************************************
|
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
)
const spotifyBaseUrl = "https://api.spotify.com"
const spotifyAuthUrl = "https://accounts.spotify.com/api/token"
const spotifyClientId = "867357abf03643fab0ee2cad0b8903f9"
func getSpotifyAuth(w http.ResponseWriter, r *http.Request) {
req, err := http.NewRequest("POST", spotifyAuthUrl, strings.NewReader("grant_type=client_credentials"))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
spotifyApiKey := os.Getenv("SPOTIFY_AUTH_KEY")
req.SetBasicAuth(spotifyClientId, spotifyApiKey)
checkErr(err, w)
res, err := http.DefaultClient.Do(req)
checkErr(err, w)
parsedBody, err := parseHttpBody(res.Body)
checkErr(err, w)
if res.StatusCode != 200 {
log.Fatalf("No auth")
}
fmt.Fprintf(w, "Login success")
var access_token string = parsedBody["access_token"].(string)
req, err = http.NewRequest("GET", spotifyBaseUrl+"/v1/tracks/11dFghVXANMlKmJXsNCbNl", nil)
req.Header.Add("Authorization", "Bearer "+access_token)
res, err = http.DefaultClient.Do(req)
checkErr(err, w)
parsedBody, err = parseHttpBody(res.Body)
log.Println(parsedBody)
}
|
package main
import (
"github.com/lavpthak/easysurvey/app/routes"
"github.com/lavpthak/easysurvey/app/routes/survey"
"github.com/labstack/echo"
)
func main() {
e := echo.New()
e.GET("/", routes.Index)
e.GET("/survey/all", survey.GetAll)
e.Logger.Fatal(e.Start(":8081"))
}
|
package util
// Pagination page
type Pagination struct {
PerPage int `json:"per_page"`
Page int `json:"page"`
TotalCount int `json:"total_count"`
PageCount int `json:"page_count"`
}
func InitPagination(totalCount, pageSize, page int) Pagination {
pageCount := totalCount / pageSize
if totalCount%pageSize > 0 {
pageCount = totalCount/pageSize + 1
}
return Pagination{
TotalCount: totalCount,
PageCount: pageCount,
Page: page,
PerPage: pageSize,
}
}
|
package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"os"
"runtime"
"strconv"
"strings"
"time"
)
// Object represents the row of the CSV as an object to use for writing and parsing data
type Object struct {
Discriminator string
Key string
Text string
}
// used to replace special characters with their html encoding
var htmlEscaper = strings.NewReplacer(
`&`, "&",
`'`, "'", // "'" is shorter than "'" and apos was not in HTML until HTML5.
`<`, "<",
`>`, ">",
`"`, """, // """ is shorter than """.
`§`, "§",
)
// parse CSV and read each line into a object type
func parseCSV(path string) ([]Object, error) {
csvFile, _ := os.Open(path)
reader := csv.NewReader(csvFile)
var objects []Object
for {
line, err := reader.Read()
if err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
objects = append(objects, Object{
Discriminator: line[0],
Key: line[1],
Text: line[3],
})
}
return objects, nil
}
// split up workload
func splitWork(objects []Object, author string) {
jobcount := runtime.NumCPU() // total jobs to run
length := len(objects) // number of elements
divided := length / jobcount // how many items should exist in each job
// setup channels for jobs
jobs := make(chan string)
// iterate for each job
for i := 0; i < jobcount; i++ {
go createLiquiBase(i, objects[i*divided:(i+1)*divided], jobs, author)
}
// for each job block until all complete
for i := 0; i < jobcount; i++ {
<-jobs
}
close(jobs)
}
// handle a workload
func createLiquiBase(count int, objects []Object, jobs chan string, author string) {
// generate the custom id based on time
timestamp := time.Now().Format("200601021504")
id := timestamp + "_update_" + strconv.Itoa(count)
// use a string builder to be efficient
var liquiBase strings.Builder
// append liquiBase databaseChangelog and changeSet information
liquiBase.WriteString("<databaseChangeLog xmlns='http://www.liquiBase.org/xml/ns/dbchangelog'\n")
liquiBase.WriteString("\t\txmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n")
liquiBase.WriteString("\t\txsi:schemaLocation='http://www.liquiBase.org/xml/ns/dbchangelog http://www.liquiBase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd'>\n\n")
liquiBase.WriteString("\t<changeSet author='")
liquiBase.WriteString(author)
liquiBase.WriteString("' id='")
liquiBase.WriteString(id)
liquiBase.WriteString("' runOnChange='false'>\n")
// loop through each object and append a liquiBase update statement
for _, object := range objects {
liquiBase.WriteString("\t\t<update tableName='")
liquiBase.WriteString(object.Discriminator)
liquiBase.WriteString("'>\n")
liquiBase.WriteString("\t\t\t<column name='TEXT' value='")
// trim trailing whitespace and html encode special characters
liquiBase.WriteString(htmlEscaper.Replace(strings.TrimSpace(object.Text)))
liquiBase.WriteString("'/>\n")
liquiBase.WriteString("\t\t\t<where>KEY = '")
liquiBase.WriteString(object.Key)
liquiBase.WriteString("'</where>\n")
liquiBase.WriteString("\t\t</update>\n")
}
// append liquiBase change set and databaseChangelog closing tags
liquiBase.WriteString("\t</changeset>\n")
liquiBase.WriteString("</databaseChangeLog>")
// write the liquiBase to a file
writeLiquiBase(id, liquiBase.String())
jobs <- id
}
// takes a change set id and the liquiBase body
func writeLiquiBase(id string, liquibase string) {
var filename = id + ".xml"
// attempt to create file
file, err := os.Create(filename)
if err != nil {
log.Fatal(err)
}
defer file.Close()
// write file
_, er := file.WriteString(liquibase)
if er != nil {
log.Fatal(er)
}
}
func main() {
inputFile := os.Args[1]
author := os.Args[2]
// confirm number of CPU threads available
fmt.Println("Threads Used: " + strconv.Itoa(runtime.NumCPU()))
// parse the CSV into an object slice
objects, _ := parseCSV(inputFile)
// attempt to split the work to write out liquiBase for the objects
splitWork(objects, author)
}
|
package server
import (
"FPproject/Backend/log"
"FPproject/Backend/models"
"net/http"
"github.com/gin-gonic/gin"
)
func (h *Handler) InsertFood(c *gin.Context) {
var body models.Food
err := c.BindJSON(&body)
if err != nil {
log.Info.Println(err)
c.JSON(http.StatusBadRequest, gin.H{
"status": "bad request",
})
return
}
id, err := h.db.InsertFood(body)
if err != nil {
log.Warning.Println(err)
c.JSON(http.StatusInternalServerError, gin.H{
"status": "internal server error",
})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "OK",
"id": id,
})
}
func (h *Handler) DelFood(c *gin.Context) {
foodid := c.Param("id")
id, err := h.db.DelFood(foodid)
if err != nil {
log.Warning.Println(err)
c.JSON(http.StatusInternalServerError, gin.H{
"status": "internal server error",
})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "OK",
"id": id,
})
}
func (h *Handler) GetFood(c *gin.Context) {
foodid := c.Param("id")
var body models.Food
body, err := h.db.GetFood(foodid)
if err != nil {
log.Warning.Println(err)
c.JSON(http.StatusInternalServerError, gin.H{
"status": "internal server error",
})
return
}
c.JSON(http.StatusOK, body)
}
func (h *Handler) GetFoodByMerchant(c *gin.Context) {
merchantid := c.Param("id")
var body []models.Food
body, err := h.db.GetFoodByMerchant(merchantid)
if err != nil {
log.Warning.Println(err)
c.JSON(http.StatusInternalServerError, gin.H{
"status": "internal server error",
})
return
}
c.JSON(http.StatusOK, body)
}
func (h *Handler) UpdateFood(c *gin.Context) {
var body models.Food
err := c.BindJSON(&body)
if err != nil {
log.Info.Println(err)
c.JSON(http.StatusBadRequest, gin.H{
"status": "bad request",
})
return
}
id, err := h.db.UpdateFood(body)
if err != nil {
log.Warning.Println(err)
c.JSON(http.StatusInternalServerError, gin.H{
"status": "internal server error",
})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "OK",
"id": id,
})
}
|
package backend
import (
"encoding/json"
"errors"
"io/fs"
"os"
"strconv"
"strings"
"time"
)
const NO_SESSION_NUMBER = -1
// Represents a single note-taking session.
type Session struct {
Notes []Note // the collection of all notes created by the user
Date time.Time // the date and time this session began
SessionTitle string // the name of the session, if one exists
SessionNumber int // the number of the session, if one exists
Path string // the path to the file where this session is saved, if one exists
}
// An option to customize the constructor for creating a new session.
type NewSessionOption func(s *Session)
// Create a new Session.
func NewSession(sessionTitle string, sessionNumber int, options ...NewSessionOption) *Session {
session := Session{
Notes: make([]Note, 0),
Date: time.Now(),
SessionTitle: sessionTitle,
SessionNumber: sessionNumber,
Path: "",
}
for _, options := range options {
options(&session)
}
return &session
}
// Option to create a new session with a custom date field. Primarily for use in testing.
func withCustomDate(t time.Time) NewSessionOption {
return func(s *Session) {
s.Date = t
}
}
// Adds a note to this session.
func (s *Session) AddNote(n Note) {
// if the note is empty, it is likely user error
if n.Content == "" {
return
}
s.Notes = append(s.Notes, n)
}
// Returns a JSON reprsentation of the session for purposes of serialization.
func (s *Session) ToJSON() string {
builder := new(strings.Builder)
encoder := json.NewEncoder(builder)
encoder.Encode(s)
return builder.String()
}
// Builds a session from a JSON representation of a session.
// If the input string is invalid, returns a pointer to an empty Session and an error.
func FromJSON(s string) (*Session, error) {
reader := strings.NewReader(s)
decoder := json.NewDecoder(reader)
session := Session{}
err := decoder.Decode(&session)
if err != nil {
return &Session{}, err
}
// rectify invalid data modified externally outside of the application
if session.SessionNumber < NO_SESSION_NUMBER {
session.SessionNumber = NO_SESSION_NUMBER
}
return &session, nil
}
// Writes Session data to specified file.
func (s *Session) Save() error {
UserRW := fs.FileMode(0600)
return os.WriteFile(s.Path, []byte(s.ToJSON()), UserRW)
}
// Load Session data from specified file.
// In the case of an error during reading the file or converting it into a session,
// returns an empty session and an error.
func Load(path string) (*Session, error) {
data, err := os.ReadFile(path)
if err != nil {
return &Session{}, err
}
s, err := FromJSON(string(data))
if err != nil {
return &Session{}, err
}
return s, nil
}
// Ensures that a session number entered by a user is non-negative.
//
// The function signature is modeled to be a fyne.StringValidator.
func ValidateSessionNumber(sessionNumber string) error {
if sessionNumber == "" {
return nil
}
i, err := strconv.Atoi(sessionNumber)
if err != nil {
return err
}
if i < NO_SESSION_NUMBER {
return errors.New("Session numbers cannot be less than 0")
}
return nil
}
|
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/troydai/blocks/echo/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
func main() {
conn, err := grpc.Dial("localhost:5436", grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
log.Fatalf("fail to dial tcp: %v", err)
}
defer conn.Close()
client := proto.NewEchoServerClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
m := metadata.New(map[string]string{"reqctx-persist": "from-edge"})
ctx = metadata.NewOutgoingContext(ctx, m)
req := &proto.EchoRequest{Message: extractMessage()}
resp, err := client.Echo(ctx, req)
if err != nil {
log.Fatalf("fail to communicate with the server")
}
fmt.Printf("message: %s\n", resp.Message)
fmt.Printf(" digest: %x\n", resp.Digest)
}
func extractMessage() string {
if len(os.Args) < 2 {
return "test message"
}
return os.Args[1]
}
|
package merkle
const (
// MaxBlockSize reasonable max byte size for blocks that are checksummed for
// a Node
MaxBlockSize = 1024 * 16
)
// DetermineBlockSize returns a reasonable block size to use, based on the
// provided size
func DetermineBlockSize(blockSize int) int {
var b = blockSize
for b > MaxBlockSize {
b /= 2
}
if b == 0 || (blockSize%b != 0) {
return 0
}
return b
}
|
package rpc_user
import (
"github.com/bqxtt/book_online/rpc/model/userpb"
"google.golang.org/grpc"
"log"
)
var UserServiceClient userpb.UserServiceClient
const (
address = "localhost:50001"
//address = "101.200.155.166:30001"
)
func Init() {
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
log.Println("user rpc service connect...")
UserServiceClient = userpb.NewUserServiceClient(conn)
}
|
package main
import "github.com/aelindeman/namedns/cmd"
func main() {
cmd.Execute()
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//389. Find the Difference
//Given two strings s and t which consist of only lowercase letters.
//String t is generated by random shuffling string s and then add one more letter at a random position.
//Find the letter that was added in t.
//Example:
//Input:
//s = "abcd"
//t = "abcde"
//Output:
//e
//Explanation:
//'e' is the letter that was added.
//func findTheDifference(s string, t string) byte {
//}
// Time Is Money |
package routing
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"net"
"os/exec"
"regexp"
log "github.com/Sirupsen/logrus"
)
func InitBGPMonitoring(masterIface string) {
ethIface = masterIface
err := cleanExistingRoutes(ethIface)
if err != nil {
log.Infof("Error cleaning old routes: %s", err)
}
// Read all existing routes from BGP peers
ribSlice := readExistingRib()
if err != nil {
log.Infof("Error getting existing routes", err)
}
log.Infof("Adding Netlink routes the learned BGP routes: %s ", ribSlice)
bgpCache := &RibCache{
BgpTable: make(map[string]*RibLocal),
}
learnedRoutes := bgpCache.handleRouteList2(ribSlice)
log.Infof("Processing [ %d ] routes learned via BGP", len(learnedRoutes))
for _, entry := range learnedRoutes {
// todo: what to do if the learned bgp route
// overlaps with an existing netlink. This check
// simply throws an error msg but still adds route
verifyRoute(entry.BgpPrefix)
err = addNetlinkRoute(entry.BgpPrefix, entry.NextHop, ethIface)
if err != nil {
log.Errorf("Add netlink route results [ %s ]", err)
}
}
cmd := exec.Command(bgpCmd, monitor, global, rib, jsonFmt)
cmdStdout, err := cmd.StdoutPipe()
if err != nil {
log.Panicf("Error reading file with tail: %s", err)
}
cmdReader := bufio.NewReader(cmdStdout)
cmd.Start()
log.Info("Initialization complete, now monitoring BGP for new routes..")
for {
route, err := cmdReader.ReadString('\n')
log.Infof("Raw json message %s ", route)
if err != nil {
log.Error("Error reading JSON: %s", err)
}
var msg RibMonitor
if err := json.Unmarshal([]byte(route), &msg); err != nil {
log.Error(err)
}
// Monitor and process the BGP update
monitorUpdate, err := bgpCache.handleBgpRibMonitor(msg)
if err != nil {
log.Errorf("error processing bgp update [ %s ]", err)
}
if monitorUpdate.IsLocal != true {
if isWithdrawn(route) {
monitorUpdate.IsWithdraw = true
log.Infof("BGP update has [ withdrawn ] the IP prefix [ %s ]", monitorUpdate.BgpPrefix.String())
// If the bgp update contained a withdraw, remove the local netlink route for the remote endpoint
err = delNetlinkRoute(monitorUpdate.BgpPrefix, monitorUpdate.NextHop, ethIface)
if err != nil {
log.Errorf("Error removing learned bgp route [ %s ]", err)
}
} else {
monitorUpdate.IsWithdraw = false
learnedRoutes = append(learnedRoutes, *monitorUpdate)
log.Debugf("Learned routes: %v ", monitorUpdate)
err = addNetlinkRoute(monitorUpdate.BgpPrefix, monitorUpdate.NextHop, ethIface)
if err != nil {
log.Debugf("Add route results [ %s ]", err)
}
log.Infof("Updated the local prefix cache from the newly learned BGP update:")
for n, entry := range learnedRoutes {
log.Debugf("%d - %+v", n+1, entry)
}
}
}
log.Debugf("Verbose update details: %s", monitorUpdate)
}
}
func (cache *RibCache) handleBgpRibMonitor(routeMonitor RibMonitor) (*RibLocal, error) {
ribLocal := &RibLocal{}
log.Debugf("BGP update for prefix: [ %v ] ", routeMonitor.Nlri.Prefix)
if routeMonitor.Nlri.Prefix != "" {
bgpPrefix, err := ParseIPNet(routeMonitor.Nlri.Prefix)
if err != nil {
log.Errorf("Error parsing the bgp update prefix")
}
ribLocal.BgpPrefix = bgpPrefix
}
for _, attr := range routeMonitor.Attrs {
log.Debugf("Type: [ %d ] Value: [ %s ]", attr.Type, attr.Value)
switch attr.Type {
case BGP_ATTR_TYPE_ORIGIN:
// 0 = iBGP; 1 = eBGP
if attr.Value != nil {
log.Debugf("Type Code: [ %d ] Origin: %g", BGP_ATTR_TYPE_ORIGIN, attr.Nexthop)
}
case BGP_ATTR_TYPE_AS_PATH:
if attr.Value != nil {
log.Debugf("Type Code: [ %d ] AS_Path: %s", BGP_ATTR_TYPE_AS_PATH, attr.Nexthop)
}
case BGP_ATTR_TYPE_NEXT_HOP:
if attr.Nexthop != "" {
log.Debugf("Type Code: [ %d ] Nexthop: %s", BGP_ATTR_TYPE_NEXT_HOP, attr.Nexthop)
ribLocal.NextHop = net.ParseIP(attr.Nexthop)
if ribLocal.NextHop.String() == localNexthop {
ribLocal.IsLocal = true
}
}
case BGP_ATTR_TYPE_MULTI_EXIT_DISC:
if attr.Value != nil {
log.Debugf("Type Code: [ %d ] MED: %g", BGP_ATTR_TYPE_MULTI_EXIT_DISC, attr.Nexthop)
}
case BGP_ATTR_TYPE_LOCAL_PREF:
if attr.Value != nil {
log.Debugf("Type Code: [ %d ] Local Pref: %g", BGP_ATTR_TYPE_LOCAL_PREF, attr.Nexthop)
}
case BGP_ATTR_TYPE_ORIGINATOR_ID:
if attr.Value != nil {
log.Debugf("Type Code: [ %d ] Originator IP: %s", BGP_ATTR_TYPE_ORIGINATOR_ID, attr.Nexthop)
ribLocal.OriginatorIP = net.ParseIP(attr.Value.(string))
log.Debugf("Type Code: [ %d ] Originator IP: %s", BGP_ATTR_TYPE_ORIGINATOR_ID, ribLocal.OriginatorIP)
}
case BGP_ATTR_TYPE_CLUSTER_LIST:
if len(attr.ClusterList) > 0 {
log.Debugf("Type Code: [ %d ] Cluster List: %s", BGP_ATTR_TYPE_CLUSTER_LIST, attr.Nexthop)
}
case BGP_ATTR_TYPE_MP_REACH_NLRI:
if attr.Value != nil {
log.Debugf("Type Code: [ %d ] MP Reachable: %v", BGP_ATTR_TYPE_MP_REACH_NLRI, attr.Nexthop)
}
case BGP_ATTR_TYPE_MP_UNREACH_NLRI:
if attr.Value != nil {
log.Debugf("Type Code: [ %d ] MP Unreachable: %v", BGP_ATTR_TYPE_MP_UNREACH_NLRI, attr.Nexthop)
}
case BGP_ATTR_TYPE_EXTENDED_COMMUNITIES:
if attr.Value != nil {
log.Debugf("Type Code: [ %d ] Extended Communities: %v", BGP_ATTR_TYPE_EXTENDED_COMMUNITIES, attr.Nexthop)
}
default:
log.Errorf("Unknown BGP attribute code [ %d ]")
}
}
return ribLocal, nil
}
func (cache *RibCache) handleRouteList2(jsonMsg string) []RibLocal {
var ribIn []RibIn
localRib := &RibLocal{}
localRibList := []RibLocal{}
if unmarshallErr := json.Unmarshal([]byte(jsonMsg), &ribIn); unmarshallErr != nil {
fmt.Println("Unmarshaling json error: ", unmarshallErr.Error())
} else {
for _, routeIn := range ribIn {
for _, paths := range routeIn.Paths {
if routeIn.Prefix != "" {
bgpPrefix, err := ParseIPNet(routeIn.Prefix)
if err != nil {
log.Errorf("Error parsing the bgp update prefix")
}
localRib.BgpPrefix = bgpPrefix
log.Debugf("Details for learned BGP Prefix [ %s ]", bgpPrefix.String())
}
for _, attr := range paths.Attrs {
// log.Printf("Type: [ %d ] Value: [ %s ]", attr.Type, attr.Value)
switch attr.Type {
case BGP_ATTR_TYPE_ORIGIN:
// 0 = iBGP; 1 = eBGP
// if attr.Value != nil {
log.Debugf("Type Code: [ %d ] Origin: %g", BGP_ATTR_TYPE_ORIGIN, attr.Value)
// }
case BGP_ATTR_TYPE_AS_PATH:
if attr.AsPaths != "" {
log.Debugf("Type Code: [ %d ] AS_Path: %s", BGP_ATTR_TYPE_AS_PATH, attr.AsPaths)
}
case BGP_ATTR_TYPE_NEXT_HOP:
if attr.Nexthop != "" {
log.Debugf("Type Code: [ %d ] Nexthop: %s", BGP_ATTR_TYPE_NEXT_HOP, attr.Nexthop)
localRib.NextHop = net.ParseIP(attr.Nexthop)
if localRib.NextHop.String() == localNexthop {
localRib.IsLocal = true
}
}
case BGP_ATTR_TYPE_MULTI_EXIT_DISC:
if attr.Metric != 0 {
log.Debugf("Type Code: [ %d ] MED: %g", BGP_ATTR_TYPE_MULTI_EXIT_DISC, attr.Metric)
}
case BGP_ATTR_TYPE_LOCAL_PREF:
if attr.Value != nil {
log.Debugf("Type Code: [ %d ] Local Pref: %g", BGP_ATTR_TYPE_LOCAL_PREF, attr.Value)
}
case BGP_ATTR_TYPE_ORIGINATOR_ID:
if attr.Value != "" {
localRib.OriginatorIP = net.ParseIP(attr.Value.(string))
log.Debugf("Type Code: [ %d ] Originator IP: %s", BGP_ATTR_TYPE_ORIGINATOR_ID, localRib.OriginatorIP.String())
}
case BGP_ATTR_TYPE_CLUSTER_LIST:
if len(attr.ClusterList) > 0 {
log.Debugf("Type Code: [ %d ] Cluster List: %s", BGP_ATTR_TYPE_CLUSTER_LIST, attr.ClusterList)
}
case BGP_ATTR_TYPE_MP_REACH_NLRI:
if attr.Value != nil {
log.Debugf("Type Code: [ %d ] MP Reachable: %v", BGP_ATTR_TYPE_MP_REACH_NLRI, attr.Nexthop)
}
case BGP_ATTR_TYPE_MP_UNREACH_NLRI:
if attr.Value != nil {
log.Debugf("Type Code: [ %d ] MP Unreachable: %v", BGP_ATTR_TYPE_MP_UNREACH_NLRI, attr.Nexthop)
}
case BGP_ATTR_TYPE_EXTENDED_COMMUNITIES:
if attr.Value != nil {
log.Debugf("Type Code: [ %d ] Extended Communities: %v", BGP_ATTR_TYPE_EXTENDED_COMMUNITIES, attr.Nexthop)
}
default:
log.Errorf("Unknown BGP attribute code")
}
}
}
localRibList = append(localRibList, *localRib)
}
}
log.Debugf("Verbose json for the [ %d ] routes learned via BGP: %+v", len(localRibList), localRibList)
return localRibList
}
// return string representation of pluginConfig for debugging
func (d *RibLocal) stringer() string {
str := fmt.Sprintf("Prefix:[ %s ], ", d.BgpPrefix.String())
str = str + fmt.Sprintf("OriginatingIP:[ %s ], ", d.OriginatorIP.String())
str = str + fmt.Sprintf("Nexthop:[ %s ], ", d.NextHop.String())
str = str + fmt.Sprintf("IsWithdrawn:[ %t ], ", d.IsWithdraw)
str = str + fmt.Sprintf("IsHostRoute:[ %t ]", d.IsHostRoute)
return str
}
func JsonPrettyPrint(input string) string {
var buf bytes.Buffer
json.Indent(&buf, []byte(input), "", " ")
return buf.String()
}
func gobgp(cmd string, arg ...string) (bytes.Buffer, bytes.Buffer, error) {
var stdout, stderr bytes.Buffer
command := exec.Command(cmd, arg...)
command.Stdout = &stdout
command.Stderr = &stderr
err := command.Run()
return stdout, stderr, err
}
// Temporary until addOvsVethPort works
func readExistingRib() string {
cmd, stderr, err := gobgp(bgpCmd, global, rib, jsonFmt)
if err != nil {
log.Errorf("%s", stderr)
return ""
}
return cmd.String()
}
func monitorBgpRIB(bridge string, port string) error {
_, stderr, err := gobgp(bgpCmd, monitor, global, rib, jsonFmt)
if err != nil {
errmsg := stderr.String()
return errors.New(errmsg)
}
return nil
}
func ParseIPNet(s string) (*net.IPNet, error) {
ip, ipNet, err := net.ParseCIDR(s)
if err != nil {
return nil, err
}
return &net.IPNet{IP: ip, Mask: ipNet.Mask}, nil
}
func isWithdrawn(str string) bool {
isWithdraw, _ := regexp.Compile(`\"isWithdraw":true`)
return isWithdraw.MatchString(str)
}
|
package pg
import (
"github.com/kyleconroy/sqlc/internal/sql/ast"
)
type RangeFunction struct {
Lateral bool
Ordinality bool
IsRowsfrom bool
Functions *ast.List
Alias *Alias
Coldeflist *ast.List
}
func (n *RangeFunction) Pos() int {
return 0
}
|
package design
// "go generate ./..." to regenerate bindata!
//go:generate go run ./data-compiler png design generationX4 icon72 icon96 ripple circle192
// DesignScale is the current scale for the Design.
var DesignScale float64
// Setup sets the sizes, fonts and borders according to the given scale.
func Setup(scale float64) {
DesignScale = scale
deSetupSizes()
deSetupFonts()
deSetupBorders()
deSetupIcons()
deSetupRipple()
deSetupCircle()
}
|
package cmd
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"github.com/spf13/cobra"
)
var SubArrayMaxSumCmd = &cobra.Command{
Use: "subArrayMaxSum",
Short: "Calculate maximum sub array sum",
Run: SubArrayMaxSum,
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func SubArrayMaxSum(cmd *cobra.Command, args []string) {
fmt.Println("Enter numbers for array separated by newline.")
fmt.Println("Enter empty line to calculate")
scanner := bufio.NewScanner(os.Stdin)
var array []int
for scanner.Scan() {
num := scanner.Text()
if len(num) == 0 {
break
}
arrayNum, err := strconv.Atoi(num)
fatalOnError(err)
array = append(array, arrayNum)
}
if len(array) == 0 {
log.Fatalln("Please put valid array")
}
var tSum, maxSum int
for _, val := range array {
tSum = max(val, tSum+val)
maxSum = max(maxSum, tSum)
}
log.Printf("Max subarray sum: %v", maxSum)
}
|
package register
import (
"bufio"
"regexp"
"strconv"
"strings"
)
const (
pattern = `([a-z]+) (inc|dec) (-?[0-9]+) if ([a-z]+) ([<>=!]+) (-?[0-9]+)`
)
type condition func(map[string]int, string, int) bool
func gt(registry map[string]int, reg string, val int) bool {
return registry[reg] > val
}
func lt(registry map[string]int, reg string, val int) bool {
return registry[reg] < val
}
func eq(registry map[string]int, reg string, val int) bool {
return registry[reg] == val
}
func ne(registry map[string]int, reg string, val int) bool {
return registry[reg] != val
}
func ge(registry map[string]int, reg string, val int) bool {
return registry[reg] >= val
}
func le(registry map[string]int, reg string, val int) bool {
return registry[reg] <= val
}
var cons = map[string]condition{
`>`: gt,
`<`: lt,
`==`: eq,
`!=`: ne,
`>=`: ge,
`<=`: le,
}
type operation func(map[string]int, string, int) int
func inc(registry map[string]int, reg string, val int) int {
return registry[reg] + val
}
func dec(registry map[string]int, reg string, val int) int {
return registry[reg] - val
}
var ops = map[string]operation{
`inc`: inc,
`dec`: dec,
}
func findMax(instructions string) (int, int) {
registry := make(map[string]int)
var highest int
lines := bufio.NewScanner(strings.NewReader(instructions))
for lines.Scan() {
inst := lines.Text()
if strings.TrimSpace(inst) == "" {
continue
}
re := regexp.MustCompile(pattern)
tokens := re.FindAllStringSubmatch(inst, -1)
if len(tokens) > 0 {
t := tokens[0]
v, _ := strconv.Atoi(t[6])
if cons[t[5]](registry, t[4], v) {
v, _ := strconv.Atoi(t[3])
h := ops[t[2]](registry, t[1], v)
if highest < h {
highest = h
}
registry[t[1]] = h
}
}
}
var max int
for _, v := range registry {
if max < v {
max = v
}
}
return max, highest
}
|
package transport
import (
"bytes"
"encoding/binary"
)
const (
FIN = 1 // 00 0001
SYN = 2 // 00 0010
RST = 4 // 00 0100
PSH = 8 // 00 1000
ACK = 16 // 01 0000
URG = 32 // 10 0000
)
type TCPHeader struct {
Source int //uint16
Destination int //uint16
SeqNum int //uint32
AckNum int //uint32
DataOffset int //uint8 // 4 bits
Reserved int //uint8 // 3 bits
ECN int //uint8 // 3 bits
Ctrl int //uint8 // 6 bits
Window int //uint16
Checksum int //uint16 // Kernel will set this if it's 0
Urgent int //uint16
Options []TCPOption
}
type TCPOption struct {
Kind uint8
Length uint8
Data []byte
}
func (tcp *TCPHeader) HasFlag(flagBit int) bool {
return tcp.Ctrl&flagBit != 0
}
func MakeTcpHeader(srcport int,
dstport int,
seqnum int,
acknum int,
ctrl int,
ws int) TCPHeader {
h := TCPHeader{
Source: srcport,
Destination: dstport,
SeqNum: seqnum,
AckNum: acknum,
DataOffset: 5,
Ctrl: ctrl,
Window: ws,
Checksum: 0,
Options: []TCPOption{},
}
return h
}
func (tcp *TCPHeader) Marshal() []byte {
buf := new(bytes.Buffer)
binary.Write(buf, binary.BigEndian, uint16(tcp.Source))
binary.Write(buf, binary.BigEndian, uint16(tcp.Destination))
binary.Write(buf, binary.BigEndian, uint32(tcp.SeqNum))
binary.Write(buf, binary.BigEndian, uint32(tcp.AckNum))
var mix uint16
mix = uint16(tcp.DataOffset)<<12 | // top 4 bits
uint16(tcp.Reserved)<<9 | // 3 bits
uint16(tcp.ECN)<<6 | // 3 bits
uint16(tcp.Ctrl) // bottom 6 bits
binary.Write(buf, binary.BigEndian, mix)
binary.Write(buf, binary.BigEndian, uint16(tcp.Window))
binary.Write(buf, binary.BigEndian, uint16(tcp.Checksum))
binary.Write(buf, binary.BigEndian, uint16(tcp.Urgent))
for _, option := range tcp.Options {
binary.Write(buf, binary.BigEndian, option.Kind)
if option.Length > 1 {
binary.Write(buf, binary.BigEndian, option.Length)
binary.Write(buf, binary.BigEndian, option.Data)
}
}
out := buf.Bytes()
// Pad to min tcp header size, which is 20 bytes (5 32-bit words)
if len(out) > 20 {
pad := 24 - len(out)
for i := 0; i < pad; i++ {
out = append(out, 0)
}
}
return out
}
// Parse packet into TCPHeader structure
func Unmarshal(data []byte) *TCPHeader {
var tcp TCPHeader
r := bytes.NewReader(data)
var src uint16
var dst uint16
var seq uint32
var ack uint32
binary.Read(r, binary.BigEndian, &src)
binary.Read(r, binary.BigEndian, &dst)
binary.Read(r, binary.BigEndian, &seq)
binary.Read(r, binary.BigEndian, &ack)
tcp.Source = int(src)
tcp.Destination = int(dst)
tcp.SeqNum = int(seq)
tcp.AckNum = int(ack)
var mix uint16
binary.Read(r, binary.BigEndian, &mix)
tcp.DataOffset = int(mix >> 12) // top 4 bits
tcp.Reserved = int(mix >> 9 & 7) // 3 bits
tcp.ECN = int(mix >> 6 & 7) // 3 bits
tcp.Ctrl = int(mix & 0x3f) // bottom 6 bits
var window uint16
var checksum uint16
var urgent uint16
binary.Read(r, binary.BigEndian, &window)
binary.Read(r, binary.BigEndian, &checksum)
binary.Read(r, binary.BigEndian, &urgent)
tcp.Window = int(window)
tcp.Checksum = int(checksum)
tcp.Urgent = int(urgent)
return &tcp
}
|
package tests
import (
"errors"
"fmt"
"math/rand"
"strings"
"time"
"github.com/gomodule/redigo/redis"
"github.com/tidwall/gjson"
)
func subTestKeys(g *testGroup) {
g.regSubTest("BOUNDS", keys_BOUNDS_test)
g.regSubTest("DEL", keys_DEL_test)
g.regSubTest("DROP", keys_DROP_test)
g.regSubTest("RENAME", keys_RENAME_test)
g.regSubTest("RENAMENX", keys_RENAMENX_test)
g.regSubTest("EXPIRE", keys_EXPIRE_test)
g.regSubTest("FSET", keys_FSET_test)
g.regSubTest("GET", keys_GET_test)
g.regSubTest("KEYS", keys_KEYS_test)
g.regSubTest("PERSIST", keys_PERSIST_test)
g.regSubTest("SET", keys_SET_test)
g.regSubTest("STATS", keys_STATS_test)
g.regSubTest("TTL", keys_TTL_test)
g.regSubTest("SET EX", keys_SET_EX_test)
g.regSubTest("PDEL", keys_PDEL_test)
g.regSubTest("FIELDS", keys_FIELDS_test)
g.regSubTest("WHEREIN", keys_WHEREIN_test)
g.regSubTest("WHEREEVAL", keys_WHEREEVAL_test)
g.regSubTest("TYPE", keys_TYPE_test)
g.regSubTest("FLUSHDB", keys_FLUSHDB_test)
g.regSubTest("HEALTHZ", keys_HEALTHZ_test)
g.regSubTest("SERVER", keys_SERVER_test)
g.regSubTest("INFO", keys_INFO_test)
}
func keys_BOUNDS_test(mc *mockServer) error {
return mc.DoBatch(
Do("BOUNDS", "mykey").Str("<nil>"),
Do("BOUNDS", "mykey").JSON().Err("key not found"),
Do("SET", "mykey", "myid1", "POINT", 33, -115).OK(),
Do("BOUNDS", "mykey").Str("[[-115 33] [-115 33]]"),
Do("BOUNDS", "mykey").JSON().Str(`{"ok":true,"bounds":{"type":"Polygon","coordinates":[[[-115,33],[-115,33],[-115,33],[-115,33],[-115,33]]]}}`),
Do("SET", "mykey", "myid2", "POINT", 34, -112).OK(),
Do("BOUNDS", "mykey").Str("[[-115 33] [-112 34]]"),
Do("DEL", "mykey", "myid2").Str("1"),
Do("BOUNDS", "mykey").Str("[[-115 33] [-115 33]]"),
Do("SET", "mykey", "myid3", "OBJECT", `{"type":"Point","coordinates":[-130,38,10]}`).OK(),
Do("SET", "mykey", "myid4", "OBJECT", `{"type":"Point","coordinates":[-110,25,-8]}`).OK(),
Do("BOUNDS", "mykey").Str("[[-130 25] [-110 38]]"),
Do("BOUNDS", "mykey", "hello").Err("wrong number of arguments for 'bounds' command"),
Do("BOUNDS", "nada").Str("<nil>"),
Do("BOUNDS", "nada").JSON().Err("key not found"),
Do("BOUNDS", "").Str("<nil>"),
Do("BOUNDS", "mykey").JSON().Str(`{"ok":true,"bounds":{"type":"Polygon","coordinates":[[[-130,25],[-110,25],[-110,38],[-130,38],[-130,25]]]}}`),
)
}
func keys_DEL_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid", "POINT", 33, -115).OK(),
Do("GET", "mykey", "myid", "POINT").Str("[33 -115]"),
Do("DEL", "mykey", "myid2", "ERRON404").Err("id not found"),
Do("DEL", "mykey", "myid").Str("1"),
Do("DEL", "mykey", "myid").Str("0"),
Do("DEL", "mykey").Err("wrong number of arguments for 'del' command"),
Do("GET", "mykey", "myid").Str("<nil>"),
Do("DEL", "mykey", "myid", "ERRON404").Err("key not found"),
Do("DEL", "mykey", "myid", "invalid-arg").Err("invalid argument 'invalid-arg'"),
Do("SET", "mykey", "myid", "POINT", 33, -115).OK(),
Do("DEL", "mykey", "myid2", "ERRON404").JSON().Err("id not found"),
Do("DEL", "mykey", "myid").JSON().OK(),
Do("DEL", "mykey", "myid").JSON().OK(),
Do("DEL", "mykey", "myid", "ERRON404").JSON().Err("key not found"),
)
}
func keys_DROP_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid1", "HASH", "9my5xp7").OK(),
Do("SET", "mykey", "myid2", "HASH", "9my5xp8").OK(),
Do("SCAN", "mykey", "COUNT").Str("2"),
Do("DROP").Err("wrong number of arguments for 'drop' command"),
Do("DROP", "mykey", "arg3").Err("wrong number of arguments for 'drop' command"),
Do("DROP", "mykey").Str("1"),
Do("SCAN", "mykey", "COUNT").Str("0"),
Do("DROP", "mykey").Str("0"),
Do("SCAN", "mykey", "COUNT").Str("0"),
Do("SET", "mykey", "myid1", "HASH", "9my5xp7").OK(),
Do("DROP", "mykey").JSON().OK(),
Do("DROP", "mykey").JSON().OK(),
)
}
func keys_RENAME_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid1", "HASH", "9my5xp7").OK(),
Do("SET", "mykey", "myid2", "HASH", "9my5xp8").OK(),
Do("SCAN", "mykey", "COUNT").Str("2"),
Do("RENAME", "foo", "mynewkey", "arg3").Err("wrong number of arguments for 'rename' command"),
Do("RENAME", "mykey", "mynewkey").OK(),
Do("SCAN", "mykey", "COUNT").Str("0"),
Do("SCAN", "mynewkey", "COUNT").Str("2"),
Do("SET", "mykey", "myid3", "HASH", "9my5xp7").OK(),
Do("RENAME", "mykey", "mynewkey").OK(),
Do("SCAN", "mykey", "COUNT").Str("0"),
Do("SCAN", "mynewkey", "COUNT").Str("1"),
Do("RENAME", "foo", "mynewkey").Err("key not found"),
Do("SCAN", "mynewkey", "COUNT").Str("1"),
Do("SETCHAN", "mychan", "INTERSECTS", "mynewkey", "BOUNDS", 10, 10, 20, 20).Str("1"),
Do("RENAME", "mynewkey", "foo2").Err("key has hooks set"),
Do("RENAMENX", "mynewkey", "foo2").Err("key has hooks set"),
Do("SET", "mykey", "myid1", "HASH", "9my5xp7").OK(),
Do("RENAME", "mykey", "foo2").OK(),
Do("RENAMENX", "foo2", "foo3").Str("1"),
Do("RENAMENX", "foo2", "foo3").Err("key not found"),
Do("RENAME", "foo2", "foo3").JSON().Err("key not found"),
Do("SET", "mykey", "myid1", "HASH", "9my5xp7").OK(),
Do("RENAMENX", "mykey", "foo3").Str("0"),
Do("RENAME", "foo3", "foo4").JSON().OK(),
)
}
func keys_RENAMENX_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid1", "HASH", "9my5xp7").OK(),
Do("SET", "mykey", "myid2", "HASH", "9my5xp8").OK(),
Do("SCAN", "mykey", "COUNT").Str("2"),
Do("RENAMENX", "mykey", "mynewkey").Str("1"),
Do("SCAN", "mykey", "COUNT").Str("0"),
Do("DROP", "mykey").Str("0"),
Do("SCAN", "mykey", "COUNT").Str("0"),
Do("SCAN", "mynewkey", "COUNT").Str("2"),
Do("SET", "mykey", "myid3", "HASH", "9my5xp7").OK(),
Do("RENAMENX", "mykey", "mynewkey").Str("0"),
Do("SCAN", "mykey", "COUNT").Str("1"),
Do("SCAN", "mynewkey", "COUNT").Str("2"),
Do("RENAMENX", "foo", "mynewkey").Str("ERR key not found"),
Do("SCAN", "mynewkey", "COUNT").Str("2"),
)
}
func keys_EXPIRE_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid", "STRING", "value").OK(),
Do("EXPIRE", "mykey", "myid").Err("wrong number of arguments for 'expire' command"),
Do("EXPIRE", "mykey", "myid", "y").Err("invalid argument 'y'"),
Do("EXPIRE", "mykey", "myid", 1).Str("1"),
Do("EXPIRE", "mykey", "myid", 1).JSON().OK(),
Sleep(time.Second/4),
Do("GET", "mykey", "myid").Str("value"),
Sleep(time.Second),
Do("GET", "mykey", "myid").Str("<nil>"),
Do("EXPIRE", "mykey", "myid", 1).JSON().Err("key not found"),
Do("SET", "mykey", "myid1", "STRING", "value1").OK(),
Do("SET", "mykey", "myid2", "STRING", "value2").OK(),
Do("EXPIRE", "mykey", "myid1", 1).Str("1"),
Sleep(time.Second/4),
Do("GET", "mykey", "myid1").Str("value1"),
Sleep(time.Second),
Do("EXPIRE", "mykey", "myid1", 1).Str("0"),
Do("EXPIRE", "mykey", "myid1", 1).JSON().Err("id not found"),
)
}
func keys_FSET_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid", "HASH", "9my5xp7").OK(),
Do("GET", "mykey", "myid", "WITHFIELDS", "HASH", 7).Str("[9my5xp7]"),
Do("FSET", "mykey", "myid", "f1", 105.6).Str("1"),
Do("GET", "mykey", "myid", "WITHFIELDS", "HASH", 7).Str("[9my5xp7 [f1 105.6]]"),
Do("FSET", "mykey", "myid", "f1", 1.1, "f2", 2.2).Str("2"),
Do("GET", "mykey", "myid", "WITHFIELDS", "HASH", 7).Str("[9my5xp7 [f1 1.1 f2 2.2]]"),
Do("FSET", "mykey", "myid", "f1", 1.1, "f2", 22.22).Str("1"),
Do("GET", "mykey", "myid", "WITHFIELDS", "HASH", 7).Str("[9my5xp7 [f1 1.1 f2 22.22]]"),
Do("FSET", "mykey", "myid", "f1", 0).Str("1"),
Do("GET", "mykey", "myid", "WITHFIELDS", "HASH", 7).Str("[9my5xp7 [f2 22.22]]"),
Do("FSET", "mykey", "myid", "f2", 0).Str("1"),
Do("GET", "mykey", "myid", "WITHFIELDS", "HASH", 7).Str("[9my5xp7]"),
Do("FSET", "mykey", "myid2", "xx", "f1", 1.1, "f2", 2.2).Str("0"),
Do("GET", "mykey", "myid2").Str("<nil>"),
Do("DEL", "mykey", "myid").Str("1"),
Do("GET", "mykey", "myid").Str("<nil>"),
Do("SET", "mykey", "myid", "POINT", 1, 2).OK(),
Do("GET", "mykey", "myid", "WITHFIELDS").JSON().Str(`{"ok":true,"object":{"type":"Point","coordinates":[2,1]}}`),
Do("FSET", "mykey", "myid", "f2", 1).JSON().OK(),
Do("GET", "mykey", "myid", "WITHFIELDS").JSON().Str(`{"ok":true,"object":{"type":"Point","coordinates":[2,1]},"fields":{"f2":1}}`),
Do("SET", "mykey", "myid", "POINT", 3, 4).OK(),
Do("GET", "mykey", "myid", "WITHFIELDS").JSON().Str(`{"ok":true,"object":{"type":"Point","coordinates":[4,3]},"fields":{"f2":1}}`),
Do("SET", "mykey", "myid", "HASH", "9my5xp7").OK(),
Do("DEL", "mykey", "myid").Str("1"),
Do("GET", "mykey", "myid").Str("<nil>"),
Do("SET", "mykey", "myid", "HASH", "9my5xp7").OK(),
Do("CONFIG", "SET", "maxmemory", "1").OK(),
Do("FSET", "mykey", "myid", "xx", "f1", 1.1, "f2", 2.2).Err(`OOM command not allowed when used memory > 'maxmemory'`),
Do("CONFIG", "SET", "maxmemory", "0").OK(),
Do("FSET", "mykey", "myid", "xx").Err("wrong number of arguments for 'fset' command"),
Do("FSET", "mykey", "myid", "f1", "a", "f2").Err("wrong number of arguments for 'fset' command"),
Do("FSET", "mykey", "myid", "z", "a").Err("invalid argument 'z'"),
Do("FSET", "mykey2", "myid", "a", "b").Err("key not found"),
Do("FSET", "mykey", "myid2", "a", "b").Err("id not found"),
Do("FSET", "mykey", "myid", "f2", 0).JSON().OK(),
)
}
func keys_GET_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid", "STRING", "value").OK(),
Do("GET", "mykey", "myid").Str("value"),
Do("SET", "mykey", "myid", "STRING", "value2").OK(),
Do("GET", "mykey", "myid").Str("value2"),
Do("DEL", "mykey", "myid").Str("1"),
Do("GET", "mykey", "myid").Str("<nil>"),
Do("GET", "mykey").Err("wrong number of arguments for 'get' command"),
Do("GET", "mykey", "myid", "hash").Err("wrong number of arguments for 'get' command"),
Do("GET", "mykey", "myid", "hash", "0").Err("invalid argument '0'"),
Do("GET", "mykey", "myid", "hash", "-1").Err("invalid argument '-1'"),
Do("GET", "mykey", "myid", "hash", "13").Err("invalid argument '13'"),
Do("SET", "mykey", "myid", "field", "hello", "world", "field", "hiya", 55, "point", 33, -112).OK(),
Do("GET", "mykey", "myid", "hash", "1").Str("9"),
Do("GET", "mykey", "myid", "point").Str("[33 -112]"),
Do("GET", "mykey", "myid", "bounds").Str("[[33 -112] [33 -112]]"),
Do("GET", "mykey", "myid", "object").Str(`{"type":"Point","coordinates":[-112,33]}`),
Do("GET", "mykey", "myid", "object").Str(`{"type":"Point","coordinates":[-112,33]}`),
Do("GET", "mykey", "myid", "withfields", "point").Str(`[[33 -112] [hello world hiya 55]]`),
Do("GET", "mykey", "myid", "joint").Err("wrong number of arguments for 'get' command"),
Do("GET", "mykey2", "myid").Str("<nil>"),
Do("GET", "mykey2", "myid").JSON().Err("key not found"),
Do("GET", "mykey", "myid2").Str("<nil>"),
Do("GET", "mykey", "myid2").JSON().Err("id not found"),
Do("GET", "mykey", "myid", "point").JSON().Str(`{"ok":true,"point":{"lat":33,"lon":-112}}`),
Do("GET", "mykey", "myid", "object").JSON().Str(`{"ok":true,"object":{"type":"Point","coordinates":[-112,33]}}`),
Do("GET", "mykey", "myid", "hash", "1").JSON().Str(`{"ok":true,"hash":"9"}`),
Do("GET", "mykey", "myid", "bounds").JSON().Str(`{"ok":true,"bounds":{"sw":{"lat":33,"lon":-112},"ne":{"lat":33,"lon":-112}}}`),
Do("SET", "mykey", "myid2", "point", 33, -112, 55).OK(),
Do("GET", "mykey", "myid2", "point").Str("[33 -112 55]"),
Do("GET", "mykey", "myid2", "point").JSON().Str(`{"ok":true,"point":{"lat":33,"lon":-112,"z":55}}`),
Do("GET", "mykey", "myid", "withfields").JSON().Str(`{"ok":true,"object":{"type":"Point","coordinates":[-112,33]},"fields":{"hello":"world","hiya":55}}`),
)
}
func keys_KEYS_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey11", "myid4", "STRING", "value").OK(),
Do("SET", "mykey22", "myid2", "HASH", "9my5xp7").OK(),
Do("SET", "mykey22", "myid1", "OBJECT", `{"type":"Point","coordinates":[-130,38,10]}`).OK(),
Do("SET", "mykey11", "myid3", "OBJECT", `{"type":"Point","coordinates":[-110,25,-8]}`).OK(),
Do("SET", "mykey42", "myid2", "HASH", "9my5xp7").OK(),
Do("SET", "mykey31", "myid4", "STRING", "value").OK(),
Do("SET", "mykey310", "myid5", "STRING", "value").OK(),
Do("KEYS", "*").Str("[mykey11 mykey22 mykey31 mykey310 mykey42]"),
Do("KEYS", "*key*").Str("[mykey11 mykey22 mykey31 mykey310 mykey42]"),
Do("KEYS", "mykey*").Str("[mykey11 mykey22 mykey31 mykey310 mykey42]"),
Do("KEYS", "mykey4*").Str("[mykey42]"),
Do("KEYS", "mykey*1").Str("[mykey11 mykey31]"),
Do("KEYS", "mykey*1*").Str("[mykey11 mykey31 mykey310]"),
Do("KEYS", "mykey*10").Str("[mykey310]"),
Do("KEYS", "mykey*2").Str("[mykey22 mykey42]"),
Do("KEYS", "*2").Str("[mykey22 mykey42]"),
Do("KEYS", "*1*").Str("[mykey11 mykey31 mykey310]"),
Do("KEYS", "mykey").Str("[]"),
Do("KEYS", "mykey31").Str("[mykey31]"),
Do("KEYS", "mykey[^3]*").Str("[mykey11 mykey22 mykey42]"),
Do("KEYS").Err("wrong number of arguments for 'keys' command"),
Do("KEYS", "*").JSON().Str(`{"ok":true,"keys":["mykey11","mykey22","mykey31","mykey310","mykey42"]}`),
)
}
func keys_PERSIST_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid", "STRING", "value").OK(),
Do("EXPIRE", "mykey", "myid", 2).Str("1"),
Do("PERSIST", "mykey", "myid").Str("1"),
Do("PERSIST", "mykey", "myid").Str("0"),
Do("PERSIST", "mykey").Err("wrong number of arguments for 'persist' command"),
Do("PERSIST", "mykey2", "myid").Str("0"),
Do("PERSIST", "mykey2", "myid").JSON().Err("key not found"),
Do("PERSIST", "mykey", "myid2").Str("0"),
Do("PERSIST", "mykey", "myid2").JSON().Err("id not found"),
Do("EXPIRE", "mykey", "myid", 2).Str("1"),
Do("PERSIST", "mykey", "myid").JSON().OK(),
)
}
func keys_SET_test(mc *mockServer) error {
return mc.DoBatch(
// Section: point
Do("SET", "mykey", "myid", "POINT", 33, -115).OK(),
Do("GET", "mykey", "myid", "POINT").Str("[33 -115]"),
Do("GET", "mykey", "myid", "BOUNDS").Str("[[33 -115] [33 -115]]"),
Do("GET", "mykey", "myid", "OBJECT").Str(`{"type":"Point","coordinates":[-115,33]}`),
Do("GET", "mykey", "myid", "HASH", 7).Str("9my5xp7"),
Do("DEL", "mykey", "myid").Str("1"),
Do("GET", "mykey", "myid").Str("<nil>"),
Do("SET", "mykey", "myid", "point", "33", "-112", "99").OK(),
// Section: object
Do("SET", "mykey", "myid", "OBJECT", `{"type":"Point","coordinates":[-115,33]}`).OK(),
Do("GET", "mykey", "myid", "POINT").Str("[33 -115]"),
Do("GET", "mykey", "myid", "BOUNDS").Str("[[33 -115] [33 -115]]"),
Do("GET", "mykey", "myid", "OBJECT").Str(`{"type":"Point","coordinates":[-115,33]}`),
Do("GET", "mykey", "myid", "HASH", 7).Str("9my5xp7"),
Do("DEL", "mykey", "myid").Str("1"),
Do("GET", "mykey", "myid").Str("<nil>"),
// Section: bounds
Do("SET", "mykey", "myid", "BOUNDS", 33, -115, 33, -115).OK(),
Do("GET", "mykey", "myid", "POINT").Str("[33 -115]"),
Do("GET", "mykey", "myid", "BOUNDS").Str("[[33 -115] [33 -115]]"),
Do("GET", "mykey", "myid", "OBJECT").Str(`{"type":"Polygon","coordinates":[[[-115,33],[-115,33],[-115,33],[-115,33],[-115,33]]]}`),
Do("GET", "mykey", "myid", "HASH", 7).Str("9my5xp7"),
Do("DEL", "mykey", "myid").Str("1"),
Do("GET", "mykey", "myid").Str("<nil>"),
// Section: hash
Do("SET", "mykey", "myid", "HASH", "9my5xp7").OK(),
Do("GET", "mykey", "myid", "HASH", 7).Str("9my5xp7"),
Do("DEL", "mykey", "myid").Str("1"),
Do("GET", "mykey", "myid").Str("<nil>"),
Do("SET", "mykey", "myid", "HASH", "9my5xp7").JSON().OK(),
// Section: field
Do("SET", "mykey", "myid", "FIELD", "f1", 33, "FIELD", "a2", 44.5, "HASH", "9my5xp7").OK(),
Do("GET", "mykey", "myid", "WITHFIELDS", "HASH", 7).Str("[9my5xp7 [a2 44.5 f1 33]]"),
Do("FSET", "mykey", "myid", "f1", 0).Str("1"),
Do("FSET", "mykey", "myid", "f1", 0).Str("0"),
Do("GET", "mykey", "myid", "WITHFIELDS", "HASH", 7).Str("[9my5xp7 [a2 44.5]]"),
Do("DEL", "mykey", "myid").Str("1"),
Do("GET", "mykey", "myid").Str("<nil>"),
// Section: string
Do("SET", "mykey", "myid", "STRING", "value").OK(),
Do("GET", "mykey", "myid").Str("value"),
Do("SET", "mykey", "myid", "STRING", "value2").OK(),
Do("GET", "mykey", "myid").Str("value2"),
Do("DEL", "mykey", "myid").Str("1"),
Do("GET", "mykey", "myid").Str("<nil>"),
// Test error conditions
Do("CONFIG", "SET", "maxmemory", "1").OK(),
Do("SET", "mykey", "myid", "STRING", "value2").Err("OOM command not allowed when used memory > 'maxmemory'"),
Do("CONFIG", "SET", "maxmemory", "0").OK(),
Do("SET").Err("wrong number of arguments for 'set' command"),
Do("SET", "mykey", "myid", "FIELD", "f1").Err("wrong number of arguments for 'set' command"),
Do("SET", "mykey", "myid", "FIELD", "z", "1").Err("invalid argument 'z'"),
Do("SET", "mykey", "myid", "EX").Err("wrong number of arguments for 'set' command"),
Do("SET", "mykey", "myid", "EX", "yyy").Err("invalid argument 'yyy'"),
Do("SET", "mykey", "myid", "EX", "123").Err("wrong number of arguments for 'set' command"),
Do("SET", "mykey", "myid", "nx").Err("wrong number of arguments for 'set' command"),
Do("SET", "mykey", "myid", "nx", "xx").Err("invalid argument 'xx'"),
Do("SET", "mykey", "myid", "xx", "nx").Err("invalid argument 'nx'"),
Do("SET", "mykey", "myid", "string").Err("wrong number of arguments for 'set' command"),
Do("SET", "mykey", "myid", "point").Err("wrong number of arguments for 'set' command"),
Do("SET", "mykey", "myid", "point", "33").Err("wrong number of arguments for 'set' command"),
Do("SET", "mykey", "myid", "point", "33f", "-112").Err("invalid argument '33f'"),
Do("SET", "mykey", "myid", "point", "33", "-112f").Err("invalid argument '-112f'"),
Do("SET", "mykey", "myid", "point", "33", "-112f", "99").Err("invalid argument '-112f'"),
Do("SET", "mykey", "myid", "bounds").Err("wrong number of arguments for 'set' command"),
Do("SET", "mykey", "myid", "bounds", "fff", "1", "2", "3").Err("invalid argument 'fff'"),
Do("SET", "mykey", "myid", "hash").Err("wrong number of arguments for 'set' command"),
Do("SET", "mykey", "myid", "object").Err("wrong number of arguments for 'set' command"),
Do("SET", "mykey", "myid", "object", "asd").Err("invalid data"),
Do("SET", "mykey", "myid", "joint").Err("invalid argument 'joint'"),
Do("SET", "mykey", "myid", "XX", "HASH", "9my5xp7").Err("<nil>"),
Do("SET", "mykey", "myid", "XX", "HASH", "9my5xp7").JSON().Err("id not found"),
Do("SET", "mykey", "myid1", "HASH", "9my5xp7").OK(),
Do("SET", "mykey", "myid", "XX", "HASH", "9my5xp7").Err("<nil>"),
Do("SET", "mykey", "myid", "NX", "HASH", "9my5xp7").OK(),
Do("SET", "mykey", "myid", "XX", "HASH", "9my5xp7").OK(),
Do("SET", "mykey", "myid", "NX", "HASH", "9my5xp7").Err("<nil>"),
Do("SET", "mykey", "myid", "NX", "HASH", "9my5xp7").JSON().Err("id already exists"),
)
}
func keys_STATS_test(mc *mockServer) error {
return mc.DoBatch(
Do("STATS", "mykey").Str("[nil]"),
Do("SET", "mykey", "myid", "STRING", "value").OK(),
Do("STATS", "mykey").Str("[[in_memory_size 9 num_objects 1 num_points 0 num_strings 1]]"),
Do("STATS", "mykey", "hello").JSON().Str(`{"ok":true,"stats":[{"in_memory_size":9,"num_objects":1,"num_points":0,"num_strings":1},null]}`),
Do("SET", "mykey", "myid2", "STRING", "value").OK(),
Do("STATS", "mykey").Str("[[in_memory_size 19 num_objects 2 num_points 0 num_strings 2]]"),
Do("SET", "mykey", "myid3", "OBJECT", `{"type":"Point","coordinates":[-115,33]}`).OK(),
Do("STATS", "mykey").Str("[[in_memory_size 40 num_objects 3 num_points 1 num_strings 2]]"),
Do("DEL", "mykey", "myid").Str("1"),
Do("STATS", "mykey").Str("[[in_memory_size 31 num_objects 2 num_points 1 num_strings 1]]"),
Do("DEL", "mykey", "myid3").Str("1"),
Do("STATS", "mykey").Str("[[in_memory_size 10 num_objects 1 num_points 0 num_strings 1]]"),
Do("STATS", "mykey", "mykey2").Str("[[in_memory_size 10 num_objects 1 num_points 0 num_strings 1] nil]"),
Do("DEL", "mykey", "myid2").Str("1"),
Do("STATS", "mykey").Str("[nil]"),
Do("STATS", "mykey", "mykey2").Str("[nil nil]"),
Do("STATS", "mykey").Str("[nil]"),
Do("STATS").Err(`wrong number of arguments for 'stats' command`),
)
}
func keys_TTL_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid", "STRING", "value").OK(),
Do("EXPIRE", "mykey", "myid", 2).Str("1"),
Do("EXPIRE", "mykey", "myid", 2).JSON().OK(),
Sleep(time.Millisecond*10),
Do("TTL", "mykey", "myid").Str("1"),
Do("EXPIRE", "mykey", "myid", 1).Str("1"),
Sleep(time.Millisecond*10),
Do("TTL", "mykey", "myid").Str("0"),
Do("TTL", "mykey", "myid").JSON().Str(`{"ok":true,"ttl":0}`),
Do("TTL", "mykey2", "myid").Str("-2"),
Do("TTL", "mykey", "myid2").Str("-2"),
Do("TTL", "mykey").Err("wrong number of arguments for 'ttl' command"),
Do("SET", "mykey", "myid", "STRING", "value").OK(),
Do("TTL", "mykey", "myid").Str("-1"),
Do("TTL", "mykey2", "myid").JSON().Err("key not found"),
Do("TTL", "mykey", "myid2").JSON().Err("id not found"),
)
}
func keys_SET_EX_test(mc *mockServer) (err error) {
rand.Seed(time.Now().UnixNano())
// add a bunch of points
for i := 0; i < 20000; i++ {
val := fmt.Sprintf("val:%d", i)
var resp string
var lat, lon float64
lat = rand.Float64()*180 - 90
lon = rand.Float64()*360 - 180
resp, err = redis.String(mc.conn.Do("SET",
fmt.Sprintf("mykey%d", i%3), val,
"EX", 1+rand.Float64(),
"POINT", lat, lon))
if err != nil {
return
}
if resp != "OK" {
err = fmt.Errorf("expected 'OK', got '%s'", resp)
return
}
time.Sleep(time.Nanosecond)
}
time.Sleep(time.Second * 3)
mc.conn.Do("OUTPUT", "json")
json, _ := redis.String(mc.conn.Do("SERVER"))
if !gjson.Get(json, "ok").Bool() {
return errors.New("not ok")
}
if gjson.Get(json, "stats.num_objects").Int() > 0 {
return errors.New("items left in database")
}
mc.conn.Do("FLUSHDB")
return nil
}
func keys_FIELDS_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid1a", "FIELD", "a", 1, "POINT", 33, -115).OK(),
Do("GET", "mykey", "myid1a", "WITHFIELDS").Str(`[{"type":"Point","coordinates":[-115,33]} [a 1]]`),
Do("SET", "mykey", "myid1a", "FIELD", "a", "a", "POINT", 33, -115).OK(),
Do("GET", "mykey", "myid1a", "WITHFIELDS").Str(`[{"type":"Point","coordinates":[-115,33]} [a a]]`),
Do("SET", "mykey", "myid1a", "FIELD", "a", 1, "FIELD", "b", 2, "POINT", 33, -115).OK(),
Do("GET", "mykey", "myid1a", "WITHFIELDS").Str(`[{"type":"Point","coordinates":[-115,33]} [a 1 b 2]]`),
Do("SET", "mykey", "myid1a", "FIELD", "b", 2, "POINT", 33, -115).OK(),
Do("GET", "mykey", "myid1a", "WITHFIELDS").Str(`[{"type":"Point","coordinates":[-115,33]} [a 1 b 2]]`),
Do("SET", "mykey", "myid1a", "FIELD", "b", 2, "FIELD", "a", "1", "FIELD", "c", 3, "POINT", 33, -115).OK(),
Do("GET", "mykey", "myid1a", "WITHFIELDS").Str(`[{"type":"Point","coordinates":[-115,33]} [a 1 b 2 c 3]]`),
Do("GET", "fleet", "truck1", "WITHFIELDS").JSON().Err("key not found"),
Do("SET", "fleet", "truck1", "FIELD", "speed", "0", "POINT", "-112", "33").JSON().OK(),
Do("GET", "fleet", "truck1", "WITHFIELDS").JSON().Str(`{"ok":true,"object":{"type":"Point","coordinates":[33,-112]}}`),
Do("SET", "fleet", "truck1", "FIELD", "speed", "1", "POINT", "-112", "33").JSON().OK(),
Do("GET", "fleet", "truck1", "WITHFIELDS").JSON().Str(`{"ok":true,"object":{"type":"Point","coordinates":[33,-112]},"fields":{"speed":1}}`),
Do("SET", "fleet", "truck1", "FIELD", "speed", "0", "POINT", "-112", "33").JSON().OK(),
Do("GET", "fleet", "truck1", "WITHFIELDS").JSON().Str(`{"ok":true,"object":{"type":"Point","coordinates":[33,-112]}}`),
Do("SET", "fleet", "truck1", "FIELD", "speed", "2", "POINT", "-112", "33").JSON().OK(),
Do("GET", "fleet", "truck1", "WITHFIELDS").JSON().Str(`{"ok":true,"object":{"type":"Point","coordinates":[33,-112]},"fields":{"speed":2}}`),
// Do some GJSON queries.
Do("SET", "fleet", "truck2", "FIELD", "hello", `{"world":"tom"}`, "POINT", "-112", "33").JSON().OK(),
Do("SCAN", "fleet", "WHERE", "hello", `{"world":"tom"}`, `{"world":"tom"}`, "COUNT").JSON().Str(`{"ok":true,"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "hello.world == 'tom'", "COUNT").JSON().Str(`{"ok":true,"count":1,"cursor":0}`),
// The next scan does not match on anything, but since we're matching
// on zeros, which is the default, then all (two) objects are returned.
Do("SCAN", "fleet", "WHERE", "hello.world.1", `0`, `0`, "IDS").JSON().Str(`{"ok":true,"ids":["truck1","truck2"],"count":2,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "hello.world", ">", `tom`, "IDS").JSON().Str(`{"ok":true,"ids":[],"count":0,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "hello.world", ">=", `Tom`, "IDS").JSON().Str(`{"ok":true,"ids":["truck2"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "hello.world", ">=", `tom`, "IDS").JSON().Str(`{"ok":true,"ids":["truck2"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "hello.world", "==", `tom`, "IDS").JSON().Str(`{"ok":true,"ids":["truck2"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "hello.world", "<", `tom`, "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "hello.world", "<=", `tom`, "IDS").JSON().Str(`{"ok":true,"ids":["truck1","truck2"],"count":2,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "hello.world", "<", `uom`, "IDS").JSON().Str(`{"ok":true,"ids":["truck1","truck2"],"count":2,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "hello.world", "!=", `tom`, "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SET", "fleet", "truck1", "OBJECT", `{"type":"Feature","geometry":{"type":"Point","coordinates":[-112,33]},"properties":{"speed":50},"asdf":"Adsf"}`).JSON().OK(),
Do("SCAN", "fleet", "WHERE", "properties.speed", ">", 49, "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "properties.speed", ">", 50, "IDS").JSON().Str(`{"ok":true,"ids":[],"count":0,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "properties.speed", "<", 51, "IDS").JSON().Str(`{"ok":true,"ids":["truck1","truck2"],"count":2,"cursor":0}`),
Do("DROP", "fleet").JSON().OK(),
Do("SET", "fleet", "truck1", "FIELD", "speed", "50", "POINT", "-112", "33").JSON().OK(),
Do("SET", "fleet", "truck1", "FIELD", "Speed", "51", "POINT", "-112", "33").JSON().OK(),
Do("SET", "fleet", "truck1", "FIELD", "speeD", "52", "POINT", "-112", "33").JSON().OK(),
Do("SET", "fleet", "truck1", "FIELD", "SpeeD", "53", "POINT", "-112", "33").JSON().OK(),
Do("GET", "fleet", "truck1", "WITHFIELDS").JSON().Str(`{"ok":true,"object":{"type":"Point","coordinates":[33,-112]},"fields":{"SpeeD":53,"Speed":51,"speeD":52,"speed":50}}`),
Do("SCAN", "fleet", "WHERE", "speed == 50", "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "Speed == 50", "IDS").JSON().Str(`{"ok":true,"ids":[],"count":0,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "Speed == 51", "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "speed", 50, 50, "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "Speed", 51, 51, "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "Speed", 50, 50, "IDS").JSON().Str(`{"ok":true,"ids":[],"count":0,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "speed", 51, 51, "IDS").JSON().Str(`{"ok":true,"ids":[],"count":0,"cursor":0}`),
Do("DROP", "fleet").JSON().OK(),
Do("SET", "fleet", "truck1", "field", "props", `{"speed":50,"Speed":51}`, "point", "33", "-112").JSON().OK(),
Do("SET", "fleet", "truck1", "field", "Props", `{"speed":52,"Speed":53}`, "point", "33", "-112").JSON().OK(),
Do("GET", "fleet", "truck1", "WITHFIELDS").JSON().Str(`{"ok":true,"object":{"type":"Point","coordinates":[-112,33]},"fields":{"Props":{"speed":52,"Speed":53},"props":{"speed":50,"Speed":51}}}`),
Do("SCAN", "fleet", "WHERE", "props.speed == 50", "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "props.Speed == 51", "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "Props.speed == 52", "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "Props.Speed == 53", "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "props.Speed == 52", "IDS").JSON().Str(`{"ok":true,"ids":[],"count":0,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "props.speed == 51", "IDS").JSON().Str(`{"ok":true,"ids":[],"count":0,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "Props.speed == 53", "IDS").JSON().Str(`{"ok":true,"ids":[],"count":0,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "Props.Speed == 50", "IDS").JSON().Str(`{"ok":true,"ids":[],"count":0,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "props.speed > 49", "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "props.Speed > 49", "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "Props.speed > 49", "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "Props.Speed > 49", "IDS").JSON().Str(`{"ok":true,"ids":["truck1"],"count":1,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "props.Speed > 53", "IDS").JSON().Str(`{"ok":true,"ids":[],"count":0,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "props.speed > 53", "IDS").JSON().Str(`{"ok":true,"ids":[],"count":0,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "Props.speed > 53", "IDS").JSON().Str(`{"ok":true,"ids":[],"count":0,"cursor":0}`),
Do("SCAN", "fleet", "WHERE", "Props.Speed > 53", "IDS").JSON().Str(`{"ok":true,"ids":[],"count":0,"cursor":0}`),
)
}
func keys_PDEL_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid1a", "POINT", 33, -115).OK(),
Do("SET", "mykey", "myid1b", "POINT", 33, -115).OK(),
Do("SET", "mykey", "myid2a", "POINT", 33, -115).OK(),
Do("SET", "mykey", "myid2b", "POINT", 33, -115).OK(),
Do("SET", "mykey", "myid3a", "POINT", 33, -115).OK(),
Do("SET", "mykey", "myid3b", "POINT", 33, -115).OK(),
Do("SET", "mykey", "myid4a", "POINT", 33, -115).OK(),
Do("SET", "mykey", "myid4b", "POINT", 33, -115).OK(),
Do("PDEL", "mykey").Err("wrong number of arguments for 'pdel' command"),
Do("PDEL", "mykeyNA", "*").Str("0"),
Do("PDEL", "mykey", "myid1a").Str("1"),
Do("PDEL", "mykey", "myid1a").Str("0"),
Do("PDEL", "mykey", "myid1*").Str("1"),
Do("PDEL", "mykey", "myid2*").Str("2"),
Do("PDEL", "mykey", "*b").Str("2"),
Do("PDEL", "mykey", "*").Str("2"),
Do("PDEL", "mykey", "*").Str("0"),
Do("SET", "mykey", "myid1a", "POINT", 33, -115).OK(),
Do("SET", "mykey", "myid1b", "POINT", 33, -115).OK(),
Do("SET", "mykey", "myid2a", "POINT", 33, -115).OK(),
Do("SET", "mykey", "myid2b", "POINT", 33, -115).OK(),
Do("SET", "mykey", "myid3a", "POINT", 33, -115).OK(),
Do("PDEL", "mykey", "*").JSON().OK(),
)
}
func keys_WHEREIN_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid_a1", "FIELD", "a", 1, "POINT", 33, -115).OK(),
Do("WITHIN", "mykey", "WHEREIN", "a", 3, 0, 1, 2, "BOUNDS", 32.8, -115.2, 33.2, -114.8).Str(`[0 [[myid_a1 {"type":"Point","coordinates":[-115,33]} [a 1]]]]`),
Do("WITHIN", "mykey", "WHEREIN", "a", "a", 0, 1, 2, "BOUNDS", 32.8, -115.2, 33.2, -114.8).Err("invalid argument 'a'"),
Do("WITHIN", "mykey", "WHEREIN", "a", 1, 0, 1, 2, "BOUNDS", 32.8, -115.2, 33.2, -114.8).Err("invalid argument '1'"),
Do("WITHIN", "mykey", "WHEREIN", "a", 3, 0, "a", 2, "BOUNDS", 32.8, -115.2, 33.2, -114.8).Str("[0 []]"),
Do("WITHIN", "mykey", "WHEREIN", "a", 4, 0, "a", 1, 2, "BOUNDS", 32.8, -115.2, 33.2, -114.8).Str(`[0 [[myid_a1 {"type":"Point","coordinates":[-115,33]} [a 1]]]]`),
Do("SET", "mykey", "myid_a2", "FIELD", "a", 2, "POINT", 32.99, -115).OK(),
Do("SET", "mykey", "myid_a3", "FIELD", "a", 3, "POINT", 33, -115.02).OK(),
Do("WITHIN", "mykey", "WHEREIN", "a", 3, 0, 1, 2, "BOUNDS", 32.8, -115.2, 33.2, -114.8).Str(`[0 [[myid_a2 {"type":"Point","coordinates":[-115,32.99]} [a 2]] [myid_a1 {"type":"Point","coordinates":[-115,33]} [a 1]]]]`),
// zero value should not match 1 and 2
Do("SET", "mykey", "myid_a0", "FIELD", "a", 0, "POINT", 33, -115.02).OK(),
Do("WITHIN", "mykey", "WHEREIN", "a", 2, 1, 2, "BOUNDS", 32.8, -115.2, 33.2, -114.8).Str(`[0 [[myid_a2 {"type":"Point","coordinates":[-115,32.99]} [a 2]] [myid_a1 {"type":"Point","coordinates":[-115,33]} [a 1]]]]`),
)
}
func keys_WHEREEVAL_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid_a1", "FIELD", "a", 1, "POINT", 33, -115).OK(),
Do("WITHIN", "mykey", "WHEREEVAL", "return FIELDS.a > tonumber(ARGV[1])", 1, 0.5, "BOUNDS", 32.8, -115.2, 33.2, -114.8).Str(`[0 [[myid_a1 {"type":"Point","coordinates":[-115,33]} [a 1]]]]`),
Do("WITHIN", "mykey", "WHEREEVAL", "return FIELDS.a > tonumber(ARGV[1])", "a", 0.5, "BOUNDS", 32.8, -115.2, 33.2, -114.8).Err("invalid argument 'a'"),
Do("WITHIN", "mykey", "WHEREEVAL", "return FIELDS.a > tonumber(ARGV[1])", 1, 0.5, 4, "BOUNDS", 32.8, -115.2, 33.2, -114.8).Err("invalid argument '4'"),
Do("SET", "mykey", "myid_a2", "FIELD", "a", 2, "POINT", 32.99, -115).OK(),
Do("SET", "mykey", "myid_a3", "FIELD", "a", 3, "POINT", 33, -115.02).OK(),
Do("WITHIN", "mykey", "WHEREEVAL", "return FIELDS.a > tonumber(ARGV[1]) and FIELDS.a ~= tonumber(ARGV[2])", 2, 0.5, 3, "BOUNDS", 32.8, -115.2, 33.2, -114.8).Str(`[0 [[myid_a2 {"type":"Point","coordinates":[-115,32.99]} [a 2]] [myid_a1 {"type":"Point","coordinates":[-115,33]} [a 1]]]]`),
)
}
func keys_TYPE_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey", "myid1", "POINT", 33, -115).OK(),
Do("TYPE", "mykey").Str("hash"),
Do("TYPE", "mykey", "hello").Err("wrong number of arguments for 'type' command"),
Do("TYPE", "mykey2").Str("none"),
Do("TYPE", "mykey2").JSON().Err("key not found"),
Do("TYPE", "mykey").JSON().Str(`{"ok":true,"type":"hash"}`),
)
}
func keys_FLUSHDB_test(mc *mockServer) error {
return mc.DoBatch(
Do("SET", "mykey1", "myid1", "POINT", 33, -115).OK(),
Do("SET", "mykey2", "myid1", "POINT", 33, -115).OK(),
Do("SETCHAN", "mychan", "INTERSECTS", "mykey1", "BOUNDS", 10, 10, 10, 10).Str("1"),
Do("KEYS", "*").Str("[mykey1 mykey2]"),
Do("CHANS", "*").JSON().Func(func(s string) error {
if gjson.Get(s, "chans.#").Int() != 1 {
return fmt.Errorf("expected '%d', got '%d'", 1, gjson.Get(s, "chans.#").Int())
}
return nil
}),
Do("FLUSHDB", "arg2").Err("wrong number of arguments for 'flushdb' command"),
Do("FLUSHDB").OK(),
Do("KEYS", "*").Str("[]"),
Do("CHANS", "*").Str("[]"),
Do("SET", "mykey1", "myid1", "POINT", 33, -115).OK(),
Do("SET", "mykey2", "myid1", "POINT", 33, -115).OK(),
Do("SETCHAN", "mychan", "INTERSECTS", "mykey1", "BOUNDS", 10, 10, 10, 10).Str("1"),
Do("FLUSHDB").JSON().OK(),
)
}
func keys_HEALTHZ_test(mc *mockServer) error {
return mc.DoBatch(
Do("HEALTHZ").OK(),
Do("HEALTHZ").JSON().OK(),
Do("HEALTHZ", "arg").Err(`wrong number of arguments for 'healthz' command`),
)
}
func keys_SERVER_test(mc *mockServer) error {
return mc.DoBatch(
Do("SERVER").Func(func(s string) error {
valid := strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]") &&
strings.Contains(s, "cpus") && strings.Contains(s, "mem_alloc")
if !valid {
return errors.New("looks invalid")
}
return nil
}),
Do("SERVER").JSON().Func(func(s string) error {
if !gjson.Get(s, "ok").Bool() {
return errors.New("not ok")
}
valid := gjson.Get(s, "stats.cpus").Exists() &&
gjson.Get(s, "stats.mem_alloc").Exists()
if !valid {
return errors.New("looks invalid")
}
return nil
}),
Do("SERVER", "ext").Func(func(s string) error {
valid := strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]") &&
strings.Contains(s, "sys_cpus") &&
strings.Contains(s, "tile38_connected_clients")
if !valid {
return errors.New("looks invalid")
}
return nil
}),
Do("SERVER", "ext").JSON().Func(func(s string) error {
if !gjson.Get(s, "ok").Bool() {
return errors.New("not ok")
}
valid := gjson.Get(s, "stats.sys_cpus").Exists() &&
gjson.Get(s, "stats.tile38_connected_clients").Exists()
if !valid {
return errors.New("looks invalid")
}
return nil
}),
Do("SERVER", "ett").Err(`invalid argument 'ett'`),
Do("SERVER", "ett").JSON().Err(`invalid argument 'ett'`),
)
}
func keys_INFO_test(mc *mockServer) error {
return mc.DoBatch(
Do("INFO").Func(func(s string) error {
if !strings.Contains(s, "# Clients") ||
!strings.Contains(s, "# Stats") {
return errors.New("looks invalid")
}
return nil
}),
Do("INFO", "all").Func(func(s string) error {
if !strings.Contains(s, "# Clients") ||
!strings.Contains(s, "# Stats") {
return errors.New("looks invalid")
}
return nil
}),
Do("INFO", "default").Func(func(s string) error {
if !strings.Contains(s, "# Clients") ||
!strings.Contains(s, "# Stats") {
return errors.New("looks invalid")
}
return nil
}),
Do("INFO", "cpu").Func(func(s string) error {
if !strings.Contains(s, "# CPU") ||
strings.Contains(s, "# Clients") ||
strings.Contains(s, "# Stats") {
return errors.New("looks invalid")
}
return nil
}),
Do("INFO", "cpu", "clients").Func(func(s string) error {
if !strings.Contains(s, "# CPU") ||
!strings.Contains(s, "# Clients") ||
strings.Contains(s, "# Stats") {
return errors.New("looks invalid")
}
return nil
}),
Do("INFO").JSON().Func(func(s string) error {
if gjson.Get(s, "info.tile38_version").String() == "" {
return errors.New("looks invalid")
}
return nil
}),
)
}
|
package actions
import (
"github.com/barrydev/api-3h-shop/src/model"
)
func InsertProductItemByProductId(productId int64, body *model.BodyProductItem) (*model.ProductItem, error) {
body.ProductId = &productId
return InsertProductItem(body)
}
|
package easypost
// ShipmentOptions represents the various options that can be applied to a
// shipment at creation.
type ShipmentOptions struct {
AdditionalHandling bool `json:"additional_handling,omitempty"`
AddressValidationLevel string `json:"address_validation_level,omitempty"`
Alcohol bool `json:"alcohol,omitempty"`
BillingRef string `json:"billing_ref,omitempty"`
BillReceiverAccount string `json:"bill_receiver_account,omitempty"`
BillReceiverPostalCode string `json:"bill_receiver_postal_code,omitempty"`
BillThirdPartyAccount string `json:"bill_third_party_account,omitempty"`
BillThirdPartyCountry string `json:"bill_third_party_country,omitempty"`
BillThirdPartyPostalCode string `json:"bill_third_party_postal_code,omitempty"`
ByDrone bool `json:"by_drone,omitempty"`
CarbonNeutral bool `json:"carbon_neutral,omitempty"`
CertifiedMail bool `json:"certified_mail,omitempty"`
CODAmount string `json:"cod_amount,omitempty"`
CODMethod string `json:"cod_method,omitempty"`
CODAddressID string `json:"cod_address_id,omitempty"`
Currency string `json:"currency,omitempty"`
DeliveryConfirmation string `json:"delivery_confirmation,omitempty"`
DeliveryMaxDatetime *DateTime `json:"delivery_max_datetime,omitempty"`
DutyPayment *Payment `json:"duty_payment,omitempty"`
DutyPaymentAccount string `json:"duty_payment_account,omitempty"`
DropoffType string `json:"dropoff_type,omitempty"`
DryIce bool `json:"dry_ice,omitempty"`
DryIceMedical bool `json:"dry_ice_medical,omitempty,string"`
DryIceWeight float64 `json:"dry_ice_weight,omitempty,string"`
Endorsement string `json:"endorsement,omitempty"`
EndShipperID string `json:"end_shipper_id,omitempty"`
FreightCharge float64 `json:"freight_charge,omitempty"`
HandlingInstructions string `json:"handling_instructions,omitempty"`
Hazmat string `json:"hazmat,omitempty"`
HoldForPickup bool `json:"hold_for_pickup,omitempty"`
Incoterm string `json:"incoterm,omitempty"`
InvoiceNumber string `json:"invoice_number,omitempty"`
LabelDate *DateTime `json:"label_date,omitempty"`
LabelFormat string `json:"label_format,omitempty"`
LabelSize string `json:"label_size,omitempty"`
Machinable bool `json:"machinable,omitempty"`
Payment *Payment `json:"payment,omitempty"`
PickupMinDatetime *DateTime `json:"pickup_min_datetime,omitempty"`
PrintCustom1 string `json:"print_custom_1,omitempty"`
PrintCustom2 string `json:"print_custom_2,omitempty"`
PrintCustom3 string `json:"print_custom_3,omitempty"`
PrintCustom1BarCode bool `json:"print_custom_1_barcode,omitempty"`
PrintCustom2BarCode bool `json:"print_custom_2_barcode,omitempty"`
PrintCustom3BarCode bool `json:"print_custom_3_barcode,omitempty"`
PrintCustom1Code string `json:"print_custom_1_code,omitempty"`
PrintCustom2Code string `json:"print_custom_2_code,omitempty"`
PrintCustom3Code string `json:"print_custom_3_code,omitempty"`
RegisteredMail bool `json:"registered_mail,omitempty"`
RegisteredMailAmount float64 `json:"registered_mail_amount,omitempty"`
ReturnReceipt bool `json:"return_receipt,omitempty"`
SaturdayDelivery bool `json:"saturday_delivery,omitempty"`
SpecialRatesEligibility string `json:"special_rates_eligibility,omitempty"`
SmartpostHub string `json:"smartpost_hub,omitempty"`
SmartpostManifest string `json:"smartpost_manifest,omitempty"`
SuppressETD bool `json:"suppress_etd,omitempty"`
}
// Payment provides information on how a shipment is billed.
type Payment struct {
Type string `json:"type,omitempty"`
Account string `json:"account,omitempty"`
Country string `json:"country,omitempty"`
PostalCode string `json:"postal_code,omitempty"`
}
|
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"os"
"runtime"
"strconv"
"strings"
"unicode"
"unicode/utf8"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/runtime-tools/generate"
"github.com/opencontainers/runtime-tools/generate/seccomp"
"github.com/urfave/cli"
)
var generateFlags = []cli.Flag{
cli.StringSliceFlag{Name: "args", Usage: "command to run in the container"},
cli.StringFlag{Name: "domainname", Usage: "domainname value for the container"},
cli.StringSliceFlag{Name: "env", Usage: "add environment variable e.g. key=value"},
cli.StringSliceFlag{Name: "env-file", Usage: "read in a file of environment variables"},
cli.StringSliceFlag{Name: "hooks-poststart-add", Usage: "set command to run in poststart hooks"},
cli.BoolFlag{Name: "hooks-poststart-remove-all", Usage: "remove all poststart hooks"},
cli.StringSliceFlag{Name: "hooks-poststop-add", Usage: "set command to run in poststop hooks"},
cli.BoolFlag{Name: "hooks-poststop-remove-all", Usage: "remove all poststop hooks"},
cli.StringSliceFlag{Name: "hooks-prestart-add", Usage: "set command to run in prestart hooks"},
cli.BoolFlag{Name: "hooks-prestart-remove-all", Usage: "remove all prestart hooks"},
cli.StringFlag{Name: "hostname", Usage: "hostname value for the container"},
cli.StringSliceFlag{Name: "label", Usage: "add annotations to the configuration e.g. key=value"},
cli.StringFlag{Name: "linux-apparmor", Usage: "specifies the the apparmor profile for the container"},
cli.IntFlag{Name: "linux-blkio-leaf-weight", Usage: "Block IO (relative leaf weight), the range is from 10 to 1000"},
cli.StringSliceFlag{Name: "linux-blkio-leaf-weight-device", Usage: "Block IO (relative device leaf weight), e.g. major:minor:leaf-weight"},
cli.StringSliceFlag{Name: "linux-blkio-read-bps-device", Usage: "Limit read rate (bytes per second) from a device"},
cli.StringSliceFlag{Name: "linux-blkio-read-iops-device", Usage: "Limit read rate (IO per second) from a device"},
cli.IntFlag{Name: "linux-blkio-weight", Usage: "Block IO (relative weight), the range is from 10 to 1000"},
cli.StringSliceFlag{Name: "linux-blkio-weight-device", Usage: "Block IO (relative device weight), e.g. major:minor:weight"},
cli.StringSliceFlag{Name: "linux-blkio-write-bps-device", Usage: "Limit write rate (bytes per second) to a device"},
cli.StringSliceFlag{Name: "linux-blkio-write-iops-device", Usage: "Limit write rate (IO per second) to a device"},
cli.StringFlag{Name: "linux-cgroups-path", Usage: "specify the path to the cgroups"},
cli.Uint64Flag{Name: "linux-cpu-period", Usage: "the CPU period to be used for hardcapping (in usecs)"},
cli.Uint64Flag{Name: "linux-cpu-quota", Usage: "the allowed CPU time in a given period (in usecs)"},
cli.StringFlag{Name: "linux-cpus", Usage: "CPUs to use within the cpuset (default is to use any CPU available)"},
cli.Uint64Flag{Name: "linux-cpu-shares", Usage: "the relative share of CPU time available to the tasks in a cgroup"},
cli.StringSliceFlag{Name: "linux-device-add", Usage: "add a device which must be made available in the container"},
cli.StringSliceFlag{Name: "linux-device-remove", Usage: "remove a device which must be made available in the container"},
cli.BoolFlag{Name: "linux-device-remove-all", Usage: "remove all devices which must be made available in the container"},
cli.StringSliceFlag{Name: "linux-device-cgroup-add", Usage: "add a device access rule"},
cli.StringSliceFlag{Name: "linux-device-cgroup-remove", Usage: "remove a device access rule"},
cli.BoolFlag{Name: "linux-disable-oom-kill", Usage: "disable OOM Killer"},
cli.StringSliceFlag{Name: "linux-gidmappings", Usage: "add GIDMappings e.g HostID:ContainerID:Size"},
cli.StringSliceFlag{Name: "linux-hugepage-limits-add", Usage: "add hugepage resource limits"},
cli.StringSliceFlag{Name: "linux-hugepage-limits-drop", Usage: "drop hugepage resource limits"},
cli.StringFlag{Name: "linux-intelRdt-closid", Usage: "RDT Class of Service, i.e. group under the resctrl pseudo-filesystem which to associate the container with"},
cli.StringFlag{Name: "linux-intelRdt-l3CacheSchema", Usage: "specifies the schema for L3 cache id and capacity bitmask"},
cli.StringSliceFlag{Name: "linux-masked-paths", Usage: "specifies paths can not be read inside container"},
cli.Uint64Flag{Name: "linux-mem-kernel-limit", Usage: "kernel memory limit (in bytes)"},
cli.Uint64Flag{Name: "linux-mem-kernel-tcp", Usage: "kernel memory limit for tcp (in bytes)"},
cli.Uint64Flag{Name: "linux-mem-limit", Usage: "memory limit (in bytes)"},
cli.Uint64Flag{Name: "linux-mem-reservation", Usage: "memory reservation or soft limit (in bytes)"},
cli.StringFlag{Name: "linux-mems", Usage: "list of memory nodes in the cpuset (default is to use any available memory node)"},
cli.Uint64Flag{Name: "linux-mem-swap", Usage: "total memory limit (memory + swap) (in bytes)"},
cli.Uint64Flag{Name: "linux-mem-swappiness", Usage: "how aggressive the kernel will swap memory pages (Range from 0 to 100)"},
cli.StringFlag{Name: "linux-mount-label", Usage: "selinux mount context label"},
cli.StringSliceFlag{Name: "linux-namespace-add", Usage: "adds a namespace to the set of namespaces to create or join of the form 'ns[:path]'"},
cli.StringSliceFlag{Name: "linux-namespace-remove", Usage: "removes a namespace from the set of namespaces to create or join of the form 'ns'"},
cli.BoolFlag{Name: "linux-namespace-remove-all", Usage: "removes all namespaces from the set of namespaces created or joined"},
cli.IntFlag{Name: "linux-network-classid", Usage: "specifies class identifier tagged by container's network packets"},
cli.StringSliceFlag{Name: "linux-network-priorities", Usage: "specifies priorities of network traffic"},
cli.IntFlag{Name: "linux-oom-score-adj", Usage: "oom_score_adj for the container"},
cli.Int64Flag{Name: "linux-pids-limit", Usage: "maximum number of PIDs"},
cli.StringSliceFlag{Name: "linux-readonly-paths", Usage: "specifies paths readonly inside container"},
cli.Int64Flag{Name: "linux-realtime-period", Usage: "CPU period to be used for realtime scheduling (in usecs)"},
cli.Int64Flag{Name: "linux-realtime-runtime", Usage: "the time realtime scheduling may use (in usecs)"},
cli.StringFlag{Name: "linux-rootfs-propagation", Usage: "mount propagation for rootfs"},
cli.StringFlag{Name: "linux-seccomp-allow", Usage: "specifies syscalls to respond with allow"},
cli.StringFlag{Name: "linux-seccomp-arch", Usage: "specifies additional architectures permitted to be used for system calls"},
cli.StringFlag{Name: "linux-seccomp-default", Usage: "specifies default action to be used for system calls and removes existing rules with specified action"},
cli.StringFlag{Name: "linux-seccomp-default-force", Usage: "same as seccomp-default but does not remove existing rules with specified action"},
cli.StringFlag{Name: "linux-seccomp-errno", Usage: "specifies syscalls to respond with errno"},
cli.StringFlag{Name: "linux-seccomp-kill", Usage: "specifies syscalls to respond with kill"},
cli.BoolFlag{Name: "linux-seccomp-only", Usage: "specifies to export just a seccomp configuration file"},
cli.StringFlag{Name: "linux-seccomp-remove", Usage: "specifies syscalls to remove seccomp rules for"},
cli.BoolFlag{Name: "linux-seccomp-remove-all", Usage: "removes all syscall rules from seccomp configuration"},
cli.StringFlag{Name: "linux-seccomp-trace", Usage: "specifies syscalls to respond with trace"},
cli.StringFlag{Name: "linux-seccomp-trap", Usage: "specifies syscalls to respond with trap"},
cli.StringFlag{Name: "linux-selinux-label", Usage: "process selinux label"},
cli.StringSliceFlag{Name: "linux-sysctl", Usage: "add sysctl settings e.g net.ipv4.forward=1"},
cli.StringSliceFlag{Name: "linux-uidmappings", Usage: "add UIDMappings e.g HostID:ContainerID:Size"},
cli.StringSliceFlag{Name: "mounts-add", Usage: "configures additional mounts inside container"},
cli.StringSliceFlag{Name: "mounts-remove", Usage: "remove destination mountpoints from inside container"},
cli.BoolFlag{Name: "mounts-remove-all", Usage: "remove all mounts inside container"},
cli.StringFlag{Name: "oci-version", Usage: "specify the version of the Open Container Initiative runtime specification"},
cli.StringFlag{Name: "os", Value: runtime.GOOS, Usage: "operating system the container is created for"},
cli.StringFlag{Name: "output", Usage: "output file (defaults to stdout)"},
cli.BoolFlag{Name: "privileged", Usage: "enable privileged container settings"},
cli.StringFlag{Name: "process-cap-add", Usage: "add Linux capabilities to all 5 capability sets"},
cli.StringFlag{Name: "process-cap-add-ambient", Usage: "add Linux ambient capabilities"},
cli.StringFlag{Name: "process-cap-add-bounding", Usage: "add Linux bounding capabilities"},
cli.StringFlag{Name: "process-cap-add-effective", Usage: "add Linux effective capabilities"},
cli.StringFlag{Name: "process-cap-add-inheritable", Usage: "add Linux inheritable capabilities"},
cli.StringFlag{Name: "process-cap-add-permitted", Usage: "add Linux permitted capabilities"},
cli.StringFlag{Name: "process-cap-drop", Usage: "drop Linux capabilities to all 5 capability sets"},
cli.BoolFlag{Name: "process-cap-drop-all", Usage: "drop all Linux capabilities"},
cli.StringFlag{Name: "process-cap-drop-ambient", Usage: "drop Linux ambient capabilities"},
cli.StringFlag{Name: "process-cap-drop-bounding", Usage: "drop Linux bounding capabilities"},
cli.StringFlag{Name: "process-cap-drop-effective", Usage: "drop Linux effective capabilities"},
cli.StringFlag{Name: "process-cap-drop-inheritable", Usage: "drop Linux inheritable capabilities"},
cli.StringFlag{Name: "process-cap-drop-permitted", Usage: "drop Linux permitted capabilities"},
cli.StringFlag{Name: "process-consolesize", Usage: "specifies the console size in characters (width:height)"},
cli.StringFlag{Name: "process-cwd", Value: "/", Usage: "current working directory for the process"},
cli.IntFlag{Name: "process-gid", Usage: "gid for the process"},
cli.StringSliceFlag{Name: "process-groups", Usage: "supplementary groups for the process"},
cli.BoolFlag{Name: "process-no-new-privileges", Usage: "set no new privileges bit for the container process"},
cli.StringSliceFlag{Name: "process-rlimits-add", Usage: "specifies resource limits for processes inside the container. "},
cli.StringSliceFlag{Name: "process-rlimits-remove", Usage: "remove specified resource limits for processes inside the container. "},
cli.BoolFlag{Name: "process-rlimits-remove-all", Usage: "remove all resource limits for processes inside the container. "},
cli.BoolFlag{Name: "process-terminal", Usage: "specifies whether a terminal is attached to the process"},
cli.IntFlag{Name: "process-uid", Usage: "uid for the process"},
cli.StringFlag{Name: "process-umask", Usage: "umask for the process"},
cli.StringFlag{Name: "process-username", Usage: "username for the process"},
cli.StringFlag{Name: "rootfs-path", Value: "rootfs", Usage: "path to the root filesystem"},
cli.BoolFlag{Name: "rootfs-readonly", Usage: "make the container's rootfs readonly"},
cli.StringSliceFlag{Name: "solaris-anet", Usage: "set up networking for Solaris application containers"},
cli.StringFlag{Name: "solaris-capped-cpu-ncpus", Usage: "Specifies the percentage of CPU usage"},
cli.StringFlag{Name: "solaris-capped-memory-physical", Usage: "Specifies the physical caps on the memory"},
cli.StringFlag{Name: "solaris-capped-memory-swap", Usage: "Specifies the swap caps on the memory"},
cli.StringFlag{Name: "solaris-limitpriv", Usage: "privilege limit"},
cli.StringFlag{Name: "solaris-max-shm-memory", Usage: "Specifies the maximum amount of shared memory"},
cli.StringFlag{Name: "solaris-milestone", Usage: "Specifies the SMF FMRI"},
cli.StringFlag{Name: "template", Usage: "base template to use for creating the configuration"},
cli.StringSliceFlag{Name: "vm-hypervisor-parameters", Usage: "specifies an array of parameters to pass to the hypervisor"},
cli.StringFlag{Name: "vm-hypervisor-path", Usage: "specifies the path to the hypervisor binary that manages the container virtual machine"},
cli.StringFlag{Name: "vm-image-format", Usage: "set the format of the container virtual machine root image"},
cli.StringFlag{Name: "vm-image-path", Usage: "set path to the container virtual machine root image"},
cli.StringFlag{Name: "vm-kernel-initrd", Usage: "set path to an initial ramdisk to be used by the container virtual machine"},
cli.StringSliceFlag{Name: "vm-kernel-parameters", Usage: "specifies an array of parameters to pass to the kernel"},
cli.StringFlag{Name: "vm-kernel-path", Usage: "set path to the kernel used to boot the container virtual machine"},
cli.StringSliceFlag{Name: "windows-devices", Usage: "specifies a list of devices to be mapped into the container"},
cli.StringFlag{Name: "windows-hyperv-utilityVMPath", Usage: "specifies the path to the image used for the utility VM"},
cli.BoolFlag{Name: "windows-ignore-flushes-during-boot", Usage: "ignore flushes during boot"},
cli.StringSliceFlag{Name: "windows-layer-folders", Usage: "specifies a list of layer folders the container image relies on"},
cli.StringFlag{Name: "windows-network", Usage: "specifies network for container"},
cli.BoolFlag{Name: "windows-network-allowunqualifieddnsquery", Usage: "specifies networking unqualified DNS query is allowed"},
cli.StringFlag{Name: "windows-network-networkNamespace", Usage: "specifies network namespace for container"},
cli.StringFlag{Name: "windows-resources-cpu", Usage: "specifies CPU for container"},
cli.Uint64Flag{Name: "windows-resources-memory-limit", Usage: "specifies limit of memory"},
cli.StringFlag{Name: "windows-resources-storage", Usage: "specifies storage for container"},
cli.BoolFlag{Name: "windows-servicing", Usage: "servicing operations"},
}
var generateCommand = cli.Command{
Name: "generate",
Usage: "generate an OCI spec file",
Flags: generateFlags,
Before: before,
Action: func(context *cli.Context) error {
// Start from the default template.
specgen, err := generate.New(context.String("os"))
if err != nil {
return err
}
var template string
if context.IsSet("template") {
template = context.String("template")
}
if template != "" {
specgen, err = generate.NewFromFile(template)
if err != nil {
return err
}
}
err = setupSpec(&specgen, context)
if err != nil {
return err
}
var exportOpts generate.ExportOptions
exportOpts.Seccomp = context.Bool("linux-seccomp-only")
if context.IsSet("output") {
err = specgen.SaveToFile(context.String("output"), exportOpts)
} else {
err = specgen.Save(os.Stdout, exportOpts)
}
if err != nil {
return err
}
return nil
},
}
func setupSpec(g *generate.Generator, context *cli.Context) error {
if context.GlobalBool("host-specific") {
g.HostSpecific = true
}
if len(g.Config.Version) == 0 {
g.SetVersion(rspec.Version)
}
if context.IsSet("hostname") {
g.SetHostname(context.String("hostname"))
}
if context.IsSet("domainname") {
g.SetDomainName(context.String("domainname"))
}
if context.IsSet("oci-version") {
g.SetOCIVersion(context.String("oci-version"))
}
if context.IsSet("label") {
annotations := context.StringSlice("label")
for _, s := range annotations {
pair := strings.SplitN(s, "=", 2)
if len(pair) != 2 || pair[0] == "" {
return fmt.Errorf("incorrectly specified annotation: %s", s)
}
g.AddAnnotation(pair[0], pair[1])
}
}
g.SetRootPath(context.String("rootfs-path"))
if context.IsSet("rootfs-readonly") {
g.SetRootReadonly(context.Bool("rootfs-readonly"))
}
if context.IsSet("process-uid") {
g.SetProcessUID(uint32(context.Int("process-uid")))
}
if context.IsSet("process-username") {
g.SetProcessUsername(context.String("process-username"))
}
if context.IsSet("process-umask") {
g.SetProcessUmask(uint32(context.Int("process-umask")))
}
if context.IsSet("process-gid") {
g.SetProcessGID(uint32(context.Int("process-gid")))
}
if context.IsSet("linux-selinux-label") {
g.SetProcessSelinuxLabel(context.String("linux-selinux-label"))
}
g.SetProcessCwd(context.String("process-cwd"))
if context.IsSet("linux-apparmor") {
g.SetProcessApparmorProfile(context.String("linux-apparmor"))
}
if context.IsSet("process-no-new-privileges") {
g.SetProcessNoNewPrivileges(context.Bool("process-no-new-privileges"))
}
if context.IsSet("process-terminal") {
g.SetProcessTerminal(context.Bool("process-terminal"))
}
if context.IsSet("args") {
g.SetProcessArgs(context.StringSlice("args"))
}
{
envs, err := readKVStrings(context.StringSlice("env-file"), context.StringSlice("env"))
if err != nil {
return err
}
for _, env := range envs {
name, value, err := parseEnv(env)
if err != nil {
return err
}
g.AddProcessEnv(name, value)
}
}
if context.IsSet("process-groups") {
groups := context.StringSlice("process-groups")
for _, group := range groups {
groupID, err := strconv.Atoi(group)
if err != nil {
return err
}
g.AddProcessAdditionalGid(uint32(groupID))
}
}
if context.IsSet("linux-cgroups-path") {
g.SetLinuxCgroupsPath(context.String("linux-cgroups-path"))
}
if context.IsSet("linux-masked-paths") {
paths := context.StringSlice("linux-masked-paths")
for _, path := range paths {
g.AddLinuxMaskedPaths(path)
}
}
if context.IsSet("linux-device-cgroup-add") {
devices := context.StringSlice("linux-device-cgroup-add")
for _, device := range devices {
dev, err := parseLinuxResourcesDeviceAccess(device, g)
if err != nil {
return err
}
g.AddLinuxResourcesDevice(dev.Allow, dev.Type, dev.Major, dev.Minor, dev.Access)
}
}
if context.IsSet("linux-device-cgroup-remove") {
devices := context.StringSlice("linux-device-cgroup-remove")
for _, device := range devices {
dev, err := parseLinuxResourcesDeviceAccess(device, g)
if err != nil {
return err
}
g.RemoveLinuxResourcesDevice(dev.Allow, dev.Type, dev.Major, dev.Minor, dev.Access)
}
}
if context.IsSet("linux-readonly-paths") {
paths := context.StringSlice("linux-readonly-paths")
for _, path := range paths {
g.AddLinuxReadonlyPaths(path)
}
}
if context.IsSet("linux-mount-label") {
g.SetLinuxMountLabel(context.String("linux-mount-label"))
}
if context.IsSet("linux-sysctl") {
sysctls := context.StringSlice("linux-sysctl")
for _, s := range sysctls {
pair := strings.Split(s, "=")
if len(pair) != 2 {
return fmt.Errorf("incorrectly specified sysctl: %s", s)
}
g.AddLinuxSysctl(pair[0], pair[1])
}
}
g.SetupPrivileged(context.Bool("privileged"))
if context.Bool("process-cap-drop-all") {
g.ClearProcessCapabilities()
}
if context.IsSet("process-cap-add") {
addCaps := context.String("process-cap-add")
parts := strings.Split(addCaps, ",")
for _, part := range parts {
if err := g.AddProcessCapability(part); err != nil {
return err
}
}
}
if context.IsSet("process-cap-add-ambient") {
addCaps := context.String("process-cap-add-ambient")
parts := strings.Split(addCaps, ",")
for _, part := range parts {
if err := g.AddProcessCapabilityAmbient(part); err != nil {
return err
}
}
}
if context.IsSet("process-cap-add-bounding") {
addCaps := context.String("process-cap-add-bounding")
parts := strings.Split(addCaps, ",")
for _, part := range parts {
if err := g.AddProcessCapabilityBounding(part); err != nil {
return err
}
}
}
if context.IsSet("process-cap-add-effective") {
addCaps := context.String("process-cap-add-effective")
parts := strings.Split(addCaps, ",")
for _, part := range parts {
if err := g.AddProcessCapabilityEffective(part); err != nil {
return err
}
}
}
if context.IsSet("process-cap-add-inheritable") {
addCaps := context.String("process-cap-add-inheritable")
parts := strings.Split(addCaps, ",")
for _, part := range parts {
if err := g.AddProcessCapabilityInheritable(part); err != nil {
return err
}
}
}
if context.IsSet("process-cap-add-permitted") {
addCaps := context.String("process-cap-add-permitted")
parts := strings.Split(addCaps, ",")
for _, part := range parts {
if err := g.AddProcessCapabilityPermitted(part); err != nil {
return err
}
}
}
if context.IsSet("process-cap-drop") {
addCaps := context.String("process-cap-drop")
parts := strings.Split(addCaps, ",")
for _, part := range parts {
if err := g.DropProcessCapability(part); err != nil {
return err
}
}
}
if context.IsSet("process-cap-drop-ambient") {
dropCaps := context.String("process-cap-drop-ambient")
parts := strings.Split(dropCaps, ",")
for _, part := range parts {
if err := g.DropProcessCapabilityAmbient(part); err != nil {
return err
}
}
}
if context.IsSet("process-cap-drop-bounding") {
dropCaps := context.String("process-cap-drop-bounding")
parts := strings.Split(dropCaps, ",")
for _, part := range parts {
if err := g.DropProcessCapabilityBounding(part); err != nil {
return err
}
}
}
if context.IsSet("process-cap-drop-effective") {
dropCaps := context.String("process-cap-drop-effective")
parts := strings.Split(dropCaps, ",")
for _, part := range parts {
if err := g.DropProcessCapabilityEffective(part); err != nil {
return err
}
}
}
if context.IsSet("process-cap-drop-inheritable") {
dropCaps := context.String("process-cap-drop-inheritable")
parts := strings.Split(dropCaps, ",")
for _, part := range parts {
if err := g.DropProcessCapabilityInheritable(part); err != nil {
return err
}
}
}
if context.IsSet("process-cap-drop-permitted") {
dropCaps := context.String("process-cap-drop-permitted")
parts := strings.Split(dropCaps, ",")
for _, part := range parts {
if err := g.DropProcessCapabilityPermitted(part); err != nil {
return err
}
}
}
if context.IsSet("process-consolesize") {
consoleSize := context.String("process-consolesize")
width, height, err := parseConsoleSize(consoleSize)
if err != nil {
return err
}
g.SetProcessConsoleSize(width, height)
}
var uidMaps, gidMaps []string
if context.IsSet("linux-uidmappings") {
uidMaps = context.StringSlice("linux-uidmappings")
}
if context.IsSet("linux-gidmappings") {
gidMaps = context.StringSlice("linux-gidmappings")
}
// Add default user namespace.
if len(uidMaps) > 0 || len(gidMaps) > 0 {
g.AddOrReplaceLinuxNamespace("user", "")
}
if context.IsSet("mounts-remove-all") {
g.ClearMounts()
}
if context.IsSet("mounts-remove") {
mounts := context.StringSlice("mounts-remove")
for _, mount := range mounts {
g.RemoveMount(mount)
}
}
if context.IsSet("mounts-add") {
mounts := context.StringSlice("mounts-add")
for _, mount := range mounts {
mnt := rspec.Mount{}
if err := json.Unmarshal([]byte(mount), &mnt); err != nil {
return err
}
g.AddMount(mnt)
}
}
if context.IsSet("hooks-poststart-remove-all") {
g.ClearPostStartHooks()
}
if context.IsSet("hooks-poststart-add") {
postStartHooks := context.StringSlice("hooks-poststart-add")
for _, hook := range postStartHooks {
tmpHook := rspec.Hook{}
if err := json.Unmarshal([]byte(hook), &tmpHook); err != nil {
return err
}
g.AddPostStartHook(tmpHook)
}
}
if context.IsSet("hooks-poststop-remove-all") {
g.ClearPostStopHooks()
}
if context.IsSet("hooks-poststop-add") {
postStopHooks := context.StringSlice("hooks-poststop-add")
for _, hook := range postStopHooks {
tmpHook := rspec.Hook{}
if err := json.Unmarshal([]byte(hook), &tmpHook); err != nil {
return err
}
g.AddPostStopHook(tmpHook)
}
}
if context.IsSet("hooks-prestart-remove-all") {
g.ClearPreStartHooks()
}
if context.IsSet("hooks-prestart-add") {
preStartHooks := context.StringSlice("hooks-prestart-add")
for _, hook := range preStartHooks {
tmpHook := rspec.Hook{}
if err := json.Unmarshal([]byte(hook), &tmpHook); err != nil {
return err
}
g.AddPreStartHook(tmpHook)
}
}
if context.IsSet("linux-rootfs-propagation") {
rp := context.String("linux-rootfs-propagation")
if err := g.SetLinuxRootPropagation(rp); err != nil {
return err
}
}
for _, uidMap := range uidMaps {
hid, cid, size, err := parseIDMapping(uidMap)
if err != nil {
return err
}
g.AddLinuxUIDMapping(hid, cid, size)
}
for _, gidMap := range gidMaps {
hid, cid, size, err := parseIDMapping(gidMap)
if err != nil {
return err
}
g.AddLinuxGIDMapping(hid, cid, size)
}
if context.IsSet("linux-disable-oom-kill") {
g.SetLinuxResourcesMemoryDisableOOMKiller(context.Bool("linux-disable-oom-kill"))
}
if context.IsSet("linux-oom-score-adj") {
g.SetProcessOOMScoreAdj(context.Int("linux-oom-score-adj"))
}
if context.IsSet("linux-blkio-leaf-weight") {
g.SetLinuxResourcesBlockIOLeafWeight(uint16(context.Uint64("linux-blkio-leaf-weight")))
}
if context.IsSet("linux-blkio-leaf-weight-device") {
devLeafWeight := context.StringSlice("linux-blkio-leaf-weight-device")
for _, v := range devLeafWeight {
major, minor, leafWeight, err := parseDeviceWeight(v)
if err != nil {
return err
}
if leafWeight == -1 {
g.DropLinuxResourcesBlockIOLeafWeightDevice(major, minor)
} else {
g.AddLinuxResourcesBlockIOLeafWeightDevice(major, minor, uint16(leafWeight))
}
}
}
if context.IsSet("linux-blkio-read-bps-device") {
throttleDevices := context.StringSlice("linux-blkio-read-bps-device")
for _, v := range throttleDevices {
major, minor, rate, err := parseThrottleDevice(v)
if err != nil {
return err
}
if rate == -1 {
g.DropLinuxResourcesBlockIOThrottleReadBpsDevice(major, minor)
} else {
g.AddLinuxResourcesBlockIOThrottleReadBpsDevice(major, minor, uint64(rate))
}
}
}
if context.IsSet("linux-blkio-read-iops-device") {
throttleDevices := context.StringSlice("linux-blkio-read-iops-device")
for _, v := range throttleDevices {
major, minor, rate, err := parseThrottleDevice(v)
if err != nil {
return err
}
if rate == -1 {
g.DropLinuxResourcesBlockIOThrottleReadIOPSDevice(major, minor)
} else {
g.AddLinuxResourcesBlockIOThrottleReadIOPSDevice(major, minor, uint64(rate))
}
}
}
if context.IsSet("linux-blkio-weight") {
g.SetLinuxResourcesBlockIOWeight(uint16(context.Uint64("linux-blkio-weight")))
}
if context.IsSet("linux-blkio-weight-device") {
devWeight := context.StringSlice("linux-blkio-weight-device")
for _, v := range devWeight {
major, minor, weight, err := parseDeviceWeight(v)
if err != nil {
return err
}
if weight == -1 {
g.DropLinuxResourcesBlockIOWeightDevice(major, minor)
} else {
g.AddLinuxResourcesBlockIOWeightDevice(major, minor, uint16(weight))
}
}
}
if context.IsSet("linux-blkio-write-bps-device") {
throttleDevices := context.StringSlice("linux-blkio-write-bps-device")
for _, v := range throttleDevices {
major, minor, rate, err := parseThrottleDevice(v)
if err != nil {
return err
}
if rate == -1 {
g.DropLinuxResourcesBlockIOThrottleWriteBpsDevice(major, minor)
} else {
g.AddLinuxResourcesBlockIOThrottleWriteBpsDevice(major, minor, uint64(rate))
}
}
}
if context.IsSet("linux-blkio-write-iops-device") {
throttleDevices := context.StringSlice("linux-blkio-write-iops-device")
for _, v := range throttleDevices {
major, minor, rate, err := parseThrottleDevice(v)
if err != nil {
return err
}
if rate == -1 {
g.DropLinuxResourcesBlockIOThrottleWriteIOPSDevice(major, minor)
} else {
g.AddLinuxResourcesBlockIOThrottleWriteIOPSDevice(major, minor, uint64(rate))
}
}
}
if context.IsSet("linux-cpu-shares") {
g.SetLinuxResourcesCPUShares(context.Uint64("linux-cpu-shares"))
}
if context.IsSet("linux-cpu-period") {
g.SetLinuxResourcesCPUPeriod(context.Uint64("linux-cpu-period"))
}
if context.IsSet("linux-cpu-quota") {
g.SetLinuxResourcesCPUQuota(context.Int64("linux-cpu-quota"))
}
if context.IsSet("linux-realtime-runtime") {
g.SetLinuxResourcesCPURealtimeRuntime(context.Int64("linux-realtime-runtime"))
}
if context.IsSet("linux-pids-limit") {
g.SetLinuxResourcesPidsLimit(context.Int64("linux-pids-limit"))
}
if context.IsSet("linux-realtime-period") {
g.SetLinuxResourcesCPURealtimePeriod(context.Uint64("linux-realtime-period"))
}
if context.IsSet("linux-cpus") {
g.SetLinuxResourcesCPUCpus(context.String("linux-cpus"))
}
if context.IsSet("linux-hugepage-limits-add") {
pageList := context.StringSlice("linux-hugepage-limits-add")
for _, v := range pageList {
pagesize, limit, err := parseHugepageLimit(v)
if err != nil {
return err
}
g.AddLinuxResourcesHugepageLimit(pagesize, limit)
}
}
if context.IsSet("linux-hugepage-limits-drop") {
pageList := context.StringSlice("linux-hugepage-limits-drop")
for _, v := range pageList {
g.DropLinuxResourcesHugepageLimit(v)
}
}
if context.IsSet("linux-intelRdt-closid") {
g.SetLinuxIntelRdtClosID(context.String("linux-intelRdt-closid"))
}
if context.IsSet("linux-intelRdt-l3CacheSchema") {
g.SetLinuxIntelRdtL3CacheSchema(context.String("linux-intelRdt-l3CacheSchema"))
}
if context.IsSet("linux-mems") {
g.SetLinuxResourcesCPUMems(context.String("linux-mems"))
}
if context.IsSet("linux-mem-limit") {
g.SetLinuxResourcesMemoryLimit(context.Int64("linux-mem-limit"))
}
if context.IsSet("linux-mem-reservation") {
g.SetLinuxResourcesMemoryReservation(context.Int64("linux-mem-reservation"))
}
if context.IsSet("linux-mem-swap") {
g.SetLinuxResourcesMemorySwap(context.Int64("linux-mem-swap"))
}
if context.IsSet("linux-mem-kernel-limit") {
g.SetLinuxResourcesMemoryKernel(context.Int64("linux-mem-kernel-limit"))
}
if context.IsSet("linux-mem-kernel-tcp") {
g.SetLinuxResourcesMemoryKernelTCP(context.Int64("linux-mem-kernel-tcp"))
}
if context.IsSet("linux-mem-swappiness") {
g.SetLinuxResourcesMemorySwappiness(context.Uint64("linux-mem-swappiness"))
}
if context.IsSet("linux-network-classid") {
g.SetLinuxResourcesNetworkClassID(uint32(context.Int("linux-network-classid")))
}
if context.IsSet("linux-network-priorities") {
priorities := context.StringSlice("linux-network-priorities")
for _, p := range priorities {
name, priority, err := parseNetworkPriority(p)
if err != nil {
return err
}
if priority == -1 {
g.DropLinuxResourcesNetworkPriorities(name)
} else {
g.AddLinuxResourcesNetworkPriorities(name, uint32(priority))
}
}
}
if context.Bool("linux-namespace-remove-all") {
g.ClearLinuxNamespaces()
}
if context.IsSet("linux-namespace-add") {
namespaces := context.StringSlice("linux-namespace-add")
for _, ns := range namespaces {
name, path, err := parseNamespace(ns)
if err != nil {
return err
}
if err := g.AddOrReplaceLinuxNamespace(name, path); err != nil {
return err
}
}
}
if context.IsSet("linux-namespace-remove") {
namespaces := context.StringSlice("linux-namespace-remove")
for _, name := range namespaces {
if err := g.RemoveLinuxNamespace(name); err != nil {
return err
}
}
}
if context.Bool("process-rlimits-remove-all") {
g.ClearProcessRlimits()
}
if context.IsSet("process-rlimits-add") {
rlimits := context.StringSlice("process-rlimits-add")
for _, rlimit := range rlimits {
rType, rHard, rSoft, err := parseRlimit(rlimit)
if err != nil {
return err
}
g.AddProcessRlimits(rType, rHard, rSoft)
}
}
if context.IsSet("process-rlimits-remove") {
rlimits := context.StringSlice("process-rlimits-remove")
for _, rlimit := range rlimits {
g.RemoveProcessRlimits(rlimit)
}
}
if context.Bool("linux-device-remove-all") {
g.ClearLinuxDevices()
}
if context.IsSet("linux-device-add") {
devices := context.StringSlice("linux-device-add")
for _, deviceArg := range devices {
dev, err := parseDevice(deviceArg, g)
if err != nil {
return err
}
g.AddDevice(dev)
}
}
if context.IsSet("linux-device-remove") {
devices := context.StringSlice("linux-device-remove")
for _, device := range devices {
g.RemoveDevice(device)
}
}
if context.IsSet("solaris-anet") {
anets := context.StringSlice("solaris-anet")
for _, anet := range anets {
tmpAnet := rspec.SolarisAnet{}
if err := json.Unmarshal([]byte(anet), &tmpAnet); err != nil {
return err
}
g.AddSolarisAnet(tmpAnet)
}
}
if context.IsSet("solaris-capped-cpu-ncpus") {
g.SetSolarisCappedCPUNcpus(context.String("solaris-capped-cpu-ncpus"))
}
if context.IsSet("solaris-capped-memory-physical") {
g.SetSolarisCappedMemoryPhysical(context.String("solaris-capped-memory-physical"))
}
if context.IsSet("solaris-capped-memory-swap") {
g.SetSolarisCappedMemorySwap(context.String("solaris-capped-memory-swap"))
}
if context.IsSet("solaris-limitpriv") {
g.SetSolarisLimitPriv(context.String("solaris-limitpriv"))
}
if context.IsSet("solaris-max-shm-memory") {
g.SetSolarisMaxShmMemory(context.String("solaris-max-shm-memory"))
}
if context.IsSet("solaris-milestone") {
g.SetSolarisMilestone(context.String("solaris-milestone"))
}
if context.IsSet("vm-hypervisor-path") {
if err := g.SetVMHypervisorPath(context.String("vm-hypervisor-path")); err != nil {
return err
}
}
if context.IsSet("vm-hypervisor-parameters") {
g.SetVMHypervisorParameters(context.StringSlice("vm-hypervisor-parameters"))
}
if context.IsSet("vm-kernel-path") {
if err := g.SetVMKernelPath(context.String("vm-kernel-path")); err != nil {
return err
}
}
if context.IsSet("vm-kernel-parameters") {
g.SetVMKernelParameters(context.StringSlice("vm-kernel-parameters"))
}
if context.IsSet("vm-kernel-initrd") {
if err := g.SetVMKernelInitRD(context.String("vm-kernel-initrd")); err != nil {
return err
}
}
if context.IsSet("vm-image-path") {
if err := g.SetVMImagePath(context.String("vm-image-path")); err != nil {
return err
}
}
if context.IsSet("vm-image-format") {
if err := g.SetVMImageFormat(context.String("vm-image-format")); err != nil {
return err
}
}
if context.IsSet("windows-hyperv-utilityVMPath") {
g.SetWindowsHypervUntilityVMPath(context.String("windows-hyperv-utilityVMPath"))
}
if context.IsSet("windows-ignore-flushes-during-boot") {
g.SetWindowsIgnoreFlushesDuringBoot(context.Bool("windows-ignore-flushes-during-boot"))
}
if context.IsSet("windows-layer-folders") {
folders := context.StringSlice("windows-layer-folders")
for _, folder := range folders {
g.AddWindowsLayerFolders(folder)
}
}
if context.IsSet("windows-devices") {
devices := context.StringSlice("windows-devices")
for _, device := range devices {
id, idType, err := parseWindowsDevices(device)
if err != nil {
return err
}
if err := g.AddWindowsDevices(id, idType); err != nil {
return err
}
}
}
if context.IsSet("windows-network") {
network := context.String("windows-network")
tmpNetwork := rspec.WindowsNetwork{}
if err := json.Unmarshal([]byte(network), &tmpNetwork); err != nil {
return err
}
g.SetWindowsNetwork(tmpNetwork)
}
if context.IsSet("windows-network-allowunqualifieddnsquery") {
g.SetWindowsNetworkAllowUnqualifiedDNSQuery(context.Bool("windows-network-allowunqualifieddnsquery"))
}
if context.IsSet("windows-network-networkNamespace") {
g.SetWindowsNetworkNamespace(context.String("windows-network-networkNamespace"))
}
if context.IsSet("windows-resources-cpu") {
cpu := context.String("windows-resources-cpu")
tmpCPU := rspec.WindowsCPUResources{}
if err := json.Unmarshal([]byte(cpu), &tmpCPU); err != nil {
return err
}
g.SetWindowsResourcesCPU(tmpCPU)
}
if context.IsSet("windows-resources-memory-limit") {
limit := context.Uint64("windows-resources-memory-limit")
g.SetWindowsResourcesMemoryLimit(limit)
}
if context.IsSet("windows-resources-storage") {
storage := context.String("windows-resources-storage")
tmpStorage := rspec.WindowsStorageResources{}
if err := json.Unmarshal([]byte(storage), &tmpStorage); err != nil {
return err
}
g.SetWindowsResourcesStorage(tmpStorage)
}
if context.IsSet("windows-servicing") {
g.SetWindowsServicing(context.Bool("windows-servicing"))
}
err := addSeccomp(context, g)
return err
}
func parseConsoleSize(consoleSize string) (uint, uint, error) {
size := strings.Split(consoleSize, ":")
if len(size) != 2 {
return 0, 0, fmt.Errorf("invalid consolesize value: %s", consoleSize)
}
width, err := strconv.Atoi(size[0])
if err != nil {
return 0, 0, err
}
height, err := strconv.Atoi(size[1])
if err != nil {
return 0, 0, err
}
return uint(width), uint(height), nil
}
func parseIDMapping(idms string) (uint32, uint32, uint32, error) {
idm := strings.Split(idms, ":")
if len(idm) != 3 {
return 0, 0, 0, fmt.Errorf("idmappings error: %s", idms)
}
hid, err := strconv.Atoi(idm[0])
if err != nil {
return 0, 0, 0, err
}
cid, err := strconv.Atoi(idm[1])
if err != nil {
return 0, 0, 0, err
}
size, err := strconv.Atoi(idm[2])
if err != nil {
return 0, 0, 0, err
}
return uint32(hid), uint32(cid), uint32(size), nil
}
func parseHugepageLimit(pageLimit string) (string, uint64, error) {
pl := strings.Split(pageLimit, ":")
if len(pl) != 2 {
return "", 0, fmt.Errorf("invalid format: %s", pageLimit)
}
limit, err := strconv.Atoi(pl[1])
if err != nil {
return "", 0, err
}
return pl[0], uint64(limit), nil
}
func parseNetworkPriority(np string) (string, int32, error) {
var err error
parts := strings.Split(np, ":")
if len(parts) != 2 || parts[0] == "" {
return "", 0, fmt.Errorf("invalid value %v for --linux-network-priorities", np)
}
priority, err := strconv.Atoi(parts[1])
if err != nil {
return "", 0, err
}
return parts[0], int32(priority), nil
}
func parseRlimit(rlimit string) (string, uint64, uint64, error) {
parts := strings.Split(rlimit, ":")
if len(parts) != 3 || parts[0] == "" {
return "", 0, 0, fmt.Errorf("invalid rlimits value: %s", rlimit)
}
hard, err := strconv.Atoi(parts[1])
if err != nil {
return "", 0, 0, err
}
soft, err := strconv.Atoi(parts[2])
if err != nil {
return "", 0, 0, err
}
return parts[0], uint64(hard), uint64(soft), nil
}
func parseNamespace(ns string) (string, string, error) {
parts := strings.SplitN(ns, ":", 2)
if len(parts) == 0 || parts[0] == "" {
return "", "", fmt.Errorf("invalid namespace value: %s", ns)
}
nsType := parts[0]
nsPath := ""
if len(parts) == 2 {
nsPath = parts[1]
}
return nsType, nsPath, nil
}
func parseWindowsDevices(device string) (string, string, error) {
parts := strings.Split(device, ":")
if len(parts) != 2 {
return "", "", fmt.Errorf("invalid windows device value: %s", device)
}
id := parts[0]
idType := parts[1]
return id, idType, nil
}
var deviceType = map[string]bool{
"b": true, // a block (buffered) special file
"c": true, // a character special file
"u": true, // a character (unbuffered) special file
"p": true, // a FIFO
}
// parseDevice takes the raw string passed with the --device-add flag
func parseDevice(device string, g *generate.Generator) (rspec.LinuxDevice, error) {
dev := rspec.LinuxDevice{}
// The required part and optional part are separated by ":"
argsParts := strings.Split(device, ":")
if len(argsParts) < 4 {
return dev, fmt.Errorf("Incomplete device arguments: %s", device)
}
requiredPart := argsParts[0:4]
optionalPart := argsParts[4:]
// The required part must contain type, major, minor, and path
dev.Type = requiredPart[0]
if !deviceType[dev.Type] {
return dev, fmt.Errorf("Invalid device type: %s", dev.Type)
}
i, err := strconv.ParseInt(requiredPart[1], 10, 64)
if err != nil {
return dev, err
}
dev.Major = i
i, err = strconv.ParseInt(requiredPart[2], 10, 64)
if err != nil {
return dev, err
}
dev.Minor = i
dev.Path = requiredPart[3]
// The optional part include all optional property
for _, s := range optionalPart {
parts := strings.SplitN(s, "=", 2)
if len(parts) != 2 {
return dev, fmt.Errorf("Incomplete device arguments: %s", s)
}
name, value := parts[0], parts[1]
switch name {
case "fileMode":
i, err := strconv.ParseInt(value, 10, 32)
if err != nil {
return dev, err
}
mode := os.FileMode(i)
dev.FileMode = &mode
case "uid":
i, err := strconv.ParseInt(value, 10, 32)
if err != nil {
return dev, err
}
uid := uint32(i)
dev.UID = &uid
case "gid":
i, err := strconv.ParseInt(value, 10, 32)
if err != nil {
return dev, err
}
gid := uint32(i)
dev.GID = &gid
default:
return dev, fmt.Errorf("'%s' is not supported by device section", name)
}
}
return dev, nil
}
var cgroupDeviceType = map[string]bool{
"a": true, // all
"b": true, // block device
"c": true, // character device
}
var cgroupDeviceAccess = map[string]bool{
"r": true, //read
"w": true, //write
"m": true, //mknod
}
// parseLinuxResourcesDeviceAccess parses the raw string passed with the --device-access-add flag
func parseLinuxResourcesDeviceAccess(device string, g *generate.Generator) (rspec.LinuxDeviceCgroup, error) {
var allow bool
var devType, access string
var major, minor *int64
argsParts := strings.Split(device, ",")
switch argsParts[0] {
case "allow":
allow = true
case "deny":
allow = false
default:
return rspec.LinuxDeviceCgroup{},
fmt.Errorf("Only 'allow' and 'deny' are allowed in the first field of device-access-add: %s", device)
}
for _, s := range argsParts[1:] {
s = strings.TrimSpace(s)
if s == "" {
continue
}
parts := strings.SplitN(s, "=", 2)
if len(parts) != 2 {
return rspec.LinuxDeviceCgroup{}, fmt.Errorf("Incomplete device-access-add arguments: %s", s)
}
name, value := parts[0], parts[1]
switch name {
case "type":
if !cgroupDeviceType[value] {
return rspec.LinuxDeviceCgroup{}, fmt.Errorf("Invalid device type in device-access-add: %s", value)
}
devType = value
case "major":
i, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return rspec.LinuxDeviceCgroup{}, err
}
major = &i
case "minor":
i, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return rspec.LinuxDeviceCgroup{}, err
}
minor = &i
case "access":
for _, c := range strings.Split(value, "") {
if !cgroupDeviceAccess[c] {
return rspec.LinuxDeviceCgroup{}, fmt.Errorf("Invalid device access in device-access-add: %s", c)
}
}
access = value
}
}
return rspec.LinuxDeviceCgroup{
Allow: allow,
Type: devType,
Major: major,
Minor: minor,
Access: access,
}, nil
}
func addSeccomp(context *cli.Context, g *generate.Generator) error {
if context.Bool("linux-seccomp-remove-all") {
err := g.RemoveAllSeccompRules()
if err != nil {
return err
}
}
// Set the DefaultAction of seccomp
if context.IsSet("linux-seccomp-default") {
seccompDefault := context.String("linux-seccomp-default")
err := g.SetDefaultSeccompAction(seccompDefault)
if err != nil {
return err
}
} else if context.IsSet("linux-seccomp-default-force") {
seccompDefaultForced := context.String("linux-seccomp-default-force")
err := g.SetDefaultSeccompActionForce(seccompDefaultForced)
if err != nil {
return err
}
}
// Add the additional architectures permitted to be used for system calls
if context.IsSet("linux-seccomp-arch") {
seccompArch := context.String("linux-seccomp-arch")
architectureArgs := strings.Split(seccompArch, ",")
for _, arg := range architectureArgs {
err := g.SetSeccompArchitecture(arg)
if err != nil {
return err
}
}
}
if context.IsSet("linux-seccomp-errno") {
err := seccompSet(context, "errno", g)
if err != nil {
return err
}
}
if context.IsSet("linux-seccomp-kill") {
err := seccompSet(context, "kill", g)
if err != nil {
return err
}
}
if context.IsSet("linux-seccomp-trace") {
err := seccompSet(context, "trace", g)
if err != nil {
return err
}
}
if context.IsSet("linux-seccomp-trap") {
err := seccompSet(context, "trap", g)
if err != nil {
return err
}
}
if context.IsSet("linux-seccomp-allow") {
err := seccompSet(context, "allow", g)
if err != nil {
return err
}
}
if context.IsSet("linux-seccomp-remove") {
seccompRemove := context.String("linux-seccomp-remove")
err := g.RemoveSeccompRule(seccompRemove)
if err != nil {
return err
}
}
return nil
}
func seccompSet(context *cli.Context, seccompFlag string, g *generate.Generator) error {
flagInput := context.String("linux-seccomp-" + seccompFlag)
flagArgs := strings.Split(flagInput, ",")
setSyscallArgsSlice := []seccomp.SyscallOpts{}
for _, flagArg := range flagArgs {
comparisonArgs := strings.Split(flagArg, ":")
if len(comparisonArgs) == 5 {
setSyscallArgs := seccomp.SyscallOpts{
Action: seccompFlag,
Syscall: comparisonArgs[0],
Index: comparisonArgs[1],
Value: comparisonArgs[2],
ValueTwo: comparisonArgs[3],
Operator: comparisonArgs[4],
}
setSyscallArgsSlice = append(setSyscallArgsSlice, setSyscallArgs)
} else if len(comparisonArgs) == 1 {
setSyscallArgs := seccomp.SyscallOpts{
Action: seccompFlag,
Syscall: comparisonArgs[0],
}
setSyscallArgsSlice = append(setSyscallArgsSlice, setSyscallArgs)
} else {
return fmt.Errorf("invalid syscall argument formatting %v", comparisonArgs)
}
for _, r := range setSyscallArgsSlice {
err := g.SetSyscallAction(r)
if err != nil {
return err
}
}
}
return nil
}
// readKVStrings reads a file of line terminated key=value pairs, and overrides any keys
// present in the file with additional pairs specified in the override parameter
//
// This function is copied from github.com/docker/docker/runconfig/opts/parse.go
func readKVStrings(files []string, override []string) ([]string, error) {
envVariables := []string{}
for _, ef := range files {
parsedVars, err := parseEnvFile(ef)
if err != nil {
return nil, err
}
envVariables = append(envVariables, parsedVars...)
}
// parse the '-e' and '--env' after, to allow override
envVariables = append(envVariables, override...)
return envVariables, nil
}
// parseEnv splits a given environment variable (of the form name=value) into
// (name, value). An error is returned if there is no "=" in the line or if the
// name is empty.
func parseEnv(env string) (string, string, error) {
parts := strings.SplitN(env, "=", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("environment variable must contain '=': %s", env)
}
name, value := parts[0], parts[1]
if name == "" {
return "", "", fmt.Errorf("environment variable must have non-empty name: %s", env)
}
return name, value, nil
}
// parseEnvFile reads a file with environment variables enumerated by lines
//
// ``Environment variable names used by the utilities in the Shell and
// Utilities volume of IEEE Std 1003.1-2001 consist solely of uppercase
// letters, digits, and the '_' (underscore) from the characters defined in
// Portable Character Set and do not begin with a digit. *But*, other
// characters may be permitted by an implementation; applications shall
// tolerate the presence of such names.''
// -- http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html
//
// As of #16585, it's up to application inside docker to validate or not
// environment variables, that's why we just strip leading whitespace and
// nothing more.
//
// This function is copied from github.com/docker/docker/runconfig/opts/envfile.go
func parseEnvFile(filename string) ([]string, error) {
fh, err := os.Open(filename)
if err != nil {
return []string{}, err
}
defer fh.Close()
lines := []string{}
scanner := bufio.NewScanner(fh)
currentLine := 0
utf8bom := []byte{0xEF, 0xBB, 0xBF}
for scanner.Scan() {
scannedBytes := scanner.Bytes()
if !utf8.Valid(scannedBytes) {
return []string{}, fmt.Errorf("env file %s contains invalid utf8 bytes at line %d: %v", filename, currentLine+1, scannedBytes)
}
// We trim UTF8 BOM
if currentLine == 0 {
scannedBytes = bytes.TrimPrefix(scannedBytes, utf8bom)
}
// trim the line from all leading whitespace first
line := strings.TrimLeftFunc(string(scannedBytes), unicode.IsSpace)
currentLine++
// line is not empty, and not starting with '#'
if len(line) > 0 && !strings.HasPrefix(line, "#") {
data := strings.SplitN(line, "=", 2)
// trim the front of a variable, but nothing else
variable := strings.TrimLeft(data[0], whiteSpaces)
if strings.ContainsAny(variable, whiteSpaces) {
return []string{}, ErrBadEnvVariable{fmt.Sprintf("variable '%s' has white spaces", variable)}
}
if len(data) > 1 {
// pass the value through, no trimming
lines = append(lines, fmt.Sprintf("%s=%s", variable, data[1]))
} else {
// if only a pass-through variable is given, clean it up.
lines = append(lines, fmt.Sprintf("%s=%s", strings.TrimSpace(line), os.Getenv(line)))
}
}
}
return lines, scanner.Err()
}
var whiteSpaces = " \t"
// ErrBadEnvVariable typed error for bad environment variable
type ErrBadEnvVariable struct {
msg string
}
func (e ErrBadEnvVariable) Error() string {
return fmt.Sprintf("poorly formatted environment: %s", e.msg)
}
func parseDeviceWeight(weightDevice string) (int64, int64, int16, error) {
list := strings.Split(weightDevice, ":")
if len(list) != 3 {
return 0, 0, 0, fmt.Errorf("invalid format: %s", weightDevice)
}
major, err := strconv.Atoi(list[0])
if err != nil {
return 0, 0, 0, err
}
minor, err := strconv.Atoi(list[1])
if err != nil {
return 0, 0, 0, err
}
weight, err := strconv.Atoi(list[2])
if err != nil {
return 0, 0, 0, err
}
return int64(major), int64(minor), int16(weight), nil
}
func parseThrottleDevice(throttleDevice string) (int64, int64, int64, error) {
list := strings.Split(throttleDevice, ":")
if len(list) != 3 {
return 0, 0, 0, fmt.Errorf("invalid format: %s", throttleDevice)
}
major, err := strconv.Atoi(list[0])
if err != nil {
return 0, 0, 0, err
}
minor, err := strconv.Atoi(list[1])
if err != nil {
return 0, 0, 0, err
}
rate, err := strconv.Atoi(list[2])
if err != nil {
return 0, 0, 0, err
}
return int64(major), int64(minor), int64(rate), nil
}
|
package logic
import (
"encoding/json"
"reflect"
"testing"
"time"
)
func Test_UnmarshalJSON(t *testing.T) {
type args struct {
jsonString string
}
type output struct {
load inputLoad
hasError bool
}
tests := []struct {
name string
args args
want output
}{
{
name: "MarshallingOk",
args: args{
jsonString: `{"id": "1234","customer_id": "2345","load_amount": "$123.45","time": "2018-01-01T00:00:00Z"}`,
},
want: output{
load: inputLoad{
LoadID: "1234",
CustomerID: "2345",
Amount: loadAmount{Value: 123.45},
Time: time.Date(2018, time.January, 1, 0, 0, 0, 0, time.UTC),
},
hasError: false,
},
},
{
name: "MarshallingAmountFailed",
args: args{
jsonString: `{"id": "1234","customer_id": "2345","load_amount": "AAAAAAAAAA","time": "2018-01-01T00:00:00Z"}`,
},
want: output{
load: inputLoad{
LoadID: "1234",
CustomerID: "2345",
Amount: loadAmount{Value: 0},
Time: time.Date(0001, time.January, 1, 0, 0, 0, 0, time.UTC), // time not parsed because of error in amount
},
hasError: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
l := inputLoad{}
err := json.Unmarshal([]byte(tt.args.jsonString), &l)
if (err != nil) != tt.want.hasError || l != tt.want.load {
t.Errorf("unmarshallJson = %v and %v, want %v", l, err, tt.want)
}
})
}
}
func Test_validateLoad(t *testing.T) {
type args struct {
load inputLoad
historyLoads []inputLoad
}
tests := []struct {
name string
args args
want bool
}{
{
"validateAcceptedNoHistory",
args{
load: inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
historyLoads: nil,
},
true,
},
{
"validateRefusedMaxAmountNoHistory",
args{
load: inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 6000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
historyLoads: nil,
},
false,
},
{
"validateMaxAmountDifferentDays",
args{
load: inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2000, time.Month(1), 2, 10, 0, 0, 0, time.UTC),
},
historyLoads: []inputLoad{
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
},
},
true,
},
{
"validateMaxAmountDay",
args{
load: inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
historyLoads: []inputLoad{
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
},
},
false,
},
{
"validateExactMaxAmountDay",
args{
load: inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
historyLoads: []inputLoad{
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 2000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
},
},
true,
},
{
"validateMaxCountDay",
args{
load: inputLoad{
LoadID: "4",
CustomerID: "1",
Amount: loadAmount{Value: 1000},
Time: time.Date(2000, time.Month(1), 1, 15, 0, 0, 0, time.UTC),
},
historyLoads: []inputLoad{
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 1000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 1000},
Time: time.Date(2000, time.Month(1), 1, 11, 0, 0, 0, time.UTC),
},
inputLoad{
LoadID: "3",
CustomerID: "1",
Amount: loadAmount{Value: 1000},
Time: time.Date(2000, time.Month(1), 1, 12, 0, 0, 0, time.UTC),
},
},
},
false,
},
{
"validateExactCountDay",
args{
load: inputLoad{
LoadID: "4",
CustomerID: "1",
Amount: loadAmount{Value: 1000},
Time: time.Date(2000, time.Month(1), 1, 15, 0, 0, 0, time.UTC),
},
historyLoads: []inputLoad{
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 1000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 1000},
Time: time.Date(2000, time.Month(1), 1, 11, 0, 0, 0, time.UTC),
},
},
},
true,
},
{
"validateMaxCountOnDifferentDays",
args{
load: inputLoad{
LoadID: "4",
CustomerID: "1",
Amount: loadAmount{Value: 1000},
Time: time.Date(2000, time.Month(1), 2, 15, 0, 0, 0, time.UTC),
},
historyLoads: []inputLoad{
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 1000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 1000},
Time: time.Date(2000, time.Month(1), 1, 11, 0, 0, 0, time.UTC),
},
inputLoad{
LoadID: "3",
CustomerID: "1",
Amount: loadAmount{Value: 1000},
Time: time.Date(2000, time.Month(1), 1, 12, 0, 0, 0, time.UTC),
},
},
},
true,
},
{
"validateExactMaxOnWeek",
args{
load: inputLoad{
LoadID: "4",
CustomerID: "1",
Amount: loadAmount{Value: 5000},
Time: time.Date(2020, time.Month(1), 9, 15, 0, 0, 0, time.UTC),
},
historyLoads: []inputLoad{
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 5000},
Time: time.Date(2020, time.Month(1), 6, 10, 0, 0, 0, time.UTC), // 6th Jan 2020 is a Monday
},
inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 5000},
Time: time.Date(2020, time.Month(1), 7, 11, 0, 0, 0, time.UTC),
},
inputLoad{
LoadID: "3",
CustomerID: "1",
Amount: loadAmount{Value: 5000},
Time: time.Date(2020, time.Month(1), 8, 12, 0, 0, 0, time.UTC),
},
},
},
true,
},
{
"validateMaxOnWeek",
args{
load: inputLoad{
LoadID: "5",
CustomerID: "1",
Amount: loadAmount{Value: 4000},
Time: time.Date(2020, time.Month(1), 10, 15, 0, 0, 0, time.UTC),
},
historyLoads: []inputLoad{
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 5000},
Time: time.Date(2020, time.Month(1), 6, 10, 0, 0, 0, time.UTC), // 6 Jan is a Monday
},
inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 5000},
Time: time.Date(2020, time.Month(1), 7, 11, 0, 0, 0, time.UTC),
},
inputLoad{
LoadID: "3",
CustomerID: "1",
Amount: loadAmount{Value: 5000},
Time: time.Date(2020, time.Month(1), 8, 12, 0, 0, 0, time.UTC),
},
inputLoad{
LoadID: "4",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2020, time.Month(1), 9, 12, 0, 0, 0, time.UTC),
},
},
},
false,
},
{
"validateMaxOnTwoWeeks",
args{
load: inputLoad{
LoadID: "5",
CustomerID: "1",
Amount: loadAmount{Value: 4000},
Time: time.Date(2020, time.Month(1), 13, 15, 0, 0, 0, time.UTC),
},
historyLoads: []inputLoad{
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 5000},
Time: time.Date(2020, time.Month(1), 6, 10, 0, 0, 0, time.UTC), // 6 Jan is a Monday
},
inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 5000},
Time: time.Date(2020, time.Month(1), 7, 11, 0, 0, 0, time.UTC),
},
inputLoad{
LoadID: "3",
CustomerID: "1",
Amount: loadAmount{Value: 5000},
Time: time.Date(2020, time.Month(1), 8, 12, 0, 0, 0, time.UTC),
},
inputLoad{
LoadID: "4",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2020, time.Month(1), 9, 12, 0, 0, 0, time.UTC),
},
},
},
true,
},
{
"validateMidnightOnWeeks",
args{
load: inputLoad{
LoadID: "5",
CustomerID: "1",
Amount: loadAmount{Value: 4000},
Time: time.Date(2020, time.Month(1), 12, 23, 59, 59, 0, time.UTC).Add(time.Second),
},
historyLoads: []inputLoad{
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 5000},
Time: time.Date(2020, time.Month(1), 6, 10, 0, 0, 0, time.UTC), // 6 Jan is a Monday
},
inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 5000},
Time: time.Date(2020, time.Month(1), 7, 11, 0, 0, 0, time.UTC),
},
inputLoad{
LoadID: "3",
CustomerID: "1",
Amount: loadAmount{Value: 5000},
Time: time.Date(2020, time.Month(1), 8, 12, 0, 0, 0, time.UTC),
},
inputLoad{
LoadID: "4",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2020, time.Month(1), 9, 12, 0, 0, 0, time.UTC),
},
},
},
true,
},
{
"validateMidnightOnTwoDays",
args{
load: inputLoad{
LoadID: "5",
CustomerID: "1",
Amount: loadAmount{Value: 4000},
Time: time.Date(2020, time.Month(1), 7, 0, 0, 0, 0, time.UTC),
},
historyLoads: []inputLoad{
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2020, time.Month(1), 6, 10, 0, 0, 0, time.UTC), // 6 Jan is a Monday
},
},
},
true,
},
{
"validateMidnightMinusOneSecond",
args{
load: inputLoad{
LoadID: "5",
CustomerID: "1",
Amount: loadAmount{Value: 4000},
Time: time.Date(2020, time.Month(1), 7, 0, 0, 0, 0, time.UTC).Add(-time.Second),
},
historyLoads: []inputLoad{
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2020, time.Month(1), 6, 10, 0, 0, 0, time.UTC), // 6 Jan is a Monday
},
},
},
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := validateLoad(tt.args.load, tt.args.historyLoads); got != tt.want {
t.Errorf("validateLoad = %v, want %v", got, tt.want)
}
})
}
}
func Test_validateLoadAndFillHistory(t *testing.T) {
type args struct {
load inputLoad
customerHistoryLoads map[string][]inputLoad
}
type output struct {
returnedValue bool
customerHistoryLoads map[string][]inputLoad
}
tests := []struct {
name string
args args
want output
}{
{
"validateEmptyAccepted",
args{
load: inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
customerHistoryLoads: make(map[string][]inputLoad),
},
output{
returnedValue: true,
customerHistoryLoads: map[string][]inputLoad{
"1": {
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
}},
},
},
},
{
"validateEmptyNotAccepted",
args{
load: inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 6000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
customerHistoryLoads: make(map[string][]inputLoad),
},
output{
returnedValue: false,
customerHistoryLoads: make(map[string][]inputLoad),
},
},
{
"validateNotEmptyAccepted",
args{
load: inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
customerHistoryLoads: map[string][]inputLoad{
"1": {
inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 1000},
Time: time.Date(2000, time.Month(1), 1, 5, 0, 0, 0, time.UTC),
},
},
},
},
output{
returnedValue: true,
customerHistoryLoads: map[string][]inputLoad{
"1": {
inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 1000},
Time: time.Date(2000, time.Month(1), 1, 5, 0, 0, 0, time.UTC),
},
inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
}},
},
},
},
{
"validateNotEmptyNotAccepted",
args{
load: inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2000, time.Month(1), 1, 10, 0, 0, 0, time.UTC),
},
customerHistoryLoads: map[string][]inputLoad{
"1": {
inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2000, time.Month(1), 1, 5, 0, 0, 0, time.UTC),
},
},
},
},
output{
returnedValue: false,
customerHistoryLoads: map[string][]inputLoad{
"1": {
inputLoad{
LoadID: "2",
CustomerID: "1",
Amount: loadAmount{Value: 3000},
Time: time.Date(2000, time.Month(1), 1, 5, 0, 0, 0, time.UTC),
}},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
loadParser := NewFinanceLogic()
loadParser.CustomersLoads = tt.args.customerHistoryLoads
if got := loadParser.validateLoadAndFillHistory(tt.args.load); got != tt.want.returnedValue || !reflect.DeepEqual(loadParser.CustomersLoads, tt.want.customerHistoryLoads) {
t.Errorf("validateLoadAndFillHistory = %v and %v, want %v", got, loadParser.CustomersLoads, tt.want)
}
})
}
}
func Test_addCustomerLoadToTreated(t *testing.T) {
type args struct {
load inputLoad
treatedLoadIds map[customerLoadID]interface{}
}
tests := []struct {
name string
args args
want bool
}{
{
name: "NewCustomerLoad",
args: args{
load: inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{},
Time: time.Time{},
},
treatedLoadIds: make(map[customerLoadID]interface{}),
},
want: true,
},
{
name: "ExistingCustomerLoad",
args: args{
load: inputLoad{
LoadID: "1",
CustomerID: "1",
Amount: loadAmount{},
Time: time.Time{},
},
treatedLoadIds: map[customerLoadID]interface{}{
customerLoadID{
LoadID: "1",
CustomerID: "1",
}: nil,
},
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
loadParser := NewFinanceLogic()
loadParser.TreatedLoadIds = tt.args.treatedLoadIds
if got := loadParser.addCustomerLoadToTreated(tt.args.load); got != tt.want {
t.Errorf("addCustomerLoadToTreated = %v, want %v", got, tt.want)
}
})
}
}
func Test_ParseLoads(t *testing.T) {
type args struct {
loadStrings []string
}
type output struct {
loadResponses []string
numberOfErrors int
}
tests := []struct {
name string
args args
want output
}{
{
name: "oneLoad",
args: args{
loadStrings: []string{
`{"id": "1234","customer_id": "2345","load_amount": "$123.45","time": "2018-01-01T00:00:00Z"}`,
},
},
want: output{
loadResponses: []string{`{"id":"1234","customer_id":"2345","accepted":true}`},
numberOfErrors: 0,
}},
{
name: "emptyLoad",
args: args{
loadStrings: make([]string, 0),
},
want: output{
loadResponses: make([]string, 0),
numberOfErrors: 0,
}},
{
name: "jsonError",
args: args{
loadStrings: []string{`anerrorinjson`},
},
want: output{
loadResponses: make([]string, 0),
numberOfErrors: 1,
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
loadParser := NewFinanceLogic()
stringChannel := make(chan string)
go func(stringChan chan string, stringsToLoad []string) {
for _, line := range stringsToLoad {
stringChan <- line
}
close(stringChan)
}(stringChannel, tt.args.loadStrings)
if gotLoads, gotErrors := loadParser.ParseLoads(stringChannel); !reflect.DeepEqual(gotLoads, tt.want.loadResponses) || len(gotErrors) != tt.want.numberOfErrors {
t.Errorf("ParseLoads = %v,%v want %v", gotLoads, gotErrors, tt.want)
}
})
}
}
|
package main
import "fmt"
/* pointer (*) จะทำให้ฟังก์ชัน zero เปลี่ยนค่าเริ่มต้นของตัวแปรได้
เครื่องหมาย * จะตามด้วยประเภทของตัวแปรที่ถูกจัดเก็บ
*/
func zero(xPrt *int) {
// *xPrt เป็นการบอกว่า xPrt ชี้ไปที่ int เก็บค่า 0 ไว้ที่หน่วยความจำที่ xPrt อ้างถึงอยู่
*xPrt = 0
}
func main() {
x := 5
// ส่งตำแหน่งของ x เข้าไปแทนที่่ตำแหน่งของ xPrt
// ผลลัพธ์จะเป็น 0
zero(&x)
fmt.Println(x)
}
|
package explorerutils
import (
"bytes"
"fmt"
"log"
"os"
yaml "gopkg.in/yaml.v2"
)
type ExplorerServices struct {
Version string `yaml:"version"`
Volumes map[string]interface{} `yaml:"volumes"`
Networks map[string]Networks `yaml:"networks"`
Services map[string]ExplorerService `yaml:"services"`
}
type External struct {
Name string `yaml:"name"`
}
type Networks struct {
External External `yaml:"external"`
}
type Healthcheck struct {
Test string `yaml:"test"`
Interval string `yaml:"interval"`
Timeout string `yaml:"timeout"`
Retries int `yaml:"retries"`
}
type DependsOn struct {
Condition string `yaml:"condition"`
}
type ExplorerService struct {
Image string `yaml:"image,omitempty"`
ContainerName string `yaml:"container_name,omitempty"`
Hostname string `yaml:"hostname,omitempty"`
Environment []string `yaml:"environment,omitempty"`
Healthcheck Healthcheck `yaml:"healthcheck,omitempty"`
Volumes []string `yaml:"volumes,omitempty"`
Command string `yaml:"command,omitempty"`
Ports []string `yaml:"ports,omitempty"`
DependsOn map[string]DependsOn `yaml:"depends_on,omitempty"`
Networks []string `yaml:"networks,omitempty"`
}
func (configInput *ExplorerInput) GenerateDockerCompose() {
fid, err := os.Create("docker-compose-explorer.yaml")
if err != nil {
log.Fatalf("Unable to create file docker-compose-explorer.yaml")
return
}
defer fid.Close()
// Version
var explorerServices ExplorerServices
explorerServices.Version = "2.1"
//Volumes
var volumeMap map[string]interface{}
volumeMap = make(map[string]interface{})
volumeMap["pgdata"] = nil
volumeMap["walletstore"] = nil
explorerServices.Volumes = volumeMap
// External networks
var networks Networks
var networkMap map[string]Networks
networkMap = make(map[string]Networks)
var externalNetworkName string
if configInput.ExternalNetworkName != "" {
externalNetworkName = configInput.ExternalNetworkName
} else {
externalNetworkName = fmt.Sprintf("organizations_%s", configInput.NetworkName)
}
networks.External.Name = externalNetworkName
networkMap[fmt.Sprintf("%s.com", configInput.NetworkName)] = networks
explorerServices.Networks = networkMap
// Services
var explorerServiceMap map[string]ExplorerService
explorerServiceMap = make(map[string]ExplorerService)
// DB Service
var explorerService1 ExplorerService
explorerService1.Image = "hyperledger/explorer-db:latest"
explorerService1.ContainerName = fmt.Sprintf("explorerdb.%s.com", configInput.NetworkName)
explorerService1.Hostname = fmt.Sprintf("explorerdb.%s.com", configInput.NetworkName)
explorerService1.Environment = []string{
"DATABASE_DATABASE=fabricexplorer",
"DATABASE_USERNAME=hppoc",
"DATABASE_PASSWORD=password",
}
explorerService1.Healthcheck.Test = "pg_isready -h localhost -p 5432 -q -U postgres"
explorerService1.Healthcheck.Interval = "30s"
explorerService1.Healthcheck.Timeout = "10s"
explorerService1.Healthcheck.Retries = 5
explorerService1.Volumes = []string{
"pgdata:/var/lib/postgresql/data",
}
explorerService1.Networks = []string{
fmt.Sprintf("%s.com", configInput.NetworkName),
}
// Explorer Service
var explorerService2 ExplorerService
explorerService2.Image = "hyperledger/explorer:latest"
explorerService2.ContainerName = fmt.Sprintf("explorer.%s.com", configInput.NetworkName)
explorerService2.Hostname = fmt.Sprintf("explorer.%s.com", configInput.NetworkName)
explorerService2.Environment = []string{
fmt.Sprintf("DATABASE_HOST=explorerdb.%s.com", configInput.NetworkName),
"DATABASE_DATABASE=fabricexplorer",
"DATABASE_USERNAME=hppoc",
"DATABASE_PASSWD=password",
"LOG_LEVEL_APP=debug",
"LOG_LEVEL_DB=debug",
"LOG_LEVEL_CONSOLE=info",
"LOG_CONSOLE_STDOUT=true",
fmt.Sprintf("DISCOVERY_AS_LOCALHOST=%t", configInput.DiscoverAsLocalHost),
}
explorerService2.Volumes = []string{
"./config.json:/opt/explorer/app/platform/fabric/config.json",
"./connection-profile:/opt/explorer/app/platform/fabric/connection-profile",
fmt.Sprintf("%s:/tmp/crypto", configInput.CryptoConfigPath),
"walletstore:/opt/wallet",
}
explorerService2.Command = "sh -c \"node /opt/explorer/main.js && tail -f /dev/null\""
explorerService2.Ports = []string{
fmt.Sprintf("%d:8080", configInput.ExplorerPort),
}
var dependsOnMap map[string]DependsOn
dependsOnMap = make(map[string]DependsOn)
var dependsOn DependsOn
dependsOn.Condition = "service_healthy"
dependsOnMap[fmt.Sprintf("explorerdb.%s.com", configInput.NetworkName)] = dependsOn
explorerService2.DependsOn = dependsOnMap
explorerService2.Networks = []string{
fmt.Sprintf("%s.com", configInput.NetworkName),
}
explorerServiceMap[fmt.Sprintf("explorerdb.%s.com", configInput.NetworkName)] = explorerService1
explorerServiceMap[fmt.Sprintf("explorer.%s.com", configInput.NetworkName)] = explorerService2
explorerServices.Services = explorerServiceMap
var buffer bytes.Buffer
err = yaml.NewEncoder(&buffer).Encode(explorerServices)
if err != nil {
fmt.Println(err)
}
fid.Write([]byte(buffer.String()))
}
|
package main
import (
"adventofcode-solutions/2018/readinput"
"fmt"
)
// Part1 should calculate the multiplication of amount of string that has 2 repetitions and 3 repetitions
func Part1(input []string) int {
var numberOfTwices = 0
var numberOfTripples = 0
for _, line := range input {
occurrences := make(map[rune]int)
for _, char := range line {
val, ok := occurrences[char]
if ok {
occurrences[char] = val + 1
} else {
occurrences[char] = 1
}
}
var foundTwo = false
var foundThree = false
for _, value := range occurrences {
if value == 2 && !foundTwo {
numberOfTwices = numberOfTwices + 1
foundTwo = true
}
if value == 3 && !foundThree {
numberOfTripples = numberOfTripples + 1
foundThree = true
}
}
}
return numberOfTwices * numberOfTripples
}
func findSimilarLines(input []string) (string, string) {
for i := 0; i < len(input); i++ {
for j := i + 1; j < len(input); j++ {
lineA := input[i]
lineB := input[j]
numberOfErrors := 0
for k := 0; k < len(lineA); k++ {
if lineA[k] != lineB[k] {
numberOfErrors++
}
}
if numberOfErrors == 1 {
return lineA, lineB
}
}
}
return "", ""
}
// Part2 returns the overlap of chars between two strings
func Part2(input []string) string {
lineA, lineB := findSimilarLines(input)
var res = []byte{}
for i := 0; i < len(lineA); i++ {
if lineA[i] == lineB[i] {
res = append(res, lineA[i])
}
}
return string(res[:])
}
func main() {
input := readinput.ReadToArray("input.txt")
res1 := Part1(input)
res2 := Part2(input)
fmt.Println("Part 1:", res1)
fmt.Println("Part 2:", res2)
}
|
package main
import (
"testing"
)
func TestReverseWords(t *testing.T) {
}
|
package http_handlers
import (
"fmt"
"github.com/go-martini/martini"
"net/http"
"project/models"
"runtime/debug"
)
const (
AUTH_REQUIRED = "auth_required"
CACHE_REQUIRED = "cache_required"
DOCUMENT_REQUIRED = "document_required"
IGNORE_PAYLOAD = "ignore_payload"
PAYLOAD_REQUIRED = "payload_required"
PAYLOAD_OR_INTERFACE_REQUIRED = "payload_or_interface_required"
)
var (
S *models.Sessions
Router *martini.ClassicMartini
)
// This is a place where all panics are serving
// Also you can attach some middleware
func HttpHandler(
decorators []string,
handler_function func(*Http),
) func(
martini.Context,
martini.Params,
http.ResponseWriter,
*http.Request,
) {
return func(
context martini.Context,
params martini.Params,
writer http.ResponseWriter,
request *http.Request,
) {
_http := NewHttp()
_http.initResponse(
context,
params,
writer,
request,
decorators,
)
if len(_http.Errors) == 0 {
// Trigger main function
handler_function(_http)
}
_http.commitResponse()
defer func(_http_passed *Http) {
// Panic handling
if x := recover(); x != nil {
err := fmt.Errorf(
"%[1]s %[2]s caught panic: %v\n %s\n\n",
request.RemoteAddr,
request.URL.RequestURI(),
x,
debug.Stack(),
)
_http_passed.AddError(
err,
500,
)
}
}(_http)
}
}
|
//////////////////////////////////////////////////////////////////////////////////////////////
//
// Usage: go run AQMstat.go
//
// Summary: This program was written for use to statistically compare modeled and
// measured values of ambient air pollutants.
// Data time range: Jan-01-2005 through Dec-31-2005
// ISO 8601 Format: 2005-01-01 through 2005-12-31
//
// Inputs:
// SD = prompts user for the start date as a string in ISO 8601 format YYYY-MM-DD
// ED = prompts user for the end date as a string in ISO 8601 format YYYY-MM-D
// polntyp = prompts user for the type of pollution to be evaluated
//
// Outputs:
// ResultsYYYY-MM-DD HH:MM:SS.ssss 0000 TIMEZONE.csv = a CSV file of the results
// is created with a filename that includes a time-stamp of when the
// results were created with the date-time-timezone format shown above.
//
// Associated Files:
// GoNetCDF Package from http://www.unidata.ucar.edu/software/netcdf/docs/netcdf-c/
// GaryBoone's "GoStats" Statistics Package from https://github.com/GaryBoone/GoStats
// csvdata/folder/GeographicalLocationXX.csv
// csvdata/folder/GeoTemporalMeasurementXX.csv
// (where "folder" = pollutant type (Ozone, PM2.5)
// (where "XX" represents the region desired; 01-10 and 25.
// 11 per pollutant)
//
// Pollutant Types: "Ozone", "PM2.5"
//
// Region Identifiers:
// 01 Boston
// 02 New York City
// 03 Philidelphia
// 04 Atlanta
// 05 Chicago
// 06 Dallas
// 07 Kansas City
// 08 Denver
// 09 San Fransisco
// 10 Seattle
// 25 Mexico & Canada
//
// Version: 2012.06.25
//
// Written by: Steven J. Roste, EIT - June 2012
// Junior Scientist
// Department of Civil Engineering
// College of Science and Engineering
// University of Minnesota
// roste025@umn.edu
//
// References: 1. The constants, the function "AQMcompare", and everything below that
// function was written by Chris Tessum PhDc and modified
// by Steven Roste.
// 2. The "GoStats" Package was written by Gary Boone and is available at:
// https://github.com/GaryBoone/GoStats
// 3. GoNetCDF Package from
// http://www.unidata.ucar.edu/software/netcdf/docs/netcdf-c/
// 4. http://golang.org/
// 5. http://stackoverflow.com/
// 6. https://groups.google.com/forum/?fromgroups#!forum/golang-nuts
// 7. Summerfield, Mark. Programming in Go: Creating Applications for the 21st Century.
// Upper Saddle River, NJ: Addison-Wesley, 2012. Print.
// 8. Chisnall, David. The Go Programming Language: Phrasebook.
// Upper Saddle River, NJ: Addison-Wesley Professional, 2012. Print.
//
//////////////////////////////////////////////////////////////////////////////////////////////
package main
import(
"os"
"log"
"fmt"
"encoding/csv"
"strconv"
"bitbucket.org/ctessum/gonetcdf"
"errors"
"math"
"../GoStats"
"time"
)
// some information about the projection
const (
reflat = 40.0
reflon = -97.0
phi1 = 45.0
phi2 = 33.0
x_o = -2736000.
y_o = -2088000.
R = 6370997.
dx = 12000.
dy = 12000.
nx = 444
ny = 336
g = 9.8 // m/s2
dateFormat = "2006-01-02"
)
func main() {
// Which Pollutant to evaluate
var polntyp string
fmt.Println("Enter the Pollution Type (Ozone or PM2.5): ")
fmt.Scan(&polntyp)
// Coordinates
var SD string // Start Date in YYYY-MM-DD
var ED string // End Date in YYYY-MM-DD
fmt.Println("Enter the Start Date (YYYY-MM-DD): ")
fmt.Scan(&SD)
fmt.Println("Enter the Longitude Coordinate (YYYY-MM-DD): ")
fmt.Scan(&ED)
// Aquire Data
fmt.Println("Aquiring measured EPA data...")
valuDAT, locs := CSVreader(SD, ED, polntyp)
fmt.Println("Aquiring modeled data...")
valuMOD := AQMcompare(SD, ED, polntyp, locs)
// Process measured data
meanDAT := stats.StatsMean(valuDAT)
minDAT := stats.StatsMin(valuDAT)
maxDAT := stats.StatsMax(valuDAT)
countDAT := stats.StatsCount(valuDAT)
stdDAT := stats.StatsSampleStandardDeviation(valuDAT)
varDAT := stats.StatsSampleVariance(valuDAT)
skewDAT := stats.StatsSampleSkew(valuDAT)
// Process modeled data
meanMOD := stats.StatsMean(valuMOD)
minMOD := stats.StatsMin(valuMOD)
maxMOD := stats.StatsMax(valuMOD)
countMOD := stats.StatsCount(valuMOD)
stdMOD := stats.StatsSampleStandardDeviation(valuMOD)
varMOD := stats.StatsSampleVariance(valuMOD)
skewMOD := stats.StatsSampleSkew(valuMOD)
// Comparitive Stats
e := meanMOD - meanDAT
eabs := math.Abs(e)
bias := e / meanDAT
biasabs := math.Abs(bias)
// Print Stats to screen
fmt.Println(" ")
fmt.Println(" Pollutant Start Date End Date")
fmt.Println(" ", polntyp, " ", SD, " ", ED)
fmt.Println(" ")
fmt.Println(" Measured Modeled")
fmt.Println("Mean: ", meanDAT, " ", meanMOD)
fmt.Println("Min: ", minDAT, " ", minMOD)
fmt.Println("Max: ", maxDAT, " ", maxMOD)
fmt.Println("Count: ", countDAT, " ",countMOD)
fmt.Println("StdDev: ", stdDAT, " ", stdMOD)
fmt.Println("Variance: ", varDAT, " ", varMOD)
fmt.Println("Skew: ", skewDAT, " ", skewMOD)
fmt.Println(" ")
fmt.Println(" Error and Bias Statistics:")
fmt.Println("Error: ", e)
fmt.Println("Abs Err: ", eabs)
fmt.Println("Bias: ", bias)
fmt.Println("Abs Bias: ", biasabs)
fmt.Println(" ")
Results(data) // "data" must be in [][]string format with all headers and data contained
}
fun Results(results [][]string) {
// The results are output to a file that is named with a timestamp
// so that if multiple files are created, the previous results are
// not overwritten.
var fn string
fn = "Results"
datetime := time.Now()
filename := fmt.Sprint(fn, datetime.String(), ".csv")
fmt.Println("Creating File: ", filename, "...")
file, err := os.Create(filename)
if err != nil {
panic(err)
}
defer file.Close()
f := csv.NewWriter(file)
fmt.Println("Writing Results to file...")
f.WriteAll(results)
}
func CSVreader(SD string, ED string, polntyp string) []float64, [][]float64 {
count := 0
valuOUT := make([]float64,1)
var SDt time.Time
var EDt time.Time
SDt, err = time.Parse(dateFormat, SD)
if err != nil {
panic(err)
}
EDt, err = time.Parse(dateFormat, ED)
if err != nil {
panic(err)
}
EDf := EDt.AddDate(0,0,1)
//Cycle through all Location and Data files
for i := 1; i < 11; i++ {
filenum := i
////////////////////////////////////////////////////////////////////////////////////
//
// Determining which files to open
//
////////////////////////////////////////////////////////////////////////////////////
var fileloc string
var filedat string
switch {
case polntyp == "Ozone":
switch {
case filenum == 1:
fileloc = "csvdata/Ozone/GeographicalLocation01.csv"
filedat = "csvdata/Ozone/GeoTemporalMeasurement01.csv"
case filenum == 2:
fileloc = "csvdata/Ozone/GeographicalLocation02.csv"
filedat = "csvdata/Ozone/GeoTemporalMeasurement02.csv"
case filenum == 3:
fileloc = "csvdata/Ozone/GeographicalLocation03.csv"
filedat = "csvdata/Ozone/GeoTemporalMeasurement03.csv"
case filenum == 4:
fileloc = "csvdata/Ozone/GeographicalLocation04.csv"
filedat = "csvdata/Ozone/GeoTemporalMeasurement04.csv"
case filenum == 5:
fileloc = "csvdata/Ozone/GeographicalLocation05.csv"
filedat = "csvdata/Ozone/GeoTemporalMeasurement05.csv"
case filenum == 6:
fileloc = "csvdata/Ozone/GeographicalLocation06.csv"
filedat = "csvdata/Ozone/GeoTemporalMeasurement06.csv"
case filenum == 7:
fileloc = "csvdata/Ozone/GeographicalLocation07.csv"
filedat = "csvdata/Ozone/GeoTemporalMeasurement07.csv"
case filenum == 8:
fileloc = "csvdata/Ozone/GeographicalLocation08.csv"
filedat = "csvdata/Ozone/GeoTemporalMeasurement08.csv"
case filenum == 9:
fileloc = "csvdata/Ozone/GeographicalLocation09.csv"
filedat = "csvdata/Ozone/GeoTemporalMeasurement09.csv"
case filenum == 10:
fileloc = "csvdata/Ozone/GeographicalLocation10.csv"
filedat = "csvdata/Ozone/GeoTemporalMeasurement10.csv"
case filenum == 11:
fileloc = "csvdata/Ozone/GeographicalLocation25.csv"
filedat = "csvdata/Ozone/GeoTemporalMeasurement25.csv"
default:
panic("No file found.")
}
case polntyp == "PM2.5":
switch {
case filenum == 1:
fileloc = "csvdata/PM2.5/GeographicalLocation01.csv"
filedat = "csvdata/PM2.5/GeoTemporalMeasurement01.csv"
case filenum == 2:
fileloc = "csvdata/PM2.5/GeographicalLocation02.csv"
filedat = "csvdata/PM2.5/GeoTemporalMeasurement02.csv"
case filenum == 3:
fileloc = "csvdata/PM2.5/GeographicalLocation03.csv"
filedat = "csvdata/PM2.5/GeoTemporalMeasurement03.csv"
case filenum == 4:
fileloc = "csvdata/PM2.5/GeographicalLocation04.csv"
filedat = "csvdata/PM2.5/GeoTemporalMeasurement04.csv"
case filenum == 5:
fileloc = "csvdata/PM2.5/GeographicalLocation05.csv"
filedat = "csvdata/PM2.5/GeoTemporalMeasurement05.csv"
case filenum == 6:
fileloc = "csvdata/PM2.5/GeographicalLocation06.csv"
filedat = "csvdata/PM2.5/GeoTemporalMeasurement06.csv"
case filenum == 7:
fileloc = "csvdata/PM2.5/GeographicalLocation07.csv"
filedat = "csvdata/PM2.5/GeoTemporalMeasurement07.csv"
case filenum == 8:
fileloc = "csvdata/PM2.5/GeographicalLocation08.csv"
filedat = "csvdata/PM2.5/GeoTemporalMeasurement08.csv"
case filenum == 9:
fileloc = "csvdata/PM2.5/GeographicalLocation09.csv"
filedat = "csvdata/PM2.5/GeoTemporalMeasurement09.csv"
case filenum == 10:
fileloc = "csvdata/PM2.5/GeographicalLocation10.csv"
filedat = "csvdata/PM2.5/GeoTemporalMeasurement10.csv"
case filenum == 11:
fileloc = "csvdata/PM2.5/GeographicalLocation25.csv"
filedat = "csvdata/PM2.5/GeoTemporalMeasurement25.csv"
default:
panic("No file found.")
}
default:
panic("Pollutant data not found.")
}
////////////////////////////////////////////////////////////////////////////////////
//
// Extracting Locations from the GeographicalLocaionXX.csv file
//
////////////////////////////////////////////////////////////////////////////////////
// Open Location CSV file, handle any errors
filename1, err := os.Open(fileloc) // folder/pollutant/filename.csv
if err != nil {
panic(err)
}
defer filename1.Close() // close file when finished
r1 := csv.NewReader(filename1)
lines1, err := r1.ReadAll() // Read to EOF and store in lines2
if err != nil {
panic(err)
}
// define data variables to be extracted
idtag := make([]int, len(lines1)-1) // define file Id tag
label1 := make([]string, 2)
label2 := make([]string, 2)
lats := make([]float64, len(lines1)-1) // define lats
lngs := make([]float64, len(lines1)-1) // define lngs
// loop through all rows to extract data and convert to float64 values
for j, row1 := range lines1 {
if j == 0 {
label1[1] = row1[0]
label2[1] = row1[1]
} else {
lats[j-1], err = strconv.ParseFloat(row1[0],64) // store row value from column 1
if err != nil {
panic(err)
}
lngs[j-1], err = strconv.ParseFloat(row1[1],64) // store row value from column 2
if err != nil {
panic(err)
}
idtag[j-1], err = strconv.Atoi(row1[3]) // store file Id tag number for reference
if err != nil {
panic(err)
}
}
}
////////////////////////////////////////////////////////////////////////////////////
//
// Extracting Data from the corresponding GeoTemporalMeasurementXX.csv file
//
////////////////////////////////////////////////////////////////////////////////////
// extract correlated data from same region
// Open Measurement CSV file, handle any errors
filename2, err := os.Open(filedat) // folder/pollutant/filename.csv
if err != nil {
panic(err)
}
defer filename2.Close() // close file when finished
r2 := csv.NewReader(filename2)
lines2, err := r2.ReadAll() // Read to EOF and store in lines2
if err != nil {
log.Fatalf("error reading all lines: %v", err)
}
// define data variables to be extracted
label3 := make([]string, 2)
label4 := make([]string, 2)
label5 := make([]string, 2)
label6 := make([]string, 2)
label7 := make([]string, 2)
label8 := make([]string, 2)
label9 := make([]string, 2)
poln := make([]string, len(lines2)-1) // pollution type
date := make([]string, len(lines2)-1) // time of measurement
time := make([]string, len(lines2)-1) // local time
zone := make([]string, len(lines2)-1) // local time zone
valu := make([]float64, len(lines2)-1) // measurment value
unit := make([]string, len(lines2)-1) // unit of measurement
resl := make([]string, len(lines2)-1) // time resolution
// loop through all rows to extract data and convert measurements to float64 values
for k, line2 := range lines2 {
if k == 0 {
label3[1] = line2[1]
label4[1] = line2[2]
label5[1] = line2[3]
label6[1] = line2[4]
label7[1] = line2[6]
label8[1] = line2[7]
label9[1] = line2[12]
continue
} else {
poln[k-1] = line2[1] // store row values from column 2
date[k-1] = line2[2] // store row values from column 3
time[k-1] = line2[3] // etc
zone[k-1] = line2[4]
valu[k-1], err = strconv.ParseFloat(line2[6],64) // store row value from column 2
if err != nil {
panic(err)
}
unit[k-1] = line2[7]
resl[k-1] = line2[12]
}
}
////////////////////////////////////////////////////////////////////////////////////
//
// Display relevant data in a table format to command window
//
////////////////////////////////////////////////////////////////////////////////////
// display all extracted data
fmt.Println(fileloc, filedat)
fmt.Println("[ID Tag]", label1, label2, label3, label4, label5, label6, label7, label8, label9)
for w := 0; w < len(idtag)-2; w++ { // loop through all data
if SDt <= time.Parse(dateFormat, date[w]) && EDt >= time.Parse(dateFormat, date[w]) {
fmt.Println(" ", idtag[w], " ", lats[w], " ", lngs[w], " ", poln[w], " ", date[w], " ", time[w], " ", zone[w], " ", valu[w], " ", unit[w], " ", resl[w]) // print to screen data table
if count == 0 {
valuOUT[count] = valu[w]
} else {
valuOUT = append(valuOUT, valu[w])
}
count = count + 1
}
}
}
return valuOUT, locs
}
/////////////////////////////////////////////////////////////////
//
// AQMcompare and related functions
//
/////////////////////////////////////////////////////////////////
func AQMcompare(SD string, ED string, polntyp string, locs [][]float64) []float64 {
flag := 0 // 0 for Ozone, 1 for PM2.5
if polntyp == "PM2.5" {
flag = 1
}
count := 0
valuOUT :=make([]float64,1)
var SDt time.Time
var EDt time.Time
pols := [...]string{"PM2_5_DRY", "o3"}
SDt, err = time.Parse(dateFormat, SD)
if err != nil {
panic(err)
}
EDt, err = time.Parse(dateFormat, ED)
if err != nil {
panic(err)
}
EDf := EDt.AddDate(0,0,1)
for i := SDt; i != EDf; {
fn := "wrfout/wrfout_d01_"
cdate := i.Format(dateFormat)
filename := fmt.Sprint(fn, cdate, "_00_00_00")
// Open WRF file, handle any errors
f, e := gonetcdf.Open(filename, "nowrite")
if e != nil {
fmt.Println("No wrf file available for: ", cdate)
continue
}
// get the necessary data for calculating layer heights
fmt.Println("Getting the base state geopotential...")
PHB, e := NewWRFarray(f, "PHB")
if e != nil {
panic(e)
}
fmt.Println("Getting the perturbation geopotential...")
PH, e := NewWRFarray(f, "PH")
if e != nil {
panic(e)
}
for _, pol := range pols {
fmt.Printf("Getting data for %v...\n", pol)
data, e := NewWRFarray(f, pol)
if e != nil {
panic(e)
}
for i := 0; i < len(locs)-1; i++ {
lat, lon := locs(i)
for h := 0; h < 24; h++ {
height := 50. // meters
/////////////////////////////////////////////////////
ycell, xcell, e := Lambert(lat, lon, reflat, reflon, phi1,
phi2, x_o, y_o, R, dx, dy, nx, ny)
if e != nil {
panic(e)
}
layer, e := LayerHeight(height, ycell, xcell, h, &PH, &PHB)
index := []int{h, layer, ycell, xcell}
conc := data.GetVal(index)
// Which values to store
if flag == 0 && pol == "o3" {
// store Ozone values
if count == 0 {
valuOUT[h] = conc
} else {
valuOUT = append(valuOUT, conc)
}
// print the result
fmt.Printf("The value for pollutant %v at %v, %v for hour %v in layer %v is %v\n",
pol, lon, lat, h, layer, conc)
count = count + 1
} else if flag == 1 && pol == "PM2_5_DRY" {
//store PM2.5 values
if count == 0 {
valuOUT[h] = conc
} else {
valuOUT = append(valuOUT, conc)
}
// print the result
fmt.Printf("The value for pollutant %v at %v, %v for hour %v in layer %v is %v\n",
pol, lon, lat, h, layer, conc)
count = count + 1
}
}
}
}
i = i.AddDate(0,0,1)
}
return valuOUT
}
func NewWRFarray(f gonetcdf.NCfile, name string) (
out WRFarray, e error) {
out.Dims, e = f.VarSize(name)
if e != nil {
return
}
out.Data, e = f.GetVarDouble(name)
if e != nil {
return
}
return
}
type WRFarray struct {
Data []float64
Dims []int
Name string
}
// Function IndexTo1D takes an array of indecies for a
// multi-dimensional array and the dimensions of that array,
// calculates the 1D-array index, and returns the corresponding value.
func (d *WRFarray) GetVal(index []int) (val float64) {
index1d := 0
for i := 0; i < len(index); i++ {
mul := 1
for j := i + 1; j < len(index); j++ {
mul = mul * d.Dims[j]
}
index1d = index1d + index[i]*mul
}
return d.Data[index1d]
}
// Function Lambert takes the latitude and longitude of a point plus
// the definition of a lambert conic conformal projection as inputs
// (reflat and reflon are the reference coordinates of the projection,
// phi1 and phi2 are the two other reference latitudes, x_o and y_o
// are the coordinates in meters of the lower left corner of the
// grid (in meters), R is the radius of the Earth (in meters),
// dx and dy specify the size of each grid cell (in meters), and
// nx and ny specify the number of grid cells in each direction.
// The function returns returns the location of the grid cell
// containing the input latitude.
func Lambert(lat float64, lon float64, reflat float64, reflon float64,
phi1 float64, phi2 float64, x_o float64, y_o float64,
R float64, dx float64, dy float64, nx int, ny int) (
ycell int, xcell int, err error) {
lon = lon * math.Pi / 180.
lat = lat * math.Pi / 180.
reflat = reflat * math.Pi / 180.
reflon = reflon * math.Pi / 180.
phi1 = phi1 * math.Pi / 180.
phi2 = phi2 * math.Pi / 180.
n := math.Log(math.Cos(phi1)/math.Cos(phi2)) /
math.Log(math.Tan(0.25*math.Pi+0.5*phi2)/
math.Tan(0.25*math.Pi+0.5*phi1))
F := math.Cos(phi1) * math.Pow(
math.Tan(0.25*math.Pi+0.5*phi1), n) / n
rho := F * math.Pow((1./math.Tan(0.25*math.Pi+0.5*lat)), n)
rho_o := F * math.Pow(1./math.Tan(0.25*math.Pi+0.5*reflat), n)
x := rho * math.Sin(n*(lon-reflon)) * R
y := (rho_o - rho*math.Cos(n*(lon-reflon))) * R
xcell = int(math.Floor((x - x_o) / dx))
ycell = int(math.Floor((y - y_o) / dy))
if xcell >= nx || ycell >= ny || xcell < 0 || ycell < 0 {
fmt.Println(xcell)
fmt.Println(ycell)
err = errors.New("Cell number out of bounds")
}
return
}
func LayerHeight(height float64, ycell int, xcell int, hour int,
PH *WRFarray, PHB *WRFarray) (layer int, err error) {
for k := 1; k < PH.Dims[1]; k++ {
PHi := []int{hour, k, ycell, xcell}
PHBi := []int{hour, k , ycell, xcell}
layerHeight := (PH.GetVal(PHi) + PHB.GetVal(PHBi)) / g
if layerHeight < height {
layer = k - 1
} else {
return
}
}
errors.New("Height is above top layer")
return
} |
package mysql
import (
"database/sql"
_ "github.com/go-sql-driver/mysql" // dbDriver
)
// DBConn dataSourceName : "user:pwd@host:port/databasename"
func DBConn(dataSourceName string) (db *sql.DB) {
dbDriver := "mysql" // Database driver
// Realize the connection with mysql driver
db, err := sql.Open(dbDriver, dataSourceName)
// If error stop the application
if err != nil {
panic(err)
}
// Return db object to be used by another functions
return db
}
|
package main
import (
"context"
"github.com/ktsstudio/selectel-exporter/pkg/config"
"github.com/ktsstudio/selectel-exporter/pkg/exporter"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
exporterConfig, err := config.Parse()
if err != nil {
log.Println(err)
os.Exit(1)
}
exp, err := exporter.Init(exporterConfig, 60)
if err != nil {
log.Println(err)
os.Exit(1)
}
handler := promhttp.HandlerFor(exporter.Registry, promhttp.HandlerOpts{})
http.Handle("/metrics", handler)
srv := &http.Server{Addr: "0.0.0.0:9100", Handler: nil}
go func() {
log.Println(srv.ListenAndServe())
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
exp.Stop()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
err = srv.Shutdown(ctx)
if err != nil {
log.Fatal(err)
}
}
|
package model
import (
"sync"
"net"
)
type Device struct{
Uuid string
Imei string
Conn net.Conn
}
type UserCache struct{
sync.RWMutex
cache map[string] *Device
}
func (cache *UserCache) Init(){
cache.cache = make(map[string] *Device)
}
func (cache *UserCache) Add(uuid string, device *Device){
cache.Lock()
defer cache.Unlock()
cache.cache[uuid] = device
}
func (cache *UserCache) Get(uuid string) (device *Device, flag bool){
cache.Lock()
defer cache.Unlock()
value, ok := cache.cache[uuid]
if !ok{
return nil, false
}
return value, true
}
func (cache *UserCache) Remove(uuid string){
cache.Lock()
defer cache.Unlock()
}
func (cache *UserCache) GetCount() int {
cache.Lock()
defer cache.Unlock()
return len(cache.cache)
}
|
package internal
import (
"github.com/hashicorp/go-plugin"
)
func NewHandshakeConfig(pluginType string) plugin.HandshakeConfig {
return plugin.HandshakeConfig{
ProtocolVersion: 1,
MagicCookieKey: "gatekeeper|plugin-type",
MagicCookieValue: pluginType,
}
}
|
package template
import (
"bytes"
"fmt"
"path/filepath"
"text/template"
"github.com/criteo/graphite-remote-adapter/ui"
)
func getTemplate(name string) (string, error) {
baseTmpl, err := ui.Asset("templates/_base.html")
if err != nil {
return "", fmt.Errorf("error reading base template: %s", err)
}
pageTmpl, err := ui.Asset(filepath.Join("templates", name))
if err != nil {
return "", fmt.Errorf("error reading page template %s: %s", name, err)
}
return string(baseTmpl) + string(pageTmpl), nil
}
// ExecuteTemplate renders template for given name with provided data.
func ExecuteTemplate(name string, data interface{}) ([]byte, error) {
text, err := getTemplate(name)
if err != nil {
return nil, err
}
tmpl := template.New(name).Funcs(template.FuncMap(TmplFuncMap))
tmpl, err = tmpl.Parse(text)
if err != nil {
return nil, err
}
var buffer bytes.Buffer
err = tmpl.Execute(&buffer, data)
if err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
|
package main
import (
"errors"
"log"
)
type WithdrawCommand interface {
Execute() error
Undo() error
Redo() error
}
type CommandManager struct {
UndoCommand []WithdrawCommand
RedoCommand []WithdrawCommand
}
func NewCommandManager() CommandManager{
return CommandManager{
UndoCommand:make([]WithdrawCommand,0),
RedoCommand:make([]WithdrawCommand,0),
}
}
func (cmdManager *CommandManager)ExecuteCmd(cmd WithdrawCommand)error{
if err:=cmd.Execute();err!=nil{
return err
}
cmdManager.UndoCommand = append(cmdManager.UndoCommand,cmd)
if len(cmdManager.RedoCommand)!=0{
cmdManager.clearRedoCmd()
}
return nil
}
func (cmdManager *CommandManager)Undo()error{
if err:=cmdManager.UndoCommand[len(cmdManager.UndoCommand)-1].Undo();err!=nil{
return err
}
cmdManager.UndoCommand = cmdManager.UndoCommand[:len(cmdManager.UndoCommand)-1]
return nil
}
func (cmdmanager *CommandManager)UndoAll()error{
for !cmdmanager.isUndoCmdEmpty(){
err:=cmdmanager.Undo()
if err!=nil{
return err
}
}
return nil
}
func (cmdManager *CommandManager)Redo()error{
return nil
}
func (cmdManager *CommandManager)isUndoCmdEmpty()bool{
return len(cmdManager.UndoCommand) == 0
}
func (cmdManager *CommandManager)clearRedoCmd(){
cmdManager.RedoCommand = cmdManager.RedoCommand[0:0]
}
type WithdrawArgs struct {
WithdrawAmount int64
TraeNo string
Uid int64
}
type AddWithdrawRecordCmd struct {
Args WithdrawArgs
WantErr bool
}
func (command *AddWithdrawRecordCmd)Execute()error{
command.Args.TraeNo = "123456"
log.Printf("添加提现记录,用户ID:%d,提现金额:%d 交易单号:%v\n",
command.Args.Uid,command.Args.WithdrawAmount,command.Args.TraeNo)
if command.WantErr{
return errors.New("模拟[添加提现记录]错误\n")
}
return nil
}
func (command *AddWithdrawRecordCmd)Undo()error{
log.Printf("回滚提现记录,用户ID:%v,提现金额:%d,交易单号:%v\n",
command.Args.Uid,command.Args.WithdrawAmount,command.Args.TraeNo)
return nil
}
func (command *AddWithdrawRecordCmd)Redo()error{
log.Printf("redo 提现记录,用户ID:%v,提现金额:%v,交易单号:%v\n",
command.Args.Uid,command.Args.WithdrawAmount,command.Args.TraeNo)
return nil
}
type DeductAmount struct {
Args WithdrawArgs
WantErr bool
}
func (command *DeductAmount)Execute()error{
log.Printf("扣款,用户ID:%v 扣款金额:%v 交易单号:%v\n",
command.Args.Uid,command.Args.WithdrawAmount,command.Args.TraeNo)
if command.WantErr{
return errors.New("模拟扣款失败\n")
}
return nil
}
func(command *DeductAmount)Undo()error{
log.Printf("回滚扣款,用户ID:%v,扣款金额:%v,交易单号:%v\n",
command.Args.Uid,command.Args.WithdrawAmount,command.Args.TraeNo)
return nil
}
func (command *DeductAmount)Redo()error{
log.Printf("redo 扣款,用户ID:%v,提现金额:%v,交易单号:%v\n",
command.Args.Uid,command.Args.WithdrawAmount,command.Args.TraeNo)
return nil
}
type DoWithdrawCommand struct {
Args WithdrawArgs
WantErr bool
}
func(command *DoWithdrawCommand)Execute()error{
log.Printf("微信大钱,用户ID:%v,金额:%v ,交易单号:%v \n",
command.Args.Uid,command.Args.WithdrawAmount,command.Args.TraeNo)
if command.WantErr{
return errors.New("模拟扣款失败")
}
return nil
}
func (command *DoWithdrawCommand)Undo()error{
log.Printf("undo 微信大钱,用户ID:%v 金额:%v,交易单号:%v\n",
command.Args.Uid,command.Args.WithdrawAmount,command.Args.TraeNo)
return nil
}
func (command *DoWithdrawCommand)Redo()error{
log.Printf("redo 微信打钱,用户ID:%v,金额:%v ,交易单号:%v\n",
command.Args.Uid,command.Args.WithdrawAmount,command.Args.TraeNo)
return nil
}
func main(){
tests:=[]struct{
Name string
wantAddrecordErr bool
wantDeductErr bool
wantDoWithdraw bool
args WithdrawArgs
}{
{
"正常提现",
false,
false,
false,
WithdrawArgs{
WithdrawAmount:100,
Uid:1,
},
},{
"添加提现记录失败",
true,
false,
false,
WithdrawArgs{
WithdrawAmount:100,
Uid:1,
},
},
{
"扣款失败",
false,
true,
false,
WithdrawArgs{
WithdrawAmount:100,
Uid:1,
},
},{
"提现打款失败",
false,
false,
true,
WithdrawArgs{
WithdrawAmount:100,
Uid:1,
},
},
}
for _,test:=range tests{
tt:=test
cmdManager:=NewCommandManager()
var err error
//添加记录
addWithdrawRecordCmd:=&AddWithdrawRecordCmd{
Args:tt.args,
WantErr:tt.wantAddrecordErr,
}
err=cmdManager.ExecuteCmd(addWithdrawRecordCmd)
tt.args.TraeNo = addWithdrawRecordCmd.Args.TraeNo
if tt.wantAddrecordErr&&err!=nil{
_=cmdManager.UndoAll()
return
}
//扣款
err=cmdManager.ExecuteCmd(&DeductAmount{
Args:tt.args,
WantErr:tt.wantDeductErr,
})
if tt.wantDeductErr&&err!=nil{
_=cmdManager.UndoAll()
return
}
//打钱
err=cmdManager.ExecuteCmd(&DoWithdrawCommand{
Args:tt.args,
WantErr:tt.wantDoWithdraw,
})
if tt.wantDoWithdraw&&err!=nil{
_=cmdManager.UndoAll()
return
}
}
}
|
package util
import (
"math"
"path"
"runtime"
"sync"
"time"
"github.com/OopsMouse/arbitgo/models"
"github.com/jpillora/backoff"
log "github.com/sirupsen/logrus"
)
func Index(vs []string, t string) int {
for i, v := range vs {
if v == t {
return i
}
}
return -1
}
func Include(vs []string, t string) bool {
return Index(vs, t) >= 0
}
func Any(vs []string, f func(string) bool) bool {
for _, v := range vs {
if f(v) {
return true
}
}
return false
}
func All(vs []string, f func(string) bool) bool {
for _, v := range vs {
if !f(v) {
return false
}
}
return true
}
func Filter(vs []string, f func(string) bool) []string {
vsf := make([]string, 0)
for _, v := range vs {
if f(v) {
vsf = append(vsf, v)
}
}
return vsf
}
func Map(vs []string, f func(string) string) []string {
vsm := make([]string, len(vs))
for i, v := range vs {
vsm[i] = f(v)
}
return vsm
}
type Set struct {
lock *sync.Mutex
buff map[string]struct{}
}
func NewSet() *Set {
return &Set{
lock: new(sync.Mutex),
buff: map[string]struct{}{},
}
}
func (s *Set) Append(i string) {
defer s.lock.Unlock()
s.lock.Lock()
s.buff[i] = struct{}{}
}
func (s *Set) Remove(i string) {
defer s.lock.Unlock()
s.lock.Lock()
if s.Include(i) {
delete(s.buff, i)
}
}
func (s *Set) Include(i string) bool {
return Include(s.ToSlice(), i)
}
func (s *Set) ToSlice() []string {
keys := make([]string, 0, len(s.buff))
for k := range s.buff {
keys = append(keys, k)
}
return keys
}
func GetCurrentFile() string {
_, filename, _, _ := runtime.Caller(1)
return filename
}
func GetCurrentDir() string {
_, filename, _, _ := runtime.Caller(1)
return path.Dir(filename)
}
type Operation func() error
func BackoffRetry(retry int, op Operation) error {
b := &backoff.Backoff{
Max: 5 * time.Minute,
}
var err error
for i := 0; i < retry; i++ {
err = op()
if err == nil {
return nil
}
d := b.Duration()
time.Sleep(d)
}
return err
}
func Floor(a float64, b float64) float64 {
return float64(math.Trunc(a/b)) * b
}
func LogOrder(order models.Order) {
log.Info("-----------------------------------------------")
log.Info(" OrderID : ", order.ID)
log.Info(" Symbol : ", order.Symbol.String())
log.Info(" Side : ", order.Side)
log.Info(" Type : ", order.OrderType)
log.Info(" Price : ", order.Price)
log.Info(" Quantity : ", order.Quantity)
log.Info(" Step : ", order.Symbol.StepSize)
log.Info("-----------------------------------------------")
}
func LogOrders(orders []models.Order) {
for _, order := range orders {
LogOrder(order)
}
}
func Delete(s []*models.Depth, i int) []*models.Depth {
ret := []*models.Depth{}
ret = append(ret, s[:i]...)
ret = append(ret, s[i+1:]...)
return ret
}
|
package persistence
import (
"fmt"
"os"
"strings"
)
var (
filename string
)
func RequestFilename() string {
fmt.Printf("Please, insert the path for the file to load:\n")
var msg string
fmt.Scanf("%s\n", &msg)
return msg
}
func ObtainSelectionList(filename string) []string {
var content string = ""
content = readTextFile(filename)
return strings.Split(content, "\n")
}
func readTextFile(filename string) string {
f, err := os.Open(filename)
check(err)
defer f.Close()
finfo, err := os.Stat(filename)
check(err)
size := finfo.Size()
content := make([]byte, size)
_ , err = f.Read(content)
check(err)
return string(content)
}
func check(e error) {
if e != nil {
panic(e)
}
}
func handlePanic() {
if r := recover(); r != nil {
fmt.Println(r)
}
}
|
package zhlog
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/connext-cs/pub/paasdb"
"github.com/go-xorm/xorm"
)
// SLog 日志表
type SLog struct {
LogId int `json:"log_id"` //日志ID
LogResId int `json:"log_res_id"` //资源ID
LogResName string `json:"log_res_name"` //资源名称
LogTraingId string `json:"log_traing_id"` //业务跟踪ID
LogBusinessId string `json:"log_business_id"` //业务主键
LogMicroUri string `json:"log_micro_uri"` //微服务URI
LogLevel string `json:"log_level"` //日志级别
LogType string `json:"log_type"` //日志类型
LogMessage string `json:"log_message"` //日志内容
LogIp string `json:"log_ip"` //请求IP
LogTakeTime int `json:"log_take_time"` //耗时
AppId int `json:"app_id"` //应用ID
OrgId int `json:"org_id"` //所属机构
Deleted int `json:"deleted"` //删除标志
CreatedBy string `json:"created_by"` //创建人
CreatedTime time.Time `json:"created_time"` //创建时间
}
func getSession() (session *xorm.Session) {
orm := paasdb.CloudprojectEngine()
orm.ShowSQL(false)
session = orm.NewSession()
defer session.Close()
err := session.Begin()
Assert(err)
return
}
// ErrorToDB Error log inTo DB
func ErrorToDB(traingID, businessID, logType string, logTakeTime int, msg string, args ...interface{}) {
message := Trace("[ERROR]"+msg, args...).Error()
if len(traingID) > 0 {
message += "\nTRACE_ID:" + traingID
}
hostName, _ := os.Hostname()
session := getSession()
_, err := session.InsertOne(&SLog{
// LogResId :,
LogResName: filepath.Base(os.Args[0]),
LogTraingId: traingID,
LogBusinessId: businessID,
LogMicroUri: filepath.Base(os.Args[0]),
LogLevel: "ERROR",
LogType: logType,
LogMessage: message,
LogIp: hostName,
LogTakeTime: logTakeTime,
// AppId :,
// OrgId :,
CreatedTime: time.Now(),
})
if err != nil {
session.Rollback()
panic(err)
}
session.Commit()
}
// InfoToDB info into DB
func InfoToDB(traingID, businessID, logType string, LogTakeTime int, msg string, args ...interface{}) {
if len(args) > 0 {
msg = fmt.Sprintf(msg, args...)
}
hostName, _ := os.Hostname()
session := getSession()
_, err := session.InsertOne(&SLog{
// LogResId :,
LogResName: filepath.Base(os.Args[0]),
LogTraingId: traingID,
LogBusinessId: businessID,
LogMicroUri: filepath.Base(os.Args[0]),
LogLevel: "INFO",
LogType: logType,
LogMessage: msg,
LogIp: hostName,
LogTakeTime: LogTakeTime,
// AppId :,
// OrgId :,
CreatedTime: time.Now(),
})
if err != nil {
session.Rollback()
panic(err)
}
session.Commit()
}
|
// Copyright (c) 2017 Intel 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 main
import (
"log/syslog"
"time"
"github.com/sirupsen/logrus"
lSyslog "github.com/sirupsen/logrus/hooks/syslog"
)
// sysLogHook wraps a syslog logrus hook and a formatter to be used for all
// syslog entries.
//
// This is necessary to allow the main logger (for "--log=") to use a custom
// formatter ("--log-format=") whilst allowing the system logger to use a
// different formatter.
type sysLogHook struct {
shook *lSyslog.SyslogHook
formatter logrus.Formatter
}
func (h *sysLogHook) Levels() []logrus.Level {
return h.shook.Levels()
}
// Fire is responsible for adding a log entry to the system log. It switches
// formatter before adding the system log entry, then reverts the original log
// formatter.
func (h *sysLogHook) Fire(e *logrus.Entry) (err error) {
formatter := e.Logger.Formatter
e.Logger.Formatter = h.formatter
err = h.shook.Fire(e)
e.Logger.Formatter = formatter
return err
}
func newSystemLogHook(network, raddr string) (*sysLogHook, error) {
hook, err := lSyslog.NewSyslogHook(network, raddr, syslog.LOG_INFO, name)
if err != nil {
return nil, err
}
return &sysLogHook{
formatter: &logrus.TextFormatter{
TimestampFormat: time.RFC3339Nano,
},
shook: hook,
}, nil
}
// handleSystemLog sets up the system-level logger.
func handleSystemLog(network, raddr string) error {
hook, err := newSystemLogHook(network, raddr)
if err != nil {
return err
}
kataLog.Logger.Hooks.Add(hook)
return nil
}
|
package ant
import (
"bufio"
"fmt"
"io"
"math"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
func (e *Env) newAnt(pos int) *Ant {
ant := new(Ant)
ant.env = e
ant.visited = make([][]int, len(e.weight))
for i := 0; i < len(e.weight); i++ {
ant.visited[i] = make([]int, len(e.weight))
for j := 0; j < len(e.weight[i]); j++ {
ant.visited[i][j] = e.weight[i][j]
}
}
ant.position = pos
ant.been = make([][]bool, len(e.weight))
for i := range ant.been {
ant.been[i] = make([]bool, len(e.weight))
}
return ant
}
func newEnv(f string) *Env {
e := new(Env)
e.weight = getWeights(f)
e.pheromon = make([][]float64, len(e.weight), len(e.weight))
for i := 0; i < len(e.pheromon); i++ {
e.pheromon[i] = make([]float64, len(e.weight[i]))
for j := range e.pheromon[i] {
e.pheromon[i][j] = 0.5
}
}
e.alpha = 3.0
e.betta = 7.0
e.q = 20.0
e.p = 0.6
return e
}
// getWeights - read graph from file
func getWeights(f string) [][]int {
g := make([][]int, 0)
file, err := os.Open(f)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer file.Close()
reader := bufio.NewReader(file)
for {
str, err := reader.ReadString('\n')
if err == io.EOF {
break
}
str = strings.TrimSuffix(str, "\n")
str = strings.TrimSuffix(str, "\r")
str = strings.TrimRight(str, " ")
//fmt.Printf(str)
cur := strings.Split(str, " ")
path := make([]int, 0)
for _, i := range cur {
i, err := strconv.Atoi(i)
if err != nil {
fmt.Println(err)
}
path = append(path, i)
}
g = append(g, path)
}
return g
}
// getProbability - probability of path being choosen
func (ant *Ant) getProbability() []float64 {
p := make([]float64, 0)
var sum float64
for i, l := range ant.visited[ant.position] {
if l != 0 {
d := math.Pow((float64(1)/float64(l)), ant.env.alpha) * math.Pow(ant.env.pheromon[ant.position][i], ant.env.betta)
p = append(p, d)
sum += d
} else {
p = append(p, 0)
}
}
for _, l := range p {
l = l / sum
}
return p
}
// pickWay - choose way with probability
func pickWay(p []float64) int {
var sum float64
for _, j := range p {
sum += j
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
rn := r.Float64() * sum
sum = 0
for i, j := range p {
if rn > sum && rn < sum+j {
return i
}
sum += j
}
return -1
}
// renewPheromon - renew pheromon after move
func (ant *Ant) renewPheromon() {
var delta float64
delta = 0
for k := 0; k < len(ant.env.pheromon); k++ {
for i, j := range ant.env.pheromon[k] {
if ant.env.weight[k][i] != 0 {
if ant.been[k][i] {
delta = ant.env.q / float64(ant.env.weight[k][i])
} else {
delta = 0
}
ant.env.pheromon[k][i] = (1 - ant.env.p) * (float64(j) + delta)
}
if ant.env.pheromon[k][i] <= 0 {
ant.env.pheromon[k][i] = 0.1
}
}
}
}
// moveWay - perform move
func (ant *Ant) moveWay(path int) {
for i := range ant.visited {
ant.visited[i][ant.position] = 0
}
ant.been[ant.position][path] = true
ant.position = path
}
// moveAnt - start moving
func (ant *Ant) moveAnt() {
for {
prob := ant.getProbability()
way := pickWay(prob)
if way == -1 {
break
}
ant.moveWay(way)
ant.renewPheromon()
}
}
// getDistance - distance travelled
func (ant *Ant) getDistance() int {
var distance int
for i, j := range ant.been {
for k, z := range j {
if z {
distance += ant.env.weight[i][k]
}
}
}
return distance
}
// StartAnt - ant
func StartAnt(env *Env, days int) []int {
short := make([]int, len(env.weight))
for n := 0; n < days; n++ {
for i := 0; i < len(env.weight); i++ {
ant := env.newAnt(i)
ant.moveAnt()
cur := ant.getDistance()
if (short[i] == 0) || (cur < short[i]) {
short[i] = cur
}
}
}
return short
}
// Brute - brute
func Brute(f string) []int {
weight := getWeights(f)
path := make([]int, 0)
res := make([]int, len(weight))
// for every node
for k := 0; k < len(weight); k++ {
ways := make([][]int, 0)
_ = getRoutes(k, weight, path, &ways)
sum := 1000
curr := 0
ind := 0
for i := 0; i < len(ways); i++ {
curr = 0
for j := 0; j < len(ways[i])-1; j++ {
curr += weight[ways[i][j]][ways[i][j+1]]
}
if curr < sum {
sum = curr
ind = i
}
}
res[k] = sum
ind = 0
_ = ind
}
return res
}
func contains(s []int, e int) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
// getRoutes - find all ways
func getRoutes(pos int, weight [][]int, path []int, routes *[][]int) []int {
path = append(path, pos)
if len(path) < len(weight) {
for i := 0; i < len(weight); i++ {
if !(contains(path, i)) {
_ = getRoutes(i, weight, path, routes)
}
}
} else {
*routes = append(*routes, path)
}
return path
}
|
package mock
import (
"context"
"github.com/google/uuid"
"github.com/odpf/optimus/job"
"github.com/odpf/optimus/core/tree"
"github.com/odpf/optimus/core/progress"
"github.com/odpf/optimus/models"
"github.com/odpf/optimus/store"
"github.com/odpf/optimus/store/local"
"github.com/stretchr/testify/mock"
)
// ProjectJobSpecRepoFactory to manage job specs at project level
type ProjectJobSpecRepoFactory struct {
mock.Mock
}
func (repo *ProjectJobSpecRepoFactory) New(proj models.ProjectSpec) store.ProjectJobSpecRepository {
return repo.Called(proj).Get(0).(store.ProjectJobSpecRepository)
}
// JobSpecRepoFactory to store raw specs
type ProjectJobSpecRepository struct {
mock.Mock
}
func (repo *ProjectJobSpecRepository) GetByName(ctx context.Context, name string) (models.JobSpec, models.NamespaceSpec, error) {
args := repo.Called(ctx, name)
if args.Get(0) != nil {
return args.Get(0).(models.JobSpec), args.Get(1).(models.NamespaceSpec), args.Error(2)
}
return models.JobSpec{}, models.NamespaceSpec{}, args.Error(1)
}
func (repo *ProjectJobSpecRepository) GetByNameForProject(ctx context.Context, job, project string) (models.JobSpec, models.ProjectSpec, error) {
args := repo.Called(ctx, job, project)
if args.Get(0) != nil {
return args.Get(0).(models.JobSpec), args.Get(1).(models.ProjectSpec), args.Error(2)
}
return models.JobSpec{}, models.ProjectSpec{}, args.Error(1)
}
func (repo *ProjectJobSpecRepository) GetAll(ctx context.Context) ([]models.JobSpec, error) {
args := repo.Called(ctx)
if args.Get(0) != nil {
return args.Get(0).([]models.JobSpec), args.Error(1)
}
return []models.JobSpec{}, args.Error(1)
}
func (repo *ProjectJobSpecRepository) GetByDestination(ctx context.Context, dest string) (models.JobSpec, models.ProjectSpec, error) {
args := repo.Called(ctx, dest)
if args.Get(0) != nil {
return args.Get(0).(models.JobSpec), args.Get(1).(models.ProjectSpec), args.Error(2)
}
return models.JobSpec{}, models.ProjectSpec{}, args.Error(2)
}
// JobSpecRepoFactory to store raw specs at namespace level
type JobSpecRepoFactory struct {
mock.Mock
}
func (repo *JobSpecRepoFactory) New(namespace models.NamespaceSpec) job.SpecRepository {
return repo.Called(namespace).Get(0).(job.SpecRepository)
}
// JobSpecRepoFactory to store raw specs
type JobSpecRepository struct {
mock.Mock
}
func (repo *JobSpecRepository) Save(ctx context.Context, t models.JobSpec) error {
return repo.Called(ctx, t).Error(0)
}
func (repo *JobSpecRepository) GetByName(ctx context.Context, name string) (models.JobSpec, error) {
args := repo.Called(ctx, name)
if args.Get(0) != nil {
return args.Get(0).(models.JobSpec), args.Error(1)
}
return models.JobSpec{}, args.Error(1)
}
func (repo *JobSpecRepository) Delete(ctx context.Context, name string) error {
return repo.Called(ctx, name).Error(0)
}
func (repo *JobSpecRepository) GetAll(ctx context.Context) ([]models.JobSpec, error) {
args := repo.Called(ctx)
if args.Get(0) != nil {
return args.Get(0).([]models.JobSpec), args.Error(1)
}
return []models.JobSpec{}, args.Error(1)
}
func (repo *JobSpecRepository) GetByDestination(ctx context.Context, dest string) (models.JobSpec, models.ProjectSpec, error) {
args := repo.Called(ctx, dest)
if args.Get(0) != nil {
return args.Get(0).(models.JobSpec), args.Get(1).(models.ProjectSpec), args.Error(2)
}
return models.JobSpec{}, models.ProjectSpec{}, args.Error(2)
}
type JobConfigLocalFactory struct {
mock.Mock
}
func (fac *JobConfigLocalFactory) New(inputs models.JobSpec) (local.Job, error) {
args := fac.Called(inputs)
return args.Get(0).(local.Job), args.Error(1)
}
type JobService struct {
mock.Mock
}
func (srv *JobService) Create(ctx context.Context, spec2 models.NamespaceSpec, spec models.JobSpec) error {
args := srv.Called(ctx, spec, spec2)
return args.Error(0)
}
func (srv *JobService) GetByName(ctx context.Context, s string, spec models.NamespaceSpec) (models.JobSpec, error) {
args := srv.Called(ctx, s, spec)
return args.Get(0).(models.JobSpec), args.Error(1)
}
func (srv *JobService) KeepOnly(ctx context.Context, spec models.NamespaceSpec, specs []models.JobSpec, observer progress.Observer) error {
args := srv.Called(ctx, spec, specs)
return args.Error(0)
}
func (srv *JobService) GetAll(ctx context.Context, spec models.NamespaceSpec) ([]models.JobSpec, error) {
args := srv.Called(ctx, spec)
return args.Get(0).([]models.JobSpec), args.Error(1)
}
func (srv *JobService) GetByNameForProject(ctx context.Context, s string, spec models.ProjectSpec) (models.JobSpec, models.NamespaceSpec, error) {
args := srv.Called(ctx, s, spec)
return args.Get(0).(models.JobSpec), args.Get(1).(models.NamespaceSpec), args.Error(2)
}
func (srv *JobService) Sync(ctx context.Context, spec models.NamespaceSpec, observer progress.Observer) error {
args := srv.Called(ctx, spec, observer)
return args.Error(0)
}
func (j *JobService) Check(ctx context.Context, namespaceSpec models.NamespaceSpec, specs []models.JobSpec, observer progress.Observer) error {
args := j.Called(ctx, namespaceSpec, specs, observer)
return args.Error(0)
}
func (j *JobService) Delete(ctx context.Context, c models.NamespaceSpec, job models.JobSpec) error {
args := j.Called(ctx, c, job)
return args.Error(0)
}
func (j *JobService) ReplayDryRun(ctx context.Context, replayRequest models.ReplayRequest) (*tree.TreeNode, error) {
args := j.Called(ctx, replayRequest)
return args.Get(0).(*tree.TreeNode), args.Error(1)
}
func (j *JobService) Replay(ctx context.Context, replayRequest models.ReplayRequest) (string, error) {
args := j.Called(ctx, replayRequest)
return args.Get(0).(string), args.Error(1)
}
func (j *JobService) GetReplayStatus(ctx context.Context, replayRequest models.ReplayRequest) (models.ReplayState, error) {
args := j.Called(ctx, replayRequest)
return args.Get(0).(models.ReplayState), args.Error(1)
}
func (j *JobService) GetReplayList(ctx context.Context, projectUUID uuid.UUID) ([]models.ReplaySpec, error) {
args := j.Called(ctx, projectUUID)
return args.Get(0).([]models.ReplaySpec), args.Error(1)
}
func (j *JobService) Run(ctx context.Context, ns models.NamespaceSpec, js []models.JobSpec, obs progress.Observer) error {
args := j.Called(ctx, ns, js, obs)
return args.Error(0)
}
func (j *JobService) GetByDestination(ctx context.Context, projectSpec models.ProjectSpec, destination string) (models.JobSpec, error) {
args := j.Called(projectSpec, destination)
return args.Get(0).(models.JobSpec), args.Error(1)
}
func (j *JobService) GetDownstream(ctx context.Context, projectSpec models.ProjectSpec, jobName string) ([]models.JobSpec, error) {
args := j.Called(ctx, projectSpec, jobName)
return args.Get(0).([]models.JobSpec), args.Error(1)
}
type DependencyResolver struct {
mock.Mock
}
func (srv *DependencyResolver) Resolve(ctx context.Context, projectSpec models.ProjectSpec,
jobSpec models.JobSpec, obs progress.Observer) (models.JobSpec, error) {
args := srv.Called(ctx, projectSpec, jobSpec, obs)
return args.Get(0).(models.JobSpec), args.Error(1)
}
type PriorityResolver struct {
mock.Mock
}
func (srv *PriorityResolver) Resolve(ctx context.Context, jobSpecs []models.JobSpec) ([]models.JobSpec, error) {
args := srv.Called(ctx, jobSpecs)
return args.Get(0).([]models.JobSpec), args.Error(1)
}
type EventService struct {
mock.Mock
}
func (e *EventService) Register(ctx context.Context, spec models.NamespaceSpec, spec2 models.JobSpec, event models.JobEvent) error {
return e.Called(ctx, spec, spec2, event).Error(0)
}
type Notifier struct {
mock.Mock
}
func (n *Notifier) Close() error {
return n.Called().Error(0)
}
func (n *Notifier) Notify(ctx context.Context, attr models.NotifyAttrs) error {
return n.Called(ctx, attr).Error(0)
}
|
package test
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"path"
"runtime"
"testing"
// account "github.com/cloudfly/ecenter/pkg/account"
"github.com/cloudfly/ecenter/pkg/store"
"github.com/stretchr/testify/require"
)
var (
addr = "127.0.0.1:3306"
user = "root"
password = "123456"
testDBName = "alarmd_test"
)
func init() {
if v := os.Getenv("MYSQL_PASSWORD"); v != "" {
password = v
}
if v := os.Getenv("MYSQL_USER"); v != "" {
user = v
}
if v := os.Getenv("MYSQL_ADDR"); v != "" {
addr = v
}
if v := os.Getenv("MYSQL_DATABASE"); v != "" {
testDBName = v
}
}
func ParseSQLFile(t *testing.T) map[string]string {
data := make(map[string]string)
_, filename, _, _ := runtime.Caller(0)
content, err := ioutil.ReadFile(path.Dir(filename) + "/../database.sql")
require.NoError(t, err)
for _, statement := range bytes.Split(content, []byte("\n\n")) {
if statement := bytes.TrimSpace(statement); len(statement) > 0 {
fields := bytes.Fields(statement)
tableName := bytes.Trim(fields[2], "`")
data[string(tableName)] = string(statement)
}
}
return data
}
func InitMySQL(t *testing.T) *store.MySQL {
DestroyMySQL(t)
mysql, err := store.NewMySQL(addr, user, password, testDBName)
require.NoError(t, err)
db, err := mysql.Connect(context.Background())
require.NoError(t, err)
defer db.Close()
statements := ParseSQLFile(t)
for _, statement := range statements {
_, err = db.Exec(string(statement))
require.NoError(t, err)
}
/*
ctx := context.Background()
accounts, err := account.New(mysql)
require.NoError(t, err)
_, err = accounts.AddUser(ctx, "kuwu", "苦无", "test", account.UPAdmin)
_, err = accounts.AddUser(ctx, "linglong", "玲珑", "linglong", account.DefaultUserPermission)
require.NoError(t, err)
_, err = accounts.AddGroup(ctx, "app:grail", false, "", "kuwu")
require.NoError(t, err)
_, err = accounts.AddGroup(ctx, "app:grail:operator", false, "", "kuwu")
require.NoError(t, err)
*/
return mysql
}
func DestroyMySQL(t *testing.T) {
mysql, err := store.NewMySQL(addr, user, password, testDBName)
require.NoError(t, err)
db, err := mysql.Connect(context.Background())
require.NoError(t, err)
defer db.Close()
tables := ParseSQLFile(t)
for table := range tables {
_, err = db.Exec(fmt.Sprintf("DROP TABLE IF EXISTS `%s`", table))
require.NoError(t, err)
}
}
|
package main
func main() {
}
func smallestEvenMultiple(n int) int {
if n%2 == 0 {
return n
}
return n * 2
}
|
package record
import (
"sync"
"sync/atomic"
"context"
"gx/ipfs/QmSJBsmLP1XMjv8hxYg2rUMdPDB7YUpyBo9idjrJ6Cmq6F/fuse"
"gx/ipfs/QmSJBsmLP1XMjv8hxYg2rUMdPDB7YUpyBo9idjrJ6Cmq6F/fuse/fs"
)
// Writes gathers data from FUSE Write calls.
type Writes struct {
buf Buffer
}
var _ = fs.HandleWriter(&Writes{})
func (w *Writes) Write(ctx context.Context, req *fuse.WriteRequest, resp *fuse.WriteResponse) error {
n, err := w.buf.Write(req.Data)
resp.Size = n
if err != nil {
return err
}
return nil
}
func (w *Writes) RecordedWriteData() []byte {
return w.buf.Bytes()
}
// Counter records number of times a thing has occurred.
type Counter struct {
count uint32
}
func (r *Counter) Inc() {
atomic.AddUint32(&r.count, 1)
}
func (r *Counter) Count() uint32 {
return atomic.LoadUint32(&r.count)
}
// MarkRecorder records whether a thing has occurred.
type MarkRecorder struct {
count Counter
}
func (r *MarkRecorder) Mark() {
r.count.Inc()
}
func (r *MarkRecorder) Recorded() bool {
return r.count.Count() > 0
}
// Flushes notes whether a FUSE Flush call has been seen.
type Flushes struct {
rec MarkRecorder
}
var _ = fs.HandleFlusher(&Flushes{})
func (r *Flushes) Flush(ctx context.Context, req *fuse.FlushRequest) error {
r.rec.Mark()
return nil
}
func (r *Flushes) RecordedFlush() bool {
return r.rec.Recorded()
}
type Recorder struct {
mu sync.Mutex
val interface{}
}
// Record that we've seen value. A nil value is indistinguishable from
// no value recorded.
func (r *Recorder) Record(value interface{}) {
r.mu.Lock()
r.val = value
r.mu.Unlock()
}
func (r *Recorder) Recorded() interface{} {
r.mu.Lock()
val := r.val
r.mu.Unlock()
return val
}
type RequestRecorder struct {
rec Recorder
}
// Record a fuse.Request, after zeroing header fields that are hard to
// reproduce.
//
// Make sure to record a copy, not the original request.
func (r *RequestRecorder) RecordRequest(req fuse.Request) {
hdr := req.Hdr()
*hdr = fuse.Header{}
r.rec.Record(req)
}
func (r *RequestRecorder) Recorded() fuse.Request {
val := r.rec.Recorded()
if val == nil {
return nil
}
return val.(fuse.Request)
}
// Setattrs records a Setattr request and its fields.
type Setattrs struct {
rec RequestRecorder
}
var _ = fs.NodeSetattrer(&Setattrs{})
func (r *Setattrs) Setattr(ctx context.Context, req *fuse.SetattrRequest, resp *fuse.SetattrResponse) error {
tmp := *req
r.rec.RecordRequest(&tmp)
return nil
}
func (r *Setattrs) RecordedSetattr() fuse.SetattrRequest {
val := r.rec.Recorded()
if val == nil {
return fuse.SetattrRequest{}
}
return *(val.(*fuse.SetattrRequest))
}
// Fsyncs records an Fsync request and its fields.
type Fsyncs struct {
rec RequestRecorder
}
var _ = fs.NodeFsyncer(&Fsyncs{})
func (r *Fsyncs) Fsync(ctx context.Context, req *fuse.FsyncRequest) error {
tmp := *req
r.rec.RecordRequest(&tmp)
return nil
}
func (r *Fsyncs) RecordedFsync() fuse.FsyncRequest {
val := r.rec.Recorded()
if val == nil {
return fuse.FsyncRequest{}
}
return *(val.(*fuse.FsyncRequest))
}
// Mkdirs records a Mkdir request and its fields.
type Mkdirs struct {
rec RequestRecorder
}
var _ = fs.NodeMkdirer(&Mkdirs{})
// Mkdir records the request and returns an error. Most callers should
// wrap this call in a function that returns a more useful result.
func (r *Mkdirs) Mkdir(ctx context.Context, req *fuse.MkdirRequest) (fs.Node, error) {
tmp := *req
r.rec.RecordRequest(&tmp)
return nil, fuse.EIO
}
// RecordedMkdir returns information about the Mkdir request.
// If no request was seen, returns a zero value.
func (r *Mkdirs) RecordedMkdir() fuse.MkdirRequest {
val := r.rec.Recorded()
if val == nil {
return fuse.MkdirRequest{}
}
return *(val.(*fuse.MkdirRequest))
}
// Symlinks records a Symlink request and its fields.
type Symlinks struct {
rec RequestRecorder
}
var _ = fs.NodeSymlinker(&Symlinks{})
// Symlink records the request and returns an error. Most callers should
// wrap this call in a function that returns a more useful result.
func (r *Symlinks) Symlink(ctx context.Context, req *fuse.SymlinkRequest) (fs.Node, error) {
tmp := *req
r.rec.RecordRequest(&tmp)
return nil, fuse.EIO
}
// RecordedSymlink returns information about the Symlink request.
// If no request was seen, returns a zero value.
func (r *Symlinks) RecordedSymlink() fuse.SymlinkRequest {
val := r.rec.Recorded()
if val == nil {
return fuse.SymlinkRequest{}
}
return *(val.(*fuse.SymlinkRequest))
}
// Links records a Link request and its fields.
type Links struct {
rec RequestRecorder
}
var _ = fs.NodeLinker(&Links{})
// Link records the request and returns an error. Most callers should
// wrap this call in a function that returns a more useful result.
func (r *Links) Link(ctx context.Context, req *fuse.LinkRequest, old fs.Node) (fs.Node, error) {
tmp := *req
r.rec.RecordRequest(&tmp)
return nil, fuse.EIO
}
// RecordedLink returns information about the Link request.
// If no request was seen, returns a zero value.
func (r *Links) RecordedLink() fuse.LinkRequest {
val := r.rec.Recorded()
if val == nil {
return fuse.LinkRequest{}
}
return *(val.(*fuse.LinkRequest))
}
// Mknods records a Mknod request and its fields.
type Mknods struct {
rec RequestRecorder
}
var _ = fs.NodeMknoder(&Mknods{})
// Mknod records the request and returns an error. Most callers should
// wrap this call in a function that returns a more useful result.
func (r *Mknods) Mknod(ctx context.Context, req *fuse.MknodRequest) (fs.Node, error) {
tmp := *req
r.rec.RecordRequest(&tmp)
return nil, fuse.EIO
}
// RecordedMknod returns information about the Mknod request.
// If no request was seen, returns a zero value.
func (r *Mknods) RecordedMknod() fuse.MknodRequest {
val := r.rec.Recorded()
if val == nil {
return fuse.MknodRequest{}
}
return *(val.(*fuse.MknodRequest))
}
// Opens records a Open request and its fields.
type Opens struct {
rec RequestRecorder
}
var _ = fs.NodeOpener(&Opens{})
// Open records the request and returns an error. Most callers should
// wrap this call in a function that returns a more useful result.
func (r *Opens) Open(ctx context.Context, req *fuse.OpenRequest, resp *fuse.OpenResponse) (fs.Handle, error) {
tmp := *req
r.rec.RecordRequest(&tmp)
return nil, fuse.EIO
}
// RecordedOpen returns information about the Open request.
// If no request was seen, returns a zero value.
func (r *Opens) RecordedOpen() fuse.OpenRequest {
val := r.rec.Recorded()
if val == nil {
return fuse.OpenRequest{}
}
return *(val.(*fuse.OpenRequest))
}
// Getxattrs records a Getxattr request and its fields.
type Getxattrs struct {
rec RequestRecorder
}
var _ = fs.NodeGetxattrer(&Getxattrs{})
// Getxattr records the request and returns an error. Most callers should
// wrap this call in a function that returns a more useful result.
func (r *Getxattrs) Getxattr(ctx context.Context, req *fuse.GetxattrRequest, resp *fuse.GetxattrResponse) error {
tmp := *req
r.rec.RecordRequest(&tmp)
return fuse.ErrNoXattr
}
// RecordedGetxattr returns information about the Getxattr request.
// If no request was seen, returns a zero value.
func (r *Getxattrs) RecordedGetxattr() fuse.GetxattrRequest {
val := r.rec.Recorded()
if val == nil {
return fuse.GetxattrRequest{}
}
return *(val.(*fuse.GetxattrRequest))
}
// Listxattrs records a Listxattr request and its fields.
type Listxattrs struct {
rec RequestRecorder
}
var _ = fs.NodeListxattrer(&Listxattrs{})
// Listxattr records the request and returns an error. Most callers should
// wrap this call in a function that returns a more useful result.
func (r *Listxattrs) Listxattr(ctx context.Context, req *fuse.ListxattrRequest, resp *fuse.ListxattrResponse) error {
tmp := *req
r.rec.RecordRequest(&tmp)
return fuse.ErrNoXattr
}
// RecordedListxattr returns information about the Listxattr request.
// If no request was seen, returns a zero value.
func (r *Listxattrs) RecordedListxattr() fuse.ListxattrRequest {
val := r.rec.Recorded()
if val == nil {
return fuse.ListxattrRequest{}
}
return *(val.(*fuse.ListxattrRequest))
}
// Setxattrs records a Setxattr request and its fields.
type Setxattrs struct {
rec RequestRecorder
}
var _ = fs.NodeSetxattrer(&Setxattrs{})
// Setxattr records the request and returns an error. Most callers should
// wrap this call in a function that returns a more useful result.
func (r *Setxattrs) Setxattr(ctx context.Context, req *fuse.SetxattrRequest) error {
tmp := *req
// The byte slice points to memory that will be reused, so make a
// deep copy.
tmp.Xattr = append([]byte(nil), req.Xattr...)
r.rec.RecordRequest(&tmp)
return nil
}
// RecordedSetxattr returns information about the Setxattr request.
// If no request was seen, returns a zero value.
func (r *Setxattrs) RecordedSetxattr() fuse.SetxattrRequest {
val := r.rec.Recorded()
if val == nil {
return fuse.SetxattrRequest{}
}
return *(val.(*fuse.SetxattrRequest))
}
// Removexattrs records a Removexattr request and its fields.
type Removexattrs struct {
rec RequestRecorder
}
var _ = fs.NodeRemovexattrer(&Removexattrs{})
// Removexattr records the request and returns an error. Most callers should
// wrap this call in a function that returns a more useful result.
func (r *Removexattrs) Removexattr(ctx context.Context, req *fuse.RemovexattrRequest) error {
tmp := *req
r.rec.RecordRequest(&tmp)
return nil
}
// RecordedRemovexattr returns information about the Removexattr request.
// If no request was seen, returns a zero value.
func (r *Removexattrs) RecordedRemovexattr() fuse.RemovexattrRequest {
val := r.rec.Recorded()
if val == nil {
return fuse.RemovexattrRequest{}
}
return *(val.(*fuse.RemovexattrRequest))
}
// Creates records a Create request and its fields.
type Creates struct {
rec RequestRecorder
}
var _ = fs.NodeCreater(&Creates{})
// Create records the request and returns an error. Most callers should
// wrap this call in a function that returns a more useful result.
func (r *Creates) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) {
tmp := *req
r.rec.RecordRequest(&tmp)
return nil, nil, fuse.EIO
}
// RecordedCreate returns information about the Create request.
// If no request was seen, returns a zero value.
func (r *Creates) RecordedCreate() fuse.CreateRequest {
val := r.rec.Recorded()
if val == nil {
return fuse.CreateRequest{}
}
return *(val.(*fuse.CreateRequest))
}
|
package main
import "fmt"
// init 函数可以用来初始化,在 main 函数之前调用,任何一个源文件都可以包含 init 函数
func init() {
fmt.Println("init1...")
}
func init() {
fmt.Println("init2...")
}
func main() {
fmt.Println("main...")
}
/**
对于导包,变量定义,init 函数,main 函数,执行流程:
包文件变量定义-->包文件 init 函数---> main 文件变量定义---> main 文件 init 函数---> main 文件 main 函数
*/
|
// +build integration
package keepalived
import (
"context"
"testing"
"time"
corev2 "github.com/sensu/sensu-go/api/core/v2"
"github.com/sensu/sensu-go/backend/etcd"
"github.com/sensu/sensu-go/backend/liveness"
"github.com/sensu/sensu-go/backend/messaging"
"github.com/sensu/sensu-go/backend/seeds"
"github.com/sensu/sensu-go/backend/store"
"github.com/sensu/sensu-go/backend/store/etcd/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestKeepaliveMonitor(t *testing.T) {
e, cleanup := etcd.NewTestEtcd(t)
defer cleanup()
client, err := e.NewClient()
if err != nil {
t.Fatal(err)
}
bus, err := messaging.NewWizardBus(messaging.WizardBusConfig{})
require.NoError(t, err)
if err := bus.Start(); err != nil {
assert.FailNow(t, "message bus failed to start")
}
eventChan := make(chan interface{}, 2)
tsub := testSubscriber{
ch: eventChan,
}
subscription, err := bus.Subscribe(messaging.TopicEventRaw, "testSubscriber", tsub)
if err != nil {
assert.FailNow(t, "failed to subscribe to message bus topic event raw")
}
defer subscription.Cancel()
entity := corev2.FixtureEntity("entity1")
ctx := store.NamespaceContext(context.Background(), entity.Namespace)
store, err := testutil.NewStoreInstance()
if err != nil {
assert.FailNow(t, err.Error())
}
if err := seeds.SeedInitialData(store); err != nil {
assert.FailNow(t, err.Error())
}
if err := store.UpdateEntity(ctx, entity); err != nil {
t.Fatal(err)
}
keepalive := &corev2.Event{
Check: &corev2.Check{
ObjectMeta: corev2.ObjectMeta{
Name: "keepalive",
Namespace: "default",
},
Interval: 1,
Timeout: 5,
},
Entity: entity,
Timestamp: time.Now().Unix(),
}
if _, _, err := store.UpdateEvent(ctx, keepalive); err != nil {
t.Fatal(err)
}
factory := liveness.EtcdFactory(context.Background(), client)
k, err := New(Config{
Store: store,
EventStore: store,
Bus: bus,
LivenessFactory: factory,
BufferSize: 1,
WorkerCount: 1,
StoreTimeout: time.Minute,
})
require.NoError(t, err)
if err := k.Start(); err != nil {
assert.FailNow(t, err.Error())
}
if err := bus.Publish(messaging.TopicKeepalive, keepalive); err != nil {
assert.FailNow(t, "failed to publish keepalive event")
}
msg, ok := <-eventChan
if !ok {
assert.FailNow(t, "failed to pull message off eventChan")
}
okEvent, ok := msg.(*corev2.Event)
if !ok {
assert.FailNow(t, "message type was not an event")
}
assert.Equal(t, uint32(0), okEvent.Check.Status)
msg, ok = <-eventChan
if !ok {
assert.FailNow(t, "failed to pull message off eventChan")
}
warnEvent, ok := msg.(*corev2.Event)
if !ok {
assert.FailNow(t, "message type was not an event")
}
assert.Equal(t, uint32(1), warnEvent.Check.Status)
// Make the entity ephemeral, so that the absence of keepalives leads to its
// deregistration and no keepalive failure events.
entity.Deregister = true
if err := store.UpdateEntity(ctx, entity); err != nil {
t.Fatal(err)
}
// We shouldn't see any keepalive failures after waiting for at least
// keepalive.Interval + keepalive.Timeout.
timer := time.NewTimer(time.Duration(keepalive.Check.Interval+keepalive.Check.Timeout) * time.Second)
select {
case <-eventChan:
assert.FailNow(t, "unexpected event received")
case <-timer.C:
}
// Check that the entity has indeed been deregistered
result, err := store.GetEntityByName(ctx, entity.Name)
if err != nil {
t.Fatal(err)
}
if result != nil {
assert.FailNow(t, "entity did not get deregistered")
}
}
|
package data
import (
"github.com/souhub/wecircles/pkg/logging"
)
type Chat struct {
ID int
Body string
UserID int
UserIdStr string
UserImagePath string
CircleID int
CircleOwnerIDStr string
CreatedAt string
}
// Get all of the chats
func GetChats(circleID int) (chats []Chat, err error) {
db := NewDB()
defer db.Close()
query := `SELECT *
FROM chats
WHERE circle_id=?
ORDER BY id DESC
LIMIT 20`
rows, err := db.Query(query, circleID)
if err != nil {
logging.Warn(err, logging.GetCurrentFile(), logging.GetCurrentFileLine())
return
}
for rows.Next() {
var chat Chat
err = rows.Scan(&chat.ID, &chat.Body, &chat.UserID, &chat.UserIdStr, &chat.UserImagePath, &chat.CircleID, &chat.CircleOwnerIDStr, &chat.CreatedAt)
if err != nil {
logging.Warn(err, logging.GetCurrentFile(), logging.GetCurrentFileLine())
return
}
chats = append(chats, chat)
}
defer rows.Close()
return
}
func GetChatByID(chatID string) (chat Chat, err error) {
db := NewDB()
defer db.Close()
query := `SELECT *
FROM chats
WHERE id=?`
err = db.QueryRow(query, chatID).Scan(&chat.ID, &chat.Body, &chat.UserID, &chat.UserIdStr, &chat.UserImagePath, &chat.CircleID, &chat.CircleOwnerIDStr, &chat.CreatedAt)
return
}
func (chat *Chat) Create() (err error) {
db := NewDB()
defer db.Close()
query := `INSERT chats (body, user_id, user_id_str, user_image_path, circle_id, circle_owner_id_str)
VALUE (?, ?, ?, ?, ?, ?)`
_, err = db.Exec(query, chat.Body, chat.UserID, chat.UserIdStr, chat.UserImagePath, chat.CircleID, chat.CircleOwnerIDStr)
return
}
func (chat *Chat) Delete() (err error) {
db := NewDB()
defer db.Close()
query := `DELETE from chats
WHERE id=?`
_, err = db.Exec(query, chat.ID)
return
}
|
package server
import (
"net"
)
type Client struct{
Id string `json:"id"`
Connection net.Conn `json:"-"`
ChunkServers []ChunkServer `json:"-"`
}
|
package model
import (
"strconv"
"strings"
)
func NumDecPlaces(v float64) int64 {
s := strconv.FormatFloat(v, 'f', -1, 64)
i := strings.IndexByte(s, '.')
if i > -1 {
return int64(len(s) - i - 1)
}
return 0
}
|
/*
Copyright (C) 2018 Synopsys, Inc.
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 protoform
// ProtoformConfig defines the configuration for protoform
type ProtoformConfig struct {
// Dry run wont actually install, but will print the objects definitions out.
DryRun bool `json:"dryRun,omitempty"`
HubUserPassword string `json:"hubUserPassword"`
// Viper secrets
ViperSecret string `json:"viperSecret,omitempty"`
// Log level
DefaultLogLevel string `json:"defaultLogLevel,omitempty"`
}
|
package controller
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"model"
"net/http"
"strconv"
)
/* handler function for GET method */
var SelectUsers = func(w http.ResponseWriter, r *http.Request) {
users := []model.User{}
err := GetDB().Table("users").Find(&users).Error
if err != nil {
msg := map[string]interface{}{"status": false, "message": err}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(msg)
} else {
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
}
/* handler function for GET method */
var SelectUser = func(w http.ResponseWriter, r *http.Request) {
userId := mux.Vars(r)["userId"]
fmt.Printf("finding user with user_id = %s", userId)
user := &model.User{}
err := GetDB().Table("users").Where("user_id = ?", userId).First(user).Error
if err != nil {
msg := map[string]interface{}{"status": false, "message": "Failed to find user"}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(msg)
} else {
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
}
/* handler function for POST method */
var CreateUser = func(w http.ResponseWriter, r *http.Request) {
user := &model.User{}
err1 := json.NewDecoder(r.Body).Decode(user)
if err1 != nil {
msg := map[string]interface{}{"status": false, "message": "Error while decoding request body"}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(msg)
return
}
err2 := GetDB().Create(&user).Error
if err2 != nil {
msg := map[string]interface{}{"status": false, "message": err2}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(msg)
return
}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
/* handler function for DELETE method */
var DeleteUser = func(w http.ResponseWriter, r *http.Request) {
userId := mux.Vars(r)["userId"]
fmt.Printf("deleting user with user_id = %s", userId)
user := &model.User{}
err1 := GetDB().Table("users").Where("user_id = ?", userId).First(user).Error
if err1 != nil {
msg := map[string]interface{}{"status": false, "message": "Failed to find user"}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(msg)
return
}
err2 := GetDB().Delete(&user).Error
if err2 != nil {
msg := map[string]interface{}{"status": false, "message": err2}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(msg)
return
}
msg := map[string]interface{}{"status": true, "message": "User deleted successfully"}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(msg)
}
/* handler function for PUT method */
var UpdateUser = func(w http.ResponseWriter, r *http.Request) {
user := &model.User{}
err1 := json.NewDecoder(r.Body).Decode(user)
if err1 != nil {
msg := map[string]interface{}{"status": false, "message": "Error while decoding request body"}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(msg)
return
}
user.UserId, _ = strconv.ParseInt(mux.Vars(r)["userId"], 10, 64)
fmt.Printf("deleting user with user_id = %d", user.UserId)
err2 := GetDB().Save(&user).Error
if err2 != nil {
msg := map[string]interface{}{"status": false, "message": err2}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(msg)
return
}
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
|
// Copyright 2018 Andrew Bates
//
// 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 insteon
import (
"time"
)
// Insteon Engine Versions
const (
VerI1 EngineVersion = iota
VerI2
VerI2Cs
)
// EngineVersion indicates the Insteon engine version that the
// device is running
type EngineVersion int
// DeviceConstructor will return an initialized device for the given input arguments
type DeviceConstructor func(info DeviceInfo, address Address, sendCh chan<- *MessageRequest, recvCh <-chan *Message, timeout time.Duration) (Device, error)
// Devices is a global DeviceRegistry. This device registry should only be used
// if you are adding a new device category to the system
var Devices DeviceRegistry
// DeviceRegistry is a mechanism to keep track of specific constructors for different
// device categories
type DeviceRegistry struct {
// devices key is the first byte of the
// Category. Documentation simply calls this
// the category and the second byte the sub
// category, but we've combined both bytes
// into a single type
devices map[Category]DeviceConstructor
}
// Register will assign the given constructor to the supplied category
func (dr *DeviceRegistry) Register(category Category, constructor DeviceConstructor) {
if dr.devices == nil {
dr.devices = make(map[Category]DeviceConstructor)
}
dr.devices[category] = constructor
}
// Delete will remove a device constructor from the registry
func (dr *DeviceRegistry) Delete(category Category) {
delete(dr.devices, category)
}
// Find looks for a constructor corresponding to the given category
func (dr *DeviceRegistry) Find(category Category) (DeviceConstructor, bool) {
constructor, found := dr.devices[category]
return constructor, found
}
// CommandRequest is used to request that a given command and payload are sent to a device
type CommandRequest struct {
// Command to send to the device
Command Command
// Payload to include, if set
Payload []byte
// RecvCh to receive subsuquent messages
RecvCh chan<- *CommandResponse
// DoneCh that will be written to by the connection once the request is complete
DoneCh chan<- *CommandRequest
// Ack contains the response Ack/Nak from the device
Ack *Message
// Err includes any error that occurred while trying to send the request
Err error
timeout time.Time
}
// CommandResponse is used for sending messages back to a caller in conjunction with a CommandRequest
type CommandResponse struct {
// Message that was received
Message *Message
// DoneCh to indicate whether more messages should be received or not.
DoneCh chan<- *CommandResponse
request *CommandRequest
}
// Addressable is any receiver that can be queried for its address
type Addressable interface {
// Address will return the 3 byte destination address of the device.
// All device implemtaions must be able to return their address
Address() Address
}
// Commandable is the most basic capability that any device must implement. Commandable
// devices can be sent commands and can receive messages
type Commandable interface {
// SendCommand will send the given command bytes to the device including
// a payload (for extended messages). If payload length is zero then a standard
// length message is used to deliver the commands. The command bytes from the
// response ack are returned as well as any error
SendCommand(cmd Command, payload []byte) (response Command, err error)
// SendCommandAndListen performs the same function as SendCommand. However, instead of returning
// the Ack/Nak command, it returns a channel that can be read to get messages received after
// the command was sent. This is useful for things like retrieving the link database where the
// response information is not in the Ack but in one or more ALDB responses. Once all information
// has been received the command response DoneCh should be sent a "false" value to indicate no
// more messages are expected.
SendCommandAndListen(cmd Command, payload []byte) (recvCh <-chan *CommandResponse, err error)
}
// Device is any implementation that returns the device address and can send commands to the
// destination addresss
type Device interface {
Addressable
Commandable
}
// PingableDevice is any device that implements the Ping method
type PingableDevice interface {
// Ping sends a ping request to the device and waits for a single ACK
Ping() error
}
// NameableDevice is any device that have a settable text string
type NameableDevice interface {
// TextString returns the information assigned to the device
TextString() (string, error)
// SetTextString assigns the information to the device
SetTextString(string) error
}
// FXDevice indicates the device is capable of user-defined FX commands
type FXDevice interface {
FXUsername() (string, error)
}
// AllLinkableDevice is any device that has an all-link database that
// can be programmed remotely
type AllLinkableDevice interface {
// AssignToAllLinkGroup should be called after the set button
// has been pressed on a responder. If the set button was pressed
// then this method will assign the responder to the given
// All-Link Group
AssignToAllLinkGroup(Group) error
// DeleteFromAllLinkGroup removes an All-Link record from a responding
// device during an Unlinking session
DeleteFromAllLinkGroup(Group) error
}
// LinkableDevice is any device that can be put into
// linking mode and the link database can be managed remotely
type LinkableDevice interface {
// Address is the remote/destination address of the device
Address() Address
// EnterLinkingMode is the programmatic equivalent of holding down
// the set button for two seconds. If the device is the first
// to enter linking mode, then it is the controller. The next
// device to enter linking mode is the responder. LinkingMode
// is usually indicated by a flashing GREEN LED on the device
EnterLinkingMode(Group) error
// EnterUnlinkingMode puts a controller device into unlinking mode
// when the set button is then pushed (EnterLinkingMode) on a linked
// device the corresponding links in both the controller and responder
// are deleted. EnterUnlinkingMode is the programmatic equivalent
// to pressing the set button until the device beeps, releasing, then
// pressing the set button again until the device beeps again. UnlinkingMode
// is usually indicated by a flashing RED LED on the device
EnterUnlinkingMode(Group) error
// ExitLinkingMode takes a controller out of linking/unlinking mode.
ExitLinkingMode() error
// Links will return a list of LinkRecords that are present in
// the All-Link database
Links() ([]*LinkRecord, error)
// AddLink will either add the link to the All-Link database
// or it will replace an existing link-record that has been marked
// as deleted
AddLink(newLink *LinkRecord) error
// RemoveLinks will either remove the link records from the device
// All-Link database, or it will simply mark them as deleted
RemoveLinks(oldLinks ...*LinkRecord) error
// WriteLink will write the link record to the device's link database
WriteLink(*LinkRecord) error
}
|
package main
import "fmt"
type Problem21B struct {
Log bool;
}
func (this *Problem21B) Solve() {
Log.Info("Problem 21B solver beginning!");
this.Log = false;
system := &PasswordSwapSystem{};
// Note - the naive search approach is maybe not the intended way to solve this problem, but its fast enough < 10s to be viable
// In addition, this loop considers obviously invalid patterns (with repeat letters). Ignoring these probably brings the total search to sub second
// However, I suspect there's a relatively closed form solution using inverting the individual operations
targetPW := "fbgdceah";
maxGen := -1;
err := system.Init(targetPW, "source-data/input-day-21b.txt");
if err != nil {
Log.FatalError(err);
}
maxOdometerReading := int('h') - int('a') + 1;
indexArr := make([]int, len(targetPW));
for i := 0; i < len(indexArr); i++ {
indexArr[i] = 0;
}
genCount := 0;
for{
for i, v := range indexArr{
system.Data[i] = v + int('a');
}
password := system.RunAgain();
if(password == targetPW){
sourcePass := "";
for _, v := range indexArr{
sourcePass += fmt.Sprintf("%c", v + int('a'));
}
Log.Info("Found target password %s using source pass %s", targetPW, sourcePass);
break;
} else{
if(this.Log){
sourcePass := "";
for _, v := range indexArr{
sourcePass += fmt.Sprintf("%c", v + int('a'));
}
Log.Info("%s = %s", sourcePass, password);
}
}
atLim := false;
for j := len(indexArr) - 1; j >= 0; j--{
if(indexArr[j] + 1 < maxOdometerReading){
indexArr[j]++;
break;
} else{
if(j == 0){
atLim = true;
break;
}
indexArr[j] = 0;
}
}
if(atLim){
Log.Info("Odomoter hit max lim");
break;
}
genCount++;
if(maxGen > 0 && genCount > maxGen) {
break;
}
}
err = system.Execute();
if err != nil {
Log.FatalError(err);
}
//Log.Info(system.PrintProgram());
pw := system.PrintPassword();
Log.Info("Final password is %s", pw);
}
|
/*
Copyright 2015 Crunchy Data Solutions, 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 sec
import (
"crypto/rand"
"fmt"
"io"
)
func main() {
uuid, err := newUUID()
if err != nil {
fmt.Printf("error: %v\n", err)
}
fmt.Printf("%s\n", uuid)
}
// newUUID generates a random UUID according to RFC 4122
func newUUID() (string, error) {
uuid := make([]byte, 16)
n, err := io.ReadFull(rand.Reader, uuid)
if n != len(uuid) || err != nil {
return "", err
}
// variant bits; see section 4.1.1
uuid[8] = uuid[8]&^0xc0 | 0x80
// version 4 (pseudo-random); see section 4.1.3
uuid[6] = uuid[6]&^0xf0 | 0x40
return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]), nil
}
|
/*
go get -u github.com/tidwall/gjson
go get -u github.com/go-sql-driver/mysql
*/
package main
import (
"os"
"fmt"
"./package/http"
)
func main() {
fmt.Print("【HTTP开放接口】服务器")
arg_num := len(os.Args)
if false {
fmt.Printf("\nthe num of input is %d", arg_num)
}
http.ListenAndServe()
}
|
package transdsl
type Specification interface {
Ok(transInfo *TransInfo) bool
}
type Not struct {
Spec Specification
}
func (this *Not) Ok(transInfo *TransInfo) bool {
return !this.Spec.Ok(transInfo)
}
type AllOf struct {
Specs []Specification
}
func (this *AllOf) Ok(transInfo *TransInfo) bool {
for _, spec := range this.Specs {
if !spec.Ok(transInfo) {
return false
}
}
return true
}
type AnyOf struct {
Specs []Specification
}
func (this *AnyOf) Ok(transInfo *TransInfo) bool {
for _, spec := range this.Specs {
if spec.Ok(transInfo) {
return true
}
}
return false
}
|
package main
import "fmt"
func main() {
student_1 := "Goku"
student_2 := "Gohan"
student_3 := "Vegeta"
student_4 := "Piccolo"
student_5 := "Krillin"
student_6 := "Yamcha"
student_7 := "Bluma"
student_8 := "Videl"
student_9 := "Oolang"
student_10 := "Puar"
fmt.Println(student_1, student_2, student_3, student_4, student_5, student_6, student_7, student_8, student_9, student_10)
}
|
package main
import (
"crypto/hmac"
"crypto/sha512"
"database/sql"
"encoding/base64"
"flag"
"fmt"
"log"
"net"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/adhocteam/soapbox"
"github.com/adhocteam/soapbox/buildinfo"
pb "github.com/adhocteam/soapbox/proto"
"github.com/adhocteam/soapbox/soapboxd"
"github.com/adhocteam/soapbox/soapboxd/aws"
_ "github.com/lib/pq"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
func main() {
port := flag.Int("port", 9090, "port to listen on")
printVersion := flag.Bool("V", false, "print version and exit")
logTiming := flag.Bool("log-timing", false, "print log of method call timings")
flag.Parse()
if *printVersion {
fmt.Printf(" version: %s\n", buildinfo.Version)
fmt.Printf(" git commit: %s\n", buildinfo.GitCommit)
fmt.Printf(" build time: %s\n", buildinfo.BuildTime)
return
}
if err := checkJobDependencies(); err != nil {
log.Fatalf("checking for dependencies: %v", err)
}
db, err := sql.Open("postgres", "")
if err != nil {
log.Fatalf("couldn't connect to database: %v", err)
}
ln, err := net.Listen("tcp", ":"+strconv.Itoa(*port))
if err != nil {
log.Fatalf("couldn't listen on port %d: %v", *port, err)
}
var opts []grpc.ServerOption
opts = append(opts, serverInterceptor(loginInterceptor))
if *logTiming {
opts = append(opts, serverInterceptor(timingInterceptor))
}
soapboxConfig := getConfig()
cloud := aws.NewCloudProvider(soapboxConfig)
server := grpc.NewServer(opts...)
apiServer := soapboxd.NewServer(db, nil, cloud)
pb.RegisterApplicationsServer(server, apiServer)
pb.RegisterConfigurationsServer(server, apiServer)
pb.RegisterEnvironmentsServer(server, apiServer)
pb.RegisterDeploymentsServer(server, apiServer)
pb.RegisterUsersServer(server, apiServer)
pb.RegisterVersionServer(server, apiServer)
pb.RegisterActivitiesServer(server, apiServer)
log.Printf("soapboxd listening on 0.0.0.0:%d", *port)
log.Fatal(server.Serve(ln))
}
func checkJobDependencies() error {
binaries := []string{"terraform", "docker", "git"}
for _, bin := range binaries {
if _, err := exec.LookPath(bin); err != nil {
return fmt.Errorf("%s not found: %v", bin, err)
}
}
return nil
}
func getConfig() soapbox.Config {
c := soapbox.Config{
AmiName: "soapbox-aws-linux-ami-*",
Domain: "soapbox.hosting",
IamProfile: "soapbox-app",
InstanceType: "t2.micro",
KeyName: "soapbox-app",
}
if val := os.Getenv("SOAPBOX_AMI_NAME"); val != "" {
c.AmiName = val
}
if val := os.Getenv("SOAPBOX_DOMAIN"); val != "" {
c.Domain = val
}
if val := os.Getenv("SOAPBOX_IAM_PROFILE"); val != "" {
c.IamProfile = val
}
if val := os.Getenv("SOAPBOX_INSTANCE_TYPE"); val != "" {
c.InstanceType = val
}
if val := os.Getenv("SOAPBOX_KEY_NAME"); val != "" {
c.KeyName = val
}
return c
}
func serverInterceptor(interceptor grpc.UnaryServerInterceptor) grpc.ServerOption {
return grpc.UnaryInterceptor(interceptor)
}
func timingInterceptor(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (interface{}, error) {
t0 := time.Now()
resp, err := handler(ctx, req)
log.Printf("method=%s duration=%s error=%v", info.FullMethod, time.Since(t0), err)
return resp, err
}
func loginInterceptor(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (interface{}, error) {
switch strings.Split(info.FullMethod, "/")[2] {
case "LoginUser", "CreateUser", "GetUser":
return handler(ctx, req)
default:
if err := authorize(ctx); err != nil {
return nil, err
}
return handler(ctx, req)
}
}
type accessDeniedErr struct {
userID []byte
}
func (e *accessDeniedErr) Error() string {
return fmt.Sprintf("Incorrect login token for user %s", e.userID)
}
type missingMetadataErr struct{}
func (e *missingMetadataErr) Error() string {
return fmt.Sprint("Not enough metadata attached to authorize request")
}
// TODO(kalilsn) The token calculated here is static, so it can't be revoked, and if stolen
// would allow an attacker to impersonate a user indefinitely.
func authorize(ctx context.Context) error {
if md, ok := metadata.FromIncomingContext(ctx); ok {
vals, ok := md["user_id"]
if !ok || len(vals) < 1 {
return &missingMetadataErr{}
}
userID := []byte(vals[0])
vals, ok = md["login_token"]
if !ok || len(vals) < 1 {
return &missingMetadataErr{}
}
sentToken, err := base64.StdEncoding.DecodeString(vals[0])
if err != nil {
return err
}
key := []byte(os.Getenv("LOGIN_SECRET_KEY"))
h := hmac.New(sha512.New, key)
h.Write(userID)
calculated := h.Sum(nil)
if hmac.Equal(sentToken, calculated) {
return nil
}
return &accessDeniedErr{userID}
}
return &missingMetadataErr{}
}
|
package main
import (
"github.com/ActiveState/log"
"github.com/ActiveState/logyard-apps/applog_endpoint"
"github.com/ActiveState/logyard-apps/applog_endpoint/config"
"github.com/ActiveState/logyard-apps/applog_endpoint/drain"
)
func main() {
config.LoadConfig()
drain.RemoveOrphanedDrains()
applog_endpoint.RouterMain()
err := applog_endpoint.Serve()
log.Fatal(err)
}
|
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
)
// const INF int = 1000000
var sc = bufio.NewScanner(os.Stdin)
func nextInt() int {
sc.Scan()
i, e := strconv.Atoi(sc.Text())
if e != nil {
panic(e)
}
return i
}
func main() {
sc.Split(bufio.ScanWords)
n := nextInt()
k := nextInt()
list := make([]int, n)
for i := 0; i < n; i++ {
list[i] = nextInt()
}
// TODO
dict := map[int]int{}
// 種類ごとに個数をカウント
for _, v := range list {
_, hasKey := dict[v]
if hasKey {
dict[v]++
} else {
dict[v] = 1
}
}
// 種類がk以下なら0
l := len(keys(dict))
if l <= k {
fmt.Println(0)
return
}
numReduce := l - k
// kより多い場合、少ないものから消していく
// ソートする
vals := values(dict)
sort.Ints(vals)
idx := 0
ans := 0
for numReduce > 0 {
ans += vals[idx]
idx++
numReduce--
}
// ソートしないで毎回探しているとすごく遅い
// for {
// var minKey int
// minVal := INF
// for key, val := range dict {
// if min(minVal, val) == val {
// minKey = key
// minVal = val
// }
// }
// ans += minVal
// delete(dict, minKey)
// numReduce--
// if numReduce == 0 {
// break
// }
// }
fmt.Println(ans)
}
func keys(m map[int]int) []int {
ks := []int{}
for k := range m {
ks = append(ks, k)
}
return ks
}
func values(m map[int]int) []int {
vs := []int{}
for _, v := range m {
vs = append(vs, v)
}
return vs
}
func min(a, b int) int {
if a > b {
return b
}
return a
}
|
package db
import (
"database/sql"
"io/ioutil"
"log"
)
func Migrate() {
con, err := sql.Open("mysql", "root:@/php_datebase")
defer con.Close()
if err != nil {
panic(err)
}
b, err := ioutil.ReadFile("./db/migration.sql")
if err != nil {
log.Fatal(err)
}
//for _, q := range strings.Split(string(b),";") {
// fmt.Println(q)
// _,err:=con.Exec(q)
// if err != nil {
// log.Fatal(err)
// }
//}
_, err = con.Exec(string(b))
if err != nil {
log.Fatal(err)
}
//_, err = con.Exec(`CREATE TABLE mig_test(
//id INT(10)AUTO_INCREMENT UNIQUE NOT NULL
//);`)
//if err != nil {
// log.Fatal(err)
//}
}
|
package main
import "net/http"
func (a *apiServer) routes() {
// C
// s.router.POST("/payments")
// R
a.router.HandleFunc("/payments", a.GET(a.handleGetSinglePayment()))
// s.router.GET("/payments", nil)
// U
// s.router.PUT("/payments", nil)
// D
// s.router.DELETE("/payments", nil)
//.HandleFunc("/api/", s.handleAPI())
// s.router.HandleFunc("/about", s.handleAbout())
// s.router.HandleFunc("/", s.handleIndex())
}
/*
func (s *server) handleSomething() http.HandlerFunc {
thing := prepareThing()
return func(w http.ResponseWriter, r *http.Request) {
// use thing
}
}
*/
func (a *apiServer) handleIndex() http.HandlerFunc {
// thing := prepareThing()
return func(w http.ResponseWriter, r *http.Request) {
// use thing
}
}
|
package sp
import (
"bytes"
"errors"
"fmt"
"regexp"
"regexp/syntax"
"strconv"
"strings"
"time"
)
// DataType represents the primitive data types available in InfluxQL.
type DataType int
const (
// Unknown primitive data type.
Unknown DataType = 0
// Float means the data type is a float
Float = 1
// Integer means the data type is a integer
Integer = 2
// String means the data type is a string of text.
String = 3
// Boolean means the data type is a boolean.
Boolean = 4
// AnyField means the data type is any field.
AnyField = 5
)
var (
// ErrInvalidTime is returned when the timestamp string used to
// compare against time field is invalid.
ErrInvalidTime = errors.New("invalid timestamp string")
)
// InspectDataType returns the data type of a given value.
func InspectDataType(v interface{}) DataType {
switch v.(type) {
case float64:
return Float
case int64, int32, int:
return Integer
case string:
return String
case bool:
return Boolean
default:
return Unknown
}
}
// InspectDataTypes returns all of the data types for an interface slice.
func InspectDataTypes(a []interface{}) []DataType {
dta := make([]DataType, len(a))
for i, v := range a {
dta[i] = InspectDataType(v)
}
return dta
}
func (d DataType) String() string {
switch d {
case Float:
return "float"
case Integer:
return "integer"
case String:
return "string"
case Boolean:
return "boolean"
case AnyField:
return "field"
}
return "unknown"
}
// Node represents a node in the InfluxDB abstract syntax tree.
type Node interface {
node()
String() string
}
func (Statements) node() {}
func (*SelectStatement) node() {}
func (*BinaryExpr) node() {}
func (*BooleanLiteral) node() {}
func (*Call) node() {}
func (*Dimension) node() {}
func (Dimensions) node() {}
func (*IntegerLiteral) node() {}
func (*Field) node() {}
func (Fields) node() {}
func (*Measurement) node() {}
func (Measurements) node() {}
func (*nilLiteral) node() {}
func (*NumberLiteral) node() {}
func (*ParenExpr) node() {}
func (*RegexLiteral) node() {}
func (*ListLiteral) node() {}
func (*SortField) node() {}
func (SortFields) node() {}
func (Sources) node() {}
func (*StringLiteral) node() {}
func (*VarRef) node() {}
func (*Wildcard) node() {}
// Statements represents a list of statements.
type Statements []Statement
// String returns a string representation of the statements.
func (a Statements) String() string {
var str []string
for _, stmt := range a {
str = append(str, stmt.String())
}
return strings.Join(str, ";\n")
}
// Statement represents a single command in InfluxQL.
type Statement interface {
Node
stmt()
}
// HasDefaultDatabase provides an interface to get the default database from a Statement.
type HasDefaultDatabase interface {
Node
stmt()
DefaultDatabase() string
}
func (*SelectStatement) stmt() {}
// Expr represents an expression that can be evaluated to a value.
type Expr interface {
Node
expr()
}
func (*BinaryExpr) expr() {}
func (*BooleanLiteral) expr() {}
func (*Call) expr() {}
func (*IntegerLiteral) expr() {}
func (*nilLiteral) expr() {}
func (*NumberLiteral) expr() {}
func (*ParenExpr) expr() {}
func (*RegexLiteral) expr() {}
func (*ListLiteral) expr() {}
func (*StringLiteral) expr() {}
func (*VarRef) expr() {}
func (*Wildcard) expr() {}
// Literal represents a static literal.
type Literal interface {
Expr
literal()
}
func (*BooleanLiteral) literal() {}
func (*IntegerLiteral) literal() {}
func (*nilLiteral) literal() {}
func (*NumberLiteral) literal() {}
func (*RegexLiteral) literal() {}
func (*ListLiteral) literal() {}
func (*StringLiteral) literal() {}
// Source represents a source of data for a statement.
type Source interface {
Node
source()
}
func (*Measurement) source() {}
// Sources represents a list of sources.
type Sources []Source
// Names returns a list of source names.
func (a Sources) Names() []string {
names := make([]string, 0, len(a))
for _, s := range a {
switch s := s.(type) {
case *Measurement:
names = append(names, s.Database)
}
}
return names
}
// String returns a string representation of a Sources array.
func (a Sources) String() string {
var buf bytes.Buffer
ubound := len(a) - 1
for i, src := range a {
_, _ = buf.WriteString(src.String())
if i < ubound {
_, _ = buf.WriteString(", ")
}
}
return buf.String()
}
// SortField represents a field to sort results by.
type SortField struct {
// Name of the field
Name string
// Sort order.
Ascending bool
}
// String returns a string representation of a sort field
func (field *SortField) String() string {
var buf bytes.Buffer
if field.Name != "" {
_, _ = buf.WriteString(field.Name)
_, _ = buf.WriteString(" ")
}
if field.Ascending {
_, _ = buf.WriteString("ASC")
} else {
_, _ = buf.WriteString("DESC")
}
return buf.String()
}
// SortFields represents an ordered list of ORDER BY fields
type SortFields []*SortField
// String returns a string representation of sort fields
func (a SortFields) String() string {
fields := make([]string, 0, len(a))
for _, field := range a {
fields = append(fields, field.String())
}
return strings.Join(fields, ", ")
}
// SelectStatement represents a command for extracting data from the database.
type SelectStatement struct {
// Expressions returned from the selection.
Fields Fields
// Data sources that fields are extracted from.
Sources Sources
// An expression evaluated on data point.
Condition Expr
// Fields to sort results by
SortFields SortFields
// Maximum number of rows to be returned. Unlimited if zero.
Limit int
// Returns rows starting at an offset from the first row.
Offset int
// Expressions used for grouping the selection.
Dimensions Dimensions
// Expressions used for filter grouping buckets.
Having Expr
// if it's a query for raw data values (i.e. not an aggregate)
IsRawQuery bool
// Removes duplicate rows from raw queries.
Dedupe bool
}
// HasDerivative returns true if one of the function calls in the statement is a
// derivative aggregate
func (s *SelectStatement) HasDerivative() bool {
for _, f := range s.FunctionCalls() {
if f.Name == "derivative" || f.Name == "non_negative_derivative" {
return true
}
}
return false
}
// IsSimpleDerivative return true if one of the function call is a derivative function with a
// variable ref as the first arg
func (s *SelectStatement) IsSimpleDerivative() bool {
for _, f := range s.FunctionCalls() {
if f.Name == "derivative" || f.Name == "non_negative_derivative" {
// it's nested if the first argument is an aggregate function
if _, ok := f.Args[0].(*VarRef); ok {
return true
}
}
}
return false
}
// matchExactRegex matches regexes that have the following form: /^foo$/. It
// considers /^$/ to be a matching regex.
func matchExactRegex(v string) (string, bool) {
re, err := syntax.Parse(v, syntax.Perl)
if err != nil {
// Nothing we can do or log.
return "", false
}
if re.Op != syntax.OpConcat {
return "", false
}
if len(re.Sub) < 2 || len(re.Sub) > 3 {
// Regex has too few or too many subexpressions.
return "", false
}
start := re.Sub[0]
if !(start.Op == syntax.OpBeginLine || start.Op == syntax.OpBeginText) {
// Regex does not begin with ^
return "", false
}
end := re.Sub[len(re.Sub)-1]
if !(end.Op == syntax.OpEndLine || end.Op == syntax.OpEndText) {
// Regex does not end with $
return "", false
}
if len(re.Sub) == 3 {
middle := re.Sub[1]
if middle.Op != syntax.OpLiteral {
// Regex does not contain a literal op.
return "", false
}
// We can rewrite this regex.
return string(middle.Rune), true
}
// The regex /^$/
return "", true
}
// ColumnNames will walk all fields and functions and return the appropriate field names for the select statement
// while maintaining order of the field names
func (s *SelectStatement) ColumnNames() []string {
// First walk each field to determine the number of columns.
columnFields := Fields{}
for _, field := range s.Fields {
columnFields = append(columnFields, field)
}
columnNames := make([]string, len(columnFields))
// Keep track of the encountered column names.
names := make(map[string]int)
// Resolve aliases first.
for i, col := range columnFields {
if col.Alias != "" {
columnNames[i] = col.Alias
names[col.Alias] = 1
}
}
// Resolve any generated names and resolve conflicts.
for i, col := range columnFields {
if columnNames[i] != "" {
continue
}
name := col.Name()
count, conflict := names[name]
if conflict {
for {
resolvedName := fmt.Sprintf("%s_%d", name, count)
_, conflict = names[resolvedName]
if !conflict {
names[name] = count + 1
name = resolvedName
break
}
count++
}
}
names[name]++
columnNames[i] = name
}
return columnNames
}
// String returns a string representation of the select statement.
func (s *SelectStatement) String() string {
var buf bytes.Buffer
_, _ = buf.WriteString("SELECT ")
_, _ = buf.WriteString(s.Fields.String())
if len(s.Sources) > 0 {
_, _ = buf.WriteString(" FROM ")
_, _ = buf.WriteString(s.Sources.String())
}
if s.Condition != nil {
_, _ = buf.WriteString(" WHERE ")
_, _ = buf.WriteString(s.Condition.String())
}
if len(s.Dimensions) > 0 {
_, _ = buf.WriteString(" GROUP BY ")
_, _ = buf.WriteString(s.Dimensions.String())
}
if s.Having != nil {
_, _ = buf.WriteString(" HAVING ")
_, _ = buf.WriteString(s.Having.String())
}
if len(s.SortFields) > 0 {
_, _ = buf.WriteString(" ORDER BY ")
_, _ = buf.WriteString(s.SortFields.String())
}
if s.Limit > 0 {
_, _ = fmt.Fprintf(&buf, " LIMIT %d", s.Limit)
}
if s.Offset > 0 {
_, _ = buf.WriteString(", ")
_, _ = buf.WriteString(strconv.Itoa(s.Offset))
}
return buf.String()
}
func (s *SelectStatement) validate() error {
if err := s.validateFields(); err != nil {
return err
}
if err := s.validateAggregates(); err != nil {
return err
}
if err := s.validateConditions(); err != nil {
return err
}
return nil
}
func (s *SelectStatement) validateConditions() error {
expr := s.Condition
if expr == nil {
return nil
}
return validateCondition(expr, ILLEGAL)
}
// valid condition expr.
func validateCondition(expr Expr, op Token) error {
if expr == nil {
return nil
}
switch expr := expr.(type) {
case *Call:
return fmt.Errorf("invalid filter, unsupport function %s", expr.String())
case *BinaryExpr:
err := validateCondition(expr.LHS, expr.Op)
if err != nil {
return err
}
return validateCondition(expr.RHS, expr.Op)
case *ParenExpr:
return validateCondition(expr.Expr, ILLEGAL)
case *RegexLiteral:
switch op {
case EQREGEX, NEQREGEX:
return nil
default:
return fmt.Errorf("invalid filter, unsupport op %s for regex", op.String())
}
case *StringLiteral:
switch op {
case LT, LTE, GT, GTE, SUB, MUL, DIV, ADD:
return fmt.Errorf("invalid filter, unsupport op %s for string", op.String())
default:
return nil
}
default:
return nil
}
}
func (s *SelectStatement) validateFields() error {
for _, f := range s.Fields {
var c validateField
Walk(&c, f.Expr)
if c.foundInvalid {
return fmt.Errorf("invalid operator %s in SELECT field, only support +-*/", c.badToken)
}
switch expr := f.Expr.(type) {
case *BinaryExpr:
if err := expr.validate(); err != nil {
return err
}
case *ParenExpr, *Call, *VarRef, *Wildcard:
default:
return fmt.Errorf("invalid field %v in SELECT field", expr)
}
}
return nil
}
func (s *SelectStatement) validateAggregates() error {
for _, f := range s.Fields {
for _, expr := range walkFunctionCalls(f.Expr) {
if len(expr.Args) < 1 {
return fmt.Errorf("invalid number of arguments for %s, expected at least 1, got %d", expr.Name, len(expr.Args))
}
switch fc := expr.Args[0].(type) {
case *VarRef:
// do nothing
case *BinaryExpr:
if err := fc.validateArgs(); err != nil {
return err
}
case *Wildcard:
case *Call:
default:
return fmt.Errorf("expected field argument in %s()", expr.Name)
}
}
}
return nil
}
// NamesInWhere returns the field and tag names (idents) referenced in the where clause
func (s *SelectStatement) NamesInWhere() []string {
var a []string
if s.Condition != nil {
a = walkNames(s.Condition)
}
return a
}
// NamesInSelect returns the field and tag names (idents) in the select clause
func (s *SelectStatement) NamesInSelect() []string {
var a []string
for _, f := range s.Fields {
a = append(a, walkNames(f.Expr)...)
}
return a
}
// NamesInHaving returns the field and tag names (idents) referenced in the having clause
func (s *SelectStatement) NamesInHaving() []string {
var a []string
if s.Having != nil {
a = walkNames(s.Having)
}
return a
}
// NamesInDimension returns the field and tag names (idents) in the group by
func (s *SelectStatement) NamesInDimension() []string {
var a []string
for _, d := range s.Dimensions {
a = append(a, walkNames(d.Expr)...)
}
return a
}
// walkNames will walk the Expr and return the database fields
func walkNames(exp Expr) []string {
switch expr := exp.(type) {
case *VarRef:
return []string{expr.Val}
case *Call:
var a []string
for _, expr := range expr.Args {
// if ref, ok := expr.(*VarRef); ok {
// a = append(a, ref.Val)
// }
a = append(a, walkNames(expr)...)
}
return a
case *BinaryExpr:
var ret []string
ret = append(ret, walkNames(expr.LHS)...)
ret = append(ret, walkNames(expr.RHS)...)
return ret
case *ParenExpr:
return walkNames(expr.Expr)
}
return nil
}
// walkRefs will walk the Expr and return the database fields
func walkRefs(exp Expr) []VarRef {
switch expr := exp.(type) {
case *VarRef:
return []VarRef{*expr}
case *Call:
a := make([]VarRef, 0, len(expr.Args))
for _, expr := range expr.Args {
if ref, ok := expr.(*VarRef); ok {
a = append(a, *ref)
}
}
return a
case *BinaryExpr:
lhs := walkRefs(expr.LHS)
rhs := walkRefs(expr.RHS)
ret := make([]VarRef, 0, len(lhs)+len(rhs))
ret = append(ret, lhs...)
ret = append(ret, rhs...)
return ret
case *ParenExpr:
return walkRefs(expr.Expr)
}
return nil
}
// FunctionCalls returns the Call objects from the query
func (s *SelectStatement) FunctionCalls() []*Call {
var a []*Call
for _, f := range s.Fields {
a = append(a, walkFunctionCalls(f.Expr)...)
}
return a
}
// FunctionCallsByPosition returns the Call objects from the query in the order they appear in the select statement
func (s *SelectStatement) FunctionCallsByPosition() [][]*Call {
var a [][]*Call
for _, f := range s.Fields {
a = append(a, walkFunctionCalls(f.Expr))
}
return a
}
// walkFunctionCalls walks the Field of a query for any function calls made
func walkFunctionCalls(exp Expr) []*Call {
switch expr := exp.(type) {
case *VarRef:
return nil
case *Call:
return []*Call{expr}
case *BinaryExpr:
var ret []*Call
ret = append(ret, walkFunctionCalls(expr.LHS)...)
ret = append(ret, walkFunctionCalls(expr.RHS)...)
return ret
case *ParenExpr:
return walkFunctionCalls(expr.Expr)
}
return nil
}
// filters an expression to exclude expressions unrelated to a source.
func filterExprBySource(name string, expr Expr) Expr {
switch expr := expr.(type) {
case *VarRef:
if !strings.HasPrefix(expr.Val, name) {
return nil
}
case *BinaryExpr:
lhs := filterExprBySource(name, expr.LHS)
rhs := filterExprBySource(name, expr.RHS)
// If an expr is logical then return either LHS/RHS or both.
// If an expr is arithmetic or comparative then require both sides.
if expr.Op == AND || expr.Op == OR {
if lhs == nil && rhs == nil {
return nil
} else if lhs != nil && rhs == nil {
return lhs
} else if lhs == nil && rhs != nil {
return rhs
}
} else {
if lhs == nil || rhs == nil {
return nil
}
}
return &BinaryExpr{Op: expr.Op, LHS: lhs, RHS: rhs}
case *ParenExpr:
exp := filterExprBySource(name, expr.Expr)
if exp == nil {
return nil
}
return &ParenExpr{Expr: exp}
}
return expr
}
// MatchSource returns the source name that matches a field name.
// Returns a blank string if no sources match.
func MatchSource(sources Sources, name string) string {
return ""
}
// Fields represents a list of fields.
type Fields []*Field
// AliasNames returns a list of calculated field names in
// order of alias, function name, then field.
func (a Fields) AliasNames() []string {
names := []string{}
for _, f := range a {
names = append(names, f.Name())
}
return names
}
// Names returns a list of field names.
func (a Fields) Names() []string {
names := []string{}
for _, f := range a {
switch expr := f.Expr.(type) {
case *Call:
names = append(names, expr.Name)
case *VarRef:
names = append(names, expr.Val)
case *BinaryExpr:
names = append(names, walkNames(expr)...)
case *ParenExpr:
names = append(names, walkNames(expr)...)
}
}
return names
}
// String returns a string representation of the fields.
func (a Fields) String() string {
var str []string
for _, f := range a {
str = append(str, f.String())
}
return strings.Join(str, ", ")
}
// Field represents an expression retrieved from a select statement.
type Field struct {
Expr Expr
Alias string
}
// Name returns the name of the field. Returns alias, if set.
// Otherwise uses the function name or variable name.
func (f *Field) Name() string {
// Return alias, if set.
if f.Alias != "" {
return f.Alias
}
// Return the function name or variable name, if available.
switch expr := f.Expr.(type) {
case *Call:
return expr.Name
case *BinaryExpr:
return BinaryExprName(expr)
case *ParenExpr:
f := Field{Expr: expr.Expr}
return f.Name()
case *VarRef:
return expr.Val
}
// Otherwise return a blank name.
return ""
}
// String returns a string representation of the field.
func (f *Field) String() string {
str := f.Expr.String()
if f.Alias == "" {
return str
}
return fmt.Sprintf("%s AS %s", str, QuoteIdent(f.Alias))
}
// Sort Interface for Fields
func (a Fields) Len() int { return len(a) }
func (a Fields) Less(i, j int) bool { return a[i].Name() < a[j].Name() }
func (a Fields) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// Dimensions represents a list of dimensions.
type Dimensions []*Dimension
// String returns a string representation of the dimensions.
func (a Dimensions) String() string {
var str []string
for _, d := range a {
str = append(str, d.String())
}
return strings.Join(str, ", ")
}
// Dimension represents an expression that a select statement is grouped by.
type Dimension struct {
Expr Expr
Alias string
}
// String returns a string representation of the dimension.
func (d *Dimension) String() string {
str := d.Expr.String()
if d.Alias == "" {
return str
}
return fmt.Sprintf("%s AS %s", str, QuoteIdent(d.Alias))
}
// VarRef represents a reference to a variable.
type VarRef struct {
Val string
Segments []string
}
// String returns a string representation of the variable reference.
func (r *VarRef) String() string {
buf := bytes.NewBufferString(r.Val)
return buf.String()
}
// VarRefs represents a slice of VarRef types.
type VarRefs []VarRef
// Strings returns a slice of the variable names.
func (a VarRefs) Strings() []string {
s := make([]string, len(a))
for i, ref := range a {
s[i] = ref.Val
}
return s
}
// Call represents a function call.
type Call struct {
Name string
Args []Expr
}
// String returns a string representation of the call.
func (c *Call) String() string {
// Join arguments.
var str []string
for _, arg := range c.Args {
str = append(str, arg.String())
}
// Write function name and args.
return fmt.Sprintf("%s(%s)", c.Name, strings.Join(str, ", "))
}
// NumberLiteral represents a numeric literal.
type NumberLiteral struct {
Val float64
}
// String returns a string representation of the literal.
func (l *NumberLiteral) String() string { return strconv.FormatFloat(l.Val, 'f', 3, 64) }
// IntegerLiteral represents an integer literal.
type IntegerLiteral struct {
Val int64
}
// String returns a string representation of the literal.
func (l *IntegerLiteral) String() string { return fmt.Sprintf("%d", l.Val) }
// BooleanLiteral represents a boolean literal.
type BooleanLiteral struct {
Val bool
}
// String returns a string representation of the literal.
func (l *BooleanLiteral) String() string {
if l.Val {
return "true"
}
return "false"
}
// isTrueLiteral returns true if the expression is a literal "true" value.
func isTrueLiteral(expr Expr) bool {
if expr, ok := expr.(*BooleanLiteral); ok {
return expr.Val == true
}
return false
}
// isFalseLiteral returns true if the expression is a literal "false" value.
func isFalseLiteral(expr Expr) bool {
if expr, ok := expr.(*BooleanLiteral); ok {
return expr.Val == false
}
return false
}
// ListLiteral represents a list of strings literal.
type ListLiteral struct {
Vals []interface{}
}
// String returns a string representation of the literal.
func (s *ListLiteral) String() string {
var buf bytes.Buffer
_, _ = buf.WriteString("[")
for idx, tagKey := range s.Vals {
if idx != 0 {
_, _ = buf.WriteString(", ")
}
switch v := tagKey.(type) {
case string:
_, _ = buf.WriteString(QuoteIdent(v))
case float64:
_, _ = buf.WriteString((fmt.Sprintf("%f", v)))
case int64:
_, _ = buf.WriteString((fmt.Sprintf("%d", v)))
}
}
_, _ = buf.WriteString("]")
return buf.String()
}
// StringLiteral represents a string literal.
type StringLiteral struct {
Val string
}
// String returns a string representation of the literal.
func (l *StringLiteral) String() string { return QuoteString(l.Val) }
// nilLiteral represents a nil literal.
// This is not available to the query language itself. It's only used internally.
type nilLiteral struct{}
// String returns a string representation of the literal.
func (l *nilLiteral) String() string { return `nil` }
// BinaryExpr represents an operation between two expressions.
type BinaryExpr struct {
Op Token
LHS Expr
RHS Expr
}
// String returns a string representation of the binary expression.
func (e *BinaryExpr) String() string {
return fmt.Sprintf("%s %s %s", e.LHS.String(), e.Op.String(), e.RHS.String())
}
func (e *BinaryExpr) validate() error {
v := binaryExprValidator{}
Walk(&v, e)
if v.err != nil {
return v.err
} else if v.calls && v.refs {
return errors.New("binary expressions cannot mix aggregates and raw fields")
}
return nil
}
func (e *BinaryExpr) validateArgs() error {
v := binaryExprValidator{}
Walk(&v, e)
if v.err != nil {
return v.err
} else if v.calls {
return errors.New("argument binary expressions cannot mix function")
} else if !v.refs {
return errors.New("argument binary expressions at least one key")
}
return nil
}
type binaryExprValidator struct {
calls bool
refs bool
err error
}
func (v *binaryExprValidator) Visit(n Node) Visitor {
if v.err != nil {
return nil
}
switch n := n.(type) {
case *Call:
v.calls = true
for _, expr := range n.Args {
switch e := expr.(type) {
case *BinaryExpr:
v.err = e.validate()
return nil
}
}
return nil
case *VarRef:
v.refs = true
return nil
}
return v
}
// BinaryExprName returns the name of a binary expression by concatenating
// the variables in the binary expression with underscores.
func BinaryExprName(expr *BinaryExpr) string {
v := binaryExprNameVisitor{}
Walk(&v, expr)
return strings.Join(v.names, "_")
}
type binaryExprNameVisitor struct {
names []string
}
func (v *binaryExprNameVisitor) Visit(n Node) Visitor {
switch n := n.(type) {
case *VarRef:
v.names = append(v.names, n.Val)
case *Call:
v.names = append(v.names, n.Name)
return nil
}
return v
}
// ParenExpr represents a parenthesized expression.
type ParenExpr struct {
Expr Expr
}
// String returns a string representation of the parenthesized expression.
func (e *ParenExpr) String() string { return fmt.Sprintf("(%s)", e.Expr.String()) }
// RegexLiteral represents a regular expression.
type RegexLiteral struct {
Val *regexp.Regexp
}
// String returns a string representation of the literal.
func (r *RegexLiteral) String() string {
if r.Val != nil {
return fmt.Sprintf("/%s/", strings.Replace(r.Val.String(), `/`, `\/`, -1))
}
return ""
}
// Visitor can be called by Walk to traverse an AST hierarchy.
// The Visit() function is called once per node.
type Visitor interface {
Visit(Node) Visitor
}
// Walk traverses a node hierarchy in depth-first order.
func Walk(v Visitor, node Node) {
if node == nil {
return
}
if v = v.Visit(node); v == nil {
return
}
switch n := node.(type) {
case *BinaryExpr:
Walk(v, n.LHS)
Walk(v, n.RHS)
case *Call:
for _, expr := range n.Args {
Walk(v, expr)
}
case *Dimension:
Walk(v, n.Expr)
case Dimensions:
for _, c := range n {
Walk(v, c)
}
case *Field:
Walk(v, n.Expr)
case Fields:
for _, c := range n {
Walk(v, c)
}
case *ParenExpr:
Walk(v, n.Expr)
case *SelectStatement:
Walk(v, n.Fields)
Walk(v, n.Dimensions)
Walk(v, n.Sources)
Walk(v, n.Condition)
Walk(v, n.SortFields)
case SortFields:
for _, sf := range n {
Walk(v, sf)
}
case Sources:
for _, s := range n {
Walk(v, s)
}
case Statements:
for _, s := range n {
Walk(v, s)
}
}
}
// WalkFunc traverses a node hierarchy in depth-first order.
func WalkFunc(node Node, fn func(Node)) {
Walk(walkFuncVisitor(fn), node)
}
type walkFuncVisitor func(Node)
func (fn walkFuncVisitor) Visit(n Node) Visitor { fn(n); return fn }
// Valuer is the interface that wraps the Value() method.
//
// Value returns the value and existence flag for a given key.
type Valuer interface {
Value(key string) (interface{}, bool)
}
// NowValuer returns only the value for "now()".
type NowValuer struct {
Now time.Time
}
// Value is a method that returns the value and existence flag for a given key.
func (v *NowValuer) Value(key string) (interface{}, bool) {
if key == "now()" {
return v.Now, true
}
return nil, false
}
// ContainsVarRef returns true if expr is a VarRef or contains one.
func ContainsVarRef(expr Expr) bool {
var v containsVarRefVisitor
Walk(&v, expr)
return v.contains
}
type containsVarRefVisitor struct {
contains bool
}
func (v *containsVarRefVisitor) Visit(n Node) Visitor {
switch n.(type) {
case *Call:
return nil
case *VarRef:
v.contains = true
}
return v
}
// Measurements represents a list of measurements.
type Measurements []*Measurement
// String returns a string representation of the measurements.
func (a Measurements) String() string {
var str []string
for _, m := range a {
str = append(str, m.String())
}
return strings.Join(str, ", ")
}
// Measurement represents a single measurement used as a datasource.
type Measurement struct {
Database string
}
// String returns a string representation of the measurement.
func (m *Measurement) String() string {
return m.Database
}
//ESString ...
func (m *Measurement) ESString() string {
return m.Database
}
// Wildcard represents a wild card expression.
type Wildcard struct {
Type Token
}
// String returns a string representation of the wildcard.
func (e *Wildcard) String() string {
switch e.Type {
default:
return "*"
}
}
|
/*
Copyright (c) 2015 Antonin Amand <antonin.amand@gmail.com>, All rights reserved.
See LICENSE file or http://www.opensource.org/licenses/BSD-3-Clause.
*/
// Package server provides utilities to run celery workers.
package server
import (
"os"
"os/signal"
"time"
"github.com/efimbakulin/celery"
"github.com/efimbakulin/celery/amqpbackend"
"github.com/efimbakulin/celery/amqpconsumer"
"github.com/efimbakulin/celery/amqputil"
"github.com/efimbakulin/celery/logging"
_ "github.com/efimbakulin/celery/jsonmessage"
)
// Serve loads config from environment and runs a worker with an AMQP consumer and result backend.
// declare should be used to register tasks.
func Serve(queue string, declare func(worker *celery.Worker), log logging.Logger, consumerConfig *amqpconsumer.Config, discardResults bool) {
conf := celery.ConfigFromEnv()
retry := amqputil.NewRetry(conf.BrokerURL, nil, 2*time.Second, log)
sched := celery.NewScheduler(amqpconsumer.NewAMQPSubscriber(queue, consumerConfig, retry, log), log)
var backend celery.Backend
if discardResults {
backend = &celery.DiscardBackend{}
} else {
backend = amqpbackend.NewAMQPBackend(retry, log)
}
worker := celery.NewWorker(conf.CelerydConcurrency, sched, backend, sched, log)
quit := make(chan struct{})
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, os.Kill)
go func() {
s := <-sigs
log.Infof("Signal %v received. Closing...", s)
go func() {
<-sigs
os.Exit(1)
}()
worker.Close()
worker.Wait()
retry.Close()
log.Info("Closed.")
close(quit)
}()
declare(worker)
worker.Start()
<-quit
}
|
package main
import "fmt"
func main() {
// เรียกใช้ฟังก์ชัน
// x คือ ข้อความที่เก็บไว้ในพารามิเตอร์(str)
showString("x")
// 10,20 คือ ข้อมูลที่เก็บไว้ในพารามิเตอร์ (a,b)
addition(10, 20)
empty()
// ตัวแปร result เก็บค่าจาก function addition2(5, 5)
// 5+5 = 10 การบวกมาจากใน function
// 10 * 10 = 100
result := addition2(5, 5)
fmt.Println(result * 10)
}
// สร้าง function โดยมีค่าพารามิเตอร์ คือ str เก็บข้อมูลแบบ string
func showString(str string) {
fmt.Println(str)
}
// สร้าง function
// โดยมีค่าพารามิเตอร์ คือ a,b เก็บข้อมูลแบบ integer
func addition(a int, b int) {
fmt.Println("Sum total =", a+b)
fmt.Println("Minus total =", a-b)
fmt.Println("Multiply total =", a*b)
fmt.Println("Divide total =", a/b)
}
// function ที่ไม่มีการรับค่า
func empty() {
fmt.Println("OK")
}
// return ค่า
func addition2(a int, b int) int {
// ต้องระบุว่า return ออกไปประเภทไหน
output := a + b
return output
}
|
package store
import (
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
"time"
"github.com/zwj186/alog/log"
)
type _FileConfig struct {
Size int64
Path string
RetainDay int
GCInterval time.Duration
ChildTmpl *template.Template
NameTmpl *template.Template
TimeTmpl *template.Template
MsgTmpl *template.Template
}
// NewFileStore 创建新的FileStore实例
func NewFileStore(config log.FileConfig) log.LogStore {
var (
size = config.FileSize
fpath = config.FilePath
childpath = config.ChildPathTmpl
filename = config.FileNameTmpl
timeTmpl = config.Item.TimeTmpl
msgTmpl = config.Item.Tmpl
interval = config.GCInterval
)
if size == 0 {
size = log.DefaultFileSize
}
if fpath == "" {
fpath = log.DefaultFilePath
}
if !filepath.IsAbs(fpath) {
fpath, _ = filepath.Abs(fpath)
}
if filename == "" {
filename = log.DefaultFileNameTmpl
}
if timeTmpl == "" {
timeTmpl = log.DefaultTimeTmpl
}
if msgTmpl == "" {
msgTmpl = log.DefaultMsgTmpl
}
if interval == 0 {
interval = log.DefaultFileGCInterval
}
if l := len(fpath); l > 0 && fpath[l-1] == '/' {
fpath = fpath[:l-1]
}
cfg := &_FileConfig{
Size: size * 1024,
Path: fpath,
ChildTmpl: template.Must(template.New("").Parse(childpath)),
NameTmpl: template.Must(template.New("").Parse(filename)),
TimeTmpl: template.Must(template.New("").Parse(timeTmpl)),
MsgTmpl: template.Must(template.New("").Parse(msgTmpl)),
RetainDay: config.RetainDay,
GCInterval: time.Duration(interval) * time.Minute,
}
fs := &FileStore{config: cfg, fileMap: make(map[string]*FileUnit)}
// 创建日志目录
if err := fs.createFolder(fs.config.Path); err != nil {
panic("创建目录发生错误:" + err.Error())
}
if config.RetainDay > 0 {
// 清理过期的文件
go func() {
fs.gc()
}()
}
return fs
}
// FileUnit 提供文件管理
type FileUnit struct {
fileName string
file *os.File
size int64
}
// FileStore 提供文件日志存储
type FileStore struct {
config *_FileConfig
fileMap map[string]*FileUnit
}
// 执行文件清理
func (fs *FileStore) gc() {
ct := time.Now()
err := filepath.Walk(fs.config.Path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if info.ModTime().Before(ct.AddDate(0, 0, -fs.config.RetainDay)) {
os.Remove(path)
}
return nil
})
if err != nil {
fmt.Println("FileStore GC Error:", err.Error())
}
time.AfterFunc(fs.config.GCInterval, fs.gc)
}
func (fs *FileStore) createFolder(folder string) error {
//folder := fs.config.Path
_, err := os.Stat(folder)
if err != nil {
if os.IsNotExist(err) {
err = os.MkdirAll(folder, os.ModePerm)
if err != nil {
return err
}
}
}
return nil
}
func (fs *FileStore) changeName(name, ext string) string {
var number int
prefix := fmt.Sprintf("%s/%s", fs.config.Path, name)
err := filepath.Walk(fs.config.Path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() || !strings.HasPrefix(path, prefix) {
return nil
}
number++
return nil
})
if err != nil {
return fmt.Sprintf("%s%s", name, ext)
}
return fmt.Sprintf("%s_%d%s", name, number, ext)
}
func (fs *FileStore) rename(fileName string) (err error) {
ext := filepath.Ext(fileName)
prefix := fileName[:len(fileName)-len(ext)]
err = os.Rename(fmt.Sprintf("%s/%s", fs.config.Path, fileName), fmt.Sprintf("%s/%s", fs.config.Path, fs.changeName(prefix, ext)))
return
}
func (fs *FileStore) getFile(item *log.LogItem) (fileUnit *FileUnit, err error) {
childPath := log.ParseName(fs.config.ChildTmpl, item)
fileName := log.ParseName(fs.config.NameTmpl, item)
if fileName == "" {
fileName = fmt.Sprintf("unknown.%s.log", item.Time.Format("20060102"))
}
if len(childPath) > 0 {
fileName = childPath + "/" + fileName
}
fileUnit, ok := fs.fileMap[fileName]
if ok {
if fileUnit.file != nil {
finfo, err := fileUnit.file.Stat()
if err != nil || (finfo.Size() > 0 && finfo.Size() >= fs.config.Size) {
fileUnit.file.Close()
fileUnit.file = nil
fs.rename(fileUnit.fileName)
} else if err == nil {
fileUnit.file.Close()
fileUnit.file = nil
} else {
return fileUnit, err
}
} else if fileUnit.size > 0 && fileUnit.size >= fs.config.Size {
fs.rename(fileUnit.fileName)
}
} else {
fileUnit = &FileUnit{fileName: fileName}
fs.fileMap[fileUnit.fileName] = fileUnit
}
if fileUnit.file == nil {
if len(childPath) > 0 {
fs.createFolder(fs.config.Path + "/" + childPath)
}
file, err := os.OpenFile(fmt.Sprintf("%s/%s", fs.config.Path, fileUnit.fileName), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
if err != nil {
return fileUnit, err
}
fileUnit.file = file
return fileUnit, err
}
return fileUnit, err
}
func (fs *FileStore) Store(item *log.LogItem) (err error) {
fileUnit, err := fs.getFile(item)
if err != nil {
return
}
logInfo := log.ParseLogItem(fs.config.MsgTmpl, fs.config.TimeTmpl, item)
_, err = fileUnit.file.WriteString(logInfo)
if err != nil {
return
}
finfo, err := fileUnit.file.Stat()
if err == nil {
fileUnit.size = finfo.Size()
}
if err != nil || finfo.Size() >= fs.config.Size {
fileUnit.file.Close()
fileUnit.file = nil
}
return
}
func (fs *FileStore) Close() (err error) {
for fileName, fileUnit := range fs.fileMap {
if fileUnit.file != nil {
fileUnit.file.Close()
fileUnit.file = nil
if fileUnit.size >= fs.config.Size {
fs.rename(fileUnit.fileName)
}
}
delete(fs.fileMap, fileName)
}
return
}
|
package query
import (
"fmt"
"time"
"github.com/EverythingMe/meduza/errors"
)
// Query is just the commmon interface for all queries.
// They must validate themselves
type Query interface {
Validate() error
}
type Ordering struct {
By string `bson:"by"`
Ascending bool `bson:"asc"`
}
var NoOrder = Ordering{Ascending: true}
// IsNil tells us whether an Ordering object actually contains any ordering directive or is just empty
func (o Ordering) IsNil() bool {
return len(o.By) == 0
}
func (o Ordering) Validate() error {
return nil
}
type Paging struct {
Offset int `bson:"offset"`
Limit int `bson:"limit"`
}
func (p Paging) Validate() error {
switch {
case p.Offset < 0:
fallthrough
case p.Limit == 0:
fallthrough
case p.Limit < -1:
return errors.NewError("Invalid paging parameters: offset: %d, limit: %d", p.Offset, p.Limit)
default:
return nil
}
}
// This sets the deault limit for queries that don't have limit built into them
var DefaultPagingLimit = 100
type Response struct {
Time time.Duration `bson:"time"`
startTime time.Time
Error *errors.Error `bson:"error"`
}
type QueryResult interface {
Elapsed() time.Duration
Err() error
}
func NewResponse(err error) *Response {
return &Response{
startTime: time.Now(),
Error: errors.Wrap(err),
}
}
func (r *Response) Elapsed() time.Duration {
return r.Time
}
func (r *Response) Err() error {
if r.Error == nil {
return nil
}
return r.Error
}
func (r *Response) Done() {
r.Time = time.Since(r.startTime)
}
func (r *Response) String() string {
return fmt.Sprintf("Response: {Time: %v, Error: %v}", r.Time, r.Error)
}
type PingQuery struct{}
func (PingQuery) Validate() error {
return nil
}
type PingResponse struct {
*Response
}
func NewPingResponse() PingResponse {
return PingResponse{
NewResponse(nil),
}
}
|
package processlink
import (
"learn_go/dataStruct/linkstruct"
"learn_go/datastruct/stacks"
)
var (
head = linkstruct.New(0)
)
// CreateSingleLink 创建一个新链表
func CreateSingleLink() *linkstruct.LinkNode {
head := linkstruct.New(0)
head.Append(1)
head.Append(2)
head.Append(4)
head.Append(5)
head.Append(6)
return head
}
// CreateCycle 创建一个新链表
func CreateCycle() *linkstruct.LinkNode {
head := linkstruct.New(0)
Cycle := head.Loop()
return Cycle
}
// 题目
// 反转一个单链表。
// 示例:
// 输入: 1->2->3->4->5->NULL
// 输出: 5->4->3->2->1->NULL
// ReverserSignleListIter 翻转单链表 方法1 采用迭代的方法
func ReverserSignleListIter(head *linkstruct.LinkNode) *linkstruct.LinkNode {
// 设置一个前置指针
var pre *linkstruct.LinkNode = nil
cur := head
for cur != nil {
// 保存下一跳的指针
temp := cur.Next
cur.Next = nil
// 斩断当前的节点的连接
cur.Next = pre
// 更新前驱指针
pre = cur
// 更新当前节点
cur = temp
}
return pre
}
// ReverserSignleListRecursive 翻转单链表 方法2 采用递归的方法
func ReverserSignleListRecursive(head *linkstruct.LinkNode) *linkstruct.LinkNode {
return reverse(nil, head)
}
func reverse(prev, cur *linkstruct.LinkNode) *linkstruct.LinkNode {
// 采用递归法,首先判断退出递归的条件
if cur == nil {
return prev
}
head := reverse(cur, cur.Next)
// cur.Next这时候是尾节点 prev是前一个节点 相当于前后节点互换了指针方向
cur.Next = prev
return head
}
// 题目
// 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
// 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
// SwapPairsyOne 两两进行节点交换
func SwapPairsyOne(head *linkstruct.LinkNode) *linkstruct.LinkNode {
// 创建一个前置指针
var prev *linkstruct.LinkNode = &linkstruct.LinkNode{Val: -1, Next: head}
// 在创建一个根节点,它的下一个节点就是头结点
var hint *linkstruct.LinkNode = prev
// go 代码赋值的特殊性 一行代码完成交换
// 例如 prev->1->2->3->4->nil
// 实际上是一次性跳过两个节点,这样才能交换 遍历链表时跳出循环的条件 prev的下一个不为空,并且下一个的下一个也不为空
// 1. prev.Next 也就是1,赋值给2的下一个元素,也就是把1接在2的后面
// 2. 把2的下一个元素,也就是3,赋值给1的下一个元素,也就是是把1接在3的后面
// 3. 把1的下一个元素,也就是2,赋值给prev的下一个元素,因为2和1已经调换顺序,需要把prev重新连接在2的前面
// 4. 把prev的下一个元素,也就是1,赋值给prev,注意这里的prev还没有发生改变,这一行是同时生效,所以现在prev的下一个元素还是1,所以看似把prev.Next赋值
// 给了prev是一跳,其实是两跳,因为1和2换了位置,我们又跳到了1,所以是两跳
for prev.Next != nil && prev.Next.Next != nil {
// prev.Next.Next.Next, prev.Next.Next, prev.Next, prev = prev.Next, prev.Next.Next.Next, prev.Next.Next, prev.Next
prev.Next.Next.Next, prev.Next.Next, prev.Next, prev = prev.Next, prev.Next.Next.Next, prev.Next.Next, prev.Next
}
return hint.Next
}
// SwapPairsyTwo 两两进行节点交换
func SwapPairsyTwo(head *linkstruct.LinkNode) *linkstruct.LinkNode {
// 申请一个空节点
p := new(linkstruct.LinkNode)
q := p
for head != nil && head.Next != nil {
nextHead := head.Next.Next
p.Next = head.Next
head.Next = nil
p.Next.Next = head
p = p.Next.Next
head = nextHead
}
if head != nil {
p.Next = head
}
return q.Next
}
// SwapPairsyThree 递归交换
func SwapPairsyThree(head *linkstruct.LinkNode) *linkstruct.LinkNode {
// 1.终止条件:当前没有节点或者只有一个节点,肯定就不需要交换了
if head == nil || head.Next == nil {
return head
}
// 2 节点交换 两个挨着的节点用于交换 head 和 head.Next
firstNode, secondNode := head, head.Next
firstNode.Next = SwapPairsyThree(secondNode.Next)
secondNode.Next = firstNode
return secondNode
}
// 题目
// 给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
// k 是一个正整数,它的值小于或等于链表的长度。
// 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。 方法 有迭代 递归 栈等解决
//ReverseGroup 翻转指定个数的链表节点
func ReverseGroup(head *linkstruct.LinkNode, k int) *linkstruct.LinkNode {
// 设置前驱节点
dummy := &linkstruct.LinkNode{Val: -1, Next: head}
prev := dummy
cur := prev.Next
for {
// 先判断链表的节点是否满足要求
n := k
nextPart := cur
for nextPart != nil && n > 0 {
nextPart = nextPart.Next
n--
}
if n > 0 {
break
} else {
n = k
}
// 保存下一个pre节点
nextPre := cur
for n > 0 {
// 保存下一跳元素
temp := cur.Next
// 斩断前尘
cur.Next = nextPart
// 下个头为当前元素
nextPart = cur
cur = temp
n--
}
// n次翻转完毕
prev.Next = nextPart
// 设置下一个prev
prev = nextPre
cur = prev.Next
}
return dummy.Next
}
// ReverseGroupRecursive 递归
func ReverseGroupRecursive(head *linkstruct.LinkNode, k int) *linkstruct.LinkNode {
cur := head
count := 0
for count != k && cur != nil {
cur = cur.Next
count++
}
if count == k {
cur = ReverseGroupRecursive(cur, k)
for count > 0 {
}
}
return nil
}
// ReverseGroupStack 用栈
func ReverseGroupStack(head *linkstruct.LinkNode, k int) *linkstruct.LinkNode {
dummy := &linkstruct.LinkNode{Val: -1, Next: nil}
p := dummy
_ = p
tmp := head
flagBool := false
var stack stacks.Stack
var temp *linkstruct.LinkNode
for head != nil{
count := k
temp = tmp
for count != 0 && tmp != nil {
if tmp == nil && count > 0{
flagBool = true
break
}
value := &linkstruct.LinkNode{Val: -1, Next: nil}
value.Val = tmp.Val
stack.Push(value)
tmp = tmp.Next
head = head.Next
count--
}
if flagBool {
break
}
if count == 0 {
for stack.Len() != 0 {
value,_:= stack.Pop()
// p.Next = interface{}(value).(*linkstruct.LinkNode)
p.Next = value.(*linkstruct.LinkNode)
p = p.Next
}
}
}
if tmp != nil {
p.Next = temp
}
return dummy.Next
}
// 题目
// 给定一个链表,判断链表中是否有环。
// 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
// HasCyclePointer 判断一个指针是否有环
func HasCyclePointer(head *linkstruct.LinkNode) bool {
if head == nil {
return false
}
quick, slow := head, head
for quick != nil && quick.Next != nil {
if quick == slow {
return true
}
quick = quick.Next.Next
slow = slow.Next
}
return false
}
// HasCycleMap 利用哈希表存储
func HasCycleMap(head *linkstruct.LinkNode) bool {
if head == nil {
return false
}
hash := make(map[*linkstruct.LinkNode]linkstruct.Elem)
for head != nil {
if _, exist := hash[head]; exist {
return true
}
hash[head] = head.Val
head = head.Next
}
return false
}
// HasCycleSomeVal 把链表中节点的值全部置为全部一样值
func HasCycleSomeVal(head *linkstruct.LinkNode) bool {
if head == nil {
return false
}
for head != nil {
if head.Val == 9999999 {
return true
}
head.Val = 9999999
head = head.Next
}
return false
}
// 题目
// 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
// 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
// 说明:不允许修改给定的链表。
// DetectCycle 判断一个链表是否有环,并返回环的位置 利用快慢指针解题
func DetectCycle(head *linkstruct.LinkNode)*linkstruct.LinkNode{
if head == nil && head.Next == nil {
return nil
}
CycleFlag := false
// 快指针一次走两步,慢指针一次走一步
quick,slow := head,head
for quick != nil && quick.Next != nil {
quick ,slow= quick.Next.Next,slow.Next
if quick == slow {
// 证明有环
CycleFlag = true
break
}
}
if !CycleFlag {
return nil
}
quick = head
for quick != slow {
quick,slow = quick.Next,slow.Next
}
return slow
} |
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
fmt.Println("Make file generator for Golang (xgo)")
reader := bufio.NewReader(os.Stdin)
fmt.Print("\nWorking golang directory: ")
wdir, _ := reader.ReadString('\n')
wdir = normalize(wdir)
fmt.Print("Build output directory: ")
bdir, _ := reader.ReadString('\n')
bdir = normalize(bdir)
fmt.Print("Go version: ")
goVersion, _ := reader.ReadString('\n')
goVersion = normalize(goVersion)
fmt.Print("Test build targets: ")
Tt, _ := reader.ReadString('\n')
Tt = normalize(Tt)
Ttargets := strings.Fields(Tt)
fmt.Print("Full build targets: ")
Ft, _ := reader.ReadString('\n')
Ft = normalize(Ft)
Ftargets := strings.Fields(Ft)
fmt.Print("Test build prefix: ")
TBpr, _ := reader.ReadString('\n')
TBpr = normalize(TBpr)
fmt.Print("Full build prefix: ")
FBpr, _ := reader.ReadString('\n')
FBpr = normalize(FBpr)
fmt.Print("\nMakefile export directory: ")
expDir, _ := reader.ReadString('\n')
expDir = normalize(expDir)
makefile := ""
// Build
makefile += "default:\n cd " + bdir + " && xgo --targets="
for i, a := range Ftargets {
if i+1 != len(Ftargets) {
makefile += a + ","
} else {
makefile += a
}
}
makefile += " -go " + goVersion
makefile += " -out " + FBpr
makefile += " " + wdir
// Build and Run
makefile += "\n\nrbuild:\n cd " + bdir + " && xgo --targets="
for i, a := range Ttargets {
if i+1 != len(Ttargets) {
makefile += a + ","
} else {
makefile += a
}
}
makefile += " -go " + goVersion
makefile += " -out " + TBpr
makefile += " " + wdir
makefile += " && ./" + TBpr + "-linux-amd64"
// Test build
makefile += "\n\ntbuild:\n cd " + bdir + " && xgo --targets="
for i, a := range Ttargets {
if i+1 != len(Ttargets) {
makefile += a + ","
} else {
makefile += a
}
}
makefile += " -go " + goVersion
makefile += " -out " + TBpr
makefile += " " + wdir
file, err := os.Create(expDir + "/Makefile")
if err != nil {
fmt.Println(err)
}
file.Close()
file, err = os.OpenFile(expDir+"/Makefile", os.O_RDWR, 0644)
_, err = file.WriteString(makefile)
if err != nil {
fmt.Println(err)
}
file.Close()
}
func normalize(input string) string {
return input[:len(input)-1]
}
|
package main
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func main() {
var wg sync.WaitGroup
ch := make(chan int, 100)
chSend := make(chan int)
chConsume := make(chan int)
sc := make(chan os.Signal, 1)
signal.Notify(sc,
os.Kill,
os.Interrupt,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
go func(ch, quit chan int) {
defer func() {
if err := recover(); err != nil {
fmt.Println("send to ch panic.===", err)
}
}()
i := 0
for {
select {
case ch <- i:
fmt.Println("send", i)
time.Sleep(time.Second)
i++
case <-quit:
fmt.Println("send quit.")
return
}
}
}(ch, chSend)
go func(ch, quit chan int) {
wg.Add(1)
for {
select {
case i, ok := <-ch:
if ok {
fmt.Println("read1", i)
time.Sleep(time.Second * 2)
} else {
fmt.Println("close ch1.")
}
case <-quit:
for {
select {
case i, ok := <-ch:
if ok {
fmt.Println("read2", i)
time.Sleep(time.Second * 2)
} else {
fmt.Println("close ch2.")
goto L
}
}
}
L:
fmt.Println("consume quit.")
wg.Done()
return
}
}
}(ch, chConsume)
<-sc
close(ch)
fmt.Println("close ch ")
close(chSend)
close(chConsume)
wg.Wait()
} |
package client
var (
KEY_MATERIAL = "material"
KEY_UNIT = "unit"
KEY_QUANTIFIERS = "quantifiers"
KEY_QUESTION = "question"
KEY_VERB = "verb"
KEY_NUMERIC = "numeric"
KEY_ROMAN = "roman"
KEY_CREDIT = "credit"
KEY_MARK = "mark"
regexPatternSourceWord = map[string]string{
KEY_MATERIAL: "(Silver|Gold|Iron|silver|gold|iron)",
KEY_UNIT: "(glob|prok|pish|tegj)",
KEY_QUANTIFIERS: "(Many|Much|many|much)",
KEY_QUESTION: "(How|how)",
KEY_VERB: "^(Is|is)$",
KEY_NUMERIC: "[0-9]+",
KEY_ROMAN: "^(I|V|X|L|C|D|M)$",
KEY_CREDIT: "(Credits|credits|Credit|credit)",
KEY_MARK: `(\?)`,
}
)
|
package golayout
import (
"os"
"path/filepath"
log "github.com/sirupsen/logrus"
)
func CreateFileIncludeDir(fp string) (*os.File, error) {
dir := filepath.Dir(fp)
isExist, err := Exists(dir)
if err != nil {
return nil, err
}
if !isExist {
log.Infof("Create sub directory %s", dir)
if err := os.MkdirAll(dir, 0751); err != nil {
return nil, err
}
}
fo, err := os.Create(fp)
if err != nil {
return nil, err
}
return fo, nil
}
func Exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
|
package main
import (
"flag"
"strings"
"github.com/rpcx-ecosystem/agent"
)
var (
addr = flag.String("addr", ":9981", "listen address")
registry = flag.String("reg", "", "注册中心类型,支持direct,multi,zookeeper,etcdv3,consul等类型")
opts = flag.String("opts", "", "所需参数,不同的注册中心需要不同的参数,参数以空格分隔")
)
func main() {
flag.Parse()
agent.StartAgent(*addr, *registry, strings.Fields(*opts))
}
|
package console
import (
"fmt"
"io"
)
// A SimpleConsole represents a Logger implementation for simple shell sessions
type SimpleConsole struct {
out io.Writer
}
// NewSimpleConsole returns a new SimpleConsole with the given writer
func NewSimpleConsole(w io.Writer) *SimpleConsole {
return &SimpleConsole{
out: w,
}
}
// Log takes something that behaves like a string and logs it
func (l *SimpleConsole) Log(msg interface{}) (n int, err error) {
return fmt.Fprintln(l.out, msg)
}
|
package impl
import (
"bitbucket.org/waas_pro/api/models/entity"
"bitbucket.org/waas_pro/api/views"
"bitbucket.org/waas_pro/common/constants"
"bitbucket.org/waas_pro/errorhandling"
"github.com/jinzhu/gorm"
"time"
)
var (
walletLogTag = "wallets_impl.go" + "(" + packageTag + ")"
)
func ValidateWallet(db *gorm.DB, WalletName string, userid string) (bool, *errorhandling.Error) {
var countWallets int64
var count int64
err := db.Debug().Table("wallets").Where("user_id = ?", userid).Count(&countWallets).Error
if countWallets >= 5 {
return false, errorhandling.CreateError(errorhandling.ErrorWalletsLimitReached)
}
err = db.Debug().Table("wallets").Where("user_id = ? AND wallet_name = ?", userid, WalletName).Count(&count).Error
if err != nil {
standardLogger.Error(err.Error(), walletLogTag)
return false, errorhandling.CreateError(errorhandling.ErrorDBFetchFailure)
}
if count == 0 {
return true, nil
}
return false, nil
}
func SaveWallet(w *entity.Wallets, db *gorm.DB) (*entity.Wallets, *errorhandling.Error) {
var err error
err = db.Debug().Create(&w).Error
if err != nil {
standardLogger.Error(err.Error(), walletLogTag)
return &entity.Wallets{}, errorhandling.CreateError(errorhandling.ErrorDBInsertFailure)
}
return w, nil
}
func FindActiveWallet(db *gorm.DB, WalletName string, userid string) (entity.Wallets, *errorhandling.Error) {
var wallet entity.Wallets
var err error
err = db.Debug().Table("wallets").Select("id").Where("wallet_name = ? AND user_id = ? AND is_active = ? AND is_deleted = ?", WalletName, userid, 1, 0).Scan(&wallet).Error
if err != nil {
standardLogger.Error(err.Error(), walletLogTag)
return entity.Wallets{}, errorhandling.CreateError(errorhandling.ErrorUserDoesNotExist)
}
return wallet, nil
}
func FindWallet(db *gorm.DB, WalletName string, userid string) (entity.Wallets, *errorhandling.Error) {
var wallet entity.Wallets
var err error
err = db.Debug().Table("wallets").Select("id").Where("wallet_name = ? AND user_id = ? AND is_deleted = ?", WalletName, userid, 0).Scan(&wallet).Error
if err != nil {
standardLogger.Error(err.Error(), walletLogTag)
return entity.Wallets{}, errorhandling.CreateError(errorhandling.ErrorDBFetchFailure)
}
return wallet, nil
}
func UpdateDebitBalance(db *gorm.DB, data *views.TransferReq, wallet entity.Wallets) (string, *errorhandling.Error) {
var wal entity.Wallets
var err error
err = db.Debug().Table("wallets").Select("wallet_balance").Where("id = ?", wallet.ID).Scan(&wal).Error
if err != nil {
standardLogger.Error(err.Error(), walletLogTag)
return "", errorhandling.CreateError(errorhandling.ErrorDBFetchFailure)
}
if data.Amount > wal.Balance {
return "Insufficient Balance", nil
}
err = db.Debug().Model(&wallet).UpdateColumn("wallet_balance", gorm.Expr("wallet_balance - ?", data.Amount)).Error
if err != nil {
standardLogger.Error(err.Error(), walletLogTag)
return "", errorhandling.CreateError(errorhandling.ErrorDBUpdateFailure)
}
return constants.AmountDebited, nil
}
func UpdateCreditBalance(db *gorm.DB, data *views.TransferReq, wallet entity.Wallets) (string, *errorhandling.Error) {
var err error
err = db.Debug().Model(&wallet).UpdateColumn("wallet_balance", gorm.Expr("wallet_balance + ?", data.Amount)).Error
if err != nil {
standardLogger.Error(err.Error(), walletLogTag)
return "", errorhandling.CreateError(errorhandling.ErrorDBUpdateFailure)
}
return constants.AmountCredited, nil
}
func CreateTransaction(t *entity.Transactions, db *gorm.DB) *errorhandling.Error {
var err error
err = db.Debug().Create(&t).Error
if err != nil {
standardLogger.Error(err.Error(), walletLogTag)
return errorhandling.CreateError(errorhandling.ErrorDBInsertFailure)
}
return nil
}
func BlockWallets(data *views.BlockWalletsReq, db *gorm.DB, userid string) (string, *errorhandling.Error) {
namesArray := data.BlockNames
var supersetArray []entity.Wallets
err := db.Debug().Table("wallets").Select("wallet_name").Where("user_id = ? AND is_deleted = ?", userid, 0).Scan(&supersetArray).Error
if err != nil {
standardLogger.Error(err.Error(), walletLogTag)
return "", errorhandling.CreateError(errorhandling.ErrorDBFetchFailure)
}
var namesSuperArray []string
for _, val := range supersetArray {
namesSuperArray = append(namesSuperArray, val.WalletName)
}
for _, element := range namesSuperArray {
wallet, er := FindWallet(db, element, userid)
if er != nil {
standardLogger.Error(err.Error(), walletLogTag)
return "", er
}
updatedEntityMap := map[string]interface{}{}
updatedEntityMap["is_active"] = 1
updatedEntityMap["updated_at"] = time.Now()
for _, val := range namesArray {
if val == element {
updatedEntityMap["is_active"] = 0
}
}
db.Debug().Table("wallets").Where("id = ?", wallet.ID).Updates(updatedEntityMap)
if db.Error != nil {
standardLogger.Error(err.Error(), walletLogTag)
return "", errorhandling.CreateError(errorhandling.ErrorDBUpdateFailure)
}
}
return constants.WalletsBlocked, nil
}
func DeleteWallets(data *views.DeleteWalletsReq, db *gorm.DB, userid string) (string, *errorhandling.Error) {
namesArray := data.DeleteNames
for _, element := range namesArray {
wallet, err := FindActiveWallet(db, element, userid)
if err != nil {
standardLogger.Error(err.Error(), walletLogTag)
return "", errorhandling.CreateError(errorhandling.ErrorDBFetchFailure)
}
updatedEntityMap := map[string]interface{}{}
updatedEntityMap["is_deleted"] = 1
updatedEntityMap["updated_at"] = time.Now()
db.Debug().Table("wallets").Where("id = ?", wallet.ID).Updates(updatedEntityMap)
if db.Error != nil {
standardLogger.Error(db.Error.Error(), walletLogTag)
return "", errorhandling.CreateError(errorhandling.ErrorDBUpdateFailure)
}
}
return constants.WalletsDeleted , nil
}
func GetUserWallets(userid string, db *gorm.DB) ([]entity.Wallets, *errorhandling.Error) {
var err error
var res []entity.Wallets
err = db.Debug().Table("wallets").Where("user_id = ? AND is_deleted = ?", userid, 0).Scan(&res).Error
if err != nil {
standardLogger.Error(err.Error(), userLogTag)
return []entity.Wallets{}, errorhandling.CreateError(errorhandling.ErrorDBFetchFailure)
}
return res, nil
}
|
package hunter
import (
"sync/atomic"
"time"
"github.com/lucky-loki/bounty"
)
type goWorker struct {
taskQueue chan bounty.Job
jobCount int64
size int
status int64
active time.Time // last active time
}
// NewGoWorker return a go routine worker
func NewGoWorker(size int) Worker {
if size <= 0 {
size = defaultWorkerQueueSize
}
w := &goWorker{
size: size,
status: closed,
}
return w
}
// Consume a job and push to taskQueue, if queue full will return an error.
// you should ensure worker is Running and job not be nil
func (w *goWorker) Consume(job bounty.Job) (err error) {
if atomic.LoadInt64(&w.status) == closed {
return errWorkerNotRunning
}
if job == nil {
return errJobNil
}
defer func() {
if recover() != nil {
err = errWorkerNotRunning
}
}()
select {
case w.taskQueue <- job:
atomic.AddInt64(&w.jobCount, 1)
return nil
default:
return errWorkerQueueFull
}
}
// runWithRecover wrapper job invoke with recover function
func runWithRecover(job bounty.Job) {
defer bounty.WithRecover()
job.Run()
}
// Run change status to running, init a taskQueue and start a routine
// work on it. if you Run() a Running worker, this will be a no-op
func (w *goWorker) Run() error {
if !atomic.CompareAndSwapInt64(&w.status, closed, running) {
return nil
}
w.taskQueue = make(chan bounty.Job, w.size)
go func() {
for job := range w.taskQueue {
runWithRecover(job)
w.active = time.Now()
atomic.AddInt64(&w.jobCount, -1)
}
}()
return nil
}
// Close close taskQueue and not accept new job.
// if you Close() a Closed worker, this will be a no-op
func (w *goWorker) Close() error {
if !atomic.CompareAndSwapInt64(&w.status, running, closed) {
return nil
}
close(w.taskQueue)
return nil
}
func (w *goWorker) BusyLevel() BusyLevel {
return busyLevel(int(w.jobCount), w.size)
}
func (w *goWorker) LastActiveTime() time.Time {
return w.active
}
func (w *goWorker) IsEmpty() bool {
return w.jobCount == 0
}
|
package redis
import (
"fmt"
"github.com/garyburd/redigo/redis"
"strconv"
"time"
)
type Redis struct {
RedisIp string
RedisPort int
ExpireTime int
RedisPool *redis.Pool
}
func GetRedis(RedisIp string, RedisPort int, ExpireTime int) *Redis {
var redis Redis
redis.RedisIp = RedisIp
redis.RedisPort = RedisPort
redis.ExpireTime = ExpireTime
redis.InitRedis()
return &redis
}
func (s *Redis) InitRedis() {
url := s.RedisIp + ":" + strconv.Itoa(s.RedisPort)
s.RedisPool = &redis.Pool{
MaxIdle: 256,
MaxActive: 0,
IdleTimeout: time.Duration(120),
Dial: func() (redis.Conn, error) {
return redis.Dial(
"tcp",
url,
redis.DialReadTimeout(time.Duration(1000)*time.Millisecond),
redis.DialWriteTimeout(time.Duration(1000)*time.Millisecond),
redis.DialConnectTimeout(time.Duration(1000)*time.Millisecond),
redis.DialDatabase(0),
//red.DialPassword(""),
)
},
}
}
// Exec("set","hello","world")
// Exec("get","hello")
func (s *Redis) ExecRedis(cmd string, key interface{}, args ...interface{}) (interface{}, error) {
con := s.RedisPool.Get()
if err := con.Err(); err != nil {
return nil, err
}
defer con.Close()
parmas := make([]interface{}, 0)
parmas = append(parmas, key)
if len(args) > 0 {
for _, v := range args {
parmas = append(parmas, v)
}
}
return con.Do(cmd, parmas...)
}
func (s *Redis) TestRedis() {
// testRedis
s.ExecRedis("set","hello","world")
result,err := s.ExecRedis("get","hello")
if err != nil {
fmt.Print(err.Error())
}
str,_:=redis.String(result,err)
fmt.Print(str)
}
|
package x
// GENERATED BY XO. DO NOT EDIT.
import (
"errors"
"strings"
//"time"
"ms/sun/shared/helper"
"strconv"
"github.com/jmoiron/sqlx"
)
// (shortname .TableNameGo "err" "res" "sqlstr" "db" "XOLog") -}}//(schema .Schema .Table.TableName) -}}// .TableNameGo}}// Action represents a row from 'sun.action'.
// Manualy copy this to project
type Action__ struct {
ActionId int `json:"ActionId"` // ActionId -
ActorUserId int `json:"ActorUserId"` // ActorUserId -
ActionType int `json:"ActionType"` // ActionType -
PeerUserId int `json:"PeerUserId"` // PeerUserId -
PostId int `json:"PostId"` // PostId -
CommentId int `json:"CommentId"` // CommentId -
Murmur64Hash int `json:"Murmur64Hash"` // Murmur64Hash -
CreatedTime int `json:"CreatedTime"` // CreatedTime -
// xo fields
_exists, _deleted bool
}
// Exists determines if the Action exists in the database.
func (a *Action) Exists() bool {
return a._exists
}
// Deleted provides information if the Action has been deleted from the database.
func (a *Action) Deleted() bool {
return a._deleted
}
// Insert inserts the Action to the database.
func (a *Action) Insert(db XODB) error {
var err error
// if already exist, bail
if a._exists {
return errors.New("insert failed: already exists")
}
// sql insert query, primary key must be provided
const sqlstr = `INSERT INTO sun.action (` +
`ActionId, ActorUserId, ActionType, PeerUserId, PostId, CommentId, Murmur64Hash, CreatedTime` +
`) VALUES (` +
`?, ?, ?, ?, ?, ?, ?, ?` +
`)`
// run query
if LogTableSqlReq.Action {
XOLog(sqlstr, a.ActionId, a.ActorUserId, a.ActionType, a.PeerUserId, a.PostId, a.CommentId, a.Murmur64Hash, a.CreatedTime)
}
_, err = db.Exec(sqlstr, a.ActionId, a.ActorUserId, a.ActionType, a.PeerUserId, a.PostId, a.CommentId, a.Murmur64Hash, a.CreatedTime)
if err != nil {
return err
}
// set existence
a._exists = true
OnAction_AfterInsert(a)
return nil
}
// Insert inserts the Action to the database.
func (a *Action) Replace(db XODB) error {
var err error
// sql query
const sqlstr = `REPLACE INTO sun.action (` +
`ActionId, ActorUserId, ActionType, PeerUserId, PostId, CommentId, Murmur64Hash, CreatedTime` +
`) VALUES (` +
`?, ?, ?, ?, ?, ?, ?, ?` +
`)`
// run query
if LogTableSqlReq.Action {
XOLog(sqlstr, a.ActionId, a.ActorUserId, a.ActionType, a.PeerUserId, a.PostId, a.CommentId, a.Murmur64Hash, a.CreatedTime)
}
_, err = db.Exec(sqlstr, a.ActionId, a.ActorUserId, a.ActionType, a.PeerUserId, a.PostId, a.CommentId, a.Murmur64Hash, a.CreatedTime)
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return err
}
a._exists = true
OnAction_AfterInsert(a)
return nil
}
// Update updates the Action in the database.
func (a *Action) Update(db XODB) error {
var err error
// if doesn't exist, bail
if !a._exists {
return errors.New("update failed: does not exist")
}
// if deleted, bail
if a._deleted {
return errors.New("update failed: marked for deletion")
}
// sql query
const sqlstr = `UPDATE sun.action SET ` +
`ActorUserId = ?, ActionType = ?, PeerUserId = ?, PostId = ?, CommentId = ?, Murmur64Hash = ?, CreatedTime = ?` +
` WHERE ActionId = ?`
// run query
if LogTableSqlReq.Action {
XOLog(sqlstr, a.ActorUserId, a.ActionType, a.PeerUserId, a.PostId, a.CommentId, a.Murmur64Hash, a.CreatedTime, a.ActionId)
}
_, err = db.Exec(sqlstr, a.ActorUserId, a.ActionType, a.PeerUserId, a.PostId, a.CommentId, a.Murmur64Hash, a.CreatedTime, a.ActionId)
if LogTableSqlReq.Action {
XOLogErr(err)
}
OnAction_AfterUpdate(a)
return err
}
// Save saves the Action to the database.
func (a *Action) Save(db XODB) error {
if a.Exists() {
return a.Update(db)
}
return a.Replace(db)
}
// Delete deletes the Action from the database.
func (a *Action) Delete(db XODB) error {
var err error
// if doesn't exist, bail
if !a._exists {
return nil
}
// if deleted, bail
if a._deleted {
return nil
}
// sql query
const sqlstr = `DELETE FROM sun.action WHERE ActionId = ?`
// run query
if LogTableSqlReq.Action {
XOLog(sqlstr, a.ActionId)
}
_, err = db.Exec(sqlstr, a.ActionId)
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return err
}
// set deleted
a._deleted = true
OnAction_AfterDelete(a)
return nil
}
////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// Querify gen - ME /////////////////////////////////////////
//.TableNameGo= table name
// _Deleter, _Updater
// orma types
type __Action_Deleter struct {
wheres []whereClause
whereSep string
dollarIndex int
isMysql bool
}
type __Action_Updater struct {
wheres []whereClause
// updates map[string]interface{}
updates []updateCol
whereSep string
dollarIndex int
isMysql bool
}
type __Action_Selector struct {
wheres []whereClause
selectCol string
whereSep string
orderBy string //" order by id desc //for ints
limit int
offset int
dollarIndex int
isMysql bool
}
func NewAction_Deleter() *__Action_Deleter {
d := __Action_Deleter{whereSep: " AND ", isMysql: true}
return &d
}
func NewAction_Updater() *__Action_Updater {
u := __Action_Updater{whereSep: " AND ", isMysql: true}
//u.updates = make(map[string]interface{},10)
return &u
}
func NewAction_Selector() *__Action_Selector {
u := __Action_Selector{whereSep: " AND ", selectCol: "*", isMysql: true}
return &u
}
/*/// mysql or cockroach ? or $1 handlers
func (m *__Action_Selector)nextDollars(size int) string {
r := DollarsForSqlIn(size,m.dollarIndex,m.isMysql)
m.dollarIndex += size
return r
}
func (m *__Action_Selector)nextDollar() string {
r := DollarsForSqlIn(1,m.dollarIndex,m.isMysql)
m.dollarIndex += 1
return r
}
*/
/////////////////////////////// Where for all /////////////////////////////
//// for ints all selector updater, deleter
/// mysql or cockroach ? or $1 handlers
func (m *__Action_Deleter) nextDollars(size int) string {
r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql)
m.dollarIndex += size
return r
}
func (m *__Action_Deleter) nextDollar() string {
r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql)
m.dollarIndex += 1
return r
}
////////ints
func (u *__Action_Deleter) Or() *__Action_Deleter {
u.whereSep = " OR "
return u
}
func (u *__Action_Deleter) ActionId_In(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) ActionId_Ins(ins ...int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) ActionId_NotIn(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Deleter) ActionId_Eq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActionId_NotEq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActionId_LT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActionId_LE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActionId_GT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActionId_GE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Deleter) ActorUserId_In(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActorUserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) ActorUserId_Ins(ins ...int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActorUserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) ActorUserId_NotIn(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActorUserId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Deleter) ActorUserId_Eq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActorUserId_NotEq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActorUserId_LT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActorUserId_LE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActorUserId_GT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActorUserId_GE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Deleter) ActionType_In(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionType IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) ActionType_Ins(ins ...int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionType IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) ActionType_NotIn(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionType NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Deleter) ActionType_Eq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActionType_NotEq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActionType_LT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActionType_LE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActionType_GT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) ActionType_GE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Deleter) PeerUserId_In(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PeerUserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) PeerUserId_Ins(ins ...int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PeerUserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) PeerUserId_NotIn(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PeerUserId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Deleter) PeerUserId_Eq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) PeerUserId_NotEq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) PeerUserId_LT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) PeerUserId_LE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) PeerUserId_GT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) PeerUserId_GE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Deleter) PostId_In(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) PostId_Ins(ins ...int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) PostId_NotIn(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Deleter) PostId_Eq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) PostId_NotEq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) PostId_LT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) PostId_LE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) PostId_GT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) PostId_GE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Deleter) CommentId_In(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CommentId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) CommentId_Ins(ins ...int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CommentId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) CommentId_NotIn(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CommentId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Deleter) CommentId_Eq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) CommentId_NotEq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) CommentId_LT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) CommentId_LE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) CommentId_GT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) CommentId_GE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Deleter) Murmur64Hash_In(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Murmur64Hash IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) Murmur64Hash_Ins(ins ...int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Murmur64Hash IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) Murmur64Hash_NotIn(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Murmur64Hash NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Deleter) Murmur64Hash_Eq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) Murmur64Hash_NotEq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) Murmur64Hash_LT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) Murmur64Hash_LE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) Murmur64Hash_GT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) Murmur64Hash_GE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Deleter) CreatedTime_In(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) CreatedTime_Ins(ins ...int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Deleter) CreatedTime_NotIn(ins []int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Deleter) CreatedTime_Eq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) CreatedTime_NotEq(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) CreatedTime_LT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) CreatedTime_LE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) CreatedTime_GT(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Deleter) CreatedTime_GE(val int) *__Action_Deleter {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
/// mysql or cockroach ? or $1 handlers
func (m *__Action_Updater) nextDollars(size int) string {
r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql)
m.dollarIndex += size
return r
}
func (m *__Action_Updater) nextDollar() string {
r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql)
m.dollarIndex += 1
return r
}
////////ints
func (u *__Action_Updater) Or() *__Action_Updater {
u.whereSep = " OR "
return u
}
func (u *__Action_Updater) ActionId_In(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) ActionId_Ins(ins ...int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) ActionId_NotIn(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Updater) ActionId_Eq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActionId_NotEq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActionId_LT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActionId_LE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActionId_GT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActionId_GE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Updater) ActorUserId_In(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActorUserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) ActorUserId_Ins(ins ...int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActorUserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) ActorUserId_NotIn(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActorUserId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Updater) ActorUserId_Eq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActorUserId_NotEq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActorUserId_LT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActorUserId_LE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActorUserId_GT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActorUserId_GE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Updater) ActionType_In(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionType IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) ActionType_Ins(ins ...int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionType IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) ActionType_NotIn(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionType NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Updater) ActionType_Eq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActionType_NotEq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActionType_LT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActionType_LE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActionType_GT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) ActionType_GE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Updater) PeerUserId_In(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PeerUserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) PeerUserId_Ins(ins ...int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PeerUserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) PeerUserId_NotIn(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PeerUserId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Updater) PeerUserId_Eq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) PeerUserId_NotEq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) PeerUserId_LT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) PeerUserId_LE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) PeerUserId_GT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) PeerUserId_GE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Updater) PostId_In(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) PostId_Ins(ins ...int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) PostId_NotIn(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Updater) PostId_Eq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) PostId_NotEq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) PostId_LT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) PostId_LE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) PostId_GT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) PostId_GE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Updater) CommentId_In(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CommentId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) CommentId_Ins(ins ...int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CommentId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) CommentId_NotIn(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CommentId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Updater) CommentId_Eq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) CommentId_NotEq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) CommentId_LT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) CommentId_LE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) CommentId_GT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) CommentId_GE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Updater) Murmur64Hash_In(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Murmur64Hash IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) Murmur64Hash_Ins(ins ...int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Murmur64Hash IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) Murmur64Hash_NotIn(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Murmur64Hash NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Updater) Murmur64Hash_Eq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) Murmur64Hash_NotEq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) Murmur64Hash_LT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) Murmur64Hash_LE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) Murmur64Hash_GT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) Murmur64Hash_GE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Updater) CreatedTime_In(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) CreatedTime_Ins(ins ...int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Updater) CreatedTime_NotIn(ins []int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Updater) CreatedTime_Eq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) CreatedTime_NotEq(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) CreatedTime_LT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) CreatedTime_LE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) CreatedTime_GT(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Updater) CreatedTime_GE(val int) *__Action_Updater {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
/// mysql or cockroach ? or $1 handlers
func (m *__Action_Selector) nextDollars(size int) string {
r := DollarsForSqlIn(size, m.dollarIndex, m.isMysql)
m.dollarIndex += size
return r
}
func (m *__Action_Selector) nextDollar() string {
r := DollarsForSqlIn(1, m.dollarIndex, m.isMysql)
m.dollarIndex += 1
return r
}
////////ints
func (u *__Action_Selector) Or() *__Action_Selector {
u.whereSep = " OR "
return u
}
func (u *__Action_Selector) ActionId_In(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) ActionId_Ins(ins ...int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) ActionId_NotIn(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Selector) ActionId_Eq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActionId_NotEq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActionId_LT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActionId_LE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActionId_GT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActionId_GE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Selector) ActorUserId_In(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActorUserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) ActorUserId_Ins(ins ...int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActorUserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) ActorUserId_NotIn(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActorUserId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Selector) ActorUserId_Eq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActorUserId_NotEq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActorUserId_LT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActorUserId_LE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActorUserId_GT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActorUserId_GE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActorUserId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Selector) ActionType_In(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionType IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) ActionType_Ins(ins ...int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionType IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) ActionType_NotIn(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " ActionType NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Selector) ActionType_Eq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActionType_NotEq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActionType_LT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActionType_LE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActionType_GT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) ActionType_GE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " ActionType >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Selector) PeerUserId_In(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PeerUserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) PeerUserId_Ins(ins ...int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PeerUserId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) PeerUserId_NotIn(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PeerUserId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Selector) PeerUserId_Eq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) PeerUserId_NotEq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) PeerUserId_LT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) PeerUserId_LE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) PeerUserId_GT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) PeerUserId_GE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PeerUserId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Selector) PostId_In(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) PostId_Ins(ins ...int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) PostId_NotIn(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " PostId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Selector) PostId_Eq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) PostId_NotEq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) PostId_LT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) PostId_LE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) PostId_GT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) PostId_GE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " PostId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Selector) CommentId_In(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CommentId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) CommentId_Ins(ins ...int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CommentId IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) CommentId_NotIn(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CommentId NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Selector) CommentId_Eq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) CommentId_NotEq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) CommentId_LT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) CommentId_LE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) CommentId_GT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) CommentId_GE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CommentId >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Selector) Murmur64Hash_In(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Murmur64Hash IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) Murmur64Hash_Ins(ins ...int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Murmur64Hash IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) Murmur64Hash_NotIn(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " Murmur64Hash NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Selector) Murmur64Hash_Eq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) Murmur64Hash_NotEq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) Murmur64Hash_LT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) Murmur64Hash_LE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) Murmur64Hash_GT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) Murmur64Hash_GE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " Murmur64Hash >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (u *__Action_Selector) CreatedTime_In(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) CreatedTime_Ins(ins ...int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (u *__Action_Selector) CreatedTime_NotIn(ins []int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
for _, i := range ins {
insWhere = append(insWhere, i)
}
w.args = insWhere
w.condition = " CreatedTime NOT IN(" + u.nextDollars(len(ins)) + ") "
u.wheres = append(u.wheres, w)
return u
}
func (d *__Action_Selector) CreatedTime_Eq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime = " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) CreatedTime_NotEq(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime != " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) CreatedTime_LT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime < " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) CreatedTime_LE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime <= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) CreatedTime_GT(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime > " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
func (d *__Action_Selector) CreatedTime_GE(val int) *__Action_Selector {
w := whereClause{}
var insWhere []interface{}
insWhere = append(insWhere, val)
w.args = insWhere
w.condition = " CreatedTime >= " + d.nextDollar()
d.wheres = append(d.wheres, w)
return d
}
///// for strings //copy of above with type int -> string + rm if eq + $ms_str_cond
////////ints
////////ints
////////ints
/// End of wheres for selectors , updators, deletor
/////////////////////////////// Updater /////////////////////////////
//ints
func (u *__Action_Updater) ActionId(newVal int) *__Action_Updater {
up := updateCol{" ActionId = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" ActionId = " + u.nextDollar()] = newVal
return u
}
func (u *__Action_Updater) ActionId_Increment(count int) *__Action_Updater {
if count > 0 {
up := updateCol{" ActionId = ActionId+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" ActionId = ActionId+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" ActionId = ActionId- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" ActionId = ActionId- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__Action_Updater) ActorUserId(newVal int) *__Action_Updater {
up := updateCol{" ActorUserId = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" ActorUserId = " + u.nextDollar()] = newVal
return u
}
func (u *__Action_Updater) ActorUserId_Increment(count int) *__Action_Updater {
if count > 0 {
up := updateCol{" ActorUserId = ActorUserId+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" ActorUserId = ActorUserId+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" ActorUserId = ActorUserId- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" ActorUserId = ActorUserId- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__Action_Updater) ActionType(newVal int) *__Action_Updater {
up := updateCol{" ActionType = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" ActionType = " + u.nextDollar()] = newVal
return u
}
func (u *__Action_Updater) ActionType_Increment(count int) *__Action_Updater {
if count > 0 {
up := updateCol{" ActionType = ActionType+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" ActionType = ActionType+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" ActionType = ActionType- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" ActionType = ActionType- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__Action_Updater) PeerUserId(newVal int) *__Action_Updater {
up := updateCol{" PeerUserId = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" PeerUserId = " + u.nextDollar()] = newVal
return u
}
func (u *__Action_Updater) PeerUserId_Increment(count int) *__Action_Updater {
if count > 0 {
up := updateCol{" PeerUserId = PeerUserId+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" PeerUserId = PeerUserId+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" PeerUserId = PeerUserId- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" PeerUserId = PeerUserId- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__Action_Updater) PostId(newVal int) *__Action_Updater {
up := updateCol{" PostId = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" PostId = " + u.nextDollar()] = newVal
return u
}
func (u *__Action_Updater) PostId_Increment(count int) *__Action_Updater {
if count > 0 {
up := updateCol{" PostId = PostId+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" PostId = PostId+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" PostId = PostId- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" PostId = PostId- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__Action_Updater) CommentId(newVal int) *__Action_Updater {
up := updateCol{" CommentId = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" CommentId = " + u.nextDollar()] = newVal
return u
}
func (u *__Action_Updater) CommentId_Increment(count int) *__Action_Updater {
if count > 0 {
up := updateCol{" CommentId = CommentId+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" CommentId = CommentId+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" CommentId = CommentId- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" CommentId = CommentId- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__Action_Updater) Murmur64Hash(newVal int) *__Action_Updater {
up := updateCol{" Murmur64Hash = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" Murmur64Hash = " + u.nextDollar()] = newVal
return u
}
func (u *__Action_Updater) Murmur64Hash_Increment(count int) *__Action_Updater {
if count > 0 {
up := updateCol{" Murmur64Hash = Murmur64Hash+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" Murmur64Hash = Murmur64Hash+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" Murmur64Hash = Murmur64Hash- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" Murmur64Hash = Murmur64Hash- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
//ints
func (u *__Action_Updater) CreatedTime(newVal int) *__Action_Updater {
up := updateCol{" CreatedTime = " + u.nextDollar(), newVal}
u.updates = append(u.updates, up)
// u.updates[" CreatedTime = " + u.nextDollar()] = newVal
return u
}
func (u *__Action_Updater) CreatedTime_Increment(count int) *__Action_Updater {
if count > 0 {
up := updateCol{" CreatedTime = CreatedTime+ " + u.nextDollar(), count}
u.updates = append(u.updates, up)
//u.updates[" CreatedTime = CreatedTime+ " + u.nextDollar()] = count
}
if count < 0 {
up := updateCol{" CreatedTime = CreatedTime- " + u.nextDollar(), count}
u.updates = append(u.updates, up)
// u.updates[" CreatedTime = CreatedTime- " + u.nextDollar() ] = -(count) //make it positive
}
return u
}
//string
/////////////////////////////////////////////////////////////////////
/////////////////////// Selector ///////////////////////////////////
//Select_* can just be used with: .GetString() , .GetStringSlice(), .GetInt() ..GetIntSlice()
func (u *__Action_Selector) OrderBy_ActionId_Desc() *__Action_Selector {
u.orderBy = " ORDER BY ActionId DESC "
return u
}
func (u *__Action_Selector) OrderBy_ActionId_Asc() *__Action_Selector {
u.orderBy = " ORDER BY ActionId ASC "
return u
}
func (u *__Action_Selector) Select_ActionId() *__Action_Selector {
u.selectCol = "ActionId"
return u
}
func (u *__Action_Selector) OrderBy_ActorUserId_Desc() *__Action_Selector {
u.orderBy = " ORDER BY ActorUserId DESC "
return u
}
func (u *__Action_Selector) OrderBy_ActorUserId_Asc() *__Action_Selector {
u.orderBy = " ORDER BY ActorUserId ASC "
return u
}
func (u *__Action_Selector) Select_ActorUserId() *__Action_Selector {
u.selectCol = "ActorUserId"
return u
}
func (u *__Action_Selector) OrderBy_ActionType_Desc() *__Action_Selector {
u.orderBy = " ORDER BY ActionType DESC "
return u
}
func (u *__Action_Selector) OrderBy_ActionType_Asc() *__Action_Selector {
u.orderBy = " ORDER BY ActionType ASC "
return u
}
func (u *__Action_Selector) Select_ActionType() *__Action_Selector {
u.selectCol = "ActionType"
return u
}
func (u *__Action_Selector) OrderBy_PeerUserId_Desc() *__Action_Selector {
u.orderBy = " ORDER BY PeerUserId DESC "
return u
}
func (u *__Action_Selector) OrderBy_PeerUserId_Asc() *__Action_Selector {
u.orderBy = " ORDER BY PeerUserId ASC "
return u
}
func (u *__Action_Selector) Select_PeerUserId() *__Action_Selector {
u.selectCol = "PeerUserId"
return u
}
func (u *__Action_Selector) OrderBy_PostId_Desc() *__Action_Selector {
u.orderBy = " ORDER BY PostId DESC "
return u
}
func (u *__Action_Selector) OrderBy_PostId_Asc() *__Action_Selector {
u.orderBy = " ORDER BY PostId ASC "
return u
}
func (u *__Action_Selector) Select_PostId() *__Action_Selector {
u.selectCol = "PostId"
return u
}
func (u *__Action_Selector) OrderBy_CommentId_Desc() *__Action_Selector {
u.orderBy = " ORDER BY CommentId DESC "
return u
}
func (u *__Action_Selector) OrderBy_CommentId_Asc() *__Action_Selector {
u.orderBy = " ORDER BY CommentId ASC "
return u
}
func (u *__Action_Selector) Select_CommentId() *__Action_Selector {
u.selectCol = "CommentId"
return u
}
func (u *__Action_Selector) OrderBy_Murmur64Hash_Desc() *__Action_Selector {
u.orderBy = " ORDER BY Murmur64Hash DESC "
return u
}
func (u *__Action_Selector) OrderBy_Murmur64Hash_Asc() *__Action_Selector {
u.orderBy = " ORDER BY Murmur64Hash ASC "
return u
}
func (u *__Action_Selector) Select_Murmur64Hash() *__Action_Selector {
u.selectCol = "Murmur64Hash"
return u
}
func (u *__Action_Selector) OrderBy_CreatedTime_Desc() *__Action_Selector {
u.orderBy = " ORDER BY CreatedTime DESC "
return u
}
func (u *__Action_Selector) OrderBy_CreatedTime_Asc() *__Action_Selector {
u.orderBy = " ORDER BY CreatedTime ASC "
return u
}
func (u *__Action_Selector) Select_CreatedTime() *__Action_Selector {
u.selectCol = "CreatedTime"
return u
}
func (u *__Action_Selector) Limit(num int) *__Action_Selector {
u.limit = num
return u
}
func (u *__Action_Selector) Offset(num int) *__Action_Selector {
u.offset = num
return u
}
func (u *__Action_Selector) Order_Rand() *__Action_Selector {
u.orderBy = " ORDER BY RAND() "
return u
}
///////////////////////// Queryer Selector //////////////////////////////////
func (u *__Action_Selector) _stoSql() (string, []interface{}) {
sqlWherrs, whereArgs := whereClusesToSql(u.wheres, u.whereSep)
sqlstr := "SELECT " + u.selectCol + " FROM sun.action"
if len(strings.Trim(sqlWherrs, " ")) > 0 { //2 for safty
sqlstr += " WHERE " + sqlWherrs
}
if u.orderBy != "" {
sqlstr += u.orderBy
}
if u.limit != 0 {
sqlstr += " LIMIT " + strconv.Itoa(u.limit)
}
if u.offset != 0 {
sqlstr += " OFFSET " + strconv.Itoa(u.offset)
}
return sqlstr, whereArgs
}
func (u *__Action_Selector) GetRow(db *sqlx.DB) (*Action, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Action {
XOLog(sqlstr, whereArgs)
}
row := &Action{}
//by Sqlx
err = db.Get(row, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return nil, err
}
row._exists = true
OnAction_LoadOne(row)
return row, nil
}
func (u *__Action_Selector) GetRows(db *sqlx.DB) ([]*Action, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Action {
XOLog(sqlstr, whereArgs)
}
var rows []*Action
//by Sqlx
err = db.Unsafe().Select(&rows, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return nil, err
}
/*for i:=0;i< len(rows);i++ {
rows[i]._exists = true
}*/
for i := 0; i < len(rows); i++ {
rows[i]._exists = true
}
OnAction_LoadMany(rows)
return rows, nil
}
//dep use GetRows()
func (u *__Action_Selector) GetRows2(db *sqlx.DB) ([]Action, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Action {
XOLog(sqlstr, whereArgs)
}
var rows []*Action
//by Sqlx
err = db.Unsafe().Select(&rows, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return nil, err
}
/*for i:=0;i< len(rows);i++ {
rows[i]._exists = true
}*/
for i := 0; i < len(rows); i++ {
rows[i]._exists = true
}
OnAction_LoadMany(rows)
rows2 := make([]Action, len(rows))
for i := 0; i < len(rows); i++ {
cp := *rows[i]
rows2[i] = cp
}
return rows2, nil
}
func (u *__Action_Selector) GetString(db *sqlx.DB) (string, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Action {
XOLog(sqlstr, whereArgs)
}
var res string
//by Sqlx
err = db.Get(&res, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return "", err
}
return res, nil
}
func (u *__Action_Selector) GetStringSlice(db *sqlx.DB) ([]string, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Action {
XOLog(sqlstr, whereArgs)
}
var rows []string
//by Sqlx
err = db.Select(&rows, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return nil, err
}
return rows, nil
}
func (u *__Action_Selector) GetIntSlice(db *sqlx.DB) ([]int, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Action {
XOLog(sqlstr, whereArgs)
}
var rows []int
//by Sqlx
err = db.Select(&rows, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return nil, err
}
return rows, nil
}
func (u *__Action_Selector) GetInt(db *sqlx.DB) (int, error) {
var err error
sqlstr, whereArgs := u._stoSql()
if LogTableSqlReq.Action {
XOLog(sqlstr, whereArgs)
}
var res int
//by Sqlx
err = db.Get(&res, sqlstr, whereArgs...)
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return 0, err
}
return res, nil
}
///////////////////////// Queryer Update Delete //////////////////////////////////
func (u *__Action_Updater) Update(db XODB) (int, error) {
var err error
var updateArgs []interface{}
var sqlUpdateArr []string
/*for up, newVal := range u.updates {
sqlUpdateArr = append(sqlUpdateArr, up)
updateArgs = append(updateArgs, newVal)
}*/
for _, up := range u.updates {
sqlUpdateArr = append(sqlUpdateArr, up.col)
updateArgs = append(updateArgs, up.val)
}
sqlUpdate := strings.Join(sqlUpdateArr, ",")
sqlWherrs, whereArgs := whereClusesToSql(u.wheres, u.whereSep)
var allArgs []interface{}
allArgs = append(allArgs, updateArgs...)
allArgs = append(allArgs, whereArgs...)
sqlstr := `UPDATE sun.action SET ` + sqlUpdate
if len(strings.Trim(sqlWherrs, " ")) > 0 { //2 for safty
sqlstr += " WHERE " + sqlWherrs
}
if LogTableSqlReq.Action {
XOLog(sqlstr, allArgs)
}
res, err := db.Exec(sqlstr, allArgs...)
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return 0, err
}
num, err := res.RowsAffected()
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return 0, err
}
return int(num), nil
}
func (d *__Action_Deleter) Delete(db XODB) (int, error) {
var err error
var wheresArr []string
for _, w := range d.wheres {
wheresArr = append(wheresArr, w.condition)
}
wheresStr := strings.Join(wheresArr, d.whereSep)
var args []interface{}
for _, w := range d.wheres {
args = append(args, w.args...)
}
sqlstr := "DELETE FROM sun.action WHERE " + wheresStr
// run query
if LogTableSqlReq.Action {
XOLog(sqlstr, args)
}
res, err := db.Exec(sqlstr, args...)
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return 0, err
}
// retrieve id
num, err := res.RowsAffected()
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return 0, err
}
return int(num), nil
}
///////////////////////// Mass insert - replace for Action ////////////////
func MassInsert_Action(rows []Action, db XODB) error {
if len(rows) == 0 {
return errors.New("rows slice should not be empty - inserted nothing")
}
var err error
ln := len(rows)
// insVals_:= strings.Repeat(s, ln)
// insVals := insVals_[0:len(insVals_)-1]
insVals := helper.SqlManyDollars(8, ln, true)
// sql query
sqlstr := "INSERT INTO sun.action (" +
"ActionId, ActorUserId, ActionType, PeerUserId, PostId, CommentId, Murmur64Hash, CreatedTime" +
") VALUES " + insVals
// run query
vals := make([]interface{}, 0, ln*5) //5 fields
for _, row := range rows {
// vals = append(vals,row.UserId)
vals = append(vals, row.ActionId)
vals = append(vals, row.ActorUserId)
vals = append(vals, row.ActionType)
vals = append(vals, row.PeerUserId)
vals = append(vals, row.PostId)
vals = append(vals, row.CommentId)
vals = append(vals, row.Murmur64Hash)
vals = append(vals, row.CreatedTime)
}
if LogTableSqlReq.Action {
XOLog(sqlstr, " MassInsert len = ", ln, vals)
}
_, err = db.Exec(sqlstr, vals...)
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return err
}
return nil
}
func MassReplace_Action(rows []Action, db XODB) error {
if len(rows) == 0 {
return errors.New("rows slice should not be empty - inserted nothing")
}
var err error
ln := len(rows)
// insVals_:= strings.Repeat(s, ln)
// insVals := insVals_[0:len(insVals_)-1]
insVals := helper.SqlManyDollars(8, ln, true)
// sql query
sqlstr := "REPLACE INTO sun.action (" +
"ActionId, ActorUserId, ActionType, PeerUserId, PostId, CommentId, Murmur64Hash, CreatedTime" +
") VALUES " + insVals
// run query
vals := make([]interface{}, 0, ln*5) //5 fields
for _, row := range rows {
// vals = append(vals,row.UserId)
vals = append(vals, row.ActionId)
vals = append(vals, row.ActorUserId)
vals = append(vals, row.ActionType)
vals = append(vals, row.PeerUserId)
vals = append(vals, row.PostId)
vals = append(vals, row.CommentId)
vals = append(vals, row.Murmur64Hash)
vals = append(vals, row.CreatedTime)
}
if LogTableSqlReq.Action {
XOLog(sqlstr, " MassReplace len = ", ln, vals)
}
_, err = db.Exec(sqlstr, vals...)
if err != nil {
if LogTableSqlReq.Action {
XOLogErr(err)
}
return err
}
return nil
}
//////////////////// Play ///////////////////////////////
//
//
//
//
//
//
//
//
|
package arriba
import (
"testing"
)
func TestGetFunctions(*testing.T) {
GetFunctions(html1)
}
const html1 = (`
<!DOCTYPE html>
<html>
<head >
<meta content="text/html; charset=UTF-8" http-equiv="content-type" />
<title>Home</title>
</head>
<body>
<div data-lift="surround?with=default;at=content">
<h2>Welcome to your project!</h2>
<p><span data-lift="helloWorld.howdy">Welcome to your Lift app at <span id="time">Time goes here</span></span></p>
</div>
</body>
</html>
`)
const html2 = (`<html><head></head><body><div data-lift="goFunctionName"><p name="name">Diego</p><p class="pretty-last-name">Medina</p></div></body></html>`)
const html3 = (`<span data-lift="helloWorld.howdy">Welcome to your Lift app at <span id="time">Time goes here</span></span>`)
|
package site
import (
"time"
"github.com/valyala/fasthttp"
)
// Site handler
type Site struct {
timeout time.Duration
}
// GetDatа function for get data from url
func (s *Site) GetDatа(url string) (data []byte, err error) {
_, data, err = fasthttp.GetTimeout(nil, url, s.timeout)
return
}
// NewSite constructor site handler
func NewSite(timeout time.Duration) *Site {
return &Site{
timeout: timeout,
}
}
|
package main
import (
"net/http"
"net/url"
"os"
)
func main() {
if len(os.Args) != 2 {
panic("Bad Arguments")
}
url, err := url.Parse(os.Args[1])
if err != nil {
panic(err)
}
url.Scheme = "https"
http.ListenAndServe("0.0.0.0:8080", http.RedirectHandler(url.String(), 301))
}
|
package main
import (
"LanguageBotService/grpcUtil"
"LanguageBotService/wordgen"
"fmt"
"golang.org/x/net/context"
"google.golang.org/grpc"
"log"
"net"
"os"
)
func Init(){
PORT := os.Getenv("PORT")
TcpAddress := os.Getenv("TCP_ADDRESS")
lis, err := net.Listen("tcp", TcpAddress + PORT)
if err != nil{
log.Fatal("Could not initialize listener due to ", err.Error())
}
fmt.Println("Running server on port:",PORT)
s := grpc.NewServer()
grpcUtil.RegisterBotServiceServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("Failed to start server %v", err)
}
}
type server struct {
}
func (s server) GenerateWord(ctx context.Context, request *grpcUtil.WordRequest) (*grpcUtil.WordResponse, error) {
charCount := request.GetWordCount()
wordRes, err := wordgen.GetAndReturnWordForCount(int(charCount))
if err != nil{
return &grpcUtil.WordResponse{
Status: false,
Message: err.Error(),
Data: nil,
}, nil
}
var def []string
var example [] string
var partsOfSpeech [] string
for _,word := range wordRes.WordData{
for _,meaning := range word.Meaning {
fmt.Println("Meaning POS here is ", meaning.PartOfSpeech)
partsOfSpeech = append(partsOfSpeech, meaning.PartOfSpeech)
for _,defin := range meaning.Definitions{
if defin.Definition != ""{
def = append(def,defin.Definition)
}
if defin.Example != ""{
example = append(example,defin.Example)
}
}
}
}
resp := &grpcUtil.WordResponse{
Status: true,
Message: "Successfully received generated word",
Data: &grpcUtil.WordData{
Word: wordRes.WordText,
PartOfSpeech: partsOfSpeech,
Definition: def,
Example: example,
},
}
return resp, nil
}
|
package main
import (
"flag"
"fmt"
"net/http"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
)
func main() {
// server port
ServerPort := flag.String("server-port", ":8084", "server port")
//database connection
DBHost := flag.String("db-host", "localhost", "db host")
DBPort := flag.Int("db-port", 5432, "db port")
DBUser := flag.String("db-user", "esteecoinbase", "db user")
DBPassword := flag.String("db-pw", "dev", "db password")
DBName := flag.String("db-name", "esteecoinbase", "db name")
//email
Scheme := flag.String("scheme", "http", "scheme for http or https")
ServerDomain := flag.String("server-domain", "cryptotracker.interns.theninja.life", "server domain name")
EmailAPIKey := flag.String("email-api-key", "", "api key for sending email")
EmailDomain := flag.String("email-domain", "", "domain name for sending email")
flag.Parse()
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
*DBHost, *DBPort, *DBUser, *DBPassword, *DBName)
conn, err := sqlx.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer conn.Close()
err = conn.Ping()
if err != nil {
panic(err)
}
DBDriver := &DBDriver{Conn: conn}
emailDomain := &SendEmailInfo{EmailAPIKey: *EmailAPIKey, ServerDomain: *ServerDomain, EmailDomain: *EmailDomain, Scheme: *Scheme}
api := &API{DB: DBDriver, EmailInfo: emailDomain}
r := api.setupHttp()
err = http.ListenAndServe(*ServerPort, r)
if err != nil {
fmt.Println("ListenAndServe: ", err)
}
}
|
package controllers
import (
"context"
// "log"
// tspb "github.com/golang/protobuf/ptypes/timestamp"
pb "github.com/growlog/rpc/protos"
)
func (s *ThingServer) SetSensor(ctx context.Context, in *pb.SetSensorRequest) (*pb.SetSensorResponse, error) {
return &pb.SetSensorResponse{
Message: "Sensor was created",
Status: true,
}, nil
}
|
package obs
import "errors"
// TracerConfig stores tracer configuration.
type TracerConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
ZipkinURL string `json:"zipkin-url" yaml:"zipkin-url"`
}
// SetDefault sets sane default for tracer's config.
func (c *TracerConfig) SetDefault() {
c.Enabled = false
}
// Validate makes sure config has valid values.
func (c *TracerConfig) Validate() error {
if !c.Enabled {
return nil
}
if c.ZipkinURL == "" {
return errors.New("zipkin url should not be empty")
}
return nil
}
|
package avail
import (
"context"
"sync/atomic"
"time"
"github.com/XiaoMi/pegasus-go-client/pegasus"
log "github.com/sirupsen/logrus"
)
// Detector periodically checks the service availability of the Pegasus cluster.
type Detector interface {
// Start detection until the ctx cancelled. This method will block the current thread.
Start(ctx context.Context) error
}
// NewDetector returns a service-availability detector.
func NewDetector(client pegasus.Client) Detector {
return &pegasusDetector{client: client}
}
type pegasusDetector struct {
// client reads and writes periodically to a specified table.
client pegasus.Client
detectTable pegasus.TableConnector
detectInterval time.Duration
detectTableName string
// timeout of a single detect
detectTimeout time.Duration
detectHashKeys [][]byte
recentMinuteDetectTimes uint64
recentMinuteFailureTimes uint64
recentHourDetectTimes uint64
recentHourFailureTimes uint64
recentDayDetectTimes uint64
recentDayFailureTimes uint64
}
func (d *pegasusDetector) Start(rootCtx context.Context) error {
var err error
ctx, _ := context.WithTimeout(rootCtx, 10*time.Second)
d.detectTable, err = d.client.OpenTable(ctx, d.detectTableName)
if err != nil {
return err
}
ticker := time.NewTicker(d.detectInterval)
for {
select {
case <-rootCtx.Done(): // check if context cancelled
return nil
case <-ticker.C:
return nil
default:
}
// periodically set/get a configured Pegasus table.
d.detect();
}
return nil
}
func (d *pegasusDetector) detect() {
}
func (d *pegasusDetector) generateHashKeys() {
}
func (d *pegasusDetector) writeResult() {
}
func (d *pegasusDetector) detectPartition(rootCtx context.Context, partitionIdx int) {
d.incrDetectTimes()
go func() {
ctx, _ := context.WithTimeout(rootCtx, d.detectTimeout)
hashkey := d.detectHashKeys[partitionIdx]
value := []byte("")
if err := d.detectTable.Set(ctx, hashkey, []byte(""), value); err != nil {
d.incrFailureTimes()
log.Errorf("set partition [%d] failed, hashkey=\"%s\": %s", partitionIdx, err)
}
if _, err := d.detectTable.Get(ctx, hashkey, []byte("")); err != nil {
d.incrFailureTimes()
log.Errorf("get partition [%d] failed, hashkey=\"%s\": %s", partitionIdx, err)
}
}()
}
func (d *pegasusDetector) incrDetectTimes() {
atomic.AddUint64(&d.recentMinuteDetectTimes, 1)
atomic.AddUint64(&d.recentHourDetectTimes, 1)
atomic.AddUint64(&d.recentDayDetectTimes, 1)
}
func (d *pegasusDetector) incrFailureTimes() {
atomic.AddUint64(&d.recentMinuteFailureTimes, 1)
atomic.AddUint64(&d.recentHourFailureTimes, 1)
atomic.AddUint64(&d.recentDayFailureTimes, 1)
}
|
package models
import (
"time"
)
type UserFavoriteItem struct {
UserID uint64 `json:"user_id" gorm:"column:user_id;primary_key" sql:"not null;type:bigint(20);index:idx_fav_user_id_item_id"`
ItemID uint64 `json:"item_id" gorm:"column:item_id;primary_key" sql:"not null;type:bigint(20);index:idx_fav_user_id_item_id"`
CreatedAt time.Time `json:"created_at" gorm:"column:created_at" sql:"not null;type:datetime"`
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at" sql:"not null;type:datetime"`
}
func NewUserFavoriteItem(userID, itemID uint64) *UserFavoriteItem {
return &UserFavoriteItem{
UserID: userID,
ItemID: itemID,
}
}
func (e UserFavoriteItem) TableName() string {
return "user_favorite_item"
}
|
/*
Goal:
The goal of this challenge is to take a simple 6 row by 6 column XML file (without the standard XML header) and parse it out so that the program can return the value of a cell given it's coordinates.
The entry with the shortest overall length by language and overall will be declared the winner.
Additional information:
The XML syntax will always be an HTML table with each inner level being indented by four single spaces. You may assume that every file put into the program will be exactly like the one given below.
If your program uses imports you do not need to include them in the golfed version of your code but you must submit a copy of the program in the explanation that shows all imports used. This explanation will not effect your entries byte count.
Rules:
The XML file cannot be hardcoded
XML libraries/functions cannot be used
Extra Credit:
Can pretty print the table if given the --all flag (20 bytes off of total)
Can print all entries of a column given the column number in --col=number (20 bytes off of total)
Can print all entries of a row given the row number in --row=number (20 bytes off of total)
Can parse any size file as long as #rows = #columns (40 bytes off of total)
XML File:
<table>
<tr>
<th>Foo</th>
<th>Bar</th>
<th>Baz</th>
<th>Cat</th>
<th>Dog</th>
<th>Grinch</th>
</tr>
<tr>
<th>Something</th>
<th>Something</th>
<th>Darkside</th>
<th>Star</th>
<th>Wars</th>
<th>Chicken</th>
</tr>
<tr>
<th>Star</th>
<th>Trek</th>
<th>Xbox</th>
<th>Words</th>
<th>Too</th>
<th>Many</th>
</tr>
<tr>
<th>Columns</th>
<th>Not</th>
<th>Enough</th>
<th>Words</th>
<th>To</th>
<th>Fill</th>
</tr>
<tr>
<th>Them</th>
<th>So</th>
<th>I</th>
<th>Will</th>
<th>Do</th>
<th>My</th>
</tr>
<tr>
<th>Best</th>
<th>To</th>
<th>Fill</th>
<th>Them</th>
<th>All</th>
<th>Up</th>
</tr>
</table>
*/
package main
import (
"encoding/xml"
"flag"
"fmt"
"log"
"os"
)
var (
all = flag.Bool("all", true, "dump table")
row = flag.Int("row", 0, "dump row")
col = flag.Int("col", 0, "dump col")
)
func main() {
log.SetFlags(0)
log.SetPrefix("compact-xml-parser: ")
flag.Usage = usage
flag.Parse()
if flag.NArg() != 1 {
usage()
}
values, rows, cols, err := parse(flag.Arg(0))
check(err)
switch {
case 1 <= *row && *row <= rows:
for _, value := range values[*row-1] {
fmt.Printf("%-16s", value)
}
fmt.Println()
case 1 <= *col && *col <= cols:
for i := range values {
fmt.Printf("%-16s\n", values[i][*col-1])
}
case *all:
for i := range values {
for j := range values[i] {
fmt.Printf("%-16s", values[i][j])
}
fmt.Println()
}
}
}
func usage() {
fmt.Fprintln(os.Stderr, "usage: [options] file")
flag.PrintDefaults()
os.Exit(2)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func parse(name string) (values [][]string, rows, cols int, err error) {
data, err := os.ReadFile(name)
if err != nil {
return
}
var table struct {
Tr []struct {
Th []string `xml:"th"`
} `xml:"tr"`
}
err = xml.Unmarshal(data, &table)
if err != nil {
return
}
for _, tr := range table.Tr {
var value []string
for _, th := range tr.Th {
value = append(value, th)
}
values = append(values, value)
}
rows = len(values)
if rows == 0 {
err = fmt.Errorf("table has no rows")
return
}
cols = len(values[0])
if cols == 0 {
err = fmt.Errorf("table has no columns")
return
}
for i := range values {
if len(values[i]) != cols {
err = fmt.Errorf("table has mismatched number of columns")
return
}
}
return
}
|
package trea
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01300101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:trea.013.001.01 Document"`
Message *WithdrawalNotificationV01 `xml:"WdrwlNtfctnV01"`
}
func (d *Document01300101) AddMessage() *WithdrawalNotificationV01 {
d.Message = new(WithdrawalNotificationV01)
return d.Message
}
// Scope
// The WithdrawalNotification message is sent by a central system to notify the withdrawal of a trade which was previously notified to the receiver as an alleged trade.
// Usage
// The message is used to confirm the cancellation of a previously notified trade.
type WithdrawalNotificationV01 struct {
// Reference assigned by the central matching system which is notifying the deletion of a previously reported trade.
MatchingSystemUniqueReference *iso20022.MessageReference `xml:"MtchgSysUnqRef"`
}
func (w *WithdrawalNotificationV01) AddMatchingSystemUniqueReference() *iso20022.MessageReference {
w.MatchingSystemUniqueReference = new(iso20022.MessageReference)
return w.MatchingSystemUniqueReference
}
|
package client
import (
"context"
"fmt"
"github.com/wish/ctl/pkg/client/types"
batchv1 "k8s.io/api/batch/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"time"
)
// RunCronJob creates a new job with timestamp from the specified cron job template
func (c *Client) RunCronJob(contexts []string, namespace, cronjobName string, options ListOptions) (*types.JobDiscovery, error) {
cronjob, err := c.findCronJob(contexts, namespace, cronjobName, options)
if err != nil {
return nil, err
}
cl, err := c.getContextInterface(cronjob.Context)
if err != nil {
panic(err.Error())
}
job, err := cl.BatchV1().Jobs(cronjob.Namespace).Create(
context.TODO(),
&batchv1.Job{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("%s-%d", cronjobName, time.Now().Unix()), // REVIEW: What if name is not unique??
Namespace: cronjob.Namespace,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: "batch/v1beta1",
Kind: "CronJob",
Name: cronjob.Name,
UID: cronjob.UID,
// TODO: Set the Controller and BlockOwnerDeletion fields
},
},
},
Spec: cronjob.CronJob.Spec.JobTemplate.Spec,
},
metav1.CreateOptions{})
if err != nil {
return nil, err
}
return &types.JobDiscovery{cronjob.Context, *job}, nil
}
|
package paths
import (
"testing"
"github.com/criteo/graphite-remote-adapter/client/graphite/config"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/require"
yaml "gopkg.in/yaml.v2"
)
var (
metric = model.Metric{
model.MetricNameLabel: "test:metric",
"testlabel": "test:value",
"owner": "team-X",
"many_chars": "abc!ABC:012-3!45ö67~89./(){},=.\"\\",
}
metricY = model.Metric{
model.MetricNameLabel: "test:metric",
"testlabel": "test:value",
"owner": "team-Y",
"many_chars": "abc!ABC:012-3!45ö67~89./(){},=.\"\\",
}
testConfigStr = `
write:
template_data:
shared: data.foo
rules:
- match:
owner: team-X
match_re:
testlabel: ^test:.*$
template: 'tmpl_1.{{.shared | escape}}.{{.labels.owner}}'
continue: true
- match:
owner: team-X
testlabel2: test:value2
template: 'tmpl_2.{{.labels.owner}}.{{.shared}}'
continue: false
- match:
owner: team-Y
template: 'tmpl_3.{{.labels.owner}}.{{.shared}}'
continue: false
- match:
owner: team-Z
continue: false`
testConfig = loadTestConfig(testConfigStr)
)
func loadTestConfig(s string) *config.Config {
cfg := &config.Config{}
if err := yaml.Unmarshal([]byte(string(s)), cfg); err != nil {
return nil
}
return cfg
}
func TestDefaultPathsFromMetric(t *testing.T) {
expected := "prefix." +
"test:metric" +
".many_chars.abc!ABC:012-3!45%C3%B667~89%2E%2F\\(\\)\\{\\}\\,%3D%2E\\\"\\\\" +
".owner.team-X" +
".testlabel.test:value"
actual, err := pathsFromMetric(metric, Format{Type: FormatCarbon}, "prefix.", nil, nil)
require.Equal(t, expected, actual[0])
require.Empty(t, err)
expected = "prefix." +
"test:metric" +
";many_chars=abc!ABC:012-3!45%C3%B667~89%2E%2F\\(\\)\\{\\}\\,%3D%2E\\\"\\\\" +
";owner=team-X" +
";testlabel=test:value"
actual, err = pathsFromMetric(metric, Format{Type: FormatCarbonTags}, "prefix.", nil, nil)
require.Equal(t, expected, actual[0])
require.Empty(t, err)
expected = "prefix." +
"test:metric{" +
"many_chars=\"abc!ABC:012-3!45%C3%B667~89%2E%2F\\(\\)\\{\\}\\,%3D%2E\\\"\\\\\"" +
",owner=\"team-X\"" +
",testlabel=\"test:value\"" +
"}"
actual, err = pathsFromMetric(metric, Format{Type: FormatCarbonOpenMetrics}, "prefix.", nil, nil)
require.Equal(t, expected, actual[0])
require.Empty(t, err)
}
func TestDefaultPathWithFilteredTags(t *testing.T) {
expected := "prefix." +
"test:metric" +
".many_chars.abc!ABC:012-3!45%C3%B667~89%2E%2F\\(\\)\\{\\}\\,%3D%2E\\\"\\\\" +
".owner.team-X" +
".testlabel.test:value"
actual, err := pathsFromMetric(metric, Format{Type: FormatCarbon}, "prefix.", nil, nil)
require.Equal(t, expected, actual[0])
require.Empty(t, err)
// With filtered tags, it doesn't change, as format didn't change.
actual, err = pathsFromMetric(metric, Format{Type: FormatCarbon, FilteredTags: []string{"owner"}}, "prefix.", nil, nil)
require.Equal(t, expected, actual[0])
require.Empty(t, err)
expected = "prefix." +
"test:metric" +
".many_chars.abc!ABC:012-3!45%C3%B667~89%2E%2F\\(\\)\\{\\}\\,%3D%2E\\\"\\\\" +
".testlabel.test:value" +
";owner=team-X"
actual, err = pathsFromMetric(metric, Format{Type: FormatCarbonTags, FilteredTags: []string{"owner"}}, "prefix.", nil, nil)
require.Equal(t, expected, actual[0])
require.Empty(t, err)
expected = "prefix." +
"test:metric" +
".many_chars.abc!ABC:012-3!45%C3%B667~89%2E%2F\\(\\)\\{\\}\\,%3D%2E\\\"\\\\" +
";owner=team-X" +
";testlabel=test:value"
actual, err = pathsFromMetric(metric, Format{Type: FormatCarbonTags, FilteredTags: []string{"owner", "testlabel"}}, "prefix.", nil, nil)
require.Equal(t, expected, actual[0])
require.Empty(t, err)
}
func TestUnmatchedMetricPathsFromMetric(t *testing.T) {
unmatchedMetric := model.Metric{
model.MetricNameLabel: "test:metric",
"testlabel": "test:value",
"owner": "team-K",
"testlabel2": "test:value2",
}
expected := make([]string, 0)
expected = append(expected, "prefix."+
"test:metric"+
".owner.team-K"+
".testlabel.test:value"+
".testlabel2.test:value2")
actual, err := pathsFromMetric(unmatchedMetric, Format{Type: FormatCarbon}, "prefix.", testConfig.Write.Rules, testConfig.Write.TemplateData)
require.Equal(t, expected, actual)
require.Empty(t, err)
}
func TestTemplatedPathsFromMetric(t *testing.T) {
expected := make([]string, 0)
expected = append(expected, "tmpl_3.team-Y.data.foo")
actual, err := pathsFromMetric(metricY, Format{Type: FormatCarbon}, "", testConfig.Write.Rules, testConfig.Write.TemplateData)
require.Equal(t, expected, actual)
require.Empty(t, err)
}
func TestTemplatedPathsFromMetricWithDefault(t *testing.T) {
expected := make([]string, 0)
expected = append(expected, "tmpl_1.data%2Efoo.team-X")
expected = append(expected, "prefix."+
"test:metric"+
".many_chars.abc!ABC:012-3!45%C3%B667~89%2E%2F\\(\\)\\{\\}\\,%3D%2E\\\"\\\\"+
".owner.team-X"+
".testlabel.test:value")
actual, err := pathsFromMetric(metric, Format{Type: FormatCarbon}, "prefix.", testConfig.Write.Rules, testConfig.Write.TemplateData)
require.Equal(t, expected, actual)
require.Empty(t, err)
}
func TestMultiTemplatedPathsFromMetric(t *testing.T) {
multiMatchMetric := model.Metric{
model.MetricNameLabel: "test:metric",
"testlabel": "test:value",
"owner": "team-X",
"testlabel2": "test:value2",
}
expected := make([]string, 0)
expected = append(expected, "tmpl_1.data%2Efoo.team-X")
expected = append(expected, "tmpl_2.team-X.data.foo")
actual, err := pathsFromMetric(multiMatchMetric, Format{Type: FormatCarbon}, "prefix.", testConfig.Write.Rules, testConfig.Write.TemplateData)
require.Equal(t, expected, actual)
require.Empty(t, err)
}
func TestSkipedTemplatedPathsFromMetric(t *testing.T) {
skipedMetric := model.Metric{
model.MetricNameLabel: "test:metric",
"testlabel": "test:value",
"owner": "team-Z",
"testlabel2": "test:value2",
}
t.Log(testConfig.Write.Rules[2])
actual, err := pathsFromMetric(skipedMetric, Format{Type: FormatCarbon}, "", testConfig.Write.Rules, testConfig.Write.TemplateData)
require.Empty(t, actual)
require.Empty(t, err)
}
func TestReplaceNilLabelTemplatedPathsFromMetric(t *testing.T) {
testConfigNilLabelStr := `
write:
rules:
- match_re:
testlabel: test:value
template: 'test.{{ replace .labels.doesnotexist " " "_" }}'
continue: false`
testConfigNilLabel := loadTestConfig(testConfigNilLabelStr)
t.Log(testConfigNilLabel.Write.Rules[0])
actual, err := pathsFromMetric(metric, Format{Type: FormatCarbon}, "", testConfigNilLabel.Write.Rules, testConfigNilLabel.Write.TemplateData)
require.Empty(t, actual)
require.Error(t, err)
}
|
package main
import "fmt"
func main() {
fmt.Println("Aprendiendo Go Lang de nuevo!")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.