content
stringlengths 44
6.13M
| membership
stringclasses 2
values |
|---|---|
package systems
import (
"image"
"sync"
"golang.org/x/image/colornames"
"github.com/brunoga/robomaster/sdk"
"github.com/EngoEngine/ecs"
"github.com/EngoEngine/engo"
"github.com/EngoEngine/engo/common"
)
type systemVideoEntity struct {
ecs.BasicEntity
*common.SpaceComponent
*common.RenderComponent
}
type Video struct {
entity *systemVideoEntity
client *sdk.Client
frameCh chan *image.NRGBA
}
func NewVideo(client *sdk.Client) *Video {
return &Video{
nil,
client,
make(chan *image.NRGBA, 1),
}
}
func (v *Video) Add() {
// We initialize everything we need internally.
}
func (v *Video) New(w *ecs.World) {
spaceComponent := &common.SpaceComponent{
Position: engo.Point{X: 0, Y: 0},
Width: 1280,
Height: 720,
}
rect := image.Rect(0, 0, 1280, 720)
img := image.NewNRGBA(rect)
obj := common.NewImageObject(img)
renderComponent := &common.RenderComponent{
Drawable: common.NewTextureSingle(obj),
}
v.entity = &systemVideoEntity{
ecs.NewBasic(),
spaceComponent,
renderComponent,
}
for _, system := range w.Systems() {
switch sys := system.(type) {
case *common.RenderSystem:
sys.Add(&v.entity.BasicEntity,
v.entity.RenderComponent,
v.entity.SpaceComponent)
}
}
videoModule := v.client.VideoModule()
videoModule.StartStream(v.videoHandler)
}
func (v *Video) Update(dt float32) {
select {
case img := <-v.frameCh:
obj := common.NewImageObject(img)
tex := common.NewTextureSingle(obj)
v.entity.Drawable.Close()
v.entity.Drawable = tex
default:
//do nothing
}
}
func (v *Video) Remove(e ecs.BasicEntity) {
if e.ID() == v.entity.ID() {
v.entity = nil
}
}
func (v *Video) Priority() int {
// Makes sure video updates after other systems.
return -10
}
func horizontalLine(img *image.NRGBA, y, x1, x2 int) {
for ; x1 <= x2; x1++ {
img.Set(x1, y, colornames.Greenyellow)
}
}
func verticalLine(img *image.NRGBA, x, y1, y2 int) {
for ; y1 <= y2; y1++ {
img.Set(x, y1, colornames.Greenyellow)
}
}
func (v *Video) videoHandler(frame *image.RGBA, wg *sync.WaitGroup) {
frameCopy := *(*image.NRGBA)(frame)
// Draw a simple crosshair.
horizontalLine(&frameCopy, sdk.CameraVerticalResolutionPoints/2,
(sdk.CameraHorizontalResolutionPoints/2)-50,
(sdk.CameraHorizontalResolutionPoints/2)+50)
verticalLine(&frameCopy, sdk.CameraHorizontalResolutionPoints/2,
(sdk.CameraVerticalResolutionPoints/2)-50,
(sdk.CameraVerticalResolutionPoints/2)+50)
v.frameCh <- &frameCopy
wg.Done()
}
|
member
|
package main
import (
"bufio"
"encoding/binary"
"flag"
influxdb2 "github.com/influxdata/influxdb-client-go/v2"
"github.com/influxdata/influxdb-client-go/v2/api"
"log"
"math"
"net"
"os"
"strings"
"time"
)
const hostname = "0.0.0.0" // Address to listen on (0.0.0.0 = all interfaces)
const port = "43110" // UDP Port number to listen on
const service = hostname + ":" + port // Combined hostname+port
// Telemetry struct represents a piece of telemetry as defined in the Forza data format (see the .dat files)
type Telemetry struct {
position int
name string
dataType string
startOffset int
endOffset int
}
func main() {
// Parse flags
horizonMode := flag.Bool("z", false, "Enables Forza Horizon 4 support (Will default to Forza Motorsport if unset)")
debugModePTR := flag.Bool("d", false, "Enables extra debug information if set")
flag.Parse()
if *debugModePTR {
log.Println("Debug mode enabled")
}
// Create InfluxDB Client
client := influxdb2.NewClient("http://localhost:8086", "zPD41f0LWTUzW6A9DxN0AzJqCffKtlKaH5KTeAQD02tK07o84dkTz5qeGoCNdc2uybsdT_9kCqy180coOhADfg==")
writeAPI := client.WriteAPI("forza", "telemetry")
defer client.Close()
// Switch to Horizon format if needed
var formatFile = "FM7_packetformat.dat" // Path to file containing Forzas data format
if *horizonMode {
formatFile = "FH4_packetformat.dat"
log.Println("Forza Horizon mode selected")
} else {
log.Println("Forza Motorsport mode selected")
}
// Load lines from packet format file
lines, err := readLines(formatFile)
if err != nil {
log.Fatalf("Error reading format file: %s", err)
}
// Process format file into array of Telemetry structs
startOffset := 0
endOffset := 0
dataLength := 0
var telemArray []Telemetry
log.Printf("Processing %s...", formatFile)
for i, line := range lines {
dataClean := strings.Split(line, ";") // remove comments after ; from data format file
dataFormat := strings.Split(dataClean[0], " ") // array containing data type and name
dataType := dataFormat[0]
dataName := dataFormat[1]
switch dataType {
case "s32": // Signed 32bit int
dataLength = 4 // Number of bytes
endOffset = endOffset + dataLength
startOffset = endOffset - dataLength
telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset} // Create new Telemetry item / data point
telemArray = append(telemArray, telemItem) // Add Telemetry item to main telemetry array
case "u32": // Unsigned 32bit int
dataLength = 4
endOffset = endOffset + dataLength
startOffset = endOffset - dataLength
telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset}
telemArray = append(telemArray, telemItem)
case "f32": // Floating point 32bit
dataLength = 4
endOffset = endOffset + dataLength
startOffset = endOffset - dataLength
telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset}
telemArray = append(telemArray, telemItem)
case "u16": // Unsigned 16bit int
dataLength = 2
endOffset = endOffset + dataLength
startOffset = endOffset - dataLength
telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset}
telemArray = append(telemArray, telemItem)
case "u8": // Unsigned 8bit int
dataLength = 1
endOffset = endOffset + dataLength
startOffset = endOffset - dataLength
telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset}
telemArray = append(telemArray, telemItem)
case "s8": // Signed 8bit int
dataLength = 1
endOffset = endOffset + dataLength
startOffset = endOffset - dataLength
telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset}
telemArray = append(telemArray, telemItem)
case "hzn": // Forza Horizon 4 unknown values (12 bytes of.. something)
dataLength = 12
endOffset = endOffset + dataLength
startOffset = endOffset - dataLength
telemItem := Telemetry{i, dataName, dataType, startOffset, endOffset}
telemArray = append(telemArray, telemItem)
default:
log.Fatalf("Error: Unknown data type in %s \n", formatFile)
}
//Debug format file processing:
if *debugModePTR {
log.Printf("Processed %s line %d: %s (%s), Byte offset: %d:%d \n", formatFile, i, dataName, dataType, startOffset, endOffset)
}
}
if *debugModePTR { // Print completed telemetry array
log.Printf("Logging entire telemArray: \n%v", telemArray)
}
log.Printf("Proccessed %d Telemetry types OK!", len(telemArray))
// Setup UDP listener
udpAddr, err := net.ResolveUDPAddr("udp4", service)
if err != nil {
log.Fatal(err)
}
listener, err := net.ListenUDP("udp", udpAddr)
check(err)
defer listener.Close() // close after main ends - probably not really needed
// log.Printf("Forza data out server listening on %s, waiting for Forza data...\n", service)
log.Printf("Forza data out server listening on %s:%s, waiting for Forza data...\n", GetOutboundIP(), port)
for { // main loop
readForzaData(listener, writeAPI, telemArray)
}
}
// readForzaData processes recieved UDP packets
func readForzaData(conn *net.UDPConn, writeAPI api.WriteAPI, telemArray []Telemetry) {
buffer := make([]byte, 1500)
n, addr, err := conn.ReadFromUDP(buffer)
if err != nil {
log.Fatal("Error reading UDP data:", err, addr)
}
if isFlagPassed("d") == true { // Print extra connection info if debugMode set
log.Println("UDP client connected:", addr)
// fmt.Printf("Raw Data from UDP client:\n%s", string(buffer[:n])) // Debug: Dump entire received buffer
}
currentEngineRpm := float32(0)
p := influxdb2.NewPointWithMeasurement("stat")
// Use Telemetry array to map raw data against Forza's data format
for i, T := range telemArray {
data := buffer[:n][T.startOffset:T.endOffset] // Process received data in chunks based on byte offsets
if isFlagPassed("d") == true { // if debugMode, print received data in each chunk
log.Printf("Data chunk %d: %v (%s) (%s)", i, data, T.name, T.dataType)
}
if T.name == "TimestampMS" {
timestamp := binary.LittleEndian.Uint32(data)
p = p.SetTime(time.Unix(0, int64(timestamp) * int64(time.Millisecond)))
} else if T.name == "CurrentEngineRpm" {
currentEngineRpm = Float32frombytes(data)
}
switch T.dataType { // each data type needs to be converted / displayed differently
case "s32":
case "u32":
// fmt.Println("Name:", T.name, "Type:", T.dataType, "value:", binary.LittleEndian.Uint32(data))
p = p.AddField(T.name, binary.LittleEndian.Uint32(data))
case "f32":
// fmt.Println("Name:", T.name, "Type:", T.dataType, "value:", (dataFloated * 1))
p = p.AddField(T.name, Float32frombytes(data))
case "u16":
// fmt.Println("Name:", T.name, "Type:", T.dataType, "value:", binary.LittleEndian.Uint16(data))
p = p.AddField(T.name, binary.LittleEndian.Uint16(data))
case "u8":
p = p.AddField(T.name, data[0])
case "s8":
p = p.AddField(T.name, int8(data[0]))
}
}
// Dont print / log / do anything if RPM is zero
// This happens if the game is paused or you rewind
// There is a bug with FH4 where it will continue to send data when in certain menus
if currentEngineRpm == 0 {
return
}
writeAPI.WritePoint(p.SetTime(time.Now()))
}
func init() {
log.SetFlags(log.Lmicroseconds)
log.Println("Started Forza Data Tools")
}
// Helper functions
// Quick error check helper
func check(e error) {
if e != nil {
log.Fatalln(e)
}
}
// Check if flag was passed
func isFlagPassed(name string) bool {
found := false
flag.Visit(func(f *flag.Flag) {
if f.Name == name {
found = true
}
})
return found
}
// Float32frombytes converts bytes into a float32
func Float32frombytes(bytes []byte) float32 {
bits := binary.LittleEndian.Uint32(bytes)
float := math.Float32frombits(bits)
return float
}
// readLines reads a whole file into memory and returns a slice of its lines
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
// GetOutboundIP finds preferred outbound ip of this machine
func GetOutboundIP() net.IP {
conn, err := net.Dial("udp", "1.2.3.4:4321") // Destination does not need to exist, using this to see which is the primary network interface
if err != nil {
log.Fatal(err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
}
|
non-member
|
package transformer
import (
"regexp"
"strings"
"unicode"
"unicode/utf8"
)
type capitalization int
const (
noCapitalization capitalization = iota
firstCapitzlized
allCapitalized
)
// Regexes for handling how to split messages into usable components.
var wordSplitRegex = regexp.MustCompile(`(\w+\b-+|\S+)[\n]*`)
var punctuationRegex = regexp.MustCompile(`^(\W+)|(\W+)$`)
var capitalRegex = regexp.MustCompile(`\b[A-Z]+`)
// WordMetadata is individual word metadata information.
type WordMetadata struct {
Capitalization capitalization
PrePunc string
PostPunc string
}
// This method might look a little contrived with the number of "if" statements
// checking if `meta` is nil. This is intentional. The point of this is to
// reduce heap allocations as much as possible by only creating meta as needed.
func createWordMetadata(word string) (*WordMetadata, string) {
var meta *WordMetadata
if idxs := punctuationRegex.FindAllStringIndex(word, 2); len(idxs) > 0 {
var pre, post string
if len(idxs) == 1 {
if idxs[0][0] == 0 {
pre = word[0:idxs[0][1]]
} else {
post = word[idxs[0][0]:idxs[0][1]]
}
} else {
pre = word[0:idxs[0][1]]
post = word[idxs[1][0]:idxs[1][1]]
}
meta = &WordMetadata{
PrePunc: pre,
PostPunc: post,
}
word = punctuationRegex.ReplaceAllLiteralString(word, "")
}
switch len(capitalRegex.FindString(word)) {
case 0:
if meta != nil {
meta.Capitalization = noCapitalization
}
case 1:
if meta == nil {
meta = &WordMetadata{}
}
meta.Capitalization = firstCapitzlized
word = strings.ToLower(word)
default:
if meta == nil {
meta = &WordMetadata{}
}
meta.Capitalization = allCapitalized
word = strings.ToLower(word)
}
return meta, word
}
// MessageMetadata contains a list of words and their associated metadata.
type MessageMetadata struct {
Words []string
Metadata []*WordMetadata
size uint32
}
// New initializes message metadata struct from a string.
func (m *MessageMetadata) New(message string) {
wordList := wordSplitRegex.FindAllString(message, -1)
m.size = uint32(len(message))
m.Words = make([]string, len(wordList))
m.Metadata = make([]*WordMetadata, len(wordList))
for idx, word := range wordList {
meta, normalizedWord := createWordMetadata(word)
m.Words[idx] = normalizedWord
m.Metadata[idx] = meta
}
}
func (m MessageMetadata) capitalize(word string, idx int) string {
if m.Metadata[idx] == nil {
return word
}
switch m.Metadata[idx].Capitalization {
case firstCapitzlized:
return capitalizeFirst(word)
case allCapitalized:
return strings.ToUpper(word)
default:
return word
}
}
func (m MessageMetadata) String() string {
builder := ReversibleStringBuilder{}
builder.Init()
// Grow the buffer so that we have some headroom over the original string.
builder.Grow(int(1.2 * float32(m.size)))
for idx, word := range m.Words {
if meta := m.Metadata[idx]; meta != nil {
builder.WriteString(meta.PrePunc)
builder.WriteString(m.capitalize(word, idx))
builder.WriteString(meta.PostPunc)
if !strings.HasSuffix(meta.PostPunc, "\n") {
builder.WriteString(" ")
}
} else {
builder.WriteString(word)
builder.WriteString(" ")
}
if builder.Len() >= 1997 {
builder.Reverse(-1)
builder.WriteString("....")
break
}
builder.Flush()
}
return builder.String()[:builder.Len()-1]
}
func capitalizeFirst(s string) string {
if len(s) > 0 {
r, sz := utf8.DecodeRuneInString(s)
if r != utf8.RuneError || sz > 1 {
upper := unicode.ToUpper(r)
if upper != r {
s = string(upper) + s[sz:]
}
}
}
return s
}
|
non-member
|
package main
import (
"testing"
)
func TestActivityNotifications(t *testing.T) {
cases := []struct {
result int
expected int
}{
{
countInversions([]int{1, 1, 1, 2, 2}), 0,
},
{
countInversions([]int{2, 1, 3, 1, 2}), 4,
},
}
for _, c := range cases {
if c.result != c.expected {
t.Errorf("Error got: %v, want: %v.", c.result, c.expected)
}
}
}
|
non-member
|
package mysqlparse
import (
"bytes"
"fmt"
"io"
"strings"
"github.com/xwb1989/sqlparser"
)
// Parse blabla
func Parse(sql string) {
tokens := sqlparser.NewTokenizer(strings.NewReader(sql))
for {
stmt, err := sqlparser.ParseNext(tokens)
if err == io.EOF {
// t.Error(err)
break
}
fmt.Println(parseStmt(stmt))
}
}
func parseStmt(stmt sqlparser.Statement) string {
switch stmt := (stmt).(type) {
case *sqlparser.Select:
return parseSelect(stmt)
case *sqlparser.Insert:
default:
return ""
}
return ""
}
func parseSelect(stmt *sqlparser.Select) string {
ret := " select "
ret += getStr(stmt.SelectExprs)
ret += " from " + getStr(stmt.From)
if stmt.Where != nil {
ret += " where "
ret += parseExpr(stmt.Where.Expr)
}
if stmt.GroupBy != nil {
}
return ret
}
func visit(node sqlparser.SQLNode) (kontinue bool, err error) {
return false, nil
}
func parseExpr(expr sqlparser.Expr) string {
expr.WalkSubtree(visit)
switch expr := expr.(type) {
case *sqlparser.AndExpr:
return parseExpr(expr.Left) + " and " + parseExpr(expr.Right)
case *sqlparser.OrExpr:
fmt.Println("OrExpr")
return parseExpr(expr.Left) + " or " + parseExpr(expr.Right)
case *sqlparser.NotExpr:
fmt.Println("NotExpr")
case *sqlparser.ParenExpr:
fmt.Println("ParenExpr")
case *sqlparser.ComparisonExpr:
fmt.Println("ComparisonExpr")
return parseExpr(expr.Left) + expr.Operator + parseExpr(expr.Right)
case *sqlparser.RangeCond:
fmt.Println("RangeCond")
case *sqlparser.IsExpr:
fmt.Println("IsExpr")
return getStr(expr)
case *sqlparser.ExistsExpr:
fmt.Println("ExistsExpr")
case *sqlparser.SQLVal:
fmt.Println("SQLVal")
return "?"
case *sqlparser.NullVal:
fmt.Println("NullVal")
case sqlparser.BoolVal:
fmt.Println("BoolVal")
case *sqlparser.ColName:
fmt.Println("ColName")
return expr.Name.String()
case sqlparser.ValTuple:
fmt.Println("ValTuple")
case *sqlparser.Subquery:
fmt.Println("Subquery")
case sqlparser.ListArg:
fmt.Println("ListArg")
case *sqlparser.BinaryExpr:
fmt.Println("BinaryExpr")
case *sqlparser.UnaryExpr:
fmt.Println("UnaryExpr")
case *sqlparser.IntervalExpr:
fmt.Println("IntervalExpr")
case *sqlparser.CollateExpr:
fmt.Println("CollateExpr")
case *sqlparser.FuncExpr:
fmt.Println("FuncExpr")
case *sqlparser.CaseExpr:
fmt.Println("CaseExpr")
case *sqlparser.ValuesFuncExpr:
fmt.Println("ValuesFuncExpr")
case *sqlparser.ConvertExpr:
fmt.Println("ConvertExpr")
case *sqlparser.ConvertUsingExpr:
fmt.Println("ConvertUsingExpr")
case *sqlparser.MatchExpr:
fmt.Println("MatchExpr")
case *sqlparser.GroupConcatExpr:
fmt.Println("GroupConcatExpr")
case *sqlparser.Default:
fmt.Println("Default")
default:
}
return ""
}
func getStr(node sqlparser.SQLNode) string {
buff := sqlparser.TrackedBuffer{}
buff.Buffer = new(bytes.Buffer)
node.Format(&buff)
return buff.String()
}
|
non-member
|
// user.go
package main
import (
"crypto/x509"
"database/sql"
"errors"
"fmt"
"strings"
"sync"
"github.com/golang/glog"
)
// -----------------------------------------------
type TUserProfil int
const (
ProfilNone = iota
ProfilAdmin
ProfilUser
)
// -----------------------------------------------
var userListLock sync.Mutex
var userList []HomeObject
// -----------------------------------------------
// getEmailFromCert : read received peer X509 certificates and return found email or err
func getEmailFromCert(peerCrt []*x509.Certificate) (email string, err error) {
if len(peerCrt) <= 0 {
err = errors.New("No certificat received")
glog.Error(err)
return
}
// With the certificats I build email is the 5th Attribut - this may chage given the CA settings (TODO : check, not sure)
if len(peerCrt[0].Subject.Names) < 5 {
err = errors.New(fmt.Sprintf("Did not locate email in (%s)", peerCrt[0].Subject.Names))
glog.Error(err)
return
}
email = peerCrt[0].Subject.Names[4].Value.(string)
return
}
// loadUsers : load all users from DB into global userList
// If force == false then only load if userList is empty
func loadUsers(db *sql.DB, force bool) (nbUser int, err error) {
if db == nil {
if db, err = openDB(); err != nil {
return
}
defer db.Close()
}
userListLock.Lock()
defer userListLock.Unlock()
nbUser = len(userList)
if nbUser > 0 && !force {
return
}
// read all users
userList, err = getHomeObjects(db, ItemUser, -1)
nbUser = len(userList)
return
}
// getUserFromCert : return user HomeObject or error if not found
func getUserFromCert(peerCrt []*x509.Certificate) (userObj HomeObject, err error) {
email, err := getEmailFromCert(peerCrt)
if err != nil {
return
}
if glog.V(2) {
glog.Infof("User email from cert = '%s'", email)
}
userObj, err = getUserFromEmail(email)
return
}
// getUserFromCode : return user HomeObject or error if not found
func getUserFromCode(db *sql.DB, userCode string) (userObj HomeObject, err error) {
if db == nil {
if db, err = openDB(); err != nil {
return
}
defer db.Close()
}
if userCode == "" {
err = errors.New(fmt.Sprintf("getUserFromCode returning (empty user code) : '%s'", userCode))
return
}
if glog.V(2) {
glog.Infof("User code = '%s'", userCode)
}
query, err := getGlobalParam(db, "Global", "UserOTP")
if err != nil {
glog.Errorf("getUserFromCode fail to get userOTP : %s", err)
return
}
rows, err := db.Query(query, userCode)
if err != nil {
glog.Errorf("getUserFromCode query fail (query=%s,userCode=%s) : %s ", query, userCode, err)
return
}
defer rows.Close()
var email string
if rows.Next() {
err = rows.Scan(&email)
if err != nil {
glog.Errorf("getUserFromCode scan fail (query=%s,userCode=%s) : %s ", query, userCode, err)
return
}
if err = rows.Err(); err != nil {
glog.Errorf("getUserFromCode rows.Err (query=%s,userCode=%s) : %s ", query, userCode, err)
return
}
} else {
if glog.V(2) {
glog.Infof("getUserFromCode cant validate user code : '%s'", userCode)
}
}
userObj, err = getUserFromEmail(email)
return
}
// getUserFromEmail : return user HomeObject or error if not found
func getUserFromEmail(email string) (userObj HomeObject, err error) {
_, err = loadUsers(nil, false)
if err != nil {
return
}
if email == "" {
err = errors.New(fmt.Sprintf("No user found (empty email) '%s'", email))
return
}
// Search a user with the email found in the certificat
userListLock.Lock()
defer userListLock.Unlock()
for _, obj := range userList {
if glog.V(3) {
glog.Info("User : ", obj)
}
val, err1 := obj.getStrVal("Email")
if err1 != nil || strings.ToUpper(val) != strings.ToUpper(email) {
continue
}
iProfil, err1 := obj.getIntVal("IdProfil")
if err1 != nil {
continue // ignore if no IdProfile field
}
iActive, err1 := obj.getIntVal("IsActive")
if err1 != nil {
continue // ignore if no IsActive field
}
if glog.V(2) {
glog.Infof("Found active(%d) user for '%s' : id=%d profil=%d)", iActive, email, obj.getId(), iProfil)
}
userObj = obj
return
}
err = errors.New(fmt.Sprintf("No user found for '%s'", email))
if glog.V(2) {
glog.Error("getUserFromEmail Error : ", err)
}
return
}
// checkApiUser : check if userObj has acces to level 'profil'
func checkApiUser(userObj HomeObject) (profil TUserProfil, err error) {
i, err := userObj.getIntVal("IdProfil")
if err != nil {
return
}
profil = TUserProfil(i)
if profil <= ProfilNone {
err = errors.New("insufficient privileges")
return
}
iActive, err := userObj.getIntVal("IsActive")
if err != nil {
return
}
if iActive <= 0 {
err = errors.New("Not an active user")
}
return
}
// profilFilteredItems : return an []Item with only Item matching user profil
func profilFilteredItems(profil TUserProfil, items []Item) (filteredItems []Item) {
for _, item := range items {
if item.IdProfil < profil {
continue
}
filteredItems = append(filteredItems, item)
}
return
}
// profilFilteredObjects : return an []HomeObject with only Item matching user profil
func profilFilteredObjects(profil TUserProfil, objs []HomeObject) (filteredObjs []HomeObject) {
for _, obj := range objs {
if checkAccessToObject(profil, obj) != nil {
continue
}
filteredObjs = append(filteredObjs, obj)
}
return
}
func checkAccess(profilObject TUserProfil, profilAccess TUserProfil) error {
if (profilAccess == ProfilNone && profilObject > ProfilNone) || profilObject < profilAccess {
return errors.New("insufficient privileges")
}
return nil
}
// checkAccessToObject : check if 'profil' has acces to object
func checkAccessToObject(profil TUserProfil, obj HomeObject) error {
if !obj.hasField("IdProfil") {
// HomeObject without IdProfil have no access restriction
return nil
}
iProfil, err := obj.getIntVal("IdProfil")
if err != nil {
return err
}
if profil == ProfilNone || TUserProfil(iProfil) < profil {
return errors.New("insufficient privileges")
}
return checkAccess(TUserProfil(iProfil), profil)
}
// checkAccessToObjectId : check if 'profil' has acces to object (obj read from DB using objectid)
func checkAccessToObjectId(profil TUserProfil, objectid int) error {
objs, err := getHomeObjects(nil, ItemIdNone, objectid)
if err != nil {
return err
}
if len(objs) <= 0 {
return errors.New(fmt.Sprintf("Object with Id=%d not found", objectid))
}
return checkAccessToObject(profil, objs[0])
}
|
non-member
|
//go:build !windows
// +build !windows
package ledgerbackend
import (
"os"
"github.com/pkg/errors"
)
// Posix-specific methods for the StellarCoreRunner type.
func (c *stellarCoreRunner) getPipeName() string {
// The exec.Cmd.ExtraFiles field carries *io.File values that are assigned
// to child process fds counting from 3, and we'll be passing exactly one
// fd: the write end of the anonymous pipe below.
return "fd:3"
}
func (c *stellarCoreRunner) start(cmd cmdI) (pipe, error) {
// First make an anonymous pipe.
// Note io.File objects close-on-finalization.
readFile, writeFile, err := os.Pipe()
if err != nil {
return pipe{}, errors.Wrap(err, "error making a pipe")
}
p := pipe{Reader: readFile, File: writeFile}
// Add the write-end to the set of inherited file handles. This is defined
// to be fd 3 on posix platforms.
cmd.setExtraFiles([]*os.File{writeFile})
err = cmd.Start()
if err != nil {
writeFile.Close()
readFile.Close()
return pipe{}, errors.Wrap(err, "error starting stellar-core")
}
return p, nil
}
|
member
|
package main
// #cgo CPPFLAGS: -I/usr/local/modsecurity/include
// #cgo LDFLAGS: /usr/local/modsecurity/lib/libmodsecurity.so
// #include "modsec.c"
import "C"
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"net/http/httputil"
"net/url"
"time"
"unsafe"
)
func HomeFunc(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
data := "Home ModSec!!!!"
err := json.NewEncoder(w).Encode(data)
if err != nil {
_, err := fmt.Fprintf(w, "%s", err.Error())
if err != nil {
log.Fatal(err)
return
}
}
}
func TestFunc(w http.ResponseWriter, r *http.Request) {
log.Print("Processing request")
urlx, err := url.Parse("https://www.lightbase.io/freeforlife")
if err != nil {
log.Println(err)
}
proxy := httputil.NewSingleHostReverseProxy(urlx)
director := proxy.Director
proxy.Director = func(req *http.Request) {
director(req)
req.Header.Set("X-Forwarded-Host", req.Header.Get("Host"))
req.Host = req.URL.Host
req.URL.Path = urlx.Path
}
log.Print("Serving request")
proxy.ServeHTTP(w, r)
}
func InitModSec() {
//log.Println("initModSec start")
C.MyCInit()
//log.Println("initModSec -end-")
}
func modsec(url, httpMethod, httpProtocol, httpVersion string, clientLink string, clientPort int, serverLink string, serverPort int) int {
log.Println("modsec start ", url)
Curi := C.CString(url)
ChttpMethod := C.CString(httpMethod)
ChttpProtocol := C.CString(httpProtocol)
ChttpVersion := C.CString(httpVersion)
CclientLink := C.CString(clientLink)
CclientPort := C.int(clientPort)
CserverLink := C.CString(serverLink)
CserverPort := C.int(serverPort)
defer C.free(unsafe.Pointer(Curi))
defer C.free(unsafe.Pointer(ChttpMethod))
defer C.free(unsafe.Pointer(ChttpProtocol))
defer C.free(unsafe.Pointer(ChttpVersion))
defer C.free(unsafe.Pointer(CclientLink))
defer C.free(unsafe.Pointer(CserverLink))
start := time.Now()
inter := int(C.MyCProcess(Curi, ChttpMethod, ChttpProtocol, ChttpVersion, CclientLink, CclientPort, CserverLink, CserverPort))
elapsed := time.Since(start)
log.Printf("modsec()=%d, elapsed: %s", inter, elapsed)
log.Println("modsec -end-")
return inter
}
func LimitMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("req.URL : \"%s\"", r.URL)
log.Printf("Methods : \"%s\"", r.Method)
uri := r.URL.String()
httpMethod := "GET"
//protocol := "HTTP/1.1"
httpProtocol := "HTTP"
httpVersion := "1.1"
//clientSocket := "127.0.0.1:80"
clientLink := "127.0.0.1"
clientPort := 80
//serverSocket := "127.0.0.1:80"
serverLink := "127.0.0.1"
serverPort := 80
inter := modsec(uri, httpMethod, httpProtocol, httpVersion, clientLink, clientPort, serverLink, serverPort)
if inter > 0 {
log.Printf("==== Mod Security Blocked! ====")
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
next.ServeHTTP(w, r)
})
}
func main() {
log.Println("testing")
bind := ":3080"
gmux := mux.NewRouter()
gmux.HandleFunc("/", HomeFunc).Methods("GET")
gmux.HandleFunc("/test/artists.php", TestFunc).Methods("GET")
log.Printf("starting smart reverse proxy on [%s]", bind)
log.Printf("initialize mod sec")
InitModSec()
log.Printf("listening [deny]...")
if err := http.ListenAndServe(bind, LimitMiddleware(gmux)); err != nil {
log.Fatalf("unable to start web server: %s", err.Error())
}
}
|
non-member
|
package msg
import (
"bufio"
"encoding/gob"
"fmt"
"io"
"sync"
)
// Reader : simple bufio.Reader safe for goroutines...
type Reader struct {
b *bufio.Reader
m sync.Mutex
}
// NewReader : constructor
func NewReader(rd io.Reader) *Reader {
s := new(Reader)
s.b = bufio.NewReader(rd)
return s
}
// ReadString : safe version for goroutines
func (r *Reader) ReadString() (string, error) {
r.m.Lock()
defer r.m.Unlock()
return r.b.ReadString('\n')
}
// ReadMessage : decode a message in a safe way for goroutines
func (r *Reader) ReadMessage(data interface{}) error {
r.m.Lock()
defer r.m.Unlock()
enc := gob.NewDecoder(r.b)
err := enc.Decode(data)
if err != nil {
fmt.Printf("error in ReadMessage : %s\n", err)
}
return err
}
|
non-member
|
package panda
import (
"net/http"
"github.com/LeeEirc/httpsig"
)
const (
signHeaderRequestTarget = "(request-target)"
signHeaderDate = "date"
signAlgorithm = "hmac-sha256"
)
type ProfileAuth struct {
KeyID string
SecretID string
}
func (auth *ProfileAuth) Sign(r *http.Request) error {
profileReq, err := http.NewRequest(http.MethodGet, UserProfileURL, nil)
if err != nil {
return err
}
headers := []string{signHeaderRequestTarget, signHeaderDate}
signer, err := httpsig.NewRequestSigner(auth.KeyID, auth.SecretID, signAlgorithm)
if err != nil {
return err
}
err = signer.SignRequest(profileReq, headers, nil)
if err != nil {
return err
}
for k, v := range profileReq.Header {
r.Header[k] = v
}
return nil
}
const UserProfileURL = "/api/v1/users/profile/"
|
non-member
|
package linux
import (
"net"
)
func LocalIp() (string, error) {
localIp := "N/A"
adders, err := net.InterfaceAddrs()
if err != nil {
return localIp, err
}
for _, addr := range adders {
if ipNet, ok := addr.(*net.IPNet); ok &&
!ipNet.IP.IsLinkLocalUnicast() && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
localIp = ipNet.IP.String()
}
}
return localIp, nil
}
|
non-member
|
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"runtime"
"stashbox/pkg/archive"
"stashbox/pkg/crawler"
)
func usage() {
fmt.Println("Usage: stashbox <command> <options>")
fmt.Println("")
fmt.Println(" Where command is one of:")
fmt.Println(" add -- add a url to the archive")
fmt.Println(" list -- list all archives")
fmt.Println(" open -- open an archive")
fmt.Println("")
fmt.Println(" To see help text, you can run:")
fmt.Println(" stashbox <command> -h")
os.Exit(1)
}
func main() {
// add subcommand
addCmd := flag.NewFlagSet("add", flag.ExitOnError)
addBase := addCmd.String("b", "./stashDb", "stashbox archive directory (defaults to ./stashDb)")
url := addCmd.String("u", "", "url to download")
//list subcommand
listCmd := flag.NewFlagSet("list", flag.ExitOnError)
listBase := listCmd.String("b", "./stashDb", "stashbox archive directory (defaults to ./stashDb)")
//open subcommand
openCmd := flag.NewFlagSet("open", flag.ExitOnError)
openBase := openCmd.String("b", "./stashDb", "stashbox archive directory (defaults to ./stashDb)")
n := openCmd.Int("n", 0, "archive number to open (from list command)")
if len(os.Args) < 2 {
usage()
}
if os.Args[1] == "-h" {
usage()
}
switch os.Args[1] {
case "add":
if addCmd.Parse(os.Args[2:]) != nil {
addCmd.Usage()
os.Exit(2)
}
if *url == "" {
fmt.Println("ERROR: -url is required")
addCmd.Usage()
os.Exit(1)
}
c, err := crawler.NewCrawler(*addBase)
if err != nil {
panic(err)
}
err = c.AddURL(*url)
if err != nil {
panic(err)
}
err = c.Crawl()
if err != nil {
panic(err)
}
err = c.Save()
if err != nil {
panic(err)
}
case "list":
if listCmd.Parse(os.Args[2:]) != nil {
listCmd.Usage()
os.Exit(2)
}
archives, err := archive.GetArchives(*listBase)
if err != nil {
fmt.Println("Error listing archives", err)
os.Exit(1)
}
fmt.Println("Archive listing...")
for i, n := range archives {
fmt.Printf("%d. %s [%d image(s)]\n", i+1, n.URL, len(n.Dates))
}
case "open":
if openCmd.Parse(os.Args[2:]) != nil {
openCmd.Usage()
os.Exit(2)
}
archives, err := archive.GetArchives(*openBase)
if err != nil {
panic(err)
}
if *n < 1 {
fmt.Println("Choose an archive to open:")
for i, n := range archives {
fmt.Printf("%d. %s [%d image(s)]\n", i+1, n.URL, len(n.Dates))
}
fmt.Print("\n> ")
_, err := fmt.Scanf("%d", n)
if err != nil {
fmt.Printf("ERROR: reading input: %v", err)
os.Exit(1)
}
}
a := archives[*n-1]
file := fmt.Sprintf("%s/%s/%s.pdf", *openBase, a.URL, a.Dates[len(a.Dates)-1])
fmt.Printf("Opening: %s\n", file)
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
cmd = exec.Command(file) // #nosec G204
case "darwin":
cmd = exec.Command("open", file) // #nosec G204
default:
cmd = exec.Command("xdg-open", file) // #nosec G204
}
err = cmd.Run()
if err != nil {
panic(err)
}
default:
fmt.Printf("ERROR: unknown command (%s) specified\n", os.Args[1])
usage()
}
}
|
non-member
|
package valuechangevalidationfuncinfo
import (
"testing"
"golang.org/x/tools/go/analysis"
)
func TestValidateAnalyzer(t *testing.T) {
err := analysis.Validate([]*analysis.Analyzer{Analyzer})
if err != nil {
t.Fatal(err)
}
}
|
non-member
|
package main
import (
"flag"
"log"
"net"
"strconv"
)
func main() {
port := flag.Int("port", 8080, "Port to accept connections on.")
host := flag.String("host", "0.0.0.0", "Host or IP to bind to")
flag.Parse()
l, err := net.Listen("tcp", *host+":"+strconv.Itoa(*port))
if err != nil {
log.Panicln(err)
}
log.Println("Listening to connections at '"+*host+"' on port", strconv.Itoa(*port))
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
log.Panicln(err)
}
go handleRequest(conn)
}
}
func handleRequest(conn net.Conn) {
log.Println("Accepted new connection.")
defer conn.Close()
defer log.Println("Closed connection.")
for {
buf := make([]byte, 1024)
size, err := conn.Read(buf)
if err != nil {
return
}
data := buf[:size]
log.Println("Received:", string(data))
conn.Write(data)
}
}
|
non-member
|
package lib
import (
"errors"
"fmt"
"runtime"
"strings"
"testing"
)
func TestF테스트_중(t *testing.T) {
t.Parallel()
F테스트_모드_종료()
F테스트_거짓임(t, F테스트_모드_실행_중())
F테스트_모드_시작()
F테스트_참임(t, F테스트_모드_실행_중())
}
func TestF테스트_참임(t *testing.T) {
//t.Parallel() // 화면 출력 중지 로 인하여 병렬 실행 불가.
F테스트_참임(t, true)
모의_테스트 := new(S모의_테스트)
원래_출력장치 := F화면_출력_중지()
F테스트_참임(모의_테스트, false)
F화면_출력_재개(원래_출력장치)
F테스트_참임(t, 모의_테스트.Failed())
}
func TestF테스트_거짓임(t *testing.T) {
//t.Parallel() // 화면 출력 중지 로 인하여 병렬 실행 불가.
F테스트_거짓임(t, false)
모의_테스트 := new(S모의_테스트)
원래_출력장치 := F화면_출력_중지()
F테스트_거짓임(모의_테스트, true)
F화면_출력_재개(원래_출력장치)
F테스트_참임(t, 모의_테스트.Failed())
}
func TestF에러_없음(t *testing.T) {
//t.Parallel() // 화면 출력 중지 로 인하여 병렬 실행 불가.
F테스트_에러없음(t, nil)
모의_테스트 := new(S모의_테스트)
원래_출력장치 := F화면_출력_중지()
F테스트_에러없음(모의_테스트, fmt.Errorf(""))
F화면_출력_재개(원래_출력장치)
F테스트_참임(t, 모의_테스트.Failed())
}
func TestF테스트_에러발생(t *testing.T) {
//t.Parallel() // 화면 출력 중지 로 인하여 병렬 실행 불가.
F테스트_에러발생(t, errors.New(""))
모의_테스트 := new(S모의_테스트)
원래_출력장치 := F화면_출력_중지()
F테스트_에러발생(모의_테스트, nil)
F화면_출력_재개(원래_출력장치)
F테스트_참임(t, 모의_테스트.Failed())
}
func TestF테스트_같음(t *testing.T) {
//t.Parallel() // 화면 출력 중지 로 인하여 병렬 실행 불가.
F테스트_같음(t, 1, 1)
모의_테스트 := new(S모의_테스트)
원래_출력장치 := F화면_출력_중지()
F테스트_같음(모의_테스트, 1, 2)
F화면_출력_재개(원래_출력장치)
F테스트_참임(t, 모의_테스트.Failed())
}
func TestF테스트_다름(t *testing.T) {
//t.Parallel() // 화면 출력 중지 로 인하여 병렬 실행 불가.
F테스트_다름(t, 1, 2)
모의_테스트 := new(S모의_테스트)
원래_출력장치 := F화면_출력_중지()
F테스트_다름(모의_테스트, 1, 1)
F화면_출력_재개(원래_출력장치)
F테스트_참임(t, 모의_테스트.Failed())
}
func TestF임의_문자열(t *testing.T) {
t.Parallel()
맵 := make(map[string]S비어있음)
const 테스트_반복횟수 = 100
비어있는_구조체 := S비어있음{}
for i := 0; i < 테스트_반복횟수; i++ {
맵[F임의_문자열(10, 20)] = 비어있는_구조체
}
F테스트_참임(t, len(맵) > 테스트_반복횟수*0.7)
}
func TestF문자열_호출경로_출력(t *testing.T) {
//t.Parallel() // 문자열 출력 확보로 인해 병렬 실행 불가.
문자열, 에러 := F출력_문자열_확보(func() {
F문자열_호출경로_출력("%v, %v", "테스트_문자열", 1)
})
F테스트_에러없음(t, 에러)
F테스트_참임(t, strings.Count(문자열, "테스트_문자열, 1") == 1, 문자열)
F테스트_참임(t, F호출경로_포함(문자열), 문자열)
pc, _, _, _ := runtime.Caller(0)
함수명 := runtime.FuncForPC(pc).Name()
if strings.LastIndex(함수명, ".") > 0 {
함수명 = 함수명[strings.LastIndex(함수명, ".")+1:]
}
F테스트_참임(t, strings.Contains(문자열, 함수명), 문자열, 함수명)
}
func TestNew에러(t *testing.T) {
//t.Parallel() // 문자열 출력 확보로 인해 병렬 실행 불가.
에러 := New에러("테스트용 에러. %v", 100)
_, ok := 에러.(error)
F테스트_참임(t, ok)
F테스트_같음(t, strings.Count(에러.Error(), "테스트용 에러. 100"), 1)
}
func TestF변수값_자료형_문자열(t *testing.T) {
//t.Parallel() // 문자열 출력 확보로 인해 병렬 실행 불가.
문자열 := F변수값_자료형_문자열("테스트_문자열", 1)
F테스트_참임(t, strings.Contains(문자열, "테스트_문자열"))
F테스트_참임(t, strings.Contains(문자열, "string"))
F테스트_참임(t, strings.Contains(문자열, "1"))
F테스트_참임(t, strings.Contains(문자열, "int"))
}
func TestF소스코드_위치_포함(t *testing.T) {
t.Parallel()
문자열 := "github.com/ghts/sample.go.go:65:f샘플()\n\nFAIL github.com/ghts/ 23.231s"
F테스트_참임(t, F호출경로_포함(문자열))
}
|
non-member
|
package main
import (
"fmt"
"sync"
)
func greeter(wg *sync.WaitGroup, name string) {
fmt.Printf("Hallo %s\n", name)
wg.Done()
}
func main() {
wg := &sync.WaitGroup{}
wg.Add(1)
go greeter(wg, "Alice")
wg.Wait()
}
|
non-member
|
package hexaring
import (
"hash"
"math/big"
)
// CalculateRingVertexes returns the requested number of vertexes around the ring
// equi-distant from each other except for potentially the last one which may be larger
func CalculateRingVertexes(hash []byte, count int64) []*big.Int {
var circum big.Int
//circum.SetBytes(maxHash(len(hash)))
circum.Exp(big.NewInt(2), big.NewInt(int64(len(hash))*8), nil)
// Number of sections
arcs := big.NewInt(count)
// Size of each section
arcWidth := new(big.Int).Div(&circum, arcs)
// Starting offset
offset := new(big.Int).SetBytes(hash)
locs := make([]*big.Int, count)
locs[0] = offset
for i := int64(1); i < count; i++ {
// Index
bigI := big.NewInt(i)
// Index times the width of the section
piece := new(big.Int).Mul(bigI, arcWidth)
// Add to offset
po := new(big.Int).Add(piece, offset)
locs[i] = new(big.Int).Mod(po, &circum)
}
return locs
}
// CalculateRingVertexBytes returns the a slice of bytes one for each vertex
func CalculateRingVertexBytes(hash []byte, count int64) [][]byte {
// Hash size used when produces hashes are smaller.
lh := len(hash)
// Big int values of hashes
vertexes := CalculateRingVertexes(hash, count)
// Binary representation
out := make([][]byte, len(vertexes))
for i, v := range vertexes {
b := v.Bytes()
lb := len(b)
// Account for modulo. Padd required zeros
if lb < lh {
p := make([]byte, lh-lb)
b = append(p, b...)
}
out[i] = b
}
return out
}
// BuildReplicaHashes hashes the given key and build the required additional hashes
// returning the requested count of hashes.
func BuildReplicaHashes(key []byte, count int64, h hash.Hash) [][]byte {
h.Write(key)
sh := h.Sum(nil)
return CalculateRingVertexBytes(sh[:], count)
}
// replicasWithFault returns the number of replicas required in order to tolerate the
// given number of faulty nodes.
func replicasWithFault(faulty int) int {
return (3 * faulty) + 1
}
// votesWithFault returns the number of votes required for propose in order to tolerate
// the given number of faulty nodes.
func votesWithFault(faulty int) int {
return (2 * faulty) + 1
}
// commitsWithFault returns the number of commits required in order to tolerate the given
// number of faulty nodes.
func commitsWithFault(faulty int) int {
return faulty + 1
}
func maxHash(s int) []byte {
out := make([]byte, s)
for i := range out {
out[i] = 0xff
}
return out
}
|
non-member
|
package main
import (
"fmt"
"github.com/formicidae-tracker/zeus/internal/zeus"
flags "github.com/jessevdk/go-flags"
)
type VersionCommand struct {
Args struct {
Config flags.Filename
} `positional-args:"yes"`
}
func (c *VersionCommand) Execute(args []string) error {
fmt.Printf("%s\n", zeus.ZEUS_VERSION)
return nil
}
func init() {
_, err := parser.AddCommand("version",
"print zeus version",
"prints zeus version on stdout and exit",
&VersionCommand{})
if err != nil {
panic(err.Error())
}
}
|
non-member
|
package build
import (
"io"
"text/template"
"github.com/benpate/html"
)
// StepInlineSaveButton represents an action-step that can build a Stream into HTML
type StepInlineSaveButton struct {
ID *template.Template
Class string
Label *template.Template
}
// Get builds the Stream HTML to the context
func (step StepInlineSaveButton) Get(builder Builder, buffer io.Writer) PipelineBehavior {
return nil
}
func (step StepInlineSaveButton) Post(builder Builder, buffer io.Writer) PipelineBehavior {
h := html.New()
id := executeTemplate(step.ID, builder)
label := executeTemplate(step.Label, builder)
h.Button().ID(id).Script("install SaveButton").Class(step.Class + " success").InnerHTML(label)
if _, err := buffer.Write(h.Bytes()); err != nil {
return Halt().WithError(err)
}
return Halt().WithHeader("HX-Reswap", "outerHTML").WithHeader("HX-Retarget", "#"+id)
}
|
non-member
|
/*
* @Description: 前置重贴标签算法中图的节点类型 FrontFlowVertex
* @Author: wangchengdg@gmail.com
* @Date: 2020-02-18 10:31:22
* @LastEditTime: 2020-03-13 22:27:34
* @LastEditors:
*/
package GraphVertex
/*!
*
* FrontFlowVertex 继承自 FlowVertex,它比FlowVertex顶点多了一个`N_List`数据成员,表示邻接链表
*
* relabel_to_front 算法中,每一个FrontFlowVertex顶点位于两个级别的链表中:
*
* - L 链表:最顶层的链表,L包含了所有的非源、非汇顶点
* - u.N 链表:某个顶点u的邻接链表
*
*/
type FrontFlowVertex struct {
FlowVertex
N_List *List //存储和本节点相邻的所有节点
}
func NewFrontFlowVertex(k int, ids ...int) *FrontFlowVertex {
id := -1
if len(ids) > 0 {
id = ids[0]
}
newList := &List{Head: nil, Current: nil}
return &FrontFlowVertex{FlowVertex: FlowVertex{Vertex: Vertex{_ID: id, _Key: k}}, N_List: newList}
}
|
non-member
|
package main
import (
"log"
)
func main() {
log.SetFlags(log.Ldate | log.Lmicroseconds | log.Llongfile)
name := "q0phi80"
log.Println("Demo app")
log.Printf("%s is here!", name)
log.Print("Run")
}
|
non-member
|
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"github.com/eniehack/persona-server/config"
"github.com/eniehack/persona-server/handler"
"github.com/go-chi/cors"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
migrate "github.com/rubenv/sql-migrate"
"gopkg.in/go-playground/validator.v9"
)
func SetUpDataBase(Config *config.DatabaseConfig) (*sqlx.DB, error) {
databaseURL := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s", Config.User, Config.Password, Config.Host, Config.Database, Config.SSL)
db, err := sqlx.Open("postgres", databaseURL)
if err != nil {
return nil, fmt.Errorf("failed to connect Database: %s", err)
}
return db, nil
}
func main() {
var configFilePath string
flag.StringVar(&configFilePath, "config", "./configs/config.toml", "config file's path.")
flag.Parse()
config, err := config.LoadConfig(configFilePath)
if err != nil {
log.Fatalf("Failed to load config file: %s", err)
}
corsSettings := cors.New(cors.Options{
AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodOptions, http.MethodDelete},
AllowedHeaders: []string{"Authorization", "Content-Type"},
MaxAge: 3600,
ExposedHeaders: []string{"Authorization"},
})
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(corsSettings.Handler)
log.Println("Persona v0.1.0-alpha.1 starting......")
db, err := SetUpDataBase(config)
if err != nil {
log.Fatalf(err)
}
db.SetConnMaxLifetime(1)
defer db.Close()
log.Println("finiched set up database")
validator := validator.New()
h := &handler.Handler{
DB: db,
Validate: validator,
}
r.Mount("/api/v1", Router(h))
log.Println("Finished to mount router.")
if os.Getenv("PORT") == "" {
log.Fatal(http.ListenAndServe(":3000", r))
} else {
log.Fatal(
http.ListenAndServe(
fmt.Sprintf(":%s", os.Getenv("PORT")),
r,
),
)
}
}
|
non-member
|
package models
type NoSuchObjectError struct {
Info string
}
func (e NoSuchObjectError) Error() string {
return e.Info
}
func NewNoSuchObjectError(s string) NoSuchObjectError {
return NoSuchObjectError{Info: s}
}
|
member
|
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"github.com/pkg/errors"
)
func repoNameToRegistryImageTuple(repo string) (string, string, error) {
s := strings.Split(repo, "/")
var registryURL, image string
switch len(s) {
case 2:
registryURL = "registry.hub.docker.com"
image = s[0] + "/" + s[1]
case 3:
registryURL = s[0]
image = s[1] + "/" + s[2]
default:
return "", "", fmt.Errorf("couldn't get repo name correctly: %s", repo)
}
return registryURL, image, nil
}
func getManifest(t tokenGetter, repo, tag string) (*ManifestResponse, error) {
registryURL, image, err := repoNameToRegistryImageTuple(repo)
if err != nil {
return nil, err
}
token, err := t.get(registryURL, image)
if err != nil {
log.Fatalf("Couldn't get auth token: %v", err)
}
if err := checkIfImageExists(token, registryURL, image, tag); err != nil {
return nil, errors.Wrapf(err, "Image %s doesn't exist in %s", image, registryURL)
}
fmt.Printf("Image %s:%s exists at registry %s\n", image, tag, registryURL)
URL := fmt.Sprintf(DockerAPIManifestf, registryURL, image, tag)
req, _ := http.NewRequest(http.MethodGet, URL, nil)
if len(token) > 0 {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("Fail during HTTP GET %s: %v", URL, err)
}
defer res.Body.Close()
//b, _ := ioutil.ReadAll(res.Body)
//fmt.Printf("%s\n", b)
contentType := res.Header.Get("Content-Type")
if !strings.Contains(contentType, "application/vnd.docker.distribution.manifest.v1+json") &&
!strings.Contains(contentType, "application/vnd.docker.distribution.manifest.v1+prettyjws") {
return nil,
fmt.Errorf("Content-Type (schema version) %s not supported", contentType)
}
// V1
jsonManResp := &ManifestResponse{}
if err = json.NewDecoder(res.Body).Decode(jsonManResp); err != nil {
return nil, fmt.Errorf("Couldn't decode JSON manifest: %v", err)
}
return jsonManResp, nil
}
type FsLayers []struct {
BlobSum string `json:"blobSum"`
}
// ManifestResponse is the json response from manifests API v2
type ManifestResponse struct {
Name string `json:"name"`
Tag string `json:"tag"`
Architecture string `json:"architecture"`
SchemaVersion int `json:"schemaVersion"`
FsLayers `json:"fsLayers"`
History []struct {
V1CompatibilityRaw string `json:"v1Compatibility"`
V1Compatibility v1Compatibility
} `json:"history"`
}
type v1Compatibility struct {
Architecture string `json:"architecture,omitempty"`
OS string `json:"os,omitempty"`
ID string `json:"id,omitempty"`
Parent string `json:"parent,omitempty"`
Created string `json:"created,omitempty"`
DockerVersion string `json:"docker_version,omitempty"`
Throwaway bool `json:"throwaway,omitempty"`
//Tty bool `json:"Tty"`
//OpenStdin bool `json:"OpenStdin"`
//StdinOnce bool `json:"StdinOnce"`
//Env []string `json:"Env"`
ContainerConfig struct {
CmdRaw []string `json:"Cmd"`
Cmd string
} `json:"container_config"`
}
type manifestResponse ManifestResponse
// UnmarshalJSON implement json.Unmarshaller interface
func (m *ManifestResponse) UnmarshalJSON(b []byte) error {
var jsonManResp manifestResponse
if err := json.Unmarshal(b, &jsonManResp); err != nil {
return err
}
for i := range jsonManResp.History {
var comp v1Compatibility
if err := json.Unmarshal([]byte(jsonManResp.History[i].V1CompatibilityRaw), &comp); err != nil {
continue
}
jsonManResp.History[i].V1Compatibility = comp
jsonManResp.History[i].V1Compatibility.ContainerConfig.Cmd =
strings.Join(jsonManResp.History[i].V1Compatibility.ContainerConfig.CmdRaw, " ")
}
*m = ManifestResponse(jsonManResp)
return nil
}
|
non-member
|
package cpu
/*
will be useful for debugging
func getMode(mode uint8) string {
switch mode {
case ModeInvalid: return "ModeInvalid"
case ModeZeroPage: return "ModeZeroPage"
case ModeIndexedZeroPageX: return "ModeIndexedZeroPageX"
case ModeIndexedZeroPageY: return "ModeIndexedZeroPageY"
case ModeAbsolute: return "ModeAbsolute"
case ModeIndexedAbsoluteX: return "ModeIndexedAbsoluteX"
case ModeIndexedAbsoluteY: return "ModeIndexedAbsoluteY"
case ModeIndirect: return "ModeIndirect"
case ModeImplied: return "ModeImplied"
case ModeAccumulator: return "ModeAccumulator"
case ModeImmediate: return "ModeImmediate"
case ModeRelative: return "ModeRelative"
case ModeIndexedIndirectX: return "ModeIndexedIndirectX"
case ModeIndirectIndexedY: return "ModeIndirectIndexedY"
}
return "ModeInvalid"
}
*/
func (c *Cpu) setupIns() {
// illegal operations have a len of 0 for now
// created using table form http://www.oxyron.de/html/opcodes02.html
c.addIns2("BRK", 0x00, 1, 7, 0, ModeImplied, c.brk)
c.addIns2("ORA", 0x01, 2, 6, 0, ModeIndexedIndirectX, c.ora)
c.addIns("KIL", 0x02, 0, 2, 0, ModeImplied)
c.addIns("SLO", 0x03, 0, 8, 0, ModeIndexedIndirectX)
c.addIns2("NOP", 0x04, 2, 3, 0, ModeZeroPage, c.nop)
c.addIns2("ORA", 0x05, 2, 3, 0, ModeZeroPage, c.ora)
c.addIns2("ASL", 0x06, 2, 5, 0, ModeZeroPage, c.asl)
c.addIns("SLO", 0x07, 0, 5, 0, ModeZeroPage)
c.addIns2("PHP", 0x08, 1, 3, 0, ModeImplied, c.php)
c.addIns2("ORA", 0x09, 2, 2, 0, ModeImmediate, c.ora)
c.addIns2("ASL", 0x0a, 1, 2, 0, ModeAccumulator, c.asl)
c.addIns("ANC", 0x0b, 0, 2, 0, ModeImmediate)
c.addIns2("NOP", 0x0c, 3, 4, 0, ModeAbsolute, c.nop)
c.addIns2("ORA", 0x0d, 3, 4, 0, ModeAbsolute, c.ora)
c.addIns2("ASL", 0x0e, 3, 6, 0, ModeAbsolute, c.asl)
c.addIns("SLO", 0x0f, 0, 6, 0, ModeAbsolute)
c.addIns2("BPL", 0x10, 2, 2, 1, ModeRelative, c.bpl)
c.addIns2("ORA", 0x11, 2, 5, 1, ModeIndirectIndexedY, c.ora)
c.addIns("KIL", 0x12, 0, 2, 0, ModeImplied)
c.addIns("SLO", 0x13, 0, 8, 0, ModeIndirectIndexedY)
c.addIns2("NOP", 0x14, 2, 4, 0, ModeIndexedZeroPageX, c.nop)
c.addIns2("ORA", 0x15, 2, 4, 0, ModeIndexedZeroPageX, c.ora)
c.addIns2("ASL", 0x16, 2, 6, 0, ModeIndexedZeroPageX, c.asl)
c.addIns("SLO", 0x17, 0, 6, 0, ModeIndexedZeroPageX)
c.addIns2("CLC", 0x18, 1, 2, 0, ModeImplied, c.clc)
c.addIns2("ORA", 0x19, 3, 4, 1, ModeIndexedAbsoluteY, c.ora)
c.addIns2("NOP", 0x1a, 1, 2, 0, ModeImplied, c.nop)
c.addIns("SLO", 0x1b, 0, 7, 0, ModeIndexedAbsoluteY)
c.addIns2("NOP", 0x1c, 3, 4, 1, ModeIndexedAbsoluteX, c.nop)
c.addIns2("ORA", 0x1d, 3, 4, 1, ModeIndexedAbsoluteX, c.ora)
c.addIns2("ASL", 0x1e, 3, 7, 0, ModeIndexedAbsoluteX, c.asl)
c.addIns("SLO", 0x1f, 0, 7, 0, ModeIndexedAbsoluteX)
c.addIns2("JSR", 0x20, 3, 6, 0, ModeAbsolute, c.jsr)
c.addIns2("AND", 0x21, 2, 6, 0, ModeIndexedIndirectX, c.and)
c.addIns("KIL", 0x22, 0, 2, 0, ModeImplied)
c.addIns("RLA", 0x23, 0, 8, 0, ModeIndexedIndirectX)
c.addIns2("BIT", 0x24, 2, 3, 0, ModeZeroPage, c.bit)
c.addIns2("AND", 0x25, 2, 3, 0, ModeZeroPage, c.and)
c.addIns2("ROL", 0x26, 2, 5, 0, ModeZeroPage, c.rol)
c.addIns("RLA", 0x27, 0, 5, 0, ModeZeroPage)
c.addIns2("PLP", 0x28, 1, 4, 0, ModeImplied, c.plp)
c.addIns2("AND", 0x29, 2, 2, 0, ModeImmediate, c.and)
c.addIns2("ROL", 0x2a, 1, 2, 0, ModeAccumulator, c.rol)
c.addIns("ANC", 0x2b, 0, 2, 0, ModeImmediate)
c.addIns2("BIT", 0x2c, 3, 4, 0, ModeAbsolute, c.bit)
c.addIns2("AND", 0x2d, 3, 4, 0, ModeAbsolute, c.and)
c.addIns2("ROL", 0x2e, 3, 6, 0, ModeAbsolute, c.rol)
c.addIns("RLA", 0x2f, 0, 6, 0, ModeAbsolute)
c.addIns2("BMI", 0x30, 2, 2, 1, ModeRelative, c.bmi)
c.addIns2("AND", 0x31, 2, 5, 1, ModeIndirectIndexedY, c.and)
c.addIns("KIL", 0x32, 0, 2, 0, ModeImplied)
c.addIns("RLA", 0x33, 0, 8, 0, ModeIndirectIndexedY)
c.addIns2("NOP", 0x34, 2, 4, 0, ModeIndexedZeroPageX, c.nop)
c.addIns2("AND", 0x35, 2, 4, 0, ModeIndexedZeroPageX, c.and)
c.addIns2("ROL", 0x36, 2, 6, 0, ModeIndexedZeroPageX, c.rol)
c.addIns("RLA", 0x37, 0, 6, 0, ModeIndexedZeroPageX)
c.addIns2("SEC", 0x38, 1, 2, 0, ModeImplied, c.sec)
c.addIns2("AND", 0x39, 3, 4, 1, ModeIndexedAbsoluteY, c.and)
c.addIns2("NOP", 0x3a, 1, 2, 0, ModeImplied, c.nop)
c.addIns("RLA", 0x3b, 0, 7, 0, ModeIndexedAbsoluteY)
c.addIns2("NOP", 0x3c, 3, 4, 1, ModeIndexedAbsoluteX, c.nop)
c.addIns2("AND", 0x3d, 3, 4, 1, ModeIndexedAbsoluteX, c.and)
c.addIns2("ROL", 0x3e, 3, 7, 0, ModeIndexedAbsoluteX, c.rol)
c.addIns("RLA", 0x3f, 0, 7, 0, ModeIndexedAbsoluteX)
c.addIns2("RTI", 0x40, 1, 6, 0, ModeImplied, c.rti)
c.addIns2("EOR", 0x41, 2, 6, 0, ModeIndexedIndirectX, c.eor)
c.addIns("KIL", 0x42, 0, 2, 0, ModeImplied)
c.addIns("SRE", 0x43, 0, 8, 0, ModeIndexedIndirectX)
c.addIns2("NOP", 0x44, 2, 3, 0, ModeZeroPage, c.nop)
c.addIns2("EOR", 0x45, 2, 3, 0, ModeZeroPage, c.eor)
c.addIns2("LSR", 0x46, 2, 5, 0, ModeZeroPage, c.lsr)
c.addIns("SRE", 0x47, 0, 5, 0, ModeZeroPage)
c.addIns2("PHA", 0x48, 1, 3, 0, ModeImplied, c.pha)
c.addIns2("EOR", 0x49, 2, 2, 0, ModeImmediate, c.eor)
c.addIns2("LSR", 0x4a, 1, 2, 0, ModeAccumulator, c.lsr)
c.addIns("ALR", 0x4b, 0, 2, 0, ModeImmediate)
c.addIns2("JMP", 0x4c, 3, 3, 0, ModeAbsolute, c.jmp)
c.addIns2("EOR", 0x4d, 3, 4, 0, ModeAbsolute, c.eor)
c.addIns2("LSR", 0x4e, 3, 6, 0, ModeAbsolute, c.lsr)
c.addIns("SRE", 0x4f, 0, 6, 0, ModeAbsolute)
c.addIns2("BVC", 0x50, 2, 2, 1, ModeRelative, c.bvc)
c.addIns2("EOR", 0x51, 2, 5, 1, ModeIndirectIndexedY, c.eor)
c.addIns("KIL", 0x52, 0, 2, 0, ModeImplied)
c.addIns("SRE", 0x53, 0, 8, 0, ModeIndirectIndexedY)
c.addIns2("NOP", 0x54, 2, 4, 0, ModeIndexedZeroPageX, c.nop)
c.addIns2("EOR", 0x55, 2, 4, 0, ModeIndexedZeroPageX, c.eor)
c.addIns2("LSR", 0x56, 2, 6, 0, ModeIndexedZeroPageX, c.lsr)
c.addIns("SRE", 0x57, 0, 6, 0, ModeIndexedZeroPageX)
c.addIns2("CLI", 0x58, 1, 2, 0, ModeImplied, c.cli)
c.addIns2("EOR", 0x59, 3, 4, 1, ModeIndexedAbsoluteY, c.eor)
c.addIns2("NOP", 0x5a, 1, 2, 0, ModeImplied, c.nop)
c.addIns("SRE", 0x5b, 0, 7, 0, ModeIndexedAbsoluteY)
c.addIns2("NOP", 0x5c, 3, 4, 1, ModeIndexedAbsoluteX, c.nop)
c.addIns2("EOR", 0x5d, 3, 4, 1, ModeIndexedAbsoluteX, c.eor)
c.addIns2("LSR", 0x5e, 3, 7, 0, ModeIndexedAbsoluteX, c.lsr)
c.addIns("SRE", 0x5f, 0, 7, 0, ModeIndexedAbsoluteX)
c.addIns2("RTS", 0x60, 1, 6, 0, ModeImplied, c.rts)
c.addIns2("ADC", 0x61, 2, 6, 0, ModeIndexedIndirectX, c.adc)
c.addIns("KIL", 0x62, 0, 2, 0, ModeImplied)
c.addIns("RRA", 0x63, 0, 8, 0, ModeIndexedIndirectX)
c.addIns2("NOP", 0x64, 2, 3, 0, ModeZeroPage, c.nop)
c.addIns2("ADC", 0x65, 2, 3, 0, ModeZeroPage, c.adc)
c.addIns2("ROR", 0x66, 2, 5, 0, ModeZeroPage, c.ror)
c.addIns("RRA", 0x67, 0, 5, 0, ModeZeroPage)
c.addIns2("PLA", 0x68, 1, 4, 0, ModeImplied, c.pla)
c.addIns2("ADC", 0x69, 2, 2, 0, ModeImmediate, c.adc)
c.addIns2("ROR", 0x6a, 1, 2, 0, ModeAccumulator, c.ror)
c.addIns("ARR", 0x6b, 0, 2, 0, ModeImmediate)
c.addIns2("JMP", 0x6c, 3, 5, 0, ModeIndirect, c.jmp)
c.addIns2("ADC", 0x6d, 3, 4, 0, ModeAbsolute, c.adc)
c.addIns2("ROR", 0x6e, 3, 6, 0, ModeAbsolute, c.ror)
c.addIns("RRA", 0x6f, 0, 6, 0, ModeAbsolute)
c.addIns2("BVS", 0x70, 2, 2, 1, ModeRelative, c.bvs)
c.addIns2("ADC", 0x71, 2, 5, 1, ModeIndirectIndexedY, c.adc)
c.addIns("KIL", 0x72, 0, 2, 0, ModeImplied)
c.addIns("RRA", 0x73, 0, 8, 0, ModeIndirectIndexedY)
c.addIns2("NOP", 0x74, 2, 4, 0, ModeIndexedZeroPageX, c.nop)
c.addIns2("ADC", 0x75, 2, 4, 0, ModeIndexedZeroPageX, c.adc)
c.addIns2("ROR", 0x76, 2, 6, 0, ModeIndexedZeroPageX, c.ror)
c.addIns("RRA", 0x77, 0, 6, 0, ModeIndexedZeroPageX)
c.addIns2("SEI", 0x78, 1, 2, 0, ModeImplied, c.sei)
c.addIns2("ADC", 0x79, 3, 4, 1, ModeIndexedAbsoluteY, c.adc)
c.addIns2("NOP", 0x7a, 1, 2, 0, ModeImplied, c.nop)
c.addIns("RRA", 0x7b, 0, 7, 0, ModeIndexedAbsoluteY)
c.addIns2("NOP", 0x7c, 3, 4, 1, ModeIndexedAbsoluteX, c.nop)
c.addIns2("ADC", 0x7d, 3, 4, 1, ModeIndexedAbsoluteX, c.adc)
c.addIns2("ROR", 0x7e, 3, 7, 0, ModeIndexedAbsoluteX, c.ror)
c.addIns("RRA", 0x7f, 0, 7, 0, ModeIndexedAbsoluteX)
c.addIns2("NOP", 0x80, 2, 2, 0, ModeImmediate, c.nop)
c.addIns2("STA", 0x81, 2, 6, 0, ModeIndexedIndirectX, c.sta)
c.addIns2("NOP", 0x82, 0, 2, 0, ModeImmediate, c.nop)
c.addIns("SAX", 0x83, 0, 6, 0, ModeIndexedIndirectX)
c.addIns2("STY", 0x84, 2, 3, 0, ModeZeroPage, c.sty)
c.addIns2("STA", 0x85, 2, 3, 0, ModeZeroPage, c.sta)
c.addIns2("STX", 0x86, 2, 3, 0, ModeZeroPage, c.stx)
c.addIns("SAX", 0x87, 0, 3, 0, ModeZeroPage)
c.addIns2("DEY", 0x88, 1, 2, 0, ModeImplied, c.dey)
c.addIns2("NOP", 0x89, 0, 2, 0, ModeImmediate, c.nop)
c.addIns2("TXA", 0x8a, 1, 2, 0, ModeImplied, c.txa)
c.addIns("XAA", 0x8b, 0, 2, 0, ModeImmediate)
c.addIns2("STY", 0x8c, 3, 4, 0, ModeAbsolute, c.sty)
c.addIns2("STA", 0x8d, 3, 4, 0, ModeAbsolute, c.sta)
c.addIns2("STX", 0x8e, 3, 4, 0, ModeAbsolute, c.stx)
c.addIns("SAX", 0x8f, 0, 4, 0, ModeAbsolute)
c.addIns2("BCC", 0x90, 2, 2, 1, ModeRelative, c.bcc)
c.addIns2("STA", 0x91, 2, 6, 0, ModeIndirectIndexedY, c.sta)
c.addIns("KIL", 0x92, 0, 2, 0, ModeImplied)
c.addIns("AHX", 0x93, 0, 6, 0, ModeIndirectIndexedY)
c.addIns2("STY", 0x94, 2, 4, 0, ModeIndexedZeroPageX, c.sty)
c.addIns2("STA", 0x95, 2, 4, 0, ModeIndexedZeroPageX, c.sta)
c.addIns2("STX", 0x96, 2, 4, 0, ModeIndexedZeroPageY, c.stx)
c.addIns("SAX", 0x97, 0, 4, 0, ModeIndexedZeroPageY)
c.addIns2("TYA", 0x98, 1, 2, 0, ModeImplied, c.tya)
c.addIns2("STA", 0x99, 3, 5, 0, ModeIndexedAbsoluteY, c.sta)
c.addIns2("TXS", 0x9a, 1, 2, 0, ModeImplied, c.txs)
c.addIns("TAS", 0x9b, 0, 5, 0, ModeIndexedAbsoluteY)
c.addIns("SHY", 0x9c, 0, 5, 0, ModeIndexedAbsoluteX)
c.addIns2("STA", 0x9d, 3, 5, 0, ModeIndexedAbsoluteX, c.sta)
c.addIns("SHX", 0x9e, 0, 5, 0, ModeIndexedAbsoluteY)
c.addIns("AHX", 0x9f, 0, 5, 0, ModeIndexedAbsoluteY)
c.addIns2("LDY", 0xa0, 2, 2, 0, ModeImmediate, c.ldy)
c.addIns2("LDA", 0xa1, 2, 6, 0, ModeIndexedIndirectX, c.lda)
c.addIns2("LDX", 0xa2, 2, 2, 0, ModeImmediate, c.ldx)
c.addIns("LAX", 0xa3, 0, 6, 0, ModeIndexedIndirectX)
c.addIns2("LDY", 0xa4, 2, 3, 0, ModeZeroPage, c.ldy)
c.addIns2("LDA", 0xa5, 2, 3, 0, ModeZeroPage, c.lda)
c.addIns2("LDX", 0xa6, 2, 3, 0, ModeZeroPage, c.ldx)
c.addIns("LAX", 0xa7, 0, 3, 0, ModeZeroPage)
c.addIns2("TAY", 0xa8, 1, 2, 0, ModeImplied, c.tay)
c.addIns2("LDA", 0xa9, 2, 2, 0, ModeImmediate, c.lda)
c.addIns2("TAX", 0xaa, 1, 2, 0, ModeImplied, c.tax)
c.addIns("LAX", 0xab, 0, 2, 0, ModeImmediate)
c.addIns2("LDY", 0xac, 3, 4, 0, ModeAbsolute, c.ldy)
c.addIns2("LDA", 0xad, 3, 4, 0, ModeAbsolute, c.lda)
c.addIns2("LDX", 0xae, 3, 4, 0, ModeAbsolute, c.ldx)
c.addIns("LAX", 0xaf, 0, 4, 0, ModeAbsolute)
c.addIns2("BCS", 0xb0, 2, 2, 1, ModeRelative, c.bcs)
c.addIns2("LDA", 0xb1, 2, 5, 1, ModeIndirectIndexedY, c.lda)
c.addIns("KIL", 0xb2, 0, 2, 0, ModeImplied)
c.addIns("LAX", 0xb3, 0, 5, 1, ModeIndirectIndexedY)
c.addIns2("LDY", 0xb4, 2, 4, 0, ModeIndexedZeroPageX, c.ldy)
c.addIns2("LDA", 0xb5, 2, 4, 0, ModeIndexedZeroPageX, c.lda)
c.addIns2("LDX", 0xb6, 2, 4, 0, ModeIndexedZeroPageY, c.ldx)
c.addIns("LAX", 0xb7, 0, 4, 0, ModeIndexedZeroPageY)
c.addIns2("CLV", 0xb8, 1, 2, 0, ModeImplied, c.clv)
c.addIns2("LDA", 0xb9, 3, 4, 1, ModeIndexedAbsoluteY, c.lda)
c.addIns2("TSX", 0xba, 1, 2, 0, ModeImplied, c.tsx)
c.addIns("LAS", 0xbb, 0, 4, 1, ModeIndexedAbsoluteY)
c.addIns2("LDY", 0xbc, 3, 4, 1, ModeIndexedAbsoluteX, c.ldy)
c.addIns2("LDA", 0xbd, 3, 4, 1, ModeIndexedAbsoluteX, c.lda)
c.addIns2("LDX", 0xbe, 3, 4, 1, ModeIndexedAbsoluteY, c.ldx)
c.addIns("LAX", 0xbf, 0, 4, 1, ModeIndexedAbsoluteY)
c.addIns2("CPY", 0xc0, 2, 2, 0, ModeImmediate, c.cpy)
c.addIns2("CMP", 0xc1, 2, 6, 0, ModeIndexedIndirectX, c.cmp)
c.addIns2("NOP", 0xc2, 0, 2, 0, ModeImmediate, c.nop)
c.addIns("DCP", 0xc3, 0, 8, 0, ModeIndexedIndirectX)
c.addIns2("CPY", 0xc4, 2, 3, 0, ModeZeroPage, c.cpy)
c.addIns2("CMP", 0xc5, 2, 3, 0, ModeZeroPage, c.cmp)
c.addIns2("DEC", 0xc6, 2, 5, 0, ModeZeroPage, c.dec)
c.addIns("DCP", 0xc7, 0, 5, 0, ModeZeroPage)
c.addIns2("INY", 0xc8, 1, 2, 0, ModeImplied, c.iny)
c.addIns2("CMP", 0xc9, 2, 2, 0, ModeImmediate, c.cmp)
c.addIns2("DEX", 0xca, 1, 2, 0, ModeImplied, c.dex)
c.addIns("AXS", 0xcb, 0, 2, 0, ModeImmediate)
c.addIns2("CPY", 0xcc, 3, 4, 0, ModeAbsolute, c.cpy)
c.addIns2("CMP", 0xcd, 3, 4, 0, ModeAbsolute, c.cmp)
c.addIns2("DEC", 0xce, 3, 6, 0, ModeAbsolute, c.dec)
c.addIns("DCP", 0xcf, 0, 6, 0, ModeAbsolute)
c.addIns2("BNE", 0xd0, 2, 2, 1, ModeRelative, c.bne)
c.addIns2("CMP", 0xd1, 2, 5, 1, ModeIndirectIndexedY, c.cmp)
c.addIns("KIL", 0xd2, 0, 2, 0, ModeImplied)
c.addIns("DCP", 0xd3, 0, 8, 0, ModeIndirectIndexedY)
c.addIns2("NOP", 0xd4, 2, 4, 0, ModeIndexedZeroPageX, c.nop)
c.addIns2("CMP", 0xd5, 2, 4, 0, ModeIndexedZeroPageX, c.cmp)
c.addIns2("DEC", 0xd6, 2, 6, 0, ModeIndexedZeroPageX, c.dec)
c.addIns("DCP", 0xd7, 0, 6, 0, ModeIndexedZeroPageX)
c.addIns2("CLD", 0xd8, 1, 2, 0, ModeImplied, c.cld)
c.addIns2("CMP", 0xd9, 3, 4, 1, ModeIndexedAbsoluteY, c.cmp)
c.addIns2("NOP", 0xda, 1, 2, 0, ModeImplied, c.nop)
c.addIns("DCP", 0xdb, 0, 7, 0, ModeIndexedAbsoluteY)
c.addIns2("NOP", 0xdc, 3, 4, 1, ModeIndexedAbsoluteX, c.nop)
c.addIns2("CMP", 0xdd, 3, 4, 1, ModeIndexedAbsoluteX, c.cmp)
c.addIns2("DEC", 0xde, 3, 7, 0, ModeIndexedAbsoluteX, c.dec)
c.addIns("DCP", 0xdf, 0, 7, 0, ModeIndexedAbsoluteX)
c.addIns2("CPX", 0xe0, 2, 2, 0, ModeImmediate, c.cpx)
c.addIns2("SBC", 0xe1, 2, 6, 0, ModeIndexedIndirectX, c.sbc)
c.addIns2("NOP", 0xe2, 0, 2, 0, ModeImmediate, c.nop)
c.addIns("ISB", 0xe3, 0, 8, 0, ModeIndexedIndirectX)
c.addIns2("CPX", 0xe4, 2, 3, 0, ModeZeroPage, c.cpx)
c.addIns2("SBC", 0xe5, 2, 3, 0, ModeZeroPage, c.sbc)
c.addIns2("INC", 0xe6, 2, 5, 0, ModeZeroPage, c.inc)
c.addIns("ISB", 0xe7, 0, 5, 0, ModeZeroPage)
c.addIns2("INX", 0xe8, 1, 2, 0, ModeImplied, c.inx)
c.addIns2("SBC", 0xe9, 2, 2, 0, ModeImmediate, c.sbc)
c.addIns2("NOP", 0xea, 1, 2, 0, ModeImplied, c.nop)
c.addIns2("SBC", 0xeb, 0, 2, 0, ModeImmediate, c.sbc)
c.addIns2("CPX", 0xec, 3, 4, 0, ModeAbsolute, c.cpx)
c.addIns2("SBC", 0xed, 3, 4, 0, ModeAbsolute, c.sbc)
c.addIns2("INC", 0xee, 3, 6, 0, ModeAbsolute, c.inc)
c.addIns("ISB", 0xef, 0, 6, 0, ModeAbsolute)
c.addIns2("BEQ", 0xf0, 2, 2, 1, ModeRelative, c.beq)
c.addIns2("SBC", 0xf1, 2, 5, 1, ModeIndirectIndexedY, c.sbc)
c.addIns("KIL", 0xf2, 0, 2, 0, ModeImplied)
c.addIns("ISB", 0xf3, 0, 8, 0, ModeIndirectIndexedY)
c.addIns2("NOP", 0xf4, 2, 4, 0, ModeIndexedZeroPageX, c.nop)
c.addIns2("SBC", 0xf5, 2, 4, 0, ModeIndexedZeroPageX, c.sbc)
c.addIns2("INC", 0xf6, 2, 6, 0, ModeIndexedZeroPageX, c.inc)
c.addIns("ISB", 0xf7, 0, 6, 0, ModeIndexedZeroPageX)
c.addIns2("SED", 0xf8, 1, 2, 0, ModeImplied, c.sed)
c.addIns2("SBC", 0xf9, 3, 4, 1, ModeIndexedAbsoluteY, c.sbc)
c.addIns2("NOP", 0xfa, 1, 2, 0, ModeImplied, c.nop)
c.addIns("ISB", 0xfb, 0, 7, 0, ModeIndexedAbsoluteY)
c.addIns2("NOP", 0xfc, 3, 4, 1, ModeIndexedAbsoluteX, c.nop)
c.addIns2("SBC", 0xfd, 3, 4, 1, ModeIndexedAbsoluteX, c.sbc)
c.addIns2("INC", 0xfe, 3, 7, 0, ModeIndexedAbsoluteX, c.inc)
c.addIns("ISB", 0xff, 0, 7, 0, ModeIndexedAbsoluteX)
}
func (c *Cpu) unhandled() {
message := "oops... unhandled instruction!\n"
c.Logf(message)
panic(message)
}
func (c *Cpu) addIns(opName string, opCode uint8, opLength uint8, opCycles uint8, opPageCycles uint8, addrMode uint8) {
c.ins[opCode] = Instruction{opLength, opCycles, opPageCycles, addrMode,
opCode, opName, c.unhandled, false}
}
func (c *Cpu) addIns2(opName string, opCode uint8, opLength uint8, opCycles uint8, opPageCycles uint8, addrMode uint8, f func()) {
c.ins[opCode] = Instruction{opLength, opCycles, opPageCycles, addrMode,
opCode, opName, f, true}
}
|
member
|
package cluster
import (
"testing"
"github.com/ditrit/gandalf/core/cluster"
)
func TestNewClusterMember(t *testing.T) {
const (
logicalName string = "test"
databasePath string = "test"
logPath string = "test"
shosetType string = "cl"
)
connectorMember := cluster.NewClusterMember(logicalName, databasePath, logPath)
if connectorMember == nil {
t.Errorf("Should not be nil")
}
if connectorMember.GetChaussette().GetName() != logicalName {
t.Errorf("Should be equal")
}
if connectorMember.GetChaussette().GetShosetType() != shosetType {
t.Errorf("Should be equal")
}
if connectorMember.MapDatabaseClient == nil {
t.Errorf("Should not be nil")
}
if connectorMember.GetChaussette().Handle["cfgjoin"] == nil {
t.Errorf("Should not be nil")
}
if connectorMember.GetChaussette().Handle["cmd"] == nil {
t.Errorf("Should not be nil")
}
if connectorMember.GetChaussette().Handle["evt"] == nil {
t.Errorf("Should not be nil")
}
}
func TestClusterMemberInit(t *testing.T) {
const (
logicalName string = "test"
databasePath string = "test"
logPath string = "test"
shosetType string = "cls"
bindAddress string = "127.0.0.1:8001"
)
clusterMember := cluster.ClusterMemberInit(logicalName, bindAddress, databasePath, logPath)
if clusterMember == nil {
t.Errorf("Should not be nil")
}
if clusterMember.GetChaussette().GetBindAddr() != bindAddress {
t.Errorf("Should be equal")
}
}
|
non-member
|
package main
import (
"flag"
"log"
"net/http"
"os"
"github.com/nsmith5/vgraas/pkg/middleware"
"github.com/nsmith5/vgraas/pkg/vgraas"
)
func main() {
var (
addr = flag.String("api", ":8080", "API listen address")
)
flag.Parse()
var api http.Handler
{
repo := vgraas.NewRAMRepo()
api = vgraas.NewAPI(repo)
// Limit request size to 500 KiB
api = middleware.LimitBody(api, 1<<19)
// Rate limit requests to 5Hz per remote address with bursts of 2
api = middleware.RateLimit(api, 5, 2, middleware.XForwardedFor)
// Logging
api = middleware.Logging(api, os.Stdout)
}
log.Println(http.ListenAndServe(*addr, api))
}
|
non-member
|
package util
import (
"fmt"
"testing"
)
func TestGenerateRandomString(t *testing.T) {
for _, length := range []int{0, 10, 25} {
t.Run(fmt.Sprintf("length_%d", length), func(t *testing.T) {
rnd := GenerateRandomString(length)
if len(rnd) != length {
t.Errorf("GenerateRandomString() = %v, want %v", len(rnd), length)
}
})
}
}
func TestIsNameValid(t *testing.T) {
tests := []struct {
name string
username string
want bool
}{
{"empty", "", false},
{"too long", "12345678901234567", false},
{"16", "1234567890123456", true},
{"spaces", "hello world", false},
{"no spaces", "helloworld", true},
{"special chars", "helloworld!", false},
{"only special chars", "!ยง$%&", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IsNameValid(tt.username); got != tt.want {
t.Errorf("IsNameValid() = %v, want %v", got, tt.want)
}
})
}
}
|
non-member
|
package web
import "testing"
func TestIndexHandler(t *testing.T) {
rr := testHandler(createRouter(), "GET", "/", nil)
if rr.Code != 200 {
t.Fatalf("Expected index to respond with 200, got %d instead", rr.Code)
}
}
|
non-member
|
package uix
import (
"git.kirsle.net/SketchyMaze/doodle/pkg/shmem"
"git.kirsle.net/go/render"
"git.kirsle.net/go/ui"
)
/*
Functions for the Crosshair feature of the game.
NOT dependent on Canvas!
*/
type Crosshair struct {
LengthPct float64 // between 0 and 1
Widget ui.Widget
}
func NewCrosshair(child ui.Widget, length float64) *Crosshair {
return &Crosshair{
LengthPct: length,
Widget: child,
}
}
// DrawCrosshair renders a crosshair on the screen. It appears while the mouse cursor is
// over the child widget and draws within the bounds of the child widget.
//
// The lengthPct is an integer ranged 0 to 100 to be a percentage length of the crosshair.
// A value of zero will not draw anything and just return.
func DrawCrosshair(e render.Engine, child ui.Widget, color render.Color, lengthPct int) {
// Get our window boundaries based on our widget.
var (
Position = ui.AbsolutePosition(child)
Size = child.Size()
Cursor = shmem.Cursor
VertLine = []render.Point{
{X: Cursor.X, Y: Position.Y},
{X: Cursor.X, Y: Position.Y + Size.H},
}
HozLine = []render.Point{
{X: Position.X, Y: Cursor.Y},
{X: Position.X + Size.W, Y: Cursor.Y},
}
)
if lengthPct > 100 {
lengthPct = 100
} else if lengthPct <= 0 {
return
}
// Mouse outside our box.
if Cursor.X < Position.X || Cursor.X > Position.X+Size.W ||
Cursor.Y < Position.Y || Cursor.Y > Position.Y+Size.H {
return
}
e.DrawLine(
color,
VertLine[0],
VertLine[1],
)
e.DrawLine(
color,
HozLine[0],
HozLine[1],
)
}
|
non-member
|
package polyglot
var zobristHashes = [781]uint64{
0x9D39247E33776D41, 0x2AF7398005AAA5C7, 0x44DB015024623547, 0x9C15F73E62A76AE2,
0x75834465489C0C89, 0x3290AC3A203001BF, 0x0FBBAD1F61042279, 0xE83A908FF2FB60CA,
0x0D7E765D58755C10, 0x1A083822CEAFE02D, 0x9605D5F0E25EC3B0, 0xD021FF5CD13A2ED5,
0x40BDF15D4A672E32, 0x011355146FD56395, 0x5DB4832046F3D9E5, 0x239F8B2D7FF719CC,
0x05D1A1AE85B49AA1, 0x679F848F6E8FC971, 0x7449BBFF801FED0B, 0x7D11CDB1C3B7ADF0,
0x82C7709E781EB7CC, 0xF3218F1C9510786C, 0x331478F3AF51BBE6, 0x4BB38DE5E7219443,
0xAA649C6EBCFD50FC, 0x8DBD98A352AFD40B, 0x87D2074B81D79217, 0x19F3C751D3E92AE1,
0xB4AB30F062B19ABF, 0x7B0500AC42047AC4, 0xC9452CA81A09D85D, 0x24AA6C514DA27500,
0x4C9F34427501B447, 0x14A68FD73C910841, 0xA71B9B83461CBD93, 0x03488B95B0F1850F,
0x637B2B34FF93C040, 0x09D1BC9A3DD90A94, 0x3575668334A1DD3B, 0x735E2B97A4C45A23,
0x18727070F1BD400B, 0x1FCBACD259BF02E7, 0xD310A7C2CE9B6555, 0xBF983FE0FE5D8244,
0x9F74D14F7454A824, 0x51EBDC4AB9BA3035, 0x5C82C505DB9AB0FA, 0xFCF7FE8A3430B241,
0x3253A729B9BA3DDE, 0x8C74C368081B3075, 0xB9BC6C87167C33E7, 0x7EF48F2B83024E20,
0x11D505D4C351BD7F, 0x6568FCA92C76A243, 0x4DE0B0F40F32A7B8, 0x96D693460CC37E5D,
0x42E240CB63689F2F, 0x6D2BDCDAE2919661, 0x42880B0236E4D951, 0x5F0F4A5898171BB6,
0x39F890F579F92F88, 0x93C5B5F47356388B, 0x63DC359D8D231B78, 0xEC16CA8AEA98AD76,
0x5355F900C2A82DC7, 0x07FB9F855A997142, 0x5093417AA8A7ED5E, 0x7BCBC38DA25A7F3C,
0x19FC8A768CF4B6D4, 0x637A7780DECFC0D9, 0x8249A47AEE0E41F7, 0x79AD695501E7D1E8,
0x14ACBAF4777D5776, 0xF145B6BECCDEA195, 0xDABF2AC8201752FC, 0x24C3C94DF9C8D3F6,
0xBB6E2924F03912EA, 0x0CE26C0B95C980D9, 0xA49CD132BFBF7CC4, 0xE99D662AF4243939,
0x27E6AD7891165C3F, 0x8535F040B9744FF1, 0x54B3F4FA5F40D873, 0x72B12C32127FED2B,
0xEE954D3C7B411F47, 0x9A85AC909A24EAA1, 0x70AC4CD9F04F21F5, 0xF9B89D3E99A075C2,
0x87B3E2B2B5C907B1, 0xA366E5B8C54F48B8, 0xAE4A9346CC3F7CF2, 0x1920C04D47267BBD,
0x87BF02C6B49E2AE9, 0x092237AC237F3859, 0xFF07F64EF8ED14D0, 0x8DE8DCA9F03CC54E,
0x9C1633264DB49C89, 0xB3F22C3D0B0B38ED, 0x390E5FB44D01144B, 0x5BFEA5B4712768E9,
0x1E1032911FA78984, 0x9A74ACB964E78CB3, 0x4F80F7A035DAFB04, 0x6304D09A0B3738C4,
0x2171E64683023A08, 0x5B9B63EB9CEFF80C, 0x506AACF489889342, 0x1881AFC9A3A701D6,
0x6503080440750644, 0xDFD395339CDBF4A7, 0xEF927DBCF00C20F2, 0x7B32F7D1E03680EC,
0xB9FD7620E7316243, 0x05A7E8A57DB91B77, 0xB5889C6E15630A75, 0x4A750A09CE9573F7,
0xCF464CEC899A2F8A, 0xF538639CE705B824, 0x3C79A0FF5580EF7F, 0xEDE6C87F8477609D,
0x799E81F05BC93F31, 0x86536B8CF3428A8C, 0x97D7374C60087B73, 0xA246637CFF328532,
0x043FCAE60CC0EBA0, 0x920E449535DD359E, 0x70EB093B15B290CC, 0x73A1921916591CBD,
0x56436C9FE1A1AA8D, 0xEFAC4B70633B8F81, 0xBB215798D45DF7AF, 0x45F20042F24F1768,
0x930F80F4E8EB7462, 0xFF6712FFCFD75EA1, 0xAE623FD67468AA70, 0xDD2C5BC84BC8D8FC,
0x7EED120D54CF2DD9, 0x22FE545401165F1C, 0xC91800E98FB99929, 0x808BD68E6AC10365,
0xDEC468145B7605F6, 0x1BEDE3A3AEF53302, 0x43539603D6C55602, 0xAA969B5C691CCB7A,
0xA87832D392EFEE56, 0x65942C7B3C7E11AE, 0xDED2D633CAD004F6, 0x21F08570F420E565,
0xB415938D7DA94E3C, 0x91B859E59ECB6350, 0x10CFF333E0ED804A, 0x28AED140BE0BB7DD,
0xC5CC1D89724FA456, 0x5648F680F11A2741, 0x2D255069F0B7DAB3, 0x9BC5A38EF729ABD4,
0xEF2F054308F6A2BC, 0xAF2042F5CC5C2858, 0x480412BAB7F5BE2A, 0xAEF3AF4A563DFE43,
0x19AFE59AE451497F, 0x52593803DFF1E840, 0xF4F076E65F2CE6F0, 0x11379625747D5AF3,
0xBCE5D2248682C115, 0x9DA4243DE836994F, 0x066F70B33FE09017, 0x4DC4DE189B671A1C,
0x51039AB7712457C3, 0xC07A3F80C31FB4B4, 0xB46EE9C5E64A6E7C, 0xB3819A42ABE61C87,
0x21A007933A522A20, 0x2DF16F761598AA4F, 0x763C4A1371B368FD, 0xF793C46702E086A0,
0xD7288E012AEB8D31, 0xDE336A2A4BC1C44B, 0x0BF692B38D079F23, 0x2C604A7A177326B3,
0x4850E73E03EB6064, 0xCFC447F1E53C8E1B, 0xB05CA3F564268D99, 0x9AE182C8BC9474E8,
0xA4FC4BD4FC5558CA, 0xE755178D58FC4E76, 0x69B97DB1A4C03DFE, 0xF9B5B7C4ACC67C96,
0xFC6A82D64B8655FB, 0x9C684CB6C4D24417, 0x8EC97D2917456ED0, 0x6703DF9D2924E97E,
0xC547F57E42A7444E, 0x78E37644E7CAD29E, 0xFE9A44E9362F05FA, 0x08BD35CC38336615,
0x9315E5EB3A129ACE, 0x94061B871E04DF75, 0xDF1D9F9D784BA010, 0x3BBA57B68871B59D,
0xD2B7ADEEDED1F73F, 0xF7A255D83BC373F8, 0xD7F4F2448C0CEB81, 0xD95BE88CD210FFA7,
0x336F52F8FF4728E7, 0xA74049DAC312AC71, 0xA2F61BB6E437FDB5, 0x4F2A5CB07F6A35B3,
0x87D380BDA5BF7859, 0x16B9F7E06C453A21, 0x7BA2484C8A0FD54E, 0xF3A678CAD9A2E38C,
0x39B0BF7DDE437BA2, 0xFCAF55C1BF8A4424, 0x18FCF680573FA594, 0x4C0563B89F495AC3,
0x40E087931A00930D, 0x8CFFA9412EB642C1, 0x68CA39053261169F, 0x7A1EE967D27579E2,
0x9D1D60E5076F5B6F, 0x3810E399B6F65BA2, 0x32095B6D4AB5F9B1, 0x35CAB62109DD038A,
0xA90B24499FCFAFB1, 0x77A225A07CC2C6BD, 0x513E5E634C70E331, 0x4361C0CA3F692F12,
0xD941ACA44B20A45B, 0x528F7C8602C5807B, 0x52AB92BEB9613989, 0x9D1DFA2EFC557F73,
0x722FF175F572C348, 0x1D1260A51107FE97, 0x7A249A57EC0C9BA2, 0x04208FE9E8F7F2D6,
0x5A110C6058B920A0, 0x0CD9A497658A5698, 0x56FD23C8F9715A4C, 0x284C847B9D887AAE,
0x04FEABFBBDB619CB, 0x742E1E651C60BA83, 0x9A9632E65904AD3C, 0x881B82A13B51B9E2,
0x506E6744CD974924, 0xB0183DB56FFC6A79, 0x0ED9B915C66ED37E, 0x5E11E86D5873D484,
0xF678647E3519AC6E, 0x1B85D488D0F20CC5, 0xDAB9FE6525D89021, 0x0D151D86ADB73615,
0xA865A54EDCC0F019, 0x93C42566AEF98FFB, 0x99E7AFEABE000731, 0x48CBFF086DDF285A,
0x7F9B6AF1EBF78BAF, 0x58627E1A149BBA21, 0x2CD16E2ABD791E33, 0xD363EFF5F0977996,
0x0CE2A38C344A6EED, 0x1A804AADB9CFA741, 0x907F30421D78C5DE, 0x501F65EDB3034D07,
0x37624AE5A48FA6E9, 0x957BAF61700CFF4E, 0x3A6C27934E31188A, 0xD49503536ABCA345,
0x088E049589C432E0, 0xF943AEE7FEBF21B8, 0x6C3B8E3E336139D3, 0x364F6FFA464EE52E,
0xD60F6DCEDC314222, 0x56963B0DCA418FC0, 0x16F50EDF91E513AF, 0xEF1955914B609F93,
0x565601C0364E3228, 0xECB53939887E8175, 0xBAC7A9A18531294B, 0xB344C470397BBA52,
0x65D34954DAF3CEBD, 0xB4B81B3FA97511E2, 0xB422061193D6F6A7, 0x071582401C38434D,
0x7A13F18BBEDC4FF5, 0xBC4097B116C524D2, 0x59B97885E2F2EA28, 0x99170A5DC3115544,
0x6F423357E7C6A9F9, 0x325928EE6E6F8794, 0xD0E4366228B03343, 0x565C31F7DE89EA27,
0x30F5611484119414, 0xD873DB391292ED4F, 0x7BD94E1D8E17DEBC, 0xC7D9F16864A76E94,
0x947AE053EE56E63C, 0xC8C93882F9475F5F, 0x3A9BF55BA91F81CA, 0xD9A11FBB3D9808E4,
0x0FD22063EDC29FCA, 0xB3F256D8ACA0B0B9, 0xB03031A8B4516E84, 0x35DD37D5871448AF,
0xE9F6082B05542E4E, 0xEBFAFA33D7254B59, 0x9255ABB50D532280, 0xB9AB4CE57F2D34F3,
0x693501D628297551, 0xC62C58F97DD949BF, 0xCD454F8F19C5126A, 0xBBE83F4ECC2BDECB,
0xDC842B7E2819E230, 0xBA89142E007503B8, 0xA3BC941D0A5061CB, 0xE9F6760E32CD8021,
0x09C7E552BC76492F, 0x852F54934DA55CC9, 0x8107FCCF064FCF56, 0x098954D51FFF6580,
0x23B70EDB1955C4BF, 0xC330DE426430F69D, 0x4715ED43E8A45C0A, 0xA8D7E4DAB780A08D,
0x0572B974F03CE0BB, 0xB57D2E985E1419C7, 0xE8D9ECBE2CF3D73F, 0x2FE4B17170E59750,
0x11317BA87905E790, 0x7FBF21EC8A1F45EC, 0x1725CABFCB045B00, 0x964E915CD5E2B207,
0x3E2B8BCBF016D66D, 0xBE7444E39328A0AC, 0xF85B2B4FBCDE44B7, 0x49353FEA39BA63B1,
0x1DD01AAFCD53486A, 0x1FCA8A92FD719F85, 0xFC7C95D827357AFA, 0x18A6A990C8B35EBD,
0xCCCB7005C6B9C28D, 0x3BDBB92C43B17F26, 0xAA70B5B4F89695A2, 0xE94C39A54A98307F,
0xB7A0B174CFF6F36E, 0xD4DBA84729AF48AD, 0x2E18BC1AD9704A68, 0x2DE0966DAF2F8B1C,
0xB9C11D5B1E43A07E, 0x64972D68DEE33360, 0x94628D38D0C20584, 0xDBC0D2B6AB90A559,
0xD2733C4335C6A72F, 0x7E75D99D94A70F4D, 0x6CED1983376FA72B, 0x97FCAACBF030BC24,
0x7B77497B32503B12, 0x8547EDDFB81CCB94, 0x79999CDFF70902CB, 0xCFFE1939438E9B24,
0x829626E3892D95D7, 0x92FAE24291F2B3F1, 0x63E22C147B9C3403, 0xC678B6D860284A1C,
0x5873888850659AE7, 0x0981DCD296A8736D, 0x9F65789A6509A440, 0x9FF38FED72E9052F,
0xE479EE5B9930578C, 0xE7F28ECD2D49EECD, 0x56C074A581EA17FE, 0x5544F7D774B14AEF,
0x7B3F0195FC6F290F, 0x12153635B2C0CF57, 0x7F5126DBBA5E0CA7, 0x7A76956C3EAFB413,
0x3D5774A11D31AB39, 0x8A1B083821F40CB4, 0x7B4A38E32537DF62, 0x950113646D1D6E03,
0x4DA8979A0041E8A9, 0x3BC36E078F7515D7, 0x5D0A12F27AD310D1, 0x7F9D1A2E1EBE1327,
0xDA3A361B1C5157B1, 0xDCDD7D20903D0C25, 0x36833336D068F707, 0xCE68341F79893389,
0xAB9090168DD05F34, 0x43954B3252DC25E5, 0xB438C2B67F98E5E9, 0x10DCD78E3851A492,
0xDBC27AB5447822BF, 0x9B3CDB65F82CA382, 0xB67B7896167B4C84, 0xBFCED1B0048EAC50,
0xA9119B60369FFEBD, 0x1FFF7AC80904BF45, 0xAC12FB171817EEE7, 0xAF08DA9177DDA93D,
0x1B0CAB936E65C744, 0xB559EB1D04E5E932, 0xC37B45B3F8D6F2BA, 0xC3A9DC228CAAC9E9,
0xF3B8B6675A6507FF, 0x9FC477DE4ED681DA, 0x67378D8ECCEF96CB, 0x6DD856D94D259236,
0xA319CE15B0B4DB31, 0x073973751F12DD5E, 0x8A8E849EB32781A5, 0xE1925C71285279F5,
0x74C04BF1790C0EFE, 0x4DDA48153C94938A, 0x9D266D6A1CC0542C, 0x7440FB816508C4FE,
0x13328503DF48229F, 0xD6BF7BAEE43CAC40, 0x4838D65F6EF6748F, 0x1E152328F3318DEA,
0x8F8419A348F296BF, 0x72C8834A5957B511, 0xD7A023A73260B45C, 0x94EBC8ABCFB56DAE,
0x9FC10D0F989993E0, 0xDE68A2355B93CAE6, 0xA44CFE79AE538BBE, 0x9D1D84FCCE371425,
0x51D2B1AB2DDFB636, 0x2FD7E4B9E72CD38C, 0x65CA5B96B7552210, 0xDD69A0D8AB3B546D,
0x604D51B25FBF70E2, 0x73AA8A564FB7AC9E, 0x1A8C1E992B941148, 0xAAC40A2703D9BEA0,
0x764DBEAE7FA4F3A6, 0x1E99B96E70A9BE8B, 0x2C5E9DEB57EF4743, 0x3A938FEE32D29981,
0x26E6DB8FFDF5ADFE, 0x469356C504EC9F9D, 0xC8763C5B08D1908C, 0x3F6C6AF859D80055,
0x7F7CC39420A3A545, 0x9BFB227EBDF4C5CE, 0x89039D79D6FC5C5C, 0x8FE88B57305E2AB6,
0xA09E8C8C35AB96DE, 0xFA7E393983325753, 0xD6B6D0ECC617C699, 0xDFEA21EA9E7557E3,
0xB67C1FA481680AF8, 0xCA1E3785A9E724E5, 0x1CFC8BED0D681639, 0xD18D8549D140CAEA,
0x4ED0FE7E9DC91335, 0xE4DBF0634473F5D2, 0x1761F93A44D5AEFE, 0x53898E4C3910DA55,
0x734DE8181F6EC39A, 0x2680B122BAA28D97, 0x298AF231C85BAFAB, 0x7983EED3740847D5,
0x66C1A2A1A60CD889, 0x9E17E49642A3E4C1, 0xEDB454E7BADC0805, 0x50B704CAB602C329,
0x4CC317FB9CDDD023, 0x66B4835D9EAFEA22, 0x219B97E26FFC81BD, 0x261E4E4C0A333A9D,
0x1FE2CCA76517DB90, 0xD7504DFA8816EDBB, 0xB9571FA04DC089C8, 0x1DDC0325259B27DE,
0xCF3F4688801EB9AA, 0xF4F5D05C10CAB243, 0x38B6525C21A42B0E, 0x36F60E2BA4FA6800,
0xEB3593803173E0CE, 0x9C4CD6257C5A3603, 0xAF0C317D32ADAA8A, 0x258E5A80C7204C4B,
0x8B889D624D44885D, 0xF4D14597E660F855, 0xD4347F66EC8941C3, 0xE699ED85B0DFB40D,
0x2472F6207C2D0484, 0xC2A1E7B5B459AEB5, 0xAB4F6451CC1D45EC, 0x63767572AE3D6174,
0xA59E0BD101731A28, 0x116D0016CB948F09, 0x2CF9C8CA052F6E9F, 0x0B090A7560A968E3,
0xABEEDDB2DDE06FF1, 0x58EFC10B06A2068D, 0xC6E57A78FBD986E0, 0x2EAB8CA63CE802D7,
0x14A195640116F336, 0x7C0828DD624EC390, 0xD74BBE77E6116AC7, 0x804456AF10F5FB53,
0xEBE9EA2ADF4321C7, 0x03219A39EE587A30, 0x49787FEF17AF9924, 0xA1E9300CD8520548,
0x5B45E522E4B1B4EF, 0xB49C3B3995091A36, 0xD4490AD526F14431, 0x12A8F216AF9418C2,
0x001F837CC7350524, 0x1877B51E57A764D5, 0xA2853B80F17F58EE, 0x993E1DE72D36D310,
0xB3598080CE64A656, 0x252F59CF0D9F04BB, 0xD23C8E176D113600, 0x1BDA0492E7E4586E,
0x21E0BD5026C619BF, 0x3B097ADAF088F94E, 0x8D14DEDB30BE846E, 0xF95CFFA23AF5F6F4,
0x3871700761B3F743, 0xCA672B91E9E4FA16, 0x64C8E531BFF53B55, 0x241260ED4AD1E87D,
0x106C09B972D2E822, 0x7FBA195410E5CA30, 0x7884D9BC6CB569D8, 0x0647DFEDCD894A29,
0x63573FF03E224774, 0x4FC8E9560F91B123, 0x1DB956E450275779, 0xB8D91274B9E9D4FB,
0xA2EBEE47E2FBFCE1, 0xD9F1F30CCD97FB09, 0xEFED53D75FD64E6B, 0x2E6D02C36017F67F,
0xA9AA4D20DB084E9B, 0xB64BE8D8B25396C1, 0x70CB6AF7C2D5BCF0, 0x98F076A4F7A2322E,
0xBF84470805E69B5F, 0x94C3251F06F90CF3, 0x3E003E616A6591E9, 0xB925A6CD0421AFF3,
0x61BDD1307C66E300, 0xBF8D5108E27E0D48, 0x240AB57A8B888B20, 0xFC87614BAF287E07,
0xEF02CDD06FFDB432, 0xA1082C0466DF6C0A, 0x8215E577001332C8, 0xD39BB9C3A48DB6CF,
0x2738259634305C14, 0x61CF4F94C97DF93D, 0x1B6BACA2AE4E125B, 0x758F450C88572E0B,
0x959F587D507A8359, 0xB063E962E045F54D, 0x60E8ED72C0DFF5D1, 0x7B64978555326F9F,
0xFD080D236DA814BA, 0x8C90FD9B083F4558, 0x106F72FE81E2C590, 0x7976033A39F7D952,
0xA4EC0132764CA04B, 0x733EA705FAE4FA77, 0xB4D8F77BC3E56167, 0x9E21F4F903B33FD9,
0x9D765E419FB69F6D, 0xD30C088BA61EA5EF, 0x5D94337FBFAF7F5B, 0x1A4E4822EB4D7A59,
0x6FFE73E81B637FB3, 0xDDF957BC36D8B9CA, 0x64D0E29EEA8838B3, 0x08DD9BDFD96B9F63,
0x087E79E5A57D1D13, 0xE328E230E3E2B3FB, 0x1C2559E30F0946BE, 0x720BF5F26F4D2EAA,
0xB0774D261CC609DB, 0x443F64EC5A371195, 0x4112CF68649A260E, 0xD813F2FAB7F5C5CA,
0x660D3257380841EE, 0x59AC2C7873F910A3, 0xE846963877671A17, 0x93B633ABFA3469F8,
0xC0C0F5A60EF4CDCF, 0xCAF21ECD4377B28C, 0x57277707199B8175, 0x506C11B9D90E8B1D,
0xD83CC2687A19255F, 0x4A29C6465A314CD1, 0xED2DF21216235097, 0xB5635C95FF7296E2,
0x22AF003AB672E811, 0x52E762596BF68235, 0x9AEBA33AC6ECC6B0, 0x944F6DE09134DFB6,
0x6C47BEC883A7DE39, 0x6AD047C430A12104, 0xA5B1CFDBA0AB4067, 0x7C45D833AFF07862,
0x5092EF950A16DA0B, 0x9338E69C052B8E7B, 0x455A4B4CFE30E3F5, 0x6B02E63195AD0CF8,
0x6B17B224BAD6BF27, 0xD1E0CCD25BB9C169, 0xDE0C89A556B9AE70, 0x50065E535A213CF6,
0x9C1169FA2777B874, 0x78EDEFD694AF1EED, 0x6DC93D9526A50E68, 0xEE97F453F06791ED,
0x32AB0EDB696703D3, 0x3A6853C7E70757A7, 0x31865CED6120F37D, 0x67FEF95D92607890,
0x1F2B1D1F15F6DC9C, 0xB69E38A8965C6B65, 0xAA9119FF184CCCF4, 0xF43C732873F24C13,
0xFB4A3D794A9A80D2, 0x3550C2321FD6109C, 0x371F77E76BB8417E, 0x6BFA9AAE5EC05779,
0xCD04F3FF001A4778, 0xE3273522064480CA, 0x9F91508BFFCFC14A, 0x049A7F41061A9E60,
0xFCB6BE43A9F2FE9B, 0x08DE8A1C7797DA9B, 0x8F9887E6078735A1, 0xB5B4071DBFC73A66,
0x230E343DFBA08D33, 0x43ED7F5A0FAE657D, 0x3A88A0FBBCB05C63, 0x21874B8B4D2DBC4F,
0x1BDEA12E35F6A8C9, 0x53C065C6C8E63528, 0xE34A1D250E7A8D6B, 0xD6B04D3B7651DD7E,
0x5E90277E7CB39E2D, 0x2C046F22062DC67D, 0xB10BB459132D0A26, 0x3FA9DDFB67E2F199,
0x0E09B88E1914F7AF, 0x10E8B35AF3EEAB37, 0x9EEDECA8E272B933, 0xD4C718BC4AE8AE5F,
0x81536D601170FC20, 0x91B534F885818A06, 0xEC8177F83F900978, 0x190E714FADA5156E,
0xB592BF39B0364963, 0x89C350C893AE7DC1, 0xAC042E70F8B383F2, 0xB49B52E587A1EE60,
0xFB152FE3FF26DA89, 0x3E666E6F69AE2C15, 0x3B544EBE544C19F9, 0xE805A1E290CF2456,
0x24B33C9D7ED25117, 0xE74733427B72F0C1, 0x0A804D18B7097475, 0x57E3306D881EDB4F,
0x4AE7D6A36EB5DBCB, 0x2D8D5432157064C8, 0xD1E649DE1E7F268B, 0x8A328A1CEDFE552C,
0x07A3AEC79624C7DA, 0x84547DDC3E203C94, 0x990A98FD5071D263, 0x1A4FF12616EEFC89,
0xF6F7FD1431714200, 0x30C05B1BA332F41C, 0x8D2636B81555A786, 0x46C9FEB55D120902,
0xCCEC0A73B49C9921, 0x4E9D2827355FC492, 0x19EBB029435DCB0F, 0x4659D2B743848A2C,
0x963EF2C96B33BE31, 0x74F85198B05A2E7D, 0x5A0F544DD2B1FB18, 0x03727073C2E134B1,
0xC7F6AA2DE59AEA61, 0x352787BAA0D7C22F, 0x9853EAB63B5E0B35, 0xABBDCDD7ED5C0860,
0xCF05DAF5AC8D77B0, 0x49CAD48CEBF4A71E, 0x7A4C10EC2158C4A6, 0xD9E92AA246BF719E,
0x13AE978D09FE5557, 0x730499AF921549FF, 0x4E4B705B92903BA4, 0xFF577222C14F0A3A,
0x55B6344CF97AAFAE, 0xB862225B055B6960, 0xCAC09AFBDDD2CDB4, 0xDAF8E9829FE96B5F,
0xB5FDFC5D3132C498, 0x310CB380DB6F7503, 0xE87FBB46217A360E, 0x2102AE466EBB1148,
0xF8549E1A3AA5E00D, 0x07A69AFDCC42261A, 0xC4C118BFE78FEAAE, 0xF9F4892ED96BD438,
0x1AF3DBE25D8F45DA, 0xF5B4B0B0D2DEEEB4, 0x962ACEEFA82E1C84, 0x046E3ECAAF453CE9,
0xF05D129681949A4C, 0x964781CE734B3C84, 0x9C2ED44081CE5FBD, 0x522E23F3925E319E,
0x177E00F9FC32F791, 0x2BC60A63A6F3B3F2, 0x222BBFAE61725606, 0x486289DDCC3D6780,
0x7DC7785B8EFDFC80, 0x8AF38731C02BA980, 0x1FAB64EA29A2DDF7, 0xE4D9429322CD065A,
0x9DA058C67844F20C, 0x24C0E332B70019B0, 0x233003B5A6CFE6AD, 0xD586BD01C5C217F6,
0x5E5637885F29BC2B, 0x7EBA726D8C94094B, 0x0A56A5F0BFE39272, 0xD79476A84EE20D06,
0x9E4C1269BAA4BF37, 0x17EFEE45B0DEE640, 0x1D95B0A5FCF90BC6, 0x93CBE0B699C2585D,
0x65FA4F227A2B6D79, 0xD5F9E858292504D5, 0xC2B5A03F71471A6F, 0x59300222B4561E00,
0xCE2F8642CA0712DC, 0x7CA9723FBB2E8988, 0x2785338347F2BA08, 0xC61BB3A141E50E8C,
0x150F361DAB9DEC26, 0x9F6A419D382595F4, 0x64A53DC924FE7AC9, 0x142DE49FFF7A7C3D,
0x0C335248857FA9E7, 0x0A9C32D5EAE45305, 0xE6C42178C4BBB92E, 0x71F1CE2490D20B07,
0xF1BCC3D275AFE51A, 0xE728E8C83C334074, 0x96FBF83A12884624, 0x81A1549FD6573DA5,
0x5FA7867CAF35E149, 0x56986E2EF3ED091B, 0x917F1DD5F8886C61, 0xD20D8C88C8FFE65F,
0x31D71DCE64B2C310, 0xF165B587DF898190, 0xA57E6339DD2CF3A0, 0x1EF6E6DBB1961EC9,
0x70CC73D90BC26E24, 0xE21A6B35DF0C3AD7, 0x003A93D8B2806962, 0x1C99DED33CB890A1,
0xCF3145DE0ADD4289, 0xD0E4427A5514FB72, 0x77C621CC9FB3A483, 0x67A34DAC4356550B,
0xF8D626AAAF278509,
}
|
non-member
|
package stencil
import (
"fmt"
"strings"
"github.com/harrowio/harrow/domain"
)
// CapistranoRails sets up default tasks and environments for working
// with a RubyOnRails application using capistrano.
type CapistranoRails struct {
conf *Configuration
}
func NewCapistranoRails(configuration *Configuration) *CapistranoRails {
return &CapistranoRails{
conf: configuration,
}
}
// Create creates the following objects for this stencil:
//
// Environments: test, staging, production
//
// Tasks (in test): "bundle outdated", "rake notes", "rake test"
//
// Tasks (in staging, production): "cap $env deploy"
func (self *CapistranoRails) Create() error {
errors := NewError()
project, err := self.conf.Projects.FindProject(self.conf.ProjectUuid)
if err != nil {
return errors.Add("FindProject", project, err)
}
testEnvironment := project.NewEnvironment("Test")
if err := self.conf.Environments.CreateEnvironment(testEnvironment); err != nil {
errors.Add("CreateEnvironment", testEnvironment, err)
}
stagingEnvironment := project.NewEnvironment("Staging").
Set("CAPISTRANO_ENV", "staging")
if err := self.conf.Environments.CreateEnvironment(stagingEnvironment); err != nil {
errors.Add("CreateEnvironment", stagingEnvironment, err)
}
productionEnvironment := project.NewEnvironment("Production").
Set("CAPISTRANO_ENV", "production")
if err := self.conf.Environments.CreateEnvironment(productionEnvironment); err != nil {
errors.Add("CreateEnvironment", productionEnvironment, err)
}
deployTask := project.NewTask("Deploy", self.DeployTaskBody())
if err := self.conf.Tasks.CreateTask(deployTask); err != nil {
errors.Add("CreateTask", deployTask, err)
}
notesTask := project.NewTask("Notes", self.NotesTaskBody())
if err := self.conf.Tasks.CreateTask(notesTask); err != nil {
errors.Add("CreateTask", notesTask, err)
}
checkDependenciesTask := project.NewTask("Check dependencies", self.CheckDependenciesTaskBody())
if err := self.conf.Tasks.CreateTask(checkDependenciesTask); err != nil {
errors.Add("CreateTask", checkDependenciesTask, err)
}
runTestsTask := project.NewTask("Run tests", self.RunTestsTaskBody())
if err := self.conf.Tasks.CreateTask(runTestsTask); err != nil {
errors.Add("CreateTask", runTestsTask, err)
}
notesJob := &domain.Job{}
runTestsJob := &domain.Job{}
deployToStagingJob := &domain.Job{}
jobsToCreate := []struct {
Task *domain.Task
Environment *domain.Environment
SaveAs **domain.Job
}{
{runTestsTask, testEnvironment, &runTestsJob},
{notesTask, testEnvironment, ¬esJob},
{checkDependenciesTask, testEnvironment, nil},
{deployTask, stagingEnvironment, &deployToStagingJob},
{deployTask, productionEnvironment, nil},
}
for _, jobToCreate := range jobsToCreate {
jobName := fmt.Sprintf("%s - %s", jobToCreate.Environment.Name, jobToCreate.Task.Name)
job := project.NewJob(jobName, jobToCreate.Task.Uuid, jobToCreate.Environment.Uuid)
if err := self.conf.Jobs.CreateJob(job); err != nil {
errors.Add("CreateJob", job, err)
}
if jobToCreate.SaveAs != nil {
*jobToCreate.SaveAs = job
}
}
if strings.Contains(self.conf.NotifyViaEmail, "@") {
emailNotifier := project.NewEmailNotifier(self.conf.NotifyViaEmail, self.conf.UrlHost)
if err := self.conf.EmailNotifiers.CreateEmailNotifier(emailNotifier); err != nil {
errors.Add("CreateEmailNotifier", emailNotifier, err)
}
notifyAboutNotes := project.NewNotificationRule(
"email_notifiers",
emailNotifier.Uuid,
notesJob.Uuid,
"operation.succeeded",
)
notifyAboutNotes.CreatorUuid = self.conf.UserUuid
if err := self.conf.NotificationRules.CreateNotificationRule(notifyAboutNotes); err != nil {
errors.Add("CreateNotificationRule", notifyAboutNotes, err)
}
}
runNotesWeekly := notesJob.NewRecurringSchedule(self.conf.UserUuid, "@weekly")
if err := self.conf.Schedules.CreateSchedule(runNotesWeekly); err != nil {
errors.Add("CreateSchedule", runNotesWeekly, err)
}
triggerTestsOnNewCommits := project.NewGitTrigger(
"run tests",
self.conf.UserUuid,
runTestsJob.Uuid,
)
if err := self.conf.GitTriggers.CreateGitTrigger(triggerTestsOnNewCommits); err != nil {
errors.Add("CreateGitTrigger", triggerTestsOnNewCommits, err)
}
stagingDeployKey := stagingEnvironment.NewSecret("Deploy key", domain.SecretSsh)
if err := self.conf.Secrets.CreateSecret(stagingDeployKey); err != nil {
errors.Add("CreateSecret", stagingDeployKey, err)
}
productionDeployKey := productionEnvironment.NewSecret("Deploy key", domain.SecretSsh)
if err := self.conf.Secrets.CreateSecret(productionDeployKey); err != nil {
errors.Add("CreateSecret", productionDeployKey, err)
}
currentUser, err := self.conf.Users.FindUser(self.conf.UserUuid)
if err != nil && !domain.IsNotFound(err) {
errors.Add("FindUser", self.conf.UserUuid, err)
}
if currentUser != nil {
self.setUpJobNotifierForDeployingToStaging(errors, currentUser, project, runTestsJob, deployToStagingJob)
}
return errors.ToError()
}
func (self *CapistranoRails) setUpJobNotifierForDeployingToStaging(errors *Error, currentUser *domain.User, project *domain.Project, triggeringJob *domain.Job, jobToTrigger *domain.Job) {
deployToStagingAfterTestsRan := jobToTrigger.NewJobNotifier()
deployToStagingAfterTestsRan.ProjectUuid = project.Uuid
webhook := domain.NewWebhook(
self.conf.ProjectUuid,
currentUser.Uuid,
jobToTrigger.Uuid,
fmt.Sprintf("urn:harrow:job-notifier:%s", deployToStagingAfterTestsRan.Uuid),
)
if err := self.conf.Webhooks.CreateWebhook(webhook); err != nil {
errors.Add("CreateWebhook", webhook, err)
return
}
deployToStagingAfterTestsRan.WebhookURL = webhook.Links(map[string]map[string]string{}, "https", currentUser.UrlHost+"/api")["deliver"]["href"]
if err := self.conf.JobNotifiers.CreateJobNotifier(deployToStagingAfterTestsRan); err != nil {
errors.Add("CreateJobNotifier", deployToStagingAfterTestsRan, err)
}
notificationRule := project.NewNotificationRule(
"job_notifiers",
deployToStagingAfterTestsRan.Uuid,
triggeringJob.Uuid,
"operation.succeeded",
)
notificationRule.CreatorUuid = currentUser.Uuid
if err := notificationRule.Validate(); err != nil {
errors.Add("notificationRule.Validate", notificationRule, err)
}
if err := self.conf.NotificationRules.CreateNotificationRule(notificationRule); err != nil {
errors.Add("CreateNotificationRule", notificationRule, err)
}
}
// DeployTaskBody returns the body of the "deploy" task.
func (self *CapistranoRails) DeployTaskBody() string {
return `#!/bin/bash -e
find ~/repositories -type f -name 'Capfile' -print0 |
xargs -L 1 -0 -I% /bin/bash -c '
cd $(dirname $1)
hfold bundling bundle install
bundle exec cap $CAPISTRANO_ENV deploy
' _ %
`
}
// CheckDependenciesTaskBody returns the body of the "check
// dependencies" task.
func (self *CapistranoRails) CheckDependenciesTaskBody() string {
return `#!/bin/bash -e
find ~/repositories -type f -name 'Gemfile' -print0 |
xargs -L 1 -0 -I% /bin/bash -c '
cd $(dirname $1)
hfold bundling bundle install
bundle outdated
' _ %
`
}
// NotesTaskBody returns the body of the task for displaying project
// notes.
func (self *CapistranoRails) NotesTaskBody() string {
return `#!/bin/bash -e
find ~/repositories -type f -name 'Rakefile' -print0 |
xargs -L 1 -0 -I% /bin/bash -c '
cd $(dirname $1)
hfold bundling bundle install
bundle exec rake notes
' _ %
`
}
// RunTestsTaskBody returns the body of the task for running the
// project's unit tests.
func (self *CapistranoRails) RunTestsTaskBody() string {
return `#!/bin/bash -e
find ~/repositories -type f -name 'Rakefile' -print0 |
xargs -L 1 -0 -I% /bin/bash -c '
cd $(dirname $1)
hfold bundling bundle install
bundle exec rake test
' _ %
`
}
|
non-member
|
package parser
// https://github.com/SatisfactoryModdingUE/UnrealEngine/blob/4.22-CSS/Engine/Source/Runtime/Core/Public/Misc/FrameNumber.h#L16
type FFrameNumber struct {
Value int32 `json:"value"`
}
func (parser *PakParser) ReadFFrameNumber() *FFrameNumber {
return &FFrameNumber{
Value: parser.ReadInt32(),
}
}
|
non-member
|
package events
type (
Event struct {
stopped bool
}
)
// StopPropagation Stops the propagation of the event to further event listeners
func (e *Event) StopPropagation() {
e.stopped = true
}
// IsPropagationStopped returns whether further event listeners should be triggered
func (e *Event) IsPropagationStopped() bool {
return e.stopped
}
|
non-member
|
package mysqlutil
import (
"database/sql/driver"
"fmt"
"log"
"net/url"
"strings"
"github.com/leizongmin/go/sqlutil"
)
type ConnectionOptions struct {
Host string
Port int
User string
Password string
Database string
Charset string
Timezone string // +8:00
ParseTime bool
AutoCommit bool
Params map[string]string
}
func (opts ConnectionOptions) BuildDataSourceString() string {
if opts.Host == "" {
opts.Host = "127.0.0.1"
}
if opts.Port == 0 {
opts.Port = 3306
}
if opts.User == "" {
opts.User = "root"
}
str := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?",
opts.User,
opts.Password,
opts.Host,
opts.Port,
opts.Database,
)
appendQueryString := func(s string) {
if str[len(str)-1:] == "?" {
str += s
} else {
str += "&" + s
}
}
if opts.ParseTime {
appendQueryString("parseTime=true&loc=Local")
}
if opts.Charset != "" {
appendQueryString("charset=" + opts.Charset)
}
if opts.Timezone != "" {
appendQueryString("time_zone=" + url.QueryEscape("'"+opts.Timezone+"'"))
}
if opts.AutoCommit {
appendQueryString("autocommit=true")
}
for k, v := range opts.Params {
appendQueryString(k + "=" + url.QueryEscape(v))
}
return str
}
func Table(tableName string) *sqlutil.QueryBuilder {
return sqlutil.NewEmptyQuery().Init(quoteIdentifier, quoteLiteral).Table(tableName)
}
func Custom(query string, args ...driver.Value) string {
if len(args) < 1 {
return strings.Trim(query, " ")
}
ret, err := sqlutil.InterpolateParams(query, args, sqlutil.GetDefaultLocation(), quoteLiteral)
if err != nil {
log.Println(err)
return query
}
return strings.Trim(ret, " ")
}
func quoteLiteral(buf []byte, v string) []byte {
buf = append(buf, '\'')
buf = escapeStringQuotes(buf, v)
buf = append(buf, '\'')
return buf
}
func quoteIdentifier(id string) string {
return "`" + strings.Replace(strings.Replace(id, "`", "``", -1), ".", "`.`", -1) + "`"
}
|
non-member
|
package types
import (
"regexp"
"whapp-irc/ircconnection"
"whapp-irc/whapp"
)
const messageIDListSize = 750
var (
numberRegex = regexp.MustCompile(`^\+[\d ]+$`)
nonNumberRegex = regexp.MustCompile(`[^\d]`)
)
// A Participant is an user on WhatsApp.
type Participant whapp.Participant
// FullName returns the full/formatted name for the current Participant.
func (p *Participant) FullName() string {
return p.Contact.FormattedName
}
// SafeName returns the irc-safe name for the current Participant.
func (p *Participant) SafeName() string {
str := p.FullName()
if numberRegex.MatchString(str) {
if res := ircconnection.SafeString(p.Contact.PushName); res != "" {
return res
}
}
return ircconnection.SafeString(str)
}
// Chat represents a chat on the bridge.
// It can be private or public, and is always accompanied by a WhatsApp chat.
type Chat struct {
ID whapp.ID
Name string
IsGroupChat bool
Participants []Participant
Joined bool
MessageIDs []string
RawChat whapp.Chat
}
// SafeName returns the IRC-safe name for the current chat.
func (c *Chat) SafeName() string {
return ircconnection.SafeString(c.Name)
}
// Identifier returns the safe IRC identifier for the current chat.
func (c *Chat) Identifier() string {
prefix := ""
if c.IsGroupChat {
prefix = "#"
}
name := c.SafeName()
if !c.IsGroupChat && len(name) > 0 && name[0] == '+' {
name = name[1:]
}
return prefix + name
}
// AddMessageID adds the given id to the chat, so that it's known as
// received/sent.
func (c *Chat) AddMessageID(id string) {
if len(c.MessageIDs) >= messageIDListSize {
c.MessageIDs = c.MessageIDs[1:]
}
c.MessageIDs = append(c.MessageIDs, id)
}
// HasMessageID returns whether or not a message with the given id has been
// received/sent in the current chat.
func (c *Chat) HasMessageID(id string) bool {
for _, x := range c.MessageIDs {
if x == id {
return true
}
}
return false
}
// User represents the on-disk format of an user of the bridge.
type User struct {
Password string `json:"password"`
LocalStorage map[string]string `json:"localStorage"`
LastReceivedReceipts map[string]int64 `json:"lastReceivedReceipts"`
Chats []ChatListItem `json:"chats"`
}
|
non-member
|
package subsonic
import (
"errors"
"net/http"
"time"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/request"
"github.com/navidrome/navidrome/server/subsonic/responses"
"github.com/navidrome/navidrome/utils/req"
"github.com/navidrome/navidrome/utils/slice"
)
func (api *Router) GetBookmarks(r *http.Request) (*responses.Subsonic, error) {
user, _ := request.UserFrom(r.Context())
repo := api.ds.MediaFile(r.Context())
bookmarks, err := repo.GetBookmarks()
if err != nil {
return nil, err
}
response := newResponse()
response.Bookmarks = &responses.Bookmarks{}
response.Bookmarks.Bookmark = slice.Map(bookmarks, func(bmk model.Bookmark) responses.Bookmark {
return responses.Bookmark{
Entry: childFromMediaFile(r.Context(), bmk.Item),
Position: bmk.Position,
Username: user.UserName,
Comment: bmk.Comment,
Created: bmk.CreatedAt,
Changed: bmk.UpdatedAt,
}
})
return response, nil
}
func (api *Router) CreateBookmark(r *http.Request) (*responses.Subsonic, error) {
p := req.Params(r)
id, err := p.String("id")
if err != nil {
return nil, err
}
comment, _ := p.String("comment")
position := p.Int64Or("position", 0)
repo := api.ds.MediaFile(r.Context())
err = repo.AddBookmark(id, comment, position)
if err != nil {
return nil, err
}
return newResponse(), nil
}
func (api *Router) DeleteBookmark(r *http.Request) (*responses.Subsonic, error) {
p := req.Params(r)
id, err := p.String("id")
if err != nil {
return nil, err
}
repo := api.ds.MediaFile(r.Context())
err = repo.DeleteBookmark(id)
if err != nil {
return nil, err
}
return newResponse(), nil
}
func (api *Router) GetPlayQueue(r *http.Request) (*responses.Subsonic, error) {
user, _ := request.UserFrom(r.Context())
repo := api.ds.PlayQueue(r.Context())
pq, err := repo.Retrieve(user.ID)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, err
}
if pq == nil || len(pq.Items) == 0 {
return newResponse(), nil
}
response := newResponse()
response.PlayQueue = &responses.PlayQueue{
Entry: slice.MapWithArg(pq.Items, r.Context(), childFromMediaFile),
Current: pq.Current,
Position: pq.Position,
Username: user.UserName,
Changed: &pq.UpdatedAt,
ChangedBy: pq.ChangedBy,
}
return response, nil
}
func (api *Router) SavePlayQueue(r *http.Request) (*responses.Subsonic, error) {
p := req.Params(r)
ids, _ := p.Strings("id")
current, _ := p.String("current")
position := p.Int64Or("position", 0)
user, _ := request.UserFrom(r.Context())
client, _ := request.ClientFrom(r.Context())
var items model.MediaFiles
for _, id := range ids {
items = append(items, model.MediaFile{ID: id})
}
pq := &model.PlayQueue{
UserID: user.ID,
Current: current,
Position: position,
ChangedBy: client,
Items: items,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
}
repo := api.ds.PlayQueue(r.Context())
err := repo.Store(pq)
if err != nil {
return nil, err
}
return newResponse(), nil
}
|
non-member
|
package iterables
import (
"container/heap"
"fmt"
)
func (i Iterable[T]) Sort(cmp func(T, T) int) Iterable[T] {
gen := sort[T]{tHeap[T]{cmpFunc: cmp}}
for true {
item, err := i.Next()
if (err == IterationStop{}) {
break
} else if err != nil {
invalid := invalidIterable[T]{InvalidSort{err}}
return Iterable[T]{&invalid}
}
heap.Push(&gen.sorter, item)
}
return Iterable[T]{&gen}
}
type sort[T any] struct {
sorter tHeap[T]
}
func (s *sort[T]) Next() (T, error) {
if s.sorter.Len() <= 0 {
return *new(T), IterationStop{}
}
popped := heap.Pop(&s.sorter).(T)
return popped, nil
}
type tHeap[T any] struct {
cmpFunc func(T, T) int
data []T
}
func (h *tHeap[T]) Push(x any) {
item := x.(T)
h.data = append(h.data, item)
}
func (h *tHeap[T]) Pop() any {
lastIndex := len(h.data) - 1
result := h.data[lastIndex]
h.data = h.data[:lastIndex]
return result
}
func (h *tHeap[T]) Len() int {
return len(h.data)
}
func (h *tHeap[T]) Less(i int, j int) bool {
itemI := h.data[i]
itemJ := h.data[j]
return h.cmpFunc(itemI, itemJ) < 0
}
func (h *tHeap[T]) Swap(i int, j int) {
save := h.data[i]
h.data[i] = h.data[j]
h.data[j] = save
}
type InvalidSort struct {
Cause error
}
func (i InvalidSort) Error() string {
return fmt.Sprintf(
"invalid sort because underlying iterable failed: %v",
i.Cause)
}
|
non-member
|
package main
import "fmt"
func filter(in, out chan int) {
go func() {
for n := range in {
if n%2 == 0 {
out <- n
}
}
close(out)
}()
}
func main() {
done := make(chan struct{})
ch := gen(done)
f := make(chan int)
filter(ch, f)
quadratChannel := sq(f)
fmt.Println(<-quadratChannel)
fmt.Println(<-quadratChannel)
fmt.Println(<-quadratChannel)
close(done)
}
func sq(in <-chan int) <-chan int {
out := make(chan int)
go func() {
for n := range in {
out <- n * n
}
close(out)
}()
return out
}
func gen(done chan struct{}) chan int {
ch := make(chan int)
go func() {
i := 0
for {
select {
case ch <- i:
i++
case <-done:
close(ch)
return
}
}
}()
return ch
}
|
non-member
|
package k8sutil
import (
"context"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// UpdatePodCondition updates the given condition type of the given pod with the new status and reason
func UpdatePodCondition(pod *corev1.Pod, condType corev1.PodConditionType, condStatus corev1.ConditionStatus, reason string, kubeclient client.Client) error {
now := metav1.NewTime(time.Now())
found := false
for i, condition := range pod.Status.Conditions {
if condition.Type == condType {
found = true
condition.LastProbeTime = now
if condition.Status != condStatus {
condition.Status = condStatus
condition.LastTransitionTime = now
}
pod.Status.Conditions[i] = condition
break
}
}
if !found {
pod.Status.Conditions = append(pod.Status.Conditions, corev1.PodCondition{
Type: condType,
Status: condStatus,
Reason: reason,
LastProbeTime: now,
LastTransitionTime: now,
})
}
return kubeclient.Status().Update(context.TODO(), pod)
}
// UpdatePodConditionWithBool updates the given condition type of the given pod with the new status and reason.
// It accepts bool conditional status and internally calls UpdatePodCondition with correct status value
func UpdatePodConditionWithBool(pod *corev1.Pod, condType corev1.PodConditionType, condStatus *bool, reason string, kubeclient client.Client) error {
actualStatus := corev1.ConditionUnknown
if condStatus != nil {
if *condStatus {
actualStatus = corev1.ConditionTrue
} else {
actualStatus = corev1.ConditionFalse
}
}
return UpdatePodCondition(pod, condType, actualStatus, reason, kubeclient)
}
|
non-member
|
// Pictures fetcher
package pictures
import (
"fmt"
"io/ioutil"
"log"
"math/rand"
"github.com/PeterCxy/gotelegram"
"github.com/PeterCxy/gotgbot/support/types"
)
type Pictures struct {
tg *telegram.Telegram
pic string
debug bool
}
func Setup(t *telegram.Telegram, config map[string]interface{}, modules map[string]bool, cmds *types.CommandMap) types.Command {
if val, ok := modules["pictures"]; !ok || val {
pictures := &Pictures{tg: t, pic: config["gallery"].(string)}
if debug, ok := config["debug"]; ok {
pictures.debug = debug.(bool)
}
// Meizhi (gank.io girls)
(*cmds)["meizhi"] = types.Command{
Name: "meizhi",
ArgNum: 0,
Desc: "Random picture of girls from gank.io",
Processor: pictures,
}
// Local collection
(*cmds)["pic"] = types.Command{
Name: "pic",
ArgNum: 0,
Desc: "Fetch a picture randomly from Peter's personal collection (WARNING: Might be NSFW)",
Processor: pictures,
}
}
return types.Command{}
}
func (this *Pictures) Command(name string, msg telegram.TObject, args []string) {
switch name {
case "meizhi":
this.Meizhi(msg)
case "pic":
this.Pic(msg)
}
}
func (this *Pictures) Default(name string, msg telegram.TObject, state *map[string]interface{}) {
}
func (this *Pictures) Pic(msg telegram.TObject) {
this.tg.SendChatAction("upload_photo", msg.ChatId())
files, _ := ioutil.ReadDir(this.pic)
f := files[rand.Intn(len(files))]
name := fmt.Sprintf("%s/%s", this.pic, f.Name())
if this.debug {
log.Println(name)
}
this.tg.SendPhoto(name, msg.ChatId())
}
|
non-member
|
package telegram
import (
"main/pkg/constants"
tele "gopkg.in/telebot.v3"
)
func (reporter *Reporter) GetHelpCommand() Command {
return Command{
Name: "help",
Query: constants.ReporterQueryHelp,
Execute: reporter.HandleHelp,
}
}
func (reporter *Reporter) HandleHelp(c tele.Context) (string, error) {
return reporter.Render("Help", reporter.Version)
}
|
non-member
|
package jsonrpc
import (
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/yellomoon/web3tool"
"github.com/yellomoon/web3tool/testutil"
)
func TestSubscribeNewHead(t *testing.T) {
testutil.MultiAddr(t, func(s *testutil.TestServer, addr string) {
if strings.HasPrefix(addr, "http") {
return
}
c, _ := NewClient(addr)
defer c.Close()
data := make(chan []byte)
cancel, err := c.Subscribe("newHeads", func(b []byte) {
data <- b
})
if err != nil {
t.Fatal(err)
}
var lastBlock *web3tool.Block
recv := func(ok bool) {
select {
case buf := <-data:
if !ok {
t.Fatal("unexpected value")
}
var block web3tool.Block
if err := block.UnmarshalJSON(buf); err != nil {
t.Fatal(err)
}
if lastBlock != nil {
if lastBlock.Number+1 != block.Number {
t.Fatalf("bad sequence %d %d", lastBlock.Number, block.Number)
}
}
lastBlock = &block
case <-time.After(1 * time.Second):
if ok {
t.Fatal("timeout for new head")
}
}
}
s.ProcessBlock()
recv(true)
s.ProcessBlock()
recv(true)
assert.NoError(t, cancel())
s.ProcessBlock()
recv(false)
// subscription already closed
assert.Error(t, cancel())
})
}
|
non-member
|
package admin_controller
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/y-transport-server/pkg/app"
"github.com/y-transport-server/pkg/e"
"github.com/y-transport-server/service/admin_service"
)
type login struct {
User string `json:"user" valid:"Required; MaxSize(20);"` // 用户名 也是登录账号
Password string `json:"password" valid:"Required; MaxSize(20);MinSize(6);"` // 密码被加密过的
}
//AdminCheck 后台的身份验证
func AdminCheck(c *gin.Context) {
appG := app.Gin{C: c}
appG.Response(http.StatusOK, e.SUCCESS, nil)
}
//Login 后台登录
func Login(c *gin.Context) {
var (
appG = app.Gin{C: c}
form login
)
httpCode, errCode := app.BindAndValid(c, &form)
if errCode != e.SUCCESS {
appG.Response(httpCode, errCode, nil)
return
}
adminService := admin_service.Admin{User: form.User, Password: form.Password}
token, err := adminService.Login()
if err != nil {
appG.Response(http.StatusOK, e.ERROR_ADMIN_USER, err)
} else {
c.SetCookie("token", token, 86400, "/", "", false, false)
appG.Response(http.StatusOK, e.SUCCESS, nil)
}
}
//Logout 退出登录
func Logout(c *gin.Context) {
appG := app.Gin{C: c}
c.SetCookie("token", "token", -1, "/", "", false, false)
appG.Response(http.StatusOK, e.SUCCESS, nil)
}
|
member
|
package users
import (
"Office-Booking/app/config"
mid "Office-Booking/delivery/http/middleware"
domain "Office-Booking/domain/users"
"Office-Booking/domain/users/request"
"Office-Booking/domain/users/response"
"net/http"
"strconv"
"github.com/labstack/echo/v4"
)
type UserController struct {
UserUsecase domain.UserUsecase
}
func NewUserController(e *echo.Echo, Usecase domain.UserUsecase) {
UserController := &UserController{
UserUsecase: Usecase,
}
authMiddleware := mid.NewGoMiddleware().AuthMiddleware()
// Auth
e.POST("/login", UserController.Login)
e.POST("/Login", UserController.Login)
e.POST("/register", UserController.RegisterUser)
e.POST("/Register", UserController.RegisterUser)
// customer
e.POST("/customer", UserController.CreateUser)
e.GET("/customer/profile/:id", UserController.GetUserByID, authMiddleware)
e.PUT("/customer/profile/:id", UserController.UpdateUsers)
// admin
e.POST("/admin/booking/user", UserController.CreateBooking)
e.GET("/admin/users", UserController.GetUsers)
e.GET("/admin/user/:id", UserController.GetUserByID)
e.DELETE("/admin/User/:id", UserController.DeleteUsers)
e.DELETE("/admin/user/:id", UserController.DeleteUsers)
e.PUT("/admin/user/:id", UserController.UpdateUsers)
e.PUT("/admin/profile/:id", UserController.UpdatesAdmin)
}
func (u *UserController) Login(c echo.Context) error {
var req request.LoginRequest
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
res, err := u.UserUsecase.Login(req)
if err != nil {
return c.JSON(http.StatusUnauthorized, map[string]interface{}{
"code": 401,
"status": false,
"message": err.Error(),
})
}
return c.JSON(http.StatusOK, map[string]interface{}{
"code": 200,
"status": true,
"id_user": res.ID,
"email": res.Email,
"token": res.Token,
})
}
func (u *UserController) RegisterUser(c echo.Context) error {
var req request.RegisterRequest
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
res, err := u.UserUsecase.RegisterUser(req)
if err != nil {
return c.JSON(http.StatusUnauthorized, map[string]interface{}{
"code": 401,
"status": false,
"message": err.Error(),
})
}
return c.JSON(http.StatusOK, map[string]interface{}{
"code": 200,
"status": true,
"id_user": res.ID,
"email": res.Email,
"name": res.Name,
"fullname": res.Fullname,
"alamat": res.Alamat,
"phone": res.Phone,
})
}
func (u *UserController) CreateBooking(c echo.Context) error {
var req request.UserBookingReq
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
res, err := u.UserUsecase.CreateBooking(req)
if err != nil {
return c.JSON(http.StatusUnauthorized, map[string]interface{}{
"code": 401,
"status": false,
"message": err.Error(),
})
}
return c.JSON(http.StatusOK, map[string]interface{}{
"code": 200,
"status": true,
"ID": res.ID,
"Name": res.Name,
"Description": res.Email,
"IDBooking": res.IDBooking,
})
}
func (u *UserController) CreateUser(c echo.Context) error {
var req request.UserCreateRequest
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
createdUser, err := u.UserUsecase.Create(req)
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]interface{}{
"code": 400,
"status": false,
"message": err.Error(),
})
}
res := response.UserCreateResponse{
ID: int(createdUser.ID),
Email: createdUser.Email,
}
return c.JSON(http.StatusCreated, map[string]interface{}{
"code": 201,
"status": true,
"data": res,
})
}
func (u *UserController) GetUserByID(c echo.Context) error {
id, err := strconv.Atoi((c.Param("id")))
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
foundUser, err := u.UserUsecase.ReadByID(id)
if err != nil {
return c.JSON(http.StatusNotFound, map[string]interface{}{
"code": 404,
"status": false,
"message": err.Error(),
})
}
res := response.UserResponse{
ID: int(foundUser.ID),
Email: foundUser.Email,
Password: foundUser.Password,
Name: foundUser.Name,
Fullname: foundUser.Fullname,
Alamat: foundUser.Alamat,
Phone: foundUser.Phone,
CreatedAt: foundUser.CreatedAt,
}
return c.JSON(http.StatusOK, map[string]interface{}{
"code": 200,
"status": true,
"data": res,
})
}
func (u *UserController) GetUserByName(c echo.Context) error {
name := c.Param("name")
foundUser, err := u.UserUsecase.ReadByName(name)
if err != nil {
return c.JSON(http.StatusNotFound, map[string]interface{}{
"code": 404,
"status": false,
"message": err.Error(),
})
}
res := response.UserResponse{
ID: foundUser.ID,
Name: foundUser.Name,
Fullname: foundUser.Fullname,
Email: foundUser.Email,
Alamat: foundUser.Alamat,
Phone: foundUser.Phone,
Password: foundUser.Password,
}
return c.JSON(http.StatusOK, map[string]interface{}{
"code": 200,
"status": true,
"data": res,
})
}
func (u *UserController) GetUsers(c echo.Context) error {
foundUsers, err := u.UserUsecase.ReadAll()
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
var res []response.UsersResponse
for _, foundUser := range *foundUsers {
res = append(res, response.UsersResponse{
ID: int(foundUser.ID),
Email: foundUser.Email,
Name: foundUser.Name,
Fullname: foundUser.Fullname,
Alamat: foundUser.Alamat,
Phone: foundUser.Phone,
CreatedAt: foundUser.CreatedAt,
})
}
return c.JSON(http.StatusOK, map[string]interface{}{
"code": 200,
"status": true,
"data": res,
})
}
func (u *UserController) DeleteUsers(c echo.Context) error {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
_, e := u.UserUsecase.Delete(id)
if e != nil {
return c.JSON(http.StatusNotFound, map[string]interface{}{
"messages": "not found",
"code": 404,
})
}
config.DB.Unscoped().Delete(&domain.User{}, id)
return c.JSON(http.StatusOK, map[string]interface{}{
"messages": "success delete user with id " + strconv.Itoa(id),
"code": 200,
})
}
func (u *UserController) UpdateUsers(c echo.Context) error {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
updateUser := domain.User{}
err = c.Bind(&updateUser)
if err != nil {
return err
}
if err := config.DB.Model(&domain.User{}).Where("id = ?", id).Updates(domain.User{
Name: updateUser.Name,
Fullname: updateUser.Fullname,
Email: updateUser.Email,
Password: updateUser.Password,
Alamat: updateUser.Alamat,
Phone: updateUser.Phone,
IDBooking: updateUser.IDBooking,
}).Error; err != nil {
return c.JSON(http.StatusBadRequest, map[string]interface{}{
"messages": err.Error(),
"code": 400,
})
}
foundUser, _ := u.UserUsecase.ReadByID(id)
return c.JSON(http.StatusOK, map[string]interface{}{
"messages": "success update user with id " + strconv.Itoa(id),
"code": 200,
"data": foundUser,
})
}
func (u *UserController) UpdatesAdmin(c echo.Context) error {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
return c.JSON(http.StatusBadRequest, err.Error())
}
updateUser := domain.User{}
err = c.Bind(&updateUser)
if err != nil {
return err
}
if err := config.DB.Model(&domain.User{}).Where("id = ?", id).Updates(domain.User{
Password: updateUser.Password,
NewPassword: updateUser.NewPassword,
ConfirmPassword: updateUser.ConfirmPassword,
}).Error; err != nil {
return c.JSON(http.StatusBadRequest, map[string]interface{}{
"messages": err.Error(),
"code": 400,
})
}
foundUser, _ := u.UserUsecase.ReadByID(id)
return c.JSON(http.StatusOK, map[string]interface{}{
"messages": "success update user with id " + strconv.Itoa(id),
"code": 200,
"data": foundUser,
})
}
|
non-member
|
package dtclient
import (
"encoding/json"
"github.com/pkg/errors"
)
type ConnectionInfo struct {
TenantUUID string
TenantToken string
Endpoints string
}
type ActiveGateConnectionInfo struct {
ConnectionInfo
}
type OneAgentConnectionInfo struct {
ConnectionInfo
CommunicationHosts []CommunicationHost
}
// CommunicationHost => struct of connection endpoint
type CommunicationHost struct {
Protocol string // nolint:unused
Host string // nolint:unused
Port uint32 // nolint:unused
}
func (dtc *dynatraceClient) GetActiveGateConnectionInfo() (*ActiveGateConnectionInfo, error) {
response, err := dtc.makeRequest(
dtc.getActiveGateConnectionInfoUrl(),
dynatracePaaSToken,
)
if err != nil {
return nil, errors.WithStack(err)
}
defer CloseBodyAfterRequest(response)
data, err := dtc.getServerResponseData(response)
if err != nil {
return nil, dtc.handleErrorResponseFromAPI(data, response.StatusCode)
}
tenantInfo, err := dtc.readResponseForActiveGateTenantInfo(data)
if err != nil {
return nil, err
}
if len(tenantInfo.Endpoints) == 0 {
log.Info("tenant has no endpoints")
}
return tenantInfo, nil
}
type activeGateConnectionInfoJsonResponse struct {
TenantUUID string `json:"tenantUUID"`
TenantToken string `json:"tenantToken"`
CommunicationEndpoints string `json:"communicationEndpoints"`
}
func (dtc *dynatraceClient) readResponseForActiveGateTenantInfo(response []byte) (*ActiveGateConnectionInfo, error) {
resp := activeGateConnectionInfoJsonResponse{}
err := json.Unmarshal(response, &resp)
if err != nil {
log.Error(err, "error unmarshalling activegate tenant info", "response", string(response))
return nil, err
}
agTenantInfo := &ActiveGateConnectionInfo{
ConnectionInfo: ConnectionInfo{
TenantUUID: resp.TenantUUID,
TenantToken: resp.TenantToken,
Endpoints: resp.CommunicationEndpoints,
},
}
return agTenantInfo, nil
}
func (dtc *dynatraceClient) GetOneAgentConnectionInfo() (OneAgentConnectionInfo, error) {
resp, err := dtc.makeRequest(dtc.getOneAgentConnectionInfoUrl(), dynatracePaaSToken)
if err != nil {
return OneAgentConnectionInfo{}, err
}
defer CloseBodyAfterRequest(resp)
responseData, err := dtc.getServerResponseData(resp)
if err != nil {
return OneAgentConnectionInfo{}, err
}
return dtc.readResponseForOneAgentConnectionInfo(responseData)
}
func (dtc *dynatraceClient) readResponseForOneAgentConnectionInfo(response []byte) (OneAgentConnectionInfo, error) {
type jsonResponse struct {
TenantUUID string `json:"tenantUUID"`
TenantToken string `json:"tenantToken"`
CommunicationEndpoints []string `json:"communicationEndpoints"`
FormattedCommunicationEndpoints string `json:"formattedCommunicationEndpoints"`
}
resp := jsonResponse{}
err := json.Unmarshal(response, &resp)
if err != nil {
log.Error(err, "error unmarshalling connection info response", "response", string(response))
return OneAgentConnectionInfo{}, err
}
tenantUUID := resp.TenantUUID
tenantToken := resp.TenantToken
communicationHosts := make([]CommunicationHost, 0, len(resp.CommunicationEndpoints))
formattedCommunicationEndpoints := resp.FormattedCommunicationEndpoints
for _, s := range resp.CommunicationEndpoints {
e, err := ParseEndpoint(s)
if err != nil {
log.Info("failed to parse communication endpoint", "url", s)
continue
}
communicationHosts = append(communicationHosts, e)
}
if len(communicationHosts) == 0 {
return OneAgentConnectionInfo{}, errors.New("no communication hosts available")
}
ci := OneAgentConnectionInfo{
CommunicationHosts: communicationHosts,
ConnectionInfo: ConnectionInfo{
TenantUUID: tenantUUID,
TenantToken: tenantToken,
Endpoints: formattedCommunicationEndpoints,
},
}
return ci, nil
}
|
member
|
package aomx
import (
"net/url"
)
// MustUrl enables parsing and dereferencing a URL in one line.
// It returns a panic if err is not nil.
// Call it for example when you want to dereference the pointer to a parsed URL
// and assign the value to a variable in one line of code.
// This can be useful when initializing structs for example.
// var urlPtr *url.Url
// var urlVal url.Url
// // Assigning to a pointer is possible in one line
// urlPtr, _ = url.Parse(urlString)
// // But two lines are needed for the value
// tempPtr, _ := url.Parse(urlString)
// urlVal = *tempPtr
//
// // With this method though:
// urlVal = *aomx.MustUrl(url.Parse(urlString))
func MustUrl(url *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
return url
}
|
non-member
|
package main
import "testing"
var TestCases = []struct {
Str string
WordExpected string
SentenceExpected string
}{
{"a", "a", "a"},
{"word", "drow", "word"},
{"word1 word2", "2drow 1drow", "word2 word1"},
{"sentence, with. punctuation;", ";noitautcnup .htiw ,ecnetnes", "punctuation; with. sentence,"},
}
func TestReverseString(t *testing.T) {
for _, v := range TestCases {
t.Run(v.Str, func(t *testing.T) {
get := ReverseString(v.Str)
if get != v.WordExpected {
t.Errorf("Expected: %v, got: %v", v.WordExpected, get)
}
})
}
}
func TestReverseSentence(t *testing.T) {
for _, v := range TestCases {
t.Run(v.Str, func(t *testing.T) {
get := ReverseSentence(v.Str, ReverseString)
if get != v.SentenceExpected {
t.Errorf("Expected: %v, got: %v", v.SentenceExpected, get)
}
})
}
}
|
non-member
|
package db
import (
"database/sql"
"errors"
"github.com/google/uuid"
"strconv"
"tide/common"
"tide/pkg/custype"
)
type Item struct {
StationId uuid.UUID `json:"station_id" binding:"required"`
Name string `json:"name" binding:"max=20"`
Type string `json:"type"`
DeviceName string `json:"device_name"`
Status common.Status `json:"status"`
StatusChangedAt custype.TimeMillisecond `json:"status_changed_at"`
Available bool `json:"available"`
}
func GetItems(stationId uuid.UUID) ([]Item, error) {
var (
rows *sql.Rows
err error
)
if stationId == uuid.Nil {
rows, err = TideDB.Query(`select station_id, name, type ,device_name, status, status_changed_at, available!='' from items`)
} else {
rows, err = TideDB.Query(`select station_id, name, type ,device_name, status, status_changed_at, available!='' from items where station_id=$1`, stationId)
}
if err != nil {
return nil, err
}
var (
i Item
items []Item
)
for rows.Next() {
err = rows.Scan(&i.StationId, &i.Name, &i.Type, &i.DeviceName, &i.Status, &i.StatusChangedAt, &i.Available)
if err != nil {
return nil, err
}
items = append(items, i)
}
if err = rows.Err(); err != nil {
return nil, err
}
return items, err
}
func MakeSureTableExist(name string) (err error) {
if common.ContainsIllegalCharacter(name) {
return errors.New("Table name contains illegal characters: " + name)
}
var n int
err = TideDB.QueryRow("select count(to_regclass($1))", name).Scan(&n)
if err != nil {
return err
}
if n == 0 {
_, err = TideDB.Exec(`create table ` + name + `
(
station_id uuid not null,
value double precision not null,
timestamp timestamptz not null
);
create unique index on ` + name + ` (station_id, timestamp);`)
return err
}
return nil
}
func EditItem(i Item) (err error) {
if err = MakeSureTableExist(i.Name); err != nil {
return err
}
tx, err := TideDB.Begin()
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
_, err = tx.Exec(`with latestStatus as ((select status, changed_at from item_status_log where station_id = $1 and item_name = $2 order by row_id desc limit 1)
union (select '', 'epoch'::timestamptz) order by changed_at desc limit 1)
insert into items(station_id, name, type, device_name, available, status, status_changed_at) values
($1,$2,$3,$4,hstore('0', NULL),(select latestStatus.status from latestStatus), (select latestStatus.changed_at from latestStatus))
on conflict (station_id,name) do update
set type = excluded.type, device_name = excluded.device_name`, i.StationId, i.Name, i.Type, i.DeviceName)
if err != nil {
return err
}
return tx.Commit()
}
func SyncItem(i Item) (int64, error) {
res, err := TideDB.Exec(`with latestStatus as ((select status, changed_at from item_status_log where station_id = $1 and item_name = $2 order by row_id desc limit 1)
union (select '', 'epoch'::timestamptz) order by changed_at desc limit 1)
insert into items(station_id, name, type, device_name, status, status_changed_at) values
($1,$2,$3,$4,(select latestStatus.status from latestStatus), (select latestStatus.changed_at from latestStatus))
on conflict (station_id,name) do update
set type = excluded.type, device_name = excluded.device_name
where items.type != $3 or items.device_name != $4`, i.StationId, i.Name, i.Type, i.DeviceName)
return checkResult(res, err)
}
func DelItem(stationId uuid.UUID, name string) (int64, error) {
res, err := TideDB.Exec(`delete from items where station_id=$1 and name=$2`, stationId, name)
return checkResult(res, err)
}
func GetAvailableItems() ([]common.StationItemStruct, error) {
rows, err := TideDB.Query(`select station_id, name from items where available != ''`)
if err != nil {
return nil, err
}
ss, err := scanStationItem(rows)
if err != nil {
return nil, err
}
return ss, err
}
func scanStationItem(rows *sql.Rows) ([]common.StationItemStruct, error) {
var (
err error
s common.StationItemStruct
ss []common.StationItemStruct
)
for rows.Next() {
err = rows.Scan(&s.StationId, &s.ItemName)
if err != nil {
return ss, err
}
ss = append(ss, s)
}
return ss, rows.Err()
}
func UpdateAvailableItems(upstreamId int, newAvail common.UUIDStringsMap) (int64, error) {
var n int64
var err error
tx, err := TideDB.Begin()
if err != nil {
return n, err
}
defer func() {
_ = tx.Rollback()
}()
rows, err := tx.Query(`select station_id, name from items where available ? $1 and
station_id in (select station_id from upstream_stations where upstream_id=$2)`, strconv.Itoa(upstreamId), upstreamId)
if err != nil {
return n, err
}
var (
s common.StationItemStruct
old = make(map[common.StationItemStruct]struct{})
)
for rows.Next() {
err = rows.Scan(&s.StationId, &s.ItemName)
if err != nil {
return n, err
}
old[s] = struct{}{}
}
if err = rows.Err(); err != nil {
return n, err
}
for stationId, items := range newAvail {
for _, itemName := range items {
key := common.StationItemStruct{StationId: stationId, ItemName: itemName}
if _, ok := old[key]; ok {
delete(old, key)
} else {
if err = addAvailableTx(tx, stationId, itemName, upstreamId); err != nil {
return n, err
}
n++
}
}
}
for s := range old {
if err = removeAvailableTx(tx, s.StationId, s.ItemName, upstreamId); err != nil {
return n, err
}
n++
}
return n, tx.Commit()
}
func addAvailableTx(tx *sql.Tx, stationId uuid.UUID, itemName string, upstreamId int) error {
_, err := tx.Exec(`update items set available = items.available||hstore($3, NULL) where station_id=$1 and name=$2`, stationId, itemName, strconv.Itoa(upstreamId))
return err
}
func removeAvailableTx(tx *sql.Tx, stationId uuid.UUID, itemName string, upstreamId int) error {
_, err := tx.Exec(`update items set available = delete(available,$3) where station_id=$1 and name=$2`, stationId, itemName, strconv.Itoa(upstreamId))
return err
}
func RemoveAvailableByUpstreamId(upstreamId int) error {
tx, err := TideDB.Begin()
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
_, err = tx.Exec(`update items set available = delete(available,$1::text) where station_id in
(select station_id from upstream_stations where upstream_id=$1)`, upstreamId)
if err != nil {
return err
}
return tx.Commit()
}
//func AddAvailable(upstreamId int, stationId uuid.UUID, itemName string) error {
// tx, err := TideDB.Begin()
// if err != nil {
// return err
// }
// defer func() {
// _ = tx.Rollback()
// }()
// _, err = tx.Exec(`insert into items(station_id,name,available) values ($1, $2, hstore($3, NULL))
//on conflict(station_id,name) do update set available = items.available||hstore($3, NULL)`,
// stationId, itemName, strconv.Itoa(upstreamId))
// if err != nil {
// return err
// }
// return tx.Commit()
//}
|
non-member
|
package verification
type Type int
const (
Registration Type = 0
Recovery Type = 1
)
|
non-member
|
package database
import (
"testing"
"os"
"flag"
"database/sql"
)
var databaseFlag = flag.Bool("database", false, "run database integration tests")
var messageQueue = flag.Bool("messageQueue", false, "run message queue integration tests")
var integration = flag.Bool("integration", false, "run all integration tests")
var db *sql.DB
func TestMain(m *testing.M) {
flag.Parse()
if *databaseFlag || *integration {
setupDatabase()
}
if *messageQueue || *integration {
setupDatabase()
}
//if !testing.Short() {
//}
result := m.Run()
//if *databaseFlag || *integration {
// teardownDatabase()
//}
//
//if *messageQueue || *integration {
// teardownDatabase()
//}
//if !testing.Short() {
// teardownDatabase()
//}
os.Exit(result)
}
func TestDatabaseGet(t *testing.T) {
if !*databaseFlag && !*integration {
t.Skip()
}
res := ShowBooks2(db)
if res[0].Title != "Meep" {
t.Error("Expected Span")
}
if res[0].Author != "Jihaad" {
t.Error("Expected Jihaad")
}
}
func setupDatabase() {
db = NewDB()
}
|
member
|
package model
import (
"fmt"
"gorm.io/gorm"
)
type ArticleView struct {
gorm.Model
Title string `gorm:"type:varchar(50) not null;commit:标题"`
Content string `gorm:"type:text not null;commit:内容"`
CategoryID uint8 `gorm:"type:smallint not null;commit:分类ID"`
CategoryName string `gorm:"type:varchar(20) not null;commit:分类名称"`
TagID uint8 `gorm:"type:smallint not null;commit:标签ID"`
TagName string `gorm:"type:varchar(20) not null;commit:标签名称"`
CommentCount uint `gorm:"type:int(10) not null;commit:评论总数"`
}
func (av ArticleView) Create(db *gorm.DB) error {
err := db.AutoMigrate(av)
if err != nil {
fmt.Println(err)
return err
}
return db.Create(&av).Error
}
func (av ArticleView) Read(db *gorm.DB) (ArticleView, error) {
var articleView ArticleView
tx := db.First(&articleView, av.ID)
if err := tx.Error; err != nil {
return articleView, err
}
return articleView, nil
}
|
member
|
package wally
import (
"errors"
"fmt"
"github.com/google/gousb"
"io/ioutil"
"time"
)
type status struct {
bStatus string
bwPollTimeout int
bState string
iString string
}
func dfuCommand(dev *gousb.Device, addr int, command int, status *status) (err error) {
var buf []byte
if command == setAddress {
buf = make([]byte, 5)
buf[0] = 0x21
buf[1] = byte(addr & 0xff)
buf[2] = byte((addr >> 8) & 0xff)
buf[3] = byte((addr >> 16) & 0xff)
buf[4] = byte((addr >> 24) & 0xff)
}
if command == eraseAddress {
buf = make([]byte, 5)
buf[0] = 0x41
buf[1] = byte(addr & 0xff)
buf[2] = byte((addr >> 8) & 0xff)
buf[3] = byte((addr >> 16) & 0xff)
buf[4] = byte((addr >> 24) & 0xff)
}
if command == eraseFlash {
buf = make([]byte, 1)
buf[0] = 0x41
}
_, err = dev.Control(33, 1, 0, 0, buf)
err = dfuPollTimeout(dev, status)
if err != nil {
return err
}
return nil
}
func dfuPollTimeout(dev *gousb.Device, status *status) (err error) {
for i := 0; i < 3; i++ {
err = dfuGetStatus(dev, status)
time.Sleep(time.Duration(status.bwPollTimeout) * time.Millisecond)
}
return err
}
func dfuGetStatus(dev *gousb.Device, status *status) (err error) {
buf := make([]byte, 6)
stat, err := dev.Control(161, 3, 0, 0, buf)
if err != nil {
return err
}
if stat == 6 {
status.bStatus = string(buf[0])
status.bwPollTimeout = int((0xff & buf[3] << 16) | (0xff & buf[2]) | 0xff&buf[1])
status.bState = string(buf[4])
status.iString = string(buf[5])
}
return err
}
func dfuClearStatus(dev *gousb.Device) (err error) {
_, err = dev.Control(33, 4, 2, 0, nil)
return err
}
func dfuReboot(dev *gousb.Device, status *status) (err error) {
err = dfuPollTimeout(dev, status)
_, err = dev.Control(33, 1, 2, 0, nil)
time.Sleep(1000 * time.Millisecond)
err = dfuGetStatus(dev, status)
return err
}
func extractSuffix(fileData []byte) (hasSuffix bool, data []byte, err error) {
fileSize := len(fileData)
suffix := fileData[fileSize-dfuSuffixLength : fileSize]
d := string(suffix[10])
f := string(suffix[9])
u := string(suffix[8])
if d == "D" && f == "F" && u == "U" {
vid := int((suffix[5] << 8) + suffix[4])
pid := int((suffix[3] << 8) + suffix[2])
if vid != dfuSuffixVendorID || pid != dfuSuffixProductID {
message := fmt.Sprintf("Invalid vendor or product id, expected %#x:%#x got %#x:%#x", dfuSuffixVendorID, dfuSuffixProductID, vid, pid)
err = errors.New(message)
return true, fileData, err
}
return true, fileData[0 : fileSize-dfuSuffixLength], nil
}
return false, fileData, nil
}
func DFUFlash(s *State) {
dfuStatus := status{}
fileData, err := ioutil.ReadFile(s.FirmwarePath)
if err != nil {
message := fmt.Sprintf("Error while opening firmware: %s", err)
s.Log("error", message)
return
}
hasSuffix, firmwareData, err := extractSuffix(fileData)
if err != nil {
message := fmt.Sprintf("Error while extracting DFU Suffix: %s", err)
s.Log("error", message)
return
}
if hasSuffix {
s.Log("info", "Found a valid DFU Suffix")
} else {
s.Log("info", "No DFU Suffix found")
}
ctx := gousb.NewContext()
defer ctx.Close()
var dev *gousb.Device
// Get the list of device that match TMK's vendor id
for {
// if the app is reset stop this goroutine and close the usb context
if s.Step != 3 {
s.Log("info", "App reset, interrupting the flashing process.")
return
}
s.Log("info", "Waiting for a DFU capable device")
devs, err := ctx.OpenDevices(func(desc *gousb.DeviceDesc) bool {
if desc.Vendor == gousb.ID(dfuVendorID) && desc.Product == gousb.ID(dfuProductID) {
return true
}
return false
})
defer func() {
for _, d := range devs {
d.Close()
}
}()
if err != nil {
message := fmt.Sprintf("OpenDevices: %s", err)
s.Log("warning", message)
}
if len(devs) > 0 {
dev = devs[0]
break
}
time.Sleep(1 * time.Second)
}
dev.SetAutoDetach(true)
dev.ControlTimeout = 5 * time.Second
cfg, err := dev.Config(1)
if err != nil {
message := fmt.Sprintf("Error while claiming the usb interface: %s", err)
s.Log("error", message)
return
}
defer cfg.Close()
fileSize := len(firmwareData)
s.FlashProgress.Sent = 0
s.FlashProgress.Total = fileSize
err = dfuClearStatus(dev)
if err != nil {
message := fmt.Sprintf("Error while clearing the device status: %s", err)
s.Log("error", message)
return
}
s.Step = 4
s.emitUpdate()
err = dfuCommand(dev, 0, eraseFlash, &dfuStatus)
if err != nil {
message := fmt.Sprintf("Error while erasing flash:", err)
s.Log("error", message)
return
}
for page := 0; page < fileSize; page += planckBlockSize {
addr := planckStartAddress + page
chunckSize := planckBlockSize
if page+chunckSize > fileSize {
chunckSize = fileSize - page
}
err = dfuCommand(dev, addr, eraseAddress, &dfuStatus)
if err != nil {
message := fmt.Sprintf("Error while sending the erase address command: %s", err)
s.Log("error", message)
return
}
err = dfuCommand(dev, addr, setAddress, &dfuStatus)
if err != nil {
message := fmt.Sprintf("Error while sending the set address command: %s", err)
s.Log("error", message)
return
}
buf := firmwareData[page : page+chunckSize]
bytes, err := dev.Control(33, 1, 2, 0, buf)
if err != nil {
message := fmt.Sprintf("Error while sending firmware bytes: %s", err)
s.Log("error", message)
return
}
message := fmt.Sprintf("Sent %d bytes out of %d", page+bytes, fileSize)
s.Log("info", message)
s.FlashProgress.Sent += bytes
s.emitUpdate()
}
time.Sleep(1 * time.Second)
s.Log("info", "Sending the reboot command")
err = dfuReboot(dev, &dfuStatus)
if err != nil {
message := fmt.Sprintf("Error while rebooting device: %s", err)
s.Log("error", message)
return
}
s.Step = 5
s.Log("info", "Flash complete")
}
|
member
|
package utils
import (
"github.com/dgrijalva/jwt-go"
"pledge-bridge-backend/config"
"time"
)
func CreateToken(username string) (string, error) {
at := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": username,
"exp": time.Now().Add(time.Hour * 24 * 30).Unix(),
})
token, err := at.SignedString([]byte(config.Config.Jwt.SecretKey))
if err != nil {
return "", err
}
return token, nil
}
func ParseToken(token string, secret string) (string, error) {
claim, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil {
return "", err
}
return claim.Claims.(jwt.MapClaims)["username"].(string), nil
}
|
non-member
|
package main
import (
"github.com/kataras/iris"
"github.com/kataras/iris/context"
)
func main() {
app := iris.New()
none := app.None("/invisible/{username}", func(ctx context.Context) {
ctx.Writef("Hello %s with method: %s", ctx.Values().GetString("username"), ctx.Method())
if from := ctx.Values().GetString("from"); from != "" {
ctx.Writef("\nI see that you're coming from %s", from)
}
})
app.Get("/change", func(ctx context.Context) {
if none.IsOnline() {
none.Method = iris.MethodNone
} else {
none.Method = iris.MethodGet
}
// refresh re-builds the router at serve-time in order to be notified for its new routes.
app.RefreshRouter()
})
app.Get("/execute", func(ctx context.Context) {
// same as navigating to "http://localhost:8080/invisible/iris" when /change has being invoked and route state changed
// from "offline" to "online"
ctx.Values().Set("from", "/execute") // values and session can be shared when calling Exec from a "foreign" context.
ctx.Exec("GET", "/invisible/iris")
})
app.Run(iris.Addr(":8080"))
}
|
non-member
|
package workflow_error
import (
"time"
"go.temporal.io/sdk/temporal"
"go.temporal.io/sdk/workflow"
)
type BusinessError struct{}
func (be BusinessError) Error() string {
return "business error"
}
func ExperimentalWorkflow(ctx workflow.Context) error {
ctx = defineActivityOptions(ctx, "some")
err := workflow.ExecuteActivity(ctx, "Activity1").Get(ctx, nil)
if err != nil {
return err
}
err = workflow.ExecuteActivity(ctx, "Activity2").Get(ctx, nil)
if err != nil {
return err
}
return nil
}
func defineActivityOptions(ctx workflow.Context, queue string) workflow.Context {
ao := workflow.ActivityOptions{
TaskQueue: queue,
ScheduleToStartTimeout: time.Second,
StartToCloseTimeout: 24 * time.Hour,
HeartbeatTimeout: time.Second * 2,
RetryPolicy: &temporal.RetryPolicy{
InitialInterval: time.Second,
BackoffCoefficient: 2.0,
MaximumInterval: time.Minute * 5,
NonRetryableErrorTypes: []string{"BusinessError"},
},
}
ctxOut := workflow.WithActivityOptions(ctx, ao)
return ctxOut
}
|
non-member
|
package psql_test
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dobermanndotdev/dobermann/internal/app/query"
"github.com/dobermanndotdev/dobermann/internal/domain"
"github.com/dobermanndotdev/dobermann/internal/domain/monitor"
"github.com/dobermanndotdev/dobermann/tests"
)
func TestIncidentRepository_Lifecycle(t *testing.T) {
account00 := tests.FixtureAndInsertAccount(t, db, true)
monitor00 := tests.FixtureMonitor(t, account00)
incident00 := tests.FixtureIncident(t, monitor00.ID().String())
require.NoError(t, monitorRepository.Insert(ctx, monitor00))
assert.NoError(t, incidentRepository.Create(ctx, incident00))
t.Run("find_incident_by_id", func(t *testing.T) {
t.Parallel()
found00, err := incidentRepository.FindByID(ctx, incident00.ID())
require.NoError(t, err)
assertIncident(t, incident00, found00)
})
t.Run("incident_not_found", func(t *testing.T) {
t.Parallel()
_, err := incidentRepository.FindByID(ctx, domain.NewID())
assert.ErrorIs(t, err, monitor.ErrIncidentNotFound)
})
t.Run("all_incidents", func(t *testing.T) {
t.Parallel()
result, err := incidentRepository.FindAll(ctx, account00.ID(), query.PaginationParams{
Page: 1,
Limit: 100,
})
require.NoError(t, err)
for _, foundIncident := range result.Data {
require.Equal(t, monitor00.ID(), foundIncident.MonitorID())
}
})
}
func assertIncident(t *testing.T, expected, found *monitor.Incident) {
t.Helper()
assert.Equal(t, expected.ID(), found.ID())
assert.Equal(t, expected.CheckedURL(), found.CheckedURL())
assert.Equal(t, expected.Cause(), found.Cause())
//POST_IDEA?: comparing dates in tests
assert.Equal(t, expected.CreatedAt().Truncate(time.Second), found.CreatedAt().Truncate(time.Second))
}
|
non-member
|
package finder
import (
"testing"
)
func TestFunction_elemInSlice(t *testing.T) {
var elem string = "elem"
var slice = []string{"elem", "foo", "bar"}
if !elemInSlice(slice, elem) {
t.Errorf("Failure: Expected to find element 'elem' in slice!")
}
elem = "elem"
slice = []string{"foo", "bar"}
if elemInSlice(slice, elem) {
t.Errorf("Failure: Expected to not find element 'elem' in slice!")
}
}
func TestFunction_ToString(t *testing.T) {
var function = Function{
name: "testFunction",
line: 1337,
file: "just/some/random/test/file.ext",
}
var shouldBe = "Function | Name: testFunction, Line: 1337, File: just/some/random/test/file.ext"
if function.ToString() != shouldBe {
t.Errorf("Failure: Expected \"%s\", got: : \"%s\"", shouldBe, function.ToString())
}
}
func TestCleanLine(t *testing.T) {
var idx = 1
auxTest := func(line, exp string) {
ret := CleanLine(line)
if ret != exp {
t.Errorf("%v: Expected line '%s' to have answer: '%v', got: '%v'", idx, line, exp, ret)
}
idx++
}
auxTest("// This is a inline comment", "")
auxTest(" // Same inline comment", "")
auxTest(" \t // Same inline comment with tab", "")
auxTest("int a = 12; // Random comment", "int a = 12;")
auxTest("bool func(type param) // Comment", "bool func(type param)")
auxTest("bool func(type param) /* Comment */", "bool func(type param)")
auxTest(" bool func(type param) /* Comment */", "bool func(type param)")
auxTest(" \tbool func(type param) /* Comment */", "bool func(type param)")
auxTest("// func(type param)", "")
auxTest(" * This is a multiline comment", "")
auxTest(" /* This is the startline of a multiline comment", "")
auxTest(" * This is a multiline comment with additional steps", "")
auxTest(" \t * This is a multiline comment with tab", "")
auxTest(" int a = 12; /* Comment */ int b = 24;", "int a = 12; int b = 24;")
}
func TestHasFuncDec(t *testing.T) {
var idx = 1
auxTest := func(line string, exp bool) {
ret := HasFuncDec(line)
if ret != exp {
t.Errorf("%v: Expected line '%s' to have answer: %v, got: %v", idx, line, exp, ret)
}
idx++
}
auxTest("", false)
auxTest("bool (func(type param)", false)
auxTest("bool func(type param", false)
auxTest("bool func(type param,", true)
auxTest("bool func(type param)", true)
auxTest("bool func(type param){", true)
auxTest("bool func(type param", false)
auxTest("bool func(void){", true)
auxTest("bool func(void)", true)
auxTest("bool func(uint8 param_1, void)", true) // not really okay, but to tidious if i wanted to fix that
auxTest("bool func(void, ", false)
auxTest("bool func(void, \t", false)
auxTest("bool func(uint8 param_1, void)", true) // not really okay, but to tidious if i wanted to fix that
auxTest("bool func(uint8 param_1)", true)
auxTest("bool func()", true)
auxTest("bool func( )", true)
auxTest("bool func(void)", true)
auxTest("bool func(void,", true) // not really okay, but to tidious if i wanted to fix that
auxTest("bool func(uint8 param_1,", true)
auxTest("// bool func(void,", false)
auxTest("// bool func(type param,", false)
auxTest(" * bool func(type param,", false)
auxTest("bool func(type param,", true)
auxTest("extern bool func(type param,", true)
auxTest("static bool func(type param,", true)
auxTest("extern static bool func(type param,", false)
auxTest("external bool func(type param,", false)
auxTest("static \t bool func(type param,", true)
auxTest("extern \t bool func(type param,", true)
auxTest("extern \t\t bool funcincation(type param,", true)
auxTest("extern bool funcincation{type param,", false)
auxTest("bool funcincation{type param,", false)
auxTest("bool bool funcincation(type param,", false)
auxTest("bool funcincation(type param, type param,type param){", true)
auxTest("\tbool funcincation(type param,", true)
auxTest(" bool funcincation(type param,", true)
auxTest("\t bool funcincation(type param,", true)
auxTest("\t \tbool funcincation(type param,", true)
}
func TestHasOptimize(t *testing.T) {
var idx = 1
testFunc := func(line string, exp bool) {
ret := HasOptimize(line, PossibleOptimizations)
if ret != exp {
t.Errorf("%v: Expected line '%s' to have answer: %v, got: %v", idx, line, exp, ret)
}
idx++
}
testFunc("", false)
testFunc("// commment __attribute__((optimize(\"-Os\")))", false)
testFunc("__attribute__((optimize(\"-Os\")))", true)
testFunc("__attribute__((optimize(\"-Ost\")))", false)
testFunc("__attribute__((optimize(\"-O5\")))", false)
testFunc("__attribute__((optimize(\"-0s\")))", false)
testFunc("__attribute__((optimize(\"-\")))", false)
testFunc("__attribute__((optimize(\"-O\")))", true)
testFunc(" * __attribute__((optimize(\"-Os\")))", false)
testFunc("#__attribute__((optimize(\"-Os\")))", false)
testFunc(" \t \t__attribute__((optimize(\"-Os\")))", true)
testFunc("_attribute__((optimize(\"-Os\")))", false)
testFunc("__attribute_((optimize(\"-Os\")))", false)
testFunc("__attribute__(optimize(\"-Os\"))", false)
testFunc("__attribute__((optimize(\"-Os\"))))", false)
testFunc("__attribute__((optimize\"-Os\")))", false)
testFunc("__attribute__ ((optimize-Os\")))", false)
testFunc("__attribute__ ((optimize-Os)))", false)
testFunc("__attribute__((optimize-Oss)))\t", false)
testFunc("__attribute__ ((optimize-Oss)))", false)
}
func TestExtractFuncName(t *testing.T) {
testFunc := func(line string, exp string) {
ret := ExtractFuncName(line)
if ret != exp {
t.Errorf("Expected line '%s' to have answer: %v, got: %v", line, exp, ret)
}
}
testFunc("bool func(type param", "func")
testFunc("bool func(type param,", "func")
testFunc("bool func(type param)", "func")
testFunc("bool func(type param){", "func")
testFunc("bool func(type param", "func")
testFunc("bool func(void){", "func")
testFunc("bool func(void)", "func")
testFunc("bool func(type param,", "func")
testFunc("extern bool func(type param,", "func")
testFunc("static bool func(type param,", "func")
testFunc("extern \t bool func(type param,", "func")
testFunc("extern \t\t bool funcincation(type param,", "funcincation")
testFunc("bool funcincation(type param, type param,type param){", "funcincation")
testFunc("\tbool funcincation(type param,", "funcincation")
testFunc(" bool funcincation(type param,", "funcincation")
testFunc("\t bool funcincation(type param,", "funcincation")
testFunc("\t \tbool funcincation(type param,", "funcincation")
}
|
non-member
|
package transfer_test
import (
"testing"
)
func TestAccTransfer_serial(t *testing.T) {
testCases := map[string]map[string]func(t *testing.T){
"Access": {
"disappears": testAccAccess_disappears,
"EFSBasic": testAccAccess_efs_basic,
"S3Basic": testAccAccess_s3_basic,
"S3Policy": testAccAccess_s3_policy,
},
"Server": {
"basic": testAccServer_basic,
"disappears": testAccServer_disappears,
"APIGateway": testAccServer_apiGateway,
"APIGatewayForceDestroy": testAccServer_apiGateway_forceDestroy,
"DirectoryService": testAccServer_directoryService,
"Domain": testAccServer_domain,
"ForceDestroy": testAccServer_forceDestroy,
"HostKey": testAccServer_hostKey,
"Protocols": testAccServer_protocols,
"SecurityPolicy": testAccServer_securityPolicy,
"UpdateEndpointTypePublicToVPC": testAccServer_updateEndpointType_publicToVPC,
"UpdateEndpointTypePublicToVPCAddressAllocationIDs": testAccServer_updateEndpointType_publicToVPC_addressAllocationIDs,
"UpdateEndpointTypeVPCEndpointToVPC": testAccServer_updateEndpointType_vpcEndpointToVPC,
"UpdateEndpointTypeVPCEndpointToVPCAddressAllocationIDs": testAccServer_updateEndpointType_vpcEndpointToVPC_addressAllocationIDs,
"UpdateEndpointTypeVPCEndpointToVPCSecurityGroupIDs": testAccServer_updateEndpointType_vpcEndpointToVPC_securityGroupIDs,
"UpdateEndpointTypeVPCToPublic": testAccServer_updateEndpointType_vpcToPublic,
"VPC": testAccServer_vpc,
"VPCAddressAllocationIDs": testAccServer_vpcAddressAllocationIDs,
"VPCAddressAllocationIDsSecurityGroupIDs": testAccServer_vpcAddressAllocationIds_securityGroupIDs,
"VPCEndpointID": testAccServer_vpcEndpointID,
"VPCSecurityGroupIDs": testAccServer_vpcSecurityGroupIDs,
},
"SSHKey": {
"basic": testAccSSHKey_basic,
},
"User": {
"basic": testAccUser_basic,
"disappears": testAccUser_disappears,
"HomeDirectoryMappings": testAccUser_homeDirectoryMappings,
"ModifyWithOptions": testAccUser_modifyWithOptions,
"Posix": testAccUser_posix,
"UserNameValidation": testAccUser_UserName_Validation,
},
}
for group, m := range testCases {
m := m
t.Run(group, func(t *testing.T) {
for name, tc := range m {
tc := tc
t.Run(name, func(t *testing.T) {
tc(t)
})
}
})
}
}
|
non-member
|
package utils
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"minirpc/Model"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unsafe"
)
type StackInfo struct {
Name string `json:"name"`
Code string `json:"code"`
Ocode string `json:"ocode"`
Gcode string `json:"gcode"`
Val string `json:"val"`
Per string `json:"per"`
//位置
Ptype string `json:"ptype"`
Daystr string `json:"daystr"`
}
type StockHistory struct {
Code string `json:"code"`
Todaye string `json:"todaye"`
Ydaye string `json:"ydaye"`
List []StockHistoryItem `json:"list"`
}
type StockHistoryItem struct {
Date string `json:"date"`
Sprice float64 `json:"sprice"`
Eprice float64 `json:"eprice"`
Cval float64 `json:"cval"`
Cper float64 `json:"cper"`
Cnum float64 `json:"cnum"`
Ctval float64 `json:"ctval"`
Chand float64 `json:"chand"`
}
var Ofile string
var Gdreg *regexp.Regexp
var Gdreg2 *regexp.Regexp
var otherinfoarr []string
func StockAnaly(code string) string {
var retstr string
dayNum := 7
end :=time.Now().Format("20060102")
start :=time.Now().AddDate(0,0,-dayNum).Format("20060102")
dayarr := make(map[int]string,dayNum)
for {
week := time.Now().AddDate(0,0,-dayNum).Weekday()
if week ==0 || week==6 {
dayarr[dayNum] =""
}else{
dayarr[dayNum] = time.Now().AddDate(0,0,-dayNum).Format("2006-01-02")
}
dayNum--
if dayNum<0 {
break
}
}
list := gethistory(code,start,end)
retstr +="昨到今:" +list.Ydaye +"~"+list.Todaye
if checkRaise(list,dayarr) {
retstr += " 连涨3天!!"
}
if checkDec(list,dayarr) {
retstr += " 连跌3天!!"
}
return retstr
}
func checkRaise(list StockHistory,dayarr map[int]string) bool {
flag := true
raseCunt :=0
startval := 0.0
for n:=0 ; n<len(dayarr); n++ {
if dayarr[n]!="" {
for _,v :=range list.List{
if v.Date == dayarr[n]{
if startval ==0 {
startval = v.Eprice
}else if startval>v.Eprice{
startval = v.Eprice
raseCunt++
}else{
//未涨
flag = false
}
break
}
}
}
if !flag{
break
}
}
if raseCunt>=3{
//连涨3天
fmt.Println("连涨"+strconv.Itoa(raseCunt)+"天")
return true
}
return false
}
func checkDec(list StockHistory,dayarr map[int]string) bool {
flag := true
raseCunt :=0
startval := 0.0
for n:=0 ; n<len(dayarr); n++ {
if dayarr[n]!="" {
for _,v :=range list.List{
if v.Date == dayarr[n]{
if startval ==0 {
startval = v.Eprice
}else if startval<v.Eprice{
startval = v.Eprice
raseCunt++
}else{
//fmt.Println(startval,v.Eprice)
flag = false
}
break
}
}
}
if !flag{
break
}
}
if raseCunt>=3{
//连跌3天
fmt.Println("连跌"+strconv.Itoa(raseCunt)+"天")
return true
}
return false
}
func gethistory(code string,start string,end string ) StockHistory {
var list StockHistory
list.List = make([]StockHistoryItem,0)
//https://q.stock.sohu.com/hisHq?code=cn_002960&start=20210301&end=20210309&stat=1&order=D&period=d&callback=historySearchHandler&rt=json
data := make(map[string]string)
data["code"] ="cn_"+code
data["start"] =start
data["end"] =end
data["stat"] ="1"
data["order"] = "D"
data["period"] = "d"
data["callback"] = "historySearchHandler"
data["rt"] = "json"
header := make(map[string]string)
header["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36"
res,err:=curltest("https://q.stock.sohu.com/hisHq",data,header,"GET")
//["2018-05-10","3.02","3.05","0.04","1.33%","3.02","3.06","118307","3601.96","0.52%"]
//[日期,开盘价,收盘价,涨跌额,涨跌幅,最低,最高,成交量,成交额,换手率]
nowdaystr := time.Now().Format("2006-01-02")
nowweek := time.Now().Weekday()
lastdaystr :=""
if nowweek==1 {
lastdaystr = time.Now().AddDate(0,0,-3).Format("2006-01-02")
}else{
lastdaystr = time.Now().AddDate(0,0,-1).Format("2006-01-02")
}
if err !=nil {
fmt.Println(err)
return list
}else{
var m []interface{}
err = json.Unmarshal([]byte(res), &m)
if err != nil {
fmt.Println(data["code"]," gethistory json fail")
fmt.Println(res)
fmt.Println(err)
return list
}
tcode := m[0].(map[string]interface{})["code"].(string)
if tcode!="cn_"+code{
return list
}
dlst := m[0].(map[string]interface{})["hq"].([]interface{})
for _,item := range dlst{
var titem StockHistoryItem
titem.Date = item.([]interface{})[0].(string)
v, err := strtof64(item.([]interface{})[1].(string))
if err != nil{
fmt.Println(err)
return list
}
titem.Sprice = v
v, err = strtof64(item.([]interface{})[2].(string))
if err != nil{
fmt.Println(err)
}
titem.Eprice = v
if nowdaystr == titem.Date{
list.Todaye = item.([]interface{})[2].(string)
}
if lastdaystr ==titem.Date{
list.Ydaye = item.([]interface{})[2].(string)
}
v, err = strtof64(item.([]interface{})[3].(string))
if err != nil{
fmt.Println(err)
}
titem.Cval = v
v, err = strtof64(strings.Trim(item.([]interface{})[4].(string),"%"))
if err != nil{
fmt.Println(err)
}
titem.Cper = v
v, err = strtof64(item.([]interface{})[7].(string))
if err != nil{
fmt.Println(err)
}
titem.Cnum = v
v, err = strtof64(item.([]interface{})[8].(string))
if err != nil{
fmt.Println(err)
}
titem.Ctval = v
v, err = strtof64(strings.Trim(item.([]interface{})[9].(string),"%"))
if err != nil{
fmt.Println(err)
}
titem.Chand = v
list.List = append(list.List,titem)
}
}
list.Code = code
return list
}
func GetStockBaseInfo(gcode string,name string) StackInfo{
//查询数据库
info,err := Model.GetOneStockInfo(gcode)
if err!=nil{
fmt.Println(err)
}
if info.Name !="" {
return StackInfo{
Name:info.Name,
Code:info.Code,
Gcode:info.Gcode,
Ptype :info.Type,
}
}else {
//爬取
info2 :=CrawStockBaseInfo(name)
if info2.Name !=""{
//入库
Model.AddOneStockInfo(info2.Name,info2.Code,info2.Ptype,gcode,name)
return StackInfo{
Name:info2.Name,
Code:info2.Code,
Gcode:info2.Gcode,
Ptype :info2.Ptype,
}
}else{
return StackInfo{
Name:"",
}
}
}
}
func CrawStockBaseInfo(name string) StackInfo{
var stockInfo StackInfo
//https://quotes.money.163.com/stocksearch/json.do?type=HS&count=5&word=%E4%B8%AD%E9%87%91%E5%85%AC%E5%8F%B8&t=0.40060858273627353
data := make(map[string]string)
data["word"] =name
data["type"] ="HS"
data["count"] = "1"
header := make(map[string]string)
header["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36"
res,err:=curltest("https://quotes.money.163.com/stocksearch/json.do",data,header,"GET")
//_ntes_stocksearch_callback([{"code":"0601995","type":"SH","symbol":"601995","tag":"HS MYHS","spell":"zjgs","name":"\u4e2d\u91d1\u516c\u53f8"}])
if err!= nil {
fmt.Println(err)
return stockInfo
}
if len(res)<27 {
fmt.Println("get stockInfo fail")
return stockInfo
}
res = res[27:len(res)-1]
var m []interface{}
err = json.Unmarshal([]byte(res), &m)
if err != nil {
fmt.Println(name)
fmt.Println(res)
fmt.Println(err)
return stockInfo
}
/*
if name != m[0].(map[string]interface{})["name"].(string){
fmt.Println(name)
fmt.Println(m[0].(map[string]interface{})["name"].(string))
fmt.Println("get stockInfo no match")
return stockInfo
}
*/
stockInfo.Name =m[0].(map[string]interface{})["name"].(string)
stockInfo.Code = m[0].(map[string]interface{})["symbol"].(string)
stockInfo.Ptype = m[0].(map[string]interface{})["type"].(string)
return stockInfo
}
func strtof64(str string) (float64,error) {
v, err := strconv.ParseFloat(str, 64)
if err != nil{
return 0,err
}
return v,nil
}
func curltest(ourl string,data map[string]string, header map[string]string,dtype string) (string,error) {
reader := strings.NewReader("")
var mentype string
if dtype =="JSON" {
mentype = "POST"
}else{
mentype = dtype
}
if data!=nil {
if mentype == "POST"{
str, err := json.Marshal(data)
if err != nil {
fmt.Println("json.Marshal failed:", err)
return "",err
}
reader = strings.NewReader(string(str))
} else if mentype== "GET"{
params := url.Values{}
parseURL, err := url.Parse(ourl)
if err != nil {
log.Println("err")
}
for key,val := range data {
params.Set(key, val)
}
//如果参数中有中文参数,这个方法会进行URLEncode
parseURL.RawQuery = params.Encode()
ourl = parseURL.String()
}
}
//fmt.Println(ourl)
// request, err := http.Get(ourl)
//fmt.Println(reader)
request, err := http.NewRequest(mentype, ourl, reader)
if err != nil {
return "",err
}
if dtype =="JSON" {
request.Header.Set("Content-Type", "application/json;charset=utf-8")
}
for key,item := range header{
request.Header.Set(key,item)
}
client := http.Client{}
resp, err := client.Do(request)
if err != nil {
return "",err
}
//utf8Reader := transform.NewReader(resp.Body,simplifiedchinese.GBK.NewDecoder())
respBytes, err := ioutil.ReadAll(resp.Body)
//respBytes, err := ioutil.ReadAll(utf8Reader)
if err != nil {
return "",err
}
//byte数组直接转成string,优化内存
//utf8 := mahonia.NewDecoder("utf8").ConvertString(string(respBytes))
//ioutil.WriteFile("./output2.txt", respBytes, 0666) //写入文件(字节数组)
res := (*string)(unsafe.Pointer(&respBytes))
return *res,nil
}
|
non-member
|
package files
import (
"fmt"
"github.com/alexcoder04/iserv2go/iserv/types"
"github.com/studio-b12/gowebdav"
)
type FilesClient struct {
config *types.ClientConfig
davClient *gowebdav.Client
}
func (c *FilesClient) Login(config *types.ClientConfig) error {
c.config = config
c.davClient = gowebdav.NewClient(fmt.Sprintf("https://webdav.%s", c.config.IServHost), c.config.Username, c.config.Password)
return c.davClient.Connect()
}
func (c *FilesClient) Logout() error {
return nil
}
|
non-member
|
package currency
import (
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)
func (a Big) MarshalBSONValue() (bsontype.Type, []byte, error) {
return bsontype.String, bsoncore.AppendString(nil, a.String()), nil
}
func (a *Big) UnmarshalBSONValue(t bsontype.Type, b []byte) error {
if t != bsontype.String {
return errors.Errorf("invalid marshaled type for Big, %v", t)
}
s, _, ok := bsoncore.ReadString(b)
if !ok {
return errors.Errorf("can not read string")
}
ua, err := NewBigFromString(s)
if err != nil {
return err
}
*a = ua
return nil
}
|
non-member
|
package main
import (
glog "github.com/Sirupsen/logrus"
"k8s.io/apimachinery/pkg/api/resource"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/pkg/api/v1"
)
// Load nodes
func LoadNodes() []v1.Node {
nodes, err := GetKubeCli().CoreV1().Nodes().List(meta_v1.ListOptions{})
if err != nil {
panic(err.Error())
}
glog.Infof("There are %d nodes in the cluster\n", len(nodes.Items))
for _, node := range nodes.Items {
glog.Infof("node info: %v\n", node)
}
return nodes.Items
}
// node strategies
type NodeStrategy struct {
Nodes []v1.Node
Strategies []*Strategy
}
func NewNodeStrategy(nodes ...v1.Node) *NodeStrategy {
ns := &NodeStrategy{
Nodes: make([]v1.Node, 0),
Strategies: make([]*Strategy, 0),
}
nodeLen := len(nodes)
if nodeLen == 0 {
return ns
} else if nodeLen > 1 {
ns.Nodes = append(ns.Nodes, nodes...)
ns.Strategies = append(ns.Strategies, ClusterStrategies...)
} else {
ns.Nodes = append(ns.Nodes, nodes[0])
if ss, ok := NodesStrategies["general"]; ok {
ns.Strategies = append(ns.Strategies, ss...)
}
if ss, ok := NodesStrategies[ns.Nodes[0].Name]; ok {
ns.Strategies = append(ns.Strategies, ss...)
}
}
return ns
}
func (ns *NodeStrategy) Check() {
if len(ns.Nodes) == 0 || len(ns.Strategies) == 0 {
return
}
STRATEGIES:
for _, s := range ns.Strategies {
switch s.StrategyType {
case ResourceStrategy:
for resourceName, resourceThreshold := range s.ResourceRules {
threshold, err := resource.ParseQuantity(resourceThreshold)
if err != nil {
glog.Errorf("invalid resource threshold format: %v\n", err)
continue STRATEGIES
}
leftResource := ns.LeftResource(resourceName)
if leftResource.Cmp(threshold) > 1 {
glog.Infof("left %s is greater than threshold, %s >= %s\n", resourceName, leftResource, threshold)
continue STRATEGIES
}
}
// current strategy has been captured.
for _, op := range s.Operations {
if err := op.Execute(); err != nil {
glog.Warningf("exec operation return err: %v\n", err)
}
}
if !s.Fallthrough {
break STRATEGIES
}
case NodePhaseStrategy:
case NodeConditionStrategy:
}
}
}
// LeftResource
func (ns *NodeStrategy) LeftResource(resourceName v1.ResourceName) *resource.Quantity {
leftResource := resource.NewQuantity(0, resource.DecimalSI)
for _, node := range ns.Nodes {
leftResource.Add(node.Status.Allocatable[resourceName])
}
glog.Debugf("%s leftResource: %v", resourceName, leftResource)
return leftResource
}
|
member
|
package types
import (
log "github.com/33cn/chain33/common/log/log15"
"github.com/33cn/chain33/types"
)
/*
* 交易相关类型定义
* 交易action通常有对应的log结构,用于交易回执日志记录
* 每一种action和log需要用id数值和name名称加以区分
*/
// action类型id和name,这些常量可以自定义修改
const (
TyUnknowAction = iota + 100
TyAddAction
TySubAction
TyMulAction
TyDivAction
NameAddAction = "Add"
NameSubAction = "Sub"
NameMulAction = "Mul"
NameDivAction = "Div"
)
// log类型id值
const (
TyUnknownLog = iota + 100
TyAddLog
TySubLog
TyMulLog
TyDivLog
)
var (
//HelloX 执行器名称定义
HelloX = "hello"
//定义actionMap
actionMap = map[string]int32{
NameAddAction: TyAddAction,
NameSubAction: TySubAction,
NameMulAction: TyMulAction,
NameDivAction: TyDivAction,
}
//定义log的id和具体log类型及名称,填入具体自定义log类型
logMap = map[int64]*types.LogInfo{
//LogID: {Ty: reflect.TypeOf(LogStruct), Name: LogName},
}
tlog = log.New("module", "hello.types")
)
// init defines a register function
func init() {
types.AllowUserExec = append(types.AllowUserExec, []byte(HelloX))
//注册合约启用高度
types.RegFork(HelloX, InitFork)
types.RegExec(HelloX, InitExecutor)
}
// InitFork defines register fork
func InitFork(cfg *types.Chain33Config) {
cfg.RegisterDappFork(HelloX, "Enable", 0)
}
// InitExecutor defines register executor
func InitExecutor(cfg *types.Chain33Config) {
types.RegistorExecutor(HelloX, NewType(cfg))
}
type helloType struct {
types.ExecTypeBase
}
func NewType(cfg *types.Chain33Config) *helloType {
c := &helloType{}
c.SetChild(c)
c.SetConfig(cfg)
return c
}
// GetPayload 获取合约action结构
func (h *helloType) GetPayload() types.Message {
return &HelloAction{}
}
// GeTypeMap 获取合约action的id和name信息
func (h *helloType) GetTypeMap() map[string]int32 {
return actionMap
}
// GetLogMap 获取合约log相关信息
func (h *helloType) GetLogMap() map[int64]*types.LogInfo {
return logMap
}
|
member
|
package runner
import (
"errors"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
"testing"
"time"
)
func TestIsDirRootPath(t *testing.T) {
result := isDir(".")
if result != true {
t.Errorf("expected '%t' but got '%t'", true, result)
}
}
func TestIsDirMainFile(t *testing.T) {
result := isDir("main.go")
if result != false {
t.Errorf("expected '%t' but got '%t'", true, result)
}
}
func TestIsDirFileNot(t *testing.T) {
result := isDir("main.go")
if result != false {
t.Errorf("expected '%t' but got '%t'", true, result)
}
}
func TestExpandPathWithDot(t *testing.T) {
path, _ := expandPath(".")
wd, _ := os.Getwd()
if path != wd {
t.Errorf("expected '%s' but got '%s'", wd, path)
}
}
func TestExpandPathWithHomePath(t *testing.T) {
path := "~/.conf"
result, _ := expandPath(path)
home := os.Getenv("HOME")
want := home + path[1:]
if result != want {
t.Errorf("expected '%s' but got '%s'", want, result)
}
}
func TestFileChecksum(t *testing.T) {
tests := []struct {
name string
fileContents []byte
expectedChecksum string
expectedChecksumError string
}{
{
name: "empty",
fileContents: []byte(``),
expectedChecksum: "",
expectedChecksumError: "empty file, forcing rebuild without updating checksum",
},
{
name: "simple",
fileContents: []byte(`foo`),
expectedChecksum: "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae",
expectedChecksumError: "",
},
{
name: "binary",
fileContents: []byte{0xF}, // invalid UTF-8 codepoint
expectedChecksum: "dc0e9c3658a1a3ed1ec94274d8b19925c93e1abb7ddba294923ad9bde30f8cb8",
expectedChecksumError: "",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
f, err := os.CreateTemp("", "")
if err != nil {
t.Fatalf("couldn't create temp file for test: %v", err)
}
defer func() {
if err := f.Close(); err != nil {
t.Errorf("error closing temp file: %v", err)
}
if err := os.Remove(f.Name()); err != nil {
t.Errorf("error removing temp file: %v", err)
}
}()
_, err = f.Write(test.fileContents)
if err != nil {
t.Fatalf("couldn't write to temp file for test: %v", err)
}
checksum, err := fileChecksum(f.Name())
if err != nil && err.Error() != test.expectedChecksumError {
t.Errorf("expected '%s' but got '%s'", test.expectedChecksumError, err.Error())
}
if checksum != test.expectedChecksum {
t.Errorf("expected '%s' but got '%s'", test.expectedChecksum, checksum)
}
})
}
}
func TestChecksumMap(t *testing.T) {
m := &checksumMap{m: make(map[string]string, 3)}
if !m.updateFileChecksum("foo.txt", "abcxyz") {
t.Errorf("expected no entry for foo.txt, but had one")
}
if m.updateFileChecksum("foo.txt", "abcxyz") {
t.Errorf("expected matching entry for foo.txt")
}
if !m.updateFileChecksum("foo.txt", "123456") {
t.Errorf("expected matching entry for foo.txt")
}
if !m.updateFileChecksum("bar.txt", "123456") {
t.Errorf("expected no entry for bar.txt, but had one")
}
}
func TestAdaptToVariousPlatforms(t *testing.T) {
config := &config{
Build: cfgBuild{
Bin: "tmp\\main.exe -dev",
},
}
adaptToVariousPlatforms(config)
if config.Build.Bin != "tmp\\main.exe -dev" {
t.Errorf("expected '%s' but got '%s'", "tmp\\main.exe -dev", config.Build.Bin)
}
}
func Test_killCmd_no_process(t *testing.T) {
e := Engine{
config: &config{
Build: cfgBuild{
SendInterrupt: false,
},
},
}
_, err := e.killCmd(&exec.Cmd{
Process: &os.Process{
Pid: 9999,
},
})
if err == nil {
t.Errorf("expected error but got none")
}
if !errors.Is(err, syscall.ESRCH) {
t.Errorf("expected '%s' but got '%s'", syscall.ESRCH, errors.Unwrap(err))
}
}
func Test_killCmd_SendInterrupt_false(t *testing.T) {
_, b, _, _ := runtime.Caller(0)
// Root folder of this project
dir := filepath.Dir(b)
err := os.Chdir(dir)
if err != nil {
t.Fatalf("couldn't change directory: %v", err)
}
// clean file before test
os.Remove("pid")
defer os.Remove("pid")
e := Engine{
config: &config{
Build: cfgBuild{
SendInterrupt: false,
},
},
}
startChan := make(chan struct {
pid int
cmd *exec.Cmd
})
go func() {
cmd, _, _, _, err := e.startCmd("sh _testdata/run-many-processes.sh")
if err != nil {
t.Errorf("failed to start command: %v", err)
return
}
pid := cmd.Process.Pid
t.Logf("process pid is %v", pid)
startChan <- struct {
pid int
cmd *exec.Cmd
}{pid: pid, cmd: cmd}
_ = cmd.Wait()
}()
resp := <-startChan
t.Logf("process started. checking pid %v", resp.pid)
time.Sleep(5 * time.Second)
pid, err := e.killCmd(resp.cmd)
if err != nil {
t.Fatalf("failed to kill command: %v", err)
}
t.Logf("%v was been killed", pid)
// check processes were being killed
// read pids from file
bytesRead, _ := ioutil.ReadFile("pid")
lines := strings.Split(string(bytesRead), "\n")
for _, line := range lines {
_, err := strconv.Atoi(line)
if err != nil {
t.Logf("failed to covert str to int %v", err)
continue
}
_, err = exec.Command("ps", "-p", line, "-o", "comm= ").Output()
if err == nil {
t.Fatalf("process should be killed %v", line)
}
}
}
|
non-member
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 41